block_processor.go 12 KB

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