block_processor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. const (
  19. // must be bumped when consensus algorithm is changed, this forces the upgradedb
  20. // command to be run (forces the blocks to be imported again using the new algorithm)
  21. BlockChainVersion = 3
  22. )
  23. var receiptsPre = []byte("receipts-")
  24. type BlockProcessor struct {
  25. db common.Database
  26. extraDb common.Database
  27. // Mutex for locking the block processor. Blocks can only be handled one at a time
  28. mutex sync.Mutex
  29. // Canonical block chain
  30. bc *ChainManager
  31. // non-persistent key/value memory storage
  32. mem map[string]*big.Int
  33. // Proof of work used for validating
  34. Pow pow.PoW
  35. events event.Subscription
  36. eventMux *event.TypeMux
  37. }
  38. func NewBlockProcessor(db, extra common.Database, pow pow.PoW, 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. }
  47. return sm
  48. }
  49. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  50. coinbase := statedb.GetOrNewStateObject(block.Coinbase())
  51. coinbase.SetGasLimit(block.GasLimit())
  52. // Process the transactions on to parent state
  53. receipts, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return receipts, nil
  58. }
  59. func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
  60. // If we are mining this block and validating we want to set the logs back to 0
  61. cb := statedb.GetStateObject(coinbase.Address())
  62. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, header), tx, cb)
  63. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  64. return nil, nil, err
  65. }
  66. // Update the state with pending changes
  67. statedb.Update()
  68. usedGas.Add(usedGas, gas)
  69. receipt := types.NewReceipt(statedb.Root().Bytes(), usedGas)
  70. logs := statedb.GetLogs(tx.Hash())
  71. receipt.SetLogs(logs)
  72. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  73. glog.V(logger.Debug).Infoln(receipt)
  74. // Notify all subscribers
  75. if !transientProcess {
  76. go self.eventMux.Post(TxPostEvent{tx})
  77. go self.eventMux.Post(logs)
  78. }
  79. return receipt, gas, err
  80. }
  81. func (self *BlockProcessor) ChainManager() *ChainManager {
  82. return self.bc
  83. }
  84. func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
  85. var (
  86. receipts types.Receipts
  87. totalUsedGas = big.NewInt(0)
  88. err error
  89. cumulativeSum = new(big.Int)
  90. header = block.Header()
  91. )
  92. for i, tx := range txs {
  93. statedb.StartRecord(tx.Hash(), block.Hash(), i)
  94. receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, header, tx, totalUsedGas, transientProcess)
  95. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  96. return nil, err
  97. }
  98. if err != nil {
  99. glog.V(logger.Core).Infoln("TX err:", err)
  100. }
  101. receipts = append(receipts, receipt)
  102. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  103. }
  104. if block.GasUsed().Cmp(totalUsedGas) != 0 {
  105. return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
  106. }
  107. if transientProcess {
  108. go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
  109. }
  110. return receipts, err
  111. }
  112. func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err error) {
  113. // Processing a blocks may never happen simultaneously
  114. sm.mutex.Lock()
  115. defer sm.mutex.Unlock()
  116. if !sm.bc.HasBlock(block.ParentHash()) {
  117. return nil, ParentError(block.ParentHash())
  118. }
  119. parent := sm.bc.GetBlock(block.ParentHash())
  120. // FIXME Change to full header validation. See #1225
  121. errch := make(chan bool)
  122. go func() { errch <- sm.Pow.Verify(block) }()
  123. logs, _, err = sm.processWithParent(block, parent)
  124. if !<-errch {
  125. return nil, ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  126. }
  127. return logs, err
  128. }
  129. // Process block will attempt to process the given block's transactions and applies them
  130. // on top of the block's parent state (given it exists) and will return wether it was
  131. // successful or not.
  132. func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
  133. // Processing a blocks may never happen simultaneously
  134. sm.mutex.Lock()
  135. defer sm.mutex.Unlock()
  136. if sm.bc.HasBlock(block.Hash()) {
  137. return nil, nil, &KnownBlockError{block.Number(), block.Hash()}
  138. }
  139. if !sm.bc.HasBlock(block.ParentHash()) {
  140. return nil, nil, ParentError(block.ParentHash())
  141. }
  142. parent := sm.bc.GetBlock(block.ParentHash())
  143. return sm.processWithParent(block, parent)
  144. }
  145. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
  146. // Create a new state based on the parent's root (e.g., create copy)
  147. state := state.New(parent.Root(), sm.db)
  148. header := block.Header()
  149. uncles := block.Uncles()
  150. txs := block.Transactions()
  151. // Block validation
  152. if err = ValidateHeader(sm.Pow, header, parent, false); err != nil {
  153. return
  154. }
  155. // There can be at most two uncles
  156. if len(uncles) > 2 {
  157. return nil, nil, ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(uncles))
  158. }
  159. receipts, err = sm.TransitionState(state, parent, block, false)
  160. if err != nil {
  161. return
  162. }
  163. // Validate the received block's bloom with the one derived from the generated receipts.
  164. // For valid blocks this should always validate to true.
  165. rbloom := types.CreateBloom(receipts)
  166. if rbloom != header.Bloom {
  167. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  168. return
  169. }
  170. // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
  171. // can be used by light clients to make sure they've received the correct Txs
  172. txSha := types.DeriveSha(txs)
  173. if txSha != header.TxHash {
  174. err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
  175. return
  176. }
  177. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  178. receiptSha := types.DeriveSha(receipts)
  179. if receiptSha != header.ReceiptHash {
  180. err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
  181. return
  182. }
  183. // Verify UncleHash before running other uncle validations
  184. unclesSha := types.CalcUncleHash(uncles)
  185. if unclesSha != header.UncleHash {
  186. err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
  187. return
  188. }
  189. // Verify uncles
  190. if err = sm.VerifyUncles(state, block, parent); err != nil {
  191. return
  192. }
  193. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  194. AccumulateRewards(state, header, uncles)
  195. // Commit state objects/accounts to a temporary trie (does not save)
  196. // used to calculate the state root.
  197. state.Update()
  198. if header.Root != state.Root() {
  199. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  200. return
  201. }
  202. // Sync the current block's state to the database
  203. state.Sync()
  204. return state.Logs(), receipts, nil
  205. }
  206. var (
  207. big8 = big.NewInt(8)
  208. big32 = big.NewInt(32)
  209. )
  210. // AccumulateRewards credits the coinbase of the given block with the
  211. // mining reward. The total reward consists of the static block reward
  212. // and rewards for included uncles. The coinbase of each uncle block is
  213. // also rewarded.
  214. func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*types.Header) {
  215. reward := new(big.Int).Set(BlockReward)
  216. r := new(big.Int)
  217. for _, uncle := range uncles {
  218. r.Add(uncle.Number, big8)
  219. r.Sub(r, header.Number)
  220. r.Mul(r, BlockReward)
  221. r.Div(r, big8)
  222. statedb.AddBalance(uncle.Coinbase, r)
  223. r.Div(BlockReward, big32)
  224. reward.Add(reward, r)
  225. }
  226. statedb.AddBalance(header.Coinbase, reward)
  227. }
  228. func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
  229. uncles := set.New()
  230. ancestors := make(map[common.Hash]*types.Block)
  231. for _, ancestor := range sm.bc.GetBlocksFromHash(block.ParentHash(), 7) {
  232. ancestors[ancestor.Hash()] = ancestor
  233. // Include ancestors uncles in the uncle set. Uncles must be unique.
  234. for _, uncle := range ancestor.Uncles() {
  235. uncles.Add(uncle.Hash())
  236. }
  237. }
  238. ancestors[block.Hash()] = block
  239. uncles.Add(block.Hash())
  240. for i, uncle := range block.Uncles() {
  241. hash := uncle.Hash()
  242. if uncles.Has(hash) {
  243. // Error not unique
  244. return UncleError("uncle[%d](%x) not unique", i, hash[:4])
  245. }
  246. uncles.Add(hash)
  247. if ancestors[hash] != nil {
  248. branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
  249. for h := range ancestors {
  250. branch += fmt.Sprintf(" O - %x\n |\n", h)
  251. }
  252. glog.Infoln(branch)
  253. return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
  254. }
  255. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() {
  256. return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
  257. }
  258. if err := ValidateHeader(sm.Pow, uncle, ancestors[uncle.ParentHash], true); err != nil {
  259. return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
  260. }
  261. }
  262. return nil
  263. }
  264. // GetBlockReceipts returns the receipts beloniging to the block hash
  265. func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) (receipts types.Receipts, err error) {
  266. return getBlockReceipts(sm.extraDb, bhash)
  267. }
  268. // GetLogs returns the logs of the given block. This method is using a two step approach
  269. // where it tries to get it from the (updated) method which gets them from the receipts or
  270. // the depricated way by re-processing the block.
  271. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  272. receipts, err := sm.GetBlockReceipts(block.Hash())
  273. if err == nil && len(receipts) > 0 {
  274. // coalesce logs
  275. for _, receipt := range receipts {
  276. logs = append(logs, receipt.Logs()...)
  277. }
  278. return
  279. }
  280. // TODO: remove backward compatibility
  281. var (
  282. parent = sm.bc.GetBlock(block.ParentHash())
  283. state = state.New(parent.Root(), sm.db)
  284. )
  285. sm.TransitionState(state, parent, block, true)
  286. return state.Logs(), nil
  287. }
  288. // See YP section 4.3.4. "Block Header Validity"
  289. // Validates a block. Returns an error if the block is invalid.
  290. func ValidateHeader(pow pow.PoW, block *types.Header, parent *types.Block, checkPow bool) error {
  291. if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
  292. return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
  293. }
  294. if block.Time > uint64(time.Now().Unix()) {
  295. return BlockFutureErr
  296. }
  297. if block.Time <= parent.Time() {
  298. return BlockEqualTSErr
  299. }
  300. expd := CalcDifficulty(int64(block.Time), int64(parent.Time()), parent.Difficulty())
  301. if expd.Cmp(block.Difficulty) != 0 {
  302. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
  303. }
  304. var a, b *big.Int
  305. a = parent.GasLimit()
  306. a = a.Sub(a, block.GasLimit)
  307. a.Abs(a)
  308. b = parent.GasLimit()
  309. b = b.Div(b, params.GasLimitBoundDivisor)
  310. if !(a.Cmp(b) < 0) || (block.GasLimit.Cmp(params.MinGasLimit) == -1) {
  311. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
  312. }
  313. num := parent.Number()
  314. num.Sub(block.Number, num)
  315. if num.Cmp(big.NewInt(1)) != 0 {
  316. return BlockNumberErr
  317. }
  318. if checkPow {
  319. // Verify the nonce of the block. Return an error if it's not valid
  320. if !pow.Verify(types.NewBlockWithHeader(block)) {
  321. return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  322. }
  323. }
  324. return nil
  325. }
  326. func getBlockReceipts(db common.Database, bhash common.Hash) (receipts types.Receipts, err error) {
  327. var rdata []byte
  328. rdata, err = db.Get(append(receiptsPre, bhash[:]...))
  329. if err == nil {
  330. err = rlp.DecodeBytes(rdata, &receipts)
  331. } else {
  332. glog.V(logger.Detail).Infof("getBlockReceipts error %v\n", err)
  333. }
  334. return
  335. }