forked from onflow/flow-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ledger.go
398 lines (331 loc) · 9.59 KB
/
ledger.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
package ledger
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"github.com/onflow/flow-go/ledger/common/hash"
"github.com/onflow/flow-go/module"
)
// Ledger is a stateful fork-aware key/value storage.
// Any update (value change for a key) to the ledger generates a new ledger state.
// Updates can be applied to any recent states. These changes don't have to be sequential and ledger supports a tree of states.
// Ledger provides value lookup by key at a particular state (historic lookups) and can prove the existence/non-existence of a key-value pair at the given state.
// Ledger assumes the initial state includes all keys with an empty bytes slice as value.
type Ledger interface {
// ledger implements methods needed to be ReadyDone aware
module.ReadyDoneAware
// InitialState returns the initial state of the ledger
InitialState() State
// HasState returns true if the given state exists inside the ledger
HasState(state State) bool
// GetSingleValue returns value for a given key at specific state
GetSingleValue(query *QuerySingleValue) (value Value, err error)
// Get returns values for the given slice of keys at specific state
Get(query *Query) (values []Value, err error)
// Update updates a list of keys with new values at specific state (update) and returns a new state
Set(update *Update) (newState State, trieUpdate *TrieUpdate, err error)
// Prove returns proofs for the given keys at specific state
Prove(query *Query) (proof Proof, err error)
}
// Query holds all data needed for a ledger read or ledger proof
type Query struct {
state State
keys []Key
}
// NewEmptyQuery returns an empty ledger query
func NewEmptyQuery(sc State) (*Query, error) {
return &Query{state: sc}, nil
}
// NewQuery constructs a new ledger query
func NewQuery(sc State, keys []Key) (*Query, error) {
return &Query{state: sc, keys: keys}, nil
}
// Keys returns keys of the query
func (q *Query) Keys() []Key {
return q.keys
}
// Size returns number of keys in the query
func (q *Query) Size() int {
return len(q.keys)
}
// State returns the state part of the query
func (q *Query) State() State {
return q.state
}
// SetState sets the state part of the query
func (q *Query) SetState(s State) {
q.state = s
}
// QuerySingleValue contains ledger query for a single value
type QuerySingleValue struct {
state State
key Key
}
// NewQuerySingleValue constructs a new ledger query for a single value
func NewQuerySingleValue(sc State, key Key) (*QuerySingleValue, error) {
return &QuerySingleValue{state: sc, key: key}, nil
}
// Key returns key of the query
func (q *QuerySingleValue) Key() Key {
return q.key
}
// State returns the state part of the query
func (q *QuerySingleValue) State() State {
return q.state
}
// Update holds all data needed for a ledger update
type Update struct {
state State
keys []Key
values []Value
}
// Size returns number of keys in the ledger update
func (u *Update) Size() int {
return len(u.keys)
}
// Keys returns keys of the update
func (u *Update) Keys() []Key {
return u.keys
}
// Values returns value of the update
func (u *Update) Values() []Value {
return u.values
}
// State returns the state part of this update
func (u *Update) State() State {
return u.state
}
// SetState sets the state part of the update
func (u *Update) SetState(sc State) {
u.state = sc
}
// NewEmptyUpdate returns an empty ledger update
func NewEmptyUpdate(sc State) (*Update, error) {
return &Update{state: sc}, nil
}
// NewUpdate returns an ledger update
func NewUpdate(sc State, keys []Key, values []Value) (*Update, error) {
if len(keys) != len(values) {
return nil, fmt.Errorf("length mismatch: keys have %d elements, but values have %d elements", len(keys), len(values))
}
return &Update{state: sc, keys: keys, values: values}, nil
}
// State captures an state of the ledger
type State hash.Hash
// DummyState is an arbitrary value used in function failure cases,
// although it can represent a valid state.
var DummyState = State(hash.DummyHash)
// String returns the hex encoding of the state
func (sc State) String() string {
return hex.EncodeToString(sc[:])
}
// Base64 return the base64 encoding of the state
func (sc State) Base64() string {
return base64.StdEncoding.EncodeToString(sc[:])
}
// Equals compares the state to another state
func (sc State) Equals(o State) bool {
return sc == o
}
// ToState converts a byte slice into a State.
// It returns an error if the slice has an invalid length.
func ToState(stateBytes []byte) (State, error) {
var state State
if len(stateBytes) != len(state) {
return DummyState, fmt.Errorf("expecting %d bytes but got %d bytes", len(state), len(stateBytes))
}
copy(state[:], stateBytes)
return state, nil
}
// Proof is a byte slice capturing encoded version of a batch proof
type Proof []byte
func (pr Proof) String() string {
return hex.EncodeToString(pr)
}
// Equals compares a proof to another ledger proof
func (pr Proof) Equals(o Proof) bool {
if o == nil {
return false
}
return bytes.Equal(pr, o)
}
// Key represents a hierarchical ledger key
type Key struct {
KeyParts []KeyPart
}
// NewKey construct a new key
func NewKey(kp []KeyPart) Key {
return Key{KeyParts: kp}
}
// Size returns the byte size needed to encode the key
func (k *Key) Size() int {
size := 0
for _, kp := range k.KeyParts {
// value size + 2 bytes for type
size += len(kp.Value) + 2
}
return size
}
// CanonicalForm returns a byte slice describing the key
// Warning: Changing this has an impact on how leaf hashes are computed!
// don't use this to reconstruct the key later
func (k *Key) CanonicalForm() []byte {
// calculate the size of the byte array
// the maximum size of a uint16 is 5 characters, so
// this is using 10 for the estimate, to include the two '/'
// characters and an extra 3 characters for padding safety
constant := 10
requiredLen := constant * len(k.KeyParts)
for _, kp := range k.KeyParts {
requiredLen += len(kp.Value)
}
retval := make([]byte, 0, requiredLen)
for _, kp := range k.KeyParts {
typeNumber := strconv.Itoa(int(kp.Type))
retval = append(retval, byte('/'))
retval = append(retval, []byte(typeNumber)...)
retval = append(retval, byte('/'))
retval = append(retval, kp.Value...)
}
// create a byte slice with the correct size and copy
// the estimated string into it.
return retval
}
func (k *Key) String() string {
return string(k.CanonicalForm())
}
// DeepCopy returns a deep copy of the key
func (k *Key) DeepCopy() Key {
newKPs := make([]KeyPart, len(k.KeyParts))
for i, kp := range k.KeyParts {
newKPs[i] = *kp.DeepCopy()
}
return Key{KeyParts: newKPs}
}
// Equals compares this key to another key
// A nil key is equivalent to an empty key.
func (k *Key) Equals(other *Key) bool {
if k == nil || len(k.KeyParts) == 0 {
return other == nil || len(other.KeyParts) == 0
}
if other == nil {
return false
}
if len(k.KeyParts) != len(other.KeyParts) {
return false
}
for i, kp := range k.KeyParts {
if !kp.Equals(&other.KeyParts[i]) {
return false
}
}
return true
}
// KeyPart is a typed part of a key
type KeyPart struct {
Type uint16
Value []byte
}
// NewKeyPart construct a new key part
func NewKeyPart(typ uint16, val []byte) KeyPart {
return KeyPart{Type: typ, Value: val}
}
// Equals compares this key part to another key part
func (kp *KeyPart) Equals(other *KeyPart) bool {
if other == nil {
return false
}
if kp.Type != other.Type {
return false
}
return bytes.Equal(kp.Value, other.Value)
}
// DeepCopy returns a deep copy of the key part
func (kp *KeyPart) DeepCopy() *KeyPart {
newV := make([]byte, len(kp.Value))
copy(newV, kp.Value)
return &KeyPart{Type: kp.Type, Value: newV}
}
func (kp KeyPart) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type uint16
Value string
}{
Type: kp.Type,
Value: hex.EncodeToString(kp.Value),
})
}
// UnmarshalJSON unmarshals a JSON value of KeyPart.
func (kp *KeyPart) UnmarshalJSON(b []byte) error {
if kp == nil {
return errors.New("UnmarshalJSON on nil KeyPart")
}
var v struct {
Type uint16
Value string
}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
data, err := hex.DecodeString(v.Value)
if err != nil {
return err
}
kp.Type = v.Type
kp.Value = data
return nil
}
// Value holds the value part of a ledger key value pair
type Value []byte
// Size returns the value size
func (v Value) Size() int {
return len(v)
}
func (v Value) String() string {
return hex.EncodeToString(v)
}
// DeepCopy returns a deep copy of the value
func (v Value) DeepCopy() Value {
newV := make([]byte, len(v))
copy(newV, v)
return newV
}
// Equals compares a ledger Value to another one
// A nil value is equivalent to an empty value.
func (v Value) Equals(other Value) bool {
return bytes.Equal(v, other)
}
func (v Value) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(v))
}
// UnmarshalJSON unmarshals a JSON value of Value.
func (v *Value) UnmarshalJSON(b []byte) error {
if v == nil {
return errors.New("UnmarshalJSON on nil Value")
}
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
data, err := hex.DecodeString(s)
if err != nil {
return err
}
*v = data
return nil
}
// Migration defines how to convert the given slice of input payloads into an slice of output payloads
type Migration func(payloads []*Payload) ([]*Payload, error)
// Reporter reports on data from the state
type Reporter interface {
// Name returns the name of the reporter. Only used for logging.
Name() string
// Report accepts slice ledger payloads and reports the state of the ledger
Report(payloads []Payload, statecommitment State) error
}