block_processor.go 10.0 KB

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