block_processor.go 12 KB

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