@@ -166,13 +166,8 @@ type StateDB struct {
166166
167167// Create a new state from a given trie.
168168func New (root common.Hash , db Database ) (* StateDB , error ) {
169- tr , err := db .OpenTrie (root )
170- if err != nil {
171- return nil , err
172- }
173169 sdb := & StateDB {
174170 db : db ,
175- trie : tr ,
176171 originalRoot : root ,
177172 accounts : make (map [common.Hash ][]byte ),
178173 storages : make (map [common.Hash ]map [common.Hash ][]byte ),
@@ -671,6 +666,14 @@ func (s *StateDB) getStateObject(addr common.Address) *stateObject {
671666 // If snapshot unavailable or reading from it failed, load from the database
672667 if data == nil {
673668 start := time .Now ()
669+ if s .trie == nil {
670+ tr , err := s .db .OpenTrie (s .originalRoot )
671+ if err != nil {
672+ return nil
673+ }
674+ s .trie = tr
675+
676+ }
674677 enc , err := s .trie .TryGet (addr .Bytes ())
675678 s .AccountReads += time .Since (start )
676679 if err != nil {
@@ -782,8 +785,7 @@ func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common
782785func (s * StateDB ) Copy () * StateDB {
783786 // Copy all the basic fields, initialize the memory ones
784787 state := & StateDB {
785- db : s .db ,
786- trie : s .db .CopyTrie (s .trie ),
788+ db : s .db ,
787789 //hasher: crypto.NewKeccakState(),
788790 originalRoot : s .originalRoot ,
789791 accounts : copySet (s .accounts ),
@@ -808,6 +810,9 @@ func (s *StateDB) Copy() *StateDB {
808810 // miner to operate trie-backed only.
809811 snap : s .snap ,
810812 }
813+ if s .trie != nil {
814+ state .trie = mustCopyTrie (s .trie )
815+ }
811816 // Deep copy cached state objects.
812817 for addr , obj := range s .stateObjects {
813818 state .stateObjects [addr ] = obj .deepCopy (state )
@@ -913,6 +918,20 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) {
913918func (s * StateDB ) IntermediateRoot (deleteEmptyObjects bool ) common.Hash {
914919 // Finalise all the dirty storage states and write them into the tries
915920 s .Finalise (deleteEmptyObjects )
921+ // Initialize the trie if it's not constructed yet. If the prefetch
922+ // is enabled, the trie constructed below will be replaced by the
923+ // prefetched one.
924+ //
925+ // This operation must be done before state object storage hashing,
926+ // as it assumes the main trie is already loaded.
927+ if s .trie == nil {
928+ tr , err := s .db .OpenTrie (s .originalRoot )
929+ if err != nil {
930+ s .setError (err )
931+ return common.Hash {}
932+ }
933+ s .trie = tr
934+ }
916935
917936 // If there was a trie prefetcher operating, terminate it async so that the
918937 // individual storage tries can be updated as soon as the disk load finishes.
0 commit comments