From 0a573c104e9d3c043ddb9872f2bd44a3211881f7 Mon Sep 17 00:00:00 2001 From: Minh Doan Date: Thu, 29 Nov 2018 22:28:22 -0800 Subject: [PATCH 1/3] gix golint --- client/txgen/main.go | 2 +- core/blockchain.go | 4 +- core/chain_makers.go | 6 +-- core/genesis.go | 4 +- core/types/block.go | 73 ++++++++++++++++++++++--------- core/types/transaction.go | 4 +- core/types/transaction_signing.go | 1 + harmony/main.go | 4 +- node/node.go | 4 +- node/worker/worker.go | 4 +- 10 files changed, 70 insertions(+), 36 deletions(-) diff --git a/client/txgen/main.go b/client/txgen/main.go index a952ad1f7..61be9c062 100644 --- a/client/txgen/main.go +++ b/client/txgen/main.go @@ -103,7 +103,7 @@ func main() { accountBlock := new(types.Block) err := rlp.DecodeBytes(block.AccountBlock, accountBlock) if err == nil { - shardId = accountBlock.ShardId() + shardId = accountBlock.ShardID() } if node.Consensus.ShardID == shardId { log.Debug("Adding block from leader", "shardID", shardId) diff --git a/core/blockchain.go b/core/blockchain.go index 9638ca06d..937c952b4 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -348,8 +348,8 @@ func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error { return nil } -// ShardId returns the shard Id of the blockchain. -func (bc *BlockChain) ShardId() uint32 { +// ShardID returns the shard Id of the blockchain. +func (bc *BlockChain) ShardID() uint32 { return uint32(bc.chainConfig.ChainID.Int64()) } diff --git a/core/chain_makers.go b/core/chain_makers.go index 6da870aa2..8a071a6e2 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -71,9 +71,9 @@ func (b *BlockGen) SetNonce(nonce types.BlockNonce) { b.header.Nonce = nonce } -// SetShardId sets the shardId field of the generated block. -func (b *BlockGen) SetShardId(shardId types.ShardId) { - b.header.ShardId = shardId +// SetShardID sets the shardId field of the generated block. +func (b *BlockGen) SetShardID(shardId types.ShardID) { + b.header.ShardID = shardId } // AddTx adds a transaction to the generated block. If no coinbase has diff --git a/core/genesis.go b/core/genesis.go index 5c8a1a6c7..52c15e04c 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -45,7 +45,7 @@ var errGenesisNoConfig = errors.New("genesis has no chain configuration") type Genesis struct { Config *params.ChainConfig `json:"config"` Nonce uint64 `json:"nonce"` - ShardId uint32 `json:"shardId"` + ShardID uint32 `json:"shardId"` Timestamp uint64 `json:"timestamp"` ExtraData []byte `json:"extraData"` GasLimit uint64 `json:"gasLimit" gencodec:"required"` @@ -235,7 +235,7 @@ func (g *Genesis) ToBlock(db hdb.Database) *types.Block { head := &types.Header{ Number: new(big.Int).SetUint64(g.Number), Nonce: types.EncodeNonce(g.Nonce), - ShardId: types.EncodeShardId(g.ShardId), + ShardID: types.EncodeShardID(g.ShardID), Time: new(big.Int).SetUint64(g.Timestamp), ParentHash: g.ParentHash, Extra: g.ExtraData, diff --git a/core/types/block.go b/core/types/block.go index cc2089e84..945da2122 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -32,6 +32,7 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) +// Constants for block. var ( EmptyRootHash = DeriveSha(Transactions{}) EmptyUncleHash = CalcUncleHash(nil) @@ -42,8 +43,8 @@ var ( // out on a block. type BlockNonce [8]byte -// A Shard is a 32-bit id for the shard a block belongs to -type ShardId [4]byte +// ShardID is a 32-bit id for the shard a block belongs to +type ShardID [4]byte // EncodeNonce converts the given integer to a block nonce. func EncodeNonce(i uint64) BlockNonce { @@ -52,9 +53,9 @@ func EncodeNonce(i uint64) BlockNonce { return n } -// EncodeShardId converts the given integer to a shard id. -func EncodeShardId(i uint32) ShardId { - var n ShardId +// EncodeShardID converts the given integer to a shard id. +func EncodeShardID(i uint32) ShardID { + var n ShardID binary.BigEndian.PutUint32(n[:], i) return n } @@ -92,7 +93,7 @@ type Header struct { Extra []byte `json:"extraData" gencodec:"required"` MixDigest common.Hash `json:"mixHash" gencodec:"required"` Nonce BlockNonce `json:"nonce" gencodec:"required"` - ShardId ShardId `json:"shardId" gencodec:"required"` + ShardID ShardID `json:"shardId" gencodec:"required"` } // field type overrides for gencodec @@ -159,10 +160,10 @@ func (b *Block) DeprecatedTd() *big.Int { return b.td } -// [deprecated by eth/63] // StorageBlock defines the RLP encoding of a Block stored in the // state database. The StorageBlock encoding contains fields that // would otherwise need to be recomputed. +// [deprecated by eth/63] type StorageBlock Block // "external" block encoding. used for eth protocol, etc. @@ -258,6 +259,7 @@ func (b *Block) EncodeRLP(w io.Writer) error { }) } +// DecodeRLP decodes RLP // [deprecated by eth/63] func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { var sb storageblock @@ -268,11 +270,17 @@ func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { return nil } -// TODO: copies +// Uncles return uncles. +func (b *Block) Uncles() []*Header { + return b.uncles +} -func (b *Block) Uncles() []*Header { return b.uncles } -func (b *Block) Transactions() Transactions { return b.transactions } +// Transactions returns transactions. +func (b *Block) Transactions() Transactions { + return b.transactions +} +// Transaction returns Transaction. func (b *Block) Transaction(hash common.Hash) *Transaction { for _, transaction := range b.transactions { if transaction.Hash() == hash { @@ -282,16 +290,32 @@ func (b *Block) Transaction(hash common.Hash) *Transaction { return nil } -func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } -func (b *Block) GasLimit() uint64 { return b.header.GasLimit } -func (b *Block) GasUsed() uint64 { return b.header.GasUsed } +// Number returns header number. +func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } + +// GasLimit returns header gas limit. +func (b *Block) GasLimit() uint64 { return b.header.GasLimit } + +// GasUsed returns header gas used. +func (b *Block) GasUsed() uint64 { return b.header.GasUsed } + +// Difficulty is the header difficulty. func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } -func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) } -func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } -func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } -func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } -func (b *Block) ShardId() uint32 { return binary.BigEndian.Uint32(b.header.ShardId[:]) } +// TIme is header time. +func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) } + +// NumberU64 is the header number in uint64. +func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } + +// MixDigest is the header mix digest. +func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } + +// Nonce is the header nonce. +func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } + +// ShardID is the header ShardID +func (b *Block) ShardID() uint32 { return binary.BigEndian.Uint32(b.header.ShardID[:]) } func (b *Block) Bloom() Bloom { return b.header.Bloom } func (b *Block) Coinbase() common.Address { return b.header.Coinbase } func (b *Block) Root() common.Hash { return b.header.Root } @@ -365,14 +389,17 @@ func (b *Block) Hash() common.Hash { return v } +// Blocks is an array of Block. type Blocks []*Block +// BlockBy is the func type. type BlockBy func(b1, b2 *Block) bool -func (self BlockBy) Sort(blocks Blocks) { +// Sort sorts blocks. +func (blockBy BlockBy) Sort(blocks Blocks) { bs := blockSorter{ blocks: blocks, - by: self, + by: blockBy, } sort.Sort(bs) } @@ -382,10 +409,16 @@ type blockSorter struct { by func(b1, b2 *Block) bool } +// Len returns len of the blocks. func (self blockSorter) Len() int { return len(self.blocks) } + +// Swap swaps block i and block j. func (self blockSorter) Swap(i, j int) { self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i] } + +// Less checks if block i is less than block j. func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) } +// Number checks if block b1 is less than block b2. func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 } diff --git a/core/types/transaction.go b/core/types/transaction.go index 6cd65e8d7..035839be1 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -45,7 +45,7 @@ type Transaction struct { type txdata struct { AccountNonce uint64 `json:"nonce" gencodec:"required"` - ShardId uint32 `json:"shardId" gencodec:"required"` + ShardID uint32 `json:"shardId" gencodec:"required"` Price *big.Int `json:"gasPrice" gencodec:"required"` GasLimit uint64 `json:"gas" gencodec:"required"` Recipient *common.Address `json:"to" rlp:"nil"` // nil means contract creation @@ -87,7 +87,7 @@ func newTransaction(nonce uint64, to *common.Address, shardId uint32, amount *bi d := txdata{ AccountNonce: nonce, Recipient: to, - ShardId: shardId, + ShardID: shardId, Payload: data, Amount: new(big.Int), GasLimit: gasLimit, diff --git a/core/types/transaction_signing.go b/core/types/transaction_signing.go index 63132048e..81abef1cf 100644 --- a/core/types/transaction_signing.go +++ b/core/types/transaction_signing.go @@ -27,6 +27,7 @@ import ( "github.com/ethereum/go-ethereum/params" ) +// Constants for transaction signing. var ( ErrInvalidChainId = errors.New("invalid chain id for signer") ) diff --git a/harmony/main.go b/harmony/main.go index 1f7a3cbf8..b678f9bab 100644 --- a/harmony/main.go +++ b/harmony/main.go @@ -53,7 +53,7 @@ func main() { gspec = core.Genesis{ Config: chainConfig, Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, - ShardId: 10, + ShardID: 10, } ) @@ -75,7 +75,7 @@ func main() { if n > 0 { blocks, _ := core.GenerateChain(chainConfig, genesis, consensus.NewFaker(), database, n, func(i int, gen *core.BlockGen) { gen.SetCoinbase(testBankAddress) - gen.SetShardId(types.EncodeShardId(10)) + gen.SetShardID(types.EncodeShardID(10)) gen.AddTx(pendingTxs[i]) }) if _, err := chain.InsertChain(blocks); err != nil { diff --git a/node/node.go b/node/node.go index 39cfe0f3f..e598bf888 100644 --- a/node/node.go +++ b/node/node.go @@ -286,11 +286,11 @@ func New(consensus *bft.Consensus, db *hdb.LDBDatabase) *Node { database := hdb.NewMemDatabase() chainConfig := params.TestChainConfig - chainConfig.ChainID = big.NewInt(int64(node.Consensus.ShardID)) // Use ChainId as piggybacked ShardId + chainConfig.ChainID = big.NewInt(int64(node.Consensus.ShardID)) // Use ChainId as piggybacked ShardID gspec := core.Genesis{ Config: chainConfig, Alloc: genesisAloc, - ShardId: uint32(node.Consensus.ShardID), + ShardID: uint32(node.Consensus.ShardID), } _ = gspec.MustCommit(database) diff --git a/node/worker/worker.go b/node/worker/worker.go index a8b066b80..ad7a8fee7 100644 --- a/node/worker/worker.go +++ b/node/worker/worker.go @@ -78,7 +78,7 @@ func (w *Worker) UpdateCurrent() error { Number: num.Add(num, common.Big1), GasLimit: core.CalcGasLimit(parent, w.gasFloor, w.gasCeil), Time: big.NewInt(timestamp), - ShardId: types.EncodeShardId(w.chain.ShardId()), + ShardID: types.EncodeShardID(w.chain.ShardID()), } return w.makeCurrent(parent, header) } @@ -131,7 +131,7 @@ func New(config *params.ChainConfig, chain *core.BlockChain, engine consensus.En Number: num.Add(num, common.Big1), GasLimit: core.CalcGasLimit(parent, worker.gasFloor, worker.gasCeil), Time: big.NewInt(timestamp), - ShardId: types.EncodeShardId(worker.chain.ShardId()), + ShardID: types.EncodeShardID(worker.chain.ShardID()), } worker.makeCurrent(parent, header) From 2877e5fb5d878bf88ae9d9cee7786530bc1890c0 Mon Sep 17 00:00:00 2001 From: Minh Doan Date: Fri, 30 Nov 2018 08:31:38 -0800 Subject: [PATCH 2/3] fix more golint --- core/state/database.go | 2 +- core/state/dump.go | 22 ++- core/state/managed_state.go | 7 +- core/state/state_object.go | 238 +++++++++++++------------ core/state/statedb.go | 345 +++++++++++++++++++----------------- 5 files changed, 318 insertions(+), 296 deletions(-) diff --git a/core/state/database.go b/core/state/database.go index 6b9be0d99..a2ebd6786 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -26,7 +26,7 @@ import ( lru "github.com/hashicorp/golang-lru" ) -// Trie cache generation limit after which to evict trie nodes from memory. +// MaxTrieCacheGen is trie cache generation limit after which to evict trie nodes from memory. var MaxTrieCacheGen = uint16(120) const ( diff --git a/core/state/dump.go b/core/state/dump.go index 072dbbf05..34569ed7d 100644 --- a/core/state/dump.go +++ b/core/state/dump.go @@ -25,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/trie" ) +// DumpAccount ... type DumpAccount struct { Balance string `json:"balance"` Nonce uint64 `json:"nonce"` @@ -34,20 +35,22 @@ type DumpAccount struct { Storage map[string]string `json:"storage"` } +// Dump is the structure of root hash and associated accounts. type Dump struct { Root string `json:"root"` Accounts map[string]DumpAccount `json:"accounts"` } -func (self *StateDB) RawDump() Dump { +// RawDump returns Dump from given StateDB. +func (stateDB *StateDB) RawDump() Dump { dump := Dump{ - Root: fmt.Sprintf("%x", self.trie.Hash()), + Root: fmt.Sprintf("%x", stateDB.trie.Hash()), Accounts: make(map[string]DumpAccount), } - it := trie.NewIterator(self.trie.NodeIterator(nil)) + it := trie.NewIterator(stateDB.trie.NodeIterator(nil)) for it.Next() { - addr := self.trie.GetKey(it.Key) + addr := stateDB.trie.GetKey(it.Key) var data Account if err := rlp.DecodeBytes(it.Value, &data); err != nil { panic(err) @@ -59,20 +62,21 @@ func (self *StateDB) RawDump() Dump { Nonce: data.Nonce, Root: common.Bytes2Hex(data.Root[:]), CodeHash: common.Bytes2Hex(data.CodeHash), - Code: common.Bytes2Hex(obj.Code(self.db)), + Code: common.Bytes2Hex(obj.Code(stateDB.db)), Storage: make(map[string]string), } - storageIt := trie.NewIterator(obj.getTrie(self.db).NodeIterator(nil)) + storageIt := trie.NewIterator(obj.getTrie(stateDB.db).NodeIterator(nil)) for storageIt.Next() { - account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value) + account.Storage[common.Bytes2Hex(stateDB.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value) } dump.Accounts[common.Bytes2Hex(addr)] = account } return dump } -func (self *StateDB) Dump() []byte { - json, err := json.MarshalIndent(self.RawDump(), "", " ") +// Dump dumps into []byte. +func (stateDB *StateDB) Dump() []byte { + json, err := json.MarshalIndent(stateDB.RawDump(), "", " ") if err != nil { fmt.Println("dump err", err) } diff --git a/core/state/managed_state.go b/core/state/managed_state.go index 1390ef4a0..a9d9bf3c7 100644 --- a/core/state/managed_state.go +++ b/core/state/managed_state.go @@ -28,6 +28,7 @@ type account struct { nonces []bool } +// ManagedState is the managed state. type ManagedState struct { *StateDB @@ -36,7 +37,7 @@ type ManagedState struct { accounts map[common.Address]*account } -// ManagedState returns a new managed state with the statedb as it's backing layer +// ManageState returns a new managed state with the statedb as it's backing layer func ManageState(statedb *StateDB) *ManagedState { return &ManagedState{ StateDB: statedb.Copy(), @@ -92,9 +93,9 @@ func (ms *ManagedState) GetNonce(addr common.Address) uint64 { if ms.hasAccount(addr) { account := ms.getAccount(addr) return uint64(len(account.nonces)) + account.nstart - } else { - return ms.StateDB.GetNonce(addr) } + return ms.StateDB.GetNonce(addr) + } // SetNonce sets the new canonical nonce for the managed state diff --git a/core/state/state_object.go b/core/state/state_object.go index f41ab0409..7f86058b3 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -29,25 +29,27 @@ import ( var emptyCodeHash = crypto.Keccak256(nil) +// Code ... type Code []byte -func (self Code) String() string { - return string(self) //strings.Join(Disassemble(self), " ") +func (code Code) String() string { + return string(code) //strings.Join(Disassemble(self), " ") } +// Storage ... type Storage map[common.Hash]common.Hash -func (self Storage) String() (str string) { - for key, value := range self { +func (storage Storage) String() (str string) { + for key, value := range storage { str += fmt.Sprintf("%X : %X\n", key, value) } - return } -func (self Storage) Copy() Storage { +// Copy returns a copy of Storage +func (storage Storage) Copy() Storage { cpy := make(Storage) - for key, value := range self { + for key, value := range storage { cpy[key] = value } @@ -57,8 +59,8 @@ func (self Storage) Copy() Storage { // stateObject represents an Ethereum account which is being modified. // // The usage pattern is as follows: -// First you need to obtain a state object. -// Account values can be accessed and modified through the object. +// First you need to obtain a state s. +// Account values can be accessed and modified through the s. // Finally, call CommitTrie to write the modified storage trie into a database. type stateObject struct { address common.Address @@ -102,7 +104,7 @@ type Account struct { CodeHash []byte } -// newObject creates a state object. +// newObject creates a state s. func newObject(db *StateDB, address common.Address, data Account) *stateObject { if data.Balance == nil { data.Balance = new(big.Int) @@ -121,192 +123,192 @@ func newObject(db *StateDB, address common.Address, data Account) *stateObject { } // EncodeRLP implements rlp.Encoder. -func (c *stateObject) EncodeRLP(w io.Writer) error { - return rlp.Encode(w, c.data) +func (s *stateObject) EncodeRLP(w io.Writer) error { + return rlp.Encode(w, s.data) } // setError remembers the first non-nil error it is called with. -func (self *stateObject) setError(err error) { - if self.dbErr == nil { - self.dbErr = err +func (s *stateObject) setError(err error) { + if s.dbErr == nil { + s.dbErr = err } } -func (self *stateObject) markSuicided() { - self.suicided = true +func (s *stateObject) markSuicided() { + s.suicided = true } -func (c *stateObject) touch() { - c.db.journal.append(touchChange{ - account: &c.address, +func (s *stateObject) touch() { + s.db.journal.append(touchChange{ + account: &s.address, }) - if c.address == ripemd { + if s.address == ripemd { // Explicitly put it in the dirty-cache, which is otherwise generated from // flattened journals. - c.db.journal.dirty(c.address) + s.db.journal.dirty(s.address) } } -func (c *stateObject) getTrie(db Database) Trie { - if c.trie == nil { +func (s *stateObject) getTrie(db Database) Trie { + if s.trie == nil { var err error - c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root) + s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) if err != nil { - c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{}) - c.setError(fmt.Errorf("can't create storage trie: %v", err)) + s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) + s.setError(fmt.Errorf("can't create storage trie: %v", err)) } } - return c.trie + return s.trie } // GetState retrieves a value from the account storage trie. -func (self *stateObject) GetState(db Database, key common.Hash) common.Hash { +func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { // If we have a dirty value for this state entry, return it - value, dirty := self.dirtyStorage[key] + value, dirty := s.dirtyStorage[key] if dirty { return value } // Otherwise return the entry's original value - return self.GetCommittedState(db, key) + return s.GetCommittedState(db, key) } // GetCommittedState retrieves a value from the committed account storage trie. -func (self *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { +func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { // If we have the original value cached, return that - value, cached := self.originStorage[key] + value, cached := s.originStorage[key] if cached { return value } // Otherwise load the value from the database - enc, err := self.getTrie(db).TryGet(key[:]) + enc, err := s.getTrie(db).TryGet(key[:]) if err != nil { - self.setError(err) + s.setError(err) return common.Hash{} } if len(enc) > 0 { _, content, _, err := rlp.Split(enc) if err != nil { - self.setError(err) + s.setError(err) } value.SetBytes(content) } - self.originStorage[key] = value + s.originStorage[key] = value return value } // SetState updates a value in account storage. -func (self *stateObject) SetState(db Database, key, value common.Hash) { +func (s *stateObject) SetState(db Database, key, value common.Hash) { // If the new value is the same as old, don't set - prev := self.GetState(db, key) + prev := s.GetState(db, key) if prev == value { return } // New value is different, update and journal the change - self.db.journal.append(storageChange{ - account: &self.address, + s.db.journal.append(storageChange{ + account: &s.address, key: key, prevalue: prev, }) - self.setState(key, value) + s.setState(key, value) } -func (self *stateObject) setState(key, value common.Hash) { - self.dirtyStorage[key] = value +func (s *stateObject) setState(key, value common.Hash) { + s.dirtyStorage[key] = value } // updateTrie writes cached storage modifications into the object's storage trie. -func (self *stateObject) updateTrie(db Database) Trie { - tr := self.getTrie(db) - for key, value := range self.dirtyStorage { - delete(self.dirtyStorage, key) +func (s *stateObject) updateTrie(db Database) Trie { + tr := s.getTrie(db) + for key, value := range s.dirtyStorage { + delete(s.dirtyStorage, key) // Skip noop changes, persist actual changes - if value == self.originStorage[key] { + if value == s.originStorage[key] { continue } - self.originStorage[key] = value + s.originStorage[key] = value if (value == common.Hash{}) { - self.setError(tr.TryDelete(key[:])) + s.setError(tr.TryDelete(key[:])) continue } // Encoding []byte cannot fail, ok to ignore the error. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00")) - self.setError(tr.TryUpdate(key[:], v)) + s.setError(tr.TryUpdate(key[:], v)) } return tr } // UpdateRoot sets the trie root to the current root hash of -func (self *stateObject) updateRoot(db Database) { - self.updateTrie(db) - self.data.Root = self.trie.Hash() +func (s *stateObject) updateRoot(db Database) { + s.updateTrie(db) + s.data.Root = s.trie.Hash() } // CommitTrie the storage trie of the object to db. // This updates the trie root. -func (self *stateObject) CommitTrie(db Database) error { - self.updateTrie(db) - if self.dbErr != nil { - return self.dbErr +func (s *stateObject) CommitTrie(db Database) error { + s.updateTrie(db) + if s.dbErr != nil { + return s.dbErr } - root, err := self.trie.Commit(nil) + root, err := s.trie.Commit(nil) if err == nil { - self.data.Root = root + s.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 (c *stateObject) AddBalance(amount *big.Int) { +func (s *stateObject) 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 c.empty() { - c.touch() + if s.empty() { + s.touch() } return } - c.SetBalance(new(big.Int).Add(c.Balance(), amount)) + s.SetBalance(new(big.Int).Add(s.Balance(), amount)) } // SubBalance removes amount from c's balance. // It is used to remove funds from the origin account of a transfer. -func (c *stateObject) SubBalance(amount *big.Int) { +func (s *stateObject) SubBalance(amount *big.Int) { if amount.Sign() == 0 { return } - c.SetBalance(new(big.Int).Sub(c.Balance(), amount)) + s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) } -func (self *stateObject) SetBalance(amount *big.Int) { - self.db.journal.append(balanceChange{ - account: &self.address, - prev: new(big.Int).Set(self.data.Balance), +func (s *stateObject) SetBalance(amount *big.Int) { + s.db.journal.append(balanceChange{ + account: &s.address, + prev: new(big.Int).Set(s.data.Balance), }) - self.setBalance(amount) + s.setBalance(amount) } -func (self *stateObject) setBalance(amount *big.Int) { - self.data.Balance = amount +func (s *stateObject) setBalance(amount *big.Int) { + s.data.Balance = amount } // Return the gas back to the origin. Used by the Virtual machine or Closures -func (c *stateObject) ReturnGas(gas *big.Int) {} +func (s *stateObject) ReturnGas(gas *big.Int) {} -func (self *stateObject) deepCopy(db *StateDB) *stateObject { - stateObject := newObject(db, self.address, self.data) - if self.trie != nil { - stateObject.trie = db.db.CopyTrie(self.trie) +func (s *stateObject) deepCopy(db *StateDB) *stateObject { + stateObject := newObject(db, s.address, s.data) + if s.trie != nil { + stateObject.trie = db.db.CopyTrie(s.trie) } - stateObject.code = self.code - stateObject.dirtyStorage = self.dirtyStorage.Copy() - stateObject.originStorage = self.originStorage.Copy() - stateObject.suicided = self.suicided - stateObject.dirtyCode = self.dirtyCode - stateObject.deleted = self.deleted + 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 return stateObject } @@ -315,69 +317,69 @@ func (self *stateObject) deepCopy(db *StateDB) *stateObject { // // Returns the address of the contract/account -func (c *stateObject) Address() common.Address { - return c.address +func (s *stateObject) Address() common.Address { + return s.address } // Code returns the contract code associated with this object, if any. -func (self *stateObject) Code(db Database) []byte { - if self.code != nil { - return self.code +func (s *stateObject) Code(db Database) []byte { + if s.code != nil { + return s.code } - if bytes.Equal(self.CodeHash(), emptyCodeHash) { + if bytes.Equal(s.CodeHash(), emptyCodeHash) { return nil } - code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash())) + code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) if err != nil { - self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err)) + s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) } - self.code = code + s.code = code return code } -func (self *stateObject) SetCode(codeHash common.Hash, code []byte) { - prevcode := self.Code(self.db.db) - self.db.journal.append(codeChange{ - account: &self.address, - prevhash: self.CodeHash(), +func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { + prevcode := s.Code(s.db.db) + s.db.journal.append(codeChange{ + account: &s.address, + prevhash: s.CodeHash(), prevcode: prevcode, }) - self.setCode(codeHash, code) + s.setCode(codeHash, code) } -func (self *stateObject) setCode(codeHash common.Hash, code []byte) { - self.code = code - self.data.CodeHash = codeHash[:] - self.dirtyCode = true +func (s *stateObject) setCode(codeHash common.Hash, code []byte) { + s.code = code + s.data.CodeHash = codeHash[:] + s.dirtyCode = true } -func (self *stateObject) SetNonce(nonce uint64) { - self.db.journal.append(nonceChange{ - account: &self.address, - prev: self.data.Nonce, +func (s *stateObject) SetNonce(nonce uint64) { + s.db.journal.append(nonceChange{ + account: &s.address, + prev: s.data.Nonce, }) - self.setNonce(nonce) + s.setNonce(nonce) } -func (self *stateObject) setNonce(nonce uint64) { - self.data.Nonce = nonce +func (s *stateObject) setNonce(nonce uint64) { + s.data.Nonce = nonce } -func (self *stateObject) CodeHash() []byte { - return self.data.CodeHash +func (s *stateObject) CodeHash() []byte { + return s.data.CodeHash } -func (self *stateObject) Balance() *big.Int { - return self.data.Balance +func (s *stateObject) Balance() *big.Int { + return s.data.Balance } -func (self *stateObject) Nonce() uint64 { - return self.data.Nonce +func (s *stateObject) Nonce() uint64 { + return s.data.Nonce } // Never called, but must be present to allow stateObject to be used // as a vm.Account interface that also satisfies the vm.ContractRef // interface. Interfaces are awesome. -func (self *stateObject) Value() *big.Int { +func (s *stateObject) Value() *big.Int { panic("Value on stateObject should never be called") } diff --git a/core/state/statedb.go b/core/state/statedb.go index cafcca8ba..4ab0a637c 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -1,3 +1,4 @@ +// package state ... // Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // @@ -18,6 +19,7 @@ package state import ( + "github.com/harmony-one/harmony/core/state" "errors" "fmt" "math/big" @@ -52,7 +54,7 @@ func (n *proofList) Put(key []byte, value []byte) error { return nil } -// StateDBs within the ethereum protocol are used to store anything +// StateDB within the ethereum protocol are used to store anything // within the merkle trie. StateDBs take care of caching and storing // nested states. It's the general query interface to retrieve: // * Contracts @@ -86,12 +88,12 @@ type StateDB struct { // Snapshot and RevertToSnapshot. journal *journal validRevisions []revision - nextRevisionId int + nextRevisionID int lock sync.Mutex } -// Create a new state from a given trie. +// New creates a new state from a given trie. func New(root common.Hash, db Database) (*StateDB, error) { tr, err := db.OpenTrie(root) if err != nil { @@ -109,114 +111,118 @@ func New(root common.Hash, db Database) (*StateDB, error) { } // setError remembers the first non-nil error it is called with. -func (self *StateDB) setError(err error) { - if self.dbErr == nil { - self.dbErr = err +func (stateDB *StateDB) setError(err error) { + if stateDB.dbErr == nil { + stateDB.dbErr = err } } -func (self *StateDB) Error() error { - return self.dbErr +func (stateDB *StateDB) Error() error { + return stateDB.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 (self *StateDB) Reset(root common.Hash) error { - tr, err := self.db.OpenTrie(root) +func (stateDB *StateDB) Reset(root common.Hash) error { + tr, err := stateDB.db.OpenTrie(root) if err != nil { return err } - self.trie = tr - self.stateObjects = make(map[common.Address]*stateObject) - self.stateObjectsDirty = make(map[common.Address]struct{}) - self.thash = common.Hash{} - self.bhash = common.Hash{} - self.txIndex = 0 - self.logs = make(map[common.Hash][]*types.Log) - self.logSize = 0 - self.preimages = make(map[common.Hash][]byte) - self.clearJournalAndRefund() + stateDB.trie = tr + stateDB.stateObjects = make(map[common.Address]*stateObject) + 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() return nil } -func (self *StateDB) AddLog(log *types.Log) { - self.journal.append(addLogChange{txhash: self.thash}) +// AddLog adds logs into stateDB +func (stateDB *StateDB) AddLog(log *types.Log) { + stateDB.journal.append(addLogChange{txhash: stateDB.thash}) - log.TxHash = self.thash - log.BlockHash = self.bhash - log.TxIndex = uint(self.txIndex) - log.Index = self.logSize - self.logs[self.thash] = append(self.logs[self.thash], log) - self.logSize++ + 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++ } -func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { - return self.logs[hash] +// GetLogs gets logs from stateDB given a hash +func (stateDB *StateDB) GetLogs(hash common.Hash) []*types.Log { + return stateDB.logs[hash] } -func (self *StateDB) Logs() []*types.Log { +// Logs returns a list of Log. +func (stateDB *StateDB) Logs() []*types.Log { var logs []*types.Log - for _, lgs := range self.logs { + for _, lgs := range stateDB.logs { logs = append(logs, lgs...) } return logs } // AddPreimage records a SHA3 preimage seen by the VM. -func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { - if _, ok := self.preimages[hash]; !ok { - self.journal.append(addPreimageChange{hash: hash}) +func (stateDB *StateDB) AddPreimage(hash common.Hash, preimage []byte) { + if _, ok := stateDB.preimages[hash]; !ok { + stateDB.journal.append(addPreimageChange{hash: hash}) pi := make([]byte, len(preimage)) copy(pi, preimage) - self.preimages[hash] = pi + stateDB.preimages[hash] = pi } } // Preimages returns a list of SHA3 preimages that have been submitted. -func (self *StateDB) Preimages() map[common.Hash][]byte { - return self.preimages +func (stateDB *StateDB) Preimages() map[common.Hash][]byte { + return stateDB.preimages } // AddRefund adds gas to the refund counter -func (self *StateDB) AddRefund(gas uint64) { - self.journal.append(refundChange{prev: self.refund}) - self.refund += gas +func (stateDB *StateDB) AddRefund(gas uint64) { + stateDB.journal.append(refundChange{prev: stateDB.refund}) + stateDB.refund += gas } // SubRefund removes gas from the refund counter. // This method will panic if the refund counter goes below zero -func (self *StateDB) SubRefund(gas uint64) { - self.journal.append(refundChange{prev: self.refund}) - if gas > self.refund { +func (stateDB *StateDB) SubRefund(gas uint64) { + stateDB.journal.append(refundChange{prev: stateDB.refund}) + if gas > stateDB.refund { panic("Refund counter below zero") } - self.refund -= gas + stateDB.refund -= gas } // Exist reports whether the given account address exists in the state. // Notably this also returns true for suicided accounts. -func (self *StateDB) Exist(addr common.Address) bool { - return self.getStateObject(addr) != nil +func (stateDB *StateDB) Exist(addr common.Address) bool { + return stateDB.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 (self *StateDB) Empty(addr common.Address) bool { - so := self.getStateObject(addr) +func (stateDB *StateDB) Empty(addr common.Address) bool { + so := stateDB.getStateObject(addr) return so == nil || so.empty() } -// Retrieve the balance from the given address or 0 if object not found -func (self *StateDB) GetBalance(addr common.Address) *big.Int { - stateObject := self.getStateObject(addr) +// GetBalance retrieves the balance from the given address or 0 if object not found +func (stateDB *StateDB) GetBalance(addr common.Address) *big.Int { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { return stateObject.Balance() } return common.Big0 } -func (self *StateDB) GetNonce(addr common.Address) uint64 { - stateObject := self.getStateObject(addr) +// GetNonce returns the nonce of the given address. +func (stateDB *StateDB) GetNonce(addr common.Address) uint64 { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { return stateObject.Nonce() } @@ -224,31 +230,34 @@ func (self *StateDB) GetNonce(addr common.Address) uint64 { return 0 } -func (self *StateDB) GetCode(addr common.Address) []byte { - stateObject := self.getStateObject(addr) +// GetCode returns code of a given address. +func (stateDB *StateDB) GetCode(addr common.Address) []byte { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { - return stateObject.Code(self.db) + return stateObject.Code(stateDB.db) } return nil } -func (self *StateDB) GetCodeSize(addr common.Address) int { - stateObject := self.getStateObject(addr) +// GetCodeSize returns code size of a given address in stateDB. +func (stateDB *StateDB) GetCodeSize(addr common.Address) int { + stateObject := stateDB.getStateObject(addr) if stateObject == nil { return 0 } if stateObject.code != nil { return len(stateObject.code) } - size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) + size, err := stateDB.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) if err != nil { - self.setError(err) + stateDB.setError(err) } return size } -func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { - stateObject := self.getStateObject(addr) +// GetCodeHash returns code hash of a given address. +func (stateDB *StateDB) GetCodeHash(addr common.Address) common.Hash { + stateObject := stateDB.getStateObject(addr) if stateObject == nil { return common.Hash{} } @@ -256,25 +265,25 @@ func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { } // GetState retrieves a value from the given account's storage trie. -func (self *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { - stateObject := self.getStateObject(addr) +func (stateDB *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { - return stateObject.GetState(self.db, hash) + return stateObject.GetState(stateDB.db, hash) } return common.Hash{} } // GetProof returns the MerkleProof for a given Account -func (self *StateDB) GetProof(a common.Address) ([][]byte, error) { +func (stateDB *StateDB) GetProof(a common.Address) ([][]byte, error) { var proof proofList - err := self.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) + err := stateDB.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) return [][]byte(proof), err } -// GetProof returns the StorageProof for given key -func (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { +// GetStorageProof returns the StorageProof for given key +func (stateDB *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { var proof proofList - trie := self.StorageTrie(a) + trie := stateDB.StorageTrie(a) if trie == nil { return proof, errors.New("storage trie for requested address does not exist") } @@ -283,32 +292,33 @@ func (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byt } // GetCommittedState retrieves a value from the given account's committed storage trie. -func (self *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { - stateObject := self.getStateObject(addr) +func (stateDB *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { - return stateObject.GetCommittedState(self.db, hash) + return stateObject.GetCommittedState(stateDB.db, hash) } return common.Hash{} } // Database retrieves the low level database supporting the lower level trie ops. -func (self *StateDB) Database() Database { - return self.db +func (stateDB *StateDB) Database() Database { + return stateDB.db } // StorageTrie returns the storage trie of an account. // The return value is a copy and is nil for non-existent accounts. -func (self *StateDB) StorageTrie(addr common.Address) Trie { - stateObject := self.getStateObject(addr) +func (stateDB *StateDB) StorageTrie(addr common.Address) Trie { + stateObject := stateDB.getStateObject(addr) if stateObject == nil { return nil } - cpy := stateObject.deepCopy(self) - return cpy.updateTrie(self.db) + cpy := stateObject.deepCopy(stateDB) + return cpy.updateTrie(stateDB.db) } -func (self *StateDB) HasSuicided(addr common.Address) bool { - stateObject := self.getStateObject(addr) +// HasSuicided checks if the state object of the given addr is suicided. +func (stateDB *StateDB) HasSuicided(addr common.Address) bool { + stateObject := stateDB.getStateObject(addr) if stateObject != nil { return stateObject.suicided } @@ -320,46 +330,50 @@ func (self *StateDB) HasSuicided(addr common.Address) bool { */ // AddBalance adds amount to the account associated with addr. -func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { - stateObject := self.GetOrNewStateObject(addr) +func (stateDB *StateDB) AddBalance(addr common.Address, amount *big.Int) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { stateObject.AddBalance(amount) } } // SubBalance subtracts amount from the account associated with addr. -func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { - stateObject := self.GetOrNewStateObject(addr) +func (stateDB *StateDB) SubBalance(addr common.Address, amount *big.Int) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SubBalance(amount) } } -func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { - stateObject := self.GetOrNewStateObject(addr) +// SetBalance sets balance of an address. +func (stateDB *StateDB) SetBalance(addr common.Address, amount *big.Int) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SetBalance(amount) } } -func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { - stateObject := self.GetOrNewStateObject(addr) +// SetNonce sets nonce of a given address. +func (stateDB *StateDB) SetNonce(addr common.Address, nonce uint64) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SetNonce(nonce) } } -func (self *StateDB) SetCode(addr common.Address, code []byte) { - stateObject := self.GetOrNewStateObject(addr) +// SetCode sets code of a given address. +func (stateDB *StateDB) SetCode(addr common.Address, code []byte) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { stateObject.SetCode(crypto.Keccak256Hash(code), code) } } -func (self *StateDB) SetState(addr common.Address, key, value common.Hash) { - stateObject := self.GetOrNewStateObject(addr) +// SetState sets hash value of a given address. +func (stateDB *StateDB) SetState(addr common.Address, key, value common.Hash) { + stateObject := stateDB.GetOrNewStateObject(addr) if stateObject != nil { - stateObject.SetState(self.db, key, value) + stateObject.SetState(stateDB.db, key, value) } } @@ -368,12 +382,12 @@ func (self *StateDB) SetState(addr common.Address, key, value common.Hash) { // // The account's state object is still available until the state is committed, // getStateObject will return a non-nil account after Suicide. -func (self *StateDB) Suicide(addr common.Address) bool { - stateObject := self.getStateObject(addr) +func (stateDB *StateDB) Suicide(addr common.Address) bool { + stateObject := stateDB.getStateObject(addr) if stateObject == nil { return false } - self.journal.append(suicideChange{ + stateDB.journal.append(suicideChange{ account: &addr, prev: stateObject.suicided, prevbalance: new(big.Int).Set(stateObject.Balance()), @@ -389,26 +403,26 @@ func (self *StateDB) Suicide(addr common.Address) bool { // // updateStateObject writes the given object to the trie. -func (self *StateDB) updateStateObject(stateObject *stateObject) { +func (stateDB *StateDB) updateStateObject(stateObject *stateObject) { addr := stateObject.Address() data, err := rlp.EncodeToBytes(stateObject) if err != nil { panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) } - self.setError(self.trie.TryUpdate(addr[:], data)) + stateDB.setError(stateDB.trie.TryUpdate(addr[:], data)) } // deleteStateObject removes the given object from the state trie. -func (self *StateDB) deleteStateObject(stateObject *stateObject) { +func (stateDB *StateDB) deleteStateObject(stateObject *stateObject) { stateObject.deleted = true addr := stateObject.Address() - self.setError(self.trie.TryDelete(addr[:])) + stateDB.setError(stateDB.trie.TryDelete(addr[:])) } // Retrieve a state object given by the address. Returns nil if not found. -func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { +func (stateDB *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { // Prefer 'live' objects. - if obj := self.stateObjects[addr]; obj != nil { + if obj := stateDB.stateObjects[addr]; obj != nil { if obj.deleted { return nil } @@ -416,9 +430,9 @@ func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObje } // Load the object from the database. - enc, err := self.trie.TryGet(addr[:]) + enc, err := stateDB.trie.TryGet(addr[:]) if len(enc) == 0 { - self.setError(err) + stateDB.setError(err) return nil } var data Account @@ -427,36 +441,36 @@ func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObje return nil } // Insert into the live set. - obj := newObject(self, addr, data) - self.setStateObject(obj) + obj := newObject(stateDB, addr, data) + stateDB.setStateObject(obj) return obj } -func (self *StateDB) setStateObject(object *stateObject) { - self.stateObjects[object.Address()] = object +func (stateDB *StateDB) setStateObject(object *stateObject) { + stateDB.stateObjects[object.Address()] = object } -// Retrieve a state object or create a new state object if nil. -func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { - stateObject := self.getStateObject(addr) +// GetOrNewStateObject retrieves a state object or create a new state object if nil. +func (stateDB *StateDB) GetOrNewStateObject(addr common.Address) *StateObject { + stateObject := stateDB.getStateObject(addr) if stateObject == nil || stateObject.deleted { - stateObject, _ = self.createObject(addr) + stateObject, _ = stateDB.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 (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { - prev = self.getStateObject(addr) - newobj = newObject(self, addr, Account{}) +func (stateDB *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { + prev = stateDB.getStateObject(addr) + newobj = newObject(stateDB, addr, Account{}) newobj.setNonce(0) // sets the object to dirty if prev == nil { - self.journal.append(createObjectChange{account: &addr}) + stateDB.journal.append(createObjectChange{account: &addr}) } else { - self.journal.append(resetObjectChange{prev: prev}) + stateDB.journal.append(resetObjectChange{prev: prev}) } - self.setStateObject(newobj) + stateDB.setStateObject(newobj) return newobj, prev } @@ -470,21 +484,22 @@ func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObjec // 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 (self *StateDB) CreateAccount(addr common.Address) { - new, prev := self.createObject(addr) +func (stateDB *StateDB) CreateAccount(addr common.Address) { + new, prev := stateDB.createObject(addr) if prev != nil { new.setBalance(prev.data.Balance) } } -func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { - so := db.getStateObject(addr) +// ForEachStorage runs a function on every item in state DB. +func (stateDB *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { + so := stateDB.getStateObject(addr) if so == nil { return } - it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) + it := trie.NewIterator(so.getTrie(stateDB.db).NodeIterator(nil)) for it.Next() { - key := common.BytesToHash(db.trie.GetKey(it.Key)) + key := common.BytesToHash(stateDB.trie.GetKey(it.Key)) if value, dirty := so.dirtyStorage[key]; dirty { cb(key, value) continue @@ -495,29 +510,29 @@ func (db *StateDB) 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 (self *StateDB) Copy() *StateDB { - self.lock.Lock() - defer self.lock.Unlock() +func (stateDB *StateDB) Copy() *StateDB { + stateDB.lock.Lock() + defer stateDB.lock.Unlock() // Copy all the basic fields, initialize the memory ones state := &StateDB{ - db: self.db, - trie: self.db.CopyTrie(self.trie), - stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)), - stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)), - refund: self.refund, - logs: make(map[common.Hash][]*types.Log, len(self.logs)), - logSize: self.logSize, + db: stateDB.db, + trie: stateDB.db.CopyTrie(stateDB.trie), + stateObjects: make(map[common.Address]*stateObject, 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, preimages: make(map[common.Hash][]byte), journal: newJournal(), } // Copy the dirty states, logs, and preimages - for addr := range self.journal.dirties { + for addr := range stateDB.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 := self.stateObjects[addr]; exist { + if object, exist := stateDB.stateObjects[addr]; exist { state.stateObjects[addr] = object.deepCopy(state) state.stateObjectsDirty[addr] = struct{}{} } @@ -525,13 +540,13 @@ func (self *StateDB) Copy() *StateDB { // 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 self.stateObjectsDirty { + for addr := range stateDB.stateObjectsDirty { if _, exist := state.stateObjects[addr]; !exist { - state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) + state.stateObjects[addr] = stateDB.stateObjects[addr].deepCopy(state) state.stateObjectsDirty[addr] = struct{}{} } } - for hash, logs := range self.logs { + for hash, logs := range stateDB.logs { cpy := make([]*types.Log, len(logs)) for i, l := range logs { cpy[i] = new(types.Log) @@ -539,46 +554,46 @@ func (self *StateDB) Copy() *StateDB { } state.logs[hash] = cpy } - for hash, preimage := range self.preimages { + for hash, preimage := range stateDB.preimages { state.preimages[hash] = preimage } return state } // Snapshot returns an identifier for the current revision of the state. -func (self *StateDB) Snapshot() int { - id := self.nextRevisionId - self.nextRevisionId++ - self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) +func (stateDB *StateDB) Snapshot() int { + id := stateDB.nextRevisionID + stateDB.nextRevisionID++ + stateDB.validRevisions = append(stateDB.validRevisions, revision{id, stateDB.journal.length()}) return id } // RevertToSnapshot reverts all state changes made since the given revision. -func (self *StateDB) RevertToSnapshot(revid int) { +func (stateDB *StateDB) RevertToSnapshot(revid int) { // Find the snapshot in the stack of valid snapshots. - idx := sort.Search(len(self.validRevisions), func(i int) bool { - return self.validRevisions[i].id >= revid + idx := sort.Search(len(stateDB.validRevisions), func(i int) bool { + return stateDB.validRevisions[i].id >= revid }) - if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { + if idx == len(stateDB.validRevisions) || stateDB.validRevisions[idx].id != revid { panic(fmt.Errorf("revision id %v cannot be reverted", revid)) } - snapshot := self.validRevisions[idx].journalIndex + snapshot := stateDB.validRevisions[idx].journalIndex // Replay the journal to undo changes and remove invalidated snapshots - self.journal.revert(self, snapshot) - self.validRevisions = self.validRevisions[:idx] + stateDB.journal.revert(stateDB, snapshot) + stateDB.validRevisions = stateDB.validRevisions[:idx] } // GetRefund returns the current value of the refund counter. -func (self *StateDB) GetRefund() uint64 { - return self.refund +func (stateDB *StateDB) GetRefund() uint64 { + return stateDB.refund } // Finalise finalises the state by removing the self destructed objects // and clears the journal as well as the refunds. -func (s *StateDB) Finalise(deleteEmptyObjects bool) { - for addr := range s.journal.dirties { - stateObject, exist := s.stateObjects[addr] +func (stateDB *StateDB) Finalise(deleteEmptyObjects bool) { + for addr := range stateDB.journal.dirties { + stateObject, exist := stateDB.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 @@ -604,27 +619,27 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) { // 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 (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { +func (stateDB *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { s.Finalise(deleteEmptyObjects) return s.trie.Hash() } // Prepare sets the current transaction hash and index and block hash which is // used when the EVM emits new state logs. -func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { - self.thash = thash - self.bhash = bhash - self.txIndex = ti +func (stateDB *StateDB) Prepare(thash, bhash common.Hash, ti int) { + stateDB.thash = thash + stateDB.bhash = bhash + stateDB.txIndex = ti } -func (s *StateDB) clearJournalAndRefund() { +func (stateDB *StateDB) clearJournalAndRefund() { s.journal = newJournal() s.validRevisions = s.validRevisions[:0] s.refund = 0 } // Commit writes the state to the underlying in-memory trie database. -func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { +func (stateDB *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { defer s.clearJournalAndRefund() for addr := range s.journal.dirties { From 40553e0fa5c37a28c3219e401083a88c25b9d78d Mon Sep 17 00:00:00 2001 From: Minh Doan Date: Fri, 30 Nov 2018 09:07:06 -0800 Subject: [PATCH 3/3] fix other golint --- core/state/managed_state.go | 1 - core/state/state_object.go | 6 ++--- core/state/statedb.go | 50 ++++++++++++++++++------------------- 3 files changed, 27 insertions(+), 30 deletions(-) diff --git a/core/state/managed_state.go b/core/state/managed_state.go index a9d9bf3c7..8bb6744dd 100644 --- a/core/state/managed_state.go +++ b/core/state/managed_state.go @@ -95,7 +95,6 @@ func (ms *ManagedState) GetNonce(addr common.Address) uint64 { return uint64(len(account.nonces)) + account.nstart } return ms.StateDB.GetNonce(addr) - } // SetNonce sets the new canonical nonce for the managed state diff --git a/core/state/state_object.go b/core/state/state_object.go index 7f86058b3..7a922d88e 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -59,8 +59,8 @@ func (storage Storage) Copy() Storage { // stateObject represents an Ethereum account which is being modified. // // The usage pattern is as follows: -// First you need to obtain a state s. -// Account values can be accessed and modified through the s. +// First you need to obtain a state object. +// Account values can be accessed and modified through the object. // Finally, call CommitTrie to write the modified storage trie into a database. type stateObject struct { address common.Address @@ -104,7 +104,7 @@ type Account struct { CodeHash []byte } -// newObject creates a state s. +// newObject creates a state object. func newObject(db *StateDB, address common.Address, data Account) *stateObject { if data.Balance == nil { data.Balance = new(big.Int) diff --git a/core/state/statedb.go b/core/state/statedb.go index 4ab0a637c..1cdf11170 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -1,4 +1,3 @@ -// package state ... // Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // @@ -19,7 +18,6 @@ package state import ( - "github.com/harmony-one/harmony/core/state" "errors" "fmt" "math/big" @@ -451,7 +449,7 @@ func (stateDB *StateDB) setStateObject(object *stateObject) { } // GetOrNewStateObject retrieves a state object or create a new state object if nil. -func (stateDB *StateDB) GetOrNewStateObject(addr common.Address) *StateObject { +func (stateDB *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { stateObject := stateDB.getStateObject(addr) if stateObject == nil || stateObject.deleted { stateObject, _ = stateDB.createObject(addr) @@ -605,23 +603,23 @@ func (stateDB *StateDB) Finalise(deleteEmptyObjects bool) { } if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { - s.deleteStateObject(stateObject) + stateDB.deleteStateObject(stateObject) } else { - stateObject.updateRoot(s.db) - s.updateStateObject(stateObject) + stateObject.updateRoot(stateDB.db) + stateDB.updateStateObject(stateObject) } - s.stateObjectsDirty[addr] = struct{}{} + stateDB.stateObjectsDirty[addr] = struct{}{} } // Invalidate journal because reverting across transactions is not allowed. - s.clearJournalAndRefund() + stateDB.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 *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { - s.Finalise(deleteEmptyObjects) - return s.trie.Hash() + stateDB.Finalise(deleteEmptyObjects) + return stateDB.trie.Hash() } // Prepare sets the current transaction hash and index and block hash which is @@ -633,53 +631,53 @@ func (stateDB *StateDB) Prepare(thash, bhash common.Hash, ti int) { } func (stateDB *StateDB) clearJournalAndRefund() { - s.journal = newJournal() - s.validRevisions = s.validRevisions[:0] - s.refund = 0 + stateDB.journal = newJournal() + stateDB.validRevisions = stateDB.validRevisions[:0] + stateDB.refund = 0 } // Commit writes the state to the underlying in-memory trie database. func (stateDB *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { - defer s.clearJournalAndRefund() + defer stateDB.clearJournalAndRefund() - for addr := range s.journal.dirties { - s.stateObjectsDirty[addr] = struct{}{} + for addr := range stateDB.journal.dirties { + stateDB.stateObjectsDirty[addr] = struct{}{} } // Commit objects to the trie. - for addr, stateObject := range s.stateObjects { - _, isDirty := s.stateObjectsDirty[addr] + for addr, stateObject := range stateDB.stateObjects { + _, isDirty := stateDB.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. - s.deleteStateObject(stateObject) + stateDB.deleteStateObject(stateObject) case isDirty: // Write any contract code associated with the state object if stateObject.code != nil && stateObject.dirtyCode { - s.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code) + stateDB.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(s.db); err != nil { + if err := stateObject.CommitTrie(stateDB.db); err != nil { return common.Hash{}, err } // Update the object in the main account trie. - s.updateStateObject(stateObject) + stateDB.updateStateObject(stateObject) } - delete(s.stateObjectsDirty, addr) + delete(stateDB.stateObjectsDirty, addr) } // Write trie changes. - root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error { + root, err = stateDB.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 { - s.db.TrieDB().Reference(account.Root, parent) + stateDB.db.TrieDB().Reference(account.Root, parent) } code := common.BytesToHash(account.CodeHash) if code != emptyCode { - s.db.TrieDB().Reference(code, parent) + stateDB.db.TrieDB().Reference(code, parent) } return nil })