block_processor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. type PendingBlockEvent struct {
  17. Block *types.Block
  18. }
  19. var statelogger = logger.NewLogger("BLOCK")
  20. type BlockProcessor struct {
  21. db common.Database
  22. extraDb common.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, extra common.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  40. sm := &BlockProcessor{
  41. db: db,
  42. extraDb: extra,
  43. mem: make(map[string]*big.Int),
  44. Pow: pow,
  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, transientProcess bool) (receipts types.Receipts, err error) {
  52. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  53. coinbase.SetGasPool(block.Header().GasLimit)
  54. // Process the transactions on to parent state
  55. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return receipts, nil
  60. }
  61. 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) {
  62. // If we are mining this block and validating we want to set the logs back to 0
  63. statedb.EmptyLogs()
  64. cb := statedb.GetStateObject(coinbase.Address())
  65. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, block), tx, cb)
  66. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  67. // If the account is managed, remove the invalid nonce.
  68. self.bc.TxState().RemoveNonce(tx.From(), tx.Nonce())
  69. return nil, nil, err
  70. }
  71. // Update the state with pending changes
  72. statedb.Update(nil)
  73. cumulative := new(big.Int).Set(usedGas.Add(usedGas, gas))
  74. receipt := types.NewReceipt(statedb.Root().Bytes(), cumulative)
  75. receipt.SetLogs(statedb.Logs())
  76. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  77. chainlogger.Debugln(receipt)
  78. // Notify all subscribers
  79. if !transientProcess {
  80. go self.eventMux.Post(TxPostEvent{tx})
  81. logs := statedb.Logs()
  82. go self.eventMux.Post(logs)
  83. }
  84. return receipt, gas, err
  85. }
  86. func (self *BlockProcessor) ChainManager() *ChainManager {
  87. return self.bc
  88. }
  89. 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) {
  90. var (
  91. receipts types.Receipts
  92. handled, unhandled types.Transactions
  93. erroneous types.Transactions
  94. totalUsedGas = big.NewInt(0)
  95. err error
  96. cumulativeSum = new(big.Int)
  97. )
  98. for _, tx := range txs {
  99. receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
  100. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  101. return nil, nil, nil, nil, err
  102. }
  103. if err != nil {
  104. statelogger.Infoln("TX err:", err)
  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.ValidateHeader(block.Header(), parent.Header()); err != nil {
  140. return
  141. }
  142. // There can be at most two uncles
  143. if len(block.Uncles()) > 2 {
  144. return nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
  145. }
  146. receipts, err := sm.TransitionState(state, parent, block, false)
  147. if err != nil {
  148. return
  149. }
  150. header := block.Header()
  151. // Validate the received block's bloom with the one derived from the generated receipts.
  152. // For valid blocks this should always validate to true.
  153. rbloom := types.CreateBloom(receipts)
  154. if rbloom != header.Bloom {
  155. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  156. return
  157. }
  158. // The transactions Trie's root (R = (Tr [[H1, T1], [H2, T2], ... [Hn, Tn]]))
  159. // can be used by light clients to make sure they've received the correct Txs
  160. txSha := types.DeriveSha(block.Transactions())
  161. if txSha != header.TxHash {
  162. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  163. return
  164. }
  165. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  166. receiptSha := types.DeriveSha(receipts)
  167. if receiptSha != header.ReceiptHash {
  168. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  169. return
  170. }
  171. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  172. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  173. return
  174. }
  175. // Commit state objects/accounts to a temporary trie (does not save)
  176. // used to calculate the state root.
  177. state.Update(common.Big0)
  178. if header.Root != state.Root() {
  179. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  180. return
  181. }
  182. // Calculate the td for this block
  183. td = CalculateTD(block, parent)
  184. // Sync the current block's state to the database
  185. state.Sync()
  186. // Remove transactions from the pool
  187. sm.txpool.RemoveSet(block.Transactions())
  188. for _, tx := range block.Transactions() {
  189. putTx(sm.extraDb, tx)
  190. }
  191. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash().Bytes()[0:4])
  192. return td, nil
  193. }
  194. // Validates the current block. Returns an error if the block was invalid,
  195. // an uncle or anything that isn't on the current block chain.
  196. // Validation validates easy over difficult (dagger takes longer time = difficult)
  197. func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
  198. if len(block.Extra) > 1024 {
  199. return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
  200. }
  201. expd := CalcDifficulty(block, parent)
  202. if expd.Cmp(block.Difficulty) != 0 {
  203. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
  204. }
  205. // block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
  206. a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
  207. b := new(big.Int).Div(parent.GasLimit, big.NewInt(1024))
  208. if a.Cmp(b) > 0 {
  209. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
  210. }
  211. if block.Time <= parent.Time {
  212. return ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
  213. }
  214. if int64(block.Time) > time.Now().Unix() {
  215. return BlockFutureErr
  216. }
  217. if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
  218. return BlockNumberErr
  219. }
  220. // Verify the nonce of the block. Return an error if it's not valid
  221. if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
  222. return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  223. }
  224. return nil
  225. }
  226. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  227. reward := new(big.Int).Set(BlockReward)
  228. ancestors := set.New()
  229. uncles := set.New()
  230. ancestorHeaders := make(map[common.Hash]*types.Header)
  231. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  232. ancestorHeaders[ancestor.Hash()] = ancestor.Header()
  233. ancestors.Add(ancestor.Hash())
  234. // Include ancestors uncles in the uncle set. Uncles must be unique.
  235. for _, uncle := range ancestor.Uncles() {
  236. uncles.Add(uncle.Hash())
  237. }
  238. }
  239. uncles.Add(block.Hash())
  240. for _, uncle := range block.Uncles() {
  241. if uncles.Has(uncle.Hash()) {
  242. // Error not unique
  243. return UncleError("Uncle not unique")
  244. }
  245. uncles.Add(uncle.Hash())
  246. if ancestors.Has(uncle.Hash()) {
  247. return UncleError("Uncle is ancestor")
  248. }
  249. if !ancestors.Has(uncle.ParentHash) {
  250. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  251. }
  252. if err := sm.ValidateHeader(uncle, ancestorHeaders[uncle.ParentHash]); err != nil {
  253. return ValidationError(fmt.Sprintf("%v", err))
  254. }
  255. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  256. return ValidationError("Uncle's nonce is invalid (= %x)", uncle.Nonce)
  257. }
  258. r := new(big.Int)
  259. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  260. statedb.AddBalance(uncle.Coinbase, r)
  261. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  262. }
  263. // Get the account associated with the coinbase
  264. statedb.AddBalance(block.Header().Coinbase, reward)
  265. return nil
  266. }
  267. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  268. if !sm.bc.HasBlock(block.Header().ParentHash) {
  269. return nil, ParentError(block.Header().ParentHash)
  270. }
  271. sm.lastAttemptedBlock = block
  272. var (
  273. parent = sm.bc.GetBlock(block.Header().ParentHash)
  274. state = state.New(parent.Root(), sm.db)
  275. )
  276. sm.TransitionState(state, parent, block, true)
  277. sm.AccumulateRewards(state, block, parent)
  278. return state.Logs(), nil
  279. }
  280. func putTx(db common.Database, tx *types.Transaction) {
  281. rlpEnc, err := rlp.EncodeToBytes(tx)
  282. if err != nil {
  283. statelogger.Infoln("Failed encoding tx", err)
  284. return
  285. }
  286. db.Put(tx.Hash().Bytes(), rlpEnc)
  287. }