block_processor.go 11 KB

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