all: add and use Hash.IsZero helper func

This commit is contained in:
islishude 2024-04-25 15:46:49 +08:00
parent 4f4f9d88d3
commit 2c235985ae
78 changed files with 214 additions and 186 deletions

View file

@ -190,7 +190,7 @@ func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method stri
return ErrNoCode
}
}
} else if opts.BlockHash != (common.Hash{}) {
} else if !opts.BlockHash.IsZero() {
bh, ok := c.caller.(BlockHashContractCaller)
if !ok {
return ErrNoBlockHashState

View file

@ -85,7 +85,7 @@ func (s *beaconBlockSync) Process(requester request.Requester, events []request.
s.tryRequestBlock(requester, vh.Attested.Hash(), false)
}
// request prefetch head if the given server has announced it
if prefetchHead := s.headTracker.PrefetchHead().BlockRoot; prefetchHead != (common.Hash{}) {
if prefetchHead := s.headTracker.PrefetchHead().BlockRoot; !prefetchHead.IsZero() {
s.tryRequestBlock(requester, prefetchHead, true)
}
}

View file

@ -216,7 +216,7 @@ func decodeOptimisticUpdate(enc []byte) (types.OptimisticUpdate, error) {
if err != nil {
return types.OptimisticUpdate{}, fmt.Errorf("invalid attested header: %v", err)
}
if data.Data.Attested.Beacon.StateRoot == (common.Hash{}) {
if data.Data.Attested.Beacon.StateRoot.IsZero() {
// workaround for different event encoding format in Lodestar
if err := json.Unmarshal(enc, &data.Data); err != nil {
return types.OptimisticUpdate{}, err
@ -306,7 +306,7 @@ func decodeFinalityUpdate(enc []byte) (types.FinalityUpdate, error) {
// these flags are not validated.
func (api *BeaconLightApi) GetHeader(blockRoot common.Hash) (types.Header, bool, bool, error) {
var blockId string
if blockRoot == (common.Hash{}) {
if blockRoot.IsZero() {
blockId = "head"
} else {
blockId = blockRoot.Hex()
@ -331,7 +331,7 @@ func (api *BeaconLightApi) GetHeader(blockRoot common.Hash) (types.Header, bool,
return types.Header{}, false, false, err
}
header := data.Data.Header.Message
if blockRoot == (common.Hash{}) {
if blockRoot.IsZero() {
blockRoot = data.Data.Root
}
if header.Hash() != blockRoot {

View file

@ -229,7 +229,7 @@ func (s *CommitteeChain) CheckpointInit(bootstrap types.BootstrapData) error {
// Note that the period where the first committee is added has to have a fixed
// root which can either come from a BootstrapData or a trusted source.
func (s *CommitteeChain) addFixedCommitteeRoot(period uint64, root common.Hash) error {
if root == (common.Hash{}) {
if root.IsZero() {
return ErrWrongCommitteeRoot
}
@ -257,7 +257,7 @@ func (s *CommitteeChain) addFixedCommitteeRoot(period uint64, root common.Hash)
}
}
}
if oldRoot != (common.Hash{}) && (oldRoot != root) {
if !oldRoot.IsZero() && (oldRoot != root) {
// existing old root was different, we have to reorg the chain
if err := s.rollback(period); err != nil {
return err
@ -321,7 +321,7 @@ func (s *CommitteeChain) addCommittee(period uint64, committee *types.Serialized
return ErrInvalidPeriod
}
root := s.getCommitteeRoot(period)
if root == (common.Hash{}) {
if root.IsZero() {
return ErrInvalidPeriod
}
if root != committee.Root() {
@ -349,7 +349,7 @@ func (s *CommitteeChain) InsertUpdate(update *types.LightClientUpdate, nextCommi
return ErrInvalidUpdate
}
oldRoot := s.getCommitteeRoot(period + 1)
reorg := oldRoot != (common.Hash{}) && oldRoot != update.NextSyncCommitteeRoot
reorg := !oldRoot.IsZero() && oldRoot != update.NextSyncCommitteeRoot
if oldUpdate, ok := s.updates.get(s.db, period); ok && !update.Score().BetterThan(oldUpdate.Score()) {
// a better or equal update already exists; no changes, only fail if new one tried to reorg
if reorg {

View file

@ -409,7 +409,7 @@ func rlpHash(x interface{}) (h common.Hash) {
func calcDifficulty(config *params.ChainConfig, number, currentTime, parentTime uint64,
parentDifficulty *big.Int, parentUncleHash common.Hash) *big.Int {
uncleHash := parentUncleHash
if uncleHash == (common.Hash{}) {
if uncleHash.IsZero() {
uncleHash = types.EmptyUncleHash
}
parent := &types.Header{

View file

@ -56,7 +56,7 @@ func (r *result) MarshalJSON() ([]byte, error) {
if r.Address != (common.Address{}) {
out.Address = &r.Address
}
if r.Hash != (common.Hash{}) {
if !r.Hash.IsZero() {
out.Hash = &r.Hash
}
out.IntrinsicGas = hexutil.Uint64(r.IntrinsicGas)

View file

@ -535,7 +535,7 @@ func parseDumpConfig(ctx *cli.Context, stack *node.Node, db ethdb.Database) (*st
if err != nil {
return nil, common.Hash{}, err
}
if hash := rawdb.ReadCanonicalHash(db, number); hash != (common.Hash{}) {
if hash := rawdb.ReadCanonicalHash(db, number); !hash.IsZero() {
header = rawdb.ReadHeader(db, hash, number)
} else {
return nil, common.Hash{}, fmt.Errorf("header for block %d not found", number)

View file

@ -922,7 +922,7 @@ func inspectHistory(ctx *cli.Context) error {
}
}
// Inspect the state history.
if slot == (common.Hash{}) {
if slot.IsZero() {
return inspectAccount(triedb, start, end, address, ctx.Bool("raw"))
}
return inspectStorage(triedb, start, end, address, slot, ctx.Bool("raw"))

View file

@ -439,7 +439,7 @@ func traverseRawState(ctx *cli.Context) error {
// Check the present for non-empty hash node(embedded node doesn't
// have their own hash).
if node != (common.Hash{}) {
if !node.IsZero() {
blob, _ := reader.Node(common.Hash{}, accIter.Path(), node)
if len(blob) == 0 {
log.Error("Missing trie node(account)", "hash", node)
@ -480,7 +480,7 @@ func traverseRawState(ctx *cli.Context) error {
// Check the presence for non-empty hash node(embedded node doesn't
// have their own hash).
if node != (common.Hash{}) {
if !node.IsZero() {
blob, _ := reader.Node(common.BytesToHash(accIter.LeafKey()), storageIter.Path(), node)
if len(blob) == 0 {
log.Error("Missing trie node(storage)", "hash", node)

View file

@ -617,7 +617,7 @@ func ExportSnapshotPreimages(chaindb ethdb.Database, snaptree *snapshot.Tree, fn
preimages += 1
hashCh <- hashAndPreimageSize{Hash: accIt.Hash(), Size: common.AddressLength}
if acc.Root != (common.Hash{}) && acc.Root != types.EmptyRootHash {
if !acc.Root.IsZero() && acc.Root != types.EmptyRootHash {
stIt, err := snaptree.StorageIterator(root, accIt.Hash(), common.Hash{})
if err != nil {
log.Error("Failed to create storage iterator", "error", err)

View file

@ -1863,7 +1863,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
cfg.Genesis = core.DeveloperGenesisBlock(ctx.Uint64(DeveloperGasLimitFlag.Name), &developer.Address)
if ctx.IsSet(DataDirFlag.Name) {
chaindb := tryMakeReadOnlyDatabase(ctx, stack)
if rawdb.ReadCanonicalHash(chaindb, 0) != (common.Hash{}) {
if !rawdb.ReadCanonicalHash(chaindb, 0).IsZero() {
cfg.Genesis = nil // fallback to db content
//validate genesis has PoS enabled in block 0

View file

@ -179,6 +179,16 @@ func (h Hash) Value() (driver.Value, error) {
return h[:], nil
}
// IsZero checks if the Hash is a zero value
func (h Hash) IsZero() bool {
for _, b := range h {
if b != 0 {
return false
}
}
return true
}
// ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" }

View file

@ -595,3 +595,21 @@ func BenchmarkPrettyDuration(b *testing.B) {
}
b.Logf("Post %s", a)
}
func TestHash_IsZero(t *testing.T) {
tests := []struct {
name string
h Hash
want bool
}{
{"yes", Hash{}, true},
{"no", Hash{1}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.h.IsZero(); got != tt.want {
t.Errorf("Hash.IsZero() = %v, want %v", got, tt.want)
}
})
}
}

View file

@ -282,7 +282,7 @@ func (c *Clique) verifyHeader(chain consensus.ChainHeaderReader, header *types.H
return errInvalidCheckpointSigners
}
// Ensure that the mix digest is zero as we don't have fork protection currently
if header.MixDigest != (common.Hash{}) {
if !header.MixDigest.IsZero() {
return errInvalidMixDigest
}
// Ensure that the block doesn't contain any uncles which are meaningless in PoA

View file

@ -358,7 +358,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
if bc.cacheConfig.SnapshotLimit > 0 {
diskRoot = rawdb.ReadSnapshotRoot(bc.db)
}
if diskRoot != (common.Hash{}) {
if !diskRoot.IsZero() {
log.Warn("Head state missing, repairing", "number", head.Number, "hash", head.Hash(), "snaproot", diskRoot)
snapDisk, err := bc.setHeadBeyondRoot(head.Number.Uint64(), 0, diskRoot, true)
@ -487,7 +487,7 @@ func (bc *BlockChain) empty() bool {
func (bc *BlockChain) loadLastState() error {
// Restore the last known head block
head := rawdb.ReadHeadBlockHash(bc.db)
if head == (common.Hash{}) {
if head.IsZero() {
// Corrupt or empty database, init from scratch
log.Warn("Empty database, resetting chain")
return bc.Reset()
@ -505,7 +505,7 @@ func (bc *BlockChain) loadLastState() error {
// Restore the last known head header
headHeader := headBlock.Header()
if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
if head := rawdb.ReadHeadHeaderHash(bc.db); !head.IsZero() {
if header := bc.GetHeaderByHash(head); header != nil {
headHeader = header
}
@ -516,7 +516,7 @@ func (bc *BlockChain) loadLastState() error {
bc.currentSnapBlock.Store(headBlock.Header())
headFastBlockGauge.Update(int64(headBlock.NumberU64()))
if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
if head := rawdb.ReadHeadFastBlockHash(bc.db); !head.IsZero() {
if block := bc.GetBlockByHash(head); block != nil {
bc.currentSnapBlock.Store(block.Header())
headFastBlockGauge.Update(int64(block.NumberU64()))
@ -526,7 +526,7 @@ func (bc *BlockChain) loadLastState() error {
// Restore the last known finalized block and safe block
// Note: the safe block is not stored on disk and it is set to the last
// known finalized block on startup
if head := rawdb.ReadFinalizedBlockHash(bc.db); head != (common.Hash{}) {
if head := rawdb.ReadFinalizedBlockHash(bc.db); !head.IsZero() {
if block := bc.GetBlockByHash(head); block != nil {
bc.currentFinalBlock.Store(block.Header())
headFinalizedBlockGauge.Update(int64(block.NumberU64()))
@ -629,7 +629,7 @@ func (bc *BlockChain) SetSafe(header *types.Header) {
func (bc *BlockChain) rewindHashHead(head *types.Header, root common.Hash) (*types.Header, uint64) {
var (
limit uint64 // The oldest block that will be searched for this rewinding
beyondRoot = root == common.Hash{} // Flag whether we're beyond the requested root (no root, always true)
beyondRoot = root.IsZero() // Flag whether we're beyond the requested root (no root, always true)
pivot = rawdb.ReadLastPivotNumber(bc.db) // Associated block number of pivot point state
rootNumber uint64 // Associated block number of requested root
@ -709,7 +709,7 @@ func (bc *BlockChain) rewindPathHead(head *types.Header, root common.Hash) (*typ
// BeyondRoot represents whether the requested root is already
// crossed. The flag value is set to true if the root is empty.
beyondRoot = root == common.Hash{}
beyondRoot = root.IsZero()
// noState represents if the target state requested for search
// is unavailable and impossible to be recovered.
@ -1139,7 +1139,7 @@ func (bc *BlockChain) Stop() {
}
}
}
if snapBase != (common.Hash{}) {
if !snapBase.IsZero() {
log.Info("Writing snapshot state to disk", "root", snapBase)
if err := triedb.Commit(snapBase, true); err != nil {
log.Error("Failed to commit recent state trie", "err", err)
@ -2308,7 +2308,7 @@ func (bc *BlockChain) reorg(oldHead *types.Header, newHead *types.Block) error {
}
for i := number + 1; ; i++ {
hash := rawdb.ReadCanonicalHash(bc.db, i)
if hash == (common.Hash{}) {
if hash.IsZero() {
break
}
rawdb.DeleteCanonicalHash(indexesBatch, i)
@ -2454,7 +2454,7 @@ func (bc *BlockChain) skipBlock(err error, it *insertIterator) bool {
} else if parent = bc.GetHeaderByHash(header.ParentHash); parent != nil {
parentRoot = parent.Root
}
if parentRoot == (common.Hash{}) {
if parentRoot.IsZero() {
return false // Theoretically impossible case
}
// Parent is also missing snapshot: we can skip this. Otherwise process.

View file

@ -184,7 +184,7 @@ func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
// (associated with its hash) if found.
func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
hash := rawdb.ReadCanonicalHash(bc.db, number)
if hash == (common.Hash{}) {
if hash.IsZero() {
return nil
}
return bc.GetBlock(hash, number)

View file

@ -1440,7 +1440,7 @@ func testCanonicalBlockRetrieval(t *testing.T, scheme string) {
// try to retrieve a block by its canonical hash and see if the block data can be retrieved.
for {
ch := rawdb.ReadCanonicalHash(blockchain.db, block.NumberU64())
if ch == (common.Hash{}) {
if ch.IsZero() {
continue // busy wait for canonical hash to be written
}
if ch != block.Hash() {

View file

@ -397,7 +397,7 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
hash := rawdb.ReadCanonicalHash(c.chainDb, number)
if hash == (common.Hash{}) {
if hash.IsZero() {
return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
}
header := rawdb.ReadHeader(c.chainDb, hash, number)

View file

@ -78,7 +78,7 @@ type Genesis struct {
func ReadGenesis(db ethdb.Database) (*Genesis, error) {
var genesis Genesis
stored := rawdb.ReadCanonicalHash(db, 0)
if (stored == common.Hash{}) {
if stored.IsZero() {
return nil, fmt.Errorf("invalid genesis hash in database: %x", stored)
}
blob := rawdb.ReadGenesisStateSpec(db, stored)
@ -281,7 +281,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *triedb.Database, g
}
// Just commit the new block if there is no stored genesis block.
stored := rawdb.ReadCanonicalHash(db, 0)
if (stored == common.Hash{}) {
if stored.IsZero() {
if genesis == nil {
log.Info("Writing default main-net genesis block")
genesis = DefaultGenesisBlock()
@ -371,7 +371,7 @@ func LoadChainConfig(db ethdb.Database, genesis *Genesis) (*params.ChainConfig,
// in case the database is empty. Notably, we only care about the
// chain config corresponds to the canonical chain.
stored := rawdb.ReadCanonicalHash(db, 0)
if stored != (common.Hash{}) {
if !stored.IsZero() {
storedcfg := rawdb.ReadChainConfig(db, stored)
if storedcfg != nil {
return storedcfg, nil
@ -387,7 +387,7 @@ func LoadChainConfig(db ethdb.Database, genesis *Genesis) (*params.ChainConfig,
// config is missing(initialize the empty leveldb with an
// external ancient chain segment), ensure the provided genesis
// is matched.
if stored != (common.Hash{}) && genesis.ToBlock().Hash() != stored {
if !stored.IsZero() && genesis.ToBlock().Hash() != stored {
return nil, &GenesisMismatchError{stored, genesis.ToBlock().Hash()}
}
return genesis.Config, nil
@ -443,7 +443,7 @@ func (g *Genesis) ToBlock() *types.Block {
if g.GasLimit == 0 {
head.GasLimit = params.GenesisGasLimit
}
if g.Difficulty == nil && g.Mixhash == (common.Hash{}) {
if g.Difficulty == nil && g.Mixhash.IsZero() {
head.Difficulty = params.GenesisDifficulty
}
if g.Config != nil && g.Config.IsLondon(common.Big0) {

View file

@ -89,7 +89,7 @@ func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine c
return nil, ErrNoGenesis
}
hc.currentHeader.Store(hc.genesisHeader)
if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
if head := rawdb.ReadHeadBlockHash(chainDb); !head.IsZero() {
if chead := hc.GetHeaderByHash(head); chead != nil {
hc.currentHeader.Store(chead)
}
@ -141,7 +141,7 @@ func (hc *HeaderChain) Reorg(headers []*types.Header) error {
// Delete any canonical number assignments above the new head
for i := last.Number.Uint64() + 1; ; i++ {
hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
if hash == (common.Hash{}) {
if hash.IsZero() {
break
}
rawdb.DeleteCanonicalHash(batch, i)
@ -457,7 +457,7 @@ func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
// caching it (associated with its hash) if found.
func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
if hash == (common.Hash{}) {
if hash.IsZero() {
return nil
}
return hc.GetHeader(hash, number)
@ -481,7 +481,7 @@ func (hc *HeaderChain) GetHeadersFrom(number, count uint64) []rlp.RawValue {
var headers []rlp.RawValue
// If we have some of the headers in cache already, use that before going to db.
hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
if hash == (common.Hash{}) {
if hash.IsZero() {
return nil
}
for count > 0 {

View file

@ -943,7 +943,7 @@ func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header {
// ReadHeadHeader returns the current canonical head header.
func ReadHeadHeader(db ethdb.Reader) *types.Header {
headHeaderHash := ReadHeadHeaderHash(db)
if headHeaderHash == (common.Hash{}) {
if headHeaderHash.IsZero() {
return nil
}
headHeaderNumber := ReadHeaderNumber(db, headHeaderHash)
@ -956,7 +956,7 @@ func ReadHeadHeader(db ethdb.Reader) *types.Header {
// ReadHeadBlock returns the current canonical head block.
func ReadHeadBlock(db ethdb.Reader) *types.Block {
headBlockHash := ReadHeadBlockHash(db)
if headBlockHash == (common.Hash{}) {
if headBlockHash.IsZero() {
return nil
}
headBlockNumber := ReadHeaderNumber(db, headBlockHash)

View file

@ -292,7 +292,7 @@ func TestCanonicalMappingStorage(t *testing.T) {
}
// Write and verify the TD in the database
WriteCanonicalHash(db, hash, number)
if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
if entry := ReadCanonicalHash(db, number); entry.IsZero() {
t.Fatalf("Stored canonical mapping not found")
} else if entry != hash {
t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)

View file

@ -101,7 +101,7 @@ func ReadTransaction(db ethdb.Reader, hash common.Hash) (*types.Transaction, com
return nil, common.Hash{}, 0, 0
}
blockHash := ReadCanonicalHash(db, *blockNumber)
if blockHash == (common.Hash{}) {
if blockHash.IsZero() {
return nil, common.Hash{}, 0, 0
}
body := ReadBody(db, blockHash, *blockNumber)
@ -127,7 +127,7 @@ func ReadReceipt(db ethdb.Reader, hash common.Hash, config *params.ChainConfig)
return nil, common.Hash{}, 0, 0
}
blockHash := ReadCanonicalHash(db, *blockNumber)
if blockHash == (common.Hash{}) {
if blockHash.IsZero() {
return nil, common.Hash{}, 0, 0
}
blockHeader := ReadHeader(db, blockHash, *blockNumber)

View file

@ -198,7 +198,7 @@ func HasTrieNode(db ethdb.KeyValueReader, owner common.Hash, path []byte, hash c
case HashScheme:
return HasLegacyTrieNode(db, hash)
case PathScheme:
if owner == (common.Hash{}) {
if owner.IsZero() {
return HasAccountTrieNode(db, path, hash)
}
return HasStorageTrieNode(db, owner, path, hash)
@ -224,7 +224,7 @@ func ReadTrieNode(db ethdb.KeyValueReader, owner common.Hash, path []byte, hash
blob []byte
nHash common.Hash
)
if owner == (common.Hash{}) {
if owner.IsZero() {
blob, nHash = ReadAccountTrieNode(db, path)
} else {
blob, nHash = ReadStorageTrieNode(db, owner, path)
@ -251,7 +251,7 @@ func WriteTrieNode(db ethdb.KeyValueWriter, owner common.Hash, path []byte, hash
case HashScheme:
WriteLegacyTrieNode(db, hash, node)
case PathScheme:
if owner == (common.Hash{}) {
if owner.IsZero() {
WriteAccountTrieNode(db, path, node)
} else {
WriteStorageTrieNode(db, owner, path, node)
@ -274,7 +274,7 @@ func DeleteTrieNode(db ethdb.KeyValueWriter, owner common.Hash, path []byte, has
case HashScheme:
DeleteLegacyTrieNode(db, hash)
case PathScheme:
if owner == (common.Hash{}) {
if owner.IsZero() {
DeleteAccountTrieNode(db, path)
} else {
DeleteStorageTrieNode(db, owner, path)

View file

@ -77,7 +77,7 @@ func (f *chainFreezer) Close() error {
// block is unknown or not available yet.
func (f *chainFreezer) readHeadNumber(db ethdb.KeyValueReader) uint64 {
hash := ReadHeadBlockHash(db)
if hash == (common.Hash{}) {
if hash.IsZero() {
log.Error("Head block is not reachable")
return 0
}
@ -93,7 +93,7 @@ func (f *chainFreezer) readHeadNumber(db ethdb.KeyValueReader) uint64 {
// if the block is unknown or not available yet.
func (f *chainFreezer) readFinalizedNumber(db ethdb.KeyValueReader) uint64 {
hash := ReadFinalizedBlockHash(db)
if hash == (common.Hash{}) {
if hash.IsZero() {
return 0
}
number := ReadHeaderNumber(db, hash)
@ -286,7 +286,7 @@ func (f *chainFreezer) freezeRange(nfdb *nofreezedb, number, limit uint64) (hash
for ; number <= limit; number++ {
// Retrieve all the components of the canonical block.
hash := ReadCanonicalHash(nfdb, number)
if hash == (common.Hash{}) {
if hash.IsZero() {
return fmt.Errorf("canonical hash missing, can't freeze block %d", number)
}
header := ReadHeaderRLP(nfdb, hash, number)

View file

@ -159,7 +159,7 @@ func (it *nodeIterator) retrieve() bool {
switch {
case it.dataIt != nil:
it.Hash, it.Parent = it.dataIt.Hash(), it.dataIt.Parent()
if it.Parent == (common.Hash{}) {
if it.Parent.IsZero() {
it.Parent = it.accountHash
}
case it.code != nil:

View file

@ -244,7 +244,7 @@ func (p *Pruner) Prune(root common.Hash) error {
if err != nil {
return err
}
if stateBloomRoot != (common.Hash{}) {
if !stateBloomRoot.IsZero() {
return RecoverPruning(p.config.Datadir, p.db)
}
// If the target state root is not specified, use the HEAD-127 as the
@ -252,7 +252,7 @@ func (p *Pruner) Prune(root common.Hash) error {
// - in most of the normal cases, the related state is available
// - the probability of this layer being reorg is very low
var layers []snapshot.Snapshot
if root == (common.Hash{}) {
if root.IsZero() {
// Retrieve all snapshot layers from the current HEAD.
// In theory there are 128 difflayers + 1 disk layer present,
// so 128 diff layers are expected to be returned.
@ -403,7 +403,7 @@ func RecoverPruning(datadir string, db ethdb.Database) error {
// into the given bloomfilter.
func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error {
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
if genesisHash.IsZero() {
return errors.New("missing genesis hash")
}
genesis := rawdb.ReadBlock(db, genesisHash, 0)
@ -422,7 +422,7 @@ func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error {
hash := accIter.Hash()
// Embedded nodes don't have hash.
if hash != (common.Hash{}) {
if !hash.IsZero() {
stateBloom.Put(hash.Bytes(), nil)
}
// If it's a leaf node, yes we are touching an account,
@ -444,7 +444,7 @@ func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error {
}
for storageIter.Next(true) {
hash := storageIter.Hash()
if hash != (common.Hash{}) {
if !hash.IsZero() {
stateBloom.Put(hash.Bytes(), nil)
}
}

View file

@ -50,7 +50,7 @@ type generatorStats struct {
// from the internally maintained statistics.
func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) {
var ctx []interface{}
if root != (common.Hash{}) {
if !root.IsZero() {
ctx = append(ctx, []interface{}{"root", root}...)
}
// Figure out whether we're after or within an account

View file

@ -294,7 +294,7 @@ func generateTrieRoot(db ethdb.KeyValueWriter, scheme string, it Iterator, accou
)
// Start to feed leaves
for it.Next() {
if account == (common.Hash{}) {
if account.IsZero() {
var (
err error
fullData []byte
@ -342,7 +342,7 @@ func generateTrieRoot(db ethdb.KeyValueWriter, scheme string, it Iterator, accou
// Accumulate the generation statistic if it's required.
processed++
if time.Since(logged) > 3*time.Second && stats != nil {
if account == (common.Hash{}) {
if account.IsZero() {
stats.progressAccounts(it.Hash(), processed)
} else {
stats.progressContract(account, it.Hash(), processed)
@ -352,7 +352,7 @@ func generateTrieRoot(db ethdb.KeyValueWriter, scheme string, it Iterator, accou
}
// Commit the last part statistic.
if processed > 0 && stats != nil {
if account == (common.Hash{}) {
if account.IsZero() {
stats.finishAccounts(processed)
} else {
stats.finishContract(account, processed)

View file

@ -129,7 +129,7 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *triedb.Database, root comm
// Retrieve the block number and hash of the snapshot, failing if no snapshot
// is present in the database (or crashed mid-update).
baseRoot := rawdb.ReadSnapshotRoot(diskdb)
if baseRoot == (common.Hash{}) {
if baseRoot.IsZero() {
return nil, false, errors.New("missing or corrupted snapshot")
}
base := &diskLayer{

View file

@ -693,7 +693,7 @@ func (t *Tree) Journal(root common.Hash) (common.Hash, error) {
return common.Hash{}, err
}
diskroot := t.diskRoot()
if diskroot == (common.Hash{}) {
if diskroot.IsZero() {
return common.Hash{}, errors.New("invalid disk root")
}
// Secondly write out the disk layer root, ensure the

View file

@ -322,7 +322,7 @@ func (s *stateObject) updateTrie() (Trie, error) {
s.originStorage[key] = value
var encoded []byte // rlp-encoded value to be used by the snapshot
if (value != common.Hash{}) {
if !value.IsZero() {
// Encoding []byte cannot fail, ok to ignore the error.
trimmed := common.TrimLeftZeroes(value[:])
encoded, _ = rlp.EncodeToBytes(trimmed)
@ -353,7 +353,7 @@ func (s *stateObject) updateTrie() (Trie, error) {
}
// Track the original value of slot only if it's mutated first time
if _, ok := origin[khash]; !ok {
if prev == (common.Hash{}) {
if prev.IsZero() {
origin[khash] = nil // nil if it was not present previously
} else {
// Encoding []byte cannot fail, ok to ignore the error.

View file

@ -610,7 +610,7 @@ func (s *StateDB) getStateObject(addr common.Address) *stateObject {
if len(data.CodeHash) == 0 {
data.CodeHash = types.EmptyCodeHash.Bytes()
}
if data.Root == (common.Hash{}) {
if data.Root.IsZero() {
data.Root = types.EmptyRootHash
}
}
@ -994,7 +994,7 @@ func (s *StateDB) slowDeleteStorage(addr common.Address, addrHash common.Hash, r
size += common.StorageSize(common.HashLength + len(it.LeafBlob()))
continue
}
if it.Hash() == (common.Hash{}) {
if it.Hash().IsZero() {
continue
}
size += common.StorageSize(len(it.Path()))
@ -1231,11 +1231,11 @@ func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool) (common.Hash, er
s.SnapshotCommits += time.Since(start)
s.snap = nil
}
if root == (common.Hash{}) {
if root.IsZero() {
root = types.EmptyRootHash
}
origin := s.originalRoot
if origin == (common.Hash{}) {
if origin.IsZero() {
origin = types.EmptyRootHash
}
if root != origin {

View file

@ -392,9 +392,9 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
s.CreateAccount(addr)
}
contractHash := s.GetCodeHash(addr)
emptyCode := contractHash == (common.Hash{}) || contractHash == types.EmptyCodeHash
emptyCode := contractHash.IsZero() || contractHash == types.EmptyCodeHash
storageRoot := s.GetStorageRoot(addr)
emptyStorage := storageRoot == (common.Hash{}) || storageRoot == types.EmptyRootHash
emptyStorage := storageRoot.IsZero() || storageRoot == types.EmptyRootHash
if s.GetNonce(addr) == 0 && emptyCode && emptyStorage {
s.CreateContract(addr)
// We also set some code here, to prevent the

View file

@ -297,7 +297,7 @@ func (sf *subfetcher) loop() {
defer close(sf.term)
// Start by opening the trie and stop processing if it fails
if sf.owner == (common.Hash{}) {
if sf.owner.IsZero() {
trie, err := sf.db.OpenTrie(sf.root)
if err != nil {
log.Warn("Trie prefetcher failed opening trie", "root", sf.root, "err", err)

View file

@ -294,7 +294,7 @@ func (st *StateTransition) preCheck() error {
}
// Make sure the sender is an EOA
codeHash := st.state.GetCodeHash(msg.From)
if codeHash != (common.Hash{}) && codeHash != types.EmptyCodeHash {
if !codeHash.IsZero() && codeHash != types.EmptyCodeHash {
return fmt.Errorf("%w: address %v, codehash: %s", ErrSenderNoEOA,
msg.From.Hex(), codeHash)
}

View file

@ -48,7 +48,7 @@ var (
// TrieRootHash returns the hash itself if it's non-empty or the predefined
// emptyHash one instead.
func TrieRootHash(hash common.Hash) common.Hash {
if hash == (common.Hash{}) {
if hash.IsZero() {
log.Error("Zero trie root hash!")
return EmptyRootHash
}

View file

@ -105,7 +105,7 @@ func (c *Contract) isCode(udest uint64) bool {
// Do we have a contract hash already?
// If we do have a hash, that means it's a 'regular' contract. For regular
// contracts ( not temporary initcode), we store the analysis in a map
if c.CodeHash != (common.Hash{}) {
if !c.CodeHash.IsZero() {
// Does parent context have the analysis?
analysis, exist := c.jumpdests[c.CodeHash]
if !exist {

View file

@ -409,7 +409,7 @@ type codeAndHash struct {
}
func (c *codeAndHash) Hash() common.Hash {
if c.hash == (common.Hash{}) {
if c.hash.IsZero() {
c.hash = crypto.Keccak256Hash(c.code)
}
return c.hash
@ -450,8 +450,8 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
contractHash := evm.StateDB.GetCodeHash(address)
storageRoot := evm.StateDB.GetStorageRoot(address)
if evm.StateDB.GetNonce(address) != 0 ||
(contractHash != (common.Hash{}) && contractHash != types.EmptyCodeHash) || // non-empty code
(storageRoot != (common.Hash{}) && storageRoot != types.EmptyRootHash) { // non-empty storage
(!contractHash.IsZero() && contractHash != types.EmptyCodeHash) || // non-empty code
(!storageRoot.IsZero() && storageRoot != types.EmptyRootHash) { // non-empty storage
if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
}

View file

@ -111,9 +111,9 @@ func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySi
// 2. From a non-zero value address to a zero-value address (DELETE)
// 3. From a non-zero to a non-zero (CHANGE)
switch {
case current == (common.Hash{}) && y.Sign() != 0: // 0 => non 0
case current.IsZero() && y.Sign() != 0: // 0 => non 0
return params.SstoreSetGas, nil
case current != (common.Hash{}) && y.Sign() == 0: // non 0 => 0
case !current.IsZero() && y.Sign() == 0: // non 0 => 0
evm.StateDB.AddRefund(params.SstoreRefundGas)
return params.SstoreClearGas, nil
default: // non 0 => non 0 (or 0 => 0)
@ -141,23 +141,23 @@ func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySi
}
original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
if original == current {
if original == (common.Hash{}) { // create slot (2.1.1)
if original.IsZero() { // create slot (2.1.1)
return params.NetSstoreInitGas, nil
}
if value == (common.Hash{}) { // delete slot (2.1.2b)
if value.IsZero() { // delete slot (2.1.2b)
evm.StateDB.AddRefund(params.NetSstoreClearRefund)
}
return params.NetSstoreCleanGas, nil // write existing slot (2.1.2)
}
if original != (common.Hash{}) {
if current == (common.Hash{}) { // recreate slot (2.2.1.1)
if !original.IsZero() {
if current.IsZero() { // recreate slot (2.2.1.1)
evm.StateDB.SubRefund(params.NetSstoreClearRefund)
} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
} else if value.IsZero() { // delete slot (2.2.1.2)
evm.StateDB.AddRefund(params.NetSstoreClearRefund)
}
}
if original == value {
if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
if original.IsZero() { // reset to original inexistent slot (2.2.2.1)
evm.StateDB.AddRefund(params.NetSstoreResetClearRefund)
} else { // reset to original existing slot (2.2.2.2)
evm.StateDB.AddRefund(params.NetSstoreResetRefund)
@ -198,23 +198,23 @@ func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
}
original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
if original == current {
if original == (common.Hash{}) { // create slot (2.1.1)
if original.IsZero() { // create slot (2.1.1)
return params.SstoreSetGasEIP2200, nil
}
if value == (common.Hash{}) { // delete slot (2.1.2b)
if value.IsZero() { // delete slot (2.1.2b)
evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
}
return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
}
if original != (common.Hash{}) {
if current == (common.Hash{}) { // recreate slot (2.2.1.1)
if !original.IsZero() {
if current.IsZero() { // recreate slot (2.2.1.1)
evm.StateDB.SubRefund(params.SstoreClearsScheduleRefundEIP2200)
} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
} else if value.IsZero() { // delete slot (2.2.1.2)
evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
}
}
if original == value {
if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
if original.IsZero() { // reset to original inexistent slot (2.2.2.1)
evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
} else { // reset to original existing slot (2.2.2.2)
evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)

View file

@ -59,25 +59,25 @@ func makeGasSStoreFunc(clearingRefund uint64) gasFunc {
}
original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
if original == current {
if original == (common.Hash{}) { // create slot (2.1.1)
if original.IsZero() { // create slot (2.1.1)
return cost + params.SstoreSetGasEIP2200, nil
}
if value == (common.Hash{}) { // delete slot (2.1.2b)
if value.IsZero() { // delete slot (2.1.2b)
evm.StateDB.AddRefund(clearingRefund)
}
// EIP-2200 original clause:
// return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
return cost + (params.SstoreResetGasEIP2200 - params.ColdSloadCostEIP2929), nil // write existing slot (2.1.2)
}
if original != (common.Hash{}) {
if current == (common.Hash{}) { // recreate slot (2.2.1.1)
if !original.IsZero() {
if current.IsZero() { // recreate slot (2.2.1.1)
evm.StateDB.SubRefund(clearingRefund)
} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
} else if value.IsZero() { // delete slot (2.2.1.2)
evm.StateDB.AddRefund(clearingRefund)
}
}
if original == value {
if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
if original.IsZero() { // reset to original inexistent slot (2.2.2.1)
// EIP 2200 Original clause:
//evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.WarmStorageReadCostEIP2929)

View file

@ -152,7 +152,7 @@ func (b *EthAPIBackend) BlockByHash(ctx context.Context, hash common.Hash) (*typ
// GetBody returns body of a block. It does not resolve special block numbers.
func (b *EthAPIBackend) GetBody(ctx context.Context, hash common.Hash, number rpc.BlockNumber) (*types.Body, error) {
if number < 0 || hash == (common.Hash{}) {
if number < 0 || hash.IsZero() {
return nil, errors.New("invalid arguments; expect hash and no special block numbers")
}
if body := b.eth.blockchain.GetBody(hash); body != nil {

View file

@ -231,7 +231,7 @@ func (api *DebugAPI) StorageRangeAt(ctx context.Context, blockNrOrHash rpc.Block
func storageRangeAt(statedb *state.StateDB, root common.Hash, address common.Address, start []byte, maxResult int) (StorageRangeResult, error) {
storageRoot := statedb.GetStorageRoot(address)
if storageRoot == types.EmptyRootHash || storageRoot == (common.Hash{}) {
if storageRoot == types.EmptyRootHash || storageRoot.IsZero() {
return StorageRangeResult{}, nil // empty storage
}
id := trie.StorageTrieID(root, crypto.Keccak256Hash(address.Bytes()), storageRoot)

View file

@ -236,7 +236,7 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
defer api.forkchoiceLock.Unlock()
log.Trace("Engine API request received", "method", "ForkchoiceUpdated", "head", update.HeadBlockHash, "finalized", update.FinalizedBlockHash, "safe", update.SafeBlockHash)
if update.HeadBlockHash == (common.Hash{}) {
if update.HeadBlockHash.IsZero() {
log.Warn("Forkchoice requested update to zero hash")
return engine.STATUS_INVALID, nil // TODO(karalabe): Why does someone send us this?
}
@ -269,7 +269,7 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
// Header advertised via a past newPayload request. Start syncing to it.
context := []interface{}{"number", header.Number, "hash", header.Hash()}
if update.FinalizedBlockHash != (common.Hash{}) {
if !update.FinalizedBlockHash.IsZero() {
if finalized == nil {
context = append(context, []interface{}{"finalized", "unknown"}...)
} else {
@ -328,7 +328,7 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
// If the beacon client also advertised a finalized block, mark the local
// chain final and completely in PoS mode.
if update.FinalizedBlockHash != (common.Hash{}) {
if !update.FinalizedBlockHash.IsZero() {
// If the finalized block is not in our canonical tree, something is wrong
finalBlock := api.eth.BlockChain().GetBlockByHash(update.FinalizedBlockHash)
if finalBlock == nil {
@ -342,7 +342,7 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
api.eth.BlockChain().SetFinalized(finalBlock.Header())
}
// Check if the safe block hash is in our canonical tree, if not something is wrong
if update.SafeBlockHash != (common.Hash{}) {
if !update.SafeBlockHash.IsZero() {
safeBlock := api.eth.BlockChain().GetBlockByHash(update.SafeBlockHash)
if safeBlock == nil {
log.Warn("Safe block not available in database")
@ -415,7 +415,7 @@ func (api *ConsensusAPI) ExchangeTransitionConfigurationV1(config engine.Transit
log.Warn("Invalid TTD configured", "geth", ttd, "beacon", config.TerminalTotalDifficulty)
return nil, fmt.Errorf("invalid ttd: execution %v consensus %v", ttd, config.TerminalTotalDifficulty)
}
if config.TerminalBlockHash != (common.Hash{}) {
if !config.TerminalBlockHash.IsZero() {
if hash := api.eth.BlockChain().GetCanonicalHash(uint64(config.TerminalBlockNumber)); hash == config.TerminalBlockHash {
return &engine.TransitionConfigurationV1{
TerminalTotalDifficulty: (*hexutil.Big)(ttd),

View file

@ -933,7 +933,7 @@ func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, re
}
}
// If the head fetch already found an ancestor, return
if hash != (common.Hash{}) {
if !hash.IsZero() {
if int64(number) <= floor {
p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
return 0, errInvalidAncestor

View file

@ -305,7 +305,7 @@ func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uin
log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
break
}
if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
if !q.headerHead.IsZero() && q.headerHead != header.ParentHash {
log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
break
}

View file

@ -71,7 +71,7 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64) {
b.Fatalf("error opening database at %v: %v", benchDataDir, err)
}
head := rawdb.ReadHeadBlockHash(db)
if head == (common.Hash{}) {
if head.IsZero() {
b.Fatalf("chain data not found at %v", benchDataDir)
}
@ -169,7 +169,7 @@ func BenchmarkNoBloomBits(b *testing.B) {
b.Fatalf("error opening database at %v: %v", benchDataDir, err)
}
head := rawdb.ReadHeadBlockHash(db)
if head == (common.Hash{}) {
if head.IsZero() {
b.Fatalf("chain data not found at %v", benchDataDir)
}
headNum := rawdb.ReadHeaderNumber(db, head)

View file

@ -296,7 +296,7 @@ func (f *Filter) checkMatches(ctx context.Context, header *types.Header) ([]*typ
return nil, nil
}
// Most backends will deliver un-derived logs, but check nevertheless.
if len(logs) > 0 && logs[0].TxHash != (common.Hash{}) {
if len(logs) > 0 && !logs[0].TxHash.IsZero() {
return logs, nil
}

View file

@ -317,7 +317,7 @@ func testGetBlockHeaders(t *testing.T, protocol uint) {
t.Errorf("test %d: headers mismatch: %v", i, err)
}
// If the test used number origins, repeat with hashes as the too
if tt.query.Origin.Hash == (common.Hash{}) {
if tt.query.Origin.Hash.IsZero() {
if origin := backend.chain.GetBlockByNumber(tt.query.Origin.Number); origin != nil {
tt.query.Origin.Hash, tt.query.Origin.Number = origin.Hash(), 0

View file

@ -51,7 +51,7 @@ func ServiceGetBlockHeadersQuery(chain *core.BlockChain, query *GetBlockHeadersR
}
func serviceNonContiguousBlockHeaderQuery(chain *core.BlockChain, query *GetBlockHeadersRequest, peer *Peer) []rlp.RawValue {
hashMode := query.Origin.Hash != (common.Hash{})
hashMode := !query.Origin.Hash.IsZero()
first := true
maxNonCanonical := uint64(100)
@ -98,7 +98,7 @@ func serviceNonContiguousBlockHeaderQuery(chain *core.BlockChain, query *GetBloc
unknown = true
} else {
query.Origin.Hash, query.Origin.Number = chain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
unknown = (query.Origin.Hash == common.Hash{})
unknown = query.Origin.Hash.IsZero()
}
case hashMode && !query.Reverse:
// Hash based traversal towards the leaf block
@ -144,7 +144,7 @@ func serviceContiguousBlockHeaderQuery(chain *core.BlockChain, query *GetBlockHe
if count > maxHeadersServe {
count = maxHeadersServe
}
if query.Origin.Hash == (common.Hash{}) {
if query.Origin.Hash.IsZero() {
// Number mode, just return the canon chain segment. The backend
// delivers in [N, N-1, N-2..] descending order, so we need to
// accommodate for that.

View file

@ -137,7 +137,7 @@ type HashOrNumber struct {
// EncodeRLP is a specialized encoder for HashOrNumber to encode only one of the
// two contained union fields.
func (hn *HashOrNumber) EncodeRLP(w io.Writer) error {
if hn.Hash == (common.Hash{}) {
if hn.Hash.IsZero() {
return rlp.Encode(w, hn.Number)
}
if hn.Number != 0 {

View file

@ -151,7 +151,7 @@ func (t *pathTrie) onTrieNode(path []byte, hash common.Hash, blob []byte) {
// write commits the node write to provided database batch in path mode.
func (t *pathTrie) write(path []byte, blob []byte) {
if t.owner == (common.Hash{}) {
if t.owner.IsZero() {
rawdb.WriteAccountTrieNode(t.batch, path, blob)
} else {
rawdb.WriteStorageTrieNode(t.batch, t.owner, path, blob)
@ -194,7 +194,7 @@ func (t *pathTrie) deleteStorageNode(path []byte, inner bool) {
// delete commits the node deletion to provided database batch in path mode.
func (t *pathTrie) delete(path []byte, inner bool) {
if t.owner == (common.Hash{}) {
if t.owner.IsZero() {
t.deleteAccountNode(path, inner)
} else {
t.deleteStorageNode(path, inner)

View file

@ -77,7 +77,7 @@ func (r *replayer) modifies() map[string]common.Hash {
func (r *replayer) updates() int {
var count int
for _, hash := range r.modifies() {
if hash == (common.Hash{}) {
if hash.IsZero() {
continue
}
count++
@ -118,7 +118,7 @@ func innerNodes(first, last []byte, includeLeft, includeRight bool, nodes map[st
inner = make(map[string]common.Hash)
)
for path, hash := range nodes {
if hash == (common.Hash{}) {
if hash.IsZero() {
t.Fatalf("Unexpected deletion, %v", []byte(path))
}
// Filter out the siblings on the left side or the left boundary nodes.
@ -490,7 +490,7 @@ func TestBoundSplit(t *testing.T) {
// Derive the path of left-most node in this chunk
var leftRoot []byte
for path, hash := range r.modifies() {
if hash == (common.Hash{}) {
if hash.IsZero() {
t.Fatalf("Unexpected deletion %v", []byte(path))
}
if leftRoot == nil || bytes.Compare(leftRoot, []byte(path)) > 0 {

View file

@ -326,7 +326,7 @@ func ServiceGetAccountRangeQuery(chain *core.BlockChain, req *GetAccountRangePac
log.Warn("Failed to prove account range", "origin", req.Origin, "err", err)
return nil, nil
}
if last != (common.Hash{}) {
if !last.IsZero() {
if err := tr.Prove(last[:], proof); err != nil {
log.Warn("Failed to prove account range", "last", last, "err", err)
return nil, nil
@ -411,7 +411,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP
// Generate the Merkle proofs for the first and last storage slot, but
// only if the response was capped. If the entire storage trie included
// in the response, no need for any proofs.
if origin != (common.Hash{}) || (abort && len(storage) > 0) {
if !origin.IsZero() || (abort && len(storage) > 0) {
// Request started at a non-zero hash or was capped prematurely, add
// the endpoint Merkle proofs
accTrie, err := trie.NewStateTrie(trie.StateTrieID(req.Root), chain.TrieDB())
@ -432,7 +432,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP
log.Warn("Failed to prove storage range", "origin", req.Origin, "err", err)
return nil, nil
}
if last != (common.Hash{}) {
if !last.IsZero() {
if err := stTrie.Prove(last[:], proof); err != nil {
log.Warn("Failed to prove storage range", "last", last, "err", err)
return nil, nil

View file

@ -786,7 +786,7 @@ func (s *Syncer) loadSyncStatus() {
task.genTrie = newHashTrie(task.genBatch)
}
if s.scheme == rawdb.PathScheme {
task.genTrie = newPathTrie(common.Hash{}, task.Next != common.Hash{}, s.db, task.genBatch)
task.genTrie = newPathTrie(common.Hash{}, !task.Next.IsZero(), s.db, task.genBatch)
}
// Restore leftover storage tasks
for accountHash, subtasks := range task.SubTasks {
@ -803,7 +803,7 @@ func (s *Syncer) loadSyncStatus() {
subtask.genTrie = newHashTrie(subtask.genBatch)
}
if s.scheme == rawdb.PathScheme {
subtask.genTrie = newPathTrie(accountHash, subtask.Next != common.Hash{}, s.db, subtask.genBatch)
subtask.genTrie = newPathTrie(accountHash, !subtask.Next.IsZero(), s.db, subtask.genBatch)
}
}
}
@ -861,7 +861,7 @@ func (s *Syncer) loadSyncStatus() {
tr = newHashTrie(batch)
}
if s.scheme == rawdb.PathScheme {
tr = newPathTrie(common.Hash{}, next != common.Hash{}, s.db, batch)
tr = newPathTrie(common.Hash{}, !next.IsZero(), s.db, batch)
}
s.tasks = append(s.tasks, &accountTask{
Next: next,
@ -3149,7 +3149,7 @@ func (s *Syncer) reportHealProgress(force bool) {
// a contract storage, based on the number of keys and the last hash. This method
// assumes that the hashes are lexicographically ordered and evenly distributed.
func estimateRemainingSlots(hashes int, last common.Hash) (uint64, error) {
if last == (common.Hash{}) {
if last.IsZero() {
return 0, errors.New("last hash empty")
}
space := new(big.Int).Mul(math.MaxBig256, big.NewInt(int64(hashes)))

View file

@ -256,7 +256,7 @@ func defaultAccountRequestHandler(t *testPeer, id uint64, root common.Hash, orig
func createAccountRequestResponse(t *testPeer, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) (keys []common.Hash, vals [][]byte, proofs [][]byte) {
var size uint64
if limit == (common.Hash{}) {
if limit.IsZero() {
limit = common.MaxHash
}
for _, entry := range t.accountValues {

View file

@ -163,7 +163,7 @@ func (eth *Ethereum) hashState(ctx context.Context, block *types.Block, reexec u
// Hold the state reference and also drop the parent state
// to prevent accumulating too many nodes in memory.
tdb.Reference(root, common.Hash{})
if parent != (common.Hash{}) {
if !parent.IsZero() {
tdb.Dereference(parent)
}
parent = root

View file

@ -719,7 +719,7 @@ txloop:
// be one filename per transaction traced.
func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
// If we're tracing a single transaction, make sure it's present
if config != nil && config.TxHash != (common.Hash{}) {
if config != nil && !config.TxHash.IsZero() {
if !containsTx(block, config.TxHash) {
return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
}
@ -783,7 +783,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block
err error
)
// If the transaction needs tracing, swap out the configs
if tx.Hash() == txHash || txHash == (common.Hash{}) {
if tx.Hash() == txHash || txHash.IsZero() {
// Generate a unique temporary file to dump it into
prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
if !canon {

View file

@ -153,13 +153,13 @@ func newJsTracer(code string, ctx *tracers.Context, cfg json.RawMessage) (*trace
if ctx == nil {
ctx = new(tracers.Context)
}
if ctx.BlockHash != (common.Hash{}) {
if !ctx.BlockHash.IsZero() {
blockHash, err := t.toBuf(vm, ctx.BlockHash.Bytes())
if err != nil {
return nil, err
}
t.ctx["blockHash"] = blockHash
if ctx.TxHash != (common.Hash{}) {
if !ctx.TxHash.IsZero() {
t.ctx["txIndex"] = vm.ToValue(ctx.TxIndex)
txHash, err := t.toBuf(vm, ctx.TxHash.Bytes())
if err != nil {

View file

@ -335,13 +335,13 @@ func fillCallFrameFromContext(callFrame *flatCallFrame, ctx *tracers.Context) {
if ctx == nil {
return
}
if ctx.BlockHash != (common.Hash{}) {
if !ctx.BlockHash.IsZero() {
callFrame.BlockHash = &ctx.BlockHash
}
if ctx.BlockNumber != nil {
callFrame.BlockNumber = ctx.BlockNumber.Uint64()
}
if ctx.TxHash != (common.Hash{}) {
if !ctx.TxHash.IsZero() {
callFrame.TransactionHash = &ctx.TxHash
}
callFrame.TransactionPosition = uint64(ctx.TxIndex)

View file

@ -228,7 +228,7 @@ func (t *prestateTracer) processDiffState() {
for key, val := range state.Storage {
// don't include the empty slot
if val == (common.Hash{}) {
if val.IsZero() {
delete(t.pre[addr].Storage, key)
}
@ -238,7 +238,7 @@ func (t *prestateTracer) processDiffState() {
delete(t.pre[addr].Storage, key)
} else {
modified = true
if newVal != (common.Hash{}) {
if !newVal.IsZero() {
postAccount.Storage[key] = newVal
}
}

View file

@ -271,7 +271,7 @@ func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction,
if err = ec.c.CallContext(ctx, &meta, "eth_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil {
return common.Address{}, err
}
if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() {
if meta.Hash.IsZero() || meta.Hash != tx.Hash() {
return common.Address{}, errors.New("wrong inclusion block/index")
}
return meta.From, nil

View file

@ -343,7 +343,7 @@ func (o BlockOverrides) MarshalJSON() ([]byte, error) {
if o.Coinbase != (common.Address{}) {
output.Coinbase = &o.Coinbase
}
if o.Random != (common.Hash{}) {
if !o.Random.IsZero() {
output.Random = &o.Random
}
return json.Marshal(output)

View file

@ -689,7 +689,7 @@ func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) {
if b.header != nil {
return b.header, nil
}
if b.numberOrHash == nil && b.hash == (common.Hash{}) {
if b.numberOrHash == nil && b.hash.IsZero() {
return nil, errBlockInvariant
}
var err error
@ -697,7 +697,7 @@ func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) {
if err != nil {
return nil, err
}
if b.hash == (common.Hash{}) {
if b.hash.IsZero() {
b.hash = b.header.Hash()
}
return b.header, nil

View file

@ -727,7 +727,7 @@ func (s *BlockChainAPI) GetProof(ctx context.Context, address common.Address, st
if len(keys) > 0 {
var storageTrie state.Trie
if storageRoot != types.EmptyRootHash && storageRoot != (common.Hash{}) {
if storageRoot != types.EmptyRootHash && !storageRoot.IsZero() {
id := trie.StorageTrieID(header.Root, crypto.Keccak256Hash(address.Bytes()), storageRoot)
st, err := trie.NewStateTrie(id, statedb.Database().TrieDB())
if err != nil {
@ -1365,7 +1365,7 @@ func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber
R: (*hexutil.Big)(r),
S: (*hexutil.Big)(s),
}
if blockHash != (common.Hash{}) {
if !blockHash.IsZero() {
result.BlockHash = &blockHash
result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
result.TransactionIndex = (*hexutil.Uint64)(&index)
@ -1394,7 +1394,7 @@ func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber
result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
// if the transaction has been mined, compute the effective gas price
if baseFee != nil && blockHash != (common.Hash{}) {
if baseFee != nil && !blockHash.IsZero() {
// price = min(gasTipCap + baseFee, gasFeeCap)
result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee))
} else {
@ -1410,7 +1410,7 @@ func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber
result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
// if the transaction has been mined, compute the effective gas price
if baseFee != nil && blockHash != (common.Hash{}) {
if baseFee != nil && !blockHash.IsZero() {
result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee))
} else {
result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())

View file

@ -128,7 +128,7 @@ func (miner *Miner) prepareWork(genParams *generateParams) (*environment, error)
// Find the parent block for sealing task
parent := miner.chain.CurrentBlock()
if genParams.parentHash != (common.Hash{}) {
if !genParams.parentHash.IsZero() {
block := miner.chain.GetBlockByHash(genParams.parentHash)
if block == nil {
return nil, errors.New("missing parent")
@ -157,7 +157,7 @@ func (miner *Miner) prepareWork(genParams *generateParams) (*environment, error)
header.Extra = miner.config.ExtraData
}
// Set the randomness field from the beacon chain if it's available.
if genParams.random != (common.Hash{}) {
if !genParams.random.IsZero() {
header.MixDigest = genParams.random
}
// Set baseFee and GasLimit if we are on an EIP-1559 chain

View file

@ -132,7 +132,7 @@ func (db *testDb) Commit(root common.Hash) error {
pending, roots := db.dirties(root, false)
for i, nodes := range pending {
for owner, set := range nodes.Sets {
if owner == (common.Hash{}) {
if owner.IsZero() {
continue
}
set.ForEachWithOrder(func(path string, n *trienode.Node) {

View file

@ -45,7 +45,7 @@ func (err *MissingNodeError) Unwrap() error {
}
func (err *MissingNodeError) Error() string {
if err.Owner == (common.Hash{}) {
if err.Owner.IsZero() {
return fmt.Sprintf("missing trie node %x (path %x) %v", err.NodeHash, err.Path, err.err)
}
return fmt.Sprintf("missing trie node %x (owner %x) (path %x) %v", err.NodeHash, err.Owner, err.Path, err.err)

View file

@ -256,7 +256,7 @@ func (it *nodeIterator) Path() []byte {
}
func (it *nodeIterator) NodeBlob() []byte {
if it.Hash() == (common.Hash{}) {
if it.Hash().IsZero() {
return nil // skip the non-standalone node
}
blob, err := it.resolveBlob(it.Hash().Bytes(), it.Path())
@ -344,7 +344,7 @@ func (it *nodeIterator) peek(descend bool) (*nodeIteratorState, *int, []byte, er
for len(it.stack) > 0 {
parent := it.stack[len(it.stack)-1]
ancestor := parent.hash
if (ancestor == common.Hash{}) {
if ancestor.IsZero() {
ancestor = parent.parent
}
state, path, ok := it.nextChild(parent, ancestor)
@ -377,7 +377,7 @@ func (it *nodeIterator) peekSeek(seekKey []byte) (*nodeIteratorState, *int, []by
for len(it.stack) > 0 {
parent := it.stack[len(it.stack)-1]
ancestor := parent.hash
if (ancestor == common.Hash{}) {
if ancestor.IsZero() {
ancestor = parent.parent
}
state, path, ok := it.nextChildAt(parent, ancestor, seekKey)
@ -654,7 +654,7 @@ func (it *differenceIterator) Next(bool) bool {
return true
case 0:
// a and b are identical; skip this whole subtree if the nodes have hashes
hasHash := it.a.Hash() == common.Hash{}
hasHash := it.a.Hash().IsZero()
if !it.b.Next(hasHash) {
return false
}
@ -768,7 +768,7 @@ func (it *unionIterator) Next(descend bool) bool {
for len(*it.items) > 0 && ((!descend && bytes.HasPrefix((*it.items)[0].Path(), least.Path())) || compareNodes(least, (*it.items)[0]) == 0) {
skipped := heap.Pop(it.items).(NodeIterator)
// Skip the whole subtree if the nodes have hashes; otherwise just skip this node
if skipped.Next(skipped.Hash() == common.Hash{}) {
if skipped.Next(skipped.Hash().IsZero()) {
it.count++
// If there are more elements, push the iterator back on the heap
heap.Push(it.items, skipped)

View file

@ -563,7 +563,7 @@ func testIteratorNodeBlob(t *testing.T, scheme string) {
trie, _ = New(TrieID(root), triedb)
it := trie.MustNodeIterator(nil)
for it.Next(true) {
if it.Hash() == (common.Hash{}) {
if it.Hash().IsZero() {
continue
}
found[it.Hash()] = it.NodeBlob()

View file

@ -130,7 +130,7 @@ func fuzz(data []byte, debugging bool) {
trieA, _ = New(TrieID(rootA), dbA)
iterA := trieA.MustNodeIterator(nil)
for iterA.Next(true) {
if iterA.Hash() == (common.Hash{}) {
if iterA.Hash().IsZero() {
if _, present := nodeset[string(iterA.Path())]; present {
panic("unexpected tiny node")
}

View file

@ -191,7 +191,7 @@ func (batch *syncMemBatch) addCode(hash common.Hash, code []byte) {
// addNode caches a node database write operation.
func (batch *syncMemBatch) addNode(owner common.Hash, path []byte, blob []byte, hash common.Hash) {
if batch.scheme == rawdb.PathScheme {
if owner == (common.Hash{}) {
if owner.IsZero() {
batch.size += uint64(len(path) + len(blob))
} else {
batch.size += common.HashLength + uint64(len(path)+len(blob))
@ -213,7 +213,7 @@ func (batch *syncMemBatch) delNode(owner common.Hash, path []byte) {
log.Error("Unexpected node deletion", "owner", owner, "path", path, "scheme", batch.scheme)
return // deletion is not supported in hash mode.
}
if owner == (common.Hash{}) {
if owner.IsZero() {
batch.size += uint64(len(path))
} else {
batch.size += common.HashLength + uint64(len(path))
@ -275,7 +275,7 @@ func (s *Sync) AddSubTrie(root common.Hash, path []byte, parent common.Hash, par
callback: callback,
}
// If this sub-trie has a designated parent, link them together
if parent != (common.Hash{}) {
if !parent.IsZero() {
ancestor := s.nodeReqs[string(parentPath)]
if ancestor == nil {
panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
@ -311,7 +311,7 @@ func (s *Sync) AddCodeEntry(hash common.Hash, path []byte, parent common.Hash, p
hash: hash,
}
// If this sub-trie has a designated parent, link them together
if parent != (common.Hash{}) {
if !parent.IsZero() {
ancestor := s.nodeReqs[string(parentPath)] // the parent of codereq can ONLY be nodereq
if ancestor == nil {
panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
@ -429,14 +429,14 @@ func (s *Sync) Commit(dbw ethdb.Batch) error {
for _, op := range s.membatch.nodes {
if op.isDelete() {
// node deletion is only supported in path mode.
if op.owner == (common.Hash{}) {
if op.owner.IsZero() {
rawdb.DeleteAccountTrieNode(dbw, op.path)
} else {
rawdb.DeleteStorageTrieNode(dbw, op.owner, op.path)
}
deletionGauge.Inc(1)
} else {
if op.owner == (common.Hash{}) {
if op.owner.IsZero() {
account += 1
} else {
storage += 1
@ -545,7 +545,7 @@ func (s *Sync) children(req *nodeRequest, object node) ([]*nodeRequest, error) {
// without a bloom filter, the relatively low frequency of lookups makes
// the performance impact negligible.
var exists bool
if owner == (common.Hash{}) {
if owner.IsZero() {
exists = rawdb.ExistsAccountTrieNode(s.database, append(inner, key[:i]...))
} else {
exists = rawdb.ExistsStorageTrieNode(s.database, owner, append(inner, key[:i]...))
@ -692,7 +692,7 @@ func (s *Sync) hasNode(owner common.Hash, path []byte, hash common.Hash) (exists
// If node is running with path scheme, check the presence with node path.
var blob []byte
var dbHash common.Hash
if owner == (common.Hash{}) {
if owner.IsZero() {
blob, dbHash = rawdb.ReadAccountTrieNode(s.database, path)
} else {
blob, dbHash = rawdb.ReadStorageTrieNode(s.database, owner, path)

View file

@ -324,7 +324,7 @@ func forHashedNodes(tr *Trie) map[string][]byte {
nodes = make(map[string][]byte)
)
for it.Next(true) {
if it.Hash() == (common.Hash{}) {
if it.Hash().IsZero() {
continue
}
nodes[string(it.Path())] = common.CopyBytes(it.NodeBlob())

View file

@ -90,7 +90,7 @@ func New(id *ID, db database.Database) (*Trie, error) {
reader: reader,
tracer: newTracer(),
}
if id.Root != (common.Hash{}) && id.Root != types.EmptyRootHash {
if !id.Root.IsZero() && id.Root != types.EmptyRootHash {
rootnode, err := trie.resolveAndTrack(id.Root[:], nil)
if err != nil {
return nil, err

View file

@ -34,8 +34,8 @@ type trieReader struct {
// newTrieReader initializes the trie reader with the given node reader.
func newTrieReader(stateRoot, owner common.Hash, db database.Database) (*trieReader, error) {
if stateRoot == (common.Hash{}) || stateRoot == types.EmptyRootHash {
if stateRoot == (common.Hash{}) {
if stateRoot.IsZero() || stateRoot == types.EmptyRootHash {
if stateRoot.IsZero() {
log.Error("Zero state root hash!")
}
return &trieReader{owner: owner}, nil

View file

@ -170,7 +170,7 @@ func (db *Database) insert(hash common.Hash, node []byte) {
db.dirties[hash] = entry
// Update the flush-list endpoints
if db.oldest == (common.Hash{}) {
if db.oldest.IsZero() {
db.oldest, db.newest = hash, hash
} else {
db.dirties[db.newest].flushNext, db.newest = hash, hash
@ -182,7 +182,7 @@ func (db *Database) insert(hash common.Hash, node []byte) {
// cached, the method queries the persistent database for the content.
func (db *Database) node(hash common.Hash) ([]byte, error) {
// It doesn't make sense to retrieve the metaroot
if hash == (common.Hash{}) {
if hash.IsZero() {
return nil, errors.New("not found")
}
// Retrieve the node from the clean cache if available
@ -240,7 +240,7 @@ func (db *Database) reference(child common.Hash, parent common.Hash) {
return
}
// The reference is for state root, increase the reference counter.
if parent == (common.Hash{}) {
if parent.IsZero() {
node.parents += 1
return
}
@ -260,7 +260,7 @@ func (db *Database) reference(child common.Hash, parent common.Hash) {
// Dereference removes an existing reference from a root node.
func (db *Database) Dereference(root common.Hash) {
// Sanity check to ensure that the meta-root is not removed
if root == (common.Hash{}) {
if root.IsZero() {
log.Error("Attempted to dereference the trie cache meta root")
return
}
@ -302,12 +302,12 @@ func (db *Database) dereference(hash common.Hash) {
switch hash {
case db.oldest:
db.oldest = node.flushNext
if node.flushNext != (common.Hash{}) {
if !node.flushNext.IsZero() {
db.dirties[node.flushNext].flushPrev = common.Hash{}
}
case db.newest:
db.newest = node.flushPrev
if node.flushPrev != (common.Hash{}) {
if !node.flushPrev.IsZero() {
db.dirties[node.flushPrev].flushNext = common.Hash{}
}
default:
@ -347,7 +347,7 @@ func (db *Database) Cap(limit common.StorageSize) error {
// Keep committing nodes from the flush-list until we're below allowance
oldest := db.oldest
for size > limit && oldest != (common.Hash{}) {
for size > limit && !oldest.IsZero() {
// Fetch the oldest referenced node and push into the batch
node := db.dirties[oldest]
rawdb.WriteLegacyTrieNode(batch, oldest, node.node)
@ -385,7 +385,7 @@ func (db *Database) Cap(limit common.StorageSize) error {
db.childrenSize -= common.StorageSize(len(node.external) * common.HashLength)
}
}
if db.oldest != (common.Hash{}) {
if !db.oldest.IsZero() {
db.dirties[db.oldest].flushPrev = common.Hash{}
}
db.flushnodes += uint64(nodes - len(db.dirties))
@ -510,12 +510,12 @@ func (c *cleaner) Put(key []byte, rlp []byte) error {
switch hash {
case c.db.oldest:
c.db.oldest = node.flushNext
if node.flushNext != (common.Hash{}) {
if !node.flushNext.IsZero() {
c.db.dirties[node.flushNext].flushPrev = common.Hash{}
}
case c.db.newest:
c.db.newest = node.flushPrev
if node.flushPrev != (common.Hash{}) {
if !node.flushPrev.IsZero() {
c.db.dirties[node.flushPrev].flushNext = common.Hash{}
}
default:
@ -566,7 +566,7 @@ func (db *Database) Update(root common.Hash, parent common.Hash, block uint64, n
// retain the invariant that children go into the dirty cache first.
var order []common.Hash
for owner := range nodes.Sets {
if owner == (common.Hash{}) {
if owner.IsZero() {
continue
}
order = append(order, owner)

View file

@ -134,7 +134,7 @@ func (dl *diskLayer) node(owner common.Hash, path []byte, depth int) ([]byte, co
nBlob []byte
nHash common.Hash
)
if owner == (common.Hash{}) {
if owner.IsZero() {
nBlob, nHash = rawdb.ReadAccountTrieNode(dl.db.diskdb, path)
} else {
nBlob, nHash = rawdb.ReadStorageTrieNode(dl.db.diskdb, owner, path)

View file

@ -149,7 +149,7 @@ func (b *nodebuffer) revert(db ethdb.KeyValueReader, nodes map[common.Hash]map[s
// In case of database rollback, don't panic if this "clean"
// node occurs which is not present in buffer.
var nhash common.Hash
if owner == (common.Hash{}) {
if owner.IsZero() {
_, nhash = rawdb.ReadAccountTrieNode(db, []byte(path))
} else {
_, nhash = rawdb.ReadStorageTrieNode(db, owner, []byte(path))
@ -203,7 +203,7 @@ func (b *nodebuffer) setSize(size int, db ethdb.KeyValueStore, clean *fastcache.
func (b *nodebuffer) allocBatch(db ethdb.KeyValueStore) ethdb.Batch {
var metasize int
for owner, nodes := range b.nodes {
if owner == (common.Hash{}) {
if owner.IsZero() {
metasize += len(nodes) * len(rawdb.TrieNodeAccountPrefix) // database key prefix
} else {
metasize += len(nodes) * (len(rawdb.TrieNodeStoragePrefix) + common.HashLength) // database key prefix + owner
@ -250,7 +250,7 @@ func writeNodes(batch ethdb.Batch, nodes map[common.Hash]map[string]*trienode.No
for owner, subset := range nodes {
for path, n := range subset {
if n.IsDeleted() {
if owner == (common.Hash{}) {
if owner.IsZero() {
rawdb.DeleteAccountTrieNode(batch, []byte(path))
} else {
rawdb.DeleteStorageTrieNode(batch, owner, []byte(path))
@ -259,7 +259,7 @@ func writeNodes(batch ethdb.Batch, nodes map[common.Hash]map[string]*trienode.No
clean.Del(cacheKey(owner, []byte(path)))
}
} else {
if owner == (common.Hash{}) {
if owner.IsZero() {
rawdb.WriteAccountTrieNode(batch, []byte(path), n.Blob)
} else {
rawdb.WriteStorageTrieNode(batch, owner, []byte(path), n.Blob)
@ -276,7 +276,7 @@ func writeNodes(batch ethdb.Batch, nodes map[common.Hash]map[string]*trienode.No
// cacheKey constructs the unique key of clean cache.
func cacheKey(owner common.Hash, path []byte) []byte {
if owner == (common.Hash{}) {
if owner.IsZero() {
return path
}
return append(owner.Bytes(), path...)