asmt/asmt.go
asmt.goRaw
1package asmtree
2
3import (
4 "bytes"
5 "fmt"
6 "path"
7 "sync/atomic"
8 "time"
9
10 "go.vocdoni.io/dvote/censustree"
11 "go.vocdoni.io/dvote/log"
12
13 "git.sr.ht/~sircmpwn/go-bare"
14 "github.com/p4u/asmt/db"
15 asmt "github.com/p4u/asmt/smt"
16)
17
18// We use go-bare for export/import the trie. In order to support
19// big census (up to 8 Million entries) we need to increase the maximums.
20const bareMaxArrayLength uint64 = 1024 * 1014 * 8 // 8 Million
21
22const bareMaxUnmarshalBytes uint64 = bareMaxArrayLength * 32 * 2 // 512 MiB
23
24type Tree struct {
25 Tree *asmt.Trie
26 db db.DB
27 public uint32
28 lastAccessUnix int64 // a unix timestamp, used via sync/atomic
29 size uint64
30 snapshotRoot []byte // if not nil, this trie is considered an inmutable snapshot
31 snapshotSize uint64
32}
33
34type Proof struct {
35 Bitmap []byte
36 Length int
37 Siblings [][]byte
38 Value []byte
39}
40
41type exportElement struct {
42 Key []byte `bare:"key"`
43 Value []byte `bare:"value"`
44}
45
46type exportData struct {
47 Elements []exportElement `bare:"elements"`
48}
49
50const (
51 MaxKeySize = 32
52 MaxValueSize = 64
53 dbRootPrefix = "this is the last root for the SMT tree"
54)
55
56// NewTree initializes a new AergoSMT tree following the censustree.Tree interface specification.
57func NewTree(name, storageDir string) (censustree.Tree, error) {
58 tr := &Tree{}
59 err := tr.Init(name, storageDir)
60 return tr, err
61}
62
63// newTree opens or creates a merkle tree under the given storage.
64func newTree(name, storageDir string) (*asmt.Trie, db.DB, error) {
65 dir := path.Join(storageDir, name)
66 log.Debugf("creating new tree on %s", dir)
67 d := db.NewDB(db.LevelImpl, dir)
68 root := d.Get([]byte(dbRootPrefix))
69 tr := asmt.NewTrie(root, asmt.Hasher, d)
70 if root != nil {
71 if err := tr.LoadCache(root); err != nil {
72 return nil, nil, err
73 }
74 }
75 return tr, d, nil
76}
77
78// Init initializes a new asmt tree
79func (t *Tree) Init(name, storageDir string) error {
80 var err error
81 t.Tree, t.db, err = newTree(name, storageDir)
82 t.updateAccessTime()
83 t.size = 0
84 return err
85}
86
87func (t *Tree) MaxKeySize() int {
88 return MaxKeySize
89}
90
91// LastAccess returns the last time the Tree was accessed, in the form of a unix
92// timestamp.
93func (t *Tree) LastAccess() int64 {
94 return atomic.LoadInt64(&t.lastAccessUnix)
95}
96
97func (t *Tree) updateAccessTime() {
98 atomic.StoreInt64(&t.lastAccessUnix, time.Now().Unix())
99}
100
101// Publish makes a merkle tree available for queries.
102// Application layer should check IsPublish() before considering the Tree available.
103func (t *Tree) Publish() {
104 atomic.StoreUint32(&t.public, 1)
105}
106
107// UnPublish makes a merkle tree not available for queries
108func (t *Tree) UnPublish() {
109 atomic.StoreUint32(&t.public, 0)
110}
111
112// IsPublic returns true if the tree is available
113func (t *Tree) IsPublic() bool {
114 return atomic.LoadUint32(&t.public) == 1
115}
116
117// Commit saves permanently the tree on disk
118func (t *Tree) Commit() error {
119 if t.snapshotRoot != nil {
120 return fmt.Errorf("cannot commit to a snapshot trie")
121 }
122 err := t.Tree.Commit()
123 if err != nil {
124 return err
125 }
126 t.db.Set([]byte(dbRootPrefix), t.Root())
127 return nil
128}
129
130// Add adds a new claim to the merkle tree
131// A claim is composed of two parts: index and value
132// 1.index is mandatory, the data will be used for indexing the claim into to merkle tree
133// 2.value is optional, the data will not affect the indexing
134func (t *Tree) Add(index, value []byte) error {
135 t.updateAccessTime()
136 if t.snapshotRoot != nil {
137 return fmt.Errorf("cannot add to a snapshot trie")
138 }
139 if len(index) < 4 || len(index) > MaxKeySize {
140 return fmt.Errorf("wrong key size: %d", len(index))
141 }
142 if len(value) > MaxValueSize {
143 return fmt.Errorf("index or value claim data too big")
144 }
145 _, err := t.Tree.Update([][]byte{asmt.Hasher(index)}, [][]byte{asmt.Hasher(value)})
146 if err != nil {
147 return err
148 }
149 atomic.StoreUint64(&t.size, 0) // TBD: improve this
150 return t.Commit()
151}
152
153// AddBatch adds a list of indexes and values.
154// The commit to disk is executed only once.
155// The values slince could be empty or as long as indexes.
156func (t *Tree) AddBatch(indexes, values [][]byte) ([]int, error) {
157 var wrongIndexes []int
158 t.updateAccessTime()
159 if t.snapshotRoot != nil {
160 return wrongIndexes, fmt.Errorf("cannot add to a snapshot trie")
161 }
162 if len(values) > 0 && len(indexes) != len(values) {
163 return wrongIndexes, fmt.Errorf("indexes and values have different size")
164 }
165 var value []byte
166 for i, key := range indexes {
167 if len(key) < 4 || len(key) > MaxKeySize {
168 wrongIndexes = append(wrongIndexes, i)
169 continue
170 }
171 value = nil
172 if len(values) > 0 {
173 if len(values[i]) > MaxValueSize {
174 wrongIndexes = append(wrongIndexes, i)
175 continue
176 }
177 value = values[i]
178 }
179 _, err := t.Tree.Update([][]byte{asmt.Hasher(key)}, [][]byte{asmt.Hasher(value)})
180 if err != nil {
181 return wrongIndexes, err
182 }
183 }
184 atomic.StoreUint64(&t.size, 0) // TBD: improve this
185 return wrongIndexes, t.Commit()
186}
187
188// Get returns the value of a key
189func (t *Tree) Get(key []byte) []byte { // Do something with error
190 var value []byte
191 if t.snapshotRoot != nil {
192 value, _ = t.Tree.GetWithRoot(key, t.snapshotRoot)
193 } else {
194 value, _ = t.Tree.Get(key)
195 }
196 return value
197}
198
199// GenProof generates a merkle tree proof that can be later used on CheckProof() to validate it.
200func (t *Tree) GenProof(index, value []byte) ([]byte, error) {
201 t.updateAccessTime()
202 var err error
203 var ap [][]byte
204 var pvalue, bitmap []byte
205 var length int
206 var included bool
207 key := asmt.Hasher(index)
208 if t.snapshotRoot != nil {
209 bitmap, ap, length, included, _, pvalue, err = t.Tree.MerkleProofCompressedR(key,
210 t.snapshotRoot)
211 if err != nil {
212 return nil, err
213 }
214 } else {
215 bitmap, ap, length, included, _, pvalue, err = t.Tree.MerkleProofCompressed(key)
216 if err != nil {
217 return nil, err
218 }
219 }
220 if !included {
221 return nil, nil
222 }
223 if !bytes.Equal(pvalue, asmt.Hasher(value)) {
224 return nil, fmt.Errorf("incorrect value or key on genProof")
225 }
226 return bare.Marshal(&Proof{Bitmap: bitmap, Length: length, Siblings: ap, Value: pvalue})
227}
228
229// CheckProof validates a merkle proof and its data.
230func (t *Tree) CheckProof(index, value, root, mproof []byte) (bool, error) {
231 t.updateAccessTime()
232 p := Proof{}
233 if err := bare.Unmarshal(mproof, &p); err != nil {
234 return false, err
235 }
236 if !bytes.Equal(p.Value, asmt.Hasher(value)) {
237 return false, fmt.Errorf("values mismatch %x != %x", p.Value, asmt.Hasher(value))
238 }
239 if root != nil {
240 return t.Tree.VerifyInclusionWithRootC(
241 root,
242 p.Bitmap,
243 asmt.Hasher(index),
244 p.Value,
245 p.Siblings,
246 p.Length), nil
247 }
248 if t.snapshotRoot != nil {
249 return t.Tree.VerifyInclusionWithRootC(
250 t.snapshotRoot,
251 p.Bitmap,
252 asmt.Hasher(index),
253 p.Value,
254 p.Siblings,
255 p.Length), nil
256 }
257 return t.Tree.VerifyInclusionC(
258 p.Bitmap,
259 asmt.Hasher(index),
260 p.Value,
261 p.Siblings,
262 p.Length), nil
263}
264
265// Root returns the current root hash of the merkle tree
266func (t *Tree) Root() []byte {
267 t.updateAccessTime()
268 if t.snapshotRoot != nil {
269 return t.snapshotRoot
270 }
271 return t.Tree.Root
272}
273
274// Dump returns the whole merkle tree serialized in a format that can be used on Import.
275// Byte seralization is performed using bare message protocol, it is a 40% size win over JSON.
276func (t *Tree) Dump(root []byte) ([]byte, error) {
277 t.updateAccessTime()
278 if root == nil && t.snapshotRoot != nil {
279 root = t.snapshotRoot
280 }
281 dump := exportData{}
282 t.iterateWithRoot(root, nil, func(k, v []byte) bool {
283 ee := exportElement{Key: make([]byte, len(k)), Value: make([]byte, len(v))}
284 // Copy elements since it's not safe to hold on to the []byte values from Iterate
285 copy(ee.Key, k[:])
286 copy(ee.Value, v[:])
287 dump.Elements = append(dump.Elements, ee)
288 return false
289 })
290 bare.MaxArrayLength(bareMaxArrayLength)
291 bare.MaxUnmarshalBytes(bareMaxUnmarshalBytes)
292
293 return bare.Marshal(&dump)
294}
295
296// String returns a human readable representation of the tree.
297func (t *Tree) String() string {
298 s := bytes.Buffer{}
299 t.iterate(t.snapshotRoot, func(k, v []byte) bool {
300 s.WriteString(fmt.Sprintf("%x => %x\n", k, v))
301 return false
302 })
303 return s.String()
304}
305
306// Size returns the number of leaf nodes on the merkle tree.
307// TO-DO: root is currently ignored
308func (t *Tree) Size(root []byte) (int64, error) {
309 if t.snapshotRoot != nil {
310 return int64(t.snapshotSize), nil
311 }
312 return int64(t.count()), nil
313}
314
315// DumpPlain returns the entire list of added claims for a specific root hash.
316// First return parametre are the indexes and second the values.
317// If root is not specified, the last one is used.
318func (t *Tree) DumpPlain(root []byte) ([][]byte, [][]byte, error) {
319 var indexes, values [][]byte
320 var err error
321 t.updateAccessTime()
322
323 t.iterateWithRoot(root, nil, func(k, v []byte) bool {
324 indexes = append(indexes, k)
325 values = append(values, v)
326 return false
327 })
328
329 return indexes, values, err
330}
331
332// ImportDump imports a partial or whole tree previously exported with Dump()
333func (t *Tree) ImportDump(data []byte) error {
334 t.updateAccessTime()
335 if t.snapshotRoot != nil {
336 return fmt.Errorf("cannot import to a snapshot")
337 }
338 census := new(exportData)
339 bare.MaxArrayLength(bareMaxArrayLength)
340 bare.MaxUnmarshalBytes(bareMaxUnmarshalBytes)
341 if err := bare.Unmarshal(data, census); err != nil {
342 return fmt.Errorf("importdump cannot unmarshal data: %w", err)
343 }
344 keys := [][]byte{}
345 values := [][]byte{}
346 for _, ee := range census.Elements {
347 keys = append(keys, ee.Key)
348 values = append(values, ee.Value)
349 }
350 _, err := t.Tree.Update(keys, values)
351 if err != nil {
352 return err
353 }
354 atomic.StoreUint64(&t.size, 0) // TBD: improve this
355 return t.Commit()
356}
357
358// Snapshot returns a Tree instance of a exiting merkle root.
359// A Snapshot cannot be modified.
360func (t *Tree) Snapshot(root []byte) (censustree.Tree, error) {
361 exist, err := t.HashExists(root)
362 if err != nil {
363 return nil, err
364 }
365 if !exist {
366 return nil, fmt.Errorf("root %x does not exist, cannot build snapshot", root)
367 }
368 return &Tree{Tree: t.Tree, public: t.public, snapshotRoot: root, snapshotSize: t.count()}, nil
369}
370
371func (t *Tree) Close() error {
372 t.db.Close()
373 return nil
374}
375
376// HashExists checks if a hash exists as a node in the merkle tree
377func (t *Tree) HashExists(hash []byte) (bool, error) {
378 t.updateAccessTime()
379 return t.Tree.TrieRootExists(hash), nil
380}
381
382func (t *Tree) count() uint64 {
383 if v := atomic.LoadUint64(&t.size); v != 0 {
384 return v
385 }
386 counter := uint64(0)
387 if err := t.Tree.Walk(t.snapshotRoot, func(*asmt.WalkResult) int32 {
388 counter++
389 return 0
390 }); err != nil {
391 return 0
392 }
393 atomic.StoreUint64(&t.size, counter)
394 return counter
395}
396
397func (t *Tree) iterate(prefix []byte, callback func(key, value []byte) bool) {
398 t.Tree.Walk(t.snapshotRoot, func(v *asmt.WalkResult) int32 {
399 if callback(v.Key, v.Value) {
400 return 1
401 } else {
402 return 0
403 }
404 })
405}
406
407func (t *Tree) iterateWithRoot(root, prefix []byte, callback func(key, value []byte) bool) {
408 t.Tree.Walk(root, func(v *asmt.WalkResult) int32 {
409 if callback(v.Key, v.Value) {
410 return 1
411 } else {
412 return 0
413 }
414 })
415}