block_processor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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) || IsInvalidTxErr(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 && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  100. return nil, nil, nil, nil, err
  101. }
  102. if err != nil {
  103. statelogger.Infoln("TX err:", err)
  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.ValidateHeader(block.Header(), parent.Header()); err != nil {
  139. return
  140. }
  141. // There can be at most two uncles
  142. if len(block.Uncles()) > 2 {
  143. return nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
  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. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  168. return
  169. }
  170. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  171. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  172. return
  173. }
  174. // Commit state objects/accounts to a temporary trie (does not save)
  175. // used to calculate the state root.
  176. state.Update(ethutil.Big0)
  177. if !bytes.Equal(header.Root, state.Root()) {
  178. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  179. return
  180. }
  181. // Calculate the td for this block
  182. td = CalculateTD(block, parent)
  183. // Sync the current block's state to the database
  184. state.Sync()
  185. // Remove transactions from the pool
  186. sm.txpool.RemoveSet(block.Transactions())
  187. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  188. return td, nil
  189. }
  190. // Validates the current block. Returns an error if the block was invalid,
  191. // an uncle or anything that isn't on the current block chain.
  192. // Validation validates easy over difficult (dagger takes longer time = difficult)
  193. func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
  194. if len(block.Extra) > 1024 {
  195. return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
  196. }
  197. expd := CalcDifficulty(block, parent)
  198. if expd.Cmp(block.Difficulty) != 0 {
  199. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
  200. }
  201. // block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
  202. a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
  203. b := new(big.Int).Div(parent.GasLimit, big.NewInt(1024))
  204. if a.Cmp(b) > 0 {
  205. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
  206. }
  207. if block.Time <= parent.Time {
  208. return ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
  209. }
  210. if int64(block.Time) > time.Now().Unix() {
  211. return BlockFutureErr
  212. }
  213. if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
  214. return BlockNumberErr
  215. }
  216. // Verify the nonce of the block. Return an error if it's not valid
  217. if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
  218. return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  219. }
  220. return nil
  221. }
  222. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  223. reward := new(big.Int).Set(BlockReward)
  224. ancestors := set.New()
  225. uncles := set.New()
  226. ancestorHeaders := make(map[string]*types.Header)
  227. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  228. hash := string(ancestor.Hash())
  229. ancestorHeaders[hash] = ancestor.Header()
  230. ancestors.Add(hash)
  231. // Include ancestors uncles in the uncle set. Uncles must be unique.
  232. for _, uncle := range ancestor.Uncles() {
  233. uncles.Add(string(uncle.Hash()))
  234. }
  235. }
  236. uncles.Add(string(block.Hash()))
  237. for _, uncle := range block.Uncles() {
  238. if uncles.Has(string(uncle.Hash())) {
  239. // Error not unique
  240. return UncleError("Uncle not unique")
  241. }
  242. uncles.Add(string(uncle.Hash()))
  243. if ancestors.Has(string(uncle.Hash())) {
  244. return UncleError("Uncle is ancestor")
  245. }
  246. if !ancestors.Has(string(uncle.ParentHash)) {
  247. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  248. }
  249. if err := sm.ValidateHeader(uncle, ancestorHeaders[string(uncle.ParentHash)]); err != nil {
  250. return ValidationError(fmt.Sprintf("%v", err))
  251. }
  252. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  253. return ValidationError("Uncle's nonce is invalid (= %x)", uncle.Nonce)
  254. }
  255. r := new(big.Int)
  256. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  257. statedb.AddBalance(uncle.Coinbase, r)
  258. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  259. }
  260. // Get the account associated with the coinbase
  261. statedb.AddBalance(block.Header().Coinbase, reward)
  262. return nil
  263. }
  264. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  265. if !sm.bc.HasBlock(block.Header().ParentHash) {
  266. return nil, ParentError(block.Header().ParentHash)
  267. }
  268. sm.lastAttemptedBlock = block
  269. var (
  270. parent = sm.bc.GetBlock(block.Header().ParentHash)
  271. state = state.New(parent.Root(), sm.db)
  272. )
  273. sm.TransitionState(state, parent, block, true)
  274. sm.AccumulateRewards(state, block, parent)
  275. return state.Logs(), nil
  276. }