block_processor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.ValidateBlock(block, parent); err != nil {
  145. return
  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(ethutil.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. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  190. return td, 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) ValidateBlock(block, parent *types.Block) error {
  196. if len(block.Header().Extra) > 1024 {
  197. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  198. }
  199. expd := CalcDifficulty(block, parent)
  200. if expd.Cmp(block.Header().Difficulty) != 0 {
  201. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  202. }
  203. //expl := CalcGasLimit(parent, block)
  204. //if expl.Cmp(block.Header().GasLimit) != 0 {
  205. // block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
  206. a := new(big.Int).Sub(block.Header().GasLimit, parent.Header().GasLimit)
  207. b := new(big.Int).Div(parent.Header().GasLimit, big.NewInt(1024))
  208. if a.Cmp(b) > 0 {
  209. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.Header().GasLimit, a, b)
  210. }
  211. // There can be at most one uncle
  212. if len(block.Uncles()) > 1 {
  213. return ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
  214. }
  215. if block.Time() < parent.Time() {
  216. return ValidationError("Block timestamp not after prev block (%v - %v)", block.Header().Time, parent.Header().Time)
  217. }
  218. if block.Time() > time.Now().Unix() {
  219. return BlockFutureErr
  220. }
  221. if new(big.Int).Sub(block.Number(), parent.Number()).Cmp(big.NewInt(1)) != 0 {
  222. return BlockNumberErr
  223. }
  224. // Verify the nonce of the block. Return an error if it's not valid
  225. if !sm.Pow.Verify(block) {
  226. return ValidationError("Block's nonce is invalid (= %x)", block.Header().Nonce)
  227. }
  228. return nil
  229. }
  230. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  231. reward := new(big.Int).Set(BlockReward)
  232. ancestors := set.New()
  233. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  234. ancestors.Add(string(ancestor.Hash()))
  235. }
  236. uncles := set.New()
  237. uncles.Add(string(block.Hash()))
  238. for _, uncle := range block.Uncles() {
  239. if uncles.Has(string(uncle.Hash())) {
  240. // Error not unique
  241. return UncleError("Uncle not unique")
  242. }
  243. uncles.Add(string(uncle.Hash()))
  244. if !ancestors.Has(string(uncle.ParentHash)) {
  245. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  246. }
  247. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  248. return ValidationError("Uncle's nonce is invalid (= %x)", uncle.Nonce)
  249. }
  250. r := new(big.Int)
  251. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  252. statedb.AddBalance(uncle.Coinbase, r)
  253. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  254. }
  255. // Get the account associated with the coinbase
  256. statedb.AddBalance(block.Header().Coinbase, reward)
  257. return nil
  258. }
  259. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  260. if !sm.bc.HasBlock(block.Header().ParentHash) {
  261. return nil, ParentError(block.Header().ParentHash)
  262. }
  263. sm.lastAttemptedBlock = block
  264. var (
  265. parent = sm.bc.GetBlock(block.Header().ParentHash)
  266. state = state.New(parent.Root(), sm.db)
  267. )
  268. sm.TransitionState(state, parent, block, true)
  269. sm.AccumulateRewards(state, block, parent)
  270. return state.Logs(), nil
  271. }