-
Notifications
You must be signed in to change notification settings - Fork 337
/
bmt.go
56 lines (47 loc) · 1.36 KB
/
bmt.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bmt
import (
"errors"
"github.com/ethersphere/bee/v2/pkg/bmtpool"
"github.com/ethersphere/bee/v2/pkg/file/pipeline"
"github.com/ethersphere/bee/v2/pkg/swarm"
)
var (
errInvalidData = errors.New("bmt: invalid data")
)
type bmtWriter struct {
next pipeline.ChainWriter
}
// NewBmtWriter returns a new bmtWriter. Partial writes are not supported.
// Note: branching factor is the BMT branching factor, not the merkle trie branching factor.
func NewBmtWriter(next pipeline.ChainWriter) pipeline.ChainWriter {
return &bmtWriter{
next: next,
}
}
// ChainWrite writes data in chain. It assumes span has been prepended to the data.
// The span can be encrypted or unencrypted.
func (w *bmtWriter) ChainWrite(p *pipeline.PipeWriteArgs) error {
if len(p.Data) < swarm.SpanSize {
return errInvalidData
}
hasher := bmtpool.Get()
hasher.SetHeader(p.Data[:swarm.SpanSize])
_, err := hasher.Write(p.Data[swarm.SpanSize:])
if err != nil {
bmtpool.Put(hasher)
return err
}
p.Ref, err = hasher.Hash(nil)
bmtpool.Put(hasher)
if err != nil {
return err
}
return w.next.ChainWrite(p)
}
// sum calls the next writer for the cryptographic sum
func (w *bmtWriter) Sum() ([]byte, error) {
return w.next.Sum()
}