github.com/ethersphere/bee/v2@v2.2.0/pkg/file/pipeline/bmt/bmt.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package bmt
     6  
     7  import (
     8  	"errors"
     9  
    10  	"github.com/ethersphere/bee/v2/pkg/bmtpool"
    11  	"github.com/ethersphere/bee/v2/pkg/file/pipeline"
    12  	"github.com/ethersphere/bee/v2/pkg/swarm"
    13  )
    14  
    15  var (
    16  	errInvalidData = errors.New("bmt: invalid data")
    17  )
    18  
    19  type bmtWriter struct {
    20  	next pipeline.ChainWriter
    21  }
    22  
    23  // NewBmtWriter returns a new bmtWriter. Partial writes are not supported.
    24  // Note: branching factor is the BMT branching factor, not the merkle trie branching factor.
    25  func NewBmtWriter(next pipeline.ChainWriter) pipeline.ChainWriter {
    26  	return &bmtWriter{
    27  		next: next,
    28  	}
    29  }
    30  
    31  // ChainWrite writes data in chain. It assumes span has been prepended to the data.
    32  // The span can be encrypted or unencrypted.
    33  func (w *bmtWriter) ChainWrite(p *pipeline.PipeWriteArgs) error {
    34  	if len(p.Data) < swarm.SpanSize {
    35  		return errInvalidData
    36  	}
    37  	hasher := bmtpool.Get()
    38  	hasher.SetHeader(p.Data[:swarm.SpanSize])
    39  	_, err := hasher.Write(p.Data[swarm.SpanSize:])
    40  	if err != nil {
    41  		bmtpool.Put(hasher)
    42  		return err
    43  	}
    44  	p.Ref, err = hasher.Hash(nil)
    45  	bmtpool.Put(hasher)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	return w.next.ChainWrite(p)
    51  }
    52  
    53  // sum calls the next writer for the cryptographic sum
    54  func (w *bmtWriter) Sum() ([]byte, error) {
    55  	return w.next.Sum()
    56  }