block_processor.go 13 KB

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