block_processor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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/rlp"
  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. extraDb ethutil.Database
  24. // Mutex for locking the block processor. Blocks can only be handled one at a time
  25. mutex sync.Mutex
  26. // Canonical block chain
  27. bc *ChainManager
  28. // non-persistent key/value memory storage
  29. mem map[string]*big.Int
  30. // Proof of work used for validating
  31. Pow pow.PoW
  32. txpool *TxPool
  33. // The last attempted block is mainly used for debugging purposes
  34. // This does not have to be a valid block and will be set during
  35. // 'Process' & canonical validation.
  36. lastAttemptedBlock *types.Block
  37. events event.Subscription
  38. eventMux *event.TypeMux
  39. }
  40. func NewBlockProcessor(db, extra ethutil.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  41. sm := &BlockProcessor{
  42. db: db,
  43. extraDb: extra,
  44. mem: make(map[string]*big.Int),
  45. Pow: pow,
  46. bc: chainManager,
  47. eventMux: eventMux,
  48. txpool: txpool,
  49. }
  50. return sm
  51. }
  52. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  53. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  54. coinbase.SetGasPool(block.Header().GasLimit)
  55. // Process the transactions on to parent state
  56. receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return receipts, nil
  61. }
  62. func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
  63. // If we are mining this block and validating we want to set the logs back to 0
  64. statedb.EmptyLogs()
  65. cb := statedb.GetStateObject(coinbase.Address())
  66. /*
  67. st := NewStateTransition(NewEnv(statedb, self.bc, tx, block), tx, cb)
  68. _, err := st.TransitionState()
  69. */
  70. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, block), tx, cb)
  71. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  72. return nil, nil, err
  73. }
  74. // Update the state with pending changes
  75. statedb.Update(nil)
  76. cumulative := new(big.Int).Set(usedGas.Add(usedGas, gas))
  77. receipt := types.NewReceipt(statedb.Root(), cumulative)
  78. receipt.SetLogs(statedb.Logs())
  79. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  80. chainlogger.Debugln(receipt)
  81. // Notify all subscribers
  82. if !transientProcess {
  83. go self.eventMux.Post(TxPostEvent{tx})
  84. logs := statedb.Logs()
  85. go self.eventMux.Post(logs)
  86. }
  87. return receipt, gas, err
  88. }
  89. func (self *BlockProcessor) ChainManager() *ChainManager {
  90. return self.bc
  91. }
  92. func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
  93. var (
  94. receipts types.Receipts
  95. handled, unhandled types.Transactions
  96. erroneous types.Transactions
  97. totalUsedGas = big.NewInt(0)
  98. err error
  99. cumulativeSum = new(big.Int)
  100. )
  101. for _, tx := range txs {
  102. receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
  103. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  104. return nil, nil, nil, nil, err
  105. }
  106. if err != nil {
  107. statelogger.Infoln("TX err:", err)
  108. }
  109. receipts = append(receipts, receipt)
  110. handled = append(handled, tx)
  111. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  112. }
  113. block.Reward = cumulativeSum
  114. block.Header().GasUsed = totalUsedGas
  115. if transientProcess {
  116. go self.eventMux.Post(PendingBlockEvent{block})
  117. }
  118. return receipts, handled, unhandled, erroneous, err
  119. }
  120. // Process block will attempt to process the given block's transactions and applies them
  121. // on top of the block's parent state (given it exists) and will return wether it was
  122. // successful or not.
  123. func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
  124. // Processing a blocks may never happen simultaneously
  125. sm.mutex.Lock()
  126. defer sm.mutex.Unlock()
  127. header := block.Header()
  128. if sm.bc.HasBlock(header.Hash()) {
  129. return nil, &KnownBlockError{header.Number, header.Hash()}
  130. }
  131. if !sm.bc.HasBlock(header.ParentHash) {
  132. return nil, ParentError(header.ParentHash)
  133. }
  134. parent := sm.bc.GetBlock(header.ParentHash)
  135. return sm.processWithParent(block, parent)
  136. }
  137. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big.Int, err error) {
  138. sm.lastAttemptedBlock = block
  139. // Create a new state based on the parent's root (e.g., create copy)
  140. state := state.New(parent.Root(), sm.db)
  141. // Block validation
  142. if err = sm.ValidateHeader(block.Header(), parent.Header()); err != nil {
  143. return
  144. }
  145. // There can be at most two uncles
  146. if len(block.Uncles()) > 2 {
  147. return nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
  148. }
  149. receipts, err := sm.TransitionState(state, parent, block, false)
  150. if err != nil {
  151. return
  152. }
  153. header := block.Header()
  154. // Validate the received block's bloom with the one derived from the generated receipts.
  155. // For valid blocks this should always validate to true.
  156. rbloom := types.CreateBloom(receipts)
  157. if bytes.Compare(rbloom, header.Bloom) != 0 {
  158. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  159. return
  160. }
  161. // The transactions Trie's root (R = (Tr [[H1, T1], [H2, T2], ... [Hn, Tn]]))
  162. // can be used by light clients to make sure they've received the correct Txs
  163. txSha := types.DeriveSha(block.Transactions())
  164. if bytes.Compare(txSha, header.TxHash) != 0 {
  165. err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
  166. return
  167. }
  168. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  169. receiptSha := types.DeriveSha(receipts)
  170. if bytes.Compare(receiptSha, header.ReceiptHash) != 0 {
  171. err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
  172. return
  173. }
  174. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  175. if err = sm.AccumulateRewards(state, block, parent); err != nil {
  176. return
  177. }
  178. // Commit state objects/accounts to a temporary trie (does not save)
  179. // used to calculate the state root.
  180. state.Update(ethutil.Big0)
  181. if !bytes.Equal(header.Root, state.Root()) {
  182. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  183. return
  184. }
  185. // Calculate the td for this block
  186. td = CalculateTD(block, parent)
  187. // Sync the current block's state to the database
  188. state.Sync()
  189. // Remove transactions from the pool
  190. sm.txpool.RemoveSet(block.Transactions())
  191. for _, tx := range block.Transactions() {
  192. putTx(sm.extraDb, tx)
  193. }
  194. chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
  195. return td, nil
  196. }
  197. // Validates the current block. Returns an error if the block was invalid,
  198. // an uncle or anything that isn't on the current block chain.
  199. // Validation validates easy over difficult (dagger takes longer time = difficult)
  200. func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
  201. if len(block.Extra) > 1024 {
  202. return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
  203. }
  204. expd := CalcDifficulty(block, parent)
  205. if expd.Cmp(block.Difficulty) != 0 {
  206. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
  207. }
  208. // block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
  209. a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
  210. b := new(big.Int).Div(parent.GasLimit, big.NewInt(1024))
  211. if a.Cmp(b) > 0 {
  212. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
  213. }
  214. if block.Time <= parent.Time {
  215. return ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
  216. }
  217. if int64(block.Time) > time.Now().Unix() {
  218. return BlockFutureErr
  219. }
  220. if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
  221. return BlockNumberErr
  222. }
  223. // Verify the nonce of the block. Return an error if it's not valid
  224. if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
  225. return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  226. }
  227. return nil
  228. }
  229. func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
  230. reward := new(big.Int).Set(BlockReward)
  231. ancestors := set.New()
  232. uncles := set.New()
  233. ancestorHeaders := make(map[string]*types.Header)
  234. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  235. hash := string(ancestor.Hash())
  236. ancestorHeaders[hash] = ancestor.Header()
  237. ancestors.Add(hash)
  238. // Include ancestors uncles in the uncle set. Uncles must be unique.
  239. for _, uncle := range ancestor.Uncles() {
  240. uncles.Add(string(uncle.Hash()))
  241. }
  242. }
  243. uncles.Add(string(block.Hash()))
  244. for _, uncle := range block.Uncles() {
  245. if uncles.Has(string(uncle.Hash())) {
  246. // Error not unique
  247. return UncleError("Uncle not unique")
  248. }
  249. uncles.Add(string(uncle.Hash()))
  250. if ancestors.Has(string(uncle.Hash())) {
  251. return UncleError("Uncle is ancestor")
  252. }
  253. if !ancestors.Has(string(uncle.ParentHash)) {
  254. return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  255. }
  256. if err := sm.ValidateHeader(uncle, ancestorHeaders[string(uncle.ParentHash)]); err != nil {
  257. return ValidationError(fmt.Sprintf("%v", err))
  258. }
  259. if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
  260. return ValidationError("Uncle's nonce is invalid (= %x)", uncle.Nonce)
  261. }
  262. r := new(big.Int)
  263. r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
  264. statedb.AddBalance(uncle.Coinbase, r)
  265. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  266. }
  267. // Get the account associated with the coinbase
  268. statedb.AddBalance(block.Header().Coinbase, reward)
  269. return nil
  270. }
  271. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  272. if !sm.bc.HasBlock(block.Header().ParentHash) {
  273. return nil, ParentError(block.Header().ParentHash)
  274. }
  275. sm.lastAttemptedBlock = block
  276. var (
  277. parent = sm.bc.GetBlock(block.Header().ParentHash)
  278. state = state.New(parent.Root(), sm.db)
  279. )
  280. sm.TransitionState(state, parent, block, true)
  281. sm.AccumulateRewards(state, block, parent)
  282. return state.Logs(), nil
  283. }
  284. func putTx(db ethutil.Database, tx *types.Transaction) {
  285. rlpEnc, err := rlp.EncodeToBytes(tx)
  286. if err != nil {
  287. statelogger.Infoln("Failed encoding tx", err)
  288. return
  289. }
  290. db.Put(tx.Hash(), rlpEnc)
  291. }