diff --git a/core/commands/block.go b/core/commands/block.go index c1b20a1bebf..282b40a7357 100644 --- a/core/commands/block.go +++ b/core/commands/block.go @@ -16,6 +16,8 @@ import ( blocks "gx/ipfs/QmYsEQydGrsxNZfAiskvQ76N2xE9hDQtSAkRSynwMiUK3c/go-block-format" "gx/ipfs/QmceUdzxkimdYsgtX733uNgzf1DLHyBKN6ehGSp85ayppM/go-ipfs-cmdkit" cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid" + + "github.com/pkg/errors" ) type BlockStat struct { @@ -157,27 +159,32 @@ It reads from stdin, and is a base58 encoded multihash. return } + mhtype, _ := req.Options["mhtype"].(string) + mhtval, ok := mh.Names[mhtype] + if !ok { + err := fmt.Errorf("unrecognized multihash function: %s", mhtype) + res.SetError(err, cmdkit.ErrNormal) + return + } + var pref cid.Prefix pref.Version = 1 - format, _ := req.Options["format"].(string) + format, userFormat := req.Options["format"].(string) formatval, ok := cid.Codecs[format] if !ok { res.SetError(fmt.Errorf("unrecognized format: %s", format), cmdkit.ErrNormal) return } - if format == "v0" { + if format == "v0" && (mhtval == mh.SHA2_256 || userFormat) { pref.Version = 0 } - pref.Codec = formatval - - mhtype, _ := req.Options["mhtype"].(string) - mhtval, ok := mh.Names[mhtype] - if !ok { - err := fmt.Errorf("unrecognized multihash function: %s", mhtype) - res.SetError(err, cmdkit.ErrNormal) + if mhtval != mh.SHA2_256 && pref.Version == 0 { + res.SetError(errors.New("cannot generate CIDv0 with non-sha256 hash function"), cmdkit.ErrNormal) return } + + pref.Codec = formatval pref.MhType = mhtval mhlen, ok := req.Options["mhlen"].(int) diff --git a/test/sharness/t0050-block.sh b/test/sharness/t0050-block.sh index 285d8ad94b5..0cdd2498ba4 100755 --- a/test/sharness/t0050-block.sh +++ b/test/sharness/t0050-block.sh @@ -209,4 +209,16 @@ test_expect_success "no panic in output" ' test_expect_code 1 grep "panic" stat_out ' +test_expect_success "can set multihash type and length on block put without format" ' + HASH=$(echo "foooo" | ipfs block put --mhtype=sha3 --mhlen=16) +' + +test_expect_success "output looks good" ' + test "z2APJNN6rqZTWPpv7gYFHzh7ZEDX" = "$HASH" +' + +test_expect_success "put with sha3 and cidv0 fails" ' + echo "foooo" | test_must_fail ipfs block put --mhtype=sha3 --mhlen=16 --format=v0 +' + test_done