block_processor.go 14 KB

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