state_processor.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "errors"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/state"
  22. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/core/vm"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. )
  28. var (
  29. big8 = big.NewInt(8)
  30. big32 = big.NewInt(32)
  31. blockedCodeHashErr = errors.New("core: blocked code-hash found during execution")
  32. // DAO attack chain rupture mechanism
  33. DAOSoftFork bool // Flag whether to vote for DAO rupture
  34. ruptureBlock = uint64(1775000) // Block number of the voted soft fork
  35. ruptureTarget = big.NewInt(3141592) // Gas target (hard) for miners voting to fork
  36. ruptureThreshold = big.NewInt(4000000) // Gas threshold for passing a fork vote
  37. ruptureGasCache = make(map[common.Hash]*big.Int) // Amount of gas in the point of rupture
  38. ruptureCodeHashes = map[common.Hash]struct{}{
  39. common.HexToHash("6a5d24750f78441e56fec050dc52fe8e911976485b7472faac7464a176a67caa"): struct{}{},
  40. }
  41. ruptureWhitelist = map[common.Address]bool{
  42. common.HexToAddress("Da4a4626d3E16e094De3225A751aAb7128e96526"): true, // multisig
  43. common.HexToAddress("2ba9D006C1D72E67A70b5526Fc6b4b0C0fd6D334"): true, // attack contract
  44. }
  45. ruptureCacheLimit = 30000 // 1 epoch, 0.5 per possible fork
  46. )
  47. // StateProcessor is a basic Processor, which takes care of transitioning
  48. // state from one point to another.
  49. //
  50. // StateProcessor implements Processor.
  51. type StateProcessor struct {
  52. config *ChainConfig
  53. bc *BlockChain
  54. }
  55. // NewStateProcessor initialises a new StateProcessor.
  56. func NewStateProcessor(config *ChainConfig, bc *BlockChain) *StateProcessor {
  57. return &StateProcessor{
  58. config: config,
  59. bc: bc,
  60. }
  61. }
  62. // Process processes the state changes according to the Ethereum rules by running
  63. // the transaction messages using the statedb and applying any rewards to both
  64. // the processor (coinbase) and any included uncles.
  65. //
  66. // Process returns the receipts and logs accumulated during the process and
  67. // returns the amount of gas that was used in the process. If any of the
  68. // transactions failed to execute due to insufficient gas it will return an error.
  69. func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, vm.Logs, *big.Int, error) {
  70. var (
  71. receipts types.Receipts
  72. totalUsedGas = big.NewInt(0)
  73. err error
  74. header = block.Header()
  75. allLogs vm.Logs
  76. gp = new(GasPool).AddGas(block.GasLimit())
  77. )
  78. for i, tx := range block.Transactions() {
  79. statedb.StartRecord(tx.Hash(), block.Hash(), i)
  80. receipt, logs, _, err := ApplyTransaction(p.config, p.bc, gp, statedb, header, tx, totalUsedGas, cfg)
  81. if err != nil {
  82. return nil, nil, totalUsedGas, err
  83. }
  84. receipts = append(receipts, receipt)
  85. allLogs = append(allLogs, logs...)
  86. }
  87. AccumulateRewards(statedb, header, block.Uncles())
  88. return receipts, allLogs, totalUsedGas, err
  89. }
  90. // ApplyTransaction attempts to apply a transaction to the given state database
  91. // and uses the input parameters for its environment.
  92. //
  93. // ApplyTransactions returns the generated receipts and vm logs during the
  94. // execution of the state transition phase.
  95. func ApplyTransaction(config *ChainConfig, bc *BlockChain, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *big.Int, cfg vm.Config) (*types.Receipt, vm.Logs, *big.Int, error) {
  96. env := NewEnv(statedb, config, bc, tx, header, cfg)
  97. _, gas, err := ApplyMessage(env, tx, gp)
  98. if err != nil {
  99. return nil, nil, nil, err
  100. }
  101. // Check whether the DAO needs to be blocked or not
  102. if bc != nil { // Test chain maker uses nil to construct the potential chain
  103. blockRuptureCodes := false
  104. if number := header.Number.Uint64(); number >= ruptureBlock {
  105. // We're past the rupture point, find the vote result on this chain and apply it
  106. ancestry := []common.Hash{header.Hash(), header.ParentHash}
  107. for _, ok := ruptureGasCache[ancestry[len(ancestry)-1]]; !ok && number >= ruptureBlock+uint64(len(ancestry)); {
  108. ancestry = append(ancestry, bc.GetHeaderByHash(ancestry[len(ancestry)-1]).ParentHash)
  109. }
  110. decider := ancestry[len(ancestry)-1]
  111. vote, ok := ruptureGasCache[decider]
  112. if !ok {
  113. // We've reached the rupture point, retrieve the vote
  114. vote = bc.GetHeaderByHash(decider).GasLimit
  115. ruptureGasCache[decider] = vote
  116. }
  117. // Cache the vote result for all ancestors and check the DAO
  118. for _, hash := range ancestry {
  119. ruptureGasCache[hash] = vote
  120. }
  121. if ruptureGasCache[ancestry[0]].Cmp(ruptureThreshold) <= 0 {
  122. blockRuptureCodes = true
  123. }
  124. // Make sure we don't OOM long run due to too many votes caching up
  125. for len(ruptureGasCache) > ruptureCacheLimit {
  126. for hash, _ := range ruptureGasCache {
  127. delete(ruptureGasCache, hash)
  128. break
  129. }
  130. }
  131. }
  132. // Verify if the DAO soft fork kicks in
  133. if blockRuptureCodes {
  134. if recipient := tx.To(); recipient == nil || !ruptureWhitelist[*recipient] {
  135. for hash, _ := range env.GetMarkedCodeHashes() {
  136. if _, blocked := ruptureCodeHashes[hash]; blocked {
  137. return nil, nil, nil, blockedCodeHashErr
  138. }
  139. }
  140. }
  141. }
  142. }
  143. // Update the state with pending changes
  144. usedGas.Add(usedGas, gas)
  145. receipt := types.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
  146. receipt.TxHash = tx.Hash()
  147. receipt.GasUsed = new(big.Int).Set(gas)
  148. if MessageCreatesContract(tx) {
  149. from, _ := tx.From()
  150. receipt.ContractAddress = crypto.CreateAddress(from, tx.Nonce())
  151. }
  152. logs := statedb.GetLogs(tx.Hash())
  153. receipt.Logs = logs
  154. receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
  155. glog.V(logger.Debug).Infoln(receipt)
  156. return receipt, logs, gas, err
  157. }
  158. // AccumulateRewards credits the coinbase of the given block with the
  159. // mining reward. The total reward consists of the static block reward
  160. // and rewards for included uncles. The coinbase of each uncle block is
  161. // also rewarded.
  162. func AccumulateRewards(statedb *state.StateDB, header *types.Header, uncles []*types.Header) {
  163. reward := new(big.Int).Set(BlockReward)
  164. r := new(big.Int)
  165. for _, uncle := range uncles {
  166. r.Add(uncle.Number, big8)
  167. r.Sub(r, header.Number)
  168. r.Mul(r, BlockReward)
  169. r.Div(r, big8)
  170. statedb.AddBalance(uncle.Coinbase, r)
  171. r.Div(BlockReward, big32)
  172. reward.Add(reward, r)
  173. }
  174. statedb.AddBalance(header.Coinbase, reward)
  175. }