-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDagCborObject.cs
More file actions
1055 lines (904 loc) · 34.1 KB
/
Copy pathDagCborObject.cs
File metadata and controls
1055 lines (904 loc) · 34.1 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
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Text;
namespace dnproto.repo;
/// <summary>
///
/// DagCborObject
///
/// Represents the data block section of a repo record (after version and cid).
///
/// Most of this code handles converting the data between the
/// main three formats: Json string, DagCborObject, and byte[].
///
/// You can convert between the formats in either direction.
///
/// One example of this is accepting Json input for ApplyWrites
/// and ultimately writing the byte[] to the database:
///
/// Json -> (intermediate C# JsonElement) -> DagCborObject -> byte[]
///
/// One example for the *opposite* direction is reading a byte[]
/// from a CAR repo and ultimately outputting Json:
///
/// byte[] -> DagCborObject -> (intermediate C# objects) -> Json
///
/// The items in parentheses are intermediate C# types that are held
/// for a short time during conversion. The app mainly knows how to
/// "talk" in terms of Json strings, DagCborObject, and byte[].
///
/// </summary>
public class DagCborObject
{
public required DagCborType Type;
public required object Value;
#region BYTES
/// <summary>
/// Read a DagCbor object from a stream. Recursively reads maps and arrays.
/// The top-level type for a record's data block is *usually* a map, containing one or more elements.
/// For example, a post record will have a map with keys like "text", "$type", "createdAt", etc.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static DagCborObject ReadFromStream(Stream s, Dictionary<string, DagCborObject>? dataBlockDict = null)
{
DagCborType type = DagCborType.ReadNextType(s);
int length = 0;
switch(type.MajorType)
{
case DagCborType.TYPE_MAP:
length = ReadLengthFromStream(type, s); // might read one more byte for length
Dictionary<string,DagCborObject> dict = dataBlockDict != null ? dataBlockDict : new Dictionary<string,DagCborObject>();
for(int i = 0; i < length; i++)
{
DagCborObject key = ReadFromStream(s);
string? keyString = key != null ? key.TryGetString() : null;
DagCborObject value = ReadFromStream(s);
if(keyString != null)
{
dict[keyString] = value;
}
else
{
throw new Exception("Key is null.");
}
}
return new DagCborObject { Type = type, Value = dict };
case DagCborType.TYPE_ARRAY:
length = ReadLengthFromStream(type, s);
List<DagCborObject> list = new List<DagCborObject>();
for(int i = 0; i < length; i++)
{
var value = ReadFromStream(s);
list.Add(value);
}
return new DagCborObject { Type = type, Value = list };
case DagCborType.TYPE_TEXT:
length = ReadLengthFromStream(type, s);
byte[] bytes = new byte[length];
int readLength = s.Read(bytes, 0, length);
return new DagCborObject { Type = type, Value = Encoding.UTF8.GetString(bytes) };
case DagCborType.TYPE_TAG:
int tag = s.ReadByte();
if(tag != 42)
{
throw new Exception("Unknown tag: " + tag);
}
DagCborType byteStringType =DagCborType.ReadNextType(s);
length = ReadLengthFromStream(byteStringType, s);
int shouldBeZero = s.ReadByte(); // read one more byte for 0
CidV1 cid = CidV1.ReadCid(s);
return new DagCborObject { Type = type, Value = cid };
case DagCborType.TYPE_UNSIGNED_INT:
return new DagCborObject { Type = type, Value = ReadLengthFromStream(type, s) };
case DagCborType.TYPE_BYTE_STRING:
length = ReadLengthFromStream(type, s);
byte[] byteString = new byte[length];
int bytesRead = s.Read(byteString, 0, length);
return new DagCborObject { Type = type, Value = byteString };
case DagCborType.TYPE_SIMPLE_VALUE:
if(type.AdditionalInfo == 0x16)
{
return new DagCborObject { Type = type, Value = "null" };
}
else if(type.AdditionalInfo == 0x14)
{
return new DagCborObject { Type = type, Value = false };
}
else if(type.AdditionalInfo == 0x15)
{
return new DagCborObject { Type = type, Value = true };
}
else
{
throw new Exception("Unknown simple value: " + type.AdditionalInfo);
}
default:
throw new Exception("Unknown major type: " + type.MajorType);
}
}
public void WriteToStream(Stream s)
{
WriteToStream(this, s);
}
/// <summary>
/// Write a DagCbor object to a stream. Recursively writes maps and arrays.
/// This is the mirror operation to ReadFromStream.
/// </summary>
/// <param name="obj">The DagCborObject to write</param>
/// <param name="s">The stream to write to</param>
/// <exception cref="Exception"></exception>
public static void WriteToStream(DagCborObject obj, Stream s)
{
switch(obj.Type.MajorType)
{
case DagCborType.TYPE_MAP:
Dictionary<string, DagCborObject>? dict = obj.Value as Dictionary<string, DagCborObject>;
if(dict == null)
{
throw new Exception("Expected Dictionary for TYPE_MAP");
}
WriteLengthToStream(DagCborType.TYPE_MAP, dict.Count, s);
// DAG-CBOR requires map keys to be sorted in canonical order:
// first by byte length, then lexicographically by bytes
var sortedKeys = dict.Keys.OrderBy(k => System.Text.Encoding.UTF8.GetByteCount(k))
.ThenBy(k => k, StringComparer.Ordinal)
.ToList();
foreach(var key in sortedKeys)
{
// Write key as text string
DagCborObject keyObj = new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_TEXT,
AdditionalInfo = key.Length,
OriginalByte = 0
},
Value = key
};
WriteToStream(keyObj, s);
// Write value
WriteToStream(dict[key], s);
}
break;
case DagCborType.TYPE_ARRAY:
List<DagCborObject>? list = obj.Value as List<DagCborObject>;
if(list == null)
{
throw new Exception("Expected List for TYPE_ARRAY");
}
WriteLengthToStream(DagCborType.TYPE_ARRAY, list.Count, s);
foreach(var item in list)
{
WriteToStream(item, s);
}
break;
case DagCborType.TYPE_TEXT:
string? text = obj.Value as string;
if(text == null)
{
throw new Exception("Expected string for TYPE_TEXT");
}
byte[] textBytes = Encoding.UTF8.GetBytes(text);
WriteLengthToStream(DagCborType.TYPE_TEXT, textBytes.Length, s);
s.Write(textBytes, 0, textBytes.Length);
break;
case DagCborType.TYPE_TAG:
// Write tag type and tag number (42 for CID)
byte tagByte = (byte)((DagCborType.TYPE_TAG << 5) | 24); // tag with 1-byte uint
s.WriteByte(tagByte);
s.WriteByte(42); // CID tag
CidV1? cid = obj.Value as CidV1;
if(cid == null)
{
throw new Exception("Expected CidV1 for TYPE_TAG");
}
// Calculate the total length needed for the byte string
// This includes the version, multicodec, hash function, digest size, and digest bytes
// Plus one byte for the multibase prefix (0)
using (var tempStream = new MemoryStream())
{
CidV1.WriteCid(tempStream, cid);
byte[] cidBytes = tempStream.ToArray();
// Write byte string type for CID (with 0 prefix)
WriteLengthToStream(DagCborType.TYPE_BYTE_STRING, cidBytes.Length + 1, s);
s.WriteByte(0); // multibase prefix
s.Write(cidBytes, 0, cidBytes.Length);
}
break;
case DagCborType.TYPE_UNSIGNED_INT:
int? intValue = obj.Value as int?;
if(intValue == null)
{
throw new Exception("Expected int for TYPE_UNSIGNED_INT");
}
WriteLengthToStream(DagCborType.TYPE_UNSIGNED_INT, intValue.Value, s);
break;
case DagCborType.TYPE_BYTE_STRING:
byte[]? byteString = obj.Value as byte[];
if(byteString == null)
{
throw new Exception("Expected byte[] for TYPE_BYTE_STRING");
}
WriteLengthToStream(DagCborType.TYPE_BYTE_STRING, byteString.Length, s);
s.Write(byteString, 0, byteString.Length);
break;
case DagCborType.TYPE_SIMPLE_VALUE:
byte simpleByte;
if(obj.Value as string == "null")
{
simpleByte = (byte)((DagCborType.TYPE_SIMPLE_VALUE << 5) | 0x16);
}
else if(obj.Value is bool boolVal)
{
if(boolVal)
{
simpleByte = (byte)((DagCborType.TYPE_SIMPLE_VALUE << 5) | 0x15);
}
else
{
simpleByte = (byte)((DagCborType.TYPE_SIMPLE_VALUE << 5) | 0x14);
}
}
else
{
throw new Exception("Unknown simple value: " + obj.Value);
}
s.WriteByte(simpleByte);
break;
default:
throw new Exception("Unknown major type: " + obj.Type.MajorType);
}
}
/// <summary>
/// Write the length value to the stream with appropriate encoding.
/// </summary>
/// <param name="majorType">The CBOR major type</param>
/// <param name="length">The length or value to encode</param>
/// <param name="s">The stream to write to</param>
private static void WriteLengthToStream(int majorType, int length, Stream s)
{
byte firstByte;
if(length < 24)
{
firstByte = (byte)((majorType << 5) | length);
s.WriteByte(firstByte);
}
else if(length < 256)
{
firstByte = (byte)((majorType << 5) | 24);
s.WriteByte(firstByte);
s.WriteByte((byte)length);
}
else if(length < 65536)
{
firstByte = (byte)((majorType << 5) | 25);
s.WriteByte(firstByte);
s.WriteByte((byte)(length >> 8));
s.WriteByte((byte)(length & 0xFF));
}
else
{
firstByte = (byte)((majorType << 5) | 26);
s.WriteByte(firstByte);
s.WriteByte((byte)(length >> 24));
s.WriteByte((byte)((length >> 16) & 0xFF));
s.WriteByte((byte)((length >> 8) & 0xFF));
s.WriteByte((byte)(length & 0xFF));
}
}
public static void WriteToRepoStream(System.IO.Stream stream, CidV1 cid, DagCborObject dagCbor)
{
var cidBytes = cid.AllBytes;
var dagCborBytes = dagCbor.ToBytes();
var blockLengthVarInt = VarInt.FromLong((long)(cidBytes.Length + dagCborBytes.Length));
VarInt.WriteVarInt(stream, blockLengthVarInt);
CidV1.WriteCid(stream, cid);
stream.Write(dagCborBytes, 0, dagCborBytes.Length);
}
/// <summary>
/// Read the next length value from the stream.
/// </summary>
/// <param name="type"></param>
/// <param name="s"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private static int ReadLengthFromStream(DagCborType type, Stream s)
{
int length = 0;
if(type.AdditionalInfo < 24)
{
length = type.AdditionalInfo;
}
else if(type.AdditionalInfo == 24)
{
length = (byte)s.ReadByte();
}
else if(type.AdditionalInfo == 25)
{
length = ((byte)s.ReadByte() << 8) | (byte)s.ReadByte();
}
else if (type.AdditionalInfo == 26)
{
length = ((byte)s.ReadByte() << 24) | ((byte)s.ReadByte() << 16) | ((byte)s.ReadByte() << 8) | (byte)s.ReadByte();
}
else
{
throw new Exception("Unknown additional info: " + type.AdditionalInfo);
}
return length;
}
public byte[] ToBytes()
{
using(MemoryStream ms = new MemoryStream())
{
DagCborObject.WriteToStream(this, ms);
return ms.ToArray();
}
}
public static DagCborObject FromBytes(byte[] data)
{
using(MemoryStream ms = new MemoryStream(data))
{
return DagCborObject.ReadFromStream(ms);
}
}
#endregion
public override string ToString()
{
return $"CborObject -> {TryGetString()}";
}
public string TryGetString()
{
string? sval = Value.ToString();
return sval != null ? sval : "";
}
#region RAW
/// <summary>
/// This extracts the data (Value) from this DagCborObject and its children.
/// Helpful when you want to convert to something like json for debugging.
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public object? GetRawValue(string? key = null)
{
if(Type.MajorType == DagCborType.TYPE_TEXT)
{
return Value;
}
else if(Type.MajorType == DagCborType.TYPE_BYTE_STRING)
{
return Value;
}
else if(Type.MajorType == DagCborType.TYPE_UNSIGNED_INT)
{
return Value;
}
else if(Type.MajorType == DagCborType.TYPE_SIMPLE_VALUE)
{
return Value;
}
else if(Type.MajorType == DagCborType.TYPE_ARRAY)
{
List<object> list = new List<object>();
foreach(var obj in (List<DagCborObject>)Value)
{
var v = obj.GetRawValue();
if (v != null)
{
list.Add(v);
}
}
return list;
}
else if(Type.MajorType == DagCborType.TYPE_MAP)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach(KeyValuePair<string,DagCborObject> kvp in (Dictionary<string,DagCborObject>)Value)
{
var v = kvp.Value.GetRawValue(kvp.Key);
if(v != null)
{
dict[kvp.Key] = v;
}
}
return dict;
}
else if(Type.MajorType == DagCborType.TYPE_TAG)
{
//
// If this is a ref cid, expand it
//
/*
This is related to a bug I saw where videos would disappear
from the Bluesky CDN after two days. I noticed that firehose events
I was emitting would have "ref { '$link': 'cidstring' }" in the Dag Cbor,
but Bluesky PDS was collapsing that to just "ref" with a cid tag. I suspect that
the CDN was looking for ref cid tag to ensure that the video was in use.
And if it wasn't in use, it would expire the video after two days.
The caller of GetRawValue is likely going from DagCborObject -> Json,
in which case we want to expand the "ref: cid" to "ref { '$link': 'cidstring' }".
*/
if(
string.IsNullOrEmpty(key) == false
&& string.Equals("ref", key)
&& Value is CidV1)
{
return new Dictionary<string, object>
{
["$link"] = ((CidV1)Value).GetBase32()
};
}
//
// Otherwise keep going
//
if(Value is CidV1)
{
return ((CidV1)Value).GetBase32();
}
else
{
return Value;
}
}
else
{
throw new Exception("Unknown major type: " + Type.MajorType);
}
}
/// <summary>
/// Creates a DagCborObject from a raw value (useful for converting from JSON).
/// This is the inverse of GetRawValue().
/// </summary>
/// <param name="value">The raw value to convert</param>
/// <returns>A DagCborObject representing the value</returns>
/// <exception cref="Exception"></exception>
public static DagCborObject FromRawValue(object? value)
{
if(value == null)
{
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_SIMPLE_VALUE,
AdditionalInfo = 0x16,
OriginalByte = (byte)((DagCborType.TYPE_SIMPLE_VALUE << 5) | 0x16)
},
Value = "null"
};
}
else if(value is bool boolValue)
{
byte additionalInfo = boolValue ? (byte)0x15 : (byte)0x14;
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_SIMPLE_VALUE,
AdditionalInfo = additionalInfo,
OriginalByte = (byte)((DagCborType.TYPE_SIMPLE_VALUE << 5) | additionalInfo)
},
Value = boolValue
};
}
else if(value is int intValue)
{
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_UNSIGNED_INT,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = intValue
};
}
else if(value is long longValue)
{
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_UNSIGNED_INT,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = (int)longValue
};
}
else if(value is string stringValue)
{
// Don't auto-convert CID strings to Tag 42
// CID strings should remain as text unless explicitly using {"$link": "..."} notation
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_TEXT,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = stringValue
};
}
else if(value is byte[] byteArray)
{
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_BYTE_STRING,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = byteArray
};
}
else if(value is System.Text.Json.JsonElement jsonElement)
{
return FromJsonElement(jsonElement);
}
else if(value is List<object> list)
{
List<DagCborObject> cborList = new List<DagCborObject>();
foreach(var item in list)
{
cborList.Add(FromRawValue(item));
}
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_ARRAY,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = cborList
};
}
else if(value is Dictionary<string, object> dict)
{
//
// If this is a ref $link, collapse it.
//
/*
This is related to a bug I saw where videos would disappear
from the Bluesky CDN after two days. I noticed that firehose events
I was emitting would have "ref { '$link': 'cidstring' }" in the Dag Cbor,
but Bluesky PDS was collapsing that to just "ref" with a cid tag. I suspect that
the CDN was looking for ref cid tag to ensure that the video was in use.
And if it wasn't in use, it would expire the video after two days.
The caller of FromRawValue is likely going from Json -> DagCborObject,
in which case we want to collapse "ref { '$link': 'cidstring' }" to
just "ref: cid".
*/
if(
dict.Count == 1
&& dict.ContainsKey("$link")
&& dict["$link"] is string linkStr)
{
CidV1 cid = CidV1.FromBase32(linkStr);
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_TAG,
AdditionalInfo = 42,
OriginalByte = 0
},
Value = cid
};
}
//
// Otherwise, convert normally
//
Dictionary<string, DagCborObject> cborDict = new Dictionary<string, DagCborObject>();
foreach(var kvp in dict)
{
cborDict[kvp.Key] = FromRawValue(kvp.Value);
}
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_MAP,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = cborDict
};
}
else
{
throw new Exception($"Cannot convert type {value.GetType().Name} to DagCborObject");
}
}
/// <summary>
/// Helper method to convert System.Text.Json.JsonElement to DagCborObject.
/// </summary>
private static DagCborObject FromJsonElement(System.Text.Json.JsonElement element)
{
switch(element.ValueKind)
{
case System.Text.Json.JsonValueKind.Null:
return FromRawValue(null);
case System.Text.Json.JsonValueKind.True:
return FromRawValue(true);
case System.Text.Json.JsonValueKind.False:
return FromRawValue(false);
case System.Text.Json.JsonValueKind.Number:
if(element.TryGetInt32(out int intVal))
return FromRawValue(intVal);
if(element.TryGetInt64(out long longVal))
return FromRawValue((int)longVal);
throw new Exception("Number too large for int32");
case System.Text.Json.JsonValueKind.String:
return FromRawValue(element.GetString());
case System.Text.Json.JsonValueKind.Array:
List<object> list = new List<object>();
foreach(var item in element.EnumerateArray())
{
var rawValue = FromJsonElement(item).GetRawValue();
if(rawValue != null)
list.Add(rawValue);
}
return FromRawValue(list);
case System.Text.Json.JsonValueKind.Object:
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach(var prop in element.EnumerateObject())
{
//
// 2/3/26
// Added call to prop.Name, so that GetRawValue could check for
// a special key like "ref" when converting CIDs.
//
var rawValue = FromJsonElement(prop.Value).GetRawValue(prop.Name);
if(rawValue != null)
dict[prop.Name] = rawValue;
}
return FromRawValue(dict);
default:
throw new Exception($"Unsupported JsonValueKind: {element.ValueKind}");
}
}
#endregion
public static DagCborObject FromException(Exception e, byte[] buffer, Dictionary<string, DagCborObject> dataBlockDict)
{
string bufferString = Encoding.UTF8.GetString(buffer);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Buffer String: " + bufferString);
sb.AppendLine("Exception Type: " + e.GetType().Name);
sb.AppendLine("Exception Message: " + e.Message);
sb.AppendLine("Exception StackTrace: " + e.StackTrace);
dataBlockDict["DNPROTO_EXCEPTION"] = new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_TEXT,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = sb.ToString()
};
return new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_MAP,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = dataBlockDict
};
}
#region JSON
/// <summary>
/// Parses a JSON string into a DagCborObject.
/// </summary>
/// <param name="jsonString"></param>
/// <returns></returns>
public static DagCborObject FromJsonString(string jsonString)
{
//
// First convert json string to object. The object
// will be of type JsonElement.
//
object? o = JsonData.ConvertJsonStringToObject(jsonString);
//
// Second convert from JsonElement to DagCborObject.
//
DagCborObject dagCborObject = DagCborObject.FromRawValue(o);
return dagCborObject;
}
#endregion
public static string GetRecursiveDebugString(DagCborObject obj, int indent = 0)
{
string indentStr = new string(' ', indent * 2);
string result = $"{indentStr}Type: {obj.Type.GetMajorTypeString()}, Value: {obj.Value}\n";
if (obj.Type.MajorType == DagCborType.TYPE_MAP && obj.Value is Dictionary<string, DagCborObject> dict)
{
foreach (var kvp in dict)
{
result += $"{indentStr}Key: {kvp.Key}\n";
result += GetRecursiveDebugString(kvp.Value, indent + 1);
}
}
else if (obj.Type.MajorType == DagCborType.TYPE_ARRAY && obj.Value is List<DagCborObject> list)
{
for (int i = 0; i < list.Count; i++)
{
result += $"{indentStr}Index: {i}\n";
result += GetRecursiveDebugString(list[i], indent + 1);
}
}
return result;
}
#region SELECT
/// <summary>
/// Finds an object at the path specified by the property names,
/// and returns its value.
/// </summary>
/// <param name="propertyNames"></param>
/// <returns></returns>
public object? SelectObjectValue(string[] propertyNames)
{
DagCborObject? current = this;
foreach(string propertyName in propertyNames)
{
if(current.Type.MajorType != DagCborType.TYPE_MAP) return null;
Dictionary<string,DagCborObject>? dict = current.Value as Dictionary<string,DagCborObject>;
if(dict == null) return null;
if(dict.ContainsKey(propertyName)) current = dict[propertyName];
else return null;
}
return current != null ? current.Value : null;
}
public DagCborObject? SelectObject(string[] propertyNames)
{
DagCborObject? current = this;
foreach(string propertyName in propertyNames)
{
if(current.Type.MajorType != DagCborType.TYPE_MAP) return null;
Dictionary<string,DagCborObject>? dict = current.Value as Dictionary<string,DagCborObject>;
if(dict == null) return null;
if(dict.ContainsKey(propertyName)) current = dict[propertyName];
else return null;
}
return current;
}
/// <summary>
/// Finds an object at the path specified by the property names,
/// and returns as string if possible.
/// </summary>
/// <param name="propertyNames"></param>
/// <returns></returns>
public string? SelectString(string[] propertyNames)
{
object? o = SelectObjectValue(propertyNames);
if(o as string != null) return o as string;
if(o as int? != null) return o.ToString();
if(o as bool? != null) return o.ToString();
if(o as CidV1 != null) return ((CidV1)o).GetBase32();
return null;
}
/// <summary>
/// Finds an object at the path specified by the property names,
/// and returns as int if possible.
/// </summary>
/// <param name="propertyNames"></param>
/// <returns></returns>
public int? SelectInt(string[] propertyNames)
{
object? o = SelectObjectValue(propertyNames);
if(o is int i) return i;
return null;
}
public long? SelectLong(string[] propertyNames)
{
object? o = SelectObjectValue(propertyNames);
if(o is long l) return l;
if(o is int i) return (long)i;
return null;
}
public bool SetString(string[] propertyNames, string strValue)
{
DagCborObject? current = this;
for(int i = 0; i < propertyNames.Length; i++)
{
string propertyName = propertyNames[i];
if(current.Type.MajorType != DagCborType.TYPE_MAP) return false;
Dictionary<string,DagCborObject>? dict = current.Value as Dictionary<string,DagCborObject>;
if(dict == null) return false;
if(i == propertyNames.Length - 1)
{
// Last property, set value
dict[propertyName] = new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_TEXT,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = strValue
};
}
else
{
// Intermediate property, navigate or create
if(dict.ContainsKey(propertyName))
{
current = dict[propertyName];
}
else
{
DagCborObject newObj = new DagCborObject
{
Type = new DagCborType
{
MajorType = DagCborType.TYPE_MAP,
AdditionalInfo = 0,
OriginalByte = 0
},
Value = new Dictionary<string,DagCborObject>()
};
dict[propertyName] = newObj;
current = newObj;
}
}
}
return true;
}
#endregion
}
public class DagCborType