-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathAbiSerializationProvider.cs
More file actions
1505 lines (1262 loc) · 53.1 KB
/
AbiSerializationProvider.cs
File metadata and controls
1505 lines (1262 loc) · 53.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 EosSharp.Core.Api.v1;
using EosSharp.Core.DataAttributes;
using EosSharp.Core.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace EosSharp.Core.Providers
{
/// <summary>
/// Serialize / deserialize transaction and fields using a Abi schema
/// https://developers.eos.io/eosio-home/docs/the-abi
/// </summary>
public class AbiSerializationProvider
{
private enum KeyType
{
k1 = 0,
r1 = 1,
};
private delegate object ReaderDelegate(byte[] data, ref int readIndex);
private EosApi Api { get; set; }
private Dictionary<string, Action<MemoryStream, object>> TypeWriters { get; set; }
private Dictionary<string, ReaderDelegate> TypeReaders { get; set; }
/// <summary>
/// Construct abi serialization provided using EOS api
/// </summary>
/// <param name="api"></param>
public AbiSerializationProvider(EosApi api)
{
this.Api = api;
TypeWriters = new Dictionary<string, Action<MemoryStream, object>>()
{
{"int8", WriteByte },
{"uint8", WriteByte },
{"int16", WriteUint16 },
{"uint16", WriteUint16 },
{"int32", WriteUint32 },
{"uint32", WriteUint32 },
{"int64", WriteInt64 },
{"uint64", WriteUint64 },
{"int128", WriteInt128 },
{"uint128", WriteUInt128 },
{"varuint32", WriteVarUint32 },
{"varint32", WriteVarInt32 },
{"float32", WriteFloat32 },
{"float64", WriteFloat64 },
{"float128", WriteFloat128 },
{"bytes", WriteBytes },
{"bool", WriteBool },
{"string", WriteString },
{"name", WriteName },
{"asset", WriteAsset },
{"time_point", WriteTimePoint },
{"time_point_sec", WriteTimePointSec },
{"block_timestamp_type", WriteBlockTimestampType },
{"symbol_code", WriteSymbolCode },
{"symbol", WriteSymbolString },
{"checksum160", WriteChecksum160 },
{"checksum256", WriteChecksum256 },
{"checksum512", WriteChecksum512 },
{"public_key", WritePublicKey },
{"private_key", WritePrivateKey },
{"signature", WriteSignature },
{"extended_asset", WriteExtendedAsset }
};
TypeReaders = new Dictionary<string, ReaderDelegate>()
{
{"int8", ReadByte },
{"uint8", ReadByte },
{"int16", ReadUint16 },
{"uint16", ReadUint16 },
{"int32", ReadUint32 },
{"uint32", ReadUint32 },
{"int64", ReadInt64 },
{"uint64", ReadUint64 },
{"int128", ReadInt128 },
{"uint128", ReadUInt128 },
{"varuint32", ReadVarUint32 },
{"varint32", ReadVarInt32 },
{"float32", ReadFloat32 },
{"float64", ReadFloat64 },
{"float128", ReadFloat128 },
{"bytes", ReadBytes },
{"bool", ReadBool },
{"string", ReadString },
{"name", ReadName },
{"asset", ReadAsset },
{"time_point", ReadTimePoint },
{"time_point_sec", ReadTimePointSec },
{"block_timestamp_type", ReadBlockTimestampType },
{"symbol_code", ReadSymbolCode },
{"symbol", ReadSymbolString },
{"checksum160", ReadChecksum160 },
{"checksum256", ReadChecksum256 },
{"checksum512", ReadChecksum512 },
{"public_key", ReadPublicKey },
{"private_key", ReadPrivateKey },
{"signature", ReadSignature },
{"extended_asset", ReadExtendedAsset }
};
}
/// <summary>
/// Serialize transaction to packed asynchronously
/// </summary>
/// <param name="trx">transaction to pack</param>
/// <returns></returns>
public async Task<byte[]> SerializePackedTransaction(Transaction trx)
{
int actionIndex = 0;
var abiResponses = await GetTransactionAbis(trx);
using (MemoryStream ms = new MemoryStream())
{
//trx headers
WriteUint32(ms, SerializationHelper.DateToTimePointSec(trx.expiration));
WriteUint16(ms, trx.ref_block_num);
WriteUint32(ms, trx.ref_block_prefix);
//trx info
WriteVarUint32(ms, trx.max_net_usage_words);
WriteByte(ms, trx.max_cpu_usage_ms);
WriteVarUint32(ms, trx.delay_sec);
WriteVarUint32(ms, (UInt32)trx.context_free_actions.Count);
foreach (var action in trx.context_free_actions)
{
WriteAction(ms, action, abiResponses[actionIndex++]);
}
WriteVarUint32(ms, (UInt32)trx.actions.Count);
foreach (var action in trx.actions)
{
WriteAction(ms, action, abiResponses[actionIndex++]);
}
WriteVarUint32(ms, (UInt32)trx.transaction_extensions.Count);
foreach (var extension in trx.transaction_extensions)
{
WriteExtension(ms, extension);
}
return ms.ToArray();
}
}
/// <summary>
/// Deserialize packed transaction asynchronously
/// </summary>
/// <param name="packtrx">hex encoded strinh with packed transaction</param>
/// <returns></returns>
public async Task<Transaction> DeserializePackedTransaction(string packtrx)
{
var data = SerializationHelper.HexStringToByteArray(packtrx);
int readIndex = 0;
var trx = new Transaction()
{
expiration = (DateTime)ReadTimePointSec(data, ref readIndex),
ref_block_num = (UInt16)ReadUint16(data, ref readIndex),
ref_block_prefix = (UInt32)ReadUint32(data, ref readIndex),
max_net_usage_words = (UInt32)ReadVarUint32(data, ref readIndex),
max_cpu_usage_ms = (byte)ReadByte(data, ref readIndex),
delay_sec = (UInt32)ReadVarUint32(data, ref readIndex),
};
var contextFreeActionsSize = Convert.ToInt32(ReadVarUint32(data, ref readIndex));
trx.context_free_actions = new List<Core.Api.v1.Action>(contextFreeActionsSize);
for (int i = 0; i < contextFreeActionsSize; i++)
{
var action = (Core.Api.v1.Action)ReadActionHeader(data, ref readIndex);
Abi abi = await GetAbi(action.account);
trx.context_free_actions.Add((Core.Api.v1.Action)ReadAction(data, action, abi, ref readIndex));
}
var actionsSize = Convert.ToInt32(ReadVarUint32(data, ref readIndex));
trx.actions = new List<Core.Api.v1.Action>(actionsSize);
for (int i = 0; i < actionsSize; i++)
{
var action = (Core.Api.v1.Action)ReadActionHeader(data, ref readIndex);
Abi abi = await GetAbi(action.account);
trx.actions.Add((Core.Api.v1.Action)ReadAction(data, action, abi, ref readIndex));
}
return trx;
}
/// <summary>
/// Deserialize packed abi
/// </summary>
/// <param name="packabi">string encoded abi</param>
/// <returns></returns>
public Abi DeserializePackedAbi(string packabi)
{
var data = SerializationHelper.Base64FcStringToByteArray(packabi);
int readIndex = 0;
return new Abi()
{
version = (string)ReadString(data, ref readIndex),
types = ReadType<List<AbiType>>(data, ref readIndex),
structs = ReadType<List<AbiStruct>>(data, ref readIndex),
actions = ReadAbiActionList(data, ref readIndex),
tables = ReadAbiTableList(data, ref readIndex),
ricardian_clauses = ReadType<List<AbiRicardianClause>>(data, ref readIndex),
error_messages = ReadType<List<string>>(data, ref readIndex),
abi_extensions = ReadType<List<Extension>>(data, ref readIndex),
variants = ReadType<List<Variant>>(data, ref readIndex)
};
}
/// <summary>
/// Serialize action to packed action data
/// </summary>
/// <param name="action">action to pack</param>
/// <param name="abi">abi schema to look action structure</param>
/// <returns></returns>
public byte[] SerializeActionData(Core.Api.v1.Action action, Abi abi)
{
var abiAction = abi.actions.FirstOrDefault(aa => aa.name == action.name);
if (abiAction == null)
throw new ArgumentException(string.Format("action name {0} not found on abi.", action.name));
var abiStruct = abi.structs.FirstOrDefault(s => s.name == abiAction.type);
if (abiStruct == null)
throw new ArgumentException(string.Format("struct type {0} not found on abi.", abiAction.type));
using (MemoryStream ms = new MemoryStream())
{
WriteAbiStruct(ms, action.data, abiStruct, abi);
return ms.ToArray();
}
}
/// <summary>
/// Deserialize structure data as "Dictionary<string, object>"
/// </summary>
/// <param name="structType">struct type in abi</param>
/// <param name="dataHex">data to deserialize</param>
/// <param name="abi">abi schema to look for struct type</param>
/// <returns></returns>
public Dictionary<string, object> DeserializeStructData(string structType, string dataHex, Abi abi)
{
return DeserializeStructData<Dictionary<string, object>>(structType, dataHex, abi);
}
/// <summary>
/// Deserialize structure data with generic TStructData type
/// </summary>
/// <typeparam name="TStructData">deserialization struct data type</typeparam>
/// <param name="structType">struct type in abi</param>
/// <param name="dataHex">data to deserialize</param>
/// <param name="abi">abi schema to look for struct type</param>
/// <returns></returns>
public TStructData DeserializeStructData<TStructData>(string structType, string dataHex, Abi abi)
{
var data = SerializationHelper.HexStringToByteArray(dataHex);
var abiStruct = abi.structs.First(s => s.name == structType);
int readIndex = 0;
return ReadAbiStruct<TStructData>(data, abiStruct, abi, ref readIndex);
}
/// <summary>
/// Get abi schemas used in transaction
/// </summary>
/// <param name="trx"></param>
/// <returns></returns>
public Task<Abi[]> GetTransactionAbis(Transaction trx)
{
var abiTasks = new List<Task<Abi>>();
foreach (var action in trx.context_free_actions)
{
abiTasks.Add(GetAbi(action.account));
}
foreach (var action in trx.actions)
{
abiTasks.Add(GetAbi(action.account));
}
return Task.WhenAll(abiTasks);
}
/// <summary>
/// Get abi schema by contract account name
/// </summary>
/// <param name="accountName">account name</param>
/// <returns></returns>
public async Task<Abi> GetAbi(string accountName)
{
var result = await Api.GetRawAbi(new GetRawAbiRequest()
{
account_name = accountName
},true);
return DeserializePackedAbi(result.abi);
}
/// <summary>
/// Deserialize type by encoded string data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataHex"></param>
/// <returns></returns>
public T DeserializeType<T>(string dataHex)
{
return DeserializeType<T>(SerializationHelper.HexStringToByteArray(dataHex));
}
/// <summary>
/// Deserialize type by binary data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public T DeserializeType<T>(byte[] data)
{
int readIndex = 0;
return ReadType<T>(data, ref readIndex);
}
#region Writer Functions
private static void WriteByte(MemoryStream ms, object value)
{
ms.Write(new byte[] { Convert.ToByte(value) }, 0, 1);
}
private static void WriteUint16(MemoryStream ms, object value)
{
ms.Write(BitConverter.GetBytes(Convert.ToUInt16(value)), 0, 2);
}
private static void WriteUint32(MemoryStream ms, object value)
{
ms.Write(BitConverter.GetBytes(Convert.ToUInt32(value)), 0, 4);
}
private static void WriteInt64(MemoryStream ms, object value)
{
var decimalBytes = SerializationHelper.SignedDecimalToBinary(8, value.ToString());
ms.Write(decimalBytes, 0, decimalBytes.Length);
}
private static void WriteUint64(MemoryStream ms, object value)
{
var decimalBytes = SerializationHelper.DecimalToBinary(8, value.ToString());
ms.Write(decimalBytes, 0, decimalBytes.Length);
}
private static void WriteInt128(MemoryStream ms, object value)
{
var decimalBytes = SerializationHelper.SignedDecimalToBinary(16, value.ToString());
ms.Write(decimalBytes, 0, decimalBytes.Length);
}
private static void WriteUInt128(MemoryStream ms, object value)
{
var decimalBytes = SerializationHelper.DecimalToBinary(16, value.ToString());
ms.Write(decimalBytes, 0, decimalBytes.Length);
}
private static void WriteVarUint32(MemoryStream ms, object value)
{
var v = Convert.ToUInt32(value);
while (true)
{
if ((v >> 7) != 0)
{
ms.Write(new byte[] { (byte)(0x80 | (v & 0x7f)) }, 0, 1);
v >>= 7;
}
else
{
ms.Write(new byte[] { (byte)(v) }, 0, 1);
break;
}
}
}
private static void WriteVarInt32(MemoryStream ms, object value)
{
var n = Convert.ToInt32(value);
WriteVarUint32(ms, (UInt32)((n << 1) ^ (n >> 31)));
}
private static void WriteFloat32(MemoryStream ms, object value)
{
ms.Write(BitConverter.GetBytes(Convert.ToSingle(value)), 0, 4);
}
private static void WriteFloat64(MemoryStream ms, object value)
{
ms.Write(BitConverter.GetBytes(Convert.ToDouble(value)), 0, 8);
}
private static void WriteFloat128(MemoryStream ms, object value)
{
Int32[] bits = decimal.GetBits(Convert.ToDecimal(value));
List<byte> bytes = new List<byte>();
foreach (Int32 i in bits)
{
bytes.AddRange(BitConverter.GetBytes(i));
}
ms.Write(bytes.ToArray(), 0, 16);
}
private static void WriteBytes(MemoryStream ms, object value)
{
var bytes = (byte[])value;
WriteVarUint32(ms, (UInt32)bytes.Length);
ms.Write(bytes, 0, bytes.Length);
}
private static void WriteBool(MemoryStream ms, object value)
{
WriteByte(ms, (bool)value ? 1 : 0);
}
private static void WriteString(MemoryStream ms, object value)
{
var strBytes = Encoding.UTF8.GetBytes((string)value);
WriteVarUint32(ms, (UInt32)strBytes.Length);
if (strBytes.Length > 0)
ms.Write(strBytes, 0, strBytes.Length);
}
private static void WriteName(MemoryStream ms, object value)
{
var a = SerializationHelper.ConvertNameToBytes((string)value);
ms.Write(a, 0, 8);
}
private static void WriteAsset(MemoryStream ms, object value)
{
var s = ((string)value).Trim();
Int32 pos = 0;
string amount = "";
byte precision = 0;
if (s[pos] == '-')
{
amount += '-';
++pos;
}
bool foundDigit = false;
while (pos < s.Length && s[pos] >= '0' && s[pos] <= '9')
{
foundDigit = true;
amount += s[pos];
++pos;
}
if (!foundDigit)
throw new Exception("Asset must begin with a number");
if (s[pos] == '.')
{
++pos;
while (pos < s.Length && s[pos] >= '0' && s[pos] <= '9')
{
amount += s[pos];
++precision;
++pos;
}
}
string name = s.Substring(pos).Trim();
var decimalBytes = SerializationHelper.SignedDecimalToBinary(8, amount);
ms.Write(decimalBytes, 0, decimalBytes.Length);
WriteSymbol(ms, new Symbol() { name = name, precision = precision });
}
private static void WriteTimePoint(MemoryStream ms, object value)
{
var ticks = SerializationHelper.DateToTimePoint((DateTime)value);
WriteUint32(ms, (UInt32)(ticks & 0xffffffff));
WriteUint32(ms, (UInt32)Math.Floor((double)ticks / 0x100000000));
}
private static void WriteTimePointSec(MemoryStream ms, object value)
{
WriteUint32(ms, SerializationHelper.DateToTimePointSec((DateTime)value));
}
private static void WriteBlockTimestampType(MemoryStream ms, object value)
{
WriteUint32(ms, SerializationHelper.DateToBlockTimestamp((DateTime)value));
}
private static void WriteSymbolString(MemoryStream ms, object value)
{
Regex r = new Regex("^([0-9]+),([A-Z]+)$", RegexOptions.IgnoreCase);
Match m = r.Match((string)value);
if (!m.Success)
throw new Exception("Invalid symbol.");
WriteSymbol(ms, new Symbol() { name = m.Groups[2].ToString(), precision = byte.Parse(m.Groups[1].ToString()) });
}
private static void WriteSymbolCode(MemoryStream ms, object value)
{
var name = (string)value;
if (name.Length > 8)
ms.Write(Encoding.UTF8.GetBytes(name.Substring(0, 8)), 0, 8);
else
{
ms.Write(Encoding.UTF8.GetBytes(name), 0, name.Length);
if (name.Length < 8)
{
var fill = new byte[8 - name.Length];
for (int i = 0; i < fill.Length; i++)
fill[i] = 0;
ms.Write(fill, 0, fill.Length);
}
}
}
private static void WriteChecksum160(MemoryStream ms, object value)
{
var bytes = SerializationHelper.HexStringToByteArray((string)value);
if (bytes.Length != 20)
throw new Exception("Binary data has incorrect size");
ms.Write(bytes, 0, bytes.Length);
}
private static void WriteChecksum256(MemoryStream ms, object value)
{
var bytes = SerializationHelper.HexStringToByteArray((string)value);
if (bytes.Length != 32)
throw new Exception("Binary data has incorrect size");
ms.Write(bytes, 0, bytes.Length);
}
private static void WriteChecksum512(MemoryStream ms, object value)
{
var bytes = SerializationHelper.HexStringToByteArray((string)value);
if (bytes.Length != 64)
throw new Exception("Binary data has incorrect size");
ms.Write(bytes, 0, bytes.Length);
}
private static void WritePublicKey(MemoryStream ms, object value)
{
var s = (string)value;
var keyBytes = CryptoHelper.PubKeyStringToBytes(s);
WriteByte(ms, s.StartsWith("PUB_R1_") ? KeyType.r1 : KeyType.k1);
ms.Write(keyBytes, 0, CryptoHelper.PUB_KEY_DATA_SIZE);
}
private static void WritePrivateKey(MemoryStream ms, object value)
{
var s = (string)value;
var keyBytes = CryptoHelper.PrivKeyStringToBytes(s);
WriteByte(ms, KeyType.r1);
ms.Write(keyBytes, 0, CryptoHelper.PRIV_KEY_DATA_SIZE);
}
private static void WriteSignature(MemoryStream ms, object value)
{
var s = (string)value;
var signBytes = CryptoHelper.SignStringToBytes(s);
if (s.StartsWith("SIG_K1_"))
WriteByte(ms, KeyType.k1);
else if (s.StartsWith("SIG_R1_"))
WriteByte(ms, KeyType.r1);
ms.Write(signBytes, 0, CryptoHelper.SIGN_KEY_DATA_SIZE);
}
private static void WriteExtendedAsset(MemoryStream ms, object value)
{
var extAsset = (ExtendedAsset)value;
WriteAsset(ms, extAsset.quantity);
WriteName(ms, extAsset.contract);
}
private static void WriteSymbol(MemoryStream ms, object value)
{
var symbol = (Symbol)value;
WriteByte(ms, symbol.precision);
if (symbol.name.Length > 7)
ms.Write(Encoding.UTF8.GetBytes(symbol.name.Substring(0, 7)), 0, 7);
else
{
ms.Write(Encoding.UTF8.GetBytes(symbol.name), 0, symbol.name.Length);
if (symbol.name.Length < 7)
{
var fill = new byte[7 - symbol.name.Length];
for (int i = 0; i < fill.Length; i++)
fill[i] = 0;
ms.Write(fill, 0, fill.Length);
}
}
}
private static void WriteExtension(MemoryStream ms, Core.Api.v1.Extension extension)
{
if (extension.data == null)
return;
WriteUint16(ms, extension.type);
WriteBytes(ms, extension.data);
}
private static void WritePermissionLevel(MemoryStream ms, PermissionLevel perm)
{
WriteName(ms, perm.actor);
WriteName(ms, perm.permission);
}
private void WriteAction(MemoryStream ms, Core.Api.v1.Action action, Abi abi)
{
WriteName(ms, action.account);
WriteName(ms, action.name);
WriteVarUint32(ms, (UInt32)action.authorization.Count);
foreach (var perm in action.authorization)
{
WritePermissionLevel(ms, perm);
}
WriteBytes(ms, SerializeActionData(action, abi));
}
private void WriteAbiType(MemoryStream ms, object value, string type, Abi abi, bool isBinaryExtensionAllowed)
{
var uwtype = UnwrapTypeDef(abi, type);
// binary extension type
if(uwtype.EndsWith("$"))
{
if (!isBinaryExtensionAllowed) throw new Exception("Binary Extension type not allowed.");
WriteAbiType(ms, value, uwtype.Substring(0, uwtype.Length - 1), abi, isBinaryExtensionAllowed);
return;
}
//optional type
if (uwtype.EndsWith("?"))
{
if(value != null)
{
WriteByte(ms, 1);
type = uwtype.Substring(0, uwtype.Length - 1);
}
else
{
WriteByte(ms, 0);
return;
}
}
// array type
if(uwtype.EndsWith("[]"))
{
var items = (ICollection)value;
var arrayType = uwtype.Substring(0, uwtype.Length - 2);
WriteVarUint32(ms, items.Count);
foreach (var item in items)
WriteAbiType(ms, item, arrayType, abi, false);
return;
}
var writer = GetTypeSerializerAndCache(type, TypeWriters, abi);
if (writer != null)
{
writer(ms, value);
return;
}
var abiStruct = abi.structs.FirstOrDefault(s => s.name == uwtype);
if (abiStruct != null)
{
WriteAbiStruct(ms, value, abiStruct, abi);
return;
}
var abiVariant = abi.variants.FirstOrDefault(v => v.name == uwtype);
if (abiVariant != null)
{
WriteAbiVariant(ms, value, abiVariant, abi, isBinaryExtensionAllowed);
}
else
{
throw new Exception("Type supported writer not found.");
}
}
private void WriteAbiStruct(MemoryStream ms, object value, AbiStruct abiStruct, Abi abi)
{
if (value == null)
return;
if(!string.IsNullOrWhiteSpace(abiStruct.@base))
{
WriteAbiType(ms, value, abiStruct.@base, abi, true);
}
if(value is System.Collections.IDictionary)
{
var skippedBinaryExtension = false;
var valueDict = value as System.Collections.IDictionary;
foreach (var field in abiStruct.fields)
{
var fieldName = FindObjectFieldName(field.name, valueDict);
if (string.IsNullOrWhiteSpace(fieldName))
{
if (field.type.EndsWith("$"))
{
skippedBinaryExtension = true;
continue;
}
throw new Exception("Missing " + abiStruct.name + "." + field.name + " (type=" + field.type + ")");
}
else if (skippedBinaryExtension)
{
throw new Exception("Unexpected " + abiStruct.name + "." + field.name + " (type=" + field.type + ")");
}
WriteAbiType(ms, valueDict[fieldName], field.type, abi, true);
}
}
else
{
var valueType = value.GetType();
foreach (var field in abiStruct.fields)
{
var fieldInfo = valueType.GetField(field.name);
if(fieldInfo != null)
WriteAbiType(ms, fieldInfo.GetValue(value), field.type, abi, true);
else
{
var propInfo = valueType.GetProperty(field.name);
if(propInfo != null)
WriteAbiType(ms, propInfo.GetValue(value), field.type, abi, true);
else
throw new Exception("Missing " + abiStruct.name + "." + field.name + " (type=" + field.type + ")");
}
}
}
}
private void WriteAbiVariant(MemoryStream ms, object value, Variant abiVariant, Abi abi, bool isBinaryExtensionAllowed)
{
var variantValue = (KeyValuePair<string, object>)value;
var i = abiVariant.types.IndexOf(variantValue.Key);
if (i < 0)
{
throw new Exception("type " + variantValue.Key + " is not valid for variant");
}
WriteVarUint32(ms, i);
WriteAbiType(ms, variantValue.Value, variantValue.Key, abi, isBinaryExtensionAllowed);
}
private string UnwrapTypeDef(Abi abi, string type)
{
var wtype = abi.types.FirstOrDefault(t => t.new_type_name == type);
if(wtype != null && wtype.type != type)
{
return UnwrapTypeDef(abi, wtype.type);
}
return type;
}
private TSerializer GetTypeSerializerAndCache<TSerializer>(string type, Dictionary<string, TSerializer> typeSerializers, Abi abi)
{
TSerializer nativeSerializer;
if (typeSerializers.TryGetValue(type, out nativeSerializer))
{
return nativeSerializer;
}
var abiTypeDef = abi.types.FirstOrDefault(t => t.new_type_name == type);
if(abiTypeDef != null)
{
var serializer = GetTypeSerializerAndCache(abiTypeDef.type, typeSerializers, abi);
if(serializer != null)
{
typeSerializers.Add(type, serializer);
return serializer;
}
}
return default(TSerializer);
}
#endregion
#region Reader Functions
private object ReadByte(byte[] data, ref int readIndex)
{
return data[readIndex++];
}
private object ReadUint16(byte[] data, ref int readIndex)
{
var value = BitConverter.ToUInt16(data, readIndex);
readIndex += 2;
return value;
}
private object ReadUint32(byte[] data, ref int readIndex)
{
var value = BitConverter.ToUInt32(data, readIndex);
readIndex += 4;
return value;
}
private object ReadInt64(byte[] data, ref int readIndex)
{
var value = (Int64)BitConverter.ToUInt64(data, readIndex);
readIndex += 8;
return value;
}
private object ReadUint64(byte[] data, ref int readIndex)
{
var value = BitConverter.ToUInt64(data, readIndex);
readIndex += 8;
return value;
}
private object ReadInt128(byte[] data, ref int readIndex)
{
byte[] amount = data.Skip(readIndex).Take(16).ToArray();
readIndex += 16;
return SerializationHelper.SignedBinaryToDecimal(amount);
}
private object ReadUInt128(byte[] data, ref int readIndex)
{
byte[] amount = data.Skip(readIndex).Take(16).ToArray();
readIndex += 16;
return SerializationHelper.BinaryToDecimal(amount);
}
private object ReadVarUint32(byte[] data, ref int readIndex)
{
uint v = 0;
int bit = 0;
while (true)
{
byte b = data[readIndex++];
v |= (uint)((b & 0x7f) << bit);
bit += 7;
if ((b & 0x80) == 0)
break;
}
return v >> 0;
}
private object ReadVarInt32(byte[] data, ref int readIndex)
{
var v = (UInt32)ReadVarUint32(data, ref readIndex);
if ((v & 1) != 0)
return ((~v) >> 1) | 0x80000000;
else
return v >> 1;
}
private object ReadFloat32(byte[] data, ref int readIndex)
{
var value = BitConverter.ToSingle(data, readIndex);
readIndex += 4;
return value;
}
private object ReadFloat64(byte[] data, ref int readIndex)
{
var value = BitConverter.ToDouble(data, readIndex);
readIndex += 8;
return value;
}
private object ReadFloat128(byte[] data, ref int readIndex)
{
var a = data.Skip(readIndex).Take(16).ToArray();
var value = SerializationHelper.ByteArrayToHexString(a);
readIndex += 16;
return value;
}
private object ReadBytes(byte[] data, ref int readIndex)
{
var size = Convert.ToInt32(ReadVarUint32(data, ref readIndex));
var value = data.Skip(readIndex).Take(size).ToArray();
readIndex += size;
return value;
}
private object ReadBool(byte[] data, ref int readIndex)
{
return (byte)ReadByte(data, ref readIndex) == 1;
}
private object ReadString(byte[] data, ref int readIndex)
{
var size = Convert.ToInt32(ReadVarUint32(data, ref readIndex));
string value = null;
if (size > 0)
{
value = Encoding.UTF8.GetString(data.Skip(readIndex).Take(size).ToArray());
readIndex += size;
}
return value;
}
private object ReadName(byte[] data, ref int readIndex)
{
byte[] a = data.Skip(readIndex).Take(8).ToArray();
string result = "";
readIndex += 8;
for (int bit = 63; bit >= 0;)
{
int c = 0;
for (int i = 0; i < 5; ++i)
{
if (bit >= 0)
{
c = (c << 1) | ((a[(int)Math.Floor((double)bit / 8)] >> (bit % 8)) & 1);
--bit;
}
}
if (c >= 6)
result += (char)(c + 'a' - 6);
else if (c >= 1)
result += (char)(c + '1' - 1);
else
result += '.';
}
if (result == ".............")
return result;
while (result.EndsWith("."))
result = result.Substring(0, result.Length - 1);
return result;
}
private object ReadAsset(byte[] data, ref int readIndex)
{
byte[] amount = data.Skip(readIndex).Take(8).ToArray();
readIndex += 8;
var symbol = (Symbol)ReadSymbol(data, ref readIndex);
string s = SerializationHelper.SignedBinaryToDecimal(amount, symbol.precision + 1);