block_processor.go 9.9 KB

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