Update EVM to latest constantinople

pull/1133/head
Rongjian Lan 6 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 // Verify the randomness
_ = blockHash _ = blockHash
consensus.getLogger().Info("[ConsensusMainLoop] Adding randomness into new block", "rnd", rnd) 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 { } else {
//consensus.getLogger().Info("Failed to get randomness", "error", err) //consensus.getLogger().Info("Failed to get randomness", "error", err)
} }

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

@ -26,7 +26,7 @@ import (
lru "github.com/hashicorp/golang-lru" 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) var MaxTrieCacheGen = uint16(120)
const ( const (
@ -72,13 +72,19 @@ type Trie interface {
} }
// NewDatabase creates a backing store for state. The returned database is safe for // 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 // concurrent use and retains a few recent expanded trie nodes in memory. To keep
// intermediate trie-node memory pool between the low level storage layer and the // more historical state in memory, use the NewDatabaseWithCache constructor.
// high level trie abstraction.
func NewDatabase(db ethdb.Database) Database { 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) csc, _ := lru.New(codeSizeCacheSize)
return &cachingDB{ return &cachingDB{
db: trie.NewDatabase(db), db: trie.NewDatabaseWithCache(db, cache),
codeSizeCache: csc, codeSizeCache: csc,
} }
} }

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

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

@ -33,7 +33,7 @@ var emptyCodeHash = crypto.Keccak256(nil)
type Code []byte type Code []byte
func (code Code) String() string { func (code Code) String() string {
return string(code) //strings.Join(Disassemble(self), " ") return string(code) //strings.Join(Disassemble(so), " ")
} }
// Storage ... // Storage ...
@ -43,10 +43,11 @@ func (storage Storage) String() (str string) {
for key, value := range storage { for key, value := range storage {
str += fmt.Sprintf("%X : %X\n", key, value) str += fmt.Sprintf("%X : %X\n", key, value)
} }
return return
} }
// Copy returns a copy of Storage // Copy ...
func (storage Storage) Copy() Storage { func (storage Storage) Copy() Storage {
cpy := make(Storage) cpy := make(Storage)
for key, value := range storage { for key, value := range storage {
@ -91,8 +92,8 @@ type Object struct {
} }
// empty returns whether the account is considered empty. // empty returns whether the account is considered empty.
func (s *Object) empty() bool { func (so *Object) 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.
@ -123,194 +124,193 @@ func newObject(db *DB, address common.Address, data Account) *Object {
} }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
func (s *Object) EncodeRLP(w io.Writer) error { func (so *Object) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, s.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 (s *Object) setError(err error) { func (so *Object) setError(err error) {
if s.dbErr == nil { if so.dbErr == nil {
s.dbErr = err so.dbErr = err
} }
} }
func (s *Object) markSuicided() { func (so *Object) markSuicided() {
s.suicided = true so.suicided = true
} }
func (s *Object) touch() { func (so *Object) touch() {
s.db.journal.append(touchChange{ so.db.journal.append(touchChange{
account: &s.address, account: &so.address,
}) })
if s.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.
s.db.journal.dirty(s.address) so.db.journal.dirty(so.address)
} }
} }
func (s *Object) getTrie(db Database) Trie { func (so *Object) getTrie(db Database) Trie {
if s.trie == nil { if so.trie == nil {
var err error 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 { if err != nil {
s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) so.trie, _ = db.OpenStorageTrie(so.addrHash, common.Hash{})
s.setError(fmt.Errorf("can't create storage trie: %v", err)) 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. // 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 // If we have a dirty value for this state entry, return it
value, dirty := s.dirtyStorage[key] value, dirty := so.dirtyStorage[key]
if dirty { if dirty {
return value return value
} }
// Otherwise return the entry's original 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. // 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 // If we have the original value cached, return that
value, cached := s.originStorage[key] value, cached := so.originStorage[key]
if cached { if cached {
return value return value
} }
// Otherwise load the value from the database // Otherwise load the value from the database
enc, err := s.getTrie(db).TryGet(key[:]) enc, err := so.getTrie(db).TryGet(key[:])
if err != nil { if err != nil {
s.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 {
s.setError(err) so.setError(err)
} }
value.SetBytes(content) value.SetBytes(content)
} }
s.originStorage[key] = value so.originStorage[key] = value
return value return value
} }
// SetState updates a value in account storage. // 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 // 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 { if prev == value {
return return
} }
// New value is different, update and journal the change // New value is different, update and journal the change
s.db.journal.append(storageChange{ so.db.journal.append(storageChange{
account: &s.address, account: &so.address,
key: key, key: key,
prevalue: prev, prevalue: prev,
}) })
s.setState(key, value) so.setState(key, value)
} }
func (s *Object) setState(key, value common.Hash) { func (so *Object) setState(key, value common.Hash) {
s.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 (s *Object) updateTrie(db Database) Trie { func (so *Object) updateTrie(db Database) Trie {
tr := s.getTrie(db) tr := so.getTrie(db)
for key, value := range s.dirtyStorage { for key, value := range so.dirtyStorage {
delete(s.dirtyStorage, key) delete(so.dirtyStorage, key)
// Skip noop changes, persist actual changes // Skip noop changes, persist actual changes
if value == s.originStorage[key] { if value == so.originStorage[key] {
continue continue
} }
s.originStorage[key] = value so.originStorage[key] = value
if (value == common.Hash{}) { if (value == common.Hash{}) {
s.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"))
s.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 (s *Object) updateRoot(db Database) { func (so *Object) updateRoot(db Database) {
s.updateTrie(db) so.updateTrie(db)
s.data.Root = s.trie.Hash() so.data.Root = so.trie.Hash()
} }
// CommitTrie the storage trie of the object to db. // CommitTrie the storage trie of the object to db.
// This updates the trie root. // This updates the trie root.
func (s *Object) CommitTrie(db Database) error { func (so *Object) CommitTrie(db Database) error {
s.updateTrie(db) so.updateTrie(db)
if s.dbErr != nil { if so.dbErr != nil {
return s.dbErr return so.dbErr
} }
root, err := s.trie.Commit(nil) root, err := so.trie.Commit(nil)
if err == nil { if err == nil {
s.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 (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 // 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 s.empty() { if so.empty() {
s.touch() so.touch()
} }
return 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. // 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 (s *Object) SubBalance(amount *big.Int) { func (so *Object) SubBalance(amount *big.Int) {
if amount.Sign() == 0 { if amount.Sign() == 0 {
return 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. // SetBalance ...
func (s *Object) SetBalance(amount *big.Int) { func (so *Object) SetBalance(amount *big.Int) {
s.db.journal.append(balanceChange{ so.db.journal.append(balanceChange{
account: &s.address, account: &so.address,
prev: new(big.Int).Set(s.data.Balance), prev: new(big.Int).Set(so.data.Balance),
}) })
s.setBalance(amount) so.setBalance(amount)
} }
func (s *Object) setBalance(amount *big.Int) { func (so *Object) setBalance(amount *big.Int) {
s.data.Balance = amount so.data.Balance = amount
} }
// ReturnGas returns the gas back to the origin. // ReturnGas returns the gas back to the origin. Used by the Virtual machine or Closures
// Used by the Virtual machine or Closures func (so *Object) ReturnGas(gas *big.Int) {}
func (s *Object) ReturnGas(gas *big.Int) {}
func (s *Object) deepCopy(db *DB) *Object { func (so *Object) deepCopy(db *DB) *Object {
stateObject := newObject(db, s.address, s.data) stateObject := newObject(db, so.address, so.data)
if s.trie != nil { if so.trie != nil {
stateObject.trie = db.db.CopyTrie(s.trie) stateObject.trie = db.db.CopyTrie(so.trie)
} }
stateObject.code = s.code stateObject.code = so.code
stateObject.dirtyStorage = s.dirtyStorage.Copy() stateObject.dirtyStorage = so.dirtyStorage.Copy()
stateObject.originStorage = s.originStorage.Copy() stateObject.originStorage = so.originStorage.Copy()
stateObject.suicided = s.suicided stateObject.suicided = so.suicided
stateObject.dirtyCode = s.dirtyCode stateObject.dirtyCode = so.dirtyCode
stateObject.deleted = s.deleted stateObject.deleted = so.deleted
return stateObject return stateObject
} }
@ -318,75 +318,75 @@ func (s *Object) deepCopy(db *DB) *Object {
// Attribute accessors // Attribute accessors
// //
// Address returns the address of the contract/account. // Address returns the address of the contract/account
func (s *Object) Address() common.Address { func (so *Object) Address() common.Address {
return s.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 (s *Object) Code(db Database) []byte { func (so *Object) Code(db Database) []byte {
if s.code != nil { if so.code != nil {
return s.code return so.code
} }
if bytes.Equal(s.CodeHash(), emptyCodeHash) { if bytes.Equal(so.CodeHash(), emptyCodeHash) {
return nil 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 { 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 return code
} }
// SetCode sets the object's contract code to the given code. // SetCode ...
func (s *Object) SetCode(codeHash common.Hash, code []byte) { func (so *Object) SetCode(codeHash common.Hash, code []byte) {
prevcode := s.Code(s.db.db) prevcode := so.Code(so.db.db)
s.db.journal.append(codeChange{ so.db.journal.append(codeChange{
account: &s.address, account: &so.address,
prevhash: s.CodeHash(), prevhash: so.CodeHash(),
prevcode: prevcode, prevcode: prevcode,
}) })
s.setCode(codeHash, code) so.setCode(codeHash, code)
} }
func (s *Object) setCode(codeHash common.Hash, code []byte) { func (so *Object) setCode(codeHash common.Hash, code []byte) {
s.code = code so.code = code
s.data.CodeHash = codeHash[:] so.data.CodeHash = codeHash[:]
s.dirtyCode = true so.dirtyCode = true
} }
// SetNonce sets the account's nonce to the given nonce value. // SetNonce ...
func (s *Object) SetNonce(nonce uint64) { func (so *Object) SetNonce(nonce uint64) {
s.db.journal.append(nonceChange{ so.db.journal.append(nonceChange{
account: &s.address, account: &so.address,
prev: s.data.Nonce, prev: so.data.Nonce,
}) })
s.setNonce(nonce) so.setNonce(nonce)
} }
func (s *Object) setNonce(nonce uint64) { func (so *Object) setNonce(nonce uint64) {
s.data.Nonce = nonce so.data.Nonce = nonce
} }
// CodeHash returns the hash of the account's contract code. // CodeHash ...
func (s *Object) CodeHash() []byte { func (so *Object) CodeHash() []byte {
return s.data.CodeHash return so.data.CodeHash
} }
// Balance returns the account balance. // Balance ...
func (s *Object) Balance() *big.Int { func (so *Object) Balance() *big.Int {
return s.data.Balance return so.data.Balance
} }
// Nonce returns the account nonce. // Nonce ...
func (s *Object) Nonce() uint64 { func (so *Object) Nonce() uint64 {
return s.data.Nonce 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 // as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome. // interface. Interfaces are awesome.
func (s *Object) Value() *big.Int { func (so *Object) Value() *big.Int {
panic("Value on Object should never be called") panic("Value on Object should never be called")
} }

@ -22,7 +22,6 @@ import (
"fmt" "fmt"
"math/big" "math/big"
"sort" "sort"
"sync"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
@ -87,8 +86,6 @@ type DB struct {
journal *journal journal *journal
validRevisions []revision validRevisions []revision
nextRevisionID int nextRevisionID int
lock sync.Mutex
} }
// New creates a new state from a given trie. // 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. // setError remembers the first non-nil error it is called with.
func (stateDB *DB) setError(err error) { func (db *DB) setError(err error) {
if stateDB.dbErr == nil { if db.dbErr == nil {
stateDB.dbErr = err db.dbErr = err
} }
} }
func (stateDB *DB) Error() error { func (db *DB) Error() error {
return stateDB.dbErr return db.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 (stateDB *DB) Reset(root common.Hash) error { func (db *DB) Reset(root common.Hash) error {
tr, err := stateDB.db.OpenTrie(root) tr, err := db.db.OpenTrie(root)
if err != nil { if err != nil {
return err return err
} }
stateDB.trie = tr db.trie = tr
stateDB.stateObjects = make(map[common.Address]*Object) db.stateObjects = make(map[common.Address]*Object)
stateDB.stateObjectsDirty = make(map[common.Address]struct{}) db.stateObjectsDirty = make(map[common.Address]struct{})
stateDB.thash = common.Hash{} db.thash = common.Hash{}
stateDB.bhash = common.Hash{} db.bhash = common.Hash{}
stateDB.txIndex = 0 db.txIndex = 0
stateDB.logs = make(map[common.Hash][]*types.Log) db.logs = make(map[common.Hash][]*types.Log)
stateDB.logSize = 0 db.logSize = 0
stateDB.preimages = make(map[common.Hash][]byte) db.preimages = make(map[common.Hash][]byte)
stateDB.clearJournalAndRefund() db.clearJournalAndRefund()
return nil return nil
} }
// AddLog adds logs into stateDB // AddLog ...
func (stateDB *DB) AddLog(log *types.Log) { func (db *DB) AddLog(log *types.Log) {
stateDB.journal.append(addLogChange{txhash: stateDB.thash}) db.journal.append(addLogChange{txhash: db.thash})
log.TxHash = stateDB.thash log.TxHash = db.thash
log.BlockHash = stateDB.bhash log.BlockHash = db.bhash
log.TxIndex = uint(stateDB.txIndex) log.TxIndex = uint(db.txIndex)
log.Index = stateDB.logSize log.Index = db.logSize
stateDB.logs[stateDB.thash] = append(stateDB.logs[stateDB.thash], log) db.logs[db.thash] = append(db.logs[db.thash], log)
stateDB.logSize++ db.logSize++
} }
// GetLogs gets logs from stateDB given a hash // GetLogs ...
func (stateDB *DB) GetLogs(hash common.Hash) []*types.Log { func (db *DB) GetLogs(hash common.Hash) []*types.Log {
return stateDB.logs[hash] return db.logs[hash]
} }
// Logs returns a list of Log. // Logs ...
func (stateDB *DB) Logs() []*types.Log { func (db *DB) Logs() []*types.Log {
var logs []*types.Log var logs []*types.Log
for _, lgs := range stateDB.logs { for _, lgs := range db.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 (stateDB *DB) AddPreimage(hash common.Hash, preimage []byte) { func (db *DB) AddPreimage(hash common.Hash, preimage []byte) {
if _, ok := stateDB.preimages[hash]; !ok { if _, ok := db.preimages[hash]; !ok {
stateDB.journal.append(addPreimageChange{hash: hash}) db.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage)) pi := make([]byte, len(preimage))
copy(pi, preimage) copy(pi, preimage)
stateDB.preimages[hash] = pi db.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 (stateDB *DB) Preimages() map[common.Hash][]byte { func (db *DB) Preimages() map[common.Hash][]byte {
return stateDB.preimages return db.preimages
} }
// AddRefund adds gas to the refund counter // AddRefund adds gas to the refund counter
func (stateDB *DB) AddRefund(gas uint64) { func (db *DB) AddRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund}) db.journal.append(refundChange{prev: db.refund})
stateDB.refund += gas db.refund += gas
} }
// SubRefund removes gas from the refund counter. // SubRefund removes gas from the refund counter.
// This method will panic if the refund counter goes below zero // This method will panic if the refund counter goes below zero
func (stateDB *DB) SubRefund(gas uint64) { func (db *DB) SubRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund}) db.journal.append(refundChange{prev: db.refund})
if gas > stateDB.refund { if gas > db.refund {
panic("Refund counter below zero") panic("Refund counter below zero")
} }
stateDB.refund -= gas db.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 (stateDB *DB) Exist(addr common.Address) bool { func (db *DB) Exist(addr common.Address) bool {
return stateDB.getStateObject(addr) != nil return db.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 (stateDB *DB) Empty(addr common.Address) bool { func (db *DB) Empty(addr common.Address) bool {
so := stateDB.getStateObject(addr) so := db.getStateObject(addr)
return so == nil || so.empty() return so == nil || so.empty()
} }
// GetBalance retrieves 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 (stateDB *DB) GetBalance(addr common.Address) *big.Int { func (db *DB) GetBalance(addr common.Address) *big.Int {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Balance() return stateObject.Balance()
} }
return common.Big0 return common.Big0
} }
// GetNonce returns the nonce of the given address. // GetNonce ...
func (stateDB *DB) GetNonce(addr common.Address) uint64 { func (db *DB) GetNonce(addr common.Address) uint64 {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Nonce() return stateObject.Nonce()
} }
@ -228,34 +225,34 @@ func (stateDB *DB) GetNonce(addr common.Address) uint64 {
return 0 return 0
} }
// GetCode returns code of a given address. // GetCode ...
func (stateDB *DB) GetCode(addr common.Address) []byte { func (db *DB) GetCode(addr common.Address) []byte {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Code(stateDB.db) return stateObject.Code(db.db)
} }
return nil return nil
} }
// GetCodeSize returns code size of a given address in stateDB. // GetCodeSize ...
func (stateDB *DB) GetCodeSize(addr common.Address) int { func (db *DB) GetCodeSize(addr common.Address) int {
stateObject := stateDB.getStateObject(addr) stateObject := db.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 := stateDB.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) size, err := db.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
if err != nil { if err != nil {
stateDB.setError(err) db.setError(err)
} }
return size return size
} }
// GetCodeHash returns code hash of a given address. // GetCodeHash ...
func (stateDB *DB) GetCodeHash(addr common.Address) common.Hash { func (db *DB) GetCodeHash(addr common.Address) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return common.Hash{} 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. // GetState retrieves a value from the given account's storage trie.
func (stateDB *DB) GetState(addr common.Address, hash common.Hash) common.Hash { func (db *DB) GetState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.GetState(stateDB.db, hash) return stateObject.GetState(db.db, hash)
} }
return common.Hash{} return common.Hash{}
} }
// GetProof returns the MerkleProof for a given Account // 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 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 return [][]byte(proof), err
} }
// GetStorageProof returns the StorageProof for given key // 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 var proof proofList
trie := stateDB.StorageTrie(a) trie := db.StorageTrie(a)
if trie == nil { if trie == nil {
return proof, errors.New("storage trie for requested address does not exist") 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. // GetCommittedState retrieves a value from the given account's committed storage trie.
func (stateDB *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { func (db *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.GetCommittedState(stateDB.db, hash) return stateObject.GetCommittedState(db.db, hash)
} }
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 (stateDB *DB) Database() Database { func (db *DB) Database() Database {
return stateDB.db return db.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 (stateDB *DB) StorageTrie(addr common.Address) Trie { func (db *DB) StorageTrie(addr common.Address) Trie {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return nil return nil
} }
cpy := stateObject.deepCopy(stateDB) cpy := stateObject.deepCopy(db)
return cpy.updateTrie(stateDB.db) return cpy.updateTrie(db.db)
} }
// HasSuicided checks if the state object of the given addr is suicided. // HasSuicided ...
func (stateDB *DB) HasSuicided(addr common.Address) bool { func (db *DB) HasSuicided(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.suicided return stateObject.suicided
} }
@ -328,50 +325,50 @@ func (stateDB *DB) HasSuicided(addr common.Address) bool {
*/ */
// AddBalance adds amount to the account associated with addr. // AddBalance adds amount to the account associated with addr.
func (stateDB *DB) AddBalance(addr common.Address, amount *big.Int) { func (db *DB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.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 (stateDB *DB) SubBalance(addr common.Address, amount *big.Int) { func (db *DB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SubBalance(amount) stateObject.SubBalance(amount)
} }
} }
// SetBalance sets balance of an address. // SetBalance ...
func (stateDB *DB) SetBalance(addr common.Address, amount *big.Int) { func (db *DB) SetBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetBalance(amount) stateObject.SetBalance(amount)
} }
} }
// SetNonce sets nonce of a given address. // SetNonce ...
func (stateDB *DB) SetNonce(addr common.Address, nonce uint64) { func (db *DB) SetNonce(addr common.Address, nonce uint64) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetNonce(nonce) stateObject.SetNonce(nonce)
} }
} }
// SetCode sets code of a given address. // SetCode ...
func (stateDB *DB) SetCode(addr common.Address, code []byte) { func (db *DB) SetCode(addr common.Address, code []byte) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetCode(crypto.Keccak256Hash(code), code) stateObject.SetCode(crypto.Keccak256Hash(code), code)
} }
} }
// SetState sets hash value of a given address. // SetState ...
func (stateDB *DB) SetState(addr common.Address, key, value common.Hash) { func (db *DB) SetState(addr common.Address, key, value common.Hash) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := db.GetOrNewStateObject(addr)
if stateObject != nil { 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, // 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 (stateDB *DB) Suicide(addr common.Address) bool { func (db *DB) Suicide(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return false return false
} }
stateDB.journal.append(suicideChange{ db.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()),
@ -401,26 +398,26 @@ func (stateDB *DB) Suicide(addr common.Address) bool {
// //
// updateStateObject writes the given object to the trie. // updateStateObject writes the given object to the trie.
func (stateDB *DB) updateStateObject(stateObject *Object) { func (db *DB) updateStateObject(stateObject *Object) {
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))
} }
stateDB.setError(stateDB.trie.TryUpdate(addr[:], data)) db.setError(db.trie.TryUpdate(addr[:], data))
} }
// deleteStateObject removes the given object from the state trie. // deleteStateObject removes the given object from the state trie.
func (stateDB *DB) deleteStateObject(stateObject *Object) { func (db *DB) deleteStateObject(stateObject *Object) {
stateObject.deleted = true stateObject.deleted = true
addr := stateObject.Address() 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. // 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. // Prefer 'live' objects.
if obj := stateDB.stateObjects[addr]; obj != nil { if obj := db.stateObjects[addr]; obj != nil {
if obj.deleted { if obj.deleted {
return nil return nil
} }
@ -428,9 +425,9 @@ func (stateDB *DB) getStateObject(addr common.Address) (stateObject *Object) {
} }
// Load the object from the database. // Load the object from the database.
enc, err := stateDB.trie.TryGet(addr[:]) enc, err := db.trie.TryGet(addr[:])
if len(enc) == 0 { if len(enc) == 0 {
stateDB.setError(err) db.setError(err)
return nil return nil
} }
var data Account var data Account
@ -439,36 +436,36 @@ func (stateDB *DB) getStateObject(addr common.Address) (stateObject *Object) {
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newObject(stateDB, addr, data) obj := newObject(db, addr, data)
stateDB.setStateObject(obj) db.setStateObject(obj)
return obj return obj
} }
func (stateDB *DB) setStateObject(object *Object) { func (db *DB) setStateObject(object *Object) {
stateDB.stateObjects[object.Address()] = object db.stateObjects[object.Address()] = object
} }
// GetOrNewStateObject retrieves a state object or create a new state object if nil. // GetOrNewStateObject retrieves a state object or create a new state object if nil.
func (stateDB *DB) GetOrNewStateObject(addr common.Address) *Object { func (db *DB) GetOrNewStateObject(addr common.Address) *Object {
stateObject := stateDB.getStateObject(addr) stateObject := db.getStateObject(addr)
if stateObject == nil || stateObject.deleted { if stateObject == nil || stateObject.deleted {
stateObject, _ = stateDB.createObject(addr) stateObject, _ = db.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 (stateDB *DB) createObject(addr common.Address) (newobj, prev *Object) { func (db *DB) createObject(addr common.Address) (newobj, prev *Object) {
prev = stateDB.getStateObject(addr) prev = db.getStateObject(addr)
newobj = newObject(stateDB, addr, Account{}) newobj = newObject(db, addr, Account{})
newobj.setNonce(0) // sets the object to dirty newobj.setNonce(0) // sets the object to dirty
if prev == nil { if prev == nil {
stateDB.journal.append(createObjectChange{account: &addr}) db.journal.append(createObjectChange{account: &addr})
} else { } else {
stateDB.journal.append(resetObjectChange{prev: prev}) db.journal.append(resetObjectChange{prev: prev})
} }
stateDB.setStateObject(newobj) db.setStateObject(newobj)
return newobj, prev 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) // 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 (stateDB *DB) CreateAccount(addr common.Address) { func (db *DB) CreateAccount(addr common.Address) {
new, prev := stateDB.createObject(addr) newObj, prev := db.createObject(addr)
if prev != nil { if prev != nil {
new.setBalance(prev.data.Balance) newObj.setBalance(prev.data.Balance)
} }
} }
// ForEachStorage runs a function on every item in state DB. // ForEachStorage ...
func (stateDB *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { func (db *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
so := stateDB.getStateObject(addr) so := db.getStateObject(addr)
if so == nil { if so == nil {
return return
} }
it := trie.NewIterator(so.getTrie(stateDB.db).NodeIterator(nil)) it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
for it.Next() { 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 { if value, dirty := so.dirtyStorage[key]; dirty {
cb(key, value) cb(key, value)
continue 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. // 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 (stateDB *DB) Copy() *DB { func (db *DB) Copy() *DB {
stateDB.lock.Lock()
defer stateDB.lock.Unlock()
// Copy all the basic fields, initialize the memory ones // Copy all the basic fields, initialize the memory ones
state := &DB{ state := &DB{
db: stateDB.db, db: db.db,
trie: stateDB.db.CopyTrie(stateDB.trie), trie: db.db.CopyTrie(db.trie),
stateObjects: make(map[common.Address]*Object, len(stateDB.journal.dirties)), stateObjects: make(map[common.Address]*Object, len(db.journal.dirties)),
stateObjectsDirty: make(map[common.Address]struct{}, len(stateDB.journal.dirties)), stateObjectsDirty: make(map[common.Address]struct{}, len(db.journal.dirties)),
refund: stateDB.refund, refund: db.refund,
logs: make(map[common.Hash][]*types.Log, len(stateDB.logs)), logs: make(map[common.Hash][]*types.Log, len(db.logs)),
logSize: stateDB.logSize, logSize: db.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 stateDB.journal.dirties { for addr := range db.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 := stateDB.stateObjects[addr]; exist { if object, exist := db.stateObjects[addr]; exist {
state.stateObjects[addr] = object.deepCopy(state) state.stateObjects[addr] = object.deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{} 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 // 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 stateDB.stateObjectsDirty { for addr := range db.stateObjectsDirty {
if _, exist := state.stateObjects[addr]; !exist { 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{}{} state.stateObjectsDirty[addr] = struct{}{}
} }
} }
for hash, logs := range stateDB.logs { for hash, logs := range db.logs {
cpy := make([]*types.Log, len(logs)) cpy := make([]*types.Log, len(logs))
for i, l := range logs { for i, l := range logs {
cpy[i] = new(types.Log) cpy[i] = new(types.Log)
@ -552,132 +546,132 @@ func (stateDB *DB) Copy() *DB {
} }
state.logs[hash] = cpy state.logs[hash] = cpy
} }
for hash, preimage := range stateDB.preimages { for hash, preimage := range db.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 (stateDB *DB) Snapshot() int { func (db *DB) Snapshot() int {
id := stateDB.nextRevisionID id := db.nextRevisionID
stateDB.nextRevisionID++ db.nextRevisionID++
stateDB.validRevisions = append(stateDB.validRevisions, revision{id, stateDB.journal.length()}) db.validRevisions = append(db.validRevisions, revision{id, db.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 (stateDB *DB) RevertToSnapshot(revid int) { func (db *DB) 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(stateDB.validRevisions), func(i int) bool { idx := sort.Search(len(db.validRevisions), func(i int) bool {
return stateDB.validRevisions[i].id >= revid 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)) 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 // Replay the journal to undo changes and remove invalidated snapshots
stateDB.journal.revert(stateDB, snapshot) db.journal.revert(db, snapshot)
stateDB.validRevisions = stateDB.validRevisions[:idx] db.validRevisions = db.validRevisions[:idx]
} }
// GetRefund returns the current value of the refund counter. // GetRefund returns the current value of the refund counter.
func (stateDB *DB) GetRefund() uint64 { func (db *DB) GetRefund() uint64 {
return stateDB.refund 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. // and clears the journal as well as the refunds.
func (stateDB *DB) Finalise(deleteEmptyObjects bool) { func (db *DB) Finalise(deleteEmptyObjects bool) {
for addr := range stateDB.journal.dirties { for addr := range db.journal.dirties {
stateObject, exist := stateDB.stateObjects[addr] stateObject, exist := db.stateObjects[addr]
if !exist { if !exist {
// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 // 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 // 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, // 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 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 // Thus, we can safely ignore it here
continue continue
} }
if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
stateDB.deleteStateObject(stateObject) db.deleteStateObject(stateObject)
} else { } else {
stateObject.updateRoot(stateDB.db) stateObject.updateRoot(db.db)
stateDB.updateStateObject(stateObject) db.updateStateObject(stateObject)
} }
stateDB.stateObjectsDirty[addr] = struct{}{} db.stateObjectsDirty[addr] = struct{}{}
} }
// Invalidate journal because reverting across transactions is not allowed. // Invalidate journal because reverting across transactions is not allowed.
stateDB.clearJournalAndRefund() db.clearJournalAndRefund()
} }
// IntermediateRoot computes the current root hash of the state trie. // IntermediateRoot computes the current root hash of the state trie.
// It is called in between transactions to get the root hash that // It is called in between transactions to get the root hash that
// goes into transaction receipts. // goes into transaction receipts.
func (stateDB *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { func (db *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
stateDB.Finalise(deleteEmptyObjects) db.Finalise(deleteEmptyObjects)
return stateDB.trie.Hash() return db.trie.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 (stateDB *DB) Prepare(thash, bhash common.Hash, ti int) { func (db *DB) Prepare(thash, bhash common.Hash, ti int) {
stateDB.thash = thash db.thash = thash
stateDB.bhash = bhash db.bhash = bhash
stateDB.txIndex = ti db.txIndex = ti
} }
func (stateDB *DB) clearJournalAndRefund() { func (db *DB) clearJournalAndRefund() {
stateDB.journal = newJournal() db.journal = newJournal()
stateDB.validRevisions = stateDB.validRevisions[:0] db.validRevisions = db.validRevisions[:0]
stateDB.refund = 0 db.refund = 0
} }
// Commit writes the state to the underlying in-memory trie database. // Commit writes the state to the underlying in-memory trie database.
func (stateDB *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { func (db *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
defer stateDB.clearJournalAndRefund() defer db.clearJournalAndRefund()
for addr := range stateDB.journal.dirties { for addr := range db.journal.dirties {
stateDB.stateObjectsDirty[addr] = struct{}{} db.stateObjectsDirty[addr] = struct{}{}
} }
// Commit objects to the trie. // Commit objects to the trie.
for addr, stateObject := range stateDB.stateObjects { for addr, stateObject := range db.stateObjects {
_, isDirty := stateDB.stateObjectsDirty[addr] _, isDirty := db.stateObjectsDirty[addr]
switch { switch {
case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
// If the object has been removed, don't bother syncing it // If the object has been removed, don't bother syncing it
// and just mark it for deletion in the trie. // and just mark it for deletion in the trie.
stateDB.deleteStateObject(stateObject) db.deleteStateObject(stateObject)
case isDirty: case isDirty:
// Write any contract code associated with the state object // Write any contract code associated with the state object
if stateObject.code != nil && stateObject.dirtyCode { 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 stateObject.dirtyCode = false
} }
// Write any storage changes in the state object to its storage trie. // 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 return common.Hash{}, err
} }
// Update the object in the main account trie. // 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. // 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 var account Account
if err := rlp.DecodeBytes(leaf, &account); err != nil { if err := rlp.DecodeBytes(leaf, &account); err != nil {
return nil return nil
} }
if account.Root != emptyState { if account.Root != emptyState {
stateDB.db.TrieDB().Reference(account.Root, parent) db.db.TrieDB().Reference(account.Root, parent)
} }
code := common.BytesToHash(account.CodeHash) code := common.BytesToHash(account.CodeHash)
if code != emptyCode { if code != emptyCode {
stateDB.db.TrieDB().Reference(code, parent) db.db.TrieDB().Reference(code, parent)
} }
return nil return nil
}) })

@ -33,7 +33,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/core/types" "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 // 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))] action := actions[r.Intn(len(actions))]
var nameargs []string var nameargs []string
if !action.noAddr { if !action.noAddr {
nameargs = append(nameargs, common2.MustAddressToBech32(addr)) nameargs = append(nameargs, addr.Hex())
} }
for _, i := range action.args { for _, i := range action.args {
action.args[i] = rand.Int63n(100) action.args[i] = rand.Int63n(100)
@ -367,7 +366,7 @@ func (test *snapshotTest) checkEqual(state, checkstate *DB) error {
var err error var err error
checkeq := func(op string, a, b interface{}) bool { checkeq := func(op string, a, b interface{}) bool {
if err == nil && !reflect.DeepEqual(a, b) { 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 false
} }
return true return true

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

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

@ -102,7 +102,7 @@ type Context struct {
type EVM struct { type EVM struct {
// Context provides auxiliary blockchain related information // Context provides auxiliary blockchain related information
Context Context
// StateDB gives access to the underlying state // DB gives access to the underlying state
StateDB StateDB StateDB StateDB
// Depth is the current call stack // Depth is the current call stack
depth int 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 := NewContract(caller, to, new(big.Int), gas)
contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr)) 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 // 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 // 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. // 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)) current = evm.StateDB.GetState(contract.Address(), common.BigToHash(x))
) )
// The legacy gas metering only takes into consideration the current state // 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: // This checks for 3 scenario's and calculates gas accordingly:
// //
// 1. From a zero-value address to a non-zero value (NEW VALUE) // 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. // 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) { func opExtCodeHash(pc *uint64, interpreter *EVMInterpreter, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
slot := stack.peek() 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 return nil, nil
} }

@ -99,16 +99,17 @@ func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
// the jump table was initialised. If it was not // the jump table was initialised. If it was not
// we'll set the default jump table. // we'll set the default jump table.
if !cfg.JumpTable[STOP].valid { if !cfg.JumpTable[STOP].valid {
switch { //switch {
case evm.ChainConfig().IsConstantinople(evm.BlockNumber): //case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
cfg.JumpTable = constantinopleInstructionSet // cfg.JumpTable = constantinopleInstructionSet
case evm.ChainConfig().IsByzantium(evm.BlockNumber): //case evm.ChainConfig().IsByzantium(evm.BlockNumber):
cfg.JumpTable = byzantiumInstructionSet // cfg.JumpTable = byzantiumInstructionSet
case evm.ChainConfig().IsHomestead(evm.BlockNumber): //case evm.ChainConfig().IsHomestead(evm.BlockNumber):
cfg.JumpTable = homesteadInstructionSet // cfg.JumpTable = homesteadInstructionSet
default: //default:
cfg.JumpTable = frontierInstructionSet // cfg.JumpTable = frontierInstructionSet
} //}
cfg.JumpTable = constantinopleInstructionSet
} }
return &EVMInterpreter{ 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 state.DB
} }
// GetRefund ... func (*dummyStatedb) GetRefund() uint64 { return 1337 }
func (*dummyStatedb) GetRefund() uint64 {
return 1337
}
func TestStoreCapture(t *testing.T) { func TestStoreCapture(t *testing.T) {
var ( var (

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

@ -149,7 +149,6 @@ func BenchmarkCall(b *testing.B) {
} }
} }
} }
func benchmarkEVMCreate(bench *testing.B, code string) { func benchmarkEVMCreate(bench *testing.B, code string) {
var ( var (
statedb, _ = state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase())) 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) { if core.IsEpochLastBlock(newBlock) {
dRand.init(newBlock) dRand.init(newBlock)
} }
pRnd := newBlock.Header().Vrf // TODO: use real vrf
pRnd := [32]byte{} //newBlock.Header().Vrf
zeros := [32]byte{} zeros := [32]byte{}
if core.IsEpochBlock(newBlock) && !bytes.Equal(pRnd[:], zeros[:]) { if core.IsEpochBlock(newBlock) && !bytes.Equal(pRnd[:], zeros[:]) {
// The epoch block should contain the randomness preimage pRnd // 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) GetBlock(ctx context.Context, blockHash common.Hash) (*types.Block, error)
GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
// GetTd(blockHash common.Hash) *big.Int // 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 SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription

@ -1,9 +1,10 @@
package shardchain package shardchain
import ( import (
"math/big"
"sync" "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/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
@ -102,7 +103,7 @@ func (sc *CollectionImpl) ShardChain(shardID uint32, networkType nodeconfig.Netw
chainConfig = *params.TestnetChainConfig chainConfig = *params.TestnetChainConfig
} }
//chainConfig.ChainID = big.NewInt(int64(shardID)) chainConfig.ChainID = big.NewInt(int64(shardID))
bc, err := core.NewBlockChain( bc, err := core.NewBlockChain(
db, cacheConfig, &chainConfig, sc.engine, vm.Config{}, nil, 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/contracts/structs"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common" 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/genesis"
"github.com/harmony-one/harmony/internal/utils" "github.com/harmony-one/harmony/internal/utils"
) )
@ -127,6 +128,9 @@ func (node *Node) QueryStakeInfo() *structs.StakeInfoReturnValue {
} }
func (node *Node) getDeployedStakingContract() common.Address { func (node *Node) getDeployedStakingContract() common.Address {
if node.NodeConfig.GetNetworkType() == nodeconfig.Mainnet {
return common.Address{}
}
return node.StakingContractAddress return node.StakingContractAddress
} }
@ -169,6 +173,9 @@ func (node *Node) AddFaucetContractToPendingTransactions() {
// CallFaucetContract invokes the faucet contract to give the walletAddress initial money // CallFaucetContract invokes the faucet contract to give the walletAddress initial money
func (node *Node) CallFaucetContract(address common.Address) common.Hash { 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) // Temporary code to workaround explorer issue for searching new addresses (https://github.com/harmony-one/harmony/issues/503)
nonce := atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1) 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) 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. // Blockchain returns the blockchain for the node's current shard.
func (node *Node) Blockchain() *core.BlockChain { func (node *Node) Blockchain() *core.BlockChain {
shardID := node.Consensus.ShardID shardID := node.NodeConfig.ShardID
bc, err := node.shardChains.ShardChain(shardID, node.NodeConfig.GetNetworkType()) bc, err := node.shardChains.ShardChain(shardID, node.NodeConfig.GetNetworkType())
if err != nil { if err != nil {
err = ctxerror.New("cannot get shard chain", "shardID", shardID). 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) { func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardState types.ShardState) {
utils.GetLogger().Info("setting up a brand new chain database", utils.GetLogger().Info("setting up a brand new chain database",
"shardID", shardID) "shardID", shardID)
if shardID == node.Consensus.ShardID { if shardID == node.NodeConfig.ShardID {
node.isFirstTime = true node.isFirstTime = true
} }
@ -93,7 +93,7 @@ func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardSt
// Initialize shard state // Initialize shard state
// TODO: add ShardID into chainconfig and change ChainID to NetworkID // 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{ gspec := core.Genesis{
Config: &chainConfig, Config: &chainConfig,

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