/
iavl_tree.go
320 lines (293 loc) · 7.4 KB
/
iavl_tree.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package merkle
import (
"bytes"
"container/list"
"sync"
. "github.com/nio-net/common"
dbm "github.com/nio-net/database"
wire "github.com/nio-net/wire"
)
/*
Immutable AVL Tree (wraps the Node root)
This tree is not goroutine safe.
*/
type IAVLTree struct {
root *IAVLNode
ndb *nodeDB
}
func NewIAVLTree(cacheSize int, db dbm.DB) *IAVLTree {
if db == nil {
// In-memory IAVLTree
return &IAVLTree{}
} else {
// Persistent IAVLTree
ndb := newNodeDB(cacheSize, db)
return &IAVLTree{
ndb: ndb,
}
}
}
// The returned tree and the original tree are goroutine independent.
// That is, they can each run in their own goroutine.
// However, upon Save(), any other trees that share a db will become
// outdated, as some nodes will become orphaned.
// Note that Save() clears leftNode and rightNode. Otherwise,
// two copies would not be goroutine independent.
func (t *IAVLTree) Copy() Tree {
if t.root == nil {
return &IAVLTree{
root: nil,
ndb: t.ndb,
}
}
if t.ndb != nil && !t.root.persisted {
// Saving a tree finalizes all the nodes.
// It sets all the hashes recursively,
// clears all the leftNode/rightNode values recursively,
// and all the .persisted flags get set.
PanicSanity("It is unsafe to Copy() an unpersisted tree.")
} else if t.ndb == nil && t.root.hash == nil {
// An in-memory IAVLTree is finalized when the hashes are
// calculated.
t.root.hashWithCount(t)
}
return &IAVLTree{
root: t.root,
ndb: t.ndb,
}
}
func (t *IAVLTree) Size() int {
if t.root == nil {
return 0
}
return t.root.size
}
func (t *IAVLTree) Height() int8 {
if t.root == nil {
return 0
}
return t.root.height
}
func (t *IAVLTree) Has(key []byte) bool {
if t.root == nil {
return false
}
return t.root.has(t, key)
}
func (t *IAVLTree) Proof(key []byte) (value []byte, proofBytes []byte, exists bool) {
value, proof := t.ConstructProof(key)
if proof == nil {
return nil, nil, false
}
proofBytes = wire.BinaryBytes(proof)
return value, proofBytes, true
}
func (t *IAVLTree) Set(key []byte, value []byte) (updated bool) {
if t.root == nil {
t.root = NewIAVLNode(key, value)
return false
}
t.root, updated = t.root.set(t, key, value)
return updated
}
func (t *IAVLTree) Hash() []byte {
if t.root == nil {
return nil
}
hash, _ := t.root.hashWithCount(t)
return hash
}
func (t *IAVLTree) HashWithCount() ([]byte, int) {
if t.root == nil {
return nil, 0
}
return t.root.hashWithCount(t)
}
func (t *IAVLTree) Save() []byte {
if t.root == nil {
return nil
}
if t.ndb != nil {
t.root.save(t)
t.ndb.Commit()
}
return t.root.hash
}
// Sets the root node by reading from db.
// If the hash is empty, then sets root to nil.
func (t *IAVLTree) Load(hash []byte) {
if len(hash) == 0 {
t.root = nil
} else {
t.root = t.ndb.GetNode(t, hash)
}
}
func (t *IAVLTree) Get(key []byte) (index int, value []byte, exists bool) {
if t.root == nil {
return 0, nil, false
}
return t.root.get(t, key)
}
func (t *IAVLTree) GetByIndex(index int) (key []byte, value []byte) {
if t.root == nil {
return nil, nil
}
return t.root.getByIndex(t, index)
}
func (t *IAVLTree) Remove(key []byte) (value []byte, removed bool) {
if t.root == nil {
return nil, false
}
newRootHash, newRoot, _, value, removed := t.root.remove(t, key)
if !removed {
return nil, false
}
if newRoot == nil && newRootHash != nil {
t.root = t.ndb.GetNode(t, newRootHash)
} else {
t.root = newRoot
}
return value, true
}
func (t *IAVLTree) Iterate(fn func(key []byte, value []byte) bool) (stopped bool) {
if t.root == nil {
return false
}
return t.root.traverse(t, true, func(node *IAVLNode) bool {
if node.height == 0 {
return fn(node.key, node.value)
} else {
return false
}
})
}
// IterateRange makes a callback for all nodes with key between start and end inclusive
// If either are nil, then it is open on that side (nil, nil is the same as Iterate)
func (t *IAVLTree) IterateRange(start, end []byte, ascending bool, fn func(key []byte, value []byte) bool) (stopped bool) {
if t.root == nil {
return false
}
return t.root.traverseInRange(t, start, end, ascending, func(node *IAVLNode) bool {
if node.height == 0 {
return fn(node.key, node.value)
} else {
return false
}
})
}
//-----------------------------------------------------------------------------
type nodeDB struct {
mtx sync.Mutex
cache map[string]*list.Element
cacheSize int
cacheQueue *list.List
db dbm.DB
batch dbm.Batch
orphans map[string]struct{}
orphansPrev map[string]struct{}
}
func newNodeDB(cacheSize int, db dbm.DB) *nodeDB {
ndb := &nodeDB{
cache: make(map[string]*list.Element),
cacheSize: cacheSize,
cacheQueue: list.New(),
db: db,
batch: db.NewBatch(),
orphans: make(map[string]struct{}),
orphansPrev: make(map[string]struct{}),
}
return ndb
}
func (ndb *nodeDB) GetNode(t *IAVLTree, hash []byte) *IAVLNode {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
// Check the cache.
elem, ok := ndb.cache[string(hash)]
if ok {
// Already exists. Move to back of cacheQueue.
ndb.cacheQueue.MoveToBack(elem)
return elem.Value.(*IAVLNode)
} else {
// Doesn't exist, load.
buf := ndb.db.Get(hash)
if len(buf) == 0 {
// ndb.db.Print()
PanicSanity(Fmt("Value missing for key %X", hash))
}
node, err := MakeIAVLNode(buf, t)
if err != nil {
PanicCrisis(Fmt("Error reading IAVLNode. bytes: %X error: %v", buf, err))
}
node.hash = hash
node.persisted = true
ndb.cacheNode(node)
return node
}
}
func (ndb *nodeDB) SaveNode(t *IAVLTree, node *IAVLNode) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if node.hash == nil {
PanicSanity("Expected to find node.hash, but none found.")
}
if node.persisted {
PanicSanity("Shouldn't be calling save on an already persisted node.")
}
/*if _, ok := ndb.cache[string(node.hash)]; ok {
panic("Shouldn't be calling save on an already cached node.")
}*/
// Save node bytes to db
buf := bytes.NewBuffer(nil)
_, err := node.writePersistBytes(t, buf)
if err != nil {
PanicCrisis(err)
}
ndb.batch.Set(node.hash, buf.Bytes())
node.persisted = true
ndb.cacheNode(node)
// Re-creating the orphan,
// Do not garbage collect.
delete(ndb.orphans, string(node.hash))
delete(ndb.orphansPrev, string(node.hash))
}
func (ndb *nodeDB) RemoveNode(t *IAVLTree, node *IAVLNode) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if node.hash == nil {
PanicSanity("Expected to find node.hash, but none found.")
}
if !node.persisted {
PanicSanity("Shouldn't be calling remove on a non-persisted node.")
}
elem, ok := ndb.cache[string(node.hash)]
if ok {
ndb.cacheQueue.Remove(elem)
delete(ndb.cache, string(node.hash))
}
ndb.orphans[string(node.hash)] = struct{}{}
}
func (ndb *nodeDB) cacheNode(node *IAVLNode) {
// Create entry in cache and append to cacheQueue.
elem := ndb.cacheQueue.PushBack(node)
ndb.cache[string(node.hash)] = elem
// Maybe expire an item.
if ndb.cacheQueue.Len() > ndb.cacheSize {
hash := ndb.cacheQueue.Remove(ndb.cacheQueue.Front()).(*IAVLNode).hash
delete(ndb.cache, string(hash))
}
}
func (ndb *nodeDB) Commit() {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
// Delete orphans from previous block
for orphanHashStr, _ := range ndb.orphansPrev {
ndb.batch.Delete([]byte(orphanHashStr))
}
// Write saves & orphan deletes
ndb.batch.Write()
ndb.db.SetSync(nil, nil)
ndb.batch = ndb.db.NewBatch()
// Shift orphans
ndb.orphansPrev = ndb.orphans
ndb.orphans = make(map[string]struct{})
}