block_processor.go 9.6 KB

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