@@ -137,25 +137,39 @@ var CodecToStr = map[uint64]string{
137
137
DashTx : "dash-tx" ,
138
138
}
139
139
140
+ // tryNewCidV0 tries to convert a multihash into a CIDv0 CID and returns an
141
+ // error on failure.
142
+ func tryNewCidV0 (mhash mh.Multihash ) (Cid , error ) {
143
+ // Need to make sure hash is valid for CidV0 otherwise we will
144
+ // incorrectly detect it as CidV1 in the Version() method
145
+ dec , err := mh .Decode (mhash )
146
+ if err != nil {
147
+ return Undef , err
148
+ }
149
+ if dec .Code != mh .SHA2_256 || dec .Length != 32 {
150
+ return Undef , fmt .Errorf ("invalid hash for cidv0 %d-%d" , dec .Code , dec .Length )
151
+ }
152
+ return Cid {string (mhash )}, nil
153
+ }
154
+
140
155
// NewCidV0 returns a Cid-wrapped multihash.
141
156
// They exist to allow IPFS to work with Cids while keeping
142
157
// compatibility with the plain-multihash format used used in IPFS.
143
158
// NewCidV1 should be used preferentially.
159
+ //
160
+ // Panics if the multihash isn't sha2-256.
144
161
func NewCidV0 (mhash mh.Multihash ) Cid {
145
- // Need to make sure hash is valid for CidV0 otherwise we will
146
- // incorrectly detect it as CidV1 in the Version() method
147
- dec , err := mh .Decode (mhash )
162
+ c , err := tryNewCidV0 (mhash )
148
163
if err != nil {
149
164
panic (err )
150
165
}
151
- if dec .Code != mh .SHA2_256 || dec .Length != 32 {
152
- panic ("invalid hash for cidv0" )
153
- }
154
- return Cid {string (mhash )}
166
+ return c
155
167
}
156
168
157
169
// NewCidV1 returns a new Cid using the given multicodec-packed
158
170
// content type.
171
+ //
172
+ // Panics if the multihash is invalid.
159
173
func NewCidV1 (codecType uint64 , mhash mh.Multihash ) Cid {
160
174
hashlen := len (mhash )
161
175
// two 8 bytes (max) numbers plus hash
@@ -203,7 +217,7 @@ func Parse(v interface{}) (Cid, error) {
203
217
case []byte :
204
218
return Cast (v2 )
205
219
case mh.Multihash :
206
- return NewCidV0 (v2 ), nil
220
+ return tryNewCidV0 (v2 )
207
221
case Cid :
208
222
return v2 , nil
209
223
default :
@@ -234,7 +248,7 @@ func Decode(v string) (Cid, error) {
234
248
return Undef , err
235
249
}
236
250
237
- return NewCidV0 (hash ), nil
251
+ return tryNewCidV0 (hash )
238
252
}
239
253
240
254
_ , data , err := mbase .Decode (v )
@@ -589,7 +603,7 @@ func PrefixFromBytes(buf []byte) (Prefix, error) {
589
603
}
590
604
591
605
func CidFromBytes (data []byte ) (int , Cid , error ) {
592
- if len (data ) > 2 && data [0 ] == 18 && data [1 ] == 32 {
606
+ if len (data ) > 2 && data [0 ] == mh . SHA2_256 && data [1 ] == 32 {
593
607
if len (data ) < 34 {
594
608
return 0 , Undef , fmt .Errorf ("not enough bytes for cid v0" )
595
609
}
@@ -599,7 +613,7 @@ func CidFromBytes(data []byte) (int, Cid, error) {
599
613
return 0 , Undef , err
600
614
}
601
615
602
- return 34 , NewCidV0 (h ), nil
616
+ return 34 , Cid { string (h )} , nil
603
617
}
604
618
605
619
vers , n := binary .Uvarint (data )
0 commit comments