-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathunit_tests_crypto_utils.html
More file actions
2341 lines (2031 loc) · 109 KB
/
unit_tests_crypto_utils.html
File metadata and controls
2341 lines (2031 loc) · 109 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CryptoUtils - Interactive Test Suite</title>
<style>
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
background: #1a1a2e;
color: #eee;
line-height: 1.6;
}
h1 { color: #00d4ff; margin-bottom: 5px; }
h2 { color: #00d4ff; border-bottom: 1px solid #333; padding-bottom: 10px; margin-top: 30px; }
h3 { color: #888; margin: 0 0 20px 0; font-weight: normal; }
.test-section {
background: #16213e;
border-radius: 8px;
padding: 20px;
margin: 15px 0;
}
.test-section h4 {
margin: 0 0 15px 0;
color: #fff;
font-size: 16px;
}
.test-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 10px;
align-items: center;
}
input, textarea, select {
background: #0f0f23;
border: 1px solid #333;
color: #fff;
padding: 10px;
border-radius: 4px;
font-family: monospace;
font-size: 14px;
}
input { flex: 1; min-width: 200px; }
textarea { width: 100%; min-height: 80px; resize: vertical; }
button {
background: #00d4ff;
color: #000;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
white-space: nowrap;
}
button:hover { background: #00a8cc; }
.output {
background: #0f0f23;
border: 1px solid #333;
border-radius: 4px;
padding: 15px;
margin-top: 10px;
font-family: monospace;
font-size: 13px;
word-break: break-all;
white-space: pre-wrap;
}
.success { color: #00ff88; }
.error { color: #ff4444; }
.info { color: #00d4ff; }
.warn { color: #ffaa00; }
#test-results {
background: #0f0f23;
border-radius: 8px;
padding: 20px;
margin: 20px 0;
font-family: monospace;
font-size: 13px;
max-height: 400px;
overflow-y: auto;
}
.test-pass { color: #00ff88; }
.test-fail { color: #ff4444; }
.test-count {
font-size: 18px;
margin-bottom: 15px;
padding-bottom: 15px;
border-bottom: 1px solid #333;
}
a { color: #00d4ff; }
.note {
background: #1e3a5f;
border-left: 3px solid #00d4ff;
padding: 10px 15px;
margin: 10px 0;
font-size: 13px;
}
</style>
</head>
<body>
<h1>🔐 CryptoUtils</h1>
<h3>Standalone Cryptocurrency Utilities Library v<span id="version"></span></h3>
<div class="note">
<strong>Dependencies:</strong> <a href="https://github.com/bitrequest/bitrequest.github.io/blob/master/assets_js_lib_sjcl.js">sjcl.js</a> → <a href="https://github.com/bitrequest/bitrequest.github.io/blob/master/assets_js_lib_crypto_utils.js">crypto_utils.js</a><br>
<strong>Test phrase:</strong> <a href="https://github.com/bitcoinbook/bitcoinbook/blob/f8b883dcd4e3d1b9adf40fed59b7e898fbd9241f/ch05.asciidoc">army van defense carry jealous true garbage claim echo media make crunch</a><br>
<strong>Repository:</strong> <a href="https://github.com/bitrequest/crypto-utils-js">github.com/bitrequest/crypto-utils-js</a>
</div>
<!-- Automated Tests -->
<h2>🧪 Automated Unit Tests</h2>
<button onclick="runAllTests()">Run All Tests</button>
<div id="test-results"></div>
<!-- Interactive Tools -->
<h2>🛠️ Interactive Tools</h2>
<!-- Key Generation -->
<div class="test-section">
<h4>Private Key → Public Key (secp256k1 + Ed25519)</h4>
<div class="test-row">
<select id="privkey-coin" onchange="onPrivkeyCoinChange()">
<option value="">-- Select coin to auto-fill --</option>
<optgroup label="secp256k1">
<option value="btc-legacy">Bitcoin (Legacy)</option>
<option value="btc-segwit">Bitcoin (SegWit)</option>
<option value="ltc-legacy">Litecoin (Legacy)</option>
<option value="ltc-segwit">Litecoin (SegWit)</option>
<option value="dash">Dash</option>
<option value="doge">Dogecoin</option>
<option value="eth">Ethereum</option>
<option value="bch">Bitcoin Cash</option>
<option value="kaspa">Kaspa</option>
</optgroup>
<optgroup label="Ed25519">
<option value="nimiq">Nimiq (SHA-512)</option>
<option value="nano">Nano (Blake2b-512)</option>
</optgroup>
</select>
</div>
<div class="test-row">
<input type="text" id="privkey-input" placeholder="Enter 32-byte hex private key or WIF" value="">
<button onclick="testKeyGen()">Generate Public Key</button>
</div>
<div class="note">Select a coin to auto-fill the private key derived from the test seed phrase</div>
<div class="output" id="privkey-output"></div>
</div>
<!-- Address Generation -->
<div class="test-section">
<h4>Public Key → Address</h4>
<div class="test-row">
<select id="address-coin" onchange="onAddressCoinChange()">
<option value="btc-legacy">Bitcoin (Legacy)</option>
<option value="btc-segwit">Bitcoin (SegWit)</option>
<option value="ltc-legacy">Litecoin (Legacy)</option>
<option value="ltc-segwit">Litecoin (SegWit)</option>
<option value="dash">Dash</option>
<option value="doge">Dogecoin</option>
</select>
<input type="text" id="pubkey-input" placeholder="Compressed public key (33 bytes hex)" value="">
<button onclick="testAddressGen()">Generate Address</button>
</div>
<div class="output" id="address-output"></div>
</div>
<!-- Ethereum Address -->
<div class="test-section">
<h4>Public Key → Ethereum Address</h4>
<div class="test-row">
<input type="text" id="eth-pubkey-input" placeholder="Uncompressed public key (65 bytes hex, starts with 04)" value="">
<button onclick="testEthAddress()">Generate ETH Address</button>
</div>
<div class="note">Pre-filled with public key derived from the test mnemonic phrase</div>
<div class="output" id="eth-output"></div>
</div>
<!-- Bitcoin Cash Address -->
<div class="test-section">
<h4>Public Key → Bitcoin Cash Address</h4>
<div class="test-row">
<input type="text" id="bch-pubkey-input" placeholder="Compressed public key" value="">
<button onclick="testBchAddress()">Generate BCH Address</button>
</div>
<div class="note">Pre-filled with public key derived from the test mnemonic phrase</div>
<div class="output" id="bch-output"></div>
</div>
<!-- Kaspa Address -->
<div class="test-section">
<h4>Public Key → Kaspa Address</h4>
<div class="test-row">
<input type="text" id="kaspa-pubkey-input" placeholder="Compressed public key (33 bytes hex)" value="">
<button onclick="testKaspaAddress()">Generate Kaspa Address</button>
</div>
<div class="note">Kaspa uses 8-character checksum (40-bit) bech32 variant with x-only pubkey. Pre-filled with test pubkey.</div>
<div class="output" id="kaspa-output"></div>
</div>
<!-- Nimiq Address -->
<div class="test-section">
<h4>Private Key → Nimiq Address (Ed25519 + Blake2b)</h4>
<div class="test-row">
<input type="text" id="nimiq-privkey-input" placeholder="32-byte hex Ed25519 private key" value="">
<button onclick="testNimiqAddress()">Generate Nimiq Address</button>
</div>
<div class="note">Nimiq: Ed25519 pubkey (SHA-512) → Blake2b-256 → first 20 bytes → custom base32 + IBAN checksum. Pre-filled with test key.</div>
<div class="output" id="nimiq-output"></div>
</div>
<!-- Nano Address -->
<div class="test-section">
<h4>Private Key → Nano Address (Ed25519-Blake2b)</h4>
<div class="test-row">
<input type="text" id="nano-privkey-input" placeholder="32-byte hex Ed25519 private key" value="">
<button onclick="testNanoAddress()">Generate Nano Address</button>
</div>
<div class="note">Nano: Ed25519 pubkey (Blake2b-512 variant) → nano_ + base32(pubkey) + base32(Blake2b-5 checksum). Pre-filled with test key.</div>
<div class="output" id="nano-output"></div>
</div>
<!-- Blake2b Hashing -->
<div class="test-section">
<h4>Blake2b Hash</h4>
<div class="test-row">
<input type="text" id="blake2b-input" placeholder="Enter text or hex" value="abc">
<select id="blake2b-outlen">
<option value="32">32 bytes (256-bit)</option>
<option value="64">64 bytes (512-bit)</option>
<option value="5">5 bytes (Nano checksum)</option>
<option value="20">20 bytes (Nimiq address)</option>
</select>
<button onclick="testBlake2b()">Hash</button>
</div>
<div class="note">Blake2b with variable output length. Used for Nimiq addresses (32-byte), Nano keys (64-byte) and checksums (5-byte).</div>
<div class="output" id="blake2b-output"></div>
</div>
<!-- NANO to RAW -->
<div class="test-section">
<h4>NANO → RAW Conversion</h4>
<div class="test-row">
<input type="text" id="nano-raw-input" placeholder="Amount in NANO" value="1.5">
<button onclick="testNanoToRaw()">Convert</button>
</div>
<div class="note">1 NANO = 10³⁰ RAW (30 decimal places)</div>
<div class="output" id="nano-raw-output"></div>
</div>
<!-- WIF -->
<div class="test-section">
<h4>Private Key → WIF (Wallet Import Format)</h4>
<div class="test-row">
<input type="text" id="wif-input" placeholder="32-byte hex private key" value="">
<select id="wif-network">
<option value="80">Bitcoin Mainnet (80)</option>
<option value="ef">Bitcoin Testnet (ef)</option>
<option value="b0">Litecoin Mainnet (b0)</option>
</select>
<button onclick="testWif()">Convert to WIF</button>
</div>
<div class="output" id="wif-output"></div>
</div>
<!-- Hex/Bytes Conversion -->
<div class="test-section">
<h4>Hex ↔ Bytes Conversion</h4>
<div class="test-row">
<input type="text" id="hex-input" placeholder="Enter hex string (e.g., bitrequest)" value="bitrequest">
<button onclick="testHexBytes()">Convert</button>
</div>
<div class="output" id="hex-output"></div>
</div>
<!-- Base58 -->
<div class="test-section">
<h4>Base58 Encoding/Decoding</h4>
<div class="test-row">
<input type="text" id="b58-input" placeholder="Enter hex to encode">
<button onclick="testBase58Encode()">Encode</button>
<button onclick="testBase58Decode()">Decode</button>
</div>
<div class="output" id="b58-output"></div>
</div>
<!-- Base58Check -->
<div class="test-section">
<h4>Base58Check (with checksum)</h4>
<div class="test-row">
<input type="text" id="b58check-input" placeholder="Enter hex payload">
<button onclick="testBase58CheckEncode()">Encode</button>
<button onclick="testBase58CheckDecode()">Decode</button>
</div>
<div class="output" id="b58check-output"></div>
</div>
<!-- Bech32 -->
<div class="test-section">
<h4>Bech32 Encoding/Decoding</h4>
<div class="test-row">
<input type="text" id="bech32-input" placeholder="Bech32 address">
<button onclick="testBech32Decode()">Decode</button>
</div>
<div class="test-row">
<input type="text" id="bech32-hrp" placeholder="HRP (e.g., bc)" value="bc" style="max-width: 80px;">
<input type="text" id="bech32-data" placeholder="Hex data to encode">
<button onclick="testBech32Encode()">Encode</button>
</div>
<div class="output" id="bech32-output"></div>
</div>
<!-- Hashing -->
<div class="test-section">
<h4>Hash Functions</h4>
<div class="test-row">
<input type="text" id="hash-input" placeholder="Enter text or hex" value="hello">
<select id="hash-type">
<option value="sha256">SHA256 (text)</option>
<option value="sha256hex">SHA256 (hex input)</option>
<option value="hash160">Hash160 (hex input)</option>
<option value="ripemd160">RIPEMD160 (hex input)</option>
<option value="keccak256">Keccak-256 (hex input)</option>
<option value="blake2b-256">Blake2b-256 (hex input)</option>
<option value="blake2b-512">Blake2b-512 (hex input)</option>
</select>
<button onclick="testHash()">Hash</button>
</div>
<div class="output" id="hash-output"></div>
</div>
<!-- AES Encryption -->
<div class="test-section">
<h4>AES-GCM Encryption/Decryption</h4>
<div class="test-row">
<input type="text" id="aes-plaintext" placeholder="Plaintext" value="Hello, World!" style="flex: 2;">
<input type="text" id="aes-password" placeholder="Password (16 chars)" value="mypassword123456">
</div>
<div class="test-row">
<button onclick="testAesEncrypt()">Encrypt</button>
<button onclick="testAesDecrypt()">Decrypt</button>
</div>
<div class="note">Password is padded/trimmed to 16 bytes and converted to base64 for AES-128</div>
<div class="output" id="aes-output"></div>
</div>
<!-- LNURL -->
<div class="test-section">
<h4>LNURL (Lightning Network)</h4>
<div class="test-row">
<input type="text" id="lnurl-decode-input" placeholder="Enter LNURL to decode" value="">
<button onclick="testLnurlDecode()">Decode</button>
</div>
<div class="test-row">
<input type="text" id="lnurl-encode-input" placeholder="Enter URL to encode" value="">
<button onclick="testLnurlEncode()">Encode</button>
</div>
<div class="output" id="lnurl-output"></div>
</div>
<!-- Script Hash -->
<div class="test-section">
<h4>Address → Script Hash (Electrum format)</h4>
<div class="test-row">
<input type="text" id="scripthash-input" placeholder="Bitcoin/Litecoin address">
<button onclick="testScriptHash()">Get Script Hash</button>
</div>
<div class="output" id="scripthash-output"></div>
</div>
<!-- String Utilities -->
<div class="test-section">
<h4>String Utilities (BIP39 helpers)</h4>
<div class="test-row">
<input type="text" id="string-input" placeholder="Enter string" value=" Hello World ">
<button onclick="testStringUtils()">Process</button>
</div>
<div class="output" id="string-output"></div>
</div>
<!-- BigInt / Number Conversion -->
<div class="test-section">
<h4>Hex ↔ Number Conversion</h4>
<div class="test-row">
<input type="text" id="bigint-input" placeholder="Enter hex or decimal number" value="ffffffff">
<button onclick="testBigIntConvert()">Convert</button>
</div>
<div class="output" id="bigint-output"></div>
</div>
<!-- Modular Arithmetic -->
<div class="test-section">
<h4>Modular Arithmetic (secp256k1)</h4>
<div class="test-row">
<input type="text" id="mod-a" placeholder="Value a (hex)" value="ff" style="flex: 1;">
<select id="mod-op" style="width: 120px;">
<option value="mod">a mod P</option>
<option value="invert">invert(a)</option>
<option value="sqrt">sqrt(a)</option>
</select>
<button onclick="testModArith()">Calculate</button>
</div>
<div class="note">Uses secp256k1 prime P = 2²⁵⁶ - 2³² - 977</div>
<div class="output" id="mod-output"></div>
</div>
<!-- Scripts -->
<script src="assets_js_lib_sjcl.js"></script>
<script src="assets_js_lib_crypto_utils.js"></script>
<script>
// Display version
document.getElementById("version").textContent = CryptoUtils.VERSION || "1.1.0";
// Shorthand reference to test constants from library
const TestVector = CryptoUtils.crypto_utils_const,
test_privkey = TestVector.test_privkey,
test_address = TestVector.test_address,
test_address_bech32 = TestVector.test_address_bech32,
test_pubkey = TestVector.test_pubkey,
test_pubkey_bech32 = TestVector.test_pubkey_bech32,
test_pubkey_kaspa = TestVector.test_pubkey_kaspa,
test_address_eth = TestVector.test_address_eth,
test_bch_legacy_address = TestVector.test_bch_legacy_address,
test_bch_cashaddr = TestVector.test_bch_cashaddr,
b58_payload = "00b3ddf67ea6bc720cd2020107fc4aae81f518b04f";
// Test framework
const tests = [];
let passed = 0,
failed = 0;
function test(name, fn) {
tests.push({
name,
fn
});
}
function assertEqual(actual, expected, msg) {
if (actual !== expected) {
throw new Error(msg + " Expected: " + expected + " Got: " + actual);
}
}
function assertTrue(condition, msg) {
if (!condition) {
throw new Error(msg);
}
}
// Helper to log errors to console with full details
function logError(context, e) {
console.group("❌ " + context + " Error");
console.error("Message:", e.message || e);
console.error("Full error:", e);
if (e.stack) console.error("Stack:", e.stack);
console.groupEnd();
}
function assertArrayEqual(actual, expected, msg) {
if (actual.length !== expected.length) {
throw new Error(msg + " Length mismatch: " + actual.length + " vs " + expected.length);
}
for (let i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) {
throw new Error(msg + " Mismatch at index " + i);
}
}
}
// ============================================================
// BUILT-IN LIBRARY TESTS
// ============================================================
test("CryptoUtils.test_crypto_api: verify crypto API", () => {
assertTrue(CryptoUtils.test_crypto_api() === true, "crypto API should be available");
});
test("CryptoUtils.test_bigint: verify BigInt support", () => {
assertTrue(CryptoUtils.test_bigint() === true, "BigInt should be functional");
});
test("CryptoUtils.test_secp256k1: verify secp256k1 derivation", () => {
assertTrue(CryptoUtils.test_secp256k1() === true, "secp256k1 derivation should work");
});
test("CryptoUtils.test_bech32: verify bech32 encoding", () => {
assertTrue(CryptoUtils.test_bech32() === true, "bech32 encoding should work");
});
test("CryptoUtils.test_cashaddr: verify cashaddr encoding", () => {
assertTrue(CryptoUtils.test_cashaddr() === true, "cashaddr encoding should work");
});
test("CryptoUtils.test_keccak256: verify keccak256/ETH address", () => {
assertTrue(CryptoUtils.test_keccak256() === true, "keccak256 should work");
});
test("CryptoUtils.test_aes: verify AES encryption", () => {
assertTrue(CryptoUtils.test_aes() === true, "AES encryption should work");
});
test("CryptoUtils.test_kaspa: verify Kaspa address encoding", () => {
assertTrue(CryptoUtils.test_kaspa() === true, "Kaspa address encoding should work");
});
// ============================================================
// UNIT TESTS
// ============================================================
// === Core Helpers Tests ===
test("uint_8array: create typed array", () => {
const result = CryptoUtils.uint_8array([1, 2, 3]);
assertTrue(result instanceof Uint8Array, "Should be Uint8Array");
assertEqual(result.length, 3, "Length should be 3");
});
test("buffer: encode string to UTF-8", () => {
const result = CryptoUtils.buffer("hello");
assertTrue(result instanceof Uint8Array, "Should be Uint8Array");
assertEqual(result.length, 5, "Length should be 5");
});
test("unbuffer: decode UTF-8 to string", () => {
const bytes = new Uint8Array([104, 101, 108, 108, 111]);
const result = CryptoUtils.unbuffer(bytes);
assertEqual(result, "hello", "Should decode to hello");
});
test("buf2hex: convert buffer to hex", () => {
const result = CryptoUtils.buf2hex([222, 173, 190, 239]);
assertEqual(result, "deadbeef", "Should be deadbeef");
});
test("is_hex: validate hex string", () => {
assertTrue(CryptoUtils.is_hex("deadbeef"), "Valid hex");
assertTrue(CryptoUtils.is_hex("DEADBEEF"), "Valid uppercase hex");
assertTrue(!CryptoUtils.is_hex("ghij"), "Invalid hex");
assertTrue(!CryptoUtils.is_hex(""), "Empty string");
});
test("str_pad: pad string with zeros", () => {
const result = CryptoUtils.str_pad("abc", 6);
assertEqual(result, "000abc", "Should pad to 6 chars");
});
test("dec_to_hex: convert decimal to hex", () => {
assertEqual(CryptoUtils.dec_to_hex(255), "ff", "255 -> ff");
assertEqual(CryptoUtils.dec_to_hex(16), "10", "16 -> 10");
assertEqual(CryptoUtils.dec_to_hex(0), "0", "0 -> 0");
});
test("hex_to_dec: convert hex to BigInt", () => {
assertEqual(CryptoUtils.hex_to_dec("ff"), 255n, "ff -> 255n");
assertEqual(CryptoUtils.hex_to_dec("10"), 16n, "10 -> 16n");
});
test("hex_to_number_string: hex to decimal string", () => {
assertEqual(CryptoUtils.hex_to_number_string("ff"), "255", "ff -> 255");
});
test("hex_to_number_string: multi-byte value", () => {
assertEqual(CryptoUtils.hex_to_number_string("ffff"), "65535", "ffff -> 65535");
});
test("hex_to_int: hex to integer", () => {
assertEqual(CryptoUtils.hex_to_int("ff"), 255, "ff -> 255");
assertEqual(CryptoUtils.hex_to_int("00"), 0, "00 -> 0");
});
test("pad_binary: pad binary string", () => {
assertEqual(CryptoUtils.pad_binary("1", 8), "00000001", "Pad to 8 bits");
assertEqual(CryptoUtils.pad_binary("11111111", 8), "11111111", "Already 8 bits");
});
test("pad64: pad to 64 hex chars", () => {
assertEqual(CryptoUtils.pad64(1n).length, 64, "Should be 64 chars");
assertTrue(CryptoUtils.pad64(1n).endsWith("1"), "Should end with 1");
assertTrue(CryptoUtils.pad64(1n).startsWith("0"), "Should start with 0");
});
test("concat_bytes: concatenate byte arrays", () => {
const a = new Uint8Array([1, 2]);
const b = new Uint8Array([3, 4]);
const result = CryptoUtils.concat_bytes(a, b);
assertEqual(result.length, 4, "Length should be 4");
assertEqual(CryptoUtils.bytes_to_hex(result), "01020304", "Correct concatenation");
});
test("concat_bytes: multiple arrays", () => {
const a = new Uint8Array([1]);
const b = new Uint8Array([2]);
const c = new Uint8Array([3]);
const result = CryptoUtils.concat_bytes(a, b, c);
assertEqual(result.length, 3, "Length should be 3");
});
test("encode_varint: small value (< 128)", () => {
const result = CryptoUtils.encode_varint(100);
assertEqual(result.length, 1, "Single byte");
assertEqual(result[0], 100, "Correct value");
});
test("encode_varint: medium value (>= 128)", () => {
const result = CryptoUtils.encode_varint(300);
assertEqual(result.length, 2, "Two bytes for 300");
});
test("encode_varint: boundary value (127)", () => {
const result = CryptoUtils.encode_varint(127);
assertEqual(result.length, 1, "Single byte for 127");
assertEqual(result[0], 127, "Correct value");
});
test("encode_varint: boundary value (128)", () => {
const result = CryptoUtils.encode_varint(128);
assertEqual(result.length, 2, "Two bytes for 128");
});
// === Hex/Bytes Conversion Tests ===
test("hex_to_bytes: basic conversion", () => {
const result = CryptoUtils.hex_to_bytes("deadbeef");
assertEqual(result.length, 4, "4 bytes");
assertEqual(result[0], 0xde, "First byte");
assertEqual(result[3], 0xef, "Last byte");
});
test("hex_to_bytes: odd length padding", () => {
const result = CryptoUtils.hex_to_bytes("abc");
assertEqual(result.length, 2, "Pads odd length");
assertEqual(result[0], 0x0a, "Padded first byte");
});
test("hex_to_bytes: empty string", () => {
const result = CryptoUtils.hex_to_bytes("");
assertEqual(result.length, 0, "Empty array");
});
test("bytes_to_hex: basic conversion", () => {
const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
assertEqual(CryptoUtils.bytes_to_hex(bytes), "deadbeef", "Correct hex");
});
test("bytes_to_hex: single byte", () => {
const bytes = new Uint8Array([0x0f]);
assertEqual(CryptoUtils.bytes_to_hex(bytes), "0f", "Padded single byte");
});
test("hex_to_bytes/bytes_to_hex: roundtrip", () => {
const original = "deadbeef";
const bytes = CryptoUtils.hex_to_bytes(original);
const back = CryptoUtils.bytes_to_hex(bytes);
assertEqual(back, original, "Roundtrip matches");
});
test("hex_to_number: convert to BigInt", () => {
assertEqual(CryptoUtils.hex_to_number("ff"), 255n, "ff -> 255n");
assertEqual(CryptoUtils.hex_to_number("0100"), 256n, "0100 -> 256n");
});
test("bytes_to_number: convert bytes to BigInt", () => {
const bytes = new Uint8Array([0x01, 0x00]);
assertEqual(CryptoUtils.bytes_to_number(bytes), 256n, "0x0100 -> 256n");
});
// === SJCL Bit Operations Tests ===
test("to_bits: convert string to bits", () => {
const bits = CryptoUtils.to_bits("hello");
assertTrue(Array.isArray(bits), "Should return array");
});
test("hex_to_bits: convert hex to bits", () => {
const bits = CryptoUtils.hex_to_bits("deadbeef");
assertTrue(Array.isArray(bits), "Should return array");
});
test("from_bits: convert bits to hex", () => {
const bits = CryptoUtils.hex_to_bits("deadbeef");
const hex = CryptoUtils.from_bits(bits);
assertEqual(hex, "deadbeef", "Roundtrip matches");
});
test("bit_length: correct length", () => {
const bits = CryptoUtils.hex_to_bits("ff");
assertEqual(CryptoUtils.bit_length(bits), 8, "1 byte = 8 bits");
});
test("bit_length: multi-byte", () => {
const bits = CryptoUtils.hex_to_bits("ffff");
assertEqual(CryptoUtils.bit_length(bits), 16, "2 bytes = 16 bits");
});
test("concat_array: concatenate bit arrays", () => {
const a = CryptoUtils.hex_to_bits("dead");
const b = CryptoUtils.hex_to_bits("beef");
const result = CryptoUtils.concat_array(a, b);
assertEqual(CryptoUtils.from_bits(result), "deadbeef", "Concatenated");
});
// === String Utilities Tests ===
test("clean_string: normalize whitespace", () => {
assertEqual(CryptoUtils.clean_string(" hello world "), "hello world", "Clean whitespace");
});
test("clean_string: tabs and newlines", () => {
assertEqual(CryptoUtils.clean_string("hello\t\nworld"), "hello world", "Clean tabs/newlines");
});
test("split_words: split mnemonic", () => {
const result = CryptoUtils.split_words("one two three");
assertEqual(result.length, 3, "3 words");
assertEqual(result[0], "one", "First word");
});
test("split_words: extra whitespace", () => {
const result = CryptoUtils.split_words(" one two ");
assertEqual(result.length, 2, "2 words after trim");
});
test("join_words: join mnemonic", () => {
assertEqual(CryptoUtils.join_words(["one", "two", "three"]), "one two three", "Joined");
});
test("normalize_string: NFKD normalization", () => {
const result = CryptoUtils.normalize_string("café");
assertTrue(typeof result === "string", "Returns string");
});
// === Base Conversion Tests ===
test("binary_string_to_word_array: convert binary", () => {
const result = CryptoUtils.binary_string_to_word_array("11111111");
assertTrue(Array.isArray(result), "Returns array");
});
test("byte_array_to_word_array: convert bytes", () => {
const result = CryptoUtils.byte_array_to_word_array([255, 0]);
assertTrue(Array.isArray(result), "Returns array");
});
test("byte_array_to_binary_string: convert to binary", () => {
assertEqual(CryptoUtils.byte_array_to_binary_string([255]), "11111111", "255 -> 11111111");
assertEqual(CryptoUtils.byte_array_to_binary_string([0]), "00000000", "0 -> 00000000");
});
test("hex_string_to_binary_string: convert hex to binary", () => {
assertEqual(CryptoUtils.hex_string_to_binary_string("ff"), "11111111", "ff -> 11111111");
assertEqual(CryptoUtils.hex_string_to_binary_string("00"), "00000000", "00 -> 00000000");
});
// === Base58 Tests ===
test("b58enc/b58dec: roundtrip", () => {
const original = "deadbeef";
const encoded = CryptoUtils.b58enc(original, "hex");
const decoded = CryptoUtils.b58dec(encoded, "hex");
assertEqual(decoded, original, "Roundtrip matches");
});
test("b58enc: leading zeros preserved", () => {
const encoded = CryptoUtils.b58enc("0000deadbeef");
assertTrue(encoded.startsWith("11"), "Leading zeros become 1s");
});
test("b58enc_uint_array: encode Uint8Array", () => {
const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
const encoded = CryptoUtils.b58enc_uint_array(bytes);
assertTrue(typeof encoded === "string", "Returns string");
});
test("b58dec_uint_array: decode to Uint8Array", () => {
const encoded = CryptoUtils.b58enc("deadbeef");
const decoded = CryptoUtils.b58dec_uint_array(encoded);
assertTrue(decoded instanceof Uint8Array, "Returns Uint8Array");
});
test("b58check_encode: Bitcoin address test vector", () => {
const result = CryptoUtils.b58check_encode(b58_payload);
assertEqual(result, test_address, "Known address");
});
test("b58check_decode: verify checksum", () => {
const decoded = CryptoUtils.b58check_decode(test_address);
assertEqual(decoded, b58_payload, "Decode correctly");
});
test("b58check_encode/decode: roundtrip", () => {
const encoded = CryptoUtils.b58check_encode(b58_payload);
const decoded = CryptoUtils.b58check_decode(encoded);
assertEqual(decoded, b58_payload, "Roundtrip matches");
});
// === Bech32 Tests ===
test("bech32_decode: decode valid address", () => {
const result = CryptoUtils.bech32_decode(test_address_bech32);
assertEqual(result.hrp, "bc", "HRP should be bc");
assertEqual(result.data[0], 0, "Witness version 0");
});
test("bech32_decode: invalid returns null", () => {
const result = CryptoUtils.bech32_decode("bc1invalid");
assertEqual(result, null, "Should return null");
});
test("bech32_decode: Litecoin address", () => {
const result = CryptoUtils.bech32_decode("ltc1qc64rhsxzmnre94nw4spn6866gqhmcpp05suu3c");
assertEqual(result.hrp, "ltc", "HRP should be ltc");
});
test("bech32_encode/decode: roundtrip", () => {
const original = test_address_bech32;
const decoded = CryptoUtils.bech32_decode(original);
const encoded = CryptoUtils.bech32_encode("bc", decoded.data);
assertEqual(encoded, original, "Roundtrip matches");
});
test("to_words/from_words: roundtrip", () => {
const original = [0, 1, 2, 3, 255];
const words = CryptoUtils.to_words(original);
const back = CryptoUtils.from_words(words);
assertArrayEqual(back, original, "Roundtrip matches");
});
test("convert_bits: 8 to 5 bits", () => {
const data = [0xff];
const result = CryptoUtils.convert_bits(data, 8, 5, true);
assertTrue(Array.isArray(result), "Returns array");
});
test("bech32m_decode: Taproot vector", () => {
const taproot = "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0";
const decoded = CryptoUtils.bech32_decode(taproot);
assertEqual(decoded.encoding, "bech32m", "Should detect bech32m");
assertEqual(decoded.data[0], 1, "Witness version 1");
});
test("pub_to_address_bech32: generate native segwit", () => {
const address = CryptoUtils.pub_to_address_bech32("bc", test_pubkey_bech32);
assertEqual(address, test_address_bech32, "Known address");
});
test("pub_to_address_bech32: Litecoin", () => {
const address = CryptoUtils.pub_to_address_bech32("ltc", test_pubkey);
assertTrue(address.startsWith("ltc1q"), "Litecoin segwit prefix");
});
// === Kaspa Bech32 Tests (8-character checksum variant) ===
test("kaspa_polymod: basic computation", () => {
// Test with simple data array
const result = CryptoUtils.kaspa_polymod([0, 1, 2, 3, 4]);
assertTrue(typeof result === "number", "Returns number");
assertTrue(result >= 0, "Non-negative result");
});
test("kaspa_polymod: empty array returns 0", () => {
// c1 starts at 1, then c1 ^= 1 at end = 0
const result = CryptoUtils.kaspa_polymod([]);
assertEqual(result, 0, "Empty array returns 0 after final XOR");
});
test("kaspa_create_checksum: returns 8 values", () => {
const testData = [0, 1, 2, 3, 4, 5, 6, 7];
const checksum = CryptoUtils.kaspa_create_checksum("kaspa", testData);
assertEqual(checksum.length, 8, "Checksum has 8 values");
checksum.forEach(v => {
assertTrue(v >= 0 && v < 32, "Each value in bech32 range");
});
});
test("pub_to_kaspa_address: generate valid address", () => {
const address = CryptoUtils.pub_to_kaspa_address(test_pubkey_kaspa);
assertTrue(address.startsWith("kaspa:q"), "Starts with kaspa:q");
assertEqual(address.length, 67, "Kaspa address length (kaspa: prefix + 61 bech32 chars)");
});
test("pub_to_kaspa_address: known test vector", () => {
const address = CryptoUtils.pub_to_kaspa_address(test_pubkey_kaspa);
assertEqual(address, TestVector.test_address_kaspa, "Known Kaspa address matches");
});
test("pub_to_kaspa_address: different pubkeys produce different addresses", () => {
const addr1 = CryptoUtils.pub_to_kaspa_address(test_pubkey_kaspa);
const addr2 = CryptoUtils.pub_to_kaspa_address(test_pubkey);
assertTrue(addr1 !== addr2, "Different pubkeys give different addresses");
});
test("pub_to_kaspa_address: x-only extraction", () => {
// Kaspa uses x-only pubkey (strips the 02/03 prefix)
const compressedPub = "02" + "0".repeat(64);
const address = CryptoUtils.pub_to_kaspa_address(compressedPub);
assertTrue(address.startsWith("kaspa:q"), "Handles 02 prefix");
const compressedPub2 = "03" + "0".repeat(64);
const address2 = CryptoUtils.pub_to_kaspa_address(compressedPub2);
assertEqual(address, address2, "02 and 03 prefixed same x-coord give same address");
});
// === Elliptic Curve Tests ===
test("mod: positive modulo", () => {
assertEqual(CryptoUtils.mod(10n, 3n), 1n, "10 mod 3 = 1");
assertEqual(CryptoUtils.mod(-1n, 3n), 2n, "Negative handled");
});
test("mod: large numbers", () => {
const P = CryptoUtils.CURVE.P;
assertEqual(CryptoUtils.mod(P + 1n, P), 1n, "P+1 mod P = 1");
});
test("invert: modular inverse", () => {
const P = CryptoUtils.CURVE.P;
const a = 12345n;
const inv = CryptoUtils.invert(a, P);
assertEqual(CryptoUtils.mod(a * inv, P), 1n, "a * inv(a) = 1 mod P");
});
test("egcd: extended euclidean algorithm", () => {
const [gcd, x, y] = CryptoUtils.egcd(30n, 20n);
assertEqual(gcd, 10n, "GCD of 30, 20 is 10");
});
test("pow_mod: modular exponentiation", () => {
const result = CryptoUtils.pow_mod(2n, 10n, 1000n);
assertEqual(result, 24n, "2^10 mod 1000 = 24");
});
test("pow_mod: large exponent", () => {
const result = CryptoUtils.pow_mod(2n, 256n, 1000000n);
assertTrue(typeof result === "bigint", "Returns bigint");
});
test("sqrt_mod: modular square root", () => {
const P = CryptoUtils.CURVE.P;
const x = 4n;
const sqrt = CryptoUtils.sqrt_mod(x);
assertEqual(CryptoUtils.mod(sqrt * sqrt, P), x, "sqrt^2 = x");
});
test("weierstrass: curve equation", () => {
const result = CryptoUtils.weierstrass(1n);
assertTrue(typeof result === "bigint", "Returns bigint");
});
test("get_publickey: derive from private key (compressed)", () => {
const pubkey = CryptoUtils.get_publickey(test_privkey);
assertEqual(pubkey, test_pubkey, "Known G point");
});
test("get_publickey: key 2", () => {
const privkey = test_privkey;
const pubkey = CryptoUtils.get_publickey(privkey);
assertEqual(pubkey, test_pubkey, "Known 2G point");
});
test("get_publickey: uncompressed", () => {
const pubkey = CryptoUtils.get_publickey(test_privkey, false);
assertTrue(pubkey.startsWith("04"), "Uncompressed starts with 04");
assertEqual(pubkey.length, 130, "65 bytes = 130 hex");
});
test("expand_pub: decompress public key", () => {
const expanded = CryptoUtils.expand_pub(test_pubkey);
assertTrue(expanded.startsWith("04"), "Should start with 04");
assertEqual(expanded.length, 130, "Should be 65 bytes");
});
test("expand_pub: already uncompressed", () => {
const uncompressed = CryptoUtils.get_publickey(test_privkey, false);
const expanded = CryptoUtils.expand_pub(uncompressed);
assertEqual(expanded, uncompressed, "Returns same");
});
test("priv_to_pub: alias for get_publickey", () => {
const pubkey = CryptoUtils.priv_to_pub(test_privkey);
assertEqual(pubkey, test_pubkey, "Same as get_publickey");
});
test("normalize_privatekey: hex string", () => {
const key = CryptoUtils.normalize_privatekey("ff");
assertEqual(key, 255n, "Normalize hex to BigInt");
});
test("normalize_privatekey: BigInt", () => {
const key = CryptoUtils.normalize_privatekey(255n);
assertEqual(key, 255n, "Pass through BigInt");
});
// === Hash Tests ===
test("hmacsha: NIST 'abc' vector (SHA256)", () => {