dump.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. package state
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/rlp"
  22. "github.com/ethereum/go-ethereum/trie"
  23. )
  24. type DumpAccount struct {
  25. Balance string `json:"balance"`
  26. Nonce uint64 `json:"nonce"`
  27. Root string `json:"root"`
  28. CodeHash string `json:"codeHash"`
  29. Code string `json:"code"`
  30. Storage map[string]string `json:"storage"`
  31. }
  32. type Dump struct {
  33. Root string `json:"root"`
  34. Accounts map[string]DumpAccount `json:"accounts"`
  35. }
  36. func (self *StateDB) RawDump() Dump {
  37. dump := Dump{
  38. Root: fmt.Sprintf("%x", self.trie.Hash()),
  39. Accounts: make(map[string]DumpAccount),
  40. }
  41. it := trie.NewIterator(self.trie.NodeIterator(nil))
  42. for it.Next() {
  43. addr := self.trie.GetKey(it.Key)
  44. var data Account
  45. if err := rlp.DecodeBytes(it.Value, &data); err != nil {
  46. panic(err)
  47. }
  48. obj := newObject(nil, common.BytesToAddress(addr), data, nil)
  49. account := DumpAccount{
  50. Balance: data.Balance.String(),
  51. Nonce: data.Nonce,
  52. Root: common.Bytes2Hex(data.Root[:]),
  53. CodeHash: common.Bytes2Hex(data.CodeHash),
  54. Code: common.Bytes2Hex(obj.Code(self.db)),
  55. Storage: make(map[string]string),
  56. }
  57. storageIt := trie.NewIterator(obj.getTrie(self.db).NodeIterator(nil))
  58. for storageIt.Next() {
  59. account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value)
  60. }
  61. dump.Accounts[common.Bytes2Hex(addr)] = account
  62. }
  63. return dump
  64. }
  65. func (self *StateDB) Dump() []byte {
  66. json, err := json.MarshalIndent(self.RawDump(), "", " ")
  67. if err != nil {
  68. fmt.Println("dump err", err)
  69. }
  70. return json
  71. }