This commit is contained in:
kiel barry 2018-05-08 17:17:37 +00:00 committed by GitHub
commit 410dc37ff2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 312 additions and 311 deletions

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Provides support for dealing with EVM assembly instructions (e.g., disassembling them). // Package asm provides support for dealing with EVM assembly instructions (e.g., disassembling them).
package asm package asm
import ( import (
@ -34,14 +34,14 @@ type instructionIterator struct {
started bool started bool
} }
// Create a new instruction iterator. // NewInstructionIterator creates a new instruction iterator.
func NewInstructionIterator(code []byte) *instructionIterator { func NewInstructionIterator(code []byte) *instructionIterator {
it := new(instructionIterator) it := new(instructionIterator)
it.code = code it.code = code
return it return it
} }
// Returns true if there is a next instruction and moves on. // Next returns true if there is a next instruction and moves on.
func (it *instructionIterator) Next() bool { func (it *instructionIterator) Next() bool {
if it.error != nil || uint64(len(it.code)) <= it.pc { if it.error != nil || uint64(len(it.code)) <= it.pc {
// We previously reached an error or the end. // We previously reached an error or the end.
@ -99,7 +99,7 @@ func (it *instructionIterator) Arg() []byte {
return it.arg return it.arg
} }
// Pretty-print all disassembled EVM instructions to stdout. // PrintDisassembled pretty-prints all disassembled EVM instructions to stdout.
func PrintDisassembled(code string) error { func PrintDisassembled(code string) error {
script, err := hex.DecodeString(code) script, err := hex.DecodeString(code)
if err != nil { if err != nil {
@ -117,7 +117,7 @@ func PrintDisassembled(code string) error {
return it.Error() return it.Error()
} }
// Return all disassembled EVM instructions in human-readable format. // Disassemble returns all disassembled EVM instructions in human-readable format.
func Disassemble(script []byte) ([]string, error) { func Disassemble(script []byte) ([]string, error) {
instrs := make([]string, 0) instrs := make([]string, 0)

View file

@ -39,7 +39,7 @@ type Compiler struct {
debug bool debug bool
} }
// newCompiler returns a new allocated compiler. // NewCompiler returns a new allocated compiler.
func NewCompiler(debug bool) *Compiler { func NewCompiler(debug bool) *Compiler {
return &Compiler{ return &Compiler{
labels: make(map[string]int), labels: make(map[string]int),

View file

@ -93,7 +93,7 @@ type lexer struct {
debug bool // flag for triggering debug output debug bool // flag for triggering debug output
} }
// lex lexes the program by name with the given source. It returns a // Lex lexes the program by name with the given source. It returns a
// channel on which the tokens are delivered. // channel on which the tokens are delivered.
func Lex(name string, source []byte, debug bool) <-chan token { func Lex(name string, source []byte, debug bool) <-chan token {
ch := make(chan token) ch := make(chan token)

View file

@ -48,8 +48,7 @@ import (
var ( var (
blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil) blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
ErrNoGenesis = errors.New("Genesis not found in chain")
ErrNoGenesis = errors.New("Genesis not found in chain")
) )
const ( const (

View file

@ -15,6 +15,7 @@ import (
var _ = (*genesisSpecMarshaling)(nil) var _ = (*genesisSpecMarshaling)(nil)
//MarshalJSON assigns receiver values to the Genesis struct and returns its JSON encoding.
func (g Genesis) MarshalJSON() ([]byte, error) { func (g Genesis) MarshalJSON() ([]byte, error) {
type Genesis struct { type Genesis struct {
Config *params.ChainConfig `json:"config"` Config *params.ChainConfig `json:"config"`
@ -51,6 +52,7 @@ func (g Genesis) MarshalJSON() ([]byte, error) {
return json.Marshal(&enc) return json.Marshal(&enc)
} }
//UnmarshalJSON parses JSON-encoded input and assigns resulting values to the receiver.
func (g *Genesis) UnmarshalJSON(input []byte) error { func (g *Genesis) UnmarshalJSON(input []byte) error {
type Genesis struct { type Genesis struct {
Config *params.ChainConfig `json:"config"` Config *params.ChainConfig `json:"config"`

View file

@ -14,6 +14,7 @@ import (
var _ = (*genesisAccountMarshaling)(nil) var _ = (*genesisAccountMarshaling)(nil)
//MarshalJSON returns the marshalled receiver.
func (g GenesisAccount) MarshalJSON() ([]byte, error) { func (g GenesisAccount) MarshalJSON() ([]byte, error) {
type GenesisAccount struct { type GenesisAccount struct {
Code hexutil.Bytes `json:"code,omitempty"` Code hexutil.Bytes `json:"code,omitempty"`
@ -36,6 +37,7 @@ func (g GenesisAccount) MarshalJSON() ([]byte, error) {
return json.Marshal(&enc) return json.Marshal(&enc)
} }
//UnmarshalJSON parses JSON-encoded input and assigns resulting values to the receiver.
func (g *GenesisAccount) UnmarshalJSON(input []byte) error { func (g *GenesisAccount) UnmarshalJSON(input []byte) error {
type GenesisAccount struct { type GenesisAccount struct {
Code *hexutil.Bytes `json:"code,omitempty"` Code *hexutil.Bytes `json:"code,omitempty"`

View file

@ -26,7 +26,7 @@ import (
lru "github.com/hashicorp/golang-lru" lru "github.com/hashicorp/golang-lru"
) )
// Trie cache generation limit after which to evict trie nodes from memory. // MaxTrieCacheGen sets trie cache generation limit after which to evict trie nodes from memory.
var MaxTrieCacheGen = uint16(120) var MaxTrieCacheGen = uint16(120)
const ( const (

View file

@ -39,15 +39,15 @@ type Dump struct {
Accounts map[string]DumpAccount `json:"accounts"` Accounts map[string]DumpAccount `json:"accounts"`
} }
func (self *StateDB) RawDump() Dump { func (s *StateDB) RawDump() Dump {
dump := Dump{ dump := Dump{
Root: fmt.Sprintf("%x", self.trie.Hash()), Root: fmt.Sprintf("%x", s.trie.Hash()),
Accounts: make(map[string]DumpAccount), Accounts: make(map[string]DumpAccount),
} }
it := trie.NewIterator(self.trie.NodeIterator(nil)) it := trie.NewIterator(s.trie.NodeIterator(nil))
for it.Next() { for it.Next() {
addr := self.trie.GetKey(it.Key) addr := s.trie.GetKey(it.Key)
var data Account var data Account
if err := rlp.DecodeBytes(it.Value, &data); err != nil { if err := rlp.DecodeBytes(it.Value, &data); err != nil {
panic(err) panic(err)
@ -59,20 +59,20 @@ func (self *StateDB) RawDump() Dump {
Nonce: data.Nonce, Nonce: data.Nonce,
Root: common.Bytes2Hex(data.Root[:]), Root: common.Bytes2Hex(data.Root[:]),
CodeHash: common.Bytes2Hex(data.CodeHash), CodeHash: common.Bytes2Hex(data.CodeHash),
Code: common.Bytes2Hex(obj.Code(self.db)), Code: common.Bytes2Hex(obj.Code(s.db)),
Storage: make(map[string]string), Storage: make(map[string]string),
} }
storageIt := trie.NewIterator(obj.getTrie(self.db).NodeIterator(nil)) storageIt := trie.NewIterator(obj.getTrie(s.db).NodeIterator(nil))
for storageIt.Next() { for storageIt.Next() {
account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value) account.Storage[common.Bytes2Hex(s.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value)
} }
dump.Accounts[common.Bytes2Hex(addr)] = account dump.Accounts[common.Bytes2Hex(addr)] = account
} }
return dump return dump
} }
func (self *StateDB) Dump() []byte { func (s *StateDB) Dump() []byte {
json, err := json.MarshalIndent(self.RawDump(), "", " ") json, err := json.MarshalIndent(s.RawDump(), "", " ")
if err != nil { if err != nil {
fmt.Println("dump err", err) fmt.Println("dump err", err)
} }

View file

@ -36,7 +36,7 @@ type ManagedState struct {
accounts map[common.Address]*account accounts map[common.Address]*account
} }
// ManagedState returns a new managed state with the statedb as it's backing layer // ManageState returns a new managed state with the statedb as it's backing layer
func ManageState(statedb *StateDB) *ManagedState { func ManageState(statedb *StateDB) *ManagedState {
return &ManagedState{ return &ManagedState{
StateDB: statedb.Copy(), StateDB: statedb.Copy(),
@ -92,9 +92,8 @@ func (ms *ManagedState) GetNonce(addr common.Address) uint64 {
if ms.hasAccount(addr) { if ms.hasAccount(addr) {
account := ms.getAccount(addr) account := ms.getAccount(addr)
return uint64(len(account.nonces)) + account.nstart return uint64(len(account.nonces)) + account.nstart
} else {
return ms.StateDB.GetNonce(addr)
} }
return ms.StateDB.GetNonce(addr)
} }
// SetNonce sets the new canonical nonce for the managed state // SetNonce sets the new canonical nonce for the managed state

View file

@ -31,23 +31,23 @@ var emptyCodeHash = crypto.Keccak256(nil)
type Code []byte type Code []byte
func (self Code) String() string { func (c Code) String() string {
return string(self) //strings.Join(Disassemble(self), " ") return string(c) //strings.Join(Disassemble(self), " ")
} }
type Storage map[common.Hash]common.Hash type Storage map[common.Hash]common.Hash
func (self Storage) String() (str string) { func (st Storage) String() (str string) {
for key, value := range self { for key, value := range st {
str += fmt.Sprintf("%X : %X\n", key, value) str += fmt.Sprintf("%X : %X\n", key, value)
} }
return return
} }
func (self Storage) Copy() Storage { func (st Storage) Copy() Storage {
cpy := make(Storage) cpy := make(Storage)
for key, value := range self { for key, value := range st {
cpy[key] = value cpy[key] = value
} }
@ -89,8 +89,8 @@ type stateObject struct {
} }
// empty returns whether the account is considered empty. // empty returns whether the account is considered empty.
func (s *stateObject) empty() bool { func (so *stateObject) empty() bool {
return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) return so.data.Nonce == 0 && so.data.Balance.Sign() == 0 && bytes.Equal(so.data.CodeHash, emptyCodeHash)
} }
// Account is the Ethereum consensus representation of accounts. // Account is the Ethereum consensus representation of accounts.
@ -121,168 +121,168 @@ func newObject(db *StateDB, address common.Address, data Account) *stateObject {
} }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
func (c *stateObject) EncodeRLP(w io.Writer) error { func (so *stateObject) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, c.data) return rlp.Encode(w, so.data)
} }
// setError remembers the first non-nil error it is called with. // setError remembers the first non-nil error it is called with.
func (self *stateObject) setError(err error) { func (so *stateObject) setError(err error) {
if self.dbErr == nil { if so.dbErr == nil {
self.dbErr = err so.dbErr = err
} }
} }
func (self *stateObject) markSuicided() { func (so *stateObject) markSuicided() {
self.suicided = true so.suicided = true
} }
func (c *stateObject) touch() { func (so *stateObject) touch() {
c.db.journal.append(touchChange{ so.db.journal.append(touchChange{
account: &c.address, account: &so.address,
}) })
if c.address == ripemd { if so.address == ripemd {
// Explicitly put it in the dirty-cache, which is otherwise generated from // Explicitly put it in the dirty-cache, which is otherwise generated from
// flattened journals. // flattened journals.
c.db.journal.dirty(c.address) so.db.journal.dirty(so.address)
} }
} }
func (c *stateObject) getTrie(db Database) Trie { func (so *stateObject) getTrie(db Database) Trie {
if c.trie == nil { if so.trie == nil {
var err error var err error
c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root) so.trie, err = db.OpenStorageTrie(so.addrHash, so.data.Root)
if err != nil { if err != nil {
c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{}) so.trie, _ = db.OpenStorageTrie(so.addrHash, common.Hash{})
c.setError(fmt.Errorf("can't create storage trie: %v", err)) so.setError(fmt.Errorf("can't create storage trie: %v", err))
} }
} }
return c.trie return so.trie
} }
// GetState returns a value in account storage. // GetState returns a value in account storage.
func (self *stateObject) GetState(db Database, key common.Hash) common.Hash { func (so *stateObject) GetState(db Database, key common.Hash) common.Hash {
value, exists := self.cachedStorage[key] value, exists := so.cachedStorage[key]
if exists { if exists {
return value return value
} }
// Load from DB in case it is missing. // Load from DB in case it is missing.
enc, err := self.getTrie(db).TryGet(key[:]) enc, err := so.getTrie(db).TryGet(key[:])
if err != nil { if err != nil {
self.setError(err) so.setError(err)
return common.Hash{} return common.Hash{}
} }
if len(enc) > 0 { if len(enc) > 0 {
_, content, _, err := rlp.Split(enc) _, content, _, err := rlp.Split(enc)
if err != nil { if err != nil {
self.setError(err) so.setError(err)
} }
value.SetBytes(content) value.SetBytes(content)
} }
self.cachedStorage[key] = value so.cachedStorage[key] = value
return value return value
} }
// SetState updates a value in account storage. // SetState updates a value in account storage.
func (self *stateObject) SetState(db Database, key, value common.Hash) { func (so *stateObject) SetState(db Database, key, value common.Hash) {
self.db.journal.append(storageChange{ so.db.journal.append(storageChange{
account: &self.address, account: &so.address,
key: key, key: key,
prevalue: self.GetState(db, key), prevalue: so.GetState(db, key),
}) })
self.setState(key, value) so.setState(key, value)
} }
func (self *stateObject) setState(key, value common.Hash) { func (so *stateObject) setState(key, value common.Hash) {
self.cachedStorage[key] = value so.cachedStorage[key] = value
self.dirtyStorage[key] = value so.dirtyStorage[key] = value
} }
// updateTrie writes cached storage modifications into the object's storage trie. // updateTrie writes cached storage modifications into the object's storage trie.
func (self *stateObject) updateTrie(db Database) Trie { func (so *stateObject) updateTrie(db Database) Trie {
tr := self.getTrie(db) tr := so.getTrie(db)
for key, value := range self.dirtyStorage { for key, value := range so.dirtyStorage {
delete(self.dirtyStorage, key) delete(so.dirtyStorage, key)
if (value == common.Hash{}) { if (value == common.Hash{}) {
self.setError(tr.TryDelete(key[:])) so.setError(tr.TryDelete(key[:]))
continue continue
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00")) v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
self.setError(tr.TryUpdate(key[:], v)) so.setError(tr.TryUpdate(key[:], v))
} }
return tr return tr
} }
// UpdateRoot sets the trie root to the current root hash of // UpdateRoot sets the trie root to the current root hash of
func (self *stateObject) updateRoot(db Database) { func (so *stateObject) updateRoot(db Database) {
self.updateTrie(db) so.updateTrie(db)
self.data.Root = self.trie.Hash() so.data.Root = so.trie.Hash()
} }
// CommitTrie the storage trie of the object to dwb. // CommitTrie the storage trie of the object to dwb.
// This updates the trie root. // This updates the trie root.
func (self *stateObject) CommitTrie(db Database) error { func (so *stateObject) CommitTrie(db Database) error {
self.updateTrie(db) so.updateTrie(db)
if self.dbErr != nil { if so.dbErr != nil {
return self.dbErr return so.dbErr
} }
root, err := self.trie.Commit(nil) root, err := so.trie.Commit(nil)
if err == nil { if err == nil {
self.data.Root = root so.data.Root = root
} }
return err return err
} }
// AddBalance removes amount from c's balance. // AddBalance removes amount from c's balance.
// It is used to add funds to the destination account of a transfer. // It is used to add funds to the destination account of a transfer.
func (c *stateObject) AddBalance(amount *big.Int) { func (so *stateObject) AddBalance(amount *big.Int) {
// EIP158: We must check emptiness for the objects such that the account // EIP158: We must check emptiness for the objects such that the account
// clearing (0,0,0 objects) can take effect. // clearing (0,0,0 objects) can take effect.
if amount.Sign() == 0 { if amount.Sign() == 0 {
if c.empty() { if so.empty() {
c.touch() so.touch()
} }
return return
} }
c.SetBalance(new(big.Int).Add(c.Balance(), amount)) so.SetBalance(new(big.Int).Add(so.Balance(), amount))
} }
// SubBalance removes amount from c's balance. // SubBalance removes amount from c's balance.
// It is used to remove funds from the origin account of a transfer. // It is used to remove funds from the origin account of a transfer.
func (c *stateObject) SubBalance(amount *big.Int) { func (so *stateObject) SubBalance(amount *big.Int) {
if amount.Sign() == 0 { if amount.Sign() == 0 {
return return
} }
c.SetBalance(new(big.Int).Sub(c.Balance(), amount)) so.SetBalance(new(big.Int).Sub(so.Balance(), amount))
} }
func (self *stateObject) SetBalance(amount *big.Int) { func (so *stateObject) SetBalance(amount *big.Int) {
self.db.journal.append(balanceChange{ so.db.journal.append(balanceChange{
account: &self.address, account: &so.address,
prev: new(big.Int).Set(self.data.Balance), prev: new(big.Int).Set(so.data.Balance),
}) })
self.setBalance(amount) so.setBalance(amount)
} }
func (self *stateObject) setBalance(amount *big.Int) { func (so *stateObject) setBalance(amount *big.Int) {
self.data.Balance = amount so.data.Balance = amount
} }
// Return the gas back to the origin. Used by the Virtual machine or Closures // Return the gas back to the origin. Used by the Virtual machine or Closures
func (c *stateObject) ReturnGas(gas *big.Int) {} func (so *stateObject) ReturnGas(gas *big.Int) {}
func (self *stateObject) deepCopy(db *StateDB) *stateObject { func (so *stateObject) deepCopy(db *StateDB) *stateObject {
stateObject := newObject(db, self.address, self.data) stateObject := newObject(db, so.address, so.data)
if self.trie != nil { if so.trie != nil {
stateObject.trie = db.db.CopyTrie(self.trie) stateObject.trie = db.db.CopyTrie(so.trie)
} }
stateObject.code = self.code stateObject.code = so.code
stateObject.dirtyStorage = self.dirtyStorage.Copy() stateObject.dirtyStorage = so.dirtyStorage.Copy()
stateObject.cachedStorage = self.dirtyStorage.Copy() stateObject.cachedStorage = so.dirtyStorage.Copy()
stateObject.suicided = self.suicided stateObject.suicided = so.suicided
stateObject.dirtyCode = self.dirtyCode stateObject.dirtyCode = so.dirtyCode
stateObject.deleted = self.deleted stateObject.deleted = so.deleted
return stateObject return stateObject
} }
@ -290,70 +290,70 @@ func (self *stateObject) deepCopy(db *StateDB) *stateObject {
// Attribute accessors // Attribute accessors
// //
// Returns the address of the contract/account // Address returns the address of the contract/account
func (c *stateObject) Address() common.Address { func (so *stateObject) Address() common.Address {
return c.address return so.address
} }
// Code returns the contract code associated with this object, if any. // Code returns the contract code associated with this object, if any.
func (self *stateObject) Code(db Database) []byte { func (so *stateObject) Code(db Database) []byte {
if self.code != nil { if so.code != nil {
return self.code return so.code
} }
if bytes.Equal(self.CodeHash(), emptyCodeHash) { if bytes.Equal(so.CodeHash(), emptyCodeHash) {
return nil return nil
} }
code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash())) code, err := db.ContractCode(so.addrHash, common.BytesToHash(so.CodeHash()))
if err != nil { if err != nil {
self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err)) so.setError(fmt.Errorf("can't load code hash %x: %v", so.CodeHash(), err))
} }
self.code = code so.code = code
return code return code
} }
func (self *stateObject) SetCode(codeHash common.Hash, code []byte) { func (so *stateObject) SetCode(codeHash common.Hash, code []byte) {
prevcode := self.Code(self.db.db) prevcode := so.Code(so.db.db)
self.db.journal.append(codeChange{ so.db.journal.append(codeChange{
account: &self.address, account: &so.address,
prevhash: self.CodeHash(), prevhash: so.CodeHash(),
prevcode: prevcode, prevcode: prevcode,
}) })
self.setCode(codeHash, code) so.setCode(codeHash, code)
} }
func (self *stateObject) setCode(codeHash common.Hash, code []byte) { func (so *stateObject) setCode(codeHash common.Hash, code []byte) {
self.code = code so.code = code
self.data.CodeHash = codeHash[:] so.data.CodeHash = codeHash[:]
self.dirtyCode = true so.dirtyCode = true
} }
func (self *stateObject) SetNonce(nonce uint64) { func (so *stateObject) SetNonce(nonce uint64) {
self.db.journal.append(nonceChange{ so.db.journal.append(nonceChange{
account: &self.address, account: &so.address,
prev: self.data.Nonce, prev: so.data.Nonce,
}) })
self.setNonce(nonce) so.setNonce(nonce)
} }
func (self *stateObject) setNonce(nonce uint64) { func (so *stateObject) setNonce(nonce uint64) {
self.data.Nonce = nonce so.data.Nonce = nonce
} }
func (self *stateObject) CodeHash() []byte { func (so *stateObject) CodeHash() []byte {
return self.data.CodeHash return so.data.CodeHash
} }
func (self *stateObject) Balance() *big.Int { func (so *stateObject) Balance() *big.Int {
return self.data.Balance return so.data.Balance
} }
func (self *stateObject) Nonce() uint64 { func (so *stateObject) Nonce() uint64 {
return self.data.Nonce return so.data.Nonce
} }
// Never called, but must be present to allow stateObject to be used // Never called, but must be present to allow stateObject to be used
// as a vm.Account interface that also satisfies the vm.ContractRef // as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome. // interface. Interfaces are awesome.
func (self *stateObject) Value() *big.Int { func (so *stateObject) Value() *big.Int {
panic("Value on stateObject should never be called") panic("Value on stateObject should never be called")
} }

View file

@ -83,7 +83,7 @@ type StateDB struct {
lock sync.Mutex lock sync.Mutex
} }
// Create a new state from a given trie. // New creates a new state from a given trie.
func New(root common.Hash, db Database) (*StateDB, error) { func New(root common.Hash, db Database) (*StateDB, error) {
tr, err := db.OpenTrie(root) tr, err := db.OpenTrie(root)
if err != nil { if err != nil {
@ -101,103 +101,103 @@ func New(root common.Hash, db Database) (*StateDB, error) {
} }
// setError remembers the first non-nil error it is called with. // setError remembers the first non-nil error it is called with.
func (self *StateDB) setError(err error) { func (s *StateDB) setError(err error) {
if self.dbErr == nil { if s.dbErr == nil {
self.dbErr = err s.dbErr = err
} }
} }
func (self *StateDB) Error() error { func (s *StateDB) Error() error {
return self.dbErr return s.dbErr
} }
// Reset clears out all ephemeral state objects from the state db, but keeps // Reset clears out all ephemeral state objects from the state db, but keeps
// the underlying state trie to avoid reloading data for the next operations. // the underlying state trie to avoid reloading data for the next operations.
func (self *StateDB) Reset(root common.Hash) error { func (s *StateDB) Reset(root common.Hash) error {
tr, err := self.db.OpenTrie(root) tr, err := s.db.OpenTrie(root)
if err != nil { if err != nil {
return err return err
} }
self.trie = tr s.trie = tr
self.stateObjects = make(map[common.Address]*stateObject) s.stateObjects = make(map[common.Address]*stateObject)
self.stateObjectsDirty = make(map[common.Address]struct{}) s.stateObjectsDirty = make(map[common.Address]struct{})
self.thash = common.Hash{} s.thash = common.Hash{}
self.bhash = common.Hash{} s.bhash = common.Hash{}
self.txIndex = 0 s.txIndex = 0
self.logs = make(map[common.Hash][]*types.Log) s.logs = make(map[common.Hash][]*types.Log)
self.logSize = 0 s.logSize = 0
self.preimages = make(map[common.Hash][]byte) s.preimages = make(map[common.Hash][]byte)
self.clearJournalAndRefund() s.clearJournalAndRefund()
return nil return nil
} }
func (self *StateDB) AddLog(log *types.Log) { func (s *StateDB) AddLog(log *types.Log) {
self.journal.append(addLogChange{txhash: self.thash}) s.journal.append(addLogChange{txhash: s.thash})
log.TxHash = self.thash log.TxHash = s.thash
log.BlockHash = self.bhash log.BlockHash = s.bhash
log.TxIndex = uint(self.txIndex) log.TxIndex = uint(s.txIndex)
log.Index = self.logSize log.Index = s.logSize
self.logs[self.thash] = append(self.logs[self.thash], log) s.logs[s.thash] = append(s.logs[s.thash], log)
self.logSize++ s.logSize++
} }
func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
return self.logs[hash] return s.logs[hash]
} }
func (self *StateDB) Logs() []*types.Log { func (s *StateDB) Logs() []*types.Log {
var logs []*types.Log var logs []*types.Log
for _, lgs := range self.logs { for _, lgs := range s.logs {
logs = append(logs, lgs...) logs = append(logs, lgs...)
} }
return logs return logs
} }
// AddPreimage records a SHA3 preimage seen by the VM. // AddPreimage records a SHA3 preimage seen by the VM.
func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
if _, ok := self.preimages[hash]; !ok { if _, ok := s.preimages[hash]; !ok {
self.journal.append(addPreimageChange{hash: hash}) s.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage)) pi := make([]byte, len(preimage))
copy(pi, preimage) copy(pi, preimage)
self.preimages[hash] = pi s.preimages[hash] = pi
} }
} }
// Preimages returns a list of SHA3 preimages that have been submitted. // Preimages returns a list of SHA3 preimages that have been submitted.
func (self *StateDB) Preimages() map[common.Hash][]byte { func (s *StateDB) Preimages() map[common.Hash][]byte {
return self.preimages return s.preimages
} }
func (self *StateDB) AddRefund(gas uint64) { func (s *StateDB) AddRefund(gas uint64) {
self.journal.append(refundChange{prev: self.refund}) s.journal.append(refundChange{prev: s.refund})
self.refund += gas s.refund += gas
} }
// Exist reports whether the given account address exists in the state. // Exist reports whether the given account address exists in the state.
// Notably this also returns true for suicided accounts. // Notably this also returns true for suicided accounts.
func (self *StateDB) Exist(addr common.Address) bool { func (s *StateDB) Exist(addr common.Address) bool {
return self.getStateObject(addr) != nil return s.getStateObject(addr) != nil
} }
// Empty returns whether the state object is either non-existent // Empty returns whether the state object is either non-existent
// or empty according to the EIP161 specification (balance = nonce = code = 0) // or empty according to the EIP161 specification (balance = nonce = code = 0)
func (self *StateDB) Empty(addr common.Address) bool { func (s *StateDB) Empty(addr common.Address) bool {
so := self.getStateObject(addr) so := s.getStateObject(addr)
return so == nil || so.empty() return so == nil || so.empty()
} }
// Retrieve the balance from the given address or 0 if object not found // GetBalance retrieves the balance from the given address or 0 if object not found
func (self *StateDB) GetBalance(addr common.Address) *big.Int { func (s *StateDB) GetBalance(addr common.Address) *big.Int {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Balance() return stateObject.Balance()
} }
return common.Big0 return common.Big0
} }
func (self *StateDB) GetNonce(addr common.Address) uint64 { func (s *StateDB) GetNonce(addr common.Address) uint64 {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Nonce() return stateObject.Nonce()
} }
@ -205,63 +205,63 @@ func (self *StateDB) GetNonce(addr common.Address) uint64 {
return 0 return 0
} }
func (self *StateDB) GetCode(addr common.Address) []byte { func (s *StateDB) GetCode(addr common.Address) []byte {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Code(self.db) return stateObject.Code(s.db)
} }
return nil return nil
} }
func (self *StateDB) GetCodeSize(addr common.Address) int { func (s *StateDB) GetCodeSize(addr common.Address) int {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return 0 return 0
} }
if stateObject.code != nil { if stateObject.code != nil {
return len(stateObject.code) return len(stateObject.code)
} }
size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) size, err := s.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
if err != nil { if err != nil {
self.setError(err) s.setError(err)
} }
return size return size
} }
func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return common.Hash{} return common.Hash{}
} }
return common.BytesToHash(stateObject.CodeHash()) return common.BytesToHash(stateObject.CodeHash())
} }
func (self *StateDB) GetState(addr common.Address, bhash common.Hash) common.Hash { func (s *StateDB) GetState(addr common.Address, bhash common.Hash) common.Hash {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.GetState(self.db, bhash) return stateObject.GetState(s.db, bhash)
} }
return common.Hash{} return common.Hash{}
} }
// Database retrieves the low level database supporting the lower level trie ops. // Database retrieves the low level database supporting the lower level trie ops.
func (self *StateDB) Database() Database { func (s *StateDB) Database() Database {
return self.db return s.db
} }
// StorageTrie returns the storage trie of an account. // StorageTrie returns the storage trie of an account.
// The return value is a copy and is nil for non-existent accounts. // The return value is a copy and is nil for non-existent accounts.
func (self *StateDB) StorageTrie(addr common.Address) Trie { func (s *StateDB) StorageTrie(addr common.Address) Trie {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return nil return nil
} }
cpy := stateObject.deepCopy(self) cpy := stateObject.deepCopy(s)
return cpy.updateTrie(self.db) return cpy.updateTrie(s.db)
} }
func (self *StateDB) HasSuicided(addr common.Address) bool { func (s *StateDB) HasSuicided(addr common.Address) bool {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.suicided return stateObject.suicided
} }
@ -273,46 +273,46 @@ func (self *StateDB) HasSuicided(addr common.Address) bool {
*/ */
// AddBalance adds amount to the account associated with addr. // AddBalance adds amount to the account associated with addr.
func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.AddBalance(amount) stateObject.AddBalance(amount)
} }
} }
// SubBalance subtracts amount from the account associated with addr. // SubBalance subtracts amount from the account associated with addr.
func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SubBalance(amount) stateObject.SubBalance(amount)
} }
} }
func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetBalance(amount) stateObject.SetBalance(amount)
} }
} }
func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetNonce(nonce) stateObject.SetNonce(nonce)
} }
} }
func (self *StateDB) SetCode(addr common.Address, code []byte) { func (s *StateDB) SetCode(addr common.Address, code []byte) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetCode(crypto.Keccak256Hash(code), code) stateObject.SetCode(crypto.Keccak256Hash(code), code)
} }
} }
func (self *StateDB) SetState(addr common.Address, key, value common.Hash) { func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
stateObject := self.GetOrNewStateObject(addr) stateObject := s.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetState(self.db, key, value) stateObject.SetState(s.db, key, value)
} }
} }
@ -321,12 +321,12 @@ func (self *StateDB) SetState(addr common.Address, key, value common.Hash) {
// //
// The account's state object is still available until the state is committed, // The account's state object is still available until the state is committed,
// getStateObject will return a non-nil account after Suicide. // getStateObject will return a non-nil account after Suicide.
func (self *StateDB) Suicide(addr common.Address) bool { func (s *StateDB) Suicide(addr common.Address) bool {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return false return false
} }
self.journal.append(suicideChange{ s.journal.append(suicideChange{
account: &addr, account: &addr,
prev: stateObject.suicided, prev: stateObject.suicided,
prevbalance: new(big.Int).Set(stateObject.Balance()), prevbalance: new(big.Int).Set(stateObject.Balance()),
@ -342,26 +342,26 @@ func (self *StateDB) Suicide(addr common.Address) bool {
// //
// updateStateObject writes the given object to the trie. // updateStateObject writes the given object to the trie.
func (self *StateDB) updateStateObject(stateObject *stateObject) { func (s *StateDB) updateStateObject(stateObject *stateObject) {
addr := stateObject.Address() addr := stateObject.Address()
data, err := rlp.EncodeToBytes(stateObject) data, err := rlp.EncodeToBytes(stateObject)
if err != nil { if err != nil {
panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
} }
self.setError(self.trie.TryUpdate(addr[:], data)) s.setError(s.trie.TryUpdate(addr[:], data))
} }
// deleteStateObject removes the given object from the state trie. // deleteStateObject removes the given object from the state trie.
func (self *StateDB) deleteStateObject(stateObject *stateObject) { func (s *StateDB) deleteStateObject(stateObject *stateObject) {
stateObject.deleted = true stateObject.deleted = true
addr := stateObject.Address() addr := stateObject.Address()
self.setError(self.trie.TryDelete(addr[:])) s.setError(s.trie.TryDelete(addr[:]))
} }
// Retrieve a state object given my the address. Returns nil if not found. // Retrieve a state object given my the address. Returns nil if not found.
func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { func (s *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := self.stateObjects[addr]; obj != nil { if obj := s.stateObjects[addr]; obj != nil {
if obj.deleted { if obj.deleted {
return nil return nil
} }
@ -369,9 +369,9 @@ func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObje
} }
// Load the object from the database. // Load the object from the database.
enc, err := self.trie.TryGet(addr[:]) enc, err := s.trie.TryGet(addr[:])
if len(enc) == 0 { if len(enc) == 0 {
self.setError(err) s.setError(err)
return nil return nil
} }
var data Account var data Account
@ -380,36 +380,36 @@ func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObje
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newObject(self, addr, data) obj := newObject(s, addr, data)
self.setStateObject(obj) s.setStateObject(obj)
return obj return obj
} }
func (self *StateDB) setStateObject(object *stateObject) { func (s *StateDB) setStateObject(object *stateObject) {
self.stateObjects[object.Address()] = object s.stateObjects[object.Address()] = object
} }
// Retrieve a state object or create a new state object if nil. // GetOrNewStateObject retrieves a state object or creates a new state object if nil.
func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
stateObject := self.getStateObject(addr) stateObject := s.getStateObject(addr)
if stateObject == nil || stateObject.deleted { if stateObject == nil || stateObject.deleted {
stateObject, _ = self.createObject(addr) stateObject, _ = s.createObject(addr)
} }
return stateObject return stateObject
} }
// createObject creates a new state object. If there is an existing account with // createObject creates a new state object. If there is an existing account with
// the given address, it is overwritten and returned as the second return value. // the given address, it is overwritten and returned as the second return value.
func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
prev = self.getStateObject(addr) prev = s.getStateObject(addr)
newobj = newObject(self, addr, Account{}) newobj = newObject(s, addr, Account{})
newobj.setNonce(0) // sets the object to dirty newobj.setNonce(0) // sets the object to dirty
if prev == nil { if prev == nil {
self.journal.append(createObjectChange{account: &addr}) s.journal.append(createObjectChange{account: &addr})
} else { } else {
self.journal.append(resetObjectChange{prev: prev}) s.journal.append(resetObjectChange{prev: prev})
} }
self.setStateObject(newobj) s.setStateObject(newobj)
return newobj, prev return newobj, prev
} }
@ -423,15 +423,15 @@ func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObjec
// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
// //
// Carrying over the balance ensures that Ether doesn't disappear. // Carrying over the balance ensures that Ether doesn't disappear.
func (self *StateDB) CreateAccount(addr common.Address) { func (s *StateDB) CreateAccount(addr common.Address) {
new, prev := self.createObject(addr) new, prev := s.createObject(addr)
if prev != nil { if prev != nil {
new.setBalance(prev.data.Balance) new.setBalance(prev.data.Balance)
} }
} }
func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { func (s *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
so := db.getStateObject(addr) so := s.getStateObject(addr)
if so == nil { if so == nil {
return return
} }
@ -441,10 +441,10 @@ func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common
cb(h, value) cb(h, value)
} }
it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) it := trie.NewIterator(so.getTrie(s.db).NodeIterator(nil))
for it.Next() { for it.Next() {
// ignore cached values // ignore cached values
key := common.BytesToHash(db.trie.GetKey(it.Key)) key := common.BytesToHash(s.trie.GetKey(it.Key))
if _, ok := so.cachedStorage[key]; !ok { if _, ok := so.cachedStorage[key]; !ok {
cb(key, common.BytesToHash(it.Value)) cb(key, common.BytesToHash(it.Value))
} }
@ -453,29 +453,29 @@ func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common
// Copy creates a deep, independent copy of the state. // Copy creates a deep, independent copy of the state.
// Snapshots of the copied state cannot be applied to the copy. // Snapshots of the copied state cannot be applied to the copy.
func (self *StateDB) Copy() *StateDB { func (s *StateDB) Copy() *StateDB {
self.lock.Lock() s.lock.Lock()
defer self.lock.Unlock() defer s.lock.Unlock()
// Copy all the basic fields, initialize the memory ones // Copy all the basic fields, initialize the memory ones
state := &StateDB{ state := &StateDB{
db: self.db, db: s.db,
trie: self.db.CopyTrie(self.trie), trie: s.db.CopyTrie(s.trie),
stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)), stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)),
stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)), stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)),
refund: self.refund, refund: s.refund,
logs: make(map[common.Hash][]*types.Log, len(self.logs)), logs: make(map[common.Hash][]*types.Log, len(s.logs)),
logSize: self.logSize, logSize: s.logSize,
preimages: make(map[common.Hash][]byte), preimages: make(map[common.Hash][]byte),
journal: newJournal(), journal: newJournal(),
} }
// Copy the dirty states, logs, and preimages // Copy the dirty states, logs, and preimages
for addr := range self.journal.dirties { for addr := range s.journal.dirties {
// As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
// and in the Finalise-method, there is a case where an object is in the journal but not // and in the Finalise-method, there is a case where an object is in the journal but not
// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
// nil // nil
if object, exist := self.stateObjects[addr]; exist { if object, exist := s.stateObjects[addr]; exist {
state.stateObjects[addr] = object.deepCopy(state) state.stateObjects[addr] = object.deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{} state.stateObjectsDirty[addr] = struct{}{}
} }
@ -483,50 +483,50 @@ func (self *StateDB) Copy() *StateDB {
// Above, we don't copy the actual journal. This means that if the copy is copied, the // Above, we don't copy the actual journal. This means that if the copy is copied, the
// loop above will be a no-op, since the copy's journal is empty. // loop above will be a no-op, since the copy's journal is empty.
// Thus, here we iterate over stateObjects, to enable copies of copies // Thus, here we iterate over stateObjects, to enable copies of copies
for addr := range self.stateObjectsDirty { for addr := range s.stateObjectsDirty {
if _, exist := state.stateObjects[addr]; !exist { if _, exist := state.stateObjects[addr]; !exist {
state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{} state.stateObjectsDirty[addr] = struct{}{}
} }
} }
for hash, logs := range self.logs { for hash, logs := range s.logs {
state.logs[hash] = make([]*types.Log, len(logs)) state.logs[hash] = make([]*types.Log, len(logs))
copy(state.logs[hash], logs) copy(state.logs[hash], logs)
} }
for hash, preimage := range self.preimages { for hash, preimage := range s.preimages {
state.preimages[hash] = preimage state.preimages[hash] = preimage
} }
return state return state
} }
// Snapshot returns an identifier for the current revision of the state. // Snapshot returns an identifier for the current revision of the state.
func (self *StateDB) Snapshot() int { func (s *StateDB) Snapshot() int {
id := self.nextRevisionId id := s.nextRevisionId
self.nextRevisionId++ s.nextRevisionId++
self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
return id return id
} }
// RevertToSnapshot reverts all state changes made since the given revision. // RevertToSnapshot reverts all state changes made since the given revision.
func (self *StateDB) RevertToSnapshot(revid int) { func (s *StateDB) RevertToSnapshot(revid int) {
// Find the snapshot in the stack of valid snapshots. // Find the snapshot in the stack of valid snapshots.
idx := sort.Search(len(self.validRevisions), func(i int) bool { idx := sort.Search(len(s.validRevisions), func(i int) bool {
return self.validRevisions[i].id >= revid return s.validRevisions[i].id >= revid
}) })
if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
panic(fmt.Errorf("revision id %v cannot be reverted", revid)) panic(fmt.Errorf("revision id %v cannot be reverted", revid))
} }
snapshot := self.validRevisions[idx].journalIndex snapshot := s.validRevisions[idx].journalIndex
// Replay the journal to undo changes and remove invalidated snapshots // Replay the journal to undo changes and remove invalidated snapshots
self.journal.revert(self, snapshot) s.journal.revert(s, snapshot)
self.validRevisions = self.validRevisions[:idx] s.validRevisions = s.validRevisions[:idx]
} }
// GetRefund returns the current value of the refund counter. // GetRefund returns the current value of the refund counter.
func (self *StateDB) GetRefund() uint64 { func (s *StateDB) GetRefund() uint64 {
return self.refund return s.refund
} }
// Finalise finalises the state by removing the self destructed objects // Finalise finalises the state by removing the self destructed objects
@ -566,10 +566,10 @@ func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
// Prepare sets the current transaction hash and index and block hash which is // Prepare sets the current transaction hash and index and block hash which is
// used when the EVM emits new state logs. // used when the EVM emits new state logs.
func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
self.thash = thash s.thash = thash
self.bhash = bhash s.bhash = bhash
self.txIndex = ti s.txIndex = ti
} }
func (s *StateDB) clearJournalAndRefund() { func (s *StateDB) clearJournalAndRefund() {

View file

@ -1282,13 +1282,13 @@ func TestTransactionPoolRepricingKeepsLocals(t *testing.T) {
// Create transaction (both pending and queued) with a linearly growing gasprice // Create transaction (both pending and queued) with a linearly growing gasprice
for i := uint64(0); i < 500; i++ { for i := uint64(0); i < 500; i++ {
// Add pending // Add pending
p_tx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2]) pTx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2])
if err := pool.AddLocal(p_tx); err != nil { if err := pool.AddLocal(pTx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Add queued // Add queued
q_tx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2]) qTx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2])
if err := pool.AddLocal(q_tx); err != nil { if err := pool.AddLocal(qTx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }

View file

@ -277,7 +277,7 @@ func (b *Block) EncodeRLP(w io.Writer) error {
}) })
} }
// [deprecated by eth/63] // DecodeRLP was [deprecated by eth/63]
func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
var sb storageblock var sb storageblock
if err := s.Decode(&sb); err != nil { if err := s.Decode(&sb); err != nil {
@ -392,10 +392,10 @@ type Blocks []*Block
type BlockBy func(b1, b2 *Block) bool type BlockBy func(b1, b2 *Block) bool
func (self BlockBy) Sort(blocks Blocks) { func (b BlockBy) Sort(blocks Blocks) {
bs := blockSorter{ bs := blockSorter{
blocks: blocks, blocks: blocks,
by: self, by: b,
} }
sort.Sort(bs) sort.Sort(bs)
} }
@ -405,10 +405,10 @@ type blockSorter struct {
by func(b1, b2 *Block) bool by func(b1, b2 *Block) bool
} }
func (self blockSorter) Len() int { return len(self.blocks) } func (s blockSorter) Len() int { return len(s.blocks) }
func (self blockSorter) Swap(i, j int) { func (s blockSorter) Swap(i, j int) {
self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i] s.blocks[i], s.blocks[j] = s.blocks[j], s.blocks[i]
} }
func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) } func (s blockSorter) Less(i, j int) bool { return s.by(s.blocks[i], s.blocks[j]) }
func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 } func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }

View file

@ -39,9 +39,8 @@ var (
func deriveSigner(V *big.Int) Signer { func deriveSigner(V *big.Int) Signer {
if V.Sign() != 0 && isProtectedV(V) { if V.Sign() != 0 && isProtectedV(V) {
return NewEIP155Signer(deriveChainId(V)) return NewEIP155Signer(deriveChainId(V))
} else {
return HomesteadSigner{}
} }
return HomesteadSigner{}
} }
type Transaction struct { type Transaction struct {

View file

@ -168,7 +168,7 @@ func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
// homestead rules. // homestead rules.
type HomesteadSigner struct{ FrontierSigner } type HomesteadSigner struct{ FrontierSigner }
func (s HomesteadSigner) Equal(s2 Signer) bool { func (hs HomesteadSigner) Equal(s2 Signer) bool {
_, ok := s2.(HomesteadSigner) _, ok := s2.(HomesteadSigner)
return ok return ok
} }
@ -185,7 +185,7 @@ func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) {
type FrontierSigner struct{} type FrontierSigner struct{}
func (s FrontierSigner) Equal(s2 Signer) bool { func (fs FrontierSigner) Equal(s2 Signer) bool {
_, ok := s2.(FrontierSigner) _, ok := s2.(FrontierSigner)
return ok return ok
} }

View file

@ -861,7 +861,7 @@ func makeDup(size int64) executionFunc {
// make swap instruction function // make swap instruction function
func makeSwap(size int64) executionFunc { func makeSwap(size int64) executionFunc {
// switch n + 1 otherwise n would be swapped with n // switch n + 1 otherwise n would be swapped with n
size += 1 size++
return func(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { return func(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
stack.swap(int(size)) stack.swap(int(size))
return nil, nil return nil, nil

View file

@ -21,8 +21,8 @@ import (
"math/big" "math/big"
) )
// stack is an object for basic stack operations. Items popped to the stack are // Stack is an object for basic stack operations. Items popped to the stack are
// expected to be changed and modified. stack does not take care of adding newly // expected to be changed and modified. Stack does not take care of adding newly
// initialised objects. // initialised objects.
type Stack struct { type Stack struct {
data []*big.Int data []*big.Int

View file

@ -35,8 +35,8 @@ import (
) )
var ( var (
secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16) secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2)) secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
) )
// Keccak256 calculates and returns the Keccak256 hash of the input data. // Keccak256 calculates and returns the Keccak256 hash of the input data.
@ -68,7 +68,7 @@ func Keccak512(data ...[]byte) []byte {
return d.Sum(nil) return d.Sum(nil)
} }
// Creates an ethereum address given the bytes and the nonce // CreateAddress creates an ethereum address given the bytes and the nonce
func CreateAddress(b common.Address, nonce uint64) common.Address { func CreateAddress(b common.Address, nonce uint64) common.Address {
data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
return common.BytesToAddress(Keccak256(data)[12:]) return common.BytesToAddress(Keccak256(data)[12:])
@ -99,7 +99,7 @@ func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
priv.D = new(big.Int).SetBytes(d) priv.D = new(big.Int).SetBytes(d)
// The priv.D must < N // The priv.D must < N
if priv.D.Cmp(secp256k1_N) >= 0 { if priv.D.Cmp(secp256k1N) >= 0 {
return nil, fmt.Errorf("invalid private key, >=N") return nil, fmt.Errorf("invalid private key, >=N")
} }
// The priv.D must not be zero or negative. // The priv.D must not be zero or negative.
@ -184,11 +184,11 @@ func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
} }
// reject upper range of s values (ECDSA malleability) // reject upper range of s values (ECDSA malleability)
// see discussion in secp256k1/libsecp256k1/include/secp256k1.h // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
if homestead && s.Cmp(secp256k1_halfN) > 0 { if homestead && s.Cmp(secp256k1halfN) > 0 {
return false return false
} }
// Frontier: allow s to be in full N range // Frontier: allow s to be in full N range
return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1) return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
} }
func PubkeyToAddress(p ecdsa.PublicKey) common.Address { func PubkeyToAddress(p ecdsa.PublicKey) common.Address {

View file

@ -154,7 +154,7 @@ func TestValidateSignatureValues(t *testing.T) {
minusOne := big.NewInt(-1) minusOne := big.NewInt(-1)
one := common.Big1 one := common.Big1
zero := common.Big0 zero := common.Big0
secp256k1nMinus1 := new(big.Int).Sub(secp256k1_N, common.Big1) secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
// correct v,r,s // correct v,r,s
check(true, 0, one, one) check(true, 0, one, one)
@ -181,9 +181,9 @@ func TestValidateSignatureValues(t *testing.T) {
// correct sig with max r,s // correct sig with max r,s
check(true, 0, secp256k1nMinus1, secp256k1nMinus1) check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
// correct v, combinations of incorrect r,s at upper limit // correct v, combinations of incorrect r,s at upper limit
check(false, 0, secp256k1_N, secp256k1nMinus1) check(false, 0, secp256k1N, secp256k1nMinus1)
check(false, 0, secp256k1nMinus1, secp256k1_N) check(false, 0, secp256k1nMinus1, secp256k1N)
check(false, 0, secp256k1_N, secp256k1_N) check(false, 0, secp256k1N, secp256k1N)
// current callers ensures r,s cannot be negative, but let's test for that too // current callers ensures r,s cannot be negative, but let's test for that too
// as crypto package could be used stand-alone // as crypto package could be used stand-alone

View file

@ -77,7 +77,7 @@ func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
} }
} }
// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve. // IsOnCurve returns true if the given (x,y) lies on the BitCurve.
func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
// y² = x³ + b // y² = x³ + b
y2 := new(big.Int).Mul(y, y) //y² y2 := new(big.Int).Mul(y, y) //y²

View file

@ -49,7 +49,7 @@ func randSig() []byte {
// tests for malleability // tests for malleability
// highest bit of signature ECDSA s value must be 0, in the 33th byte // highest bit of signature ECDSA s value must be 0, in the 33th byte
func compactSigCheck(t *testing.T, sig []byte) { func compactSigCheck(t *testing.T, sig []byte) {
var b int = int(sig[32]) var b = int(sig[32])
if b < 0 { if b < 0 {
t.Errorf("highest bit is negative: %d", b) t.Errorf("highest bit is negative: %d", b)
} }

View file

@ -88,7 +88,7 @@ func VerifySignature(pubkey, hash, signature []byte) bool {
return false return false
} }
// Reject malleable signatures. libsecp256k1 does this check but btcec doesn't. // Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
if sig.S.Cmp(secp256k1_halfN) > 0 { if sig.S.Cmp(secp256k1halfN) > 0 {
return false return false
} }
return sig.Verify(hash, key) return sig.Verify(hash, key)