block_processor.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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/pow/ezp"
  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: ezp.New(),
  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) (receipts types.Receipts, err error) {
  51. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  52. coinbase.SetGasPool(CalcGasLimit(parent, block))
  53. // Process the transactions on to parent state
  54. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), false)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return receipts, nil
  59. }
  60. func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, state *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. state.EmptyLogs()
  63. txGas := new(big.Int).Set(tx.Gas())
  64. cb := state.GetStateObject(coinbase.Address())
  65. st := NewStateTransition(NewEnv(state, self.bc, tx, block), tx, cb)
  66. _, err := st.TransitionState()
  67. txGas.Sub(txGas, st.gas)
  68. // Update the state with pending changes
  69. state.Update(txGas)
  70. cumulative := new(big.Int).Set(usedGas.Add(usedGas, txGas))
  71. receipt := types.NewReceipt(state.Root(), cumulative)
  72. receipt.SetLogs(state.Logs())
  73. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  74. chainlogger.Debugln(receipt)
  75. // Notify all subscribers
  76. if !transientProcess {
  77. go self.eventMux.Post(TxPostEvent{tx})
  78. }
  79. go self.eventMux.Post(state.Logs())
  80. return receipt, txGas, err
  81. }
  82. func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
  83. var (
  84. receipts types.Receipts
  85. handled, unhandled types.Transactions
  86. erroneous types.Transactions
  87. totalUsedGas = big.NewInt(0)
  88. err error
  89. cumulativeSum = new(big.Int)
  90. )
  91. for _, tx := range txs {
  92. receipt, txGas, err := self.ApplyTransaction(coinbase, state, block, tx, totalUsedGas, transientProcess)
  93. if err != nil {
  94. switch {
  95. case IsNonceErr(err):
  96. return nil, nil, nil, nil, err
  97. case IsGasLimitErr(err):
  98. return nil, nil, nil, nil, err
  99. default:
  100. statelogger.Infoln(err)
  101. erroneous = append(erroneous, tx)
  102. err = nil
  103. }
  104. }
  105. receipts = append(receipts, receipt)
  106. handled = append(handled, tx)
  107. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  108. }
  109. block.Reward = cumulativeSum
  110. block.Header().GasUsed = totalUsedGas
  111. if transientProcess {
  112. go self.eventMux.Post(PendingBlockEvent{block})
  113. }
  114. return receipts, handled, unhandled, erroneous, err
  115. }
  116. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
  117. // Processing a blocks may never happen simultaneously
  118. sm.mutex.Lock()
  119. defer sm.mutex.Unlock()
  120. header := block.Header()
  121. if sm.bc.HasBlock(header.Hash()) {
  122. return nil, &KnownBlockError{header.Number, header.Hash()}
  123. }
  124. if !sm.bc.HasBlock(header.ParentHash) {
  125. return nil, ParentError(header.ParentHash)
  126. }
  127. parent := sm.bc.GetBlock(header.ParentHash)
  128. return sm.ProcessWithParent(block, parent)
  129. }
  130. func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, err error) {
  131. sm.lastAttemptedBlock = block
  132. state := state.New(parent.Root(), sm.db)
  133. //state := state.New(parent.Trie().Copy())
  134. // Block validation
  135. if err = sm.ValidateBlock(block, parent); err != nil {
  136. return
  137. }
  138. receipts, err := sm.TransitionState(state, parent, block)
  139. if err != nil {
  140. return
  141. }
  142. header := block.Header()
  143. rbloom := types.CreateBloom(receipts)
  144. if bytes.Compare(rbloom, header.Bloom) != 0 {
  145. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  146. return
  147. }
  148. txSha := types.DeriveSha(block.Transactions())
  149. if bytes.Compare(txSha, header.TxHash) != 0 {
  150. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  151. return
  152. }
  153. receiptSha := types.DeriveSha(receipts)
  154. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  155. fmt.Println("receipts", receipts)
  156. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  157. return
  158. }
  159. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  160. return
  161. }
  162. state.Update(ethutil.Big0)
  163. if !bytes.Equal(header.Root, state.Root()) {
  164. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  165. return
  166. }
  167. // Calculate the td for this block
  168. td = CalculateTD(block, parent)
  169. // Sync the current block's state to the database
  170. state.Sync()
  171. // Set the block hashes for the current messages
  172. state.Manifest().SetHash(block.Hash())
  173. // Reset the manifest XXX We need this?
  174. state.Manifest().Reset()
  175. // Remove transactions from the pool
  176. sm.txpool.RemoveSet(block.Transactions())
  177. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  178. return td, nil
  179. }
  180. // Validates the current block. Returns an error if the block was invalid,
  181. // an uncle or anything that isn't on the current block chain.
  182. // Validation validates easy over difficult (dagger takes longer time = difficult)
  183. func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
  184. if len(block.Header().Extra) > 1024 {
  185. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  186. }
  187. expd := CalcDifficulty(block, parent)
  188. if expd.Cmp(block.Header().Difficulty) != 0 {
  189. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  190. }
  191. if block.Time() < parent.Time() {
  192. return ValidationError("Block timestamp not after prev block (%v - %v)", block.Header().Time, parent.Header().Time)
  193. }
  194. if block.Time() > time.Now().Unix() {
  195. return fmt.Errorf("block time is in the future")
  196. }
  197. // Verify the nonce of the block. Return an error if it's not valid
  198. if !sm.Pow.Verify(block) {
  199. return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Header().Nonce))
  200. }
  201. return nil
  202. }
  203. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  204. reward := new(big.Int).Set(BlockReward)
  205. ancestors := set.New()
  206. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  207. ancestors.Add(string(ancestor.Hash()))
  208. }
  209. uncles := set.New()
  210. uncles.Add(string(block.Hash()))
  211. for _, uncle := range block.Uncles() {
  212. if uncles.Has(string(uncle.Hash())) {
  213. // Error not unique
  214. return UncleError("Uncle not unique")
  215. }
  216. uncles.Add(string(uncle.Hash()))
  217. if !ancestors.Has(string(uncle.ParentHash)) {
  218. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  219. }
  220. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  221. return ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
  222. }
  223. r := new(big.Int)
  224. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  225. uncleAccount := statedb.GetAccount(uncle.Coinbase)
  226. uncleAccount.AddAmount(r)
  227. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  228. }
  229. // Get the account associated with the coinbase
  230. account := statedb.GetAccount(block.Header().Coinbase)
  231. // Reward amount of ether to the coinbase address
  232. account.AddAmount(reward)
  233. return nil
  234. }
  235. func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Message, err error) {
  236. if !sm.bc.HasBlock(block.Header().ParentHash) {
  237. return nil, ParentError(block.Header().ParentHash)
  238. }
  239. sm.lastAttemptedBlock = block
  240. var (
  241. parent = sm.bc.GetBlock(block.Header().ParentHash)
  242. //state = state.New(parent.Trie().Copy())
  243. state = state.New(parent.Root(), sm.db)
  244. )
  245. defer state.Reset()
  246. sm.TransitionState(state, parent, block)
  247. sm.AccumulateRewards(state, block, parent)
  248. return state.Manifest().Messages, nil
  249. }
  250. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  251. if !sm.bc.HasBlock(block.Header().ParentHash) {
  252. return nil, ParentError(block.Header().ParentHash)
  253. }
  254. sm.lastAttemptedBlock = block
  255. var (
  256. parent = sm.bc.GetBlock(block.Header().ParentHash)
  257. //state = state.New(parent.Trie().Copy())
  258. state = state.New(parent.Root(), sm.db)
  259. )
  260. defer state.Reset()
  261. sm.TransitionState(state, parent, block)
  262. sm.AccumulateRewards(state, block, parent)
  263. return state.Logs(), nil
  264. }