block_processor.go 9.6 KB

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