block_processor.go 12 KB

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