-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathindex.ts
More file actions
1588 lines (1346 loc) · 48.8 KB
/
index.ts
File metadata and controls
1588 lines (1346 loc) · 48.8 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
import { bech32, bech32m } from 'bech32';
const {
decode: bech32Decode,
encode: bech32Encode,
fromWords: bech32FromWords,
toWords: bech32ToWords
} = bech32;
import bigInt from 'big-integer';
import { blake2b, blake2bHex } from 'blakejs';
import { decode as bs58DecodeNoCheck, encode as bs58EncodeNoCheck } from 'bs58';
// @ts-ignore
import {
b32decode,
b32encode,
bs58Decode,
bs58Encode,
cashaddrDecode,
cashaddrEncode,
codec as xrpCodec,
decodeCheck as decodeEd25519PublicKey,
encodeCheck as encodeEd25519PublicKey,
eosPublicKey,
hex2a,
isValid as isValidXemAddress,
isValidChecksumAddress as rskIsValidChecksumAddress,
ss58Decode,
ss58Encode,
stripHexPrefix as rskStripHexPrefix,
toChecksumAddress as rskToChecksumAddress,
} from 'crypto-addr-codec';
import { crc32 } from 'js-crc';
import { sha512_256 } from 'js-sha512';
import { decode as nanoBase32Decode, encode as nanoBase32Encode } from 'nano-base32';
import { Keccak, SHA3 } from 'sha3';
import { c32checkDecode, c32checkEncode } from './blockstack/stx-c32';
import { decode as cborDecode, encode as cborEncode, TaggedValue } from './cbor/cbor';
import { filAddrDecoder, filAddrEncoder } from './filecoin/index';
import { ChainID, isValidAddress } from './flow/index';
import { groestl_2 } from './groestl-hash-js/index';
import { xmrAddressDecoder, xmrAddressEncoder } from './monero/xmr-base58';
import { nimqDecoder, nimqEncoder } from './nimq';
const SLIP44_MSB = 0x80000000
type EnCoder = (data: Buffer) => string;
type DeCoder = (data: string) => Buffer;
type base58CheckVersion = number[]
export interface IFormat {
coinType: number;
name: string;
encoder: (data: Buffer) => string;
decoder: (data: string) => Buffer;
}
// Support version field of more than one byte (e.g. Zcash)
function makeBitcoinBase58CheckEncoder(p2pkhVersion: base58CheckVersion, p2shVersion: base58CheckVersion): (data: Buffer) => string {
return (data: Buffer) => {
let addr: Buffer;
switch (data.readUInt8(0)) {
case 0x76: // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
if (
data.readUInt8(1) !== 0xa9 ||
data.readUInt8(data.length - 2) !== 0x88 ||
data.readUInt8(data.length - 1) !== 0xac
) {
throw Error('Unrecognised address format');
}
addr = Buffer.concat([Buffer.from(p2pkhVersion), data.slice(3, 3 + data.readUInt8(2))]);
// @ts-ignore
return bs58Encode(addr);
case 0xa9: // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
if (data.readUInt8(data.length - 1) !== 0x87) {
throw Error('Unrecognised address format');
}
addr = Buffer.concat([Buffer.from(p2shVersion), data.slice(2, 2 + data.readUInt8(1))]);
return bs58Encode(addr);
default:
throw Error('Unrecognised address format');
}
};
}
// Supports version field of more than one byte
// NOTE: Assumes all versions in p2pkhVersions[] or p2shVersions[] will have the same length
function makeBitcoinBase58CheckDecoder(p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]): (data: string) => Buffer {
return (data: string) => {
const addr = bs58Decode(data);
// Checks if the first addr bytes are exactly equal to provided version field
const checkVersion = (version: base58CheckVersion) => {
return version.every((value: number, index: number) => index < addr.length && value === addr.readUInt8(index))
}
if (p2pkhVersions.some(checkVersion)) {
return Buffer.concat([Buffer.from([0x76, 0xa9, 0x14]), addr.slice(p2pkhVersions[0].length), Buffer.from([0x88, 0xac])]);
} else if (p2shVersions.some(checkVersion)) {
return Buffer.concat([Buffer.from([0xa9, 0x14]), addr.slice(p2shVersions[0].length), Buffer.from([0x87])]);
}
throw Error('Unrecognised address format');
};
}
const bitcoinBase58Chain = (name: string, coinType: number, p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]) => ({
coinType,
decoder: makeBitcoinBase58CheckDecoder(p2pkhVersions, p2shVersions),
encoder: makeBitcoinBase58CheckEncoder(p2pkhVersions[0], p2shVersions[0]),
name,
});
function makeBech32SegwitEncoder(hrp: string): (data: Buffer) => string {
return (data: Buffer) => {
let version = data.readUInt8(0);
if (version >= 0x51 && version <= 0x60) {
version -= 0x50;
} else if (version !== 0x00) {
throw Error('Unrecognised address format');
}
const words = [version].concat(bech32ToWords(data.slice(2, data.readUInt8(1) + 2)));
return bech32Encode(hrp, words);
};
}
function makeBech32SegwitDecoder(hrp: string): (data: string) => Buffer {
return (data: string) => {
const { prefix, words } = bech32Decode(data);
if (prefix !== hrp) {
throw Error('Unexpected human-readable part in bech32 encoded address');
}
const script = bech32FromWords(words.slice(1));
let version = words[0];
if (version > 0) {
version += 0x50;
}
return Buffer.concat([Buffer.from([version, script.length]), Buffer.from(script)]);
};
}
function makeBitcoinEncoder(hrp: string, p2pkhVersion: base58CheckVersion, p2shVersion: base58CheckVersion): (data: Buffer) => string {
const encodeBech32 = makeBech32SegwitEncoder(hrp);
const encodeBase58Check = makeBitcoinBase58CheckEncoder(p2pkhVersion, p2shVersion);
return (data: Buffer) => {
try {
return encodeBase58Check(data);
} catch {
return encodeBech32(data);
}
};
}
function makeBitcoinDecoder(hrp: string, p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]): (data: string) => Buffer {
const decodeBech32 = makeBech32SegwitDecoder(hrp);
const decodeBase58Check = makeBitcoinBase58CheckDecoder(p2pkhVersions, p2shVersions);
return (data: string) => {
if (data.toLowerCase().startsWith(hrp + '1')) {
return decodeBech32(data);
} else {
return decodeBase58Check(data);
}
};
}
const bitcoinChain = (
name: string,
coinType: number,
hrp: string,
p2pkhVersions: base58CheckVersion[],
p2shVersions: base58CheckVersion[],
) => ({
coinType,
decoder: makeBitcoinDecoder(hrp, p2pkhVersions, p2shVersions),
encoder: makeBitcoinEncoder(hrp, p2pkhVersions[0], p2shVersions[0]),
name,
});
// Similar to makeBitcoinEncoder but:
// - Uses Bech32 without SegWit https://zips.z.cash/zip-0173
// - Supports version field of more than one byte
function makeZcashEncoder(hrp: string, p2pkhVersion: base58CheckVersion, p2shVersion: base58CheckVersion): (data: Buffer) => string {
const encodeBech32 = makeBech32Encoder(hrp);
const encodeBase58Check = makeBitcoinBase58CheckEncoder(p2pkhVersion, p2shVersion);
return (data: Buffer) => {
try {
return encodeBase58Check(data);
} catch {
return encodeBech32(data);
}
};
}
// Similar to makeBitcoinDecoder but uses makeZcashBase58CheckDecoder to support version field of more than one byte
function makeZcashDecoder(hrp: string, p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]): (data: string) => Buffer {
const decodeBase58Check = makeBitcoinBase58CheckDecoder(p2pkhVersions, p2shVersions);
const decodeBech32 = makeBech32Decoder(hrp);
return (data: string) => {
if (data.toLowerCase().startsWith(hrp)) {
return decodeBech32(data);
} else {
return decodeBase58Check(data);
}
};
}
const zcashChain = (
name: string,
coinType: number,
hrp: string,
p2pkhVersions: base58CheckVersion[],
p2shVersions: base58CheckVersion[],
) => ({
coinType,
decoder: makeZcashDecoder(hrp, p2pkhVersions, p2shVersions),
encoder: makeZcashEncoder(hrp, p2pkhVersions[0], p2shVersions[0]),
name,
});
function encodeCashAddr(data: Buffer): string {
switch (data.readUInt8(0)) {
case 0x76: // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
if (
data.readUInt8(1) !== 0xa9 ||
data.readUInt8(data.length - 2) !== 0x88 ||
data.readUInt8(data.length - 1) !== 0xac
) {
throw Error('Unrecognised address format');
}
return cashaddrEncode('bitcoincash', 0, data.slice(3, 3 + data.readUInt8(2)));
case 0xa9: // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
if (data.readUInt8(data.length - 1) !== 0x87) {
throw Error('Unrecognised address format');
}
return cashaddrEncode('bitcoincash', 1, data.slice(2, 2 + data.readUInt8(1)));
default:
throw Error('Unrecognised address format');
}
}
function makeCardanoEncoder(hrp: string): (data: Buffer) => string {
const encodeByron = makeCardanoByronEncoder();
const encodeBech32 = makeBech32Encoder(hrp, 104);
return (data: Buffer) => {
try {
return encodeByron(data);
} catch {
return encodeBech32(data);
}
}
}
function makeCardanoDecoder(hrp: string): (data: string) => Buffer {
const decodeByron = makeCardanoByronDecoder();
const decodeBech32 = makeBech32Decoder(hrp, 104);
return (data: string) => {
if (data.toLowerCase().startsWith(hrp)) {
return decodeBech32(data);
} else {
return decodeByron(data);
}
};
}
function makeCardanoByronEncoder() {
return (data: Buffer) => {
const checksum = crc32(data);
const taggedValue = new TaggedValue(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength), 24);
const cborEncodedAddress = cborEncode([taggedValue, parseInt(checksum, 16)]);
const address = bs58EncodeNoCheck(Buffer.from(cborEncodedAddress));
if (!address.startsWith('Ae2') && !address.startsWith('Ddz')) {
throw Error('Unrecognised address format');
}
return address;
};
}
function makeCardanoByronDecoder() {
return (data: string) => {
const bytes = bs58DecodeNoCheck(data);
const bytesAb = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
const cborDecoded = cborDecode(bytesAb);
const taggedAddr = cborDecoded[0];
if(taggedAddr === undefined) {
throw Error('Unrecognised address format');
}
const addrChecksum = cborDecoded[1];
const calculatedChecksum = crc32(taggedAddr.value);
if(parseInt(calculatedChecksum, 16) !== addrChecksum) {
throw Error('Unrecognised address format');
}
return Buffer.from(taggedAddr.value);
};
}
const cardanoChain = (
name: string,
coinType: number,
hrp: string,
) => ({
coinType,
decoder: makeCardanoDecoder(hrp),
encoder: makeCardanoEncoder(hrp),
name,
});
function decodeNearAddr(data: string): Buffer {
const regex = /(^(([a-z\d]+[\-_])*[a-z\d]+\.)*([a-z\d]+[\-_])*[a-z\d]+$)/g;
if(!regex.test(data)) {
throw Error('Invalid address string');
} else {
if(data.length > 64 || data.length < 2) {
throw Error('Invalid address format');
}
return Buffer.from(data);
}
}
function encodeNearAddr(data: Buffer): string {
const ndata = data.toString();
if(ndata.length > 64 || ndata.length < 2) {
throw Error('Invalid address format');
}
return ndata;
}
function decodeCashAddr(data: string): Buffer {
const { prefix, type, hash } = cashaddrDecode(data);
if (type === 0) {
return Buffer.concat([Buffer.from([0x76, 0xa9, 0x14]), Buffer.from(hash), Buffer.from([0x88, 0xac])]);
} else if (type === 1) {
return Buffer.concat([Buffer.from([0xa9, 0x14]), Buffer.from(hash), Buffer.from([0x87])]);
}
throw Error('Unrecognised address format');
}
function decodeBitcoinCash(data: string): Buffer {
const decodeBase58Check = makeBitcoinBase58CheckDecoder([[0x00]], [[0x05]]);
try {
return decodeBase58Check(data);
} catch {
return decodeCashAddr(data);
}
}
function grsCheckSumFn(buffer: Buffer): Buffer{
const rtn : string = groestl_2(buffer, 1, 1) as string
return Buffer.from(rtn)
}
function bs58grscheckEncode(payload:Buffer): string {
const checksum = grsCheckSumFn(payload)
return bs58EncodeNoCheck(Buffer.concat([
payload,
checksum
], payload.length + 4))
}
// Lifted from https://github.com/ensdomains/address-encoder/pull/239/commits/4872330fba558730108d7f1e0d197cfef3dd9ca6
// https://github.com/groestlcoin/bs58grscheck
function decodeRaw (buffer: Buffer): Buffer {
const payload = buffer.slice(0, -4)
const checksum = buffer.slice(-4)
const newChecksum = grsCheckSumFn(payload)
/* tslint:disable:no-bitwise */
if (checksum[0] ^ newChecksum[0] |
checksum[1] ^ newChecksum[1] |
checksum[2] ^ newChecksum[2] |
checksum[3] ^ newChecksum[3]) {return Buffer.from([])};
/* tslint:enable:no-bitwise */
return payload
}
function bs58grscheckDecode(str: string): Buffer {
const buffer = bs58DecodeNoCheck(str);
const payload = decodeRaw(buffer)
if (payload.length === 0) {throw new Error('Invalid checksum');}
return payload
}
function makeBase58GrsCheckEncoder(p2pkhVersion: base58CheckVersion, p2shVersion: base58CheckVersion): (data: Buffer) => string {
return (data: Buffer) => {
let addr: Buffer;
switch (data.readUInt8(0)) {
case 0x76: // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
if (
data.readUInt8(1) !== 0xa9 ||
data.readUInt8(data.length - 2) !== 0x88 ||
data.readUInt8(data.length - 1) !== 0xac
) {
throw Error('Unrecognised address format');
}
addr = Buffer.concat([Buffer.from(p2pkhVersion), data.slice(3, 3 + data.readUInt8(2))]);
return bs58grscheckEncode(addr);
case 0xa9: // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
if (data.readUInt8(data.length - 1) !== 0x87) {
throw Error('Unrecognised address format');
}
addr = Buffer.concat([Buffer.from(p2shVersion), data.slice(2, 2 + data.readUInt8(1))]);
return bs58grscheckEncode(addr);
default:
throw Error('Unrecognised address format');
}
};
}
function makeBase58GrsCheckDecoder(p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]): (data: string) => Buffer {
return (data: string) => {
const addr = bs58grscheckDecode(data);
const checkVersion = (version: base58CheckVersion) => {
return version.every((value: number, index: number) => index < addr.length && value === addr.readUInt8(index))
}
if (p2pkhVersions.some(checkVersion)) {
return Buffer.concat([Buffer.from([0x76, 0xa9, 0x14]), addr.slice(p2pkhVersions[0].length), Buffer.from([0x88, 0xac])]);
} else if (p2shVersions.some(checkVersion)) {
return Buffer.concat([Buffer.from([0xa9, 0x14]), addr.slice(p2shVersions[0].length), Buffer.from([0x87])]);
}
throw Error('Unrecognised address format');
};
}
function makeGroestlcoinEncoder(hrp: string, p2pkhVersion: base58CheckVersion, p2shVersion: base58CheckVersion): (data: Buffer) => string {
const encodeBech32 = makeBech32SegwitEncoder(hrp);
const encodeBase58Check = makeBase58GrsCheckEncoder(p2pkhVersion, p2shVersion);
return (data: Buffer) => {
try {
return encodeBase58Check(data);
} catch {
return encodeBech32(data);
}
};
}
function makeGroestlcoinDecoder(hrp: string, p2pkhVersions: base58CheckVersion[], p2shVersions: base58CheckVersion[]): (data: string) => Buffer {
const decodeBech32 = makeBech32SegwitDecoder(hrp);
const decodeBase58Check = makeBase58GrsCheckDecoder(p2pkhVersions, p2shVersions);
return (data: string) => {
if (data.toLowerCase().startsWith(hrp + '1')) {
return decodeBech32(data);
} else {
return decodeBase58Check(data);
}
};
}
const groestlcoinChain = (
name: string,
coinType: number,
hrp: string,
p2pkhVersions: base58CheckVersion[],
p2shVersions: base58CheckVersion[],
) => ({
coinType,
decoder: makeGroestlcoinDecoder(hrp, p2pkhVersions, p2shVersions),
encoder: makeGroestlcoinEncoder(hrp, p2pkhVersions[0], p2shVersions[0]),
name,
});
function makeChecksummedHexEncoder(chainId?: number) {
return (data: Buffer) => rskToChecksumAddress(data.toString('hex'), chainId || null);
}
function makeChecksummedHexDecoder(chainId?: number) {
return (data: string) => {
const stripped = rskStripHexPrefix(data);
if (
!rskIsValidChecksumAddress(data, chainId || null) &&
stripped !== stripped.toLowerCase() &&
stripped !== stripped.toUpperCase()
) {
throw Error('Invalid address checksum');
}
return Buffer.from(rskStripHexPrefix(data), 'hex');
};
}
const hexChecksumChain = (name: string, coinType: number, chainId?: number) => ({
coinType,
decoder: makeChecksummedHexDecoder(chainId),
encoder: makeChecksummedHexEncoder(chainId),
name,
});
/* tslint:disable:no-bitwise */
export const convertEVMChainIdToCoinType = (chainId: number) =>{
return (SLIP44_MSB | chainId) >>> 0
}
/* tslint:disable:no-bitwise */
export const convertCoinTypeToEVMChainId = (coinType: number) =>{
return ((SLIP44_MSB -1) & coinType) >> 0
}
const evmChain = (name: string, coinType: number) => ({
coinType: convertEVMChainIdToCoinType(coinType),
decoder: makeChecksummedHexDecoder(),
encoder: makeChecksummedHexEncoder(),
name,
});
function makeBech32Encoder(prefix: string, limit?: number) {
return (data: Buffer) => bech32Encode(prefix, bech32ToWords(data), limit);
}
function makeBech32Decoder(currentPrefix: string, limit?: number) {
return (data: string) => {
const { prefix, words } = bech32Decode(data, limit);
if (prefix !== currentPrefix) {
throw Error('Unrecognised address format');
}
return Buffer.from(bech32FromWords(words));
};
}
const bech32Chain = (name: string, coinType: number, prefix: string, limit?: number) => ({
coinType,
decoder: makeBech32Decoder(prefix, limit),
encoder: makeBech32Encoder(prefix, limit),
name,
});
function makeIotaBech32Encoder(prefix: string, limit?: number) {
const bufferAddrVersion = Buffer.from([0o0]);
return (data: Buffer) => bech32Encode(prefix, bech32ToWords(Buffer.concat([bufferAddrVersion, data])), limit);
}
function makeIotaBech32Decoder(currentPrefix: string, limit?: number) {
return (data: string) => {
const { prefix, words } = bech32Decode(data, limit);
if (prefix !== currentPrefix) {
throw Error('Unrecognised address format');
}
return Buffer.from(bech32FromWords(words)).slice(1);
};
}
function makeBech32mEncoder(prefix: string, limit?: number) {
return (data: Buffer) => bech32m.encode(prefix, bech32m.toWords(data), limit);
}
function makeBech32mDecoder(currentPrefix: string, limit?: number) {
return (data: string) => {
const { prefix, words } = bech32m.decode(data, limit);
if (prefix !== currentPrefix) {
throw Error('Unrecognised address format');
}
return Buffer.from(bech32m.fromWords(words));
};
}
const bech32mChain = (name: string, coinType: number, prefix: string, limit?: number) => ({
coinType,
decoder: makeBech32mDecoder(prefix, limit),
encoder: makeBech32mEncoder(prefix, limit),
name,
});
const iotaBech32Chain = (name: string, coinType: number, prefix: string, limit?: number) => ({
coinType,
decoder: makeIotaBech32Decoder(prefix, limit),
encoder: makeIotaBech32Encoder(prefix, limit),
name,
});
function makeEosioEncoder(prefix: string): (data: Buffer) => string {
return (data: Buffer) => {
if (!eosPublicKey.isValid(data)) {
throw Error('Unrecognised address format');
}
const woPrefix = eosPublicKey.fromHex(data).toString();
return woPrefix.replace(/^.{3}/g, prefix);
}
}
function makeEosioDecoder(prefix: string): (data: string) => Buffer {
return (data: string) => {
if (!eosPublicKey.isValid(data)) {
throw Error('Unrecognised address format');
}
const regex = new RegExp("^.{" + prefix.length + "}", "g");
const wPrefix = data.replace(regex, 'EOS');
return eosPublicKey(wPrefix).toBuffer();
}
}
const eosioChain = (name: string, coinType: number, prefix: string) => ({
coinType,
decoder: makeEosioDecoder(prefix),
encoder: makeEosioEncoder(prefix),
name,
});
function b32encodeXemAddr(data: Buffer): string {
return b32encode(hex2a(data.toString('hex')));
}
function b32decodeXemAddr(data: string): Buffer {
if (!isValidXemAddress(data)) {
throw Error('Unrecognised address format');
}
const address = data
.toString()
.toUpperCase()
.replace(/-/g, '');
return b32decode(address);
}
function ksmAddrEncoder(data: Buffer): string {
return ss58Encode(Uint8Array.from(data), 2);
}
function dotAddrEncoder(data: Buffer): string {
return ss58Encode(Uint8Array.from(data), 0);
}
function ksmAddrDecoder(data: string): Buffer {
return Buffer.from(ss58Decode(data));
}
function nodlAddrEncoder(data: Buffer): string {
return ss58Encode(Uint8Array.from(data), 37);
}
function ontAddrEncoder(data: Buffer): string {
return bs58Encode(Buffer.concat([Buffer.from([0x17]), data]))
}
function ontAddrDecoder(data: string): Buffer {
const address = bs58Decode(data)
switch (address.readUInt8(0)) {
case 0x17:
return address.slice(1);
default:
throw Error('Unrecognised address format');
}
}
function strDecoder(data: string): Buffer {
return decodeEd25519PublicKey('ed25519PublicKey', data);
}
function strEncoder(data: Buffer): string {
return encodeEd25519PublicKey('ed25519PublicKey', data);
}
// Referenced from the followings
// https://tezos.stackexchange.com/questions/183/base58-encoding-decoding-of-addresses-in-micheline
// https://tezos.gitlab.io/api/p2p.html?highlight=contract_id#contract-id-22-bytes-8-bit-tag
function tezosAddressEncoder(data: Buffer): string {
if (data.length !== 22 && data.length !== 21) {
throw Error('Unrecognised address format');
}
let prefix: Buffer;
switch (data.readUInt8(0)) {
case 0x00:
if (data.readUInt8(1) === 0x00) {
prefix = Buffer.from([0x06, 0xa1, 0x9f]); // prefix tz1 equal 06a19f
} else if (data.readUInt8(1) === 0x01) {
prefix = Buffer.from([0x06, 0xa1, 0xa1]); // prefix tz2 equal 06a1a1
} else if (data.readUInt8(1) === 0x02) {
prefix = Buffer.from([0x06, 0xa1, 0xa4]); // prefix tz3 equal 06a1a4
} else {
throw Error('Unrecognised address format');
}
return bs58Encode(Buffer.concat([prefix, data.slice(2)]));
case 0x01:
prefix = Buffer.from([0x02, 0x5a, 0x79]); // prefix KT1 equal 025a79
return bs58Encode(Buffer.concat([prefix, data.slice(1, 21)]));
default:
throw Error('Unrecognised address format');
}
}
function tezosAddressDecoder(data: string): Buffer {
const address = bs58Decode(data).slice(3);
switch (data.substring(0, 3)) {
case 'tz1':
return Buffer.concat([Buffer.from([0x00, 0x00]), address]);
case 'tz2':
return Buffer.concat([Buffer.from([0x00, 0x01]), address]);
case 'tz3':
return Buffer.concat([Buffer.from([0x00, 0x02]), address]);
case 'KT1':
return Buffer.concat([Buffer.from([0x01]), address, Buffer.from([0x00])]);
default:
throw Error('Unrecognised address format');
}
}
// Reference from js library:
// https://github.com/hashgraph/hedera-sdk-java/blob/120d98ac9cd167db767ed77bb52cefc844b09fc9/src/main/java/com/hedera/hashgraph/sdk/SolidityUtil.java#L26
function hederaAddressEncoder(data: Buffer): string {
if (data.length !== 20) {
throw Error('Unrecognised address format');
}
const view = new DataView(data.buffer, 0);
const shard = view.getUint32(0);
const realm = view.getBigUint64(4);
const account = view.getBigUint64(12);
return [shard, realm, account].join('.');
}
// Reference from js library:
// https://github.com/hashgraph/hedera-sdk-java/blob/120d98ac9cd167db767ed77bb52cefc844b09fc9/src/main/java/com/hedera/hashgraph/sdk/SolidityUtil.java#L26
function hederaAddressDecoder(data: string): Buffer {
const buffer = Buffer.alloc(20);
const view = new DataView(buffer.buffer, 0, 20);
const components = data.split('.');
if (components.length !== 3) {
throw Error('Unrecognised address format');
}
const shard = Number(components[0]);
const realm = BigInt(components[1]);
const account = BigInt(components[2]);
view.setUint32(0, shard);
view.setBigUint64(4, realm);
view.setBigUint64(12, account);
return buffer;
}
// Reference from Lisk validator
// https://github.com/LiskHQ/lisk-sdk/blob/master/elements/lisk-validator/src/validation.ts#L202
function validateLiskAddress(address: string) {
if (address.length < 2 || address.length > 22) {
throw new Error('Address length does not match requirements. Expected between 2 and 22 characters.');
}
if (address[address.length - 1] !== 'L') {
throw new Error('Address format does not match requirements. Expected "L" at the end.');
}
if (address.includes('.')) {
throw new Error('Address format does not match requirements. Address includes invalid character: `.`.');
}
}
function liskAddressEncoder(data: Buffer): string {
const address = `${bigInt(data.toString('hex'), 16).toString(10)}L`;
return address;
}
function liskAddressDecoder(data: string): Buffer {
validateLiskAddress(data);
return Buffer.from(bigInt(data.slice(0, -1)).toString(16), 'hex');
}
function seroAddressEncoder(data: Buffer): string {
const address = bs58EncodeNoCheck(data);
return address;
}
function seroAddressDecoder(data: string): Buffer {
const bytes = bs58DecodeNoCheck(data);
if (bytes.length === 96) {
return bytes;
}
throw Error('Unrecognised address format');
}
// https://github.com/wanchain/go-wanchain/blob/develop/common/types.go
function wanToChecksumAddress(data: string): string {
const strippedData = rskStripHexPrefix(data);
const ndata = strippedData.toLowerCase();
const hashed = new Keccak(256).update(Buffer.from(ndata)).digest();
let ret = '0x';
const len = ndata.length;
let hashByte;
for(let i = 0; i < len; i++) {
hashByte = hashed[Math.floor(i / 2)];
if (i % 2 === 0) {
/* tslint:disable:no-bitwise */
hashByte = hashByte >> 4;
} else {
/* tslint:disable:no-bitwise */
hashByte &= 0xf;
/* tslint:enable:no-bitwise */
}
if(ndata[i] > '9' && hashByte <= 7) {
ret += ndata[i].toUpperCase();
} else {
ret += ndata[i];
}
}
return ret;
}
function isValidChecksumWanAddress(address: string ): boolean {
const isValid: boolean = /^0x[0-9a-fA-F]{40}$/.test(address);
return isValid && (wanToChecksumAddress(address) === address)
}
function wanChecksummedHexEncoder(data: Buffer): string {
return wanToChecksumAddress('0x'+data.toString('hex'));
}
function wanChecksummedHexDecoder(data: string): Buffer {
if(isValidChecksumWanAddress(data)) {
return Buffer.from(rskStripHexPrefix(data), 'hex');
} else {
throw Error('Invalid address checksum');
}
}
function calcCheckSum(withoutChecksum: Buffer): Buffer {
const checksum = (new Keccak(256).update(Buffer.from(blake2b(withoutChecksum, null, 32))).digest()).slice(0, 4);
return checksum;
}
function isByteArrayValid(addressBytes: Buffer): boolean {
// "M" for mainnet, "T" for test net. Just limited to mainnet
if(addressBytes.readInt8(0) !== 5 || addressBytes.readInt8(1) !== "M".charCodeAt(0) || addressBytes.length !== 26) {
return false;
}
const givenCheckSum = addressBytes.slice(-4);
const generatedCheckSum = calcCheckSum(addressBytes.slice(0 , -4));
return givenCheckSum.equals(generatedCheckSum);
}
// Reference:
// https://github.com/virtualeconomy/v-systems/blob/master/src/main/scala/vsys/account/Address.scala
function vsysAddressDecoder(data: string): Buffer {
let base58String = data;
if(data.startsWith('address:')){
base58String = data.substr(data.length);
}
if(base58String.length > 36) {
throw new Error('VSYS: Address length should not be more than 36');
}
const bytes = bs58DecodeNoCheck(base58String);
if(!isByteArrayValid(bytes)) {
throw new Error('VSYS: Invalid checksum');
}
return bytes;
}
function vsysAddressEncoder(data: Buffer): string {
if(!isByteArrayValid(data)) {
throw new Error('VSYS: Invalid checksum');
}
return bs58EncodeNoCheck(data);
}
// Reference:
// https://github.com/handshake-org/hsd/blob/c85d9b4c743a9e1c9577d840e1bd20dee33473d3/lib/primitives/address.js#L297
function hnsAddressEncoder(data: Buffer): string {
if (data.length !== 20) {
throw Error('P2WPKH must be 20 bytes');
}
const version = 0;
const words = [version].concat(bech32ToWords(data));
return bech32Encode('hs', words);
}
// Reference:
// https://github.com/handshake-org/hsd/blob/c85d9b4c743a9e1c9577d840e1bd20dee33473d3/lib/primitives/address.js#L225
function hnsAddressDecoder(data: string): Buffer {
const { prefix, words } = bech32Decode(data);
if (prefix !== 'hs') {
throw Error('Unrecognised address format');
}
const version = words[0];
const hash = bech32FromWords(words.slice(1));
if (version !== 0) {
throw Error('Bad program version');
}
if (hash.length !== 20) {
throw Error('Witness program hash is the wrong size');
}
return Buffer.from(hash);
}
function nasAddressEncoder(data: Buffer): string {
const checksum = (new SHA3(256).update(data).digest()).slice(0, 4);
return bs58EncodeNoCheck(Buffer.concat([data, checksum]));
}
function nasAddressDecoder(data: string): Buffer {
const buf = bs58DecodeNoCheck(data);
if(buf.length !== 26 || buf[0] !== 25 || (buf[1] !== 87 && buf[1] !== 88)){
throw Error('Unrecognised address format');
}
const bufferData = buf.slice(0, 22);
const checksum = buf.slice(-4);
const checksumVerify = (new SHA3(256).update(bufferData).digest()).slice(0, 4);
if(!checksumVerify.equals(checksum)) {
throw Error('Invalid checksum');
}
return bufferData;
}
// Referenced from following
// https://github.com/icon-project/icon-service/blob/master/iconservice/base/address.py#L219
function icxAddressEncoder(data: Buffer): string {
if (data.length !== 21) {
throw Error('Unrecognised address format');
}
switch (data.readUInt8(0)) {
case 0x00:
return 'hx' + data.slice(1).toString('hex');
case 0x01:
return 'cx' + data.slice(1).toString('hex');
default:
throw Error('Unrecognised address format');
}
}
// Referenced from following
// https://github.com/icon-project/icon-service/blob/master/iconservice/base/address.py#L238
function icxAddressDecoder(data: string): Buffer {
const prefix = data.slice(0, 2)
const body = data.slice(2)
switch (prefix) {
case 'hx':
return Buffer.concat([Buffer.from([0x00]), Buffer.from(body, 'hex')]);
case 'cx':
return Buffer.concat([Buffer.from([0x01]), Buffer.from(body, 'hex')]);
default:
throw Error('Unrecognised address format');
}
}
function hntAddresEncoder(data: Buffer): string {
const buf = Buffer.concat([Buffer.from([0]), data]);
return bs58Encode(buf);
}
function hntAddressDecoder(data: string): Buffer {
const buf = bs58Decode(data);
const version = buf[0];
if(version !== 0x00){
throw Error('Invalid version byte');
}
return buf.slice(1);
}
function wavesAddressDecoder(data: string): Buffer {
const buffer = bs58DecodeNoCheck(data);
if(buffer[0] !== 1) {
throw Error('Bad program version');
}
if (buffer[1] !== 87 || buffer.length !== 26) {
throw Error('Unrecognised address format');
}
const bufferData = buffer.slice(0, 22);
const checksum = buffer.slice(22, 26);
const checksumVerify = (new Keccak(256).update(Buffer.from(blake2b(bufferData, null, 32))).digest()).slice(0, 4);
if(!checksumVerify.equals(checksum)) {
throw Error('Invalid checksum');
}
return buffer;
}
const glog = [0, 0, 1, 18, 2, 5, 19, 11, 3, 29, 6, 27, 20, 8, 12, 23, 4, 10, 30, 17, 7, 22, 28, 26, 21, 25, 9, 16, 13, 14, 24, 15];
const gexp = [1, 2, 4, 8, 16, 5, 10, 20, 13, 26, 17, 7, 14, 28, 29, 31, 27, 19, 3, 6, 12, 24, 21, 15, 30, 25, 23, 11, 22, 9, 18, 1];
function gmult(a: number, b: number): number {
if (a === 0 || b === 0) {return 0;}