block_processor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "fmt"
  19. "math/big"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/core/vm"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/logger"
  30. "github.com/ethereum/go-ethereum/logger/glog"
  31. "github.com/ethereum/go-ethereum/params"
  32. "github.com/ethereum/go-ethereum/pow"
  33. "gopkg.in/fatih/set.v0"
  34. )
  35. const (
  36. // must be bumped when consensus algorithm is changed, this forces the upgradedb
  37. // command to be run (forces the blocks to be imported again using the new algorithm)
  38. BlockChainVersion = 3
  39. )
  40. type BlockProcessor struct {
  41. chainDb ethdb.Database
  42. // Mutex for locking the block processor. Blocks can only be handled one at a time
  43. mutex sync.Mutex
  44. // Canonical block chain
  45. bc *BlockChain
  46. // non-persistent key/value memory storage
  47. mem map[string]*big.Int
  48. // Proof of work used for validating
  49. Pow pow.PoW
  50. events event.Subscription
  51. eventMux *event.TypeMux
  52. }
  53. // GasPool tracks the amount of gas available during
  54. // execution of the transactions in a block.
  55. // The zero value is a pool with zero gas available.
  56. type GasPool big.Int
  57. // AddGas makes gas available for execution.
  58. func (gp *GasPool) AddGas(amount *big.Int) *GasPool {
  59. i := (*big.Int)(gp)
  60. i.Add(i, amount)
  61. return gp
  62. }
  63. // SubGas deducts the given amount from the pool if enough gas is
  64. // available and returns an error otherwise.
  65. func (gp *GasPool) SubGas(amount *big.Int) error {
  66. i := (*big.Int)(gp)
  67. if i.Cmp(amount) < 0 {
  68. return &GasLimitErr{Have: new(big.Int).Set(i), Want: amount}
  69. }
  70. i.Sub(i, amount)
  71. return nil
  72. }
  73. func (gp *GasPool) String() string {
  74. return (*big.Int)(gp).String()
  75. }
  76. func NewBlockProcessor(db ethdb.Database, pow pow.PoW, blockchain *BlockChain, eventMux *event.TypeMux) *BlockProcessor {
  77. sm := &BlockProcessor{
  78. chainDb: db,
  79. mem: make(map[string]*big.Int),
  80. Pow: pow,
  81. bc: blockchain,
  82. eventMux: eventMux,
  83. }
  84. return sm
  85. }
  86. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  87. gp := new(GasPool).AddGas(block.GasLimit())
  88. if glog.V(logger.Core) {
  89. glog.Infof("%x: gas (+ %v)", block.Coinbase(), gp)
  90. }
  91. // Process the transactions on to parent state
  92. receipts, err = sm.ApplyTransactions(gp, statedb, block, block.Transactions(), transientProcess)
  93. if err != nil {
  94. return nil, err
  95. }
  96. return receipts, nil
  97. }
  98. func (self *BlockProcessor) ApplyTransaction(gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
  99. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, header), tx, gp)
  100. if err != nil {
  101. return nil, nil, err
  102. }
  103. // Update the state with pending changes
  104. usedGas.Add(usedGas, gas)
  105. receipt := types.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
  106. receipt.TxHash = tx.Hash()
  107. receipt.GasUsed = new(big.Int).Set(gas)
  108. if MessageCreatesContract(tx) {
  109. from, _ := tx.From()
  110. receipt.ContractAddress = crypto.CreateAddress(from, tx.Nonce())
  111. }
  112. logs := statedb.GetLogs(tx.Hash())
  113. receipt.SetLogs(logs)
  114. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  115. glog.V(logger.Debug).Infoln(receipt)
  116. // Notify all subscribers
  117. if !transientProcess {
  118. go self.eventMux.Post(TxPostEvent{tx})
  119. go self.eventMux.Post(logs)
  120. }
  121. return receipt, gas, err
  122. }
  123. func (self *BlockProcessor) BlockChain() *BlockChain {
  124. return self.bc
  125. }
  126. func (self *BlockProcessor) ApplyTransactions(gp *GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
  127. var (
  128. receipts types.Receipts
  129. totalUsedGas = big.NewInt(0)
  130. err error
  131. cumulativeSum = new(big.Int)
  132. header = block.Header()
  133. )
  134. for i, tx := range txs {
  135. statedb.StartRecord(tx.Hash(), block.Hash(), i)
  136. receipt, txGas, err := self.ApplyTransaction(gp, statedb, header, tx, totalUsedGas, transientProcess)
  137. if err != nil {
  138. return nil, err
  139. }
  140. if err != nil {
  141. glog.V(logger.Core).Infoln("TX err:", err)
  142. }
  143. receipts = append(receipts, receipt)
  144. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  145. }
  146. if block.GasUsed().Cmp(totalUsedGas) != 0 {
  147. return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
  148. }
  149. if transientProcess {
  150. go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
  151. }
  152. return receipts, err
  153. }
  154. func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err error) {
  155. // Processing a blocks may never happen simultaneously
  156. sm.mutex.Lock()
  157. defer sm.mutex.Unlock()
  158. if !sm.bc.HasBlock(block.ParentHash()) {
  159. return nil, ParentError(block.ParentHash())
  160. }
  161. parent := sm.bc.GetBlock(block.ParentHash())
  162. // FIXME Change to full header validation. See #1225
  163. errch := make(chan bool)
  164. go func() { errch <- sm.Pow.Verify(block) }()
  165. logs, _, err = sm.processWithParent(block, parent)
  166. if !<-errch {
  167. return nil, ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  168. }
  169. return logs, err
  170. }
  171. // Process block will attempt to process the given block's transactions and applies them
  172. // on top of the block's parent state (given it exists) and will return wether it was
  173. // successful or not.
  174. func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
  175. // Processing a blocks may never happen simultaneously
  176. sm.mutex.Lock()
  177. defer sm.mutex.Unlock()
  178. if sm.bc.HasBlock(block.Hash()) {
  179. return nil, nil, &KnownBlockError{block.Number(), block.Hash()}
  180. }
  181. if !sm.bc.HasBlock(block.ParentHash()) {
  182. return nil, nil, ParentError(block.ParentHash())
  183. }
  184. parent := sm.bc.GetBlock(block.ParentHash())
  185. return sm.processWithParent(block, parent)
  186. }
  187. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
  188. // Create a new state based on the parent's root (e.g., create copy)
  189. state, err := state.New(parent.Root(), sm.chainDb)
  190. if err != nil {
  191. return nil, nil, err
  192. }
  193. header := block.Header()
  194. uncles := block.Uncles()
  195. txs := block.Transactions()
  196. // Block validation
  197. if err = ValidateHeader(sm.Pow, header, parent.Header(), false, false); err != nil {
  198. return
  199. }
  200. // There can be at most two uncles
  201. if len(uncles) > 2 {
  202. return nil, nil, ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(uncles))
  203. }
  204. receipts, err = sm.TransitionState(state, parent, block, false)
  205. if err != nil {
  206. return
  207. }
  208. // Validate the received block's bloom with the one derived from the generated receipts.
  209. // For valid blocks this should always validate to true.
  210. rbloom := types.CreateBloom(receipts)
  211. if rbloom != header.Bloom {
  212. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  213. return
  214. }
  215. // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
  216. // can be used by light clients to make sure they've received the correct Txs
  217. txSha := types.DeriveSha(txs)
  218. if txSha != header.TxHash {
  219. err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
  220. return
  221. }
  222. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  223. receiptSha := types.DeriveSha(receipts)
  224. if receiptSha != header.ReceiptHash {
  225. err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
  226. return
  227. }
  228. // Verify UncleHash before running other uncle validations
  229. unclesSha := types.CalcUncleHash(uncles)
  230. if unclesSha != header.UncleHash {
  231. err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
  232. return
  233. }
  234. // Verify uncles
  235. if err = sm.VerifyUncles(state, block, parent); err != nil {
  236. return
  237. }
  238. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  239. AccumulateRewards(state, header, uncles)
  240. // Commit state objects/accounts to a database batch and calculate
  241. // the state root. The database is not modified if the root
  242. // doesn't match.
  243. root, batch := state.CommitBatch()
  244. if header.Root != root {
  245. return nil, nil, fmt.Errorf("invalid merkle root: header=%x computed=%x", header.Root, root)
  246. }
  247. // Execute the database writes.
  248. batch.Write()
  249. return state.Logs(), receipts, nil
  250. }
  251. var (
  252. big8 = big.NewInt(8)
  253. big32 = big.NewInt(32)
  254. )
  255. // AccumulateRewards credits the coinbase of the given block with the
  256. // mining reward. The total reward consists of the static block reward
  257. // and rewards for included uncles. The coinbase of each uncle block is
  258. // also rewarded.
  259. func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*types.Header) {
  260. reward := new(big.Int).Set(BlockReward)
  261. r := new(big.Int)
  262. for _, uncle := range uncles {
  263. r.Add(uncle.Number, big8)
  264. r.Sub(r, header.Number)
  265. r.Mul(r, BlockReward)
  266. r.Div(r, big8)
  267. statedb.AddBalance(uncle.Coinbase, r)
  268. r.Div(BlockReward, big32)
  269. reward.Add(reward, r)
  270. }
  271. statedb.AddBalance(header.Coinbase, reward)
  272. }
  273. func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
  274. uncles := set.New()
  275. ancestors := make(map[common.Hash]*types.Block)
  276. for _, ancestor := range sm.bc.GetBlocksFromHash(block.ParentHash(), 7) {
  277. ancestors[ancestor.Hash()] = ancestor
  278. // Include ancestors uncles in the uncle set. Uncles must be unique.
  279. for _, uncle := range ancestor.Uncles() {
  280. uncles.Add(uncle.Hash())
  281. }
  282. }
  283. ancestors[block.Hash()] = block
  284. uncles.Add(block.Hash())
  285. for i, uncle := range block.Uncles() {
  286. hash := uncle.Hash()
  287. if uncles.Has(hash) {
  288. // Error not unique
  289. return UncleError("uncle[%d](%x) not unique", i, hash[:4])
  290. }
  291. uncles.Add(hash)
  292. if ancestors[hash] != nil {
  293. branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
  294. for h := range ancestors {
  295. branch += fmt.Sprintf(" O - %x\n |\n", h)
  296. }
  297. glog.Infoln(branch)
  298. return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
  299. }
  300. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() {
  301. return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
  302. }
  303. if err := ValidateHeader(sm.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil {
  304. return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
  305. }
  306. }
  307. return nil
  308. }
  309. // GetBlockReceipts returns the receipts beloniging to the block hash
  310. func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
  311. if block := sm.BlockChain().GetBlock(bhash); block != nil {
  312. return GetBlockReceipts(sm.chainDb, block.Hash())
  313. }
  314. return nil
  315. }
  316. // GetLogs returns the logs of the given block. This method is using a two step approach
  317. // where it tries to get it from the (updated) method which gets them from the receipts or
  318. // the depricated way by re-processing the block.
  319. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error) {
  320. receipts := GetBlockReceipts(sm.chainDb, block.Hash())
  321. // coalesce logs
  322. for _, receipt := range receipts {
  323. logs = append(logs, receipt.Logs()...)
  324. }
  325. return logs, nil
  326. }
  327. // See YP section 4.3.4. "Block Header Validity"
  328. // Validates a header. Returns an error if the header is invalid.
  329. func ValidateHeader(pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
  330. if big.NewInt(int64(len(header.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
  331. return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
  332. }
  333. if uncle {
  334. if header.Time.Cmp(common.MaxBig) == 1 {
  335. return BlockTSTooBigErr
  336. }
  337. } else {
  338. if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
  339. return BlockFutureErr
  340. }
  341. }
  342. if header.Time.Cmp(parent.Time) != 1 {
  343. return BlockEqualTSErr
  344. }
  345. expd := CalcDifficulty(header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
  346. if expd.Cmp(header.Difficulty) != 0 {
  347. return fmt.Errorf("Difficulty check failed for header %v, %v", header.Difficulty, expd)
  348. }
  349. a := new(big.Int).Set(parent.GasLimit)
  350. a = a.Sub(a, header.GasLimit)
  351. a.Abs(a)
  352. b := new(big.Int).Set(parent.GasLimit)
  353. b = b.Div(b, params.GasLimitBoundDivisor)
  354. if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(params.MinGasLimit) == -1) {
  355. return fmt.Errorf("GasLimit check failed for header %v (%v > %v)", header.GasLimit, a, b)
  356. }
  357. num := new(big.Int).Set(parent.Number)
  358. num.Sub(header.Number, num)
  359. if num.Cmp(big.NewInt(1)) != 0 {
  360. return BlockNumberErr
  361. }
  362. if checkPow {
  363. // Verify the nonce of the header. Return an error if it's not valid
  364. if !pow.Verify(types.NewBlockWithHeader(header)) {
  365. return ValidationError("Header's nonce is invalid (= %x)", header.Nonce)
  366. }
  367. }
  368. return nil
  369. }