1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
mod codec;
mod error;
mod to_cid;
mod version;
pub use self::codec::Codec;
pub use self::error::Error;
pub use self::version::Version;
use integer_encoding::{VarIntReader, VarIntWriter};
pub use multihash;
use multihash::{Code, Identity, Multihash, MultihashDigest};
use std::convert::TryInto;
use std::fmt;
use std::io::Cursor;
#[cfg(feature = "cbor")]
use serde::{de, ser};
#[cfg(feature = "cbor")]
use serde_cbor::tags::Tagged;
#[cfg(feature = "cbor")]
use std::convert::TryFrom;
#[cfg(feature = "cbor")]
const CBOR_TAG_CID: u64 = 42;
#[cfg(feature = "cbor")]
const MULTIBASE_IDENTITY: u8 = 0;
#[cfg(feature = "json")]
pub mod json;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Prefix {
pub version: Version,
pub codec: Codec,
pub mh_type: Code,
}
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct Cid {
pub version: Version,
pub codec: Codec,
pub hash: Multihash,
}
impl Default for Cid {
fn default() -> Self {
Self::new(Codec::Raw, Version::V1, Identity.digest(&[]))
}
}
#[cfg(feature = "cbor")]
impl ser::Serialize for Cid {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
if self == &Cid::default() {
return Err(ser::Error::custom("Cannot serialize a default Cid"));
}
let mut cid_bytes = self.to_bytes();
cid_bytes.insert(0, MULTIBASE_IDENTITY);
let value = serde_bytes::Bytes::new(&cid_bytes);
Tagged::new(Some(CBOR_TAG_CID), &value).serialize(s)
}
}
#[cfg(feature = "cbor")]
impl<'de> de::Deserialize<'de> for Cid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let tagged = Tagged::<serde_bytes::ByteBuf>::deserialize(deserializer)?;
match tagged.tag {
Some(CBOR_TAG_CID) | None => {
let mut bz = tagged.value.into_vec();
if bz.first() == Some(&MULTIBASE_IDENTITY) {
bz.remove(0);
}
Ok(Cid::try_from(bz).map_err(|e| de::Error::custom(e.to_string()))?)
}
Some(_) => Err(de::Error::custom("unexpected tag")),
}
}
}
impl Cid {
pub fn new(codec: Codec, version: Version, hash: Multihash) -> Cid {
Cid {
version,
codec,
hash,
}
}
pub fn new_v1(codec: Codec, hash: Multihash) -> Cid {
Cid::new(codec, Version::V1, hash)
}
pub fn new_v0(codec: Codec, hash: Multihash) -> Cid {
Cid::new(codec, Version::V0, hash)
}
pub fn new_from_cbor<T: MultihashDigest>(bz: &[u8], hash: T) -> Self {
let hash = hash.digest(bz);
Cid {
version: Version::V1,
codec: Codec::DagCBOR,
hash,
}
}
pub fn from_raw_cid<T: TryInto<Cid>>(data: T) -> Result<Cid, T::Error> {
data.try_into()
}
pub fn new_from_prefix(prefix: &Prefix, data: &[u8]) -> Result<Cid, Error> {
let hash = prefix
.mh_type
.hasher()
.ok_or_else(|| Error::Other("Prefix must use builtin hasher".to_owned()))?
.digest(data);
Ok(Cid {
version: prefix.version,
codec: prefix.codec.to_owned(),
hash,
})
}
fn to_string_v0(&self) -> String {
use multibase::{encode, Base};
let mut string = encode(Base::Base58Btc, self.hash.clone());
string.remove(0);
string
}
fn to_string_v1(&self) -> String {
use multibase::{encode, Base};
encode(Base::Base32Lower, self.to_bytes().as_slice())
}
fn to_bytes_v0(&self) -> Vec<u8> {
self.hash.clone().into_bytes()
}
fn to_bytes_v1(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(16);
res.write_varint(u64::from(self.version)).unwrap();
res.write_varint(u64::from(self.codec)).unwrap();
res.extend_from_slice(self.hash.as_bytes());
res
}
pub fn to_bytes(&self) -> Vec<u8> {
match self.version {
Version::V0 => self.to_bytes_v0(),
Version::V1 => self.to_bytes_v1(),
}
}
pub fn prefix(&self) -> Prefix {
Prefix {
version: self.version,
codec: self.codec.to_owned(),
mh_type: self.hash.algorithm(),
}
}
pub fn key(&self) -> Vec<u8> {
self.to_bytes()
}
}
impl fmt::Display for Cid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let encoded = match self.version {
Version::V0 => self.to_string_v0(),
Version::V1 => self.to_string_v1(),
};
write!(f, "{}", encoded)
}
}
impl fmt::Debug for Cid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Cid(\"{}\")", self)
}
}
impl Prefix {
pub fn new_from_bytes(data: &[u8]) -> Result<Prefix, Error> {
let mut cur = Cursor::new(data);
let raw_version = cur.read_varint()?;
let raw_codec = cur.read_varint()?;
let raw_mh_type: u64 = cur.read_varint()?;
let version = Version::from(raw_version)?;
let codec = Codec::from(raw_codec)?;
let mh_type = Code::from_u64(raw_mh_type as u64);
Ok(Prefix {
version,
codec,
mh_type,
})
}
pub fn as_bytes(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(4);
res.write_varint(u64::from(self.version)).unwrap();
res.write_varint(u64::from(self.codec)).unwrap();
res.write_varint(self.mh_type.to_u64()).unwrap();
res
}
}