-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
100 lines (76 loc) · 1.69 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package itrie
import (
"fmt"
lru "github.com/hashicorp/golang-lru"
"github.com/0xDaoChain/dao-chain/state"
"github.com/0xDaoChain/dao-chain/types"
)
type State struct {
storage Storage
cache *lru.Cache
}
func NewState(storage Storage) *State {
cache, _ := lru.New(128)
s := &State{
storage: storage,
cache: cache,
}
return s
}
func (s *State) NewSnapshot() state.Snapshot {
return &Snapshot{state: s, trie: s.newTrie()}
}
func (s *State) NewSnapshotAt(root types.Hash) (state.Snapshot, error) {
t, err := s.newTrieAt(root)
if err != nil {
return nil, err
}
return &Snapshot{state: s, trie: t}, nil
}
func (s *State) newTrie() *Trie {
t := NewTrie()
t.state = s
t.storage = s.storage
return t
}
func (s *State) SetCode(hash types.Hash, code []byte) {
s.storage.SetCode(hash, code)
}
func (s *State) GetCode(hash types.Hash) ([]byte, bool) {
return s.storage.GetCode(hash)
}
func (s *State) newTrieAt(root types.Hash) (*Trie, error) {
if root == types.EmptyRootHash {
// empty state
return s.newTrie(), nil
}
tt, ok := s.cache.Get(root)
if ok {
t, ok := tt.(*Trie)
if !ok {
return nil, fmt.Errorf("invalid type assertion on root: %s", root)
}
t.state = s
trie, ok := tt.(*Trie)
if !ok {
return nil, fmt.Errorf("invalid type assertion on root: %s", root)
}
return trie, nil
}
n, ok, err := GetNode(root.Bytes(), s.storage)
if err != nil {
return nil, fmt.Errorf("failed to get storage root %s: %w", root, err)
}
if !ok {
return nil, fmt.Errorf("state not found at hash %s", root)
}
t := &Trie{
root: n,
state: s,
storage: s.storage,
}
return t, nil
}
func (s *State) AddState(root types.Hash, t *Trie) {
s.cache.Add(root, t)
}