block_processor.go 13 KB

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