-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathCid.cs
658 lines (617 loc) · 20.9 KB
/
Cid.cs
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
using Google.Protobuf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
namespace Ipfs
{
/// <summary>
/// Identifies some content, e.g. a Content ID.
/// </summary>
/// <remarks>
/// <para>
/// A Cid is a self-describing content-addressed identifier for distributed systems.
/// </para>
/// <para>
/// Initially, IPFS used a <see cref="MultiHash"/> as the CID and this is still supported as <see cref="Version"/> 0.
/// Version 1 adds a self describing structure to the multi-hash, see the <see href="https://github.com/ipld/cid">spec</see>.
/// </para>
/// <note>
/// The <see cref="MultiHash.Algorithm">hashing algorithm</see> must be "sha2-256" for a version 0 CID.
/// </note>
/// </remarks>
/// <seealso href="https://github.com/ipld/cid"/>
[JsonConverter(typeof(Cid.CidJsonConverter))]
public class Cid : IEquatable<Cid>
{
/// <summary>
/// The default <see cref="ContentType"/>.
/// </summary>
public const string DefaultContentType = "dag-pb";
string encodedValue;
int version;
string encoding = MultiBase.DefaultAlgorithmName;
string contentType = DefaultContentType;
MultiHash hash;
/// <summary>
/// Throws if a property cannot be set.
/// </summary>
/// <exception cref="NotSupportedException">
/// When a property cannot be set.
/// </exception>
/// <remarks>
/// Once <see cref="Encode"/> is invoked, the CID's properties
/// cannot be set.
/// </remarks>
void EnsureMutable()
{
if (encodedValue != null)
{
throw new NotSupportedException("CID cannot be changed.");
}
}
/// <summary>
/// The version of the CID.
/// </summary>
/// <value>
/// 0 or 1.
/// </value>
/// <remarks>
/// <para>
/// When the <see cref="Version"/> is 0 and the following properties
/// are not matched, then the version is upgraded to version 1 when any
/// of the properties is set.
/// <list type="bullet">
/// <item><description><see cref="ContentType"/> equals "dag-pb"</description></item>
/// <item><description><see cref="Encoding"/> equals "base58btc"</description></item>
/// <item><description><see cref="Hash"/> algorithm name equals "sha2-256"</description></item>
/// </list>
/// </para>
/// <para>
/// </para>
/// The default <see cref="Encoding"/> is "base32" when the
/// <see cref="Version"/> is not zero.
/// </remarks>
public int Version
{
get
{
return version;
}
set
{
EnsureMutable();
if (version == 0 && value > 0 && Encoding == "base58btc")
{
encoding = "base32";
}
version = value;
}
}
/// <summary>
/// The <see cref="MultiBase"/> encoding of the CID.
/// </summary>
/// <value>
/// base58btc, base32, base64, etc. Defaults to <see cref="MultiBase.DefaultAlgorithmName"/>.
/// </value>
/// <remarks>
/// Sets <see cref="Version"/> to 1, when setting a value that
/// is not equal to "base58btc".
/// </remarks>
/// <seealso cref="MultiBase"/>
public string Encoding
{
get
{
return encoding;
}
set
{
EnsureMutable();
if (Version == 0 && value != "base58btc")
{
Version = 1;
}
encoding = value;
}
}
/// <summary>
/// The content type or format of the data being addressed.
/// </summary>
/// <value>
/// dag-pb, dag-cbor, eth-block, etc. Defaults to "dag-pb".
/// </value>
/// <remarks>
/// Sets <see cref="Version"/> to 1, when setting a value that
/// is not equal to "dag-pb".
/// </remarks>
/// <seealso cref="MultiCodec"/>
public string ContentType
{
get
{
return contentType;
}
set
{
EnsureMutable();
contentType = value;
if (Version == 0 && value != "dag-pb")
{
Version = 1;
}
}
}
/// <summary>
/// The cryptographic hash of the content being addressed.
/// </summary>
/// <value>
/// The <see cref="MultiHash"/> of the content being addressed.
/// </value>
/// <remarks>
/// Sets <see cref="Version"/> to 1, when setting a hashing algorithm that
/// is not equal to "sha2-256".
/// <note>
/// If the <see cref="MultiHash.Algorithm"/> equals <c>identity</c>, then
/// the <see cref="MultiHash.Digest"/> is also the content. This is commonly
/// referred to as 'CID inlining'.
/// </note>
/// </remarks>
public MultiHash Hash
{
get
{
return hash;
}
set
{
EnsureMutable();
hash = value;
if (Version == 0 && Hash.Algorithm.Name != "sha2-256")
{
Version = 1;
}
}
}
/// <summary>
/// Returns the string representation of the CID in the
/// general format.
/// </summary>
/// <returns>
/// e.g. "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V"
/// </returns>
public override string ToString()
{
return ToString("G");
}
/// <summary>
/// Returns a string representation of the CID
/// according to the provided format specifier.
/// </summary>
/// <param name="format">
/// A single format specifier that indicates how to format the value of the
/// CID. Can be "G" or "L".
/// </param>
/// <returns>
/// The CID in the specified <paramref name="format"/>.
/// </returns>
/// <exception cref="FormatException">
/// <paramref name="format"/> is not valid.
/// </exception>
/// <remarks>
/// <para>
/// The "G" format specifier is the same as calling <see cref="Encode"/>.
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Specifier</term>
/// <description>return value</description>
/// </listheader>
/// <item>
/// <term>G</term>
/// <description>QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V</description>
/// </item>
/// <item>
/// <term>L</term>
/// <description>base58btc cidv0 dag-pb sha2-256 Qm...</description>
/// </item>
/// </list>
/// </remarks>
public string ToString(string format)
{
switch (format)
{
case "G":
return Encode();
case "L":
var sb = new StringBuilder();
sb.Append(Encoding);
sb.Append(' ');
sb.Append("cidv");
sb.Append(Version);
sb.Append(' ');
sb.Append(ContentType);
if (Hash != null)
{
sb.Append(' ');
sb.Append(Hash.Algorithm.Name);
sb.Append(' ');
sb.Append(MultiBase.Encode(Hash.ToArray(), Encoding).Substring(1));
}
return sb.ToString();
default:
throw new FormatException($"Invalid CID format specifier '{format}'.");
}
}
/// <summary>
/// Converts the CID to its equivalent string representation.
/// </summary>
/// <returns>
/// The string representation of the <see cref="Cid"/>.
/// </returns>
/// <remarks>
/// For <see cref="Version"/> 0, this is equalivalent to the
/// <see cref="MultiHash.ToBase58()">base58btc encoding</see>
/// of the <see cref="Hash"/>.
/// </remarks>
/// <seealso cref="Decode"/>
public string Encode()
{
if (encodedValue != null)
{
return encodedValue;
}
if (Version == 0)
{
encodedValue = Hash.ToBase58();
}
else
{
using (var ms = new MemoryStream())
{
ms.WriteVarint(Version);
ms.WriteMultiCodec(ContentType);
Hash.Write(ms);
encodedValue = MultiBase.Encode(ms.ToArray(), Encoding);
}
}
return encodedValue;
}
/// <summary>
/// Converts the specified <see cref="string"/>
/// to an equivalent <see cref="Cid"/> object.
/// </summary>
/// <param name="input">
/// The <see cref="Cid.Encode">CID encoded</see> string.
/// </param>
/// <returns>
/// A new <see cref="Cid"/> that is equivalent to <paramref name="input"/>.
/// </returns>
/// <exception cref="FormatException">
/// When the <paramref name="input"/> can not be decoded.
/// </exception>
/// <seealso cref="Encode"/>
public static Cid Decode(string input)
{
try
{
// SHA2-256 MultiHash is CID v0.
if (input.Length == 46 && input.StartsWith("Qm"))
{
return (Cid)new MultiHash(input);
}
using (var ms = new MemoryStream(MultiBase.Decode(input), false))
{
var v = ms.ReadVarint32();
if (v != 1)
{
throw new InvalidDataException($"Unknown CID version '{v}'.");
}
return new Cid
{
Version = v,
Encoding = Registry.MultiBaseAlgorithm.Codes[input[0]].Name,
ContentType = ms.ReadMultiCodec().Name,
Hash = new MultiHash(ms)
};
}
}
catch (Exception e)
{
throw new FormatException($"Invalid CID '{input}'.", e);
}
}
/// <summary>
/// Reads the binary representation of the CID from the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to read from.
/// </param>
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
public static Cid Read(Stream stream)
{
var cid = new Cid();
var length = stream.ReadVarint32();
if (length == 34)
{
cid.Version = 0;
}
else
{
cid.Version = stream.ReadVarint32();
cid.ContentType = stream.ReadMultiCodec().Name;
}
cid.Hash = new MultiHash(stream);
return cid;
}
/// <summary>
/// Writes the binary representation of the CID to the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to write to.
/// </param>
public void Write(Stream stream)
{
using (var ms = new MemoryStream())
{
if (Version != 0)
{
ms.WriteVarint(Version);
ms.WriteMultiCodec(this.ContentType);
}
Hash.Write(ms);
stream.WriteVarint(ms.Length);
ms.Position = 0;
ms.CopyTo(stream);
}
}
/// <summary>
/// Reads the binary representation of the CID from the specified <see cref="CodedInputStream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="CodedInputStream"/> to read from.
/// </param>
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
public static Cid Read(CodedInputStream stream)
{
var cid = new Cid();
var length = stream.ReadLength();
if (length == 34)
{
cid.Version = 0;
}
else
{
cid.Version = stream.ReadInt32();
cid.ContentType = stream.ReadMultiCodec().Name;
}
cid.Hash = new MultiHash(stream);
return cid;
}
/// <summary>
/// Writes the binary representation of the CID to the specified <see cref="CodedOutputStream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="CodedOutputStream"/> to write to.
/// </param>
public void Write(CodedOutputStream stream)
{
using (var ms = new MemoryStream())
{
if (Version != 0)
{
ms.WriteVarint(Version);
ms.WriteMultiCodec(this.ContentType);
}
Hash.Write(ms);
var bytes = ms.ToArray();
stream.WriteLength(bytes.Length);
stream.WriteSomeBytes(bytes);
}
}
/// <summary>
/// Reads the binary representation of the CID from the specified byte array.
/// </summary>
/// <param name="buffer">
/// The souce of a CID.
/// </param>
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
/// <remarks>
/// The buffer does NOT start with a varint length prefix.
/// </remarks>
public static Cid Read(byte[] buffer)
{
var cid = new Cid();
if (buffer.Length == 34)
{
cid.Version = 0;
cid.Hash = new MultiHash(buffer);
return cid;
}
using (var ms = new MemoryStream(buffer, false))
{
cid.Version = ms.ReadVarint32();
cid.ContentType = ms.ReadMultiCodec().Name;
cid.Hash = new MultiHash(ms);
return cid;
}
}
/// <summary>
/// Returns the binary representation of the CID as a byte array.
/// </summary>
/// <returns>
/// A new buffer containing the CID.
/// </returns>
/// <remarks>
/// The buffer does NOT start with a varint length prefix.
/// </remarks>
public byte[] ToArray()
{
if (Version == 0)
{
return Hash.ToArray();
}
using (var ms = new MemoryStream())
{
ms.WriteVarint(Version);
ms.WriteMultiCodec(this.ContentType);
Hash.Write(ms);
return ms.ToArray();
}
}
/// <summary>
/// Implicit casting of a <see cref="MultiHash"/> to a <see cref="Cid"/>.
/// </summary>
/// <param name="hash">
/// A <see cref="MultiHash"/>.
/// </param>
/// <returns>
/// A new <see cref="Cid"/> based on the <paramref name="hash"/>. A <see cref="Version"/> 0
/// CID is returned if the <paramref name="hash"/> is "sha2-356"; otherwise <see cref="Version"/> 1.
/// </returns>
static public implicit operator Cid(MultiHash hash)
{
if (hash.Algorithm.Name == "sha2-256")
{
return new Cid
{
Hash = hash,
Version = 0,
Encoding = "base58btc",
ContentType = "dag-pb"
};
}
return new Cid
{
Version = 1,
Hash = hash
};
}
/// <inheritdoc />
public override int GetHashCode()
{
return Encode().GetHashCode();
}
/// <inheritdoc />
public override bool Equals(object obj)
{
var that = obj as Cid;
return (that == null)
? false
: this.Encode() == that.Encode();
}
/// <inheritdoc />
public bool Equals(Cid that)
{
return this.Encode() == that.Encode();
}
/// <summary>
/// Value equality.
/// </summary>
public static bool operator ==(Cid a, Cid b)
{
if (object.ReferenceEquals(a, b))
{
return true;
}
if (object.ReferenceEquals(a, null))
{
return false;
}
if (object.ReferenceEquals(b, null))
{
return false;
}
return a.Equals(b);
}
/// <summary>
/// Value inequality.
/// </summary>
public static bool operator !=(Cid a, Cid b)
{
if (object.ReferenceEquals(a, b))
{
return false;
}
if (object.ReferenceEquals(a, null))
{
return true;
}
if (object.ReferenceEquals(b, null))
{
return true;
}
return !a.Equals(b);
}
/// <summary>
/// Implicit casting of a <see cref="string"/> to a <see cref="Cid"/>.
/// </summary>
/// <param name="s">
/// A string encoded <b>Cid</b>.
/// </param>
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
/// <remarks>
/// Equivalent to <code> Cid.Decode(s)</code>
/// </remarks>
static public implicit operator Cid(string s)
{
return Cid.Decode(s);
}
/// <summary>
/// Implicit casting of a <see cref="Cid"/> to a <see cref="string"/>.
/// </summary>
/// <param name="id">
/// A <b>Cid</b>.
/// </param>
/// <returns>
/// A new <see cref="string"/>.
/// </returns>
/// <remarks>
/// Equivalent to <code>Cid.Encode()</code>
/// </remarks>
static public implicit operator string(Cid id)
{
return id.Encode();
}
/// <summary>
/// Conversion of a <see cref="Cid"/> to and from JSON.
/// </summary>
/// <remarks>
/// The JSON is just a single string value.
/// </remarks>
public class CidJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return true;
}
/// <inheritdoc />
public override bool CanRead => true;
/// <inheritdoc />
public override bool CanWrite => true;
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var cid = value as Cid;
writer.WriteValue(cid?.Encode());
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var s = reader.Value as string;
return s == null ? null : Cid.Decode(s);
}
}
}
}