-
Notifications
You must be signed in to change notification settings - Fork 80
/
tree.go
58 lines (47 loc) · 1.52 KB
/
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
package rsmt2d
import (
"fmt"
"sync"
)
// TreeConstructorFn creates a fresh Tree instance to be used as the Merkle tree
// inside of rsmt2d.
type TreeConstructorFn = func(axis Axis, index uint) Tree
// SquareIndex contains all information needed to identify the cell that is being
// pushed
type SquareIndex struct {
Axis, Cell uint
}
// Tree wraps Merkle tree implementations to work with rsmt2d
type Tree interface {
Push(data []byte) error
Root() ([]byte, error)
}
// treeFns is a global map used for keeping track of registered tree constructors for JSON serialization
// The keys of this map should be kebab cased. E.g. "default-tree"
var treeFns = sync.Map{}
// RegisterTree must be called in the init function
func RegisterTree(treeName string, treeConstructor TreeConstructorFn) error {
if _, ok := treeFns.Load(treeName); ok {
return fmt.Errorf("%s already registered", treeName)
}
treeFns.Store(treeName, treeConstructor)
return nil
}
// TreeFn get tree constructor function by tree name from the global map registry
func TreeFn(treeName string) (TreeConstructorFn, error) {
var treeFn TreeConstructorFn
v, ok := treeFns.Load(treeName)
if !ok {
return nil, fmt.Errorf("%s not registered yet", treeName)
}
treeFn, ok = v.(TreeConstructorFn)
if !ok {
return nil, fmt.Errorf("key %s has invalid interface", treeName)
}
return treeFn, nil
}
// removeTreeFn removes a treeConstructorFn by treeName.
// Only use for test cleanup. Proceed with caution.
func removeTreeFn(treeName string) {
treeFns.Delete(treeName)
}