block_processor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. // TODO: type GasPool big.Int
  54. //
  55. // GasPool is implemented by state.StateObject. This is a historical
  56. // coincidence. Gas tracking should move out of StateObject.
  57. // GasPool tracks the amount of gas available during
  58. // execution of the transactions in a block.
  59. type GasPool interface {
  60. AddGas(gas, price *big.Int)
  61. SubGas(gas, price *big.Int) error
  62. }
  63. func NewBlockProcessor(db ethdb.Database, pow pow.PoW, blockchain *BlockChain, eventMux *event.TypeMux) *BlockProcessor {
  64. sm := &BlockProcessor{
  65. chainDb: db,
  66. mem: make(map[string]*big.Int),
  67. Pow: pow,
  68. bc: blockchain,
  69. eventMux: eventMux,
  70. }
  71. return sm
  72. }
  73. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  74. gp := statedb.GetOrNewStateObject(block.Coinbase())
  75. gp.SetGasLimit(block.GasLimit())
  76. // Process the transactions on to parent state
  77. receipts, err = sm.ApplyTransactions(gp, statedb, block, block.Transactions(), transientProcess)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return receipts, nil
  82. }
  83. 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) {
  84. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, header), tx, gp)
  85. if err != nil {
  86. return nil, nil, err
  87. }
  88. // Update the state with pending changes
  89. usedGas.Add(usedGas, gas)
  90. receipt := types.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
  91. receipt.TxHash = tx.Hash()
  92. receipt.GasUsed = new(big.Int).Set(gas)
  93. if MessageCreatesContract(tx) {
  94. from, _ := tx.From()
  95. receipt.ContractAddress = crypto.CreateAddress(from, tx.Nonce())
  96. }
  97. logs := statedb.GetLogs(tx.Hash())
  98. receipt.Logs = logs
  99. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  100. glog.V(logger.Debug).Infoln(receipt)
  101. // Notify all subscribers
  102. if !transientProcess {
  103. go self.eventMux.Post(TxPostEvent{tx})
  104. go self.eventMux.Post(logs)
  105. }
  106. return receipt, gas, err
  107. }
  108. func (self *BlockProcessor) BlockChain() *BlockChain {
  109. return self.bc
  110. }
  111. func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
  112. var (
  113. receipts types.Receipts
  114. totalUsedGas = big.NewInt(0)
  115. err error
  116. cumulativeSum = new(big.Int)
  117. header = block.Header()
  118. )
  119. for i, tx := range txs {
  120. statedb.StartRecord(tx.Hash(), block.Hash(), i)
  121. receipt, txGas, err := self.ApplyTransaction(gp, statedb, header, tx, totalUsedGas, transientProcess)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if err != nil {
  126. glog.V(logger.Core).Infoln("TX err:", err)
  127. }
  128. receipts = append(receipts, receipt)
  129. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  130. }
  131. if block.GasUsed().Cmp(totalUsedGas) != 0 {
  132. return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
  133. }
  134. if transientProcess {
  135. go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
  136. }
  137. return receipts, err
  138. }
  139. func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs vm.Logs, err error) {
  140. // Processing a blocks may never happen simultaneously
  141. sm.mutex.Lock()
  142. defer sm.mutex.Unlock()
  143. if !sm.bc.HasBlock(block.ParentHash()) {
  144. return nil, ParentError(block.ParentHash())
  145. }
  146. parent := sm.bc.GetBlock(block.ParentHash())
  147. // FIXME Change to full header validation. See #1225
  148. errch := make(chan bool)
  149. go func() { errch <- sm.Pow.Verify(block) }()
  150. logs, _, err = sm.processWithParent(block, parent)
  151. if !<-errch {
  152. return nil, ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  153. }
  154. return logs, err
  155. }
  156. // Process block will attempt to process the given block's transactions and applies them
  157. // on top of the block's parent state (given it exists) and will return wether it was
  158. // successful or not.
  159. func (sm *BlockProcessor) Process(block *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
  160. // Processing a blocks may never happen simultaneously
  161. sm.mutex.Lock()
  162. defer sm.mutex.Unlock()
  163. if sm.bc.HasBlock(block.Hash()) {
  164. if _, err := state.New(block.Root(), sm.chainDb); err == nil {
  165. return nil, nil, &KnownBlockError{block.Number(), block.Hash()}
  166. }
  167. }
  168. if parent := sm.bc.GetBlock(block.ParentHash()); parent != nil {
  169. if _, err := state.New(parent.Root(), sm.chainDb); err == nil {
  170. return sm.processWithParent(block, parent)
  171. }
  172. }
  173. return nil, nil, ParentError(block.ParentHash())
  174. }
  175. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs vm.Logs, receipts types.Receipts, err error) {
  176. // Create a new state based on the parent's root (e.g., create copy)
  177. state, err := state.New(parent.Root(), sm.chainDb)
  178. if err != nil {
  179. return nil, nil, err
  180. }
  181. header := block.Header()
  182. uncles := block.Uncles()
  183. txs := block.Transactions()
  184. // Block validation
  185. if err = ValidateHeader(sm.Pow, header, parent.Header(), false, false); err != nil {
  186. return
  187. }
  188. // There can be at most two uncles
  189. if len(uncles) > 2 {
  190. return nil, nil, ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(uncles))
  191. }
  192. receipts, err = sm.TransitionState(state, parent, block, false)
  193. if err != nil {
  194. return
  195. }
  196. // Validate the received block's bloom with the one derived from the generated receipts.
  197. // For valid blocks this should always validate to true.
  198. rbloom := types.CreateBloom(receipts)
  199. if rbloom != header.Bloom {
  200. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  201. return
  202. }
  203. // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
  204. // can be used by light clients to make sure they've received the correct Txs
  205. txSha := types.DeriveSha(txs)
  206. if txSha != header.TxHash {
  207. err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
  208. return
  209. }
  210. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  211. receiptSha := types.DeriveSha(receipts)
  212. if receiptSha != header.ReceiptHash {
  213. err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
  214. return
  215. }
  216. // Verify UncleHash before running other uncle validations
  217. unclesSha := types.CalcUncleHash(uncles)
  218. if unclesSha != header.UncleHash {
  219. err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
  220. return
  221. }
  222. // Verify uncles
  223. if err = sm.VerifyUncles(state, block, parent); err != nil {
  224. return
  225. }
  226. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  227. AccumulateRewards(state, header, uncles)
  228. // Commit state objects/accounts to a database batch and calculate
  229. // the state root. The database is not modified if the root
  230. // doesn't match.
  231. root, batch := state.CommitBatch()
  232. if header.Root != root {
  233. return nil, nil, fmt.Errorf("invalid merkle root: header=%x computed=%x", header.Root, root)
  234. }
  235. // Execute the database writes.
  236. batch.Write()
  237. return state.Logs(), receipts, nil
  238. }
  239. var (
  240. big8 = big.NewInt(8)
  241. big32 = big.NewInt(32)
  242. )
  243. // AccumulateRewards credits the coinbase of the given block with the
  244. // mining reward. The total reward consists of the static block reward
  245. // and rewards for included uncles. The coinbase of each uncle block is
  246. // also rewarded.
  247. func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*types.Header) {
  248. reward := new(big.Int).Set(BlockReward)
  249. r := new(big.Int)
  250. for _, uncle := range uncles {
  251. r.Add(uncle.Number, big8)
  252. r.Sub(r, header.Number)
  253. r.Mul(r, BlockReward)
  254. r.Div(r, big8)
  255. statedb.AddBalance(uncle.Coinbase, r)
  256. r.Div(BlockReward, big32)
  257. reward.Add(reward, r)
  258. }
  259. statedb.AddBalance(header.Coinbase, reward)
  260. }
  261. func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
  262. uncles := set.New()
  263. ancestors := make(map[common.Hash]*types.Block)
  264. for _, ancestor := range sm.bc.GetBlocksFromHash(block.ParentHash(), 7) {
  265. ancestors[ancestor.Hash()] = ancestor
  266. // Include ancestors uncles in the uncle set. Uncles must be unique.
  267. for _, uncle := range ancestor.Uncles() {
  268. uncles.Add(uncle.Hash())
  269. }
  270. }
  271. ancestors[block.Hash()] = block
  272. uncles.Add(block.Hash())
  273. for i, uncle := range block.Uncles() {
  274. hash := uncle.Hash()
  275. if uncles.Has(hash) {
  276. // Error not unique
  277. return UncleError("uncle[%d](%x) not unique", i, hash[:4])
  278. }
  279. uncles.Add(hash)
  280. if ancestors[hash] != nil {
  281. branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
  282. for h := range ancestors {
  283. branch += fmt.Sprintf(" O - %x\n |\n", h)
  284. }
  285. glog.Infoln(branch)
  286. return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
  287. }
  288. if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == parent.Hash() {
  289. return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
  290. }
  291. if err := ValidateHeader(sm.Pow, uncle, ancestors[uncle.ParentHash].Header(), true, true); err != nil {
  292. return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
  293. }
  294. }
  295. return nil
  296. }
  297. // GetBlockReceipts returns the receipts beloniging to the block hash
  298. func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
  299. if block := sm.BlockChain().GetBlock(bhash); block != nil {
  300. return GetBlockReceipts(sm.chainDb, block.Hash())
  301. }
  302. return nil
  303. }
  304. // GetLogs returns the logs of the given block. This method is using a two step approach
  305. // where it tries to get it from the (updated) method which gets them from the receipts or
  306. // the depricated way by re-processing the block.
  307. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs vm.Logs, err error) {
  308. receipts := GetBlockReceipts(sm.chainDb, block.Hash())
  309. // coalesce logs
  310. for _, receipt := range receipts {
  311. logs = append(logs, receipt.Logs...)
  312. }
  313. return logs, nil
  314. }
  315. // ValidateHeader verifies the validity of a header, relying on the database and
  316. // POW behind the block processor.
  317. func (sm *BlockProcessor) ValidateHeader(header *types.Header, checkPow, uncle bool) error {
  318. // Short circuit if the header's already known or its parent missing
  319. if sm.bc.HasHeader(header.Hash()) {
  320. return nil
  321. }
  322. if parent := sm.bc.GetHeader(header.ParentHash); parent == nil {
  323. return ParentError(header.ParentHash)
  324. } else {
  325. return ValidateHeader(sm.Pow, header, parent, checkPow, uncle)
  326. }
  327. }
  328. // ValidateHeaderWithParent verifies the validity of a header, relying on the database and
  329. // POW behind the block processor.
  330. func (sm *BlockProcessor) ValidateHeaderWithParent(header, parent *types.Header, checkPow, uncle bool) error {
  331. if sm.bc.HasHeader(header.Hash()) {
  332. return nil
  333. }
  334. return ValidateHeader(sm.Pow, header, parent, checkPow, uncle)
  335. }
  336. // See YP section 4.3.4. "Block Header Validity"
  337. // Validates a header. Returns an error if the header is invalid.
  338. func ValidateHeader(pow pow.PoW, header *types.Header, parent *types.Header, checkPow, uncle bool) error {
  339. if big.NewInt(int64(len(header.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
  340. return fmt.Errorf("Header extra data too long (%d)", len(header.Extra))
  341. }
  342. if uncle {
  343. if header.Time.Cmp(common.MaxBig) == 1 {
  344. return BlockTSTooBigErr
  345. }
  346. } else {
  347. if header.Time.Cmp(big.NewInt(time.Now().Unix())) == 1 {
  348. return BlockFutureErr
  349. }
  350. }
  351. if header.Time.Cmp(parent.Time) != 1 {
  352. return BlockEqualTSErr
  353. }
  354. expd := CalcDifficulty(header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
  355. if expd.Cmp(header.Difficulty) != 0 {
  356. return fmt.Errorf("Difficulty check failed for header %v, %v", header.Difficulty, expd)
  357. }
  358. a := new(big.Int).Set(parent.GasLimit)
  359. a = a.Sub(a, header.GasLimit)
  360. a.Abs(a)
  361. b := new(big.Int).Set(parent.GasLimit)
  362. b = b.Div(b, params.GasLimitBoundDivisor)
  363. if !(a.Cmp(b) < 0) || (header.GasLimit.Cmp(params.MinGasLimit) == -1) {
  364. return fmt.Errorf("GasLimit check failed for header %v (%v > %v)", header.GasLimit, a, b)
  365. }
  366. num := new(big.Int).Set(parent.Number)
  367. num.Sub(header.Number, num)
  368. if num.Cmp(big.NewInt(1)) != 0 {
  369. return BlockNumberErr
  370. }
  371. if checkPow {
  372. // Verify the nonce of the header. Return an error if it's not valid
  373. if !pow.Verify(types.NewBlockWithHeader(header)) {
  374. return &BlockNonceErr{Hash: header.Hash(), Number: header.Number, Nonce: header.Nonce.Uint64()}
  375. }
  376. }
  377. return nil
  378. }