| 1 | package keyencode |
| 2 | |
| 3 | import ( |
| 4 | cmds "github.com/ipfs/go-ipfs-cmds" |
| 5 | peer "github.com/libp2p/go-libp2p/core/peer" |
| 6 | mbase "github.com/multiformats/go-multibase" |
| 7 | ) |
| 8 | |
| 9 | const ipnsKeyFormatOptionName = "ipns-base" |
| 10 | |
| 11 | var OptionIPNSBase = cmds.StringOption(ipnsKeyFormatOptionName, "Encoding used for keys: Can either be a multibase encoded CID or a base58btc encoded multihash. Takes {b58mh|base36|k|base32|b...}.").WithDefault("base36") |
| 12 | |
| 13 | type KeyEncoder struct { |
| 14 | baseEnc *mbase.Encoder |
| 15 | } |
| 16 | |
| 17 | func KeyEncoderFromString(formatLabel string) (KeyEncoder, error) { |
| 18 | switch formatLabel { |
| 19 | case "b58mh", "v0": |
| 20 | return KeyEncoder{}, nil |
| 21 | default: |
| 22 | if enc, err := mbase.EncoderByName(formatLabel); err != nil { |
| 23 | return KeyEncoder{}, err |
| 24 | } else { |
| 25 | return KeyEncoder{&enc}, nil |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func (enc KeyEncoder) FormatID(id peer.ID) string { |
| 31 | if enc.baseEnc == nil { |
| 32 | return id.String() |
| 33 | } |
| 34 | if s, err := peer.ToCid(id).StringOfBase(enc.baseEnc.Encoding()); err != nil { |
| 35 | panic(err) |
| 36 | } else { |
| 37 | return s |
| 38 | } |
| 39 | } |