block_processor.go 11 KB

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