Update EVM to latest constantinople

pull/1133/head
Rongjian Lan 5 years ago
parent b409058a2c
commit bcd89eff8c
  1. 2
      consensus/consensus_v2.go
  2. 7
      core/blockchain.go
  3. 16
      core/state/database.go
  4. 24
      core/state/dump.go
  5. 2
      core/state/managed_state.go
  6. 244
      core/state/state_object.go
  7. 398
      core/state/statedb.go
  8. 5
      core/state/statedb_test.go
  9. 31
      core/types/block.go
  10. 6
      core/vm/contracts_test.go
  11. 8
      core/vm/evm.go
  12. 4
      core/vm/gas_table.go
  13. 7
      core/vm/instructions.go
  14. 21
      core/vm/interpreter.go
  15. 89
      core/vm/logger_json.go
  16. 5
      core/vm/logger_test.go
  17. 2
      core/vm/runtime/env.go
  18. 1
      core/vm/runtime/runtime_test.go
  19. 3
      drand/drand_leader.go
  20. 2
      internal/hmyapi/backend.go
  21. 5
      internal/shardchain/shardchains.go
  22. 7
      node/contract.go
  23. 2
      node/node.go
  24. 4
      node/node_genesis.go
  25. 66
      node/node_handler.go

@ -895,7 +895,7 @@ func (consensus *Consensus) Start(blockChannel chan *types.Block, stopChan chan
// Verify the randomness
_ = blockHash
consensus.getLogger().Info("[ConsensusMainLoop] Adding randomness into new block", "rnd", rnd)
newBlock.AddVdf([258]byte{}) // TODO(HB): add real vdf
// newBlock.AddVdf([258]byte{}) // TODO(HB): add real vdf
} else {
//consensus.getLogger().Info("Failed to get randomness", "error", err)
}

@ -1696,7 +1696,8 @@ func (bc *BlockChain) GetVdfByNumber(number uint64) [32]byte {
return [32]byte{}
}
result := [32]byte{}
copy(result[:], header.Vdf[:32])
//copy(result[:], header.Vdf[:32])
// TODO: add real vdf
return result
}
@ -1706,7 +1707,9 @@ func (bc *BlockChain) GetVrfByNumber(number uint64) [32]byte {
if header == nil {
return [32]byte{}
}
return header.Vrf
//return header.Vrf
// TODO: add real vrf
return [32]byte{}
}
// GetShardState returns the shard state for the given epoch,

@ -26,7 +26,7 @@ import (
lru "github.com/hashicorp/golang-lru"
)
// MaxTrieCacheGen is trie cache generation limit after which to evict trie nodes from memory.
// MaxTrieCacheGen limit after which to evict trie nodes from memory.
var MaxTrieCacheGen = uint16(120)
const (
@ -72,13 +72,19 @@ type Trie interface {
}
// NewDatabase creates a backing store for state. The returned database is safe for
// concurrent use and retains cached trie nodes in memory. The pool is an optional
// intermediate trie-node memory pool between the low level storage layer and the
// high level trie abstraction.
// concurrent use and retains a few recent expanded trie nodes in memory. To keep
// more historical state in memory, use the NewDatabaseWithCache constructor.
func NewDatabase(db ethdb.Database) Database {
return NewDatabaseWithCache(db, 0)
}
// NewDatabaseWithCache creates a backing store for state. The returned database is safe for
// concurrent use and retains both a few recent expanded trie nodes in memory, as
// well as a lot of collapsed RLP trie nodes in a large memory cache.
func NewDatabaseWithCache(db ethdb.Database, cache int) Database {
csc, _ := lru.New(codeSizeCacheSize)
return &cachingDB{
db: trie.NewDatabase(db),
db: trie.NewDatabaseWithCache(db, cache),
codeSizeCache: csc,
}
}

@ -35,22 +35,22 @@ type DumpAccount struct {
Storage map[string]string `json:"storage"`
}
// Dump is the structure of root hash and associated accounts.
// Dump ...
type Dump struct {
Root string `json:"root"`
Accounts map[string]DumpAccount `json:"accounts"`
}
// RawDump returns Dump from given DB.
func (stateDB *DB) RawDump() Dump {
// RawDump ...
func (db *DB) RawDump() Dump {
dump := Dump{
Root: fmt.Sprintf("%x", stateDB.trie.Hash()),
Root: fmt.Sprintf("%x", db.trie.Hash()),
Accounts: make(map[string]DumpAccount),
}
it := trie.NewIterator(stateDB.trie.NodeIterator(nil))
it := trie.NewIterator(db.trie.NodeIterator(nil))
for it.Next() {
addr := stateDB.trie.GetKey(it.Key)
addr := db.trie.GetKey(it.Key)
var data Account
if err := rlp.DecodeBytes(it.Value, &data); err != nil {
panic(err)
@ -62,21 +62,21 @@ func (stateDB *DB) RawDump() Dump {
Nonce: data.Nonce,
Root: common.Bytes2Hex(data.Root[:]),
CodeHash: common.Bytes2Hex(data.CodeHash),
Code: common.Bytes2Hex(obj.Code(stateDB.db)),
Code: common.Bytes2Hex(obj.Code(db.db)),
Storage: make(map[string]string),
}
storageIt := trie.NewIterator(obj.getTrie(stateDB.db).NodeIterator(nil))
storageIt := trie.NewIterator(obj.getTrie(db.db).NodeIterator(nil))
for storageIt.Next() {
account.Storage[common.Bytes2Hex(stateDB.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value)
account.Storage[common.Bytes2Hex(db.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value)
}
dump.Accounts[common.Bytes2Hex(addr)] = account
}
return dump
}
// Dump dumps into []byte.
func (stateDB *DB) Dump() []byte {
json, err := json.MarshalIndent(stateDB.RawDump(), "", " ")
// Dump ...
func (db *DB) Dump() []byte {
json, err := json.MarshalIndent(db.RawDump(), "", " ")
if err != nil {
fmt.Println("dump err", err)
}

@ -28,7 +28,7 @@ type account struct {
nonces []bool
}
// ManagedState is the managed state.
// ManagedState ...
type ManagedState struct {
*DB

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

@ -22,7 +22,6 @@ import (
"fmt"
"math/big"
"sort"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
@ -87,8 +86,6 @@ type DB struct {
journal *journal
validRevisions []revision
nextRevisionID int
lock sync.Mutex
}
// New creates a new state from a given trie.
@ -109,118 +106,118 @@ func New(root common.Hash, db Database) (*DB, error) {
}
// setError remembers the first non-nil error it is called with.
func (stateDB *DB) setError(err error) {
if stateDB.dbErr == nil {
stateDB.dbErr = err
func (db *DB) setError(err error) {
if db.dbErr == nil {
db.dbErr = err
}
}
func (stateDB *DB) Error() error {
return stateDB.dbErr
func (db *DB) Error() error {
return db.dbErr
}
// 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.
func (stateDB *DB) Reset(root common.Hash) error {
tr, err := stateDB.db.OpenTrie(root)
func (db *DB) Reset(root common.Hash) error {
tr, err := db.db.OpenTrie(root)
if err != nil {
return err
}
stateDB.trie = tr
stateDB.stateObjects = make(map[common.Address]*Object)
stateDB.stateObjectsDirty = make(map[common.Address]struct{})
stateDB.thash = common.Hash{}
stateDB.bhash = common.Hash{}
stateDB.txIndex = 0
stateDB.logs = make(map[common.Hash][]*types.Log)
stateDB.logSize = 0
stateDB.preimages = make(map[common.Hash][]byte)
stateDB.clearJournalAndRefund()
db.trie = tr
db.stateObjects = make(map[common.Address]*Object)
db.stateObjectsDirty = make(map[common.Address]struct{})
db.thash = common.Hash{}
db.bhash = common.Hash{}
db.txIndex = 0
db.logs = make(map[common.Hash][]*types.Log)
db.logSize = 0
db.preimages = make(map[common.Hash][]byte)
db.clearJournalAndRefund()
return nil
}
// AddLog adds logs into stateDB
func (stateDB *DB) AddLog(log *types.Log) {
stateDB.journal.append(addLogChange{txhash: stateDB.thash})
// AddLog ...
func (db *DB) AddLog(log *types.Log) {
db.journal.append(addLogChange{txhash: db.thash})
log.TxHash = stateDB.thash
log.BlockHash = stateDB.bhash
log.TxIndex = uint(stateDB.txIndex)
log.Index = stateDB.logSize
stateDB.logs[stateDB.thash] = append(stateDB.logs[stateDB.thash], log)
stateDB.logSize++
log.TxHash = db.thash
log.BlockHash = db.bhash
log.TxIndex = uint(db.txIndex)
log.Index = db.logSize
db.logs[db.thash] = append(db.logs[db.thash], log)
db.logSize++
}
// GetLogs gets logs from stateDB given a hash
func (stateDB *DB) GetLogs(hash common.Hash) []*types.Log {
return stateDB.logs[hash]
// GetLogs ...
func (db *DB) GetLogs(hash common.Hash) []*types.Log {
return db.logs[hash]
}
// Logs returns a list of Log.
func (stateDB *DB) Logs() []*types.Log {
// Logs ...
func (db *DB) Logs() []*types.Log {
var logs []*types.Log
for _, lgs := range stateDB.logs {
for _, lgs := range db.logs {
logs = append(logs, lgs...)
}
return logs
}
// AddPreimage records a SHA3 preimage seen by the VM.
func (stateDB *DB) AddPreimage(hash common.Hash, preimage []byte) {
if _, ok := stateDB.preimages[hash]; !ok {
stateDB.journal.append(addPreimageChange{hash: hash})
func (db *DB) AddPreimage(hash common.Hash, preimage []byte) {
if _, ok := db.preimages[hash]; !ok {
db.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage))
copy(pi, preimage)
stateDB.preimages[hash] = pi
db.preimages[hash] = pi
}
}
// Preimages returns a list of SHA3 preimages that have been submitted.
func (stateDB *DB) Preimages() map[common.Hash][]byte {
return stateDB.preimages
func (db *DB) Preimages() map[common.Hash][]byte {
return db.preimages
}
// AddRefund adds gas to the refund counter
func (stateDB *DB) AddRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund})
stateDB.refund += gas
func (db *DB) AddRefund(gas uint64) {
db.journal.append(refundChange{prev: db.refund})
db.refund += gas
}
// SubRefund removes gas from the refund counter.
// This method will panic if the refund counter goes below zero
func (stateDB *DB) SubRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund})
if gas > stateDB.refund {
func (db *DB) SubRefund(gas uint64) {
db.journal.append(refundChange{prev: db.refund})
if gas > db.refund {
panic("Refund counter below zero")
}
stateDB.refund -= gas
db.refund -= gas
}
// Exist reports whether the given account address exists in the state.
// Notably this also returns true for suicided accounts.
func (stateDB *DB) Exist(addr common.Address) bool {
return stateDB.getStateObject(addr) != nil
func (db *DB) Exist(addr common.Address) bool {
return db.getStateObject(addr) != nil
}
// Empty returns whether the state object is either non-existent
// or empty according to the EIP161 specification (balance = nonce = code = 0)
func (stateDB *DB) Empty(addr common.Address) bool {
so := stateDB.getStateObject(addr)
func (db *DB) Empty(addr common.Address) bool {
so := db.getStateObject(addr)
return so == nil || so.empty()
}
// GetBalance retrieves the balance from the given address or 0 if object not found
func (stateDB *DB) GetBalance(addr common.Address) *big.Int {
stateObject := stateDB.getStateObject(addr)
func (db *DB) GetBalance(addr common.Address) *big.Int {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.Balance()
}
return common.Big0
}
// GetNonce returns the nonce of the given address.
func (stateDB *DB) GetNonce(addr common.Address) uint64 {
stateObject := stateDB.getStateObject(addr)
// GetNonce ...
func (db *DB) GetNonce(addr common.Address) uint64 {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.Nonce()
}
@ -228,34 +225,34 @@ func (stateDB *DB) GetNonce(addr common.Address) uint64 {
return 0
}
// GetCode returns code of a given address.
func (stateDB *DB) GetCode(addr common.Address) []byte {
stateObject := stateDB.getStateObject(addr)
// GetCode ...
func (db *DB) GetCode(addr common.Address) []byte {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.Code(stateDB.db)
return stateObject.Code(db.db)
}
return nil
}
// GetCodeSize returns code size of a given address in stateDB.
func (stateDB *DB) GetCodeSize(addr common.Address) int {
stateObject := stateDB.getStateObject(addr)
// GetCodeSize ...
func (db *DB) GetCodeSize(addr common.Address) int {
stateObject := db.getStateObject(addr)
if stateObject == nil {
return 0
}
if stateObject.code != nil {
return len(stateObject.code)
}
size, err := stateDB.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
size, err := db.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
if err != nil {
stateDB.setError(err)
db.setError(err)
}
return size
}
// GetCodeHash returns code hash of a given address.
func (stateDB *DB) GetCodeHash(addr common.Address) common.Hash {
stateObject := stateDB.getStateObject(addr)
// GetCodeHash ...
func (db *DB) GetCodeHash(addr common.Address) common.Hash {
stateObject := db.getStateObject(addr)
if stateObject == nil {
return common.Hash{}
}
@ -263,25 +260,25 @@ func (stateDB *DB) GetCodeHash(addr common.Address) common.Hash {
}
// GetState retrieves a value from the given account's storage trie.
func (stateDB *DB) GetState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr)
func (db *DB) GetState(addr common.Address, hash common.Hash) common.Hash {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.GetState(stateDB.db, hash)
return stateObject.GetState(db.db, hash)
}
return common.Hash{}
}
// GetProof returns the MerkleProof for a given Account
func (stateDB *DB) GetProof(a common.Address) ([][]byte, error) {
func (db *DB) GetProof(a common.Address) ([][]byte, error) {
var proof proofList
err := stateDB.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
err := db.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
return [][]byte(proof), err
}
// GetStorageProof returns the StorageProof for given key
func (stateDB *DB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
func (db *DB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
var proof proofList
trie := stateDB.StorageTrie(a)
trie := db.StorageTrie(a)
if trie == nil {
return proof, errors.New("storage trie for requested address does not exist")
}
@ -290,33 +287,33 @@ func (stateDB *DB) GetStorageProof(a common.Address, key common.Hash) ([][]byte,
}
// GetCommittedState retrieves a value from the given account's committed storage trie.
func (stateDB *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr)
func (db *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.GetCommittedState(stateDB.db, hash)
return stateObject.GetCommittedState(db.db, hash)
}
return common.Hash{}
}
// Database retrieves the low level database supporting the lower level trie ops.
func (stateDB *DB) Database() Database {
return stateDB.db
func (db *DB) Database() Database {
return db.db
}
// StorageTrie returns the storage trie of an account.
// The return value is a copy and is nil for non-existent accounts.
func (stateDB *DB) StorageTrie(addr common.Address) Trie {
stateObject := stateDB.getStateObject(addr)
func (db *DB) StorageTrie(addr common.Address) Trie {
stateObject := db.getStateObject(addr)
if stateObject == nil {
return nil
}
cpy := stateObject.deepCopy(stateDB)
return cpy.updateTrie(stateDB.db)
cpy := stateObject.deepCopy(db)
return cpy.updateTrie(db.db)
}
// HasSuicided checks if the state object of the given addr is suicided.
func (stateDB *DB) HasSuicided(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr)
// HasSuicided ...
func (db *DB) HasSuicided(addr common.Address) bool {
stateObject := db.getStateObject(addr)
if stateObject != nil {
return stateObject.suicided
}
@ -328,50 +325,50 @@ func (stateDB *DB) HasSuicided(addr common.Address) bool {
*/
// AddBalance adds amount to the account associated with addr.
func (stateDB *DB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr)
func (db *DB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.AddBalance(amount)
}
}
// SubBalance subtracts amount from the account associated with addr.
func (stateDB *DB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr)
func (db *DB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.SubBalance(amount)
}
}
// SetBalance sets balance of an address.
func (stateDB *DB) SetBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr)
// SetBalance ...
func (db *DB) SetBalance(addr common.Address, amount *big.Int) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetBalance(amount)
}
}
// SetNonce sets nonce of a given address.
func (stateDB *DB) SetNonce(addr common.Address, nonce uint64) {
stateObject := stateDB.GetOrNewStateObject(addr)
// SetNonce ...
func (db *DB) SetNonce(addr common.Address, nonce uint64) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetNonce(nonce)
}
}
// SetCode sets code of a given address.
func (stateDB *DB) SetCode(addr common.Address, code []byte) {
stateObject := stateDB.GetOrNewStateObject(addr)
// SetCode ...
func (db *DB) SetCode(addr common.Address, code []byte) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetCode(crypto.Keccak256Hash(code), code)
}
}
// SetState sets hash value of a given address.
func (stateDB *DB) SetState(addr common.Address, key, value common.Hash) {
stateObject := stateDB.GetOrNewStateObject(addr)
// SetState ...
func (db *DB) SetState(addr common.Address, key, value common.Hash) {
stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetState(stateDB.db, key, value)
stateObject.SetState(db.db, key, value)
}
}
@ -380,12 +377,12 @@ func (stateDB *DB) SetState(addr common.Address, key, value common.Hash) {
//
// The account's state object is still available until the state is committed,
// getStateObject will return a non-nil account after Suicide.
func (stateDB *DB) Suicide(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr)
func (db *DB) Suicide(addr common.Address) bool {
stateObject := db.getStateObject(addr)
if stateObject == nil {
return false
}
stateDB.journal.append(suicideChange{
db.journal.append(suicideChange{
account: &addr,
prev: stateObject.suicided,
prevbalance: new(big.Int).Set(stateObject.Balance()),
@ -401,26 +398,26 @@ func (stateDB *DB) Suicide(addr common.Address) bool {
//
// updateStateObject writes the given object to the trie.
func (stateDB *DB) updateStateObject(stateObject *Object) {
func (db *DB) updateStateObject(stateObject *Object) {
addr := stateObject.Address()
data, err := rlp.EncodeToBytes(stateObject)
if err != nil {
panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
}
stateDB.setError(stateDB.trie.TryUpdate(addr[:], data))
db.setError(db.trie.TryUpdate(addr[:], data))
}
// deleteStateObject removes the given object from the state trie.
func (stateDB *DB) deleteStateObject(stateObject *Object) {
func (db *DB) deleteStateObject(stateObject *Object) {
stateObject.deleted = true
addr := stateObject.Address()
stateDB.setError(stateDB.trie.TryDelete(addr[:]))
db.setError(db.trie.TryDelete(addr[:]))
}
// Retrieve a state object given by the address. Returns nil if not found.
func (stateDB *DB) getStateObject(addr common.Address) (stateObject *Object) {
func (db *DB) getStateObject(addr common.Address) (stateObject *Object) {
// Prefer 'live' objects.
if obj := stateDB.stateObjects[addr]; obj != nil {
if obj := db.stateObjects[addr]; obj != nil {
if obj.deleted {
return nil
}
@ -428,9 +425,9 @@ func (stateDB *DB) getStateObject(addr common.Address) (stateObject *Object) {
}
// Load the object from the database.
enc, err := stateDB.trie.TryGet(addr[:])
enc, err := db.trie.TryGet(addr[:])
if len(enc) == 0 {
stateDB.setError(err)
db.setError(err)
return nil
}
var data Account
@ -439,36 +436,36 @@ func (stateDB *DB) getStateObject(addr common.Address) (stateObject *Object) {
return nil
}
// Insert into the live set.
obj := newObject(stateDB, addr, data)
stateDB.setStateObject(obj)
obj := newObject(db, addr, data)
db.setStateObject(obj)
return obj
}
func (stateDB *DB) setStateObject(object *Object) {
stateDB.stateObjects[object.Address()] = object
func (db *DB) setStateObject(object *Object) {
db.stateObjects[object.Address()] = object
}
// GetOrNewStateObject retrieves a state object or create a new state object if nil.
func (stateDB *DB) GetOrNewStateObject(addr common.Address) *Object {
stateObject := stateDB.getStateObject(addr)
func (db *DB) GetOrNewStateObject(addr common.Address) *Object {
stateObject := db.getStateObject(addr)
if stateObject == nil || stateObject.deleted {
stateObject, _ = stateDB.createObject(addr)
stateObject, _ = db.createObject(addr)
}
return stateObject
}
// 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.
func (stateDB *DB) createObject(addr common.Address) (newobj, prev *Object) {
prev = stateDB.getStateObject(addr)
newobj = newObject(stateDB, addr, Account{})
func (db *DB) createObject(addr common.Address) (newobj, prev *Object) {
prev = db.getStateObject(addr)
newobj = newObject(db, addr, Account{})
newobj.setNonce(0) // sets the object to dirty
if prev == nil {
stateDB.journal.append(createObjectChange{account: &addr})
db.journal.append(createObjectChange{account: &addr})
} else {
stateDB.journal.append(resetObjectChange{prev: prev})
db.journal.append(resetObjectChange{prev: prev})
}
stateDB.setStateObject(newobj)
db.setStateObject(newobj)
return newobj, prev
}
@ -482,22 +479,22 @@ func (stateDB *DB) createObject(addr common.Address) (newobj, prev *Object) {
// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
//
// Carrying over the balance ensures that Ether doesn't disappear.
func (stateDB *DB) CreateAccount(addr common.Address) {
new, prev := stateDB.createObject(addr)
func (db *DB) CreateAccount(addr common.Address) {
newObj, prev := db.createObject(addr)
if prev != nil {
new.setBalance(prev.data.Balance)
newObj.setBalance(prev.data.Balance)
}
}
// ForEachStorage runs a function on every item in state DB.
func (stateDB *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
so := stateDB.getStateObject(addr)
// ForEachStorage ...
func (db *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
so := db.getStateObject(addr)
if so == nil {
return
}
it := trie.NewIterator(so.getTrie(stateDB.db).NodeIterator(nil))
it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
for it.Next() {
key := common.BytesToHash(stateDB.trie.GetKey(it.Key))
key := common.BytesToHash(db.trie.GetKey(it.Key))
if value, dirty := so.dirtyStorage[key]; dirty {
cb(key, value)
continue
@ -508,29 +505,26 @@ func (stateDB *DB) ForEachStorage(addr common.Address, cb func(key, value common
// Copy creates a deep, independent copy of the state.
// Snapshots of the copied state cannot be applied to the copy.
func (stateDB *DB) Copy() *DB {
stateDB.lock.Lock()
defer stateDB.lock.Unlock()
func (db *DB) Copy() *DB {
// Copy all the basic fields, initialize the memory ones
state := &DB{
db: stateDB.db,
trie: stateDB.db.CopyTrie(stateDB.trie),
stateObjects: make(map[common.Address]*Object, len(stateDB.journal.dirties)),
stateObjectsDirty: make(map[common.Address]struct{}, len(stateDB.journal.dirties)),
refund: stateDB.refund,
logs: make(map[common.Hash][]*types.Log, len(stateDB.logs)),
logSize: stateDB.logSize,
db: db.db,
trie: db.db.CopyTrie(db.trie),
stateObjects: make(map[common.Address]*Object, len(db.journal.dirties)),
stateObjectsDirty: make(map[common.Address]struct{}, len(db.journal.dirties)),
refund: db.refund,
logs: make(map[common.Hash][]*types.Log, len(db.logs)),
logSize: db.logSize,
preimages: make(map[common.Hash][]byte),
journal: newJournal(),
}
// Copy the dirty states, logs, and preimages
for addr := range stateDB.journal.dirties {
for addr := range db.journal.dirties {
// 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
// in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
// nil
if object, exist := stateDB.stateObjects[addr]; exist {
if object, exist := db.stateObjects[addr]; exist {
state.stateObjects[addr] = object.deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{}
}
@ -538,13 +532,13 @@ func (stateDB *DB) Copy() *DB {
// 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.
// Thus, here we iterate over stateObjects, to enable copies of copies
for addr := range stateDB.stateObjectsDirty {
for addr := range db.stateObjectsDirty {
if _, exist := state.stateObjects[addr]; !exist {
state.stateObjects[addr] = stateDB.stateObjects[addr].deepCopy(state)
state.stateObjects[addr] = db.stateObjects[addr].deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{}
}
}
for hash, logs := range stateDB.logs {
for hash, logs := range db.logs {
cpy := make([]*types.Log, len(logs))
for i, l := range logs {
cpy[i] = new(types.Log)
@ -552,132 +546,132 @@ func (stateDB *DB) Copy() *DB {
}
state.logs[hash] = cpy
}
for hash, preimage := range stateDB.preimages {
for hash, preimage := range db.preimages {
state.preimages[hash] = preimage
}
return state
}
// Snapshot returns an identifier for the current revision of the state.
func (stateDB *DB) Snapshot() int {
id := stateDB.nextRevisionID
stateDB.nextRevisionID++
stateDB.validRevisions = append(stateDB.validRevisions, revision{id, stateDB.journal.length()})
func (db *DB) Snapshot() int {
id := db.nextRevisionID
db.nextRevisionID++
db.validRevisions = append(db.validRevisions, revision{id, db.journal.length()})
return id
}
// RevertToSnapshot reverts all state changes made since the given revision.
func (stateDB *DB) RevertToSnapshot(revid int) {
func (db *DB) RevertToSnapshot(revid int) {
// Find the snapshot in the stack of valid snapshots.
idx := sort.Search(len(stateDB.validRevisions), func(i int) bool {
return stateDB.validRevisions[i].id >= revid
idx := sort.Search(len(db.validRevisions), func(i int) bool {
return db.validRevisions[i].id >= revid
})
if idx == len(stateDB.validRevisions) || stateDB.validRevisions[idx].id != revid {
if idx == len(db.validRevisions) || db.validRevisions[idx].id != revid {
panic(fmt.Errorf("revision id %v cannot be reverted", revid))
}
snapshot := stateDB.validRevisions[idx].journalIndex
snapshot := db.validRevisions[idx].journalIndex
// Replay the journal to undo changes and remove invalidated snapshots
stateDB.journal.revert(stateDB, snapshot)
stateDB.validRevisions = stateDB.validRevisions[:idx]
db.journal.revert(db, snapshot)
db.validRevisions = db.validRevisions[:idx]
}
// GetRefund returns the current value of the refund counter.
func (stateDB *DB) GetRefund() uint64 {
return stateDB.refund
func (db *DB) GetRefund() uint64 {
return db.refund
}
// Finalise finalises the state by removing the self destructed objects
// Finalise finalises the state by removing the db destructed objects
// and clears the journal as well as the refunds.
func (stateDB *DB) Finalise(deleteEmptyObjects bool) {
for addr := range stateDB.journal.dirties {
stateObject, exist := stateDB.stateObjects[addr]
func (db *DB) Finalise(deleteEmptyObjects bool) {
for addr := range db.journal.dirties {
stateObject, exist := db.stateObjects[addr]
if !exist {
// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
// it will persist in the journal even though the journal is reverted. In this special circumstance,
// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
// it may exist in `db.journal.dirties` but not in `db.stateObjects`.
// Thus, we can safely ignore it here
continue
}
if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
stateDB.deleteStateObject(stateObject)
db.deleteStateObject(stateObject)
} else {
stateObject.updateRoot(stateDB.db)
stateDB.updateStateObject(stateObject)
stateObject.updateRoot(db.db)
db.updateStateObject(stateObject)
}
stateDB.stateObjectsDirty[addr] = struct{}{}
db.stateObjectsDirty[addr] = struct{}{}
}
// Invalidate journal because reverting across transactions is not allowed.
stateDB.clearJournalAndRefund()
db.clearJournalAndRefund()
}
// IntermediateRoot computes the current root hash of the state trie.
// It is called in between transactions to get the root hash that
// goes into transaction receipts.
func (stateDB *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
stateDB.Finalise(deleteEmptyObjects)
return stateDB.trie.Hash()
func (db *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
db.Finalise(deleteEmptyObjects)
return db.trie.Hash()
}
// Prepare sets the current transaction hash and index and block hash which is
// used when the EVM emits new state logs.
func (stateDB *DB) Prepare(thash, bhash common.Hash, ti int) {
stateDB.thash = thash
stateDB.bhash = bhash
stateDB.txIndex = ti
func (db *DB) Prepare(thash, bhash common.Hash, ti int) {
db.thash = thash
db.bhash = bhash
db.txIndex = ti
}
func (stateDB *DB) clearJournalAndRefund() {
stateDB.journal = newJournal()
stateDB.validRevisions = stateDB.validRevisions[:0]
stateDB.refund = 0
func (db *DB) clearJournalAndRefund() {
db.journal = newJournal()
db.validRevisions = db.validRevisions[:0]
db.refund = 0
}
// Commit writes the state to the underlying in-memory trie database.
func (stateDB *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
defer stateDB.clearJournalAndRefund()
func (db *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
defer db.clearJournalAndRefund()
for addr := range stateDB.journal.dirties {
stateDB.stateObjectsDirty[addr] = struct{}{}
for addr := range db.journal.dirties {
db.stateObjectsDirty[addr] = struct{}{}
}
// Commit objects to the trie.
for addr, stateObject := range stateDB.stateObjects {
_, isDirty := stateDB.stateObjectsDirty[addr]
for addr, stateObject := range db.stateObjects {
_, isDirty := db.stateObjectsDirty[addr]
switch {
case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
// If the object has been removed, don't bother syncing it
// and just mark it for deletion in the trie.
stateDB.deleteStateObject(stateObject)
db.deleteStateObject(stateObject)
case isDirty:
// Write any contract code associated with the state object
if stateObject.code != nil && stateObject.dirtyCode {
stateDB.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code)
db.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code)
stateObject.dirtyCode = false
}
// Write any storage changes in the state object to its storage trie.
if err := stateObject.CommitTrie(stateDB.db); err != nil {
if err := stateObject.CommitTrie(db.db); err != nil {
return common.Hash{}, err
}
// Update the object in the main account trie.
stateDB.updateStateObject(stateObject)
db.updateStateObject(stateObject)
}
delete(stateDB.stateObjectsDirty, addr)
delete(db.stateObjectsDirty, addr)
}
// Write trie changes.
root, err = stateDB.trie.Commit(func(leaf []byte, parent common.Hash) error {
root, err = db.trie.Commit(func(leaf []byte, parent common.Hash) error {
var account Account
if err := rlp.DecodeBytes(leaf, &account); err != nil {
return nil
}
if account.Root != emptyState {
stateDB.db.TrieDB().Reference(account.Root, parent)
db.db.TrieDB().Reference(account.Root, parent)
}
code := common.BytesToHash(account.CodeHash)
if code != emptyCode {
stateDB.db.TrieDB().Reference(code, parent)
db.db.TrieDB().Reference(code, parent)
}
return nil
})

@ -33,7 +33,6 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
)
// Tests that updating a state trie does not leak any database writes prior to
@ -281,7 +280,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
action := actions[r.Intn(len(actions))]
var nameargs []string
if !action.noAddr {
nameargs = append(nameargs, common2.MustAddressToBech32(addr))
nameargs = append(nameargs, addr.Hex())
}
for _, i := range action.args {
action.args[i] = rand.Int63n(100)
@ -367,7 +366,7 @@ func (test *snapshotTest) checkEqual(state, checkstate *DB) error {
var err error
checkeq := func(op string, a, b interface{}) bool {
if err == nil && !reflect.DeepEqual(a, b) {
err = fmt.Errorf("got %s(%s) == %v, want %v", op, common2.MustAddressToBech32(addr), a, b)
err = fmt.Errorf("got %s(%s) == %v, want %v", op, addr.Hex(), a, b)
return false
}
return true

@ -89,13 +89,8 @@ type Header struct {
ShardID uint32 `json:"shardID" gencodec:"required"`
LastCommitSignature [96]byte `json:"lastCommitSignature" gencodec:"required"`
LastCommitBitmap []byte `json:"lastCommitBitmap" gencodec:"required"` // Contains which validator signed
Vrf [32]byte `json:"vrf"`
VrfProof [96]byte `json:"vrfProof"`
Vdf [258]byte `json:"vdf"`
VdfProof [258]byte `json:"vdfProof"`
ShardStateHash common.Hash `json:"shardStateRoot"`
ShardState []byte `json:"shardState"`
CrossLinks []byte `json:"crossLinks"`
}
// field type overrides for gencodec
@ -279,10 +274,10 @@ func CopyHeader(h *Header) *Header {
cpy.ShardState = make([]byte, len(h.ShardState))
copy(cpy.ShardState, h.ShardState)
}
if len(h.CrossLinks) > 0 {
cpy.CrossLinks = make([]byte, len(h.CrossLinks))
copy(cpy.CrossLinks, h.CrossLinks)
}
//if len(h.CrossLinks) > 0 {
// cpy.CrossLinks = make([]byte, len(h.CrossLinks))
// copy(cpy.CrossLinks, h.CrossLinks)
//}
return &cpy
}
@ -488,15 +483,15 @@ func Number(b1, b2 *Block) bool {
return b1.header.Number.Cmp(b2.header.Number) < 0
}
// AddVdf add vdf into block header
func (b *Block) AddVdf(vdf [258]byte) {
b.header.Vdf = vdf
}
// AddVrf add vrf into block header
func (b *Block) AddVrf(vrf [32]byte) {
b.header.Vrf = vrf
}
//// AddVdf add vdf into block header
//func (b *Block) AddVdf(vdf [258]byte) {
// b.header.Vdf = vdf
//}
//
//// AddVrf add vrf into block header
//func (b *Block) AddVrf(vrf [32]byte) {
// b.header.Vrf = vrf
//}
// AddShardState add shardState into block header
func (b *Block) AddShardState(shardState ShardState) error {

@ -22,8 +22,6 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
common2 "github.com/harmony-one/harmony/internal/common"
)
// precompiledTest defines the input/output pairs for precompiled contract tests.
@ -339,7 +337,7 @@ var bn256PairingTests = []precompiledTest{
}
func testPrecompiled(addr string, test precompiledTest, t *testing.T) {
p := PrecompiledContractsByzantium[common2.ParseAddr(addr)]
p := PrecompiledContractsByzantium[common.HexToAddress(addr)]
in := common.Hex2Bytes(test.input)
contract := NewContract(AccountRef(common.HexToAddress("1337")),
nil, new(big.Int), p.RequiredGas(in))
@ -356,7 +354,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) {
if test.noBenchmark {
return
}
p := PrecompiledContractsByzantium[common2.ParseAddr(addr)]
p := PrecompiledContractsByzantium[common.HexToAddress(addr)]
in := common.Hex2Bytes(test.input)
reqGas := p.RequiredGas(in)
contract := NewContract(AccountRef(common.HexToAddress("1337")),

@ -102,7 +102,7 @@ type Context struct {
type EVM struct {
// Context provides auxiliary blockchain related information
Context
// StateDB gives access to the underlying state
// DB gives access to the underlying state
StateDB StateDB
// Depth is the current call stack
depth int
@ -339,6 +339,12 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte
contract := NewContract(caller, to, new(big.Int), gas)
contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
// We do an AddBalance of zero here, just in order to trigger a touch.
// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
// but is the correct thing to do and matters on other networks, in tests, and potential
// future scenarios
evm.StateDB.AddBalance(addr, bigZero)
// When an error was returned by the EVM or when setting the creation code
// above we revert to the snapshot and consume any gas remaining. Additionally
// when we're in Homestead this also counts for code storage gas errors.

@ -121,7 +121,9 @@ func gasSStore(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, m
current = evm.StateDB.GetState(contract.Address(), common.BigToHash(x))
)
// The legacy gas metering only takes into consideration the current state
if !evm.chainRules.IsConstantinople {
// Legacy rules should be applied if we are in Petersburg (removal of EIP-1283)
// OR Constantinople is not active
if evm.chainRules.IsPetersburg || !evm.chainRules.IsConstantinople {
// This checks for 3 scenario's and calculates gas accordingly:
//
// 1. From a zero-value address to a non-zero value (NEW VALUE)

@ -544,7 +544,12 @@ func opExtCodeCopy(pc *uint64, interpreter *EVMInterpreter, contract *Contract,
// this account should be regarded as a non-existent account and zero should be returned.
func opExtCodeHash(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
slot := stack.peek()
slot.SetBytes(interpreter.evm.StateDB.GetCodeHash(common.BigToAddress(slot)).Bytes())
address := common.BigToAddress(slot)
if interpreter.evm.StateDB.Empty(address) {
slot.SetUint64(0)
} else {
slot.SetBytes(interpreter.evm.StateDB.GetCodeHash(address).Bytes())
}
return nil, nil
}

@ -99,16 +99,17 @@ func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
// the jump table was initialised. If it was not
// we'll set the default jump table.
if !cfg.JumpTable[STOP].valid {
switch {
case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
cfg.JumpTable = constantinopleInstructionSet
case evm.ChainConfig().IsByzantium(evm.BlockNumber):
cfg.JumpTable = byzantiumInstructionSet
case evm.ChainConfig().IsHomestead(evm.BlockNumber):
cfg.JumpTable = homesteadInstructionSet
default:
cfg.JumpTable = frontierInstructionSet
}
//switch {
//case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
// cfg.JumpTable = constantinopleInstructionSet
//case evm.ChainConfig().IsByzantium(evm.BlockNumber):
// cfg.JumpTable = byzantiumInstructionSet
//case evm.ChainConfig().IsHomestead(evm.BlockNumber):
// cfg.JumpTable = homesteadInstructionSet
//default:
// cfg.JumpTable = frontierInstructionSet
//}
cfg.JumpTable = constantinopleInstructionSet
}
return &EVMInterpreter{

@ -0,0 +1,89 @@
// Copyright 2017 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package vm
import (
"encoding/json"
"io"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
)
// JSONLogger ...
type JSONLogger struct {
encoder *json.Encoder
cfg *LogConfig
}
// NewJSONLogger creates a new EVM tracer that prints execution steps as JSON objects
// into the provided stream.
func NewJSONLogger(cfg *LogConfig, writer io.Writer) *JSONLogger {
l := &JSONLogger{json.NewEncoder(writer), cfg}
if l.cfg == nil {
l.cfg = &LogConfig{}
}
return l
}
// CaptureStart ...
func (l *JSONLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
return nil
}
// CaptureState outputs state information on the logger.
func (l *JSONLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
log := StructLog{
Pc: pc,
Op: op,
Gas: gas,
GasCost: cost,
MemorySize: memory.Len(),
Storage: nil,
Depth: depth,
RefundCounter: env.StateDB.GetRefund(),
Err: err,
}
if !l.cfg.DisableMemory {
log.Memory = memory.Data()
}
if !l.cfg.DisableStack {
log.Stack = stack.Data()
}
return l.encoder.Encode(log)
}
// CaptureFault outputs state information on the logger.
func (l *JSONLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
return nil
}
// CaptureEnd is triggered at end of execution.
func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
type endLog struct {
Output string `json:"output"`
GasUsed math.HexOrDecimal64 `json:"gasUsed"`
Time time.Duration `json:"time"`
Err string `json:"error,omitempty"`
}
if err != nil {
return l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, err.Error()})
}
return l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, ""})
}

@ -46,10 +46,7 @@ type dummyStatedb struct {
state.DB
}
// GetRefund ...
func (*dummyStatedb) GetRefund() uint64 {
return 1337
}
func (*dummyStatedb) GetRefund() uint64 { return 1337 }
func TestStoreCapture(t *testing.T) {
var (

@ -22,7 +22,7 @@ import (
"github.com/harmony-one/harmony/core/vm"
)
// NewEnv returns new EVM.
// NewEnv ...
func NewEnv(cfg *Config) *vm.EVM {
context := vm.Context{
CanTransfer: core.CanTransfer,

@ -149,7 +149,6 @@ func BenchmarkCall(b *testing.B) {
}
}
}
func benchmarkEVMCreate(bench *testing.B, code string) {
var (
statedb, _ = state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))

@ -33,7 +33,8 @@ func (dRand *DRand) WaitForEpochBlock(blockChannel chan *types.Block, stopChan c
if core.IsEpochLastBlock(newBlock) {
dRand.init(newBlock)
}
pRnd := newBlock.Header().Vrf
// TODO: use real vrf
pRnd := [32]byte{} //newBlock.Header().Vrf
zeros := [32]byte{}
if core.IsEpochBlock(newBlock) && !bytes.Equal(pRnd[:], zeros[:]) {
// The epoch block should contain the randomness preimage pRnd

@ -40,7 +40,7 @@ type Backend interface {
GetBlock(ctx context.Context, blockHash common.Hash) (*types.Block, error)
GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
// GetTd(blockHash common.Hash) *big.Int
// GetEVM(ctx context.Context, msg core.Message, state *state.StateDB, header *types.Header) (*vm.EVM, func() error, error)
// GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *types.Header) (*vm.EVM, func() error, error)
SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription

@ -1,9 +1,10 @@
package shardchain
import (
"math/big"
"sync"
"github.com/harmony-one/harmony/internal/configs/node"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb"
@ -102,7 +103,7 @@ func (sc *CollectionImpl) ShardChain(shardID uint32, networkType nodeconfig.Netw
chainConfig = *params.TestnetChainConfig
}
//chainConfig.ChainID = big.NewInt(int64(shardID))
chainConfig.ChainID = big.NewInt(int64(shardID))
bc, err := core.NewBlockChain(
db, cacheConfig, &chainConfig, sc.engine, vm.Config{}, nil,

@ -18,6 +18,7 @@ import (
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/genesis"
"github.com/harmony-one/harmony/internal/utils"
)
@ -127,6 +128,9 @@ func (node *Node) QueryStakeInfo() *structs.StakeInfoReturnValue {
}
func (node *Node) getDeployedStakingContract() common.Address {
if node.NodeConfig.GetNetworkType() == nodeconfig.Mainnet {
return common.Address{}
}
return node.StakingContractAddress
}
@ -169,6 +173,9 @@ func (node *Node) AddFaucetContractToPendingTransactions() {
// CallFaucetContract invokes the faucet contract to give the walletAddress initial money
func (node *Node) CallFaucetContract(address common.Address) common.Hash {
if node.NodeConfig.GetNetworkType() == nodeconfig.Mainnet {
return common.Hash{}
}
// Temporary code to workaround explorer issue for searching new addresses (https://github.com/harmony-one/harmony/issues/503)
nonce := atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1)
tx, _ := types.SignTx(types.NewTransaction(nonce-1, address, node.Consensus.ShardID, big.NewInt(0), params.TxGasContractCreation*10, nil, nil), types.HomesteadSigner{}, node.ContractDeployerKey)

@ -204,7 +204,7 @@ type Node struct {
// Blockchain returns the blockchain for the node's current shard.
func (node *Node) Blockchain() *core.BlockChain {
shardID := node.Consensus.ShardID
shardID := node.NodeConfig.ShardID
bc, err := node.shardChains.ShardChain(shardID, node.NodeConfig.GetNetworkType())
if err != nil {
err = ctxerror.New("cannot get shard chain", "shardID", shardID).

@ -57,7 +57,7 @@ func (gi *genesisInitializer) InitChainDB(db ethdb.Database, shardID uint32) err
func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardState types.ShardState) {
utils.GetLogger().Info("setting up a brand new chain database",
"shardID", shardID)
if shardID == node.Consensus.ShardID {
if shardID == node.NodeConfig.ShardID {
node.isFirstTime = true
}
@ -93,7 +93,7 @@ func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardSt
// Initialize shard state
// TODO: add ShardID into chainconfig and change ChainID to NetworkID
//chainConfig.ChainID = big.NewInt(int64(shardID)) // Use ChainID as piggybacked ShardID
chainConfig.ChainID = big.NewInt(int64(shardID)) // Use ChainID as piggybacked ShardID
gspec := core.Genesis{
Config: &chainConfig,

@ -266,6 +266,11 @@ func (node *Node) BroadcastNewBlock(newBlock *types.Block) {
func (node *Node) VerifyNewBlock(newBlock *types.Block) error {
// TODO ek – where do we verify parent-child invariants,
// e.g. "child.Number == child.IsGenesis() ? 0 : parent.Number+1"?
if newBlock.ShardID() != node.Blockchain().ShardID() {
return ctxerror.New("wrong shard ID",
"my shard ID", node.Blockchain().ShardID(),
"new block's shard ID", newBlock.ShardID())
}
err := node.Blockchain().ValidateNewBlock(newBlock)
if err != nil {
return ctxerror.New("cannot ValidateNewBlock",
@ -275,7 +280,7 @@ func (node *Node) VerifyNewBlock(newBlock *types.Block) error {
}
// TODO: verify the vrf randomness
_ = newBlock.Header().Vrf
// _ = newBlock.Header().Vrf
err = node.validateNewShardState(newBlock, &node.CurrentStakes)
if err != nil {
@ -423,35 +428,38 @@ func (node *Node) PostConsensusProcessing(newBlock *types.Block) {
if node.Consensus.ShardID == 0 {
// TODO: enable drand only for beacon chain
// ConfirmedBlockChannel which is listened by drand leader who will initiate DRG if its a epoch block (first block of a epoch)
if node.DRand != nil {
go func() {
node.ConfirmedBlockChannel <- newBlock
}()
}
//if node.DRand != nil {
// go func() {
// node.ConfirmedBlockChannel <- newBlock
// }()
//}
// TODO: enable staking
// TODO: update staking information once per epoch.
node.UpdateStakingList(node.QueryStakeInfo())
node.printStakingList()
}
newBlockHeader := newBlock.Header()
if newBlockHeader.ShardStateHash != (common.Hash{}) {
if node.Consensus.ShardID == 0 {
// TODO ek – this is a temp hack until beacon chain sync is fixed
// End-of-epoch block on beacon chain; block's EpochState is the
// master resharding table. Broadcast it to the network.
if err := node.broadcastEpochShardState(newBlock); err != nil {
e := ctxerror.New("cannot broadcast shard state").WithCause(err)
ctxerror.Log15(utils.GetLogInstance().Error, e)
}
}
shardState, err := newBlockHeader.GetShardState()
if err != nil {
e := ctxerror.New("cannot get shard state from header").WithCause(err)
ctxerror.Log15(utils.GetLogInstance().Error, e)
} else {
node.transitionIntoNextEpoch(shardState)
}
}
//node.UpdateStakingList(node.QueryStakeInfo())
//node.printStakingList()
}
// TODO: enable shard state update
//newBlockHeader := newBlock.Header()
//if newBlockHeader.ShardStateHash != (common.Hash{}) {
// if node.Consensus.ShardID == 0 {
// // TODO ek – this is a temp hack until beacon chain sync is fixed
// // End-of-epoch block on beacon chain; block's EpochState is the
// // master resharding table. Broadcast it to the network.
// if err := node.broadcastEpochShardState(newBlock); err != nil {
// e := ctxerror.New("cannot broadcast shard state").WithCause(err)
// ctxerror.Log15(utils.GetLogInstance().Error, e)
// }
// }
// shardState, err := newBlockHeader.GetShardState()
// if err != nil {
// e := ctxerror.New("cannot get shard state from header").WithCause(err)
// ctxerror.Log15(utils.GetLogInstance().Error, e)
// } else {
// node.transitionIntoNextEpoch(shardState)
// }
//}
}
}
@ -477,7 +485,7 @@ func (node *Node) AddNewBlock(newBlock *types.Block) {
if err != nil {
utils.GetLogInstance().Debug("Error Adding new block to blockchain", "blockNum", blockNum, "parentHash", newBlock.Header().ParentHash, "hash", newBlock.Header().Hash(), "Error", err)
} else {
utils.GetLogInstance().Info("Added New Block to Blockchain!!!", "blockNum", blockNum, "hash", newBlock.Header().Hash(), "by node", node.SelfPeer)
utils.GetLogInstance().Info("Added New Block to Blockchain!!!", "blockNum", blockNum, "hash", newBlock.Header().Hash().Hex())
}
}

Loading…
Cancel
Save