block_processor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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/event"
  11. "github.com/ethereum/go-ethereum/logger"
  12. "github.com/ethereum/go-ethereum/logger/glog"
  13. "github.com/ethereum/go-ethereum/params"
  14. "github.com/ethereum/go-ethereum/pow"
  15. "github.com/ethereum/go-ethereum/rlp"
  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. var receiptsPre = []byte("receipts-")
  24. type BlockProcessor struct {
  25. db common.Database
  26. extraDb common.Database
  27. // Mutex for locking the block processor. Blocks can only be handled one at a time
  28. mutex sync.Mutex
  29. // Canonical block chain
  30. bc *ChainManager
  31. // non-persistent key/value memory storage
  32. mem map[string]*big.Int
  33. // Proof of work used for validating
  34. Pow pow.PoW
  35. events event.Subscription
  36. eventMux *event.TypeMux
  37. }
  38. func NewBlockProcessor(db, extra common.Database, pow pow.PoW, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
  39. sm := &BlockProcessor{
  40. db: db,
  41. extraDb: extra,
  42. mem: make(map[string]*big.Int),
  43. Pow: pow,
  44. bc: chainManager,
  45. eventMux: eventMux,
  46. }
  47. return sm
  48. }
  49. func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
  50. coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
  51. coinbase.SetGasPool(block.Header().GasLimit)
  52. // Process the transactions on to parent state
  53. receipts, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return receipts, nil
  58. }
  59. func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
  60. // If we are mining this block and validating we want to set the logs back to 0
  61. //statedb.EmptyLogs()
  62. cb := statedb.GetStateObject(coinbase.Address())
  63. _, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, block), tx, cb)
  64. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  65. // If the account is managed, remove the invalid nonce.
  66. //from, _ := tx.From()
  67. //self.bc.TxState().RemoveNonce(from, tx.Nonce())
  68. return nil, nil, err
  69. }
  70. // Update the state with pending changes
  71. statedb.Update()
  72. cumulative := new(big.Int).Set(usedGas.Add(usedGas, gas))
  73. receipt := types.NewReceipt(statedb.Root().Bytes(), cumulative)
  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. )
  95. for i, tx := range txs {
  96. statedb.StartRecord(tx.Hash(), block.Hash(), i)
  97. receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
  98. if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
  99. return nil, err
  100. }
  101. if err != nil {
  102. glog.V(logger.Core).Infoln("TX err:", err)
  103. }
  104. receipts = append(receipts, receipt)
  105. cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
  106. }
  107. if block.GasUsed().Cmp(totalUsedGas) != 0 {
  108. return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
  109. }
  110. if transientProcess {
  111. go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
  112. }
  113. return receipts, err
  114. }
  115. func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err error) {
  116. // Processing a blocks may never happen simultaneously
  117. sm.mutex.Lock()
  118. defer sm.mutex.Unlock()
  119. header := block.Header()
  120. if !sm.bc.HasBlock(header.ParentHash) {
  121. return nil, ParentError(header.ParentHash)
  122. }
  123. parent := sm.bc.GetBlock(header.ParentHash)
  124. if !sm.Pow.Verify(block) {
  125. return nil, ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  126. }
  127. return sm.processWithParent(block, parent)
  128. }
  129. // Process block will attempt to process the given block's transactions and applies them
  130. // on top of the block's parent state (given it exists) and will return wether it was
  131. // successful or not.
  132. func (sm *BlockProcessor) Process(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. header := block.Header()
  137. if sm.bc.HasBlock(header.Hash()) {
  138. return nil, &KnownBlockError{header.Number, header.Hash()}
  139. }
  140. if !sm.bc.HasBlock(header.ParentHash) {
  141. return nil, ParentError(header.ParentHash)
  142. }
  143. parent := sm.bc.GetBlock(header.ParentHash)
  144. return sm.processWithParent(block, parent)
  145. }
  146. func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs state.Logs, err error) {
  147. // Create a new state based on the parent's root (e.g., create copy)
  148. state := state.New(parent.Root(), sm.db)
  149. // Block validation
  150. if err = sm.ValidateHeader(block.Header(), parent.Header(), false); err != nil {
  151. return
  152. }
  153. // There can be at most two uncles
  154. if len(block.Uncles()) > 2 {
  155. return nil, ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(block.Uncles()))
  156. }
  157. receipts, err := sm.TransitionState(state, parent, block, false)
  158. if err != nil {
  159. return
  160. }
  161. header := block.Header()
  162. // Validate the received block's bloom with the one derived from the generated receipts.
  163. // For valid blocks this should always validate to true.
  164. rbloom := types.CreateBloom(receipts)
  165. if rbloom != header.Bloom {
  166. err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
  167. return
  168. }
  169. // The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
  170. // can be used by light clients to make sure they've received the correct Txs
  171. txSha := types.DeriveSha(block.Transactions())
  172. if txSha != header.TxHash {
  173. err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
  174. return
  175. }
  176. // Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
  177. receiptSha := types.DeriveSha(receipts)
  178. if receiptSha != header.ReceiptHash {
  179. err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
  180. return
  181. }
  182. // Verify UncleHash before running other uncle validations
  183. unclesSha := block.CalculateUnclesHash()
  184. if unclesSha != header.UncleHash {
  185. err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
  186. return
  187. }
  188. // Verify uncles
  189. if err = sm.VerifyUncles(state, block, parent); err != nil {
  190. return
  191. }
  192. // Accumulate static rewards; block reward, uncle's and uncle inclusion.
  193. AccumulateRewards(state, block)
  194. // Commit state objects/accounts to a temporary trie (does not save)
  195. // used to calculate the state root.
  196. state.Update()
  197. if header.Root != state.Root() {
  198. err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
  199. return
  200. }
  201. // store the receipts
  202. err = putReceipts(sm.extraDb, block.Hash(), receipts)
  203. if err != nil {
  204. return nil, err
  205. }
  206. // Sync the current block's state to the database
  207. state.Sync()
  208. // This puts transactions in a extra db for rpc
  209. for i, tx := range block.Transactions() {
  210. putTx(sm.extraDb, tx, block, uint64(i))
  211. }
  212. return state.Logs(), nil
  213. }
  214. // See YP section 4.3.4. "Block Header Validity"
  215. // Validates a block. Returns an error if the block is invalid.
  216. func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header, checkPow bool) error {
  217. if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
  218. return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
  219. }
  220. expd := CalcDifficulty(block, parent)
  221. if expd.Cmp(block.Difficulty) != 0 {
  222. return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
  223. }
  224. a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
  225. a.Abs(a)
  226. b := new(big.Int).Div(parent.GasLimit, params.GasLimitBoundDivisor)
  227. if !(a.Cmp(b) < 0) || (block.GasLimit.Cmp(params.MinGasLimit) == -1) {
  228. return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
  229. }
  230. if int64(block.Time) > time.Now().Unix() {
  231. return BlockFutureErr
  232. }
  233. if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
  234. return BlockNumberErr
  235. }
  236. if block.Time <= parent.Time {
  237. return BlockEqualTSErr //ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
  238. }
  239. if checkPow {
  240. // Verify the nonce of the block. Return an error if it's not valid
  241. if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
  242. return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
  243. }
  244. }
  245. return nil
  246. }
  247. func AccumulateRewards(statedb *state.StateDB, block *types.Block) {
  248. reward := new(big.Int).Set(BlockReward)
  249. for _, uncle := range block.Uncles() {
  250. num := new(big.Int).Add(big.NewInt(8), uncle.Number)
  251. num.Sub(num, block.Number())
  252. r := new(big.Int)
  253. r.Mul(BlockReward, num)
  254. r.Div(r, big.NewInt(8))
  255. statedb.AddBalance(uncle.Coinbase, r)
  256. reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
  257. }
  258. // Get the account associated with the coinbase
  259. statedb.AddBalance(block.Header().Coinbase, reward)
  260. }
  261. func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
  262. ancestors := set.New()
  263. uncles := set.New()
  264. ancestorHeaders := make(map[common.Hash]*types.Header)
  265. for _, ancestor := range sm.bc.GetAncestors(block, 7) {
  266. ancestorHeaders[ancestor.Hash()] = ancestor.Header()
  267. ancestors.Add(ancestor.Hash())
  268. // Include ancestors uncles in the uncle set. Uncles must be unique.
  269. for _, uncle := range ancestor.Uncles() {
  270. uncles.Add(uncle.Hash())
  271. }
  272. }
  273. uncles.Add(block.Hash())
  274. for i, uncle := range block.Uncles() {
  275. hash := uncle.Hash()
  276. if uncles.Has(hash) {
  277. // Error not unique
  278. return UncleError("uncle[%d](%x) not unique", i, hash[:4])
  279. }
  280. uncles.Add(hash)
  281. if ancestors.Has(hash) {
  282. branch := fmt.Sprintf(" O - %x\n |\n", block.Hash())
  283. ancestors.Each(func(item interface{}) bool {
  284. branch += fmt.Sprintf(" O - %x\n |\n", hash)
  285. return true
  286. })
  287. glog.Infoln(branch)
  288. return UncleError("uncle[%d](%x) is ancestor", i, hash[:4])
  289. }
  290. if !ancestors.Has(uncle.ParentHash) || uncle.ParentHash == parent.Hash() {
  291. return UncleError("uncle[%d](%x)'s parent is not ancestor (%x)", i, hash[:4], uncle.ParentHash[0:4])
  292. }
  293. if err := sm.ValidateHeader(uncle, ancestorHeaders[uncle.ParentHash], true); err != nil {
  294. return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, hash[:4], err))
  295. }
  296. }
  297. return nil
  298. }
  299. // GetBlockReceipts returns the receipts beloniging to the block hash
  300. func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) (receipts types.Receipts, err error) {
  301. return getBlockReceipts(sm.extraDb, bhash)
  302. }
  303. // GetLogs returns the logs of the given block. This method is using a two step approach
  304. // where it tries to get it from the (updated) method which gets them from the receipts or
  305. // the depricated way by re-processing the block.
  306. func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
  307. receipts, err := sm.GetBlockReceipts(block.Hash())
  308. if err == nil && len(receipts) > 0 {
  309. // coalesce logs
  310. for _, receipt := range receipts {
  311. logs = append(logs, receipt.Logs()...)
  312. }
  313. return
  314. }
  315. // TODO: remove backward compatibility
  316. var (
  317. parent = sm.bc.GetBlock(block.Header().ParentHash)
  318. state = state.New(parent.Root(), sm.db)
  319. )
  320. sm.TransitionState(state, parent, block, true)
  321. return state.Logs(), nil
  322. }
  323. func getBlockReceipts(db common.Database, bhash common.Hash) (receipts types.Receipts, err error) {
  324. var rdata []byte
  325. rdata, err = db.Get(append(receiptsPre, bhash[:]...))
  326. if err == nil {
  327. err = rlp.DecodeBytes(rdata, &receipts)
  328. }
  329. return
  330. }
  331. func putTx(db common.Database, tx *types.Transaction, block *types.Block, i uint64) {
  332. rlpEnc, err := rlp.EncodeToBytes(tx)
  333. if err != nil {
  334. glog.V(logger.Debug).Infoln("Failed encoding tx", err)
  335. return
  336. }
  337. db.Put(tx.Hash().Bytes(), rlpEnc)
  338. var txExtra struct {
  339. BlockHash common.Hash
  340. BlockIndex uint64
  341. Index uint64
  342. }
  343. txExtra.BlockHash = block.Hash()
  344. txExtra.BlockIndex = block.NumberU64()
  345. txExtra.Index = i
  346. rlpMeta, err := rlp.EncodeToBytes(txExtra)
  347. if err != nil {
  348. glog.V(logger.Debug).Infoln("Failed encoding tx meta data", err)
  349. return
  350. }
  351. db.Put(append(tx.Hash().Bytes(), 0x0001), rlpMeta)
  352. }
  353. func putReceipts(db common.Database, hash common.Hash, receipts types.Receipts) error {
  354. storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
  355. for i, receipt := range receipts {
  356. storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
  357. }
  358. bytes, err := rlp.EncodeToBytes(storageReceipts)
  359. if err != nil {
  360. return err
  361. }
  362. db.Put(append(receiptsPre, hash[:]...), bytes)
  363. return nil
  364. }