-
Notifications
You must be signed in to change notification settings - Fork 4
/
treebuilder.go
75 lines (62 loc) · 1.99 KB
/
treebuilder.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
package merkle
type TreeBuilder struct {
hash HashFunc
leavesToProves Set
cacheWriter CacheWriter
minHeight uint
}
func NewTreeBuilder() TreeBuilder {
return TreeBuilder{}
}
func (tb TreeBuilder) Build() (*Tree, error) {
if tb.hash == nil {
tb.hash = GetSha256Parent
}
if tb.cacheWriter == nil {
tb.cacheWriter = disabledCacheWriter{}
}
tb.cacheWriter.SetHash(tb.hash)
writer, err := tb.cacheWriter.GetLayerWriter(0)
if err != nil {
return &Tree{}, err
}
return &Tree{
baseLayer: newLayer(0, writer),
hash: tb.hash,
leavesToProve: NewSparseBoolStack(tb.leavesToProves),
cacheWriter: tb.cacheWriter,
minHeight: tb.minHeight,
}, nil
}
func (tb TreeBuilder) WithHashFunc(hash HashFunc) TreeBuilder {
tb.hash = hash
return tb
}
func (tb TreeBuilder) WithLeavesToProve(leavesToProves map[uint64]bool) TreeBuilder {
tb.leavesToProves = leavesToProves
return tb
}
func (tb TreeBuilder) WithCacheWriter(cacheWriter CacheWriter) TreeBuilder {
tb.cacheWriter = cacheWriter
return tb
}
func (tb TreeBuilder) WithMinHeight(minHeight uint) TreeBuilder {
tb.minHeight = minHeight
return tb
}
func NewTree() (*Tree, error) {
return NewTreeBuilder().Build()
}
func NewProvingTree(leavesToProves map[uint64]bool) (*Tree, error) {
return NewTreeBuilder().WithLeavesToProve(leavesToProves).Build()
}
func NewCachingTree(cacheWriter CacheWriter) (*Tree, error) {
return NewTreeBuilder().WithCacheWriter(cacheWriter).Build()
}
type disabledCacheWriter struct{}
// A compile time check to ensure that disabledCacheWriter fully implements CacheWriter.
var _ CacheWriter = (*disabledCacheWriter)(nil)
func (disabledCacheWriter) SetLayer(layerHeight uint, rw LayerReadWriter) {}
func (disabledCacheWriter) GetLayerWriter(layerHeight uint) (LayerWriter, error) { return nil, nil }
func (disabledCacheWriter) SetHash(hashFunc HashFunc) {}
func (disabledCacheWriter) GetReader() (CacheReader, error) { return nil, nil }