block_processor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package core
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "time"
  8. "github.com/ethereum/ethash"
  9. "github.com/ethereum/go-ethereum/core/types"
  10. "github.com/ethereum/go-ethereum/ethutil"
  11. "github.com/ethereum/go-ethereum/event"
  12. "github.com/ethereum/go-ethereum/logger"
  13. "github.com/ethereum/go-ethereum/pow"
  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 ethutil.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 ethutil.Database, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  40. sm := &BlockProcessor{
  41. db: db,
  42. mem: make(map[string]*big.Int),
  43. Pow: ethash.New(chainManager),
  44. bc: chainManager,
  45. eventMux: eventMux,
  46. txpool: txpool,
  47. }
  48. return sm
  49. }
  50. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  51. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  52. coinbase.SetGasPool(block.Header().GasLimit)
  53. // Process the transactions on to parent state
  54. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return receipts, nil
  59. }
  60. 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) {
  61. // If we are mining this block and validating we want to set the logs back to 0
  62. statedb.EmptyLogs()
  63. txGas := new(big.Int).Set(tx.Gas())
  64. cb := statedb.GetStateObject(coinbase.Address())
  65. st := NewStateTransition(NewEnv(statedb, self.bc, tx, block), tx, cb)
  66. _, err := st.TransitionState()
  67. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err)) {
  68. return nil, nil, err
  69. }
  70. txGas.Sub(txGas, st.gas)
  71. // Update the state with pending changes
  72. statedb.Update(txGas)
  73. cumulative := new(big.Int).Set(usedGas.Add(usedGas, txGas))
  74. receipt := types.NewReceipt(statedb.Root(), 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, txGas, 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 {
  101. switch {
  102. case IsNonceErr(err):
  103. return nil, nil, nil, nil, err
  104. case state.IsGasLimitErr(err):
  105. return nil, nil, nil, nil, err
  106. default:
  107. statelogger.Infoln(err)
  108. erroneous = append(erroneous, tx)
  109. err = nil
  110. }
  111. }
  112. receipts = append(receipts, receipt)
  113. handled = append(handled, tx)
  114. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  115. }
  116. block.Reward = cumulativeSum
  117. block.Header().GasUsed = totalUsedGas
  118. if transientProcess {
  119. go self.eventMux.Post(PendingBlockEvent{block})
  120. }
  121. return receipts, handled, unhandled, erroneous, err
  122. }
  123. // Process block will attempt to process the given block's transactions and applies them
  124. // on top of the block's parent state (given it exists) and will return wether it was
  125. // successful or not.
  126. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
  127. // Processing a blocks may never happen simultaneously
  128. sm.mutex.Lock()
  129. defer sm.mutex.Unlock()
  130. header := block.Header()
  131. if sm.bc.HasBlock(header.Hash()) {
  132. return nil, &KnownBlockError{header.Number, header.Hash()}
  133. }
  134. if !sm.bc.HasBlock(header.ParentHash) {
  135. return nil, ParentError(header.ParentHash)
  136. }
  137. parent := sm.bc.GetBlock(header.ParentHash)
  138. return sm.processWithParent(block, parent)
  139. }
  140. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big.Int, err error) {
  141. sm.lastAttemptedBlock = block
  142. // Create a new state based on the parent's root (e.g., create copy)
  143. state := state.New(parent.Root(), sm.db)
  144. // Block validation
  145. if err = sm.ValidateBlock(block, parent); err != nil {
  146. return
  147. }
  148. receipts, err := sm.TransitionState(state, parent, block, false)
  149. if err != nil {
  150. return
  151. }
  152. header := block.Header()
  153. // Validate the received block's bloom with the one derived from the generated receipts.
  154. // For valid blocks this should always validate to true.
  155. rbloom := types.CreateBloom(receipts)
  156. if bytes.Compare(rbloom, header.Bloom) != 0 {
  157. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  158. return
  159. }
  160. // The transactions Trie's root (R = (Tr [[H1, T1], [H2, T2], ... [Hn, Tn]]))
  161. // can be used by light clients to make sure they've received the correct Txs
  162. txSha := types.DeriveSha(block.Transactions())
  163. if bytes.Compare(txSha, header.TxHash) != 0 {
  164. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  165. return
  166. }
  167. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  168. receiptSha := types.DeriveSha(receipts)
  169. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  170. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  171. return
  172. }
  173. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  174. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  175. return
  176. }
  177. // Commit state objects/accounts to a temporary trie (does not save)
  178. // used to calculate the state root.
  179. state.Update(ethutil.Big0)
  180. if !bytes.Equal(header.Root, state.Root()) {
  181. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  182. return
  183. }
  184. // Calculate the td for this block
  185. td = CalculateTD(block, parent)
  186. // Sync the current block's state to the database
  187. state.Sync()
  188. // Remove transactions from the pool
  189. sm.txpool.RemoveSet(block.Transactions())
  190. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  191. return td, nil
  192. }
  193. // Validates the current block. Returns an error if the block was invalid,
  194. // an uncle or anything that isn't on the current block chain.
  195. // Validation validates easy over difficult (dagger takes longer time = difficult)
  196. func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
  197. if len(block.Header().Extra) > 1024 {
  198. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  199. }
  200. expd := CalcDifficulty(block, parent)
  201. if expd.Cmp(block.Header().Difficulty) != 0 {
  202. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  203. }
  204. //expl := CalcGasLimit(parent, block)
  205. //if expl.Cmp(block.Header().GasLimit) != 0 {
  206. // block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
  207. a := new(big.Int).Sub(block.Header().GasLimit, parent.Header().GasLimit)
  208. b := new(big.Int).Div(parent.Header().GasLimit, big.NewInt(1024))
  209. if a.Cmp(b) > 0 {
  210. return fmt.Errorf("GasLimit check failed for block %v", block.Header().GasLimit)
  211. }
  212. // There can be at most one uncle
  213. if len(block.Uncles()) > 1 {
  214. return ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
  215. }
  216. if block.Time() < parent.Time() {
  217. return ValidationError("Block timestamp not after prev block (%v - %v)", block.Header().Time, parent.Header().Time)
  218. }
  219. if block.Time() > time.Now().Unix() {
  220. return BlockFutureErr
  221. }
  222. if new(big.Int).Sub(block.Number(), parent.Number()).Cmp(big.NewInt(1)) != 0 {
  223. return BlockNumberErr
  224. }
  225. // Verify the nonce of the block. Return an error if it's not valid
  226. if !sm.Pow.Verify(block) {
  227. return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Header().Nonce))
  228. }
  229. return nil
  230. }
  231. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  232. reward := new(big.Int).Set(BlockReward)
  233. ancestors := set.New()
  234. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  235. ancestors.Add(string(ancestor.Hash()))
  236. }
  237. uncles := set.New()
  238. uncles.Add(string(block.Hash()))
  239. for _, uncle := range block.Uncles() {
  240. if uncles.Has(string(uncle.Hash())) {
  241. // Error not unique
  242. return UncleError("Uncle not unique")
  243. }
  244. uncles.Add(string(uncle.Hash()))
  245. if !ancestors.Has(string(uncle.ParentHash)) {
  246. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  247. }
  248. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  249. return ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
  250. }
  251. r := new(big.Int)
  252. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  253. statedb.AddBalance(uncle.Coinbase, r)
  254. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  255. }
  256. // Get the account associated with the coinbase
  257. statedb.AddBalance(block.Header().Coinbase, reward)
  258. return nil
  259. }
  260. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  261. if !sm.bc.HasBlock(block.Header().ParentHash) {
  262. return nil, ParentError(block.Header().ParentHash)
  263. }
  264. sm.lastAttemptedBlock = block
  265. var (
  266. parent = sm.bc.GetBlock(block.Header().ParentHash)
  267. state = state.New(parent.Root(), sm.db)
  268. )
  269. sm.TransitionState(state, parent, block, true)
  270. sm.AccumulateRewards(state, block, parent)
  271. return state.Logs(), nil
  272. }