From f62e35b87aa7e220f97136207d7d5e4ccd27678d Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Mon, 14 Aug 2017 01:27:38 -0400 Subject: [PATCH] Implement basic 'cid-fmt' utility. Currently only implements printing the Cid prefix. --- cid-fmt/main.go | 69 +++++++++++++++++++++++++++++++++++++++++++++++++ cid.go | 21 +++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 cid-fmt/main.go diff --git a/cid-fmt/main.go b/cid-fmt/main.go new file mode 100644 index 0000000..814e96d --- /dev/null +++ b/cid-fmt/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "fmt" + "os" + + c "github.com/ipfs/go-cid" + + mh "github.com/multiformats/go-multihash" +) + +func main() { + if len(os.Args) < 2 { + fmt.Fprintf(os.Stderr, "usage: %s prefix ...\n", os.Args[0]) + os.Exit(1) + } + switch os.Args[1] { + case "prefix": + err := prefixCmd(os.Args[2:]) + if err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + default: + fmt.Fprintf(os.Stderr, "usage: %s prefix ...\n") + os.Exit(1) + } +} + +func prefixCmd(args []string) error { + for _, cid := range args { + p, err := prefix(cid) + if err != nil { + return err + } + fmt.Fprintf(os.Stdout, "%s\n", p) + } + return nil +} + +func prefix(str string) (string, error) { + cid, err := c.Decode(str) + if err != nil { + return "", err + } + p := cid.Prefix() + return fmt.Sprintf("cidv%d-%s-%s-%d", + p.Version, + codecToStr(p.Codec), + mhToStr(p.MhType), + p.MhLength, + ), nil +} + +func codecToStr(num uint64) string { + name, ok := c.CodecToStr[num] + if !ok { + return fmt.Sprintf("c?%d", num) + } + return name +} + +func mhToStr(num uint64) string { + name, ok := mh.Codes[num] + if !ok { + return fmt.Sprintf("h?%d", num) + } + return name +} diff --git a/cid.go b/cid.go index eb426ed..72fa326 100644 --- a/cid.go +++ b/cid.go @@ -101,6 +101,27 @@ var Codecs = map[string]uint64{ "zcash-tx": ZcashTx, } +// CodecToStr maps the numeric codec to its name +var CodecToStr = map[uint64]string{ + Raw: "raw", + DagProtobuf: "protobuf", + DagCBOR: "cbor", + GitRaw: "git-raw", + EthBlock: "eth-block", + EthBlockList: "eth-block-list", + EthTxTrie: "eth-tx-trie", + EthTx: "eth-tx", + EthTxReceiptTrie: "eth-tx-receipt-trie", + EthTxReceipt: "eth-tx-receipt", + EthStateTrie: "eth-state-trie", + EthAccountSnapshot: "eth-account-snapshot", + EthStorageTrie: "eth-storage-trie", + BitcoinBlock: "bitcoin-block", + BitcoinTx: "bitcoin-tx", + ZcashBlock: "zcash-block", + ZcashTx: "zcash-tx", +} + // NewCidV0 returns a Cid-wrapped multihash. // They exist to allow IPFS to work with Cids while keeping // compatibility with the plain-multihash format used used in IPFS.