Debian Codegraph @

_rsrch/cidiface/cidString.go

raw
1 package cid
2
3 import (
4 "encoding/binary"
5 "fmt"
6
7 mbase "github.com/multiformats/go-multibase"
8 mh "github.com/multiformats/go-multihash"
9 )
10
11 //=================
12 // def & accessors
13 //=================
14
15 var _ Cid = CidStr("")
16 var _ map[CidStr]struct{} = nil
17
18 // CidStr is a representation of a Cid as a string type containing binary.
19 //
20 // Using golang's string type is preferable over byte slices even for binary
21 // data because golang strings are immutable, usable as map keys,
22 // trivially comparable with built-in equals operators, etc.
23 //
24 // Please do not cast strings or bytes into the CidStr type directly;
25 // use a parse method which validates the data and yields a CidStr.
26 type CidStr string
27
28 // EmptyCidStr is a constant for a zero/uninitialized/sentinelvalue cid;
29 // it is declared mainly for readability in checks for sentinel values.
30 const EmptyCidStr = CidStr("")
31
32 func (c CidStr) Version() uint64 {
33 bytes := []byte(c)
34 v, _ := binary.Uvarint(bytes)
35 return v
36 }
37
38 func (c CidStr) Multicodec() uint64 {
39 bytes := []byte(c)
40 _, n := binary.Uvarint(bytes) // skip version length
41 codec, _ := binary.Uvarint(bytes[n:])
42 return codec
43 }
44
45 func (c CidStr) Multihash() mh.Multihash {
46 bytes := []byte(c)
47 _, n1 := binary.Uvarint(bytes) // skip version length
48 _, n2 := binary.Uvarint(bytes[n1:]) // skip codec length
49 return mh.Multihash(bytes[n1+n2:]) // return slice of remainder
50 }
51
52 // String returns the default string representation of a Cid.
53 // Currently, Base58 is used as the encoding for the multibase string.
54 func (c CidStr) String() string {
55 switch c.Version() {
56 case 0:
57 return c.Multihash().B58String()
58 case 1:
59 mbstr, err := mbase.Encode(mbase.Base58BTC, []byte(c))
60 if err != nil {
61 panic("should not error with hardcoded mbase: " + err.Error())
62 }
63 return mbstr
64 default:
65 panic("not possible to reach this point")
66 }
67 }
68
69 // Bytes produces a raw binary format of the CID.
70 //
71 // (For CidStr, this method is only distinct from casting because of
72 // compatibility with v0 CIDs.)
73 func (c CidStr) Bytes() []byte {
74 switch c.Version() {
75 case 0:
76 return c.Multihash()
77 case 1:
78 return []byte(c)
79 default:
80 panic("not possible to reach this point")
81 }
82 }
83
84 // Prefix builds and returns a Prefix out of a Cid.
85 func (c CidStr) Prefix() Prefix {
86 dec, _ := mh.Decode(c.Multihash()) // assuming we got a valid multiaddr, this will not error
87 return Prefix{
88 MhType: dec.Code,
89 MhLength: dec.Length,
90 Version: c.Version(),
91 Codec: c.Multicodec(),
92 }
93 }
94
95 //==================================
96 // parsers & validators & factories
97 //==================================
98
99 func NewCidStr(version uint64, codecType uint64, mhash mh.Multihash) CidStr {
100 hashlen := len(mhash)
101 // two 8 bytes (max) numbers plus hash
102 buf := make([]byte, 2*binary.MaxVarintLen64+hashlen)
103 n := binary.PutUvarint(buf, version)
104 n += binary.PutUvarint(buf[n:], codecType)
105 cn := copy(buf[n:], mhash)
106 if cn != hashlen {
107 panic("copy hash length is inconsistent")
108 }
109 return CidStr(buf[:n+hashlen])
110 }
111
112 // CidStrParse takes a binary byte slice, parses it, and returns either
113 // a valid CidStr, or the zero CidStr and an error.
114 //
115 // For CidV1, the data buffer is in the form:
116 //
117 // <version><codec-type><multihash>
118 //
119 // CidV0 are also supported. In particular, data buffers starting
120 // with length 34 bytes, which starts with bytes [18,32...] are considered
121 // binary multihashes.
122 //
123 // The multicodec bytes are not parsed to verify they're a valid varint;
124 // no further reification is performed.
125 //
126 // Multibase encoding should already have been unwrapped before parsing;
127 // if you have a multibase-enveloped string, use CidStrDecode instead.
128 //
129 // CidStrParse is the inverse of Cid.Bytes().
130 func CidStrParse(data []byte) (CidStr, error) {
131 if len(data) == 34 && data[0] == 18 && data[1] == 32 {
132 h, err := mh.Cast(data)
133 if err != nil {
134 return EmptyCidStr, err
135 }
136 return NewCidStr(0, DagProtobuf, h), nil
137 }
138
139 vers, n := binary.Uvarint(data)
140 if err := uvError(n); err != nil {
141 return EmptyCidStr, err
142 }
143
144 if vers != 0 && vers != 1 {
145 return EmptyCidStr, fmt.Errorf("invalid cid version number: %d", vers)
146 }
147
148 _, cn := binary.Uvarint(data[n:])
149 if err := uvError(cn); err != nil {
150 return EmptyCidStr, err
151 }
152
153 rest := data[n+cn:]
154 h, err := mh.Cast(rest)
155 if err != nil {
156 return EmptyCidStr, err
157 }
158
159 // REVIEW: if the data is longer than the mh.len expects, we silently ignore it? should we?
160 return CidStr(data[0 : n+cn+len(h)]), nil
161 }