forked from gatechain/gate-zk-smt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree_node.go
462 lines (414 loc) · 11 KB
/
tree_node.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package zk_smt
import "sync"
const (
hashSize = 32
versionSize = 40
)
func NewTreeNode(depth uint8, path uint64, nilHashes *nilHashes, hasher *Hasher) *TreeNode {
treeNode := &TreeNode{
nilHash: nilHashes.Get(depth),
nilChildHash: nilHashes.Get(depth + 4),
path: path,
depth: depth,
hasher: hasher,
internalMu: make([]sync.RWMutex, 14),
internalVer: make([]Version, 14),
}
for i := 0; i < 2; i++ {
treeNode.Internals[i] = nilHashes.Get(depth + 1)
}
for i := 2; i < 6; i++ {
treeNode.Internals[i] = nilHashes.Get(depth + 2)
}
for i := 6; i < 14; i++ {
treeNode.Internals[i] = nilHashes.Get(depth + 3)
}
return treeNode
}
type InternalNode []byte
type TreeNode struct {
mu sync.RWMutex
Children [16]*TreeNode
Internals [14]InternalNode
Versions []*VersionInfo
nilHash []byte
nilChildHash []byte
path uint64
depth uint8
hasher *Hasher
temporary bool
internalMu []sync.RWMutex
internalVer []Version
}
// Root Get latest hash of a node
func (node *TreeNode) Root() []byte {
node.mu.RLock()
defer node.mu.RUnlock()
if len(node.Versions) == 0 {
return node.nilHash
}
return node.Versions[len(node.Versions)-1].Hash
}
// Root Get latest hash of a node without a lock
func (node *TreeNode) root() []byte {
if len(node.Versions) == 0 {
return node.nilHash
}
return node.Versions[len(node.Versions)-1].Hash
}
func (node *TreeNode) Set(hash []byte, version Version) {
node.mu.Lock()
defer node.mu.Unlock()
node.newVersion(&VersionInfo{
Ver: version,
Hash: hash,
})
}
func (node *TreeNode) newVersion(version *VersionInfo) {
if len(node.Versions) > 0 && node.Versions[len(node.Versions)-1].Ver == version.Ver {
// a new version already exists, overwrite it
node.Versions[len(node.Versions)-1] = version
return
}
node.Versions = append(node.Versions, version)
}
func (node *TreeNode) SetChildren(child *TreeNode, nibble int, version Version) {
node.mu.Lock()
defer node.mu.Unlock()
node.Children[nibble] = child
left, right := node.nilChildHash, node.nilChildHash
switch nibble % 2 {
case 0:
if node.Children[nibble] != nil {
left = node.Children[nibble].Root()
}
if node.Children[nibble^1] != nil {
right = node.Children[nibble^1].Root()
}
case 1:
if node.Children[nibble] != nil {
right = node.Children[nibble].Root()
}
if node.Children[nibble^1] != nil {
left = node.Children[nibble^1].Root()
}
}
prefix := 6
for i := 4; i >= 1; i >>= 1 {
nibble = nibble / 2
node.Internals[prefix+nibble] = node.hasher.Hash(left, right)
switch nibble % 2 {
case 0:
left = node.Internals[prefix+nibble]
right = node.Internals[prefix+nibble^1]
case 1:
right = node.Internals[prefix+nibble]
left = node.Internals[prefix+nibble^1]
}
prefix = prefix - i
}
// update current root node
node.newVersion(&VersionInfo{
Ver: version,
Hash: node.hasher.Hash(node.Internals[0], node.Internals[1]),
})
}
// Recompute all internal hashes
func (node *TreeNode) ComputeInternalHash() {
node.mu.Lock()
defer node.mu.Unlock()
// leaf node
for i := 0; i < 15; i += 2 {
left, right := node.nilChildHash, node.nilChildHash
if node.Children[i] != nil {
left = node.Children[i].Root()
}
if node.Children[i+1] != nil {
right = node.Children[i+1].Root()
}
node.Internals[6+i/2] = node.hasher.Hash(left, right)
}
// internal node
for i := 13; i > 1; i -= 2 {
node.Internals[i/2-1] = node.hasher.Hash(node.Internals[i-1], node.Internals[i])
}
}
func (node *TreeNode) Copy() *TreeNode {
node.mu.RLock()
defer node.mu.RUnlock()
return &TreeNode{
Children: node.Children,
Internals: node.Internals,
Versions: node.Versions,
nilHash: node.nilHash,
nilChildHash: node.nilChildHash,
path: node.path,
depth: node.depth,
hasher: node.hasher,
temporary: node.temporary,
internalMu: node.internalMu,
internalVer: node.internalVer,
}
}
func (node *TreeNode) mark(nibble int) {
//node.mu.Lock()
//defer node.mu.Unlock()
for _, i := range leafInternalMap[nibble] {
node.Internals[i] = nil
}
}
func (node *TreeNode) Prune(oldestVersion Version) uint64 {
node.mu.Lock()
defer node.mu.Unlock()
if len(node.Versions) <= 1 {
return 0
}
i := 0
for ; i < len(node.Versions)-1; i++ {
if node.Versions[i].Ver >= oldestVersion {
break
}
}
originSize := len(node.Versions) * versionSize
if i > 0 && node.Versions[i].Ver > oldestVersion {
node.Versions = node.Versions[i-1:]
return uint64(originSize - len(node.Versions)*versionSize)
}
node.Versions = node.Versions[i:]
return uint64(originSize - len(node.Versions)*versionSize)
}
func (node *TreeNode) Rollback(targetVersion Version) (bool, uint64) {
node.mu.Lock()
defer node.mu.Unlock()
if len(node.Versions) == 0 {
return false, 0
}
var next bool
originSize := len(node.Versions) * versionSize
i := len(node.Versions) - 1
for ; i >= 0; i-- {
if node.Versions[i].Ver <= targetVersion {
break
}
next = true
}
node.Versions = node.Versions[:i+1]
return next, uint64(originSize - len(node.Versions)*versionSize)
}
// The node has not been updated for a long time,
// the subtree is emptied, and needs to be re-read from the database when it needs to be modified.
func (node *TreeNode) archive() {
for i := 0; i < len(node.Internals); i++ {
node.Internals[i] = nil
}
for i := 0; i < len(node.Children); i++ {
node.Children[i] = nil
}
node.temporary = true
}
// PreviousVersion returns the previous version number in the current TreeNode
func (node *TreeNode) PreviousVersion() Version {
node.mu.RLock()
defer node.mu.RUnlock()
if len(node.Versions) <= 1 {
return 0
}
return node.Versions[len(node.Versions)-2].Ver
}
// size returns the current node size
func (node *TreeNode) Size() uint64 {
if node.temporary {
return uint64(len(node.Versions) * versionSize)
}
return uint64(len(node.Versions)*versionSize + hashSize*len(node.Internals))
}
// Release nodes that have not been updated for a long time from memory.
// slowing down memory usage in runtime.
func (node *TreeNode) Release(oldestVersion Version) uint64 {
node.mu.Lock()
defer node.mu.Unlock()
size := node.Size()
for i := 0; i < len(node.Children); i++ {
if node.Children[i] != nil {
length := len(node.Children[i].Versions)
if length > 0 && node.Children[i].Versions[length-1].Ver < oldestVersion {
// check for the latest version and release it if it is older than the pruned version
node.Children[i].archive()
size += node.Children[i].Size()
} else {
size += node.Children[i].Release(oldestVersion)
}
}
}
return size
}
// The nodes without child data.
// will be extended when it needs to be searched down.
func (node *TreeNode) IsTemporary() bool {
return node.temporary
}
func (node *TreeNode) ToStorageTreeNode() *StorageTreeNode {
node.mu.RLock()
defer node.mu.RUnlock()
var children [16]*StorageLeafNode
for i := 0; i < 16; i++ {
if node.Children[i] != nil {
children[i] = &StorageLeafNode{node.Children[i].Versions}
}
}
return &StorageTreeNode{
Children: children,
Internals: node.Internals,
Versions: node.Versions,
Path: node.path,
}
}
type VersionInfo struct {
Ver Version
Hash []byte
}
type StorageLeafNode struct {
Versions []*VersionInfo `rlp:"optional"`
}
type StorageTreeNode struct {
Children [16]*StorageLeafNode `rlp:"optional"`
Internals [14]InternalNode `rlp:"optional"`
Versions []*VersionInfo `rlp:"optional"`
Path uint64 `rlp:"optional"`
}
func (node *StorageTreeNode) ToTreeNode(depth uint8, nilHashes *nilHashes, hasher *Hasher) *TreeNode {
treeNode := &TreeNode{
Internals: node.Internals,
Versions: node.Versions,
nilHash: nilHashes.Get(depth),
nilChildHash: nilHashes.Get(depth + 4),
path: node.Path,
depth: depth,
hasher: hasher,
internalMu: make([]sync.RWMutex, 14),
internalVer: make([]Version, 14),
}
for i := 0; i < 16; i++ {
if node.Children[i] != nil && len(node.Children[i].Versions) > 0 {
treeNode.Children[i] = &TreeNode{
Versions: node.Children[i].Versions,
nilHash: nilHashes.Get(depth + 4),
nilChildHash: nilHashes.Get(depth + 8),
hasher: hasher,
temporary: true,
depth: depth + 4,
path: treeNode.path<<4 + uint64(i),
}
}
}
return treeNode
}
func (node *TreeNode) latestVersion() Version {
if len(node.Versions) <= 0 {
return 0
}
return node.Versions[len(node.Versions)-1].Ver
}
func (node *TreeNode) latestVersionWithLock() Version {
node.mu.RLock()
defer node.mu.RUnlock()
if len(node.Versions) <= 0 {
return 0
}
return node.Versions[len(node.Versions)-1].Ver
}
// recompute inner node
func (node *TreeNode) recompute(child *TreeNode, journals *journal, version Version) bool {
nibble := int(child.path & 0xf)
left, right := node.nilChildHash, node.nilChildHash
// if sibling haven't finished yet,quit; sibling will be charge for computing
switch nibble % 2 {
case 0:
left = child.root()
if sibling, exist := journals.get(journalKey{child.depth, child.path ^ 1}); exist {
if sibling.latestVersionWithLock() < version {
return false
}
right = sibling.root()
} else if node.Children[nibble^1] != nil {
right = node.Children[nibble^1].Root()
}
case 1:
right = child.root()
if sibling, exist := journals.get(journalKey{child.depth, child.path ^ 1}); exist {
if sibling.latestVersionWithLock() < version {
return false
}
left = sibling.root()
} else if node.Children[nibble^1] != nil {
left = node.Children[nibble^1].Root()
}
}
prefix := 6
for i := 4; i >= 1; i >>= 1 {
nibble = nibble / 2
hash, setBefore := node.setInternal(prefix+nibble, left, right, version)
if setBefore {
return false
}
siblingNibble := prefix + nibble ^ 1
siblingHash := node.getInternal(siblingNibble)
if siblingHash == nil {
return false
}
switch nibble % 2 {
case 0:
left = hash
right = siblingHash
case 1:
right = hash
left = siblingHash
}
prefix = prefix - i
}
// update current root
node.newVersion(&VersionInfo{
Ver: version,
Hash: node.hasher.Hash(node.Internals[0], node.Internals[1]),
})
return true
}
func (node *TreeNode) setInternal(idx int, left []byte, right []byte, version Version) ([]byte, bool) {
node.internalMu[idx].Lock()
defer node.internalMu[idx].Unlock()
if node.Internals[idx] != nil {
return node.Internals[idx], true
}
hash := node.hasher.Hash(left, right)
node.Internals[idx] = hash
node.internalVer[idx] = version
return hash, false
}
func (node *TreeNode) getInternal(idx int) []byte {
node.internalMu[idx].RLock()
defer node.internalMu[idx].RUnlock()
return node.Internals[idx]
}
func (node *TreeNode) getChild(nibble int) *TreeNode {
node.mu.RLock()
defer node.mu.RUnlock()
return node.Children[nibble]
}
var leafInternalMap = map[int][]int{
0: {0, 2, 6},
1: {0, 2, 6},
2: {0, 2, 7},
3: {0, 2, 7},
4: {0, 3, 8},
5: {0, 3, 8},
6: {0, 3, 9},
7: {0, 3, 9},
8: {1, 4, 10},
9: {1, 4, 10},
10: {1, 4, 11},
11: {1, 4, 11},
12: {1, 5, 12},
13: {1, 5, 12},
14: {1, 5, 13},
15: {1, 5, 13},
}