block_processor.go 10 KB

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