block_processor.go 13 KB

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