github.com/sunrise-zone/sunrise-node@v0.13.1-sr2/share/ipld/get_shares.go (about)

     1  package ipld
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/ipfs/boxo/blockservice"
     7  	"github.com/ipfs/go-cid"
     8  	format "github.com/ipfs/go-ipld-format"
     9  
    10  	"github.com/celestiaorg/nmt"
    11  
    12  	"github.com/sunrise-zone/sunrise-node/share"
    13  )
    14  
    15  // GetShare fetches and returns the data for leaf `leafIndex` of root `rootCid`.
    16  func GetShare(
    17  	ctx context.Context,
    18  	bGetter blockservice.BlockGetter,
    19  	rootCid cid.Cid,
    20  	leafIndex int,
    21  	totalLeafs int, // this corresponds to the extended square width
    22  ) (share.Share, error) {
    23  	nd, err := GetLeaf(ctx, bGetter, rootCid, leafIndex, totalLeafs)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	return leafToShare(nd), nil
    29  }
    30  
    31  // GetShares walks the tree of a given root and puts shares into the given 'put' func.
    32  // Does not return any error, and returns/unblocks only on success
    33  // (got all shares) or on context cancellation.
    34  func GetShares(ctx context.Context, bg blockservice.BlockGetter, root cid.Cid, shares int, put func(int, share.Share)) {
    35  	putNode := func(i int, leaf format.Node) {
    36  		put(i, leafToShare(leaf))
    37  	}
    38  	GetLeaves(ctx, bg, root, shares, putNode)
    39  }
    40  
    41  // GetSharesByNamespace walks the tree of a given root and returns its shares within the given
    42  // Namespace. If a share could not be retrieved, err is not nil, and the returned array
    43  // contains nil shares in place of the shares it was unable to retrieve.
    44  func GetSharesByNamespace(
    45  	ctx context.Context,
    46  	bGetter blockservice.BlockGetter,
    47  	root cid.Cid,
    48  	namespace share.Namespace,
    49  	maxShares int,
    50  ) ([]share.Share, *nmt.Proof, error) {
    51  	data := NewNamespaceData(maxShares, namespace, WithLeaves(), WithProofs())
    52  	err := data.CollectLeavesByNamespace(ctx, bGetter, root)
    53  	if err != nil {
    54  		return nil, nil, err
    55  	}
    56  
    57  	leaves := data.Leaves()
    58  
    59  	shares := make([]share.Share, len(leaves))
    60  	for i, leaf := range leaves {
    61  		if leaf != nil {
    62  			shares[i] = leafToShare(leaf)
    63  		}
    64  	}
    65  	return shares, data.Proof(), err
    66  }
    67  
    68  // leafToShare converts an NMT leaf into a Share.
    69  func leafToShare(nd format.Node) share.Share {
    70  	// * Additional namespace is prepended so that parity data can be identified with a parity
    71  	// namespace, which we cut off
    72  	return share.GetData(nd.RawData())
    73  }