forked from HeliosLang/compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helios.js
19699 lines (17163 loc) · 440 KB
/
helios.js
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
//@ts-check
///////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////// Helios //////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Author: Christian Schmitz
// Email: cschmitz398@gmail.com
// Website: github.com/hyperion-bt/helios
// Version: 0.3.0
// Last update: August 2022
// License: Unlicense
//
//
// About: Helios is a smart contract DSL for Cardano.
// This Javascript library contains functions to compile Helios sources into Plutus-Core.
// The results can be used by cardano-cli to generate and submit blockchain transactions.
//
//
// Dependencies: none
//
//
// Disclaimer: I made Helios available as FOSS so that the Cardano community can test
// it extensively. I don't guarantee the library is bug-free,
// nor do I guarantee backward compatibility with future versions.
//
//
// Example usage:
// > import * as helios from "helios.js";
// > console.log(helios.compile("validator my_validator ..."));
//
//
// Exports:
// * CompilationStage
// enum with six values: Preprocess, Tokenize, BuildAST, IR, PlutusCore and Final
//
// * compile(src: string,
// config: {verbose: false, templateParameters: {}, stage: CompilationStage, simplify: false}) -> ...
// different return types depending on config.stage:
// config.stage==CompilationStage.Preprocess -> string
// config.stage==CompilationStage.Tokenize -> list of Tokens
// config.stage==CompilationStage.BuildAST -> Program
// config.stage==CompilationStage.IR -> string
// config.stage==CompilationStage.PlutusCore -> PlutusCoreProgram
// config.stage==CompilationStage.Final -> string
// The final string output is a JSON string that be can saved as a file and can then
// be used by cardano-cli as a '--tx-in-script-file' for transaction building.
//
// * async run(typedSrc: string, config: {verbose: false, templateParameters: {}}) ->
// [PlutusCoreData | UserError, []string]
// Compile and run a test program that doesn't take any arguments, returns a tuple where the
// first value is either the result or an error, and the second value is a list of printed
// messages.
//
// * FuzzyTest(seed: number)
// Fuzzy testing class which can be used for propery based testing of test scripts.
// See ./test-suite.js for examples of how to use this.
//
// * highlight(src: string) -> Uint8Array
// Returns one marker byte per src character.
//
//
// Note: the Helios library is a single file, doesn't use TypeScript, and should stay
// unminified (so that a unique git commit of this repo is directly related to a unique IPFS
// address of 'helios.js').
//
//
// Overview of internals:
// 1. Constants VERSION, DEBUG, debug, BLAKE2B_DIGEST_SIZE,
// setBlake2bDigestSize, TAB, ScriptPurpose,
// PLUTUS_CORE_VERSION_COMPONENTS, PLUTUS_CORE_VERSION,
// PLUTUS_CORE_TAG_WIDTHS, PLUTUS_CORE_BUILTINS
//
// 2. Utilities assert, assertDefined, assertEq, idiv, ipow2, imask,
// imod32, imod8, irotr, iadd64, irotr64, padZeroes,
// byteToBitString, hexToBytes, bytesToHex, stringToBytes,
// bytesToString, replaceTabs, unwrapCborBytes,
// wrapCborBytes, BitReader, BitWriter,
// DEFAULT_BASE32_ALPHABET, BECH32_BASE32_ALPHABET,
// Crypto, IR, Source, UserError, Site
//
// 3. Plutus-Core AST objects PlutusCoreValue, PlutusCoreRTE, PlutusCoreStack,
// PlutusCoreAnon, PlutusCoreInt, PlutusCoreByteArray,
// PlutusCoreString, PlutusCoreUnit, PlutusCoreBool,
// PlutusCorePair, PlutusCoreMapItem, PlutusCoreList,
// PlutusCoreMap, PlutusCoreDataValue, PlutusCoreTerm,
// PlutusCoreVariable, PlutusCoreDelay, PlutusCoreLambda,
// PlutusCoreCall, PlutusCoreConst, PlutusCoreForce,
// PlutusCoreError, PlutusCoreBuiltin, PlutusCoreProgram
//
// 4. Plutus-Core data objects PlutusCoreData, IntData, ByteArrayData, ListData,
// MapData, ConstrData, LedgerData
//
// 5. Token objects Token, Word, Symbol, Group,
// PrimitiveLiteral, IntLiteral, BoolLiteral,
// ByteArrayLiteral, StringLiteral, UnitLiteral
//
// 6. Tokenization Tokenizer, tokenize, tokenizeIR,
// SyntaxCategory, highlight
//
// 7. Type evaluation objects GeneralizedValue, Type, AnyType, DataType, AnyDataType,
// BuiltinType, StatementType, FuncType, Value, DataValue,
// FuncValue, FuncStatementValue
//
// 8. Scopes GlobalScope, Scope, TopScope, FuncStatementScope
//
// 9. AST expression objects Expr, TypeExpr, TypeRefExpr, TypePathExpr,
// ListTypeExpr, MapTypeExpr, OptionTypeExpr,
// FuncTypeExpr, ValueExpr, AssignExpr, PrintExpr,
// PrimitiveLiteralExpr, StructLiteralField,
// StructLiteralExpr, ListLiteralExpr, MapLiteralExpr,
// NameTypePair, FuncArg, FuncLiteralExpr, ValueRefExpr,
// ValuePathExpr, UnaryExpr, BinaryExpr, ParensExpr,
// CallExpr, MemberExpr, IfElseExpr,
// SwitchCase, SwitchDefault, SwitchExpr
//
// 10. AST statement objects Statement, ConstStatement, DataField,
// DataDefinition, StructStatement, FuncStatement,
// EnumMember, EnumStatement, ImplDefinition,
// Program
//
// 11. AST build functions buildProgram, buildScriptPurpose, buildConstStatement,
// splitDataImpl, buildStructStatement, buildDataFields,
// buildFuncStatement, buildFuncLiteralExpr, buildFuncArgs,
// buildEnumStatement, buildEnumMember,
// buildImplDefinition, buildImplMembers, buildTypeExpr,
// buildListTypeExpr, buildMapTypeExpr,
// buildOptionTypeExpr, buildFuncTypeExpr,
// buildTypePathExpr, buildTypeRefExpr,
// buildValueExpr, buildMaybeAssignOrPrintExpr,
// makeBinaryExprBuilder, makeUnaryExprBuilder,
// buildChainedValueExpr, buildChainStartValueExpr,
// buildCallArgs, buildIfElseExpr, buildSwitchExpr,
// buildSwitchCase, buildSwitchDefault,
// buildListLiteralExpr, buildMapLiteralExpr,
// buildStructLiteralExpr, buildStructLiteralField,
// buildValuePathExpr
//
// 12. Builtin types IntType, BoolType, StringType, ByteArrayType,
// ListType, FoldListFuncValue, MapListFuncValue,
// MapType, FoldMapFuncValue,
// OptionType, OptionSomeType, OptionNoneType,
// HashType, PubKeyHashType, ValidatorHashType,
// MintinPolicyHashType, DatumHashType, ScriptContextType,
// TxType, TxIdType, TxInputType, TxOutputType,
// TxOutputIdType, AddressType, CredentialType,
// CredentialPubKeyType, CredentialValidatorType,
// StakingCredentialType, TimeType, DurationType,
// TimeRangeType, AssetClassType, MoneyValueType
//
// 13. Builtin low-level functions onNotifyRawUsage, setRawUsageNotifier,
// RawFunc, makeRawFunctions, wrapWithRawFunctions
//
// 14. IR AST objects IRScope, IRExpr, IRVariable, IRFuncExpr,
// IRUserCallExpr, IRCoreCallExpr, IRErrorCallExpr,
// IRNameExpr, IRLiteral
//
// 15. IR AST build functions buildIRProgram, buildIRExpr, buildIRFuncExpr,
// simplifyIRProgram
//
// 16. Compilation preprocess, CompilationStage, DEFAULT_CONFIG,
// compileInternal, getPurposeName,
// extractScriptPurposeAndName, compile, run
//
// 17. Plutus-Core deserialization PlutusCoreDeserializer, deserializePlutusCore
//
// 18. Property test framework FuzzyTest
//
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////
// Section 1: Global constants and variables
////////////////////////////////////////////
const VERSION = "0.2.0";
var DEBUG = false;
/**
* Changes the value of DEBUG
* @param {boolean} b
*/
function debug(b) { DEBUG = b };
var BLAKE2B_DIGEST_SIZE = 32; // bytes
/**
* Changes the value of BLAKE2B_DIGEST_SIZE (because nodjes crypto module only supports blake2b-512 and not blake2b-256,
* and we want to avoid non-standard dependencies in the test-suite)
* @param {number} s - 32 or 64
*/
function setBlake2bDigestSize(s) {
BLAKE2B_DIGEST_SIZE = s;
}
/**
* A tab used for indenting of the IR.
* 4 spaces.
* @type {string}
*/
const TAB = " ";
/**
* A Helios Program can have different purposes
*/
const ScriptPurpose = {
Testing: -1,
Minting: 0,
Spending: 1,
};
/**
* This library use version "1.0.0" of Plutus-Core (TODO: implement "2.0.0" upon mainnet Vasil HFC)
*/
const PLUTUS_CORE_VERSION_COMPONENTS = [1n, 0n, 0n];
/**
* I.e. "1.0.0" (TODO: implement "2.0.0" upon mainnet Vasil HFC)
* @type {string}
*/
const PLUTUS_CORE_VERSION = PLUTUS_CORE_VERSION_COMPONENTS.map(c => c.toString()).join(".");
/**
* @type {Object.<string, number>}
*/
const PLUTUS_CORE_TAG_WIDTHS = {
term: 4,
type: 3,
constType: 4,
builtin: 7,
constant: 4,
kind: 1,
};
/**
* @typedef PlutusCoreBuiltinInfo
* @property {string} name
* @property {number} forceCount - number of type parameters of a plutus-core builtin function (0, 1 or 2)
*/
/** @type {PlutusCoreBuiltinInfo[]} */
const PLUTUS_CORE_BUILTINS = (
/**
* @returns {PlutusCoreBuiltinInfo[]}
*/
function () {
/**
* Constructs a builtinInfo object
* @param {string} name
* @param {number} forceCount
* @returns {PlutusCoreBuiltinInfo}
*/
function builtinInfo(name, forceCount) {
// builtins might need be wrapped in `force` a number of times if they are not fully typed
return { name: name, forceCount: forceCount };
}
return [
builtinInfo("addInteger", 0), // 0
builtinInfo("subtractInteger", 0),
builtinInfo("multiplyInteger", 0),
builtinInfo("divideInteger", 0),
builtinInfo("quotientInteger", 0),
builtinInfo("remainderInteger", 0),
builtinInfo("modInteger", 0),
builtinInfo("equalsInteger", 0),
builtinInfo("lessThanInteger", 0),
builtinInfo("lessThanEqualsInteger", 0),
builtinInfo("appendByteString", 0), // 10
builtinInfo("consByteString", 0),
builtinInfo("sliceByteString", 0),
builtinInfo("lengthOfByteString", 0),
builtinInfo("indexByteString", 0),
builtinInfo("equalsByteString", 0),
builtinInfo("lessThanByteString", 0),
builtinInfo("lessThanEqualsByteString", 0),
builtinInfo("sha2_256", 0),
builtinInfo("sha3_256", 0),
builtinInfo("blake2b_256", 0), // 20
builtinInfo("verifyEd25519Signature", 0),
builtinInfo("appendString", 0),
builtinInfo("equalsString", 0),
builtinInfo("encodeUtf8", 0),
builtinInfo("decodeUtf8", 0),
builtinInfo("ifThenElse", 1),
builtinInfo("chooseUnit", 1),
builtinInfo("trace", 1),
builtinInfo("fstPair", 2),
builtinInfo("sndPair", 2), // 30
builtinInfo("chooseList", 1),
builtinInfo("mkCons", 1),
builtinInfo("headList", 1),
builtinInfo("tailList", 1),
builtinInfo("nullList", 1),
builtinInfo("chooseData", 0),
builtinInfo("constrData", 0),
builtinInfo("mapData", 0),
builtinInfo("listData", 0),
builtinInfo("iData", 0), // 40
builtinInfo("bData", 0),
builtinInfo("unConstrData", 0),
builtinInfo("unMapData", 0),
builtinInfo("unListData", 0),
builtinInfo("unIData", 0),
builtinInfo("unBData", 0),
builtinInfo("equalsData", 0),
builtinInfo("mkPairData", 0),
builtinInfo("mkNilData", 0),
builtinInfo("mkNilPairData", 0), // 50
builtinInfo("serialiseData", 0),
builtinInfo("verifyEcdsaSecp256k1Signature", 0),
builtinInfo("verifySchnorrSecp256k1Signature", 0),
];
}
)();
///////////////////////
// Section 2: utilities
///////////////////////
/**
* Throws an error if 'cond' is false.
* @param {boolean} cond
* @param {string} msg
*/
function assert(cond, msg = "unexpected") {
if (!cond) {
throw new Error(msg);
}
}
/**
* Throws an error if 'obj' is undefined. Returns 'obj' itself (for chained application).
* @template T
* @param {T | undefined} obj
* @param {string} msg
* @returns {T}
*/
function assertDefined(obj, msg = "unexpected undefined value") {
if (obj == undefined) {
throw new Error(msg);
}
return obj;
}
/**
* Throws an error if two object aren't equal (deep comparison).
* Used by unit tests that are autogenerated from JSDoc inline examples.
* @template T
* @param {T} a
* @param {T} b
* @param {string} msg
*/
function assertEq(a, b, msg) {
/**
* Compares two objects (deep recursive comparison)
* @param {T} a
* @param {T} b
* @returns {boolean}
*/
var eq = function (a, b) {
if (a == undefined || b == undefined) {
throw new Error("one of the args is undefined");
} else if (typeof a == "string") {
return a === b;
} else if (typeof a == "number") {
return a === b;
} else if (typeof a == "boolean") {
return a === b;
} else if (typeof a == "bigint") {
return a === b;
} else if (a instanceof Array && b instanceof Array) {
if (a.length != b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (!eq(a[i], b[i])) {
return false;
}
}
return true;
} else {
throw new Error("eq not yet implemented for these types");
}
}
if (!eq(a, b)) {
console.log(a);
console.log(b);
throw new Error(msg);
}
}
/**
* Divides two integers. Assumes a and b are whole numbers. Rounds down the result.
* @example
* idiv(355, 113) => 3
* @param {number} a
* @param {number} b
* */
function idiv(a, b) {
return Math.floor(a / b);
// alternatively: (a - a%b)/b
}
/**
* 2 to the power 'p' for bigint.
* @param {bigint} p
* @returns {bigint}
*/
function ipow2(p) {
return (p <= 0n) ? 1n : 2n << (p - 1n);
}
/**
* Masks bits of 'b' by setting bits outside the range ['i0', 'i1') to 0.
* 'b' is an 8 bit integer (i.e. number between 0 and 255).
* The return value is also an 8 bit integer, shift right by 'i1'.
* @example
* imask(0b11111111, 1, 4) => 0b0111 // (i.e. 7)
* @param {number} b
* @param {number} i0
* @param {number} i1
* @returns {number}
*/
function imask(b, i0, i1) {
assert(i0 < i1);
const mask_bits = [
0b11111111,
0b01111111,
0b00111111,
0b00011111,
0b00001111,
0b00000111,
0b00000011,
0b00000001,
];
return (b & mask_bits[i0]) >> (8 - i1);
}
/**
* Make sure resulting number fits in uint32
* @param {number} x
*/
function imod32(x) {
return x >>> 0;
}
/**
* Make sure resulting number fits in uint8
* @param {number} x
*/
function imod8(x) {
return x & 0xff;
}
/**
* 32 bit number rotation
* @param {number} x - originally uint32
* @param {number} n
* @returns {number} - originally uint32
*/
function irotr(x, n) {
return imod32((x >>> n) | (x << (32 - n)));
}
/**
* 64-bit addition emulated with 32 bit numbers.
* Low overflow spills into high result
* @param {number} a0 - left low number
* @param {number} a1 - left high number
* @param {number} b0 - right low number
* @param {number} b1 -right high number
* @returns {[number, number]} - low and high result
*/
function iadd64(a0, a1, b0, b1) {
let c0 = a0 + b0;
let c1 = a1 + b1;
if (c0 >= 0x100000000) {
c1 += 1;
}
return [imod32(c0), imod32(c1)];
}
/**
* Rotate uint64 integer right.
* The uint64 integer is emulated using two uint32 numbers.
* @param {number} x0
* @param {number} x1
* @param {number} n - between 0 and 32
* @returns {[number, number]} - low and high result
*/
function irotr64(x0, x1, n) {
if (n == 32) {
return [x1, x0];
} else if (n > 32) {
return irotr64(x1, x0, n - 32);
} else {
return [imod32((x0 >>> n) | (x1 << (32 - n))), imod32((x1 >>> n) | (x0 << (32 - n)))];
}
}
/**
* Prepends zeroes to a bit-string so that 'result.length == n'.
* @example
* padZeroes("1111", 8) => "00001111"
* @param {string} bits
* @param {number} n
* @returns {string}
*/
function padZeroes(bits, n) {
// padded to multiple of n
if (bits.length % n != 0) {
let nPad = n - bits.length % n;
bits = (new Array(nPad)).fill('0').join('') + bits;
}
return bits;
}
/**
* Converts a 8 bit integer number into a bit string with a "0b" prefix.
* The result is padded with leading zeroes to become 'n' chars long ('2 + n' chars long if you count the "0b" prefix).
* @example
* byteToBitString(7) => "0b00000111"
* @param {number} b
* @param {number} n
* @returns {string}
*/
function byteToBitString(b, n = 8) {
let s = padZeroes(b.toString(2), n);
return "0b" + s;
}
/**
* Converts a hexadecimal representation of bytes into an actual list of uint8 bytes.
* @example
* hexToBytes("00ff34") => [0, 255, 52]
* @param {string} hex
* @returns {number[]}
*/
function hexToBytes(hex) {
let bytes = [];
for (let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.slice(i, i + 2), 16));
}
return bytes;
}
/**
* Converts a list of uint8 bytes into its hexadecimal string representation.
* @example
* bytesToHex([0, 255, 52]) => "00ff34"
* @param {number[]} bytes
* @returns {string}
*/
function bytesToHex(bytes) {
let parts = [];
for (let b of bytes) {
parts.push(padZeroes(b.toString(16), 2));
}
return parts.join('');
}
/**
* Encodes a string into a list of uint8 bytes using UTF-8 encoding.
* @example
* stringToBytes("hello world") => [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
* @param {string} str
* @returns {number[]}
*/
function stringToBytes(str) {
return Array.from((new TextEncoder()).encode(str));
}
/**
* Decodes a list of uint8 bytes into a string using UTF-8 encoding.
* @example
* bytesToString([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]) => "hello world"
* @param {number[]} bytes
* @returns {string}
*/
function bytesToString(bytes) {
return (new TextDecoder("utf-8", {fatal: true})).decode((new Uint8Array(bytes)).buffer);
}
/**
* Replaces the tab characters of a string with spaces.
* This is used to create a prettier IR (which is built-up from many template js strings in this file, which might contain tabs depending on the editor used)
* @example
* replaceTabs("\t\t\t") => [TAB, TAB, TAB].join("")
* @param {string} str
* @returns {string}
*/
function replaceTabs(str) {
return str.replace(new RegExp("\t", "g"), TAB);
}
/**
* Unwraps cbor byte arrays. Returns a list of uint8 bytes without the cbor tag.
* This function unwraps one level, so must be called twice to unwrap the text envelopes of plutus scripts.
* (for some reason the text envelopes is cbor wrapped in cbor)
* @example
* bytesToHex(unwrapCborBytes(hexToBytes("4e4d01000033222220051200120011"))) => "4d01000033222220051200120011"
* @param {number[]} bytes
* @returns {number[]}
*/
function unwrapCborBytes(bytes) {
if (bytes.length == 0) {
throw new Error("expected at least one cbor byte");
}
return PlutusCoreData.decodeCBORByteArray(bytes);
}
/**
* Wraps byte arrays with a cbor tag so they become valid cbor byte arrays.
* Roughly the inverse of unwrapCborBytes.
* @example
* bytesToHex(wrapCborBytes(hexToBytes("4d01000033222220051200120011"))) => "4e4d01000033222220051200120011"
* @param {number[]} bytes
* @returns {number[]}
*/
function wrapCborBytes(bytes) {
return PlutusCoreData.encodeCBORByteArray(bytes, false);
}
/**
* Read non-byte aligned numbers
*/
class BitReader {
#view;
#pos;
#truncate;
/**
* @param {number[]} bytes
* @param {boolean} truncate - if true then read last bits as low part of number, if false pad with zero bits
*/
constructor(bytes, truncate = true) {
this.#view = new Uint8Array(bytes);
this.#pos = 0; // bit position, not byte position
this.#truncate = truncate;
}
/**
* @returns {boolean}
*/
eof() {
return idiv(this.#pos, 8) >= this.#view.length;
}
/**
* Reads a number of bits (<= 8) and returns the result as an unsigned number
* @param {number} n - number of bits to read
* @returns {number}
*/
readBits(n) {
assert(n <= 8, "reading more than 1 byte");
let leftShift = 0;
if (this.#pos + n > this.#view.length * 8) {
let newN = (this.#view.length*8 - this.#pos);
if (!this.#truncate) {
leftShift = n - newN;
}
n = newN;
}
assert(n > 0, "eof");
// it is assumed we don't need to be at the byte boundary
let res = 0;
let i0 = this.#pos;
for (let i = this.#pos + 1; i <= this.#pos + n; i++) {
if (i % 8 == 0) {
let nPart = i - i0;
res += imask(this.#view[idiv(i, 8) - 1], i0 % 8, 8) << (n - nPart);
i0 = i;
} else if (i == this.#pos + n) {
res += imask(this.#view[idiv(i, 8)], i0 % 8, i % 8);
}
}
this.#pos += n;
return res << leftShift;
}
/**
* Moves position to next byte boundary
* @param {boolean} force - if true then move to next byte boundary if already at byte boundary
*/
moveToByteBoundary(force = false) {
if (this.#pos % 8 != 0) {
let n = 8 - this.#pos % 8;
void this.readBits(n);
} else if (force) {
this.readBits(8);
}
}
/**
* Reads 8 bits
* @returns {number}
*/
readByte() {
return this.readBits(8);
}
/**
* Dumps remaining bits we #pos isn't yet at end.
* This is intended for debugging use.
*/
dumpRemainingBits() {
if (!this.eof()) {
console.log("remaining bytes:");
for (let first = true, i = idiv(this.#pos, 8); i < this.#view.length; first = false, i++) {
if (first && this.#pos % 8 != 0) {
console.log(byteToBitString(imask(this.#view[i], this.#pos % 8, 8) << 8 - this.#pos % 7));
} else {
console.log(byteToBitString(this.#view[i]));
}
}
} else {
console.log("eof");
}
}
}
/**
* BitWriter turns a string of '0's and '1's into a list of bytes.
* Finalization pads the bits using '0*1' if not yet aligned with the byte boundary.
*/
class BitWriter {
/**
* Concatenated and padded upon finalization
* @type {string[]}
*/
#parts;
/**
* Number of bits written so far
* @type {number}
*/
#n;
constructor() {
this.#parts = [];
this.#n = 0;
}
/**
* @type {number}
*/
get length() {
return this.#n;
}
/**
* Write a string of '0's and '1's to the BitWriter.
* @param {string} bitChars
*/
write(bitChars) {
for (let c of bitChars) {
if (c != '0' && c != '1') {
throw new Error("bad bit char");
}
}
this.#parts.push(bitChars);
this.#n += bitChars.length;
}
/**
* @param {number} byte
*/
writeByte(byte) {
this.write(padZeroes(byte.toString(2), 8));
}
/**
* Add padding to the BitWriter in order to align with the byte boundary.
* If 'force == true' then 8 bits are added if the BitWriter is already aligned.
* @param {boolean} force
*/
padToByteBoundary(force = false) {
let nPad = 0;
if (this.#n % 8 != 0) {
nPad = 8 - this.#n % 8;
} else if (force) {
nPad = 8;
}
if (nPad != 0) {
let padding = (new Array(nPad)).fill('0');
padding[nPad - 1] = '1';
this.#parts.push(padding.join(''));
this.#n += nPad;
}
}
/**
* Pads the BitWriter to align with the byte boundary and returns the resulting bytes.
* @param {boolean} force - force padding (will add one byte if already aligned)
* @returns {number[]}
*/
finalize(force = true) {
this.padToByteBoundary(force);
let chars = this.#parts.join('');
let bytes = [];
for (let i = 0; i < chars.length; i += 8) {
let byteChars = chars.slice(i, i + 8);
let byte = parseInt(byteChars, 2);
bytes.push(byte);
}
return bytes;
}
}
/**
* Rfc 4648 base32 alphabet
* @type {string}
*/
const DEFAULT_BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
/**
* Bech32 base32 alphabet
* @type {string}
*/
const BECH32_BASE32_ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
/**
* Function that generates a random number between 0 and 1
* @typedef {() => number} NumberGenerator
*/
/**
* A collection of cryptography primitives are included here in order to avoid external dependencies
* mulberry32: random number generator
* base32 encoding and decoding
* bech32 encoding, checking, and decoding
* sha2, sha3 and blake2b hashing
*/
class Crypto {
/**
* Returns a simple random number generator
* @param {number} seed
* @returns {NumberGenerator} - a random number generator
*/
static mulberry32(seed) {
/**
* @type {NumberGenerator}
*/
return function() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
/**
* Alias for rand generator of choice
* @param {number} seed
* @returns {NumberGenerator} - the random number generator function
*/
static rand(seed) {
return this.mulberry32(seed);
}
/**
* Encode bytes in special base32.
* @example
* Crypto.encodeBase32(stringToBytes("f")) => "my"
* @example
* Crypto.encodeBase32(stringToBytes("fo")) => "mzxq"
* @example
* Crypto.encodeBase32(stringToBytes("foo")) => "mzxw6"
* @example
* Crypto.encodeBase32(stringToBytes("foob")) => "mzxw6yq"
* @example
* Crypto.encodeBase32(stringToBytes("fooba")) => "mzxw6ytb"
* @example
* Crypto.encodeBase32(stringToBytes("foobar")) => "mzxw6ytboi"
* @param {number[]} bytes - uint8 numbers
* @param {string} alphabet - list of chars
* @return {string}
*/
static encodeBase32(bytes, alphabet = DEFAULT_BASE32_ALPHABET) {
return Crypto.encodeBase32Bytes(bytes).map(c => alphabet[c]).join("");
}
/**
* Internal method
* @param {number[]} bytes
* @returns {number[]} - list of numbers between 0 and 32
*/
static encodeBase32Bytes(bytes) {
let result = [];
let reader = new BitReader(bytes, false);
while (!reader.eof()) {
result.push(reader.readBits(5));
}
return result;
}
/**
* Decode base32 string into bytes.
* @example
* bytesToString(Crypto.decodeBase32("my")) => "f"
* @example
* bytesToString(Crypto.decodeBase32("mzxq")) => "fo"
* @example
* bytesToString(Crypto.decodeBase32("mzxw6")) => "foo"
* @example
* bytesToString(Crypto.decodeBase32("mzxw6yq")) => "foob"
* @example
* bytesToString(Crypto.decodeBase32("mzxw6ytb")) => "fooba"
* @example
* bytesToString(Crypto.decodeBase32("mzxw6ytboi")) => "foobar"
* @param {string} encoded
* @param {string} alphabet
* @return {number[]}
*/
static decodeBase32(encoded, alphabet = DEFAULT_BASE32_ALPHABET) {
let writer = new BitWriter();
let n = encoded.length;
for (let i = 0; i < n; i++) {
let c = encoded[i];
let code = alphabet.indexOf(c.toLowerCase());
if (i == n - 1) {
// last, make sure we align to byte
let nCut = n*5 - 8*Math.floor(n*5/8);
let bits = padZeroes(code.toString(2), 5)
writer.write(bits.slice(0, 5 - nCut));
} else {
let bits = padZeroes(code.toString(2), 5);
writer.write(bits);
}
}
let result = writer.finalize(false);
return result;
}
/**
* Expand human readable prefix of the bech32 encoding so it can be used in the checkSum
* Internal method.
* @param {string} hrp
* @returns {number[]}
*/
static expandBech32HumanReadablePart(hrp) {
let bytes = [];
for (let c of hrp) {
bytes.push(c.charCodeAt(0) >> 5);
}
bytes.push(0);
for (let c of hrp) {
bytes.push(c.charCodeAt(0) & 31);
}