block_processor.go 13 KB

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