Skip to content

Commit

Permalink
feat: check that the CidBuilder hasher is usable
Browse files Browse the repository at this point in the history
Ref: ipfs/go-merkledag#90


This commit was moved from ipfs/go-merkledag@bb220e8
  • Loading branch information
rvagg committed Sep 30, 2022
1 parent c71dcd8 commit 6866c15
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
35 changes: 35 additions & 0 deletions ipld/merkledag/merkledag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
u "github.com/ipfs/go-ipfs-util"
ipld "github.com/ipfs/go-ipld-format"
prime "github.com/ipld/go-ipld-prime"
mh "github.com/multiformats/go-multihash"
)

// makeDepthTestingGraph makes a small DAG with two levels. The level-two
Expand Down Expand Up @@ -73,6 +74,40 @@ func traverseAndCheck(t *testing.T, root ipld.Node, ds ipld.DAGService, hasF fun
}
}

func TestBadBuilderEncode(t *testing.T) {
n := NodeWithData([]byte("boop"))
_, err := n.EncodeProtobuf(false)
if err != nil {
t.Fatal(err)
}
err = n.SetCidBuilder(
&cid.Prefix{
MhType: mh.SHA2_256,
MhLength: -1,
Version: 1,
Codec: cid.DagProtobuf,
},
)
if err != nil {
t.Fatal(err)
}
err = n.SetCidBuilder(
&cid.Prefix{
MhType: mh.SHA2_256_TRUNC254_PADDED,
MhLength: 256,
Version: 1,
Codec: cid.DagProtobuf,
},
)
if err == nil {
t.Fatal("expected SetCidBuilder to error on unusable hasher")
}
_, err = n.EncodeProtobuf(false)
if err != nil {
t.Fatalf("expected EncodeProtobuf to use safe CidBuilder: %v", err)
}
}

func TestNode(t *testing.T) {

n1 := NodeWithData([]byte("beep"))
Expand Down
23 changes: 18 additions & 5 deletions ipld/merkledag/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
dagpb "github.com/ipld/go-codec-dagpb"
ipld "github.com/ipld/go-ipld-prime"
mh "github.com/multiformats/go-multihash"
mhcore "github.com/multiformats/go-multihash/core"
)

// Common errors
Expand Down Expand Up @@ -96,14 +97,26 @@ func (n *ProtoNode) CidBuilder() cid.Builder {
}

// SetCidBuilder sets the CID builder if it is non nil, if nil then it
// is reset to the default value
func (n *ProtoNode) SetCidBuilder(builder cid.Builder) {
// is reset to the default value. An error will be returned if the builder
// is not usable.
func (n *ProtoNode) SetCidBuilder(builder cid.Builder) error {
if builder == nil {
n.builder = v0CidPrefix
} else {
n.builder = builder.WithCodec(cid.DagProtobuf)
n.cached = cid.Undef
return nil
}
if p, ok := builder.(*cid.Prefix); ok {
mhLen := p.MhLength
if mhLen <= 0 {
mhLen = -1
}
_, err := mhcore.GetVariableHasher(p.MhType, mhLen)
if err != nil {
return err
}
}
n.builder = builder.WithCodec(cid.DagProtobuf)
n.cached = cid.Undef
return nil
}

// LinkSlice is a slice of format.Links
Expand Down

0 comments on commit 6866c15

Please sign in to comment.