block_processor.go 11 KB

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