block_processor.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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/crypto"
  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/p2p"
  14. "github.com/ethereum/go-ethereum/pow"
  15. "github.com/ethereum/go-ethereum/pow/ezp"
  16. "github.com/ethereum/go-ethereum/state"
  17. "gopkg.in/fatih/set.v0"
  18. )
  19. type PendingBlockEvent struct {
  20. Block *types.Block
  21. }
  22. var statelogger = logger.NewLogger("BLOCK")
  23. type EthManager interface {
  24. BlockProcessor() *BlockProcessor
  25. ChainManager() *ChainManager
  26. TxPool() *TxPool
  27. PeerCount() int
  28. IsMining() bool
  29. IsListening() bool
  30. Peers() []*p2p.Peer
  31. KeyManager() *crypto.KeyManager
  32. ClientIdentity() p2p.ClientIdentity
  33. Db() ethutil.Database
  34. EventMux() *event.TypeMux
  35. }
  36. type BlockProcessor struct {
  37. db ethutil.Database
  38. // Mutex for locking the block processor. Blocks can only be handled one at a time
  39. mutex sync.Mutex
  40. // Canonical block chain
  41. bc *ChainManager
  42. // non-persistent key/value memory storage
  43. mem map[string]*big.Int
  44. // Proof of work used for validating
  45. Pow pow.PoW
  46. txpool *TxPool
  47. // The last attempted block is mainly used for debugging purposes
  48. // This does not have to be a valid block and will be set during
  49. // 'Process' & canonical validation.
  50. lastAttemptedBlock *types.Block
  51. events event.Subscription
  52. eventMux *event.TypeMux
  53. }
  54. func NewBlockProcessor(db ethutil.Database, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  55. sm := &BlockProcessor{
  56. db: db,
  57. mem: make(map[string]*big.Int),
  58. Pow: ezp.New(),
  59. bc: chainManager,
  60. eventMux: eventMux,
  61. txpool: txpool,
  62. }
  63. return sm
  64. }
  65. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block) (receipts types.Receipts, err error) {
  66. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  67. coinbase.SetGasPool(CalcGasLimit(parent, block))
  68. // Process the transactions on to parent state
  69. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), false)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return receipts, nil
  74. }
  75. 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) {
  76. // If we are mining this block and validating we want to set the logs back to 0
  77. state.EmptyLogs()
  78. txGas := new(big.Int).Set(tx.Gas())
  79. cb := state.GetStateObject(coinbase.Address())
  80. st := NewStateTransition(NewEnv(state, self.bc, tx, block), tx, cb)
  81. _, err := st.TransitionState()
  82. txGas.Sub(txGas, st.gas)
  83. // Update the state with pending changes
  84. state.Update(txGas)
  85. cumulative := new(big.Int).Set(usedGas.Add(usedGas, txGas))
  86. receipt := types.NewReceipt(state.Root(), cumulative)
  87. receipt.SetLogs(state.Logs())
  88. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  89. chainlogger.Debugln(receipt)
  90. // Notify all subscribers
  91. if !transientProcess {
  92. go self.eventMux.Post(TxPostEvent{tx})
  93. }
  94. go self.eventMux.Post(state.Logs())
  95. return receipt, txGas, err
  96. }
  97. 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) {
  98. var (
  99. receipts types.Receipts
  100. handled, unhandled types.Transactions
  101. erroneous types.Transactions
  102. totalUsedGas = big.NewInt(0)
  103. err error
  104. cumulativeSum = new(big.Int)
  105. )
  106. done:
  107. for i, tx := range txs {
  108. receipt, txGas, err := self.ApplyTransaction(coinbase, state, block, tx, totalUsedGas, transientProcess)
  109. if err != nil {
  110. return nil, nil, nil, nil, err
  111. switch {
  112. case IsNonceErr(err):
  113. err = nil // ignore error
  114. continue
  115. case IsGasLimitErr(err):
  116. unhandled = txs[i:]
  117. break done
  118. default:
  119. statelogger.Infoln(err)
  120. erroneous = append(erroneous, tx)
  121. err = nil
  122. }
  123. }
  124. receipts = append(receipts, receipt)
  125. handled = append(handled, tx)
  126. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  127. }
  128. block.Reward = cumulativeSum
  129. block.Header().GasUsed = totalUsedGas
  130. if transientProcess {
  131. go self.eventMux.Post(PendingBlockEvent{block})
  132. }
  133. return receipts, handled, unhandled, erroneous, err
  134. }
  135. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
  136. // Processing a blocks may never happen simultaneously
  137. sm.mutex.Lock()
  138. defer sm.mutex.Unlock()
  139. header := block.Header()
  140. if sm.bc.HasBlock(header.Hash()) {
  141. return nil, &KnownBlockError{header.Number, header.Hash()}
  142. }
  143. if !sm.bc.HasBlock(header.ParentHash) {
  144. return nil, ParentError(header.ParentHash)
  145. }
  146. parent := sm.bc.GetBlock(header.ParentHash)
  147. return sm.ProcessWithParent(block, parent)
  148. }
  149. func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, err error) {
  150. sm.lastAttemptedBlock = block
  151. state := state.New(parent.Root(), sm.db)
  152. //state := state.New(parent.Trie().Copy())
  153. // Block validation
  154. if err = sm.ValidateBlock(block, parent); err != nil {
  155. return
  156. }
  157. receipts, err := sm.TransitionState(state, parent, block)
  158. if err != nil {
  159. return
  160. }
  161. header := block.Header()
  162. rbloom := types.CreateBloom(receipts)
  163. if bytes.Compare(rbloom, header.Bloom) != 0 {
  164. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  165. return
  166. }
  167. txSha := types.DeriveSha(block.Transactions())
  168. if bytes.Compare(txSha, header.TxHash) != 0 {
  169. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  170. return
  171. }
  172. receiptSha := types.DeriveSha(receipts)
  173. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  174. fmt.Println("receipts", receipts)
  175. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  176. return
  177. }
  178. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  179. return
  180. }
  181. state.Update(ethutil.Big0)
  182. if !bytes.Equal(header.Root, state.Root()) {
  183. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  184. return
  185. }
  186. // Calculate the td for this block
  187. td = CalculateTD(block, parent)
  188. // Sync the current block's state to the database
  189. state.Sync()
  190. // Set the block hashes for the current messages
  191. state.Manifest().SetHash(block.Hash())
  192. // Reset the manifest XXX We need this?
  193. state.Manifest().Reset()
  194. // Remove transactions from the pool
  195. sm.txpool.RemoveSet(block.Transactions())
  196. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  197. return td, nil
  198. }
  199. // Validates the current block. Returns an error if the block was invalid,
  200. // an uncle or anything that isn't on the current block chain.
  201. // Validation validates easy over difficult (dagger takes longer time = difficult)
  202. func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
  203. if len(block.Header().Extra) > 1024 {
  204. return fmt.Errorf("Block extra data too long (%d)", len(block.Header().Extra))
  205. }
  206. expd := CalcDifficulty(block, parent)
  207. if expd.Cmp(block.Header().Difficulty) != 0 {
  208. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
  209. }
  210. diff := block.Header().Time - parent.Header().Time
  211. if diff <= 0 {
  212. return ValidationError("Block timestamp not after prev block %v (%v - %v)", diff, block.Header().Time, sm.bc.CurrentBlock().Header().Time)
  213. }
  214. if block.Time() > time.Now().Unix() {
  215. return fmt.Errorf("block time is in the future")
  216. }
  217. // Verify the nonce of the block. Return an error if it's not valid
  218. if !sm.Pow.Verify(block) {
  219. return ValidationError("Block's nonce is invalid (= %v)", ethutil.Bytes2Hex(block.Header().Nonce))
  220. }
  221. return nil
  222. }
  223. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  224. reward := new(big.Int).Set(BlockReward)
  225. ancestors := set.New()
  226. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  227. ancestors.Add(string(ancestor.Hash()))
  228. }
  229. uncles := set.New()
  230. uncles.Add(string(block.Hash()))
  231. for _, uncle := range block.Uncles() {
  232. if uncles.Has(string(uncle.Hash())) {
  233. // Error not unique
  234. return UncleError("Uncle not unique")
  235. }
  236. uncles.Add(string(uncle.Hash()))
  237. if !ancestors.Has(string(uncle.ParentHash)) {
  238. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  239. }
  240. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  241. return ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
  242. }
  243. r := new(big.Int)
  244. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  245. uncleAccount := statedb.GetAccount(uncle.Coinbase)
  246. uncleAccount.AddAmount(r)
  247. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  248. }
  249. // Get the account associated with the coinbase
  250. account := statedb.GetAccount(block.Header().Coinbase)
  251. // Reward amount of ether to the coinbase address
  252. account.AddAmount(reward)
  253. return nil
  254. }
  255. func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Message, err error) {
  256. if !sm.bc.HasBlock(block.Header().ParentHash) {
  257. return nil, ParentError(block.Header().ParentHash)
  258. }
  259. sm.lastAttemptedBlock = block
  260. var (
  261. parent = sm.bc.GetBlock(block.Header().ParentHash)
  262. //state = state.New(parent.Trie().Copy())
  263. state = state.New(parent.Root(), sm.db)
  264. )
  265. defer state.Reset()
  266. sm.TransitionState(state, parent, block)
  267. sm.AccumulateRewards(state, block, parent)
  268. return state.Manifest().Messages, nil
  269. }
  270. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  271. if !sm.bc.HasBlock(block.Header().ParentHash) {
  272. return nil, ParentError(block.Header().ParentHash)
  273. }
  274. sm.lastAttemptedBlock = block
  275. var (
  276. parent = sm.bc.GetBlock(block.Header().ParentHash)
  277. //state = state.New(parent.Trie().Copy())
  278. state = state.New(parent.Root(), sm.db)
  279. )
  280. defer state.Reset()
  281. sm.TransitionState(state, parent, block)
  282. sm.AccumulateRewards(state, block, parent)
  283. return state.Logs(), nil
  284. }