block_processor.go 13 KB

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