github.com/lazyledger/lazyledger-core@v0.35.0-dev.0.20210613111200-4c651f053571/p2p/ipld/nmt_adder.go (about) 1 package ipld 2 3 import ( 4 "context" 5 6 "github.com/ipfs/go-cid" 7 ipld "github.com/ipfs/go-ipld-format" 8 9 "github.com/lazyledger/lazyledger-core/ipfs/plugin" 10 ) 11 12 // NmtNodeAdder adds ipld.Nodes to the underlying ipld.Batch if it is inserted 13 // into an nmt tree 14 type NmtNodeAdder struct { 15 ctx context.Context 16 batch *ipld.Batch 17 leaves *cid.Set 18 err error 19 } 20 21 // NewNmtNodeAdder returns a new NmtNodeAdder with the provided context and 22 // batch. Note that the context provided should have a timeout 23 // It is not thread-safe. 24 func NewNmtNodeAdder(ctx context.Context, batch *ipld.Batch) *NmtNodeAdder { 25 return &NmtNodeAdder{ 26 batch: batch, 27 ctx: ctx, 28 leaves: cid.NewSet(), 29 } 30 } 31 32 // Visit can be inserted into an nmt tree to create ipld.Nodes while computing the root 33 func (n *NmtNodeAdder) Visit(hash []byte, children ...[]byte) { 34 if n.err != nil { 35 return // protect from further visits if there is an error 36 } 37 38 id := plugin.MustCidFromNamespacedSha256(hash) 39 switch len(children) { 40 case 1: 41 if n.leaves.Visit(id) { 42 n.err = n.batch.Add(n.ctx, plugin.NewNMTLeafNode(id, children[0])) 43 } 44 case 2: 45 n.err = n.batch.Add(n.ctx, plugin.NewNMTNode(id, children[0], children[1])) 46 default: 47 panic("expected a binary tree") 48 } 49 } 50 51 // Batch return the ipld.Batch originally provided to the NmtNodeAdder 52 func (n *NmtNodeAdder) Batch() *ipld.Batch { 53 return n.batch 54 } 55 56 // Commit checks for errors happened during Visit and if absent commits data to inner Batch. 57 func (n *NmtNodeAdder) Commit() error { 58 if n.err != nil { 59 return n.err 60 } 61 62 return n.batch.Commit() 63 }