github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/core/state/dump.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package state
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"time"
    23  
    24  	"github.com/tirogen/go-ethereum/common"
    25  	"github.com/tirogen/go-ethereum/common/hexutil"
    26  	"github.com/tirogen/go-ethereum/core/types"
    27  	"github.com/tirogen/go-ethereum/log"
    28  	"github.com/tirogen/go-ethereum/rlp"
    29  	"github.com/tirogen/go-ethereum/trie"
    30  )
    31  
    32  // DumpConfig is a set of options to control what portions of the state will be
    33  // iterated and collected.
    34  type DumpConfig struct {
    35  	SkipCode          bool
    36  	SkipStorage       bool
    37  	OnlyWithAddresses bool
    38  	Start             []byte
    39  	Max               uint64
    40  }
    41  
    42  // DumpCollector interface which the state trie calls during iteration
    43  type DumpCollector interface {
    44  	// OnRoot is called with the state root
    45  	OnRoot(common.Hash)
    46  	// OnAccount is called once for each account in the trie
    47  	OnAccount(common.Address, DumpAccount)
    48  }
    49  
    50  // DumpAccount represents an account in the state.
    51  type DumpAccount struct {
    52  	Balance   string                 `json:"balance"`
    53  	Nonce     uint64                 `json:"nonce"`
    54  	Root      hexutil.Bytes          `json:"root"`
    55  	CodeHash  hexutil.Bytes          `json:"codeHash"`
    56  	Code      hexutil.Bytes          `json:"code,omitempty"`
    57  	Storage   map[common.Hash]string `json:"storage,omitempty"`
    58  	Address   *common.Address        `json:"address,omitempty"` // Address only present in iterative (line-by-line) mode
    59  	SecureKey hexutil.Bytes          `json:"key,omitempty"`     // If we don't have address, we can output the key
    60  
    61  }
    62  
    63  // Dump represents the full dump in a collected format, as one large map.
    64  type Dump struct {
    65  	Root     string                         `json:"root"`
    66  	Accounts map[common.Address]DumpAccount `json:"accounts"`
    67  }
    68  
    69  // OnRoot implements DumpCollector interface
    70  func (d *Dump) OnRoot(root common.Hash) {
    71  	d.Root = fmt.Sprintf("%x", root)
    72  }
    73  
    74  // OnAccount implements DumpCollector interface
    75  func (d *Dump) OnAccount(addr common.Address, account DumpAccount) {
    76  	d.Accounts[addr] = account
    77  }
    78  
    79  // IteratorDump is an implementation for iterating over data.
    80  type IteratorDump struct {
    81  	Root     string                         `json:"root"`
    82  	Accounts map[common.Address]DumpAccount `json:"accounts"`
    83  	Next     []byte                         `json:"next,omitempty"` // nil if no more accounts
    84  }
    85  
    86  // OnRoot implements DumpCollector interface
    87  func (d *IteratorDump) OnRoot(root common.Hash) {
    88  	d.Root = fmt.Sprintf("%x", root)
    89  }
    90  
    91  // OnAccount implements DumpCollector interface
    92  func (d *IteratorDump) OnAccount(addr common.Address, account DumpAccount) {
    93  	d.Accounts[addr] = account
    94  }
    95  
    96  // iterativeDump is a DumpCollector-implementation which dumps output line-by-line iteratively.
    97  type iterativeDump struct {
    98  	*json.Encoder
    99  }
   100  
   101  // OnAccount implements DumpCollector interface
   102  func (d iterativeDump) OnAccount(addr common.Address, account DumpAccount) {
   103  	dumpAccount := &DumpAccount{
   104  		Balance:   account.Balance,
   105  		Nonce:     account.Nonce,
   106  		Root:      account.Root,
   107  		CodeHash:  account.CodeHash,
   108  		Code:      account.Code,
   109  		Storage:   account.Storage,
   110  		SecureKey: account.SecureKey,
   111  		Address:   nil,
   112  	}
   113  	if addr != (common.Address{}) {
   114  		dumpAccount.Address = &addr
   115  	}
   116  	d.Encode(dumpAccount)
   117  }
   118  
   119  // OnRoot implements DumpCollector interface
   120  func (d iterativeDump) OnRoot(root common.Hash) {
   121  	d.Encode(struct {
   122  		Root common.Hash `json:"root"`
   123  	}{root})
   124  }
   125  
   126  // DumpToCollector iterates the state according to the given options and inserts
   127  // the items into a collector for aggregation or serialization.
   128  func (s *StateDB) DumpToCollector(c DumpCollector, conf *DumpConfig) (nextKey []byte) {
   129  	// Sanitize the input to allow nil configs
   130  	if conf == nil {
   131  		conf = new(DumpConfig)
   132  	}
   133  	var (
   134  		missingPreimages int
   135  		accounts         uint64
   136  		start            = time.Now()
   137  		logged           = time.Now()
   138  	)
   139  	log.Info("Trie dumping started", "root", s.trie.Hash())
   140  	c.OnRoot(s.trie.Hash())
   141  
   142  	it := trie.NewIterator(s.trie.NodeIterator(conf.Start))
   143  	for it.Next() {
   144  		var data types.StateAccount
   145  		if err := rlp.DecodeBytes(it.Value, &data); err != nil {
   146  			panic(err)
   147  		}
   148  		account := DumpAccount{
   149  			Balance:   data.Balance.String(),
   150  			Nonce:     data.Nonce,
   151  			Root:      data.Root[:],
   152  			CodeHash:  data.CodeHash,
   153  			SecureKey: it.Key,
   154  		}
   155  		addrBytes := s.trie.GetKey(it.Key)
   156  		if addrBytes == nil {
   157  			// Preimage missing
   158  			missingPreimages++
   159  			if conf.OnlyWithAddresses {
   160  				continue
   161  			}
   162  			account.SecureKey = it.Key
   163  		}
   164  		addr := common.BytesToAddress(addrBytes)
   165  		obj := newObject(s, addr, data)
   166  		if !conf.SkipCode {
   167  			account.Code = obj.Code(s.db)
   168  		}
   169  		if !conf.SkipStorage {
   170  			account.Storage = make(map[common.Hash]string)
   171  			tr, err := obj.getTrie(s.db)
   172  			if err != nil {
   173  				log.Error("Failed to load storage trie", "err", err)
   174  				continue
   175  			}
   176  			storageIt := trie.NewIterator(tr.NodeIterator(nil))
   177  			for storageIt.Next() {
   178  				_, content, _, err := rlp.Split(storageIt.Value)
   179  				if err != nil {
   180  					log.Error("Failed to decode the value returned by iterator", "error", err)
   181  					continue
   182  				}
   183  				account.Storage[common.BytesToHash(s.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(content)
   184  			}
   185  		}
   186  		c.OnAccount(addr, account)
   187  		accounts++
   188  		if time.Since(logged) > 8*time.Second {
   189  			log.Info("Trie dumping in progress", "at", it.Key, "accounts", accounts,
   190  				"elapsed", common.PrettyDuration(time.Since(start)))
   191  			logged = time.Now()
   192  		}
   193  		if conf.Max > 0 && accounts >= conf.Max {
   194  			if it.Next() {
   195  				nextKey = it.Key
   196  			}
   197  			break
   198  		}
   199  	}
   200  	if missingPreimages > 0 {
   201  		log.Warn("Dump incomplete due to missing preimages", "missing", missingPreimages)
   202  	}
   203  	log.Info("Trie dumping complete", "accounts", accounts,
   204  		"elapsed", common.PrettyDuration(time.Since(start)))
   205  
   206  	return nextKey
   207  }
   208  
   209  // RawDump returns the entire state an a single large object
   210  func (s *StateDB) RawDump(opts *DumpConfig) Dump {
   211  	dump := &Dump{
   212  		Accounts: make(map[common.Address]DumpAccount),
   213  	}
   214  	s.DumpToCollector(dump, opts)
   215  	return *dump
   216  }
   217  
   218  // Dump returns a JSON string representing the entire state as a single json-object
   219  func (s *StateDB) Dump(opts *DumpConfig) []byte {
   220  	dump := s.RawDump(opts)
   221  	json, err := json.MarshalIndent(dump, "", "    ")
   222  	if err != nil {
   223  		fmt.Println("Dump err", err)
   224  	}
   225  	return json
   226  }
   227  
   228  // IterativeDump dumps out accounts as json-objects, delimited by linebreaks on stdout
   229  func (s *StateDB) IterativeDump(opts *DumpConfig, output *json.Encoder) {
   230  	s.DumpToCollector(iterativeDump{output}, opts)
   231  }
   232  
   233  // IteratorDump dumps out a batch of accounts starts with the given start key
   234  func (s *StateDB) IteratorDump(opts *DumpConfig) IteratorDump {
   235  	iterator := &IteratorDump{
   236  		Accounts: make(map[common.Address]DumpAccount),
   237  	}
   238  	iterator.Next = s.DumpToCollector(iterator, opts)
   239  	return *iterator
   240  }