block_processor.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "github.com/ethereum/go-ethereum/core/types"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. "github.com/ethereum/go-ethereum/ethutil"
  10. "github.com/ethereum/go-ethereum/event"
  11. "github.com/ethereum/go-ethereum/logger"
  12. "github.com/ethereum/go-ethereum/p2p"
  13. "github.com/ethereum/go-ethereum/pow"
  14. "github.com/ethereum/go-ethereum/pow/ezp"
  15. "github.com/ethereum/go-ethereum/state"
  16. "gopkg.in/fatih/set.v0"
  17. )
  18. var statelogger = logger.NewLogger("BLOCK")
  19. type EthManager interface {
  20. BlockProcessor() *BlockProcessor
  21. ChainManager() *ChainManager
  22. TxPool() *TxPool
  23. PeerCount() int
  24. IsMining() bool
  25. IsListening() bool
  26. Peers() []*p2p.Peer
  27. KeyManager() *crypto.KeyManager
  28. ClientIdentity() p2p.ClientIdentity
  29. Db() ethutil.Database
  30. EventMux() *event.TypeMux
  31. }
  32. type BlockProcessor struct {
  33. db ethutil.Database
  34. // Mutex for locking the block processor. Blocks can only be handled one at a time
  35. mutex sync.Mutex
  36. // Canonical block chain
  37. bc *ChainManager
  38. // non-persistent key/value memory storage
  39. mem map[string]*big.Int
  40. // Proof of work used for validating
  41. Pow pow.PoW
  42. txpool *TxPool
  43. // The last attempted block is mainly used for debugging purposes
  44. // This does not have to be a valid block and will be set during
  45. // 'Process' & canonical validation.
  46. lastAttemptedBlock *types.Block
  47. events event.Subscription
  48. eventMux *event.TypeMux
  49. }
  50. func NewBlockProcessor(db ethutil.Database, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  51. sm := &BlockProcessor{
  52. db: db,
  53. mem: make(map[string]*big.Int),
  54. Pow: ezp.New(),
  55. bc: chainManager,
  56. eventMux: eventMux,
  57. txpool: txpool,
  58. }
  59. return sm
  60. }
  61. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block) (receipts types.Receipts, err error) {
  62. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  63. coinbase.SetGasPool(CalcGasLimit(parent, block))
  64. // Process the transactions on to parent state
  65. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), false)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return receipts, nil
  70. }
  71. func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
  72. var (
  73. receipts types.Receipts
  74. handled, unhandled types.Transactions
  75. erroneous types.Transactions
  76. totalUsedGas = big.NewInt(0)
  77. err error
  78. cumulativeSum = new(big.Int)
  79. )
  80. done:
  81. for i, tx := range txs {
  82. // If we are mining this block and validating we want to set the logs back to 0
  83. state.EmptyLogs()
  84. txGas := new(big.Int).Set(tx.Gas())
  85. cb := state.GetStateObject(coinbase.Address())
  86. st := NewStateTransition(NewEnv(state, self.bc, tx, block), tx, cb)
  87. _, err = st.TransitionState()
  88. if err != nil {
  89. switch {
  90. case IsNonceErr(err):
  91. err = nil // ignore error
  92. continue
  93. case IsGasLimitErr(err):
  94. unhandled = txs[i:]
  95. break done
  96. default:
  97. statelogger.Infoln(err)
  98. erroneous = append(erroneous, tx)
  99. err = nil
  100. }
  101. }
  102. txGas.Sub(txGas, st.gas)
  103. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  104. // Update the state with pending changes
  105. state.Update(txGas)
  106. cumulative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, txGas))
  107. receipt := types.NewReceipt(state.Root(), cumulative)
  108. receipt.SetLogs(state.Logs())
  109. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  110. chainlogger.Debugln(receipt)
  111. // Notify all subscribers
  112. if !transientProcess {
  113. go self.eventMux.Post(TxPostEvent{tx})
  114. }
  115. receipts = append(receipts, receipt)
  116. handled = append(handled, tx)
  117. if ethutil.Config.Diff && ethutil.Config.DiffType == "all" {
  118. state.CreateOutputForDiff()
  119. }
  120. }
  121. block.Reward = cumulativeSum
  122. block.Header().GasUsed = totalUsedGas
  123. return receipts, handled, unhandled, erroneous, err
  124. }
  125. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, msgs state.Messages, err error) {
  126. // Processing a blocks may never happen simultaneously
  127. sm.mutex.Lock()
  128. defer sm.mutex.Unlock()
  129. header := block.Header()
  130. if sm.bc.HasBlock(header.Hash()) {
  131. return nil, nil, &KnownBlockError{header.Number, header.Hash()}
  132. }
  133. if !sm.bc.HasBlock(header.ParentHash) {
  134. return nil, nil, ParentError(header.ParentHash)
  135. }
  136. parent := sm.bc.GetBlock(header.ParentHash)
  137. return sm.ProcessWithParent(block, parent)
  138. }
  139. func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
  140. sm.lastAttemptedBlock = block
  141. state := state.New(parent.Root(), sm.db)
  142. //state := state.New(parent.Trie().Copy())
  143. // Block validation
  144. if err = sm.ValidateBlock(block, parent); err != nil {
  145. return
  146. }
  147. receipts, err := sm.TransitionState(state, parent, block)
  148. if err != nil {
  149. return
  150. }
  151. header := block.Header()
  152. rbloom := types.CreateBloom(receipts)
  153. if bytes.Compare(rbloom, header.Bloom) != 0 {
  154. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  155. return
  156. }
  157. txSha := types.DeriveSha(block.Transactions())
  158. if bytes.Compare(txSha, header.TxHash) != 0 {
  159. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  160. return
  161. }
  162. receiptSha := types.DeriveSha(receipts)
  163. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  164. fmt.Println("receipts", receipts)
  165. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  166. return
  167. }
  168. if err = sm.AccumelateRewards(state, block, parent); err != nil {
  169. return
  170. }
  171. state.Update(ethutil.Big0)
  172. if !bytes.Equal(header.Root, state.Root()) {
  173. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  174. return
  175. }
  176. // Calculate the td for this block
  177. td = CalculateTD(block, parent)
  178. // Sync the current block's state to the database and cancelling out the deferred Undo
  179. state.Sync()
  180. // Set the block hashes for the current messages
  181. state.Manifest().SetHash(block.Hash())
  182. messages = state.Manifest().Messages
  183. // Reset the manifest XXX We need this?
  184. state.Manifest().Reset()
  185. // Remove transactions from the pool
  186. sm.txpool.RemoveSet(block.Transactions())
  187. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  188. return td, messages, nil
  189. }
  190. // Validates the current block. Returns an error if the block was invalid,
  191. // an uncle or anything that isn't on the current block chain.
  192. // Validation validates easy over difficult (dagger takes longer time = difficult)
  193. func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
  194. if len(block.Header().Extra) > 1024 {
  195. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  196. }
  197. expd := CalcDifficulty(block, parent)
  198. if expd.Cmp(block.Header().Difficulty) < 0 {
  199. fmt.Println("parent\n", parent)
  200. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  201. }
  202. diff := block.Header().Time - parent.Header().Time
  203. if diff < 0 {
  204. return ValidationError("Block timestamp less then prev block %v (%v - %v)", diff, block.Header().Time, sm.bc.CurrentBlock().Header().Time)
  205. }
  206. /* XXX
  207. // New blocks must be within the 15 minute range of the last block.
  208. if diff > int64(15*time.Minute) {
  209. return ValidationError("Block is too far in the future of last block (> 15 minutes)")
  210. }
  211. */
  212. // Verify the nonce of the block. Return an error if it's not valid
  213. if !sm.Pow.Verify(block /*block.HashNoNonce(), block.Difficulty, block.Nonce*/) {
  214. return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Header().Nonce))
  215. }
  216. return nil
  217. }
  218. func (sm *BlockProcessor) AccumelateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  219. reward := new(big.Int).Set(BlockReward)
  220. ancestors := set.New()
  221. for _, ancestor := range sm.bc.GetAncestors(block, 6) {
  222. ancestors.Add(string(ancestor.Hash()))
  223. }
  224. uncles := set.New()
  225. uncles.Add(string(block.Hash()))
  226. for _, uncle := range block.Uncles() {
  227. if uncles.Has(string(uncle.Hash())) {
  228. // Error not unique
  229. return UncleError("Uncle not unique")
  230. }
  231. uncles.Add(string(uncle.Hash()))
  232. if !ancestors.Has(string(uncle.ParentHash)) {
  233. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  234. }
  235. /*
  236. uncleParent := sm.bc.GetBlock(uncle.ParentHash)
  237. if uncleParent == nil {
  238. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  239. }
  240. if uncleParent.Number().Cmp(new(big.Int).Sub(parent.Number(), big.NewInt(6))) < 0 {
  241. return UncleError("Uncle too old")
  242. }
  243. if knownUncles.Has(string(uncle.Hash())) {
  244. return UncleError("Uncle in chain")
  245. }
  246. */
  247. r := new(big.Int)
  248. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  249. uncleAccount := statedb.GetAccount(uncle.Coinbase)
  250. uncleAccount.AddAmount(r)
  251. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  252. }
  253. // Get the account associated with the coinbase
  254. account := statedb.GetAccount(block.Header().Coinbase)
  255. // Reward amount of ether to the coinbase address
  256. account.AddAmount(reward)
  257. statedb.Manifest().AddMessage(&state.Message{
  258. To: block.Header().Coinbase,
  259. Input: nil,
  260. Origin: nil,
  261. Timestamp: int64(block.Header().Time), Coinbase: block.Header().Coinbase, Number: block.Header().Number,
  262. Value: new(big.Int).Add(reward, block.Reward),
  263. })
  264. return nil
  265. }
  266. func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Message, err error) {
  267. if !sm.bc.HasBlock(block.Header().ParentHash) {
  268. return nil, ParentError(block.Header().ParentHash)
  269. }
  270. sm.lastAttemptedBlock = block
  271. var (
  272. parent = sm.bc.GetBlock(block.Header().ParentHash)
  273. //state = state.New(parent.Trie().Copy())
  274. state = state.New(parent.Root(), sm.db)
  275. )
  276. defer state.Reset()
  277. sm.TransitionState(state, parent, block)
  278. sm.AccumelateRewards(state, block, parent)
  279. return state.Manifest().Messages, nil
  280. }