-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCidV1.cs
More file actions
261 lines (207 loc) · 7.14 KB
/
Copy pathCidV1.cs
File metadata and controls
261 lines (207 loc) · 7.14 KB
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
254
255
256
257
258
259
260
261
using System.Security.Cryptography;
namespace dnproto.repo;
/// <summary>
/// Represents a cid in atproto. Only cid version 1 is supported.
///
/// Two types of cids are used:
/// dag-cbor (for records)
/// raw (for blobs)
///
/// https://github.com/multiformats/cid
/// https://github.com/multiformats/multicodec/blob/master/table.csv
/// </summary>
public class CidV1
{
// first byte
public required VarInt Version { get; set; }
// second byte
public required VarInt Multicodec { get; set; }
// third byte
public required VarInt HashFunction { get; set; }
// fourth byte
public required VarInt DigestSize { get; set; }
// next (and final) 32 bytes
public required byte[] DigestBytes { get; set; }
// entire array of bytes (including version, multicodec, hash function, digest size, and digest bytes)
public required byte[] AllBytes { get; set; }
// base32 representation of the CID
public required string Base32 { get; set; }
#region READ
/// <summary>
/// Reads a CidV1 from a stream (for example, an atproto repo stream).
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static CidV1 ReadCid(Stream s)
{
// https://github.com/multiformats/cid
VarInt version = VarInt.ReadVarInt(s);
VarInt multicodec = VarInt.ReadVarInt(s);
VarInt hashFunction = VarInt.ReadVarInt(s); // likely sha2-256, 0x12, decimal 18
VarInt digestSize = VarInt.ReadVarInt(s);
if (version.Value != 1)
{
throw new Exception($"The first byte should be 1. This class supports only CidV1. First byte found: {version.Value}");
}
// https://github.com/multiformats/multicodec/blob/master/table.csv
// dag-cbor = 0x71
// raw = 0x55
// should not happen for AT
if(multicodec.Value != 0x71 && multicodec.Value != 0x55)
{
throw new Exception($"cidMulticodec.Value != 0x71 or 0x55: {multicodec.Value}");
}
byte[] digestBytes = new byte[digestSize.Value];
int cidDigestBytesRead = s.Read(digestBytes, 0, (int)digestSize.Value);
var ms = new MemoryStream();
ms.WriteByte((byte)version.Value);
ms.WriteByte((byte)multicodec.Value);
ms.WriteByte((byte)hashFunction.Value);
ms.WriteByte((byte)digestSize.Value);
ms.Write(digestBytes, 0, (int)digestSize.Value);
byte[] allBytes = ms.ToArray();
string base32 = "b" + Base32Encoding.BytesToBase32(allBytes);
return new CidV1
{
Version = version,
Multicodec = multicodec,
HashFunction = hashFunction,
DigestSize = digestSize,
DigestBytes = digestBytes,
AllBytes = allBytes,
Base32 = base32
};
}
/// <summary>
/// Reads a CidV1 from a base32 string.
/// </summary>
/// <param name="base32"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static CidV1 FromBase32(string base32)
{
if (!base32.StartsWith("b"))
{
throw new Exception("CID base32 string must start with 'b'");
}
byte[] originalBytes = Base32Encoding.Base32ToBytes(base32.Substring(1));
using var ms = new MemoryStream(originalBytes);
var cid = ReadCid(ms);
// Use the original bytes instead of reconstructed ones to preserve exact encoding
cid.AllBytes = originalBytes;
cid.Base32 = base32;
return cid;
}
#endregion
#region WRITE
/// <summary>
/// Writes a CidV1 to a stream.
/// </summary>
/// <param name="s"></param>
/// <param name="cid"></param>
public static void WriteCid(Stream s, CidV1 cid)
{
VarInt.WriteVarInt(s, cid.Version);
VarInt.WriteVarInt(s, cid.Multicodec);
VarInt.WriteVarInt(s, cid.HashFunction);
VarInt.WriteVarInt(s, cid.DigestSize);
s.Write(cid.DigestBytes, 0, cid.DigestBytes.Length);
}
/// <summary>
/// Writes a CidV1 to a stream.
/// </summary>
/// <param name="s"></param>
/// <param name="cid"></param>
/// <returns></returns>
public static async Task WriteCidAsync(Stream s, CidV1 cid)
{
await VarInt.WriteVarIntAsync(s, cid.Version);
await VarInt.WriteVarIntAsync(s, cid.Multicodec);
await VarInt.WriteVarIntAsync(s, cid.HashFunction);
await VarInt.WriteVarIntAsync(s, cid.DigestSize);
await s.WriteAsync(cid.DigestBytes, 0, cid.DigestBytes.Length);
}
#endregion
#region COMPUTE
/// <summary>
/// Computes a CIDv1 for a dag-cbor object.
/// </summary>
/// <param name="dagCborObject"></param>
/// <returns></returns>
public static CidV1 ComputeCidForDagCbor(DagCborObject dagCborObject)
{
var bytes = dagCborObject.ToBytes();
var hash = SHA256.HashData(bytes);
// Create CIDv1 with dag-cbor multicodec (0x71) and sha256 (0x12)
var cid = new CidV1
{
Version = new VarInt { Value = 1 },
Multicodec = new VarInt { Value = 0x71 },
HashFunction = new VarInt { Value = 0x12 },
DigestSize = new VarInt { Value = 32 },
DigestBytes = hash,
AllBytes = Array.Empty<byte>(), // Will be set below
Base32 = ""
};
using var ms = new MemoryStream();
CidV1.WriteCid(ms, cid);
cid.AllBytes = ms.ToArray();
cid.Base32 = "b" + Base32Encoding.BytesToBase32(cid.AllBytes);
return cid;
}
/// <summary>
/// Computes a CIDv1 for blob bytes.
/// </summary>
/// <param name="blobBytes"></param>
/// <returns></returns>
public static CidV1 ComputeCidForBlobBytes(byte[] blobBytes)
{
//
// Compute SHA-256 hash
//
var hash = SHA256.HashData(blobBytes);
//
// Create CID for blob (using "raw" codec 0x55)
//
var cid = new CidV1
{
Version = new VarInt { Value = 1 },
Multicodec = new VarInt { Value = 0x55 }, // raw codec for blobs
HashFunction = new VarInt { Value = 0x12 }, // SHA-256
DigestSize = new VarInt { Value = 32 },
DigestBytes = hash,
AllBytes = Array.Empty<byte>(),
Base32 = ""
};
//
// Encode CID as bytes and base32
//
using var ms = new MemoryStream();
CidV1.WriteCid(ms, cid);
cid.AllBytes = ms.ToArray();
cid.Base32 = "b" + Base32Encoding.BytesToBase32(cid.AllBytes);
return cid;
}
#endregion
public string GetBase32()
{
return Base32;
}
public override string ToString()
{
return Base32;
}
public override bool Equals(object? obj)
{
if (obj is CidV1 otherCid)
{
return string.Equals(this.Base32, otherCid.Base32, StringComparison.Ordinal);
}
return false;
}
public override int GetHashCode()
{
return Base32.GetHashCode();
}
}