lotus/cmd/lotus-shed/cid.go

83 lines
1.8 KiB
Go
Raw Normal View History

2020-11-04 15:20:57 +00:00
package main
import (
"encoding/base64"
"encoding/hex"
"fmt"
2020-12-01 09:16:41 +00:00
"github.com/filecoin-project/go-state-types/abi"
2020-11-04 15:20:57 +00:00
"github.com/ipfs/go-cid"
mh "github.com/multiformats/go-multihash"
2020-12-01 08:50:53 +00:00
"github.com/urfave/cli/v2"
"golang.org/x/xerrors"
2020-11-04 15:20:57 +00:00
)
var cidCmd = &cli.Command{
2020-12-01 08:50:53 +00:00
Name: "cid",
Usage: "Cid command",
2020-11-04 15:20:57 +00:00
Subcommands: cli.Commands{
cidIdCmd,
},
}
var cidIdCmd = &cli.Command{
2020-12-01 08:50:53 +00:00
Name: "id",
Usage: "Create identity CID from hex or base64 data",
ArgsUsage: "[data]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "encoding",
Value: "base64",
Usage: "specify input encoding to parse",
},
2020-12-01 14:53:24 +00:00
&cli.StringFlag{
Name: "codec",
Value: "id",
Usage: "multicodec-packed content types: abi or id",
2020-12-01 14:53:24 +00:00
},
2020-12-01 08:50:53 +00:00
},
2020-11-04 15:20:57 +00:00
Action: func(cctx *cli.Context) error {
if !cctx.Args().Present() {
return fmt.Errorf("must specify data")
}
2020-12-01 08:50:53 +00:00
var dec []byte
switch cctx.String("encoding") {
case "base64":
data, err := base64.StdEncoding.DecodeString(cctx.Args().First())
2020-11-04 15:20:57 +00:00
if err != nil {
2020-12-01 08:50:53 +00:00
return xerrors.Errorf("decoding base64 value: %w", err)
2020-11-04 15:20:57 +00:00
}
2020-12-01 08:50:53 +00:00
dec = data
case "hex":
data, err := hex.DecodeString(cctx.Args().First())
if err != nil {
return xerrors.Errorf("decoding hex value: %w", err)
}
dec = data
default:
return xerrors.Errorf("unrecognized encoding: %s", cctx.String("encoding"))
2020-11-04 15:20:57 +00:00
}
2020-12-01 14:53:24 +00:00
switch cctx.String("codec") {
case "abi":
aCid, err := abi.CidBuilder.Sum(dec)
if err != nil {
return xerrors.Errorf("cidBuilder abi: %w", err)
}
fmt.Println(aCid)
case "id":
2020-12-01 14:53:24 +00:00
builder := cid.V1Builder{Codec: cid.Raw, MhType: mh.IDENTITY}
rCid, err := builder.Sum(dec)
if err != nil {
return xerrors.Errorf("cidBuilder raw: %w", err)
}
fmt.Println(rCid)
default:
return xerrors.Errorf("unrecognized codec: %s", cctx.String("codec"))
2020-11-04 15:20:57 +00:00
}
return nil
},
}