block_processor.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "time"
  8. "github.com/ethereum/go-ethereum/core/types"
  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/pow"
  13. "github.com/ethereum/go-ethereum/pow/ezp"
  14. "github.com/ethereum/go-ethereum/state"
  15. "gopkg.in/fatih/set.v0"
  16. )
  17. type PendingBlockEvent struct {
  18. Block *types.Block
  19. }
  20. var statelogger = logger.NewLogger("BLOCK")
  21. type BlockProcessor struct {
  22. db ethutil.Database
  23. // Mutex for locking the block processor. Blocks can only be handled one at a time
  24. mutex sync.Mutex
  25. // Canonical block chain
  26. bc *ChainManager
  27. // non-persistent key/value memory storage
  28. mem map[string]*big.Int
  29. // Proof of work used for validating
  30. Pow pow.PoW
  31. txpool *TxPool
  32. // The last attempted block is mainly used for debugging purposes
  33. // This does not have to be a valid block and will be set during
  34. // 'Process' & canonical validation.
  35. lastAttemptedBlock *types.Block
  36. events event.Subscription
  37. eventMux *event.TypeMux
  38. }
  39. func NewBlockProcessor(db ethutil.Database, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  40. sm := &BlockProcessor{
  41. db: db,
  42. mem: make(map[string]*big.Int),
  43. //Pow: &ethash.Ethash{},
  44. Pow: ezp.New(),
  45. bc: chainManager,
  46. eventMux: eventMux,
  47. txpool: txpool,
  48. }
  49. return sm
  50. }
  51. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  52. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  53. coinbase.SetGasPool(block.Header().GasLimit)
  54. // Process the transactions on to parent state
  55. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return receipts, nil
  60. }
  61. func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
  62. // If we are mining this block and validating we want to set the logs back to 0
  63. statedb.EmptyLogs()
  64. txGas := new(big.Int).Set(tx.Gas())
  65. cb := statedb.GetStateObject(coinbase.Address())
  66. st := NewStateTransition(NewEnv(statedb, self.bc, tx, block), tx, cb)
  67. _, err := st.TransitionState()
  68. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err)) {
  69. return nil, nil, err
  70. }
  71. txGas.Sub(txGas, st.gas)
  72. // Update the state with pending changes
  73. statedb.Update(txGas)
  74. cumulative := new(big.Int).Set(usedGas.Add(usedGas, txGas))
  75. receipt := types.NewReceipt(statedb.Root(), cumulative)
  76. receipt.SetLogs(statedb.Logs())
  77. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  78. chainlogger.Debugln(receipt)
  79. // Notify all subscribers
  80. if !transientProcess {
  81. go self.eventMux.Post(TxPostEvent{tx})
  82. go self.eventMux.Post(statedb.Logs())
  83. }
  84. return receipt, txGas, err
  85. }
  86. func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
  87. var (
  88. receipts types.Receipts
  89. handled, unhandled types.Transactions
  90. erroneous types.Transactions
  91. totalUsedGas = big.NewInt(0)
  92. err error
  93. cumulativeSum = new(big.Int)
  94. )
  95. for _, tx := range txs {
  96. receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
  97. if err != nil {
  98. switch {
  99. case IsNonceErr(err):
  100. return nil, nil, nil, nil, err
  101. case state.IsGasLimitErr(err):
  102. return nil, nil, nil, nil, err
  103. default:
  104. statelogger.Infoln(err)
  105. erroneous = append(erroneous, tx)
  106. err = nil
  107. }
  108. }
  109. receipts = append(receipts, receipt)
  110. handled = append(handled, tx)
  111. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  112. }
  113. block.Reward = cumulativeSum
  114. block.Header().GasUsed = totalUsedGas
  115. if transientProcess {
  116. go self.eventMux.Post(PendingBlockEvent{block})
  117. }
  118. return receipts, handled, unhandled, erroneous, err
  119. }
  120. // Process block will attempt to process the given block's transactions and applies them
  121. // on top of the block's parent state (given it exists) and will return wether it was
  122. // successful or not.
  123. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
  124. // Processing a blocks may never happen simultaneously
  125. sm.mutex.Lock()
  126. defer sm.mutex.Unlock()
  127. header := block.Header()
  128. if sm.bc.HasBlock(header.Hash()) {
  129. return nil, &KnownBlockError{header.Number, header.Hash()}
  130. }
  131. if !sm.bc.HasBlock(header.ParentHash) {
  132. return nil, ParentError(header.ParentHash)
  133. }
  134. parent := sm.bc.GetBlock(header.ParentHash)
  135. return sm.processWithParent(block, parent)
  136. }
  137. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big.Int, err error) {
  138. sm.lastAttemptedBlock = block
  139. // Create a new state based on the parent's root (e.g., create copy)
  140. state := state.New(parent.Root(), sm.db)
  141. // Block validation
  142. if err = sm.ValidateBlock(block, parent); err != nil {
  143. return
  144. }
  145. receipts, err := sm.TransitionState(state, parent, block, false)
  146. if err != nil {
  147. return
  148. }
  149. header := block.Header()
  150. // Validate the received block's bloom with the one derived from the generated receipts.
  151. // For valid blocks this should always validate to true.
  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. // The transactions Trie's root (R = (Tr [[H1, T1], [H2, T2], ... [Hn, Tn]]))
  158. // can be used by light clients to make sure they've received the correct Txs
  159. txSha := types.DeriveSha(block.Transactions())
  160. if bytes.Compare(txSha, header.TxHash) != 0 {
  161. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  162. return
  163. }
  164. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  165. receiptSha := types.DeriveSha(receipts)
  166. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  167. fmt.Println("receipts", receipts)
  168. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  169. return
  170. }
  171. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  172. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  173. return
  174. }
  175. // Commit state objects/accounts to a temporary trie (does not save)
  176. // used to calculate the state root.
  177. state.Update(ethutil.Big0)
  178. if !bytes.Equal(header.Root, state.Root()) {
  179. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  180. return
  181. }
  182. // Calculate the td for this block
  183. td = CalculateTD(block, parent)
  184. // Sync the current block's state to the database
  185. state.Sync()
  186. // Remove transactions from the pool
  187. sm.txpool.RemoveSet(block.Transactions())
  188. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  189. return td, nil
  190. }
  191. // Validates the current block. Returns an error if the block was invalid,
  192. // an uncle or anything that isn't on the current block chain.
  193. // Validation validates easy over difficult (dagger takes longer time = difficult)
  194. func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
  195. if len(block.Header().Extra) > 1024 {
  196. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  197. }
  198. expd := CalcDifficulty(block, parent)
  199. if expd.Cmp(block.Header().Difficulty) != 0 {
  200. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  201. }
  202. expl := CalcGasLimit(parent, block)
  203. if expl.Cmp(block.Header().GasLimit) != 0 {
  204. return fmt.Errorf("GasLimit check failed for block %v, %v", block.Header().GasLimit, expl)
  205. }
  206. if block.Time() < parent.Time() {
  207. return ValidationError("Block timestamp not after prev block (%v - %v)", block.Header().Time, parent.Header().Time)
  208. }
  209. if block.Time() > time.Now().Unix() {
  210. return BlockFutureErr
  211. }
  212. if new(big.Int).Sub(block.Number(), parent.Number()).Cmp(big.NewInt(1)) != 0 {
  213. return BlockNumberErr
  214. }
  215. // Verify the nonce of the block. Return an error if it's not valid
  216. if !sm.Pow.Verify(block) {
  217. return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Header().Nonce))
  218. }
  219. return nil
  220. }
  221. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  222. reward := new(big.Int).Set(BlockReward)
  223. ancestors := set.New()
  224. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  225. ancestors.Add(string(ancestor.Hash()))
  226. }
  227. uncles := set.New()
  228. uncles.Add(string(block.Hash()))
  229. for _, uncle := range block.Uncles() {
  230. if uncles.Has(string(uncle.Hash())) {
  231. // Error not unique
  232. return UncleError("Uncle not unique")
  233. }
  234. uncles.Add(string(uncle.Hash()))
  235. if !ancestors.Has(string(uncle.ParentHash)) {
  236. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  237. }
  238. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  239. return ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
  240. }
  241. r := new(big.Int)
  242. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  243. statedb.AddBalance(uncle.Coinbase, r)
  244. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  245. }
  246. // Get the account associated with the coinbase
  247. statedb.AddBalance(block.Header().Coinbase, reward)
  248. return nil
  249. }
  250. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  251. if !sm.bc.HasBlock(block.Header().ParentHash) {
  252. return nil, ParentError(block.Header().ParentHash)
  253. }
  254. sm.lastAttemptedBlock = block
  255. var (
  256. parent = sm.bc.GetBlock(block.Header().ParentHash)
  257. state = state.New(parent.Root(), sm.db)
  258. )
  259. sm.TransitionState(state, parent, block, true)
  260. sm.AccumulateRewards(state, block, parent)
  261. return state.Logs(), nil
  262. }