block_processor.go 11 KB

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