forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 3
/
history.go
258 lines (224 loc) · 7.4 KB
/
history.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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package merkledb
import (
"errors"
"fmt"
"github.com/google/btree"
"github.com/MetalBlockchain/metalgo/ids"
)
var (
ErrStartRootNotFound = errors.New("start root is not before end root in history")
ErrRootIDNotPresent = errors.New("root id is not present in history")
)
// stores previous trie states
type trieHistory struct {
// Root ID --> The most recent change resulting in [rootID].
lastChanges map[ids.ID]*changeSummaryAndIndex
// Maximum number of previous roots/changes to store in [history].
maxHistoryLen int
// Contains the history.
// Sorted by increasing order of insertion.
// Contains at most [maxHistoryLen] values.
history *btree.BTreeG[*changeSummaryAndIndex]
nextIndex uint64
}
// Tracks the beginning and ending state of a value.
type change[T any] struct {
before T
after T
}
// Wrapper around a changeSummary that allows comparison
// of when the change was made.
type changeSummaryAndIndex struct {
*changeSummary
// Another changeSummaryAndIndex with a greater
// [index] means that change was after this one.
index uint64
}
// Tracks all of the node and value changes that resulted in the rootID.
type changeSummary struct {
rootID ids.ID
// key is path prefix
nodes map[path]*change[*node]
// key is full path
values map[path]*change[Maybe[[]byte]]
}
func newChangeSummary(estimatedSize int) *changeSummary {
return &changeSummary{
nodes: make(map[path]*change[*node], estimatedSize),
values: make(map[path]*change[Maybe[[]byte]], estimatedSize),
}
}
func newTrieHistory(maxHistoryLookback int) *trieHistory {
return &trieHistory{
maxHistoryLen: maxHistoryLookback,
history: btree.NewG(
2,
func(a, b *changeSummaryAndIndex) bool {
return a.index < b.index
},
),
lastChanges: make(map[ids.ID]*changeSummaryAndIndex),
}
}
// Returns up to [maxLength] key-value pair changes with keys in [start, end] that
// occurred between [startRoot] and [endRoot].
func (th *trieHistory) getValueChanges(startRoot, endRoot ids.ID, start, end []byte, maxLength int) (*changeSummary, error) {
if maxLength <= 0 {
return nil, fmt.Errorf("%w but was %d", ErrInvalidMaxLength, maxLength)
}
if startRoot == endRoot {
return newChangeSummary(maxLength), nil
}
// Confirm there's a change resulting in [startRoot] before
// a change resulting in [endRoot] in the history.
// [lastEndRootChange] is the last change in the history resulting in [endRoot].
lastEndRootChange, ok := th.lastChanges[endRoot]
if !ok {
return nil, ErrRootIDNotPresent
}
// [lastStartRootChange] is the latest appearance of [startRoot]
// which came before [lastEndRootChange].
var lastStartRootChange *changeSummaryAndIndex
th.history.DescendLessOrEqual(
lastEndRootChange,
func(item *changeSummaryAndIndex) bool {
if item == lastEndRootChange {
return true // Skip first iteration
}
if item.rootID == startRoot {
lastStartRootChange = item
return false
}
return true
},
)
// There's no change resulting in [startRoot] before the latest change resulting in [endRoot].
if lastStartRootChange == nil {
return nil, ErrStartRootNotFound
}
// Keep changes sorted so the largest can be removed in order to stay within the maxLength limit.
sortedKeys := btree.NewG(
2,
func(a, b path) bool {
return a.Compare(b) < 0
},
)
startPath := newPath(start)
endPath := newPath(end)
// For each element in the history in the range between [startRoot]'s
// last appearance (exclusive) and [endRoot]'s last appearance (inclusive),
// add the changes to keys in [start, end] to [combinedChanges].
// Only the key-value pairs with the greatest [maxLength] keys will be kept.
combinedChanges := newChangeSummary(maxLength)
// For each change after [lastStartRootChange] up to and including
// [lastEndRootChange], record the change in [combinedChanges].
th.history.AscendGreaterOrEqual(
lastStartRootChange,
func(item *changeSummaryAndIndex) bool {
if item == lastStartRootChange {
// Start from the first change after [lastStartRootChange].
return true
}
if item.index > lastEndRootChange.index {
// Don't go past [lastEndRootChange].
return false
}
for key, valueChange := range item.values {
if (len(startPath) == 0 || key.Compare(startPath) >= 0) &&
(len(endPath) == 0 || key.Compare(endPath) <= 0) {
if existing, ok := combinedChanges.values[key]; ok {
existing.after = valueChange.after
} else {
combinedChanges.values[key] = &change[Maybe[[]byte]]{
before: valueChange.before,
after: valueChange.after,
}
}
sortedKeys.ReplaceOrInsert(key)
}
}
// Keep only the smallest [maxLength] items in [combinedChanges.values].
for sortedKeys.Len() > maxLength {
if greatestKey, found := sortedKeys.DeleteMax(); found {
delete(combinedChanges.values, greatestKey)
}
}
return true
},
)
return combinedChanges, nil
}
// Returns the changes to go from the current trie state back to the requested [rootID]
// for the keys in [start, end].
// If [start] is nil, all keys are considered > [start].
// If [end] is nil, all keys are considered < [end].
func (th *trieHistory) getChangesToGetToRoot(rootID ids.ID, start, end []byte) (*changeSummary, error) {
// [lastRootChange] is the last change in the history resulting in [rootID].
lastRootChange, ok := th.lastChanges[rootID]
if !ok {
return nil, ErrRootIDNotPresent
}
var (
startPath = newPath(start)
endPath = newPath(end)
combinedChanges = newChangeSummary(defaultPreallocationSize)
)
// Go backward from the most recent change in the history up to but
// not including the last change resulting in [rootID].
// Record each change in [combinedChanges].
th.history.Descend(
func(item *changeSummaryAndIndex) bool {
if item == lastRootChange {
return false
}
for key, changedNode := range item.nodes {
combinedChanges.nodes[key] = &change[*node]{
after: changedNode.before,
}
}
for key, valueChange := range item.values {
if (len(startPath) == 0 || key.Compare(startPath) >= 0) &&
(len(endPath) == 0 || key.Compare(endPath) <= 0) {
if existing, ok := combinedChanges.values[key]; ok {
existing.after = valueChange.before
} else {
combinedChanges.values[key] = &change[Maybe[[]byte]]{
before: valueChange.after,
after: valueChange.before,
}
}
}
}
return true
},
)
return combinedChanges, nil
}
// record the provided set of changes in the history
func (th *trieHistory) record(changes *changeSummary) {
// we aren't recording history so noop
if th.maxHistoryLen == 0 {
return
}
for th.history.Len() == th.maxHistoryLen {
// This change causes us to go over our lookback limit.
// Remove the oldest set of changes.
oldestEntry, _ := th.history.DeleteMin()
latestChange := th.lastChanges[oldestEntry.rootID]
if latestChange == oldestEntry {
// The removed change was the most recent resulting in this root ID.
delete(th.lastChanges, oldestEntry.rootID)
}
}
changesAndIndex := &changeSummaryAndIndex{
changeSummary: changes,
index: th.nextIndex,
}
th.nextIndex++
// Add [changes] to the sorted change list.
_, _ = th.history.ReplaceOrInsert(changesAndIndex)
// Mark that this is the most recent change resulting in [changes.rootID].
th.lastChanges[changes.rootID] = changesAndIndex
}