block_processor.go 10 KB

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