/
banano-util.js
1527 lines (1391 loc) · 45.7 KB
/
banano-util.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
'use strict';
// STARTED TOP nodejs/browser hack
(function() {
// FINISHED TOP nodejs/browser hack
// istanbul ignore if
if (typeof BigInt === 'undefined') {
return;
}
const blake = require('../../libraries/blake2b/blake2b.js');
const nacl = require('../../libraries/tweetnacl/nacl.js');
const workMin = BigInt('0xfffffe0000000000');
const preamble =
'0000000000000000000000000000000000000000000000000000000000000006';
const bananoMessagePreamble =
'bananomsg-';
const prefixDivisors = {
ban_: {
minorDivisor: BigInt('1000000000000000000000000000'),
majorDivisor: BigInt('100000000000000000000000000000'),
majorName: 'banano',
minorName: 'banoshi',
},
nano_: {
minorDivisor: BigInt('1000000000000000000000000'),
majorDivisor: BigInt('1000000000000000000000000000000'),
majorName: 'nano',
minorName: 'nanoshi',
},
};
const ACCOUNT_ALPHABET_REGEX_STR = '^[13456789abcdefghijkmnopqrstuwxyz]+$';
const SEED_ALPHABET_REGEX_STR = '^[0123456789abcdefABCDEF]{64}$';
const LOG_SEND = false;
const LOG_SEND_PROCESS = false;
const LOG_RECEIVE = false;
const LOG_OPEN = false;
const LOG_CHANGE = false;
const LOG_IS_WORK_VALID = false;
const LOG_GET_HASH_CPU_WORKER = false;
/**
* Converts an amount into a raw amount.
*
* @memberof BananoUtil
* @param {string} amountStr the amount, as a string.
* @param {string} amountPrefix the amount, as a string.
* @return {string} the banano as a raw value.
*/
const getRawStrFromMajorAmountStr = (amountStr, amountPrefix) => {
/* istanbul ignore if */
if (amountStr == undefined) {
throw Error('amountStr is a required parameter.');
}
/* istanbul ignore if */
if (amountPrefix == undefined) {
throw Error('amountPrefix is a required parameter.');
}
/* istanbul ignore if */
if (typeof amountStr !== 'string') {
throw Error(`'${amountStr}' is not a string.`);
}
const decimalPlace = amountStr.indexOf('.');
let divisor = BigInt('1');
// console.log('STARTED getRawStrFromAmountStr', bananoStr, decimalPlace, divisor);
if (decimalPlace !== -1) {
amountStr = amountStr.replace('.', '');
const decimalsAfter = amountStr.length - decimalPlace;
// console.log('INTERIM getRawStrFromAmountStr decimalsAfter', decimalsAfter);
divisor = BigInt('10') ** BigInt(decimalsAfter);
}
// console.log('INTERIM getRawStrFromAmountStr', bananoStr, decimalPlace, divisor);
const amountBi = BigInt(amountStr);
// console.log('INTERIM getRawStrFromAmountStr banano ', banano);
// console.log('INTERIM getRawStrFromAmountStr bananoDiv', majorDivisor);
/* istanbul ignore if */
if (prefixDivisors[amountPrefix] == undefined) {
throw Error(
`'${amountPrefix}' is not an amountPrefix. (${[
...Object.keys(prefixDivisors),
]})`,
);
}
const majorDivisor = prefixDivisors[amountPrefix].majorDivisor;
const amountRaw = (amountBi * majorDivisor) / divisor;
// console.log('INTERIM getRawStrFromAmountStr bananoRaw', bananoRaw);
// const parts = getAmountPartsFromRaw(bananoRaw.toString());
// console.log('SUCCESS getRawStrFromAmountStr', bananoStr, bananoRaw, parts);
return amountRaw.toString();
};
/**
* Converts a banoshi amount into a raw amount.
*
* @memberof BananoUtil
* @param {string} amountStr the banoshi, as a string.
* @param {string} amountPrefix the amount prefix, as a string.
* @return {string} the banano as a raw value.
*/
const getRawStrFromMinorAmountStr = (amountStr, amountPrefix) => {
/* istanbul ignore if */
if (amountPrefix == undefined) {
throw Error('amountPrefix is a required parameter.');
}
const amount = BigInt(amountStr);
const prefixDivisor = prefixDivisors[amountPrefix];
const minorDivisor = prefixDivisor.minorDivisor;
const amountRaw = amount * minorDivisor;
return amountRaw.toString();
};
/**
* @typedef {Object} BananoParts
* @property {string} banano - The amount of banano.
* @property {string} banoshi - The amount of banoshi (not counting whole banano).
* @property {string} raw - The amount of raw (not counting whole banano and whole banoshi).
*/
/**
* Get the banano parts (banano, banoshi, raw) for a given raw value.
*
* @memberof BananoUtil
* @param {string} amountRawStr the raw amount, as a string.
* @param {string} amountPrefix the amount prefix, as a string.
* @return {BananoParts} the banano parts.
*/
const getAmountPartsFromRaw = (amountRawStr, amountPrefix) => {
/* istanbul ignore if */
if (amountPrefix == undefined) {
throw Error('amountPrefix is a required parameter.');
}
const amountRaw = BigInt(amountRawStr);
// console.log(`bananoRaw: ${bananoRaw}`);
const prefixDivisor = prefixDivisors[amountPrefix];
const majorDivisor = prefixDivisor.majorDivisor;
const minorDivisor = prefixDivisor.minorDivisor;
// console.log(`bananoDivisor: ${bananoDivisor}`);
const major = amountRaw / majorDivisor;
// console.log(`banano:${banano}`);
const majorRawRemainder = amountRaw - major * majorDivisor;
const minor = majorRawRemainder / minorDivisor;
const amountRawRemainder = majorRawRemainder - minor * minorDivisor;
const bananoParts = {};
bananoParts.majorName = prefixDivisor.majorName;
bananoParts.minorName = prefixDivisor.minorName;
bananoParts[prefixDivisor.majorName] = major.toString();
bananoParts[prefixDivisor.minorName] = minor.toString();
bananoParts.raw = amountRawRemainder.toString();
return bananoParts;
};
const hexToBytes = (hex) => {
const ret = new Uint8Array(hex.length / 2);
for (let i = 0; i < ret.length; i++) {
ret[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return ret;
};
const bytesToHex = (bytes) => {
return Array.prototype.map
.call(bytes, (x) => ('00' + x.toString(16)).slice(-2))
.join('')
.toUpperCase();
};
const hash = (block) => {
/* istanbul ignore if */
if (block === undefined) {
throw Error('block is a required parameter.');
}
/* istanbul ignore if */
if (block.account === undefined) {
throw Error('block.account is a required parameter.');
}
/* istanbul ignore if */
if (block.previous === undefined) {
throw Error('block.previous is a required parameter.');
}
/* istanbul ignore if */
if (block.representative === undefined) {
throw Error('block.representative is a required parameter.');
}
/* istanbul ignore if */
if (block.balance === undefined) {
throw Error('block.balance is a required parameter.');
}
/* istanbul ignore if */
if (block.link === undefined) {
throw Error('block.link is a required parameter.');
}
const context = blake.blake2bInit(32, null);
blake.blake2bUpdate(context, hexToBytes(preamble));
blake.blake2bUpdate(
context,
hexToBytes(getAccountPublicKey(block.account)),
);
blake.blake2bUpdate(context, hexToBytes(block.previous));
blake.blake2bUpdate(
context,
hexToBytes(getAccountPublicKey(block.representative)),
);
// console.log( `block.balance:${block.balance}` );
let balanceToPad = BigInt(block.balance).toString(16);
// console.log( `pre balanceToPad:${balanceToPad}` );
while (balanceToPad.length < 32) {
balanceToPad = '0' + balanceToPad;
}
// console.log( `post balanceToPad:${balanceToPad}` );
const balance = hexToBytes(balanceToPad);
// console.log( `balance:${balance}` );
blake.blake2bUpdate(context, balance);
blake.blake2bUpdate(context, hexToBytes(block.link));
const hash = bytesToHex(blake.blake2bFinal(context));
return hash;
};
const uint5ToUint4 = (uint5) => {
const length = (uint5.length / 4) * 5;
const uint4 = new Uint8Array(length);
for (let i = 1; i <= length; i++) {
const n = i - 1;
const m = i % 5;
const z = n - (i - m) / 5;
const right = uint5[z - 1] << (5 - m);
const left = uint5[z] >> m;
uint4[n] = (left + right) % 16;
}
return uint4;
};
const arrayCrop = (array) => {
const length = array.length - 1;
const croppedArray = new Uint8Array(length);
for (let i = 0; i < length; i++) {
croppedArray[i] = array[i + 1];
}
return croppedArray;
};
const uint4ToHex = (uint4) => {
let hex = '';
for (let i = 0; i < uint4.length; i++) {
hex += uint4[i].toString(16).toUpperCase();
}
return hex;
};
const uint8ToUint4 = (uintValue) => {
const uint4 = new Uint8Array(uintValue.length * 2);
for (let i = 0; i < uintValue.length; i++) {
uint4[i * 2] = (uintValue[i] / 16) | 0;
uint4[i * 2 + 1] = uintValue[i] % 16;
}
return uint4;
};
const equalArrays = (array1, array2) => {
for (let i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) return false;
}
return true;
};
const uint4ToUint8 = (uintValue) => {
const length = uintValue.length / 2;
const uint8 = new Uint8Array(length);
for (let i = 0; i < length; i++) {
uint8[i] = uintValue[i * 2] * 16 + uintValue[i * 2 + 1];
}
return uint8;
};
const stringToUint5 = (string) => {
const letterList = '13456789abcdefghijkmnopqrstuwxyz'.split('');
const length = string.length;
const stringArray = string.split('');
const uint5 = new Uint8Array(length);
for (let i = 0; i < length; i++) {
uint5[i] = letterList.indexOf(stringArray[i]);
}
return uint5;
};
const isAccountSuffixValid = (accountSuffix) => {
const regex = new RegExp(ACCOUNT_ALPHABET_REGEX_STR);
const isValid = regex.test(accountSuffix);
const retval = {};
retval.valid = isValid;
if (isValid) {
retval.message = '';
} else {
retval.message = `does not match regex '${ACCOUNT_ALPHABET_REGEX_STR}'`;
}
return retval;
};
/**
* Get the public key for a given account.
*
* @memberof BananoUtil
* @param {string} account the account.
* @return {string} the public key.
*/
const getAccountPublicKey = (account) => {
if (account === undefined) {
throw Error(`Undefined BANANO Account`);
}
if (account.startsWith === undefined) {
throw Error(`Not a string: '${account}'`);
}
let accountCrop;
if (account.startsWith('camo')) {
if (
(!account.startsWith('camo_1') && !account.startsWith('camo_3')) ||
account.length !== 65
) {
throw Error(`Invalid CAMO BANANO Account prefix '${account}'`);
}
accountCrop = account.substring(5, 65);
} else if (account.startsWith('nano')) {
if (
(!account.startsWith('nano_1') && !account.startsWith('nano_3')) ||
account.length !== 65
) {
throw Error(`Invalid NANO Account prefix '${account}'`);
}
accountCrop = account.substring(5, 65);
} else {
if (
(!account.startsWith('ban_1') && !account.startsWith('ban_3')) ||
account.length !== 64
) {
throw Error(`Invalid BANANO Account prefix '${account}'`);
}
accountCrop = account.substring(4, 64);
}
const isAccountValid = isAccountSuffixValid(accountCrop);
if (!isAccountValid.valid) {
throw Error(
`Invalid BANANO Account '${account}', ${isAccountValid.message}`,
);
}
const keyUint4 = arrayCrop(
uint5ToUint4(stringToUint5(accountCrop.substring(0, 52))),
);
const hashUint4 = uint5ToUint4(
stringToUint5(accountCrop.substring(52, 60)),
);
const keyArray = uint4ToUint8(keyUint4);
const blakeHash = blake.blake2b(keyArray, null, 5).reverse();
const left = hashUint4;
const right = uint8ToUint4(blakeHash);
if (!equalArrays(left, right)) {
const leftStr = uint5ToString(uint4ToUint5(left));
const rightStr = uint5ToString(uint4ToUint5(right));
throw Error(`Incorrect checksum ${leftStr} <> ${rightStr}`);
}
return uint4ToHex(keyUint4);
};
const hexToUint8 = (hexValue) => {
const length = (hexValue.length / 2) | 0;
const uint8 = new Uint8Array(length);
for (let i = 0; i < length; i++) {
uint8[i] = parseInt(hexValue.substr(i * 2, 2), 16);
}
return uint8;
};
const decToHex = (decValue, bytes = null) => {
const dec = decValue.toString().split('');
const sum = [];
let hex = '';
const hexArray = [];
let i;
let s;
while (dec.length) {
s = 1 * dec.shift();
for (i = 0; s || i < sum.length; i++) {
s += (sum[i] || 0) * 10;
sum[i] = s % 16;
s = (s - sum[i]) / 16;
}
}
while (sum.length) {
hexArray.push(sum.pop().toString(16));
}
hex = hexArray.join('');
if (hex.length % 2 != 0) {
hex = '0' + hex;
}
if (bytes > hex.length / 2) {
const diff = bytes - hex.length / 2;
for (let j = 0; j < diff; j++) {
hex = '00' + hex;
}
}
return hex;
};
const generateAccountSecretKeyBytes = (seedBytes, accountIndex) => {
const accountBytes = hexToUint8(decToHex(accountIndex, 4));
const context = blake.blake2bInit(32);
blake.blake2bUpdate(context, seedBytes);
blake.blake2bUpdate(context, accountBytes);
const newKey = blake.blake2bFinal(context);
return newKey;
};
const uint4ToUint5 = (uintValue) => {
const length = (uintValue.length / 5) * 4;
const uint5 = new Uint8Array(length);
for (let i = 1; i <= length; i++) {
const n = i - 1;
const m = i % 4;
const z = n + (i - m) / 4;
const right = uintValue[z] << m;
let left;
if ((length - i) % 4 == 0) {
left = uintValue[z - 1] << 4;
} else {
left = uintValue[z + 1] >> (4 - m);
}
uint5[n] = (left + right) % 32;
}
return uint5;
};
/**
* Get the account suffix for a given public key (everything but ban_ or camo_ or nano_).
*
* @memberof BananoUtil
* @param {string} publicKey the public key.
* @return {string} the account suffix.
*/
const getAccountSuffix = (publicKey) => {
const keyBytes = uint4ToUint8(hexToUint4(publicKey)); // For some reason here we go from u, to hex, to 4, to 8??
const checksum = uint5ToString(
uint4ToUint5(uint8ToUint4(blake.blake2b(keyBytes, null, 5).reverse())),
);
const account = uint5ToString(uint4ToUint5(hexToUint4(`0${publicKey}`)));
return `${account}${checksum}`;
};
/**
* Get the account for a given public key.
*
* @memberof BananoUtil
* @param {string} publicKey the public key.
* @param {string} accountPrefix the prefix. ban_ or nano_.
* @return {string} the account.
*/
const getAccount = (publicKey, accountPrefix) => {
/* istanbul ignore if */
if (accountPrefix == undefined) {
throw Error('accountPrefix is a required parameter.');
}
const accountSuffix = getAccountSuffix(publicKey);
return `${accountPrefix}${accountSuffix}`;
};
const uint5ToString = (uint5) => {
const letterList = '13456789abcdefghijkmnopqrstuwxyz'.split('');
let string = '';
for (let i = 0; i < uint5.length; i++) {
string += letterList[uint5[i]];
}
return string;
};
const hexToUint4 = (hexValue) => {
const uint4 = new Uint8Array(hexValue.length);
for (let i = 0; i < hexValue.length; i++) {
uint4[i] = parseInt(hexValue.substr(i, 1), 16);
}
return uint4;
};
const utf8ToBytes = (utf8) => {
const bytes = new Uint8Array(utf8.length);
for (let i = 0; i < utf8.length; i++) {
const code = utf8.charCodeAt(i);
/* istanbul ignore if */
if (code > 0xff) {
throw Error('Non utf-8 character found');
}
bytes[i] = code;
}
return bytes;
};
const hashMessageToBytes = (message) => {
if (typeof message === 'string') {
message = utf8ToBytes(message);
} else if (!(message instanceof Uint8Array)) {
throw Error('Expected message to be of type Uint8Array or string');
}
const context = blake.blake2bInit(32, null);
// bananoMessagePreamble is technically not needed for dummy blocks but helps separate Nano signing from Banano signing
blake.blake2bUpdate(context, utf8ToBytes(bananoMessagePreamble));
blake.blake2bUpdate(context, message);
const bytes = blake.blake2bFinal(context);
return bytes;
};
const DUMMY_BYTES = hexToBytes('0000000000000000000000000000000000000000000000000000000000000000');
const DUMMY_BALANCE = hexToBytes('00000000000000000000000000000000');
const messageDummyBlock = (publicKeyBytes, message) => {
let publicKey;
if (typeof(publicKeyBytes) === 'string') {
publicKey = publicKeyBytes;
publicKeyBytes = hexToBytes(publicKeyBytes);
} else {
publicKey = bytesToHex(publicKeyBytes);
}
const accountAddress = getAccount(publicKey, 'ban_');
const hashedMessageBytes = hashMessageToBytes(message);
const hashedMessageHex = bytesToHex(hashedMessageBytes);
const representative = getAccount(hashedMessageHex, 'ban_');
const dummyHex = bytesToHex(DUMMY_BYTES);
const block = {
type: 'state',
account: accountAddress,
previous: dummyHex,
representative: representative,
balance: '0',
link: dummyHex,
};
return block;
};
const messageDummyBlockHashBytes = (publicKeyBytes, message) => {
if (typeof(publicKeyBytes) === 'string') {
publicKeyBytes = hexToBytes(publicKeyBytes);
}
const hashedMessageBytes = hashMessageToBytes(message);
const context = blake.blake2bInit(32, null);
blake.blake2bUpdate(context, hexToBytes(preamble));
blake.blake2bUpdate(context, publicKeyBytes);
blake.blake2bUpdate(context, DUMMY_BYTES); // previous
blake.blake2bUpdate(context, hashedMessageBytes); // representative
blake.blake2bUpdate(context, DUMMY_BALANCE);
blake.blake2bUpdate(context, DUMMY_BYTES); // link
const hashBytes = blake.blake2bFinal(context);
return hashBytes;
};
const signMessage = async (privateKeyOrSigner, message) => {
const publicKey = await getPublicKey(privateKeyOrSigner);
const publicKeyBytes = hexToBytes(publicKey);
const privateKeyBytes = hexToBytes(privateKeyOrSigner);
if (typeof privateKeyOrSigner === 'object') {
const block = messageDummyBlock(publicKeyBytes, message);
// type is signer
const hwResponse = await privateKeyOrSigner.signBlock(block);
return hwResponse.signature;
}
const dummyBlockHashBytes = messageDummyBlockHashBytes(publicKeyBytes, message);
const signed = nacl.sign.detached(dummyBlockHashBytes, privateKeyBytes);
const signature = bytesToHex(signed);
return signature;
};
const verifyMessage = (publicKey, message, signature) => {
const publicKeyBytes = hexToBytes(publicKey);
const signatureBytes = hexToBytes(signature);
const dummyBlockHashBytes = messageDummyBlockHashBytes(publicKeyBytes, message);
const verified = nacl.sign.detached.verify(dummyBlockHashBytes, signatureBytes, publicKeyBytes);
return verified;
};
const signHash = (privateKey, hash) => {
// console.log( `sign ${JSON.stringify( block )}` );
const hashBytes = hexToBytes(hash);
// console.log( `hashBytes[${hashBytes.length}]:${hashBytes}` );
const privateKeyBytes = hexToBytes(privateKey);
// console.log( `privateKeyBytes[${privateKeyBytes.length}]:${privateKeyBytes}` );
const signed = nacl.sign.detached(hashBytes, privateKeyBytes);
const signature = bytesToHex(signed);
return signature;
};
const verify = (hash, signature, publicKey) => {
const hashBytes = hexToBytes(hash);
const signatureBytes = hexToBytes(signature);
const publicKeyBytes = hexToBytes(publicKey);
return nacl.sign.detached.verify(hashBytes, signatureBytes, publicKeyBytes);
};
/**
* @typedef {Object} Block
* @property {string} type
* @property {string} account
* @property {string} previous
* @property {string} representative
* @property {string} balance
* @property {string} link
* @property {string} signature
* @property {string} work?
*/
/**
* signs a block and returns the signature.
*
* @memberof BananoUtil
* @param {string} privateKeyOrSigner the private key to use to sign or signer object (ledger).
* @param {Block} block block to sign
* @return {string} the signature
*/
const sign = async (privateKeyOrSigner, block) => {
if (typeof privateKeyOrSigner === 'object') {
// type is signer
const hwResponse = await privateKeyOrSigner.signBlock(block);
return hwResponse.signature;
} else {
// type is private key
return signHash(privateKeyOrSigner, hash(block));
}
};
const generateAccountKeyPair = (accountSecretKeyBytes) => {
return nacl.sign.keyPair.fromSecretKey(accountSecretKeyBytes);
};
/**
* returns true if the work (in bytes) for the hash (in bytes) is valid.
*
* @memberof BananoUtil
* @param {Uint8Array} bytes the bytes to hash.
* @param {{number}} size the digest size
* @return {Uint8Array} the bytes of the hash.
*/
const getBlake2bHash = (bytes, size) => {
const context = blake.blake2bInit(size);
blake.blake2bUpdate(context, bytes);
const output = blake.blake2bFinal(context);
return output;
};
/**
* returns true if the work (in bytes) for the hash (in bytes) is valid.
*
* @memberof BananoUtil
* @param {string} hashBytes the hash bytes to check.
* @param {Uint8Array} workBytes the work bytes to check.
* @return {boolean} true if the work is valid for the hash.
*/
const isWorkValid = (hashBytes, workBytes) => {
const context = blake.blake2bInit(8);
blake.blake2bUpdate(context, workBytes);
blake.blake2bUpdate(context, hashBytes);
const output = blake.blake2bFinal(context).reverse();
const outputHex = bytesToHex(output);
const outputBigInt = BigInt('0x' + outputHex);
const retval = outputBigInt >= workMin;
/* istanbul ignore if */
if (LOG_IS_WORK_VALID) {
console.log(`isWorkValid ${outputBigInt} >= ${workMin} ? ${retval}`);
}
return retval;
};
const incrementBytes = (bytes) => {
let x = bytes.length - 1;
for (x; x >= 0; x--) {
if (bytes[x] ^ 0xff) {
bytes[x]++;
return;
} else {
bytes[x] = 0;
}
}
};
/**
* creates a new Uint8Array(8) to calculate work bytes.
*
* @memberof BananoUtil
* @return {Uint8Array} the bytes in a Uint8Array.
*/
const getZeroedWorkBytes = () => {
return new Uint8Array(8);
};
const getHashCPUWorker = (hash, workBytes) => {
/* istanbul ignore if */
if (LOG_GET_HASH_CPU_WORKER) {
console.log('STARTED getHashCPUWorker', hash, bytesToHex(workBytes));
}
/* istanbul ignore if */
if (hash === undefined) {
throw Error('hash is a required parameter.');
}
/* istanbul ignore if */
if (workBytes === undefined) {
throw Error('workBytes is a required parameter.');
}
const hashBytes = hexToBytes(hash);
// const startTime = process.hrtime.bigint();
let isWorkValidFlag = isWorkValid(hashBytes, workBytes);
// let isWorkValidNanos = process.hrtime.bigint() - startTime;
// let incrementBytesNanos = BigInt(0);
while (!isWorkValidFlag) {
// const startTime0 = process.hrtime.bigint();
incrementBytes(workBytes);
// incrementBytesNanos += process.hrtime.bigint() - startTime0;
// const startTime1 = process.hrtime.bigint();
isWorkValidFlag = isWorkValid(hashBytes, workBytes);
// isWorkValidNanos += process.hrtime.bigint() - startTime1;
}
const retval = bytesToHex(workBytes.reverse());
/* istanbul ignore if */
if (LOG_GET_HASH_CPU_WORKER) {
console.log(
'SUCCESS getHashCPUWorker',
hash,
bytesToHex(startWorkBytes),
retval,
);
}
return retval;
};
/**
* Get the public key for a given private key.
*
* @memberof BananoUtil
* @param {string} privateKeyOrSigner the private key or signer object (ledger).
* @return {Promise<string>} the public key.
*/
const getPublicKey = async (privateKeyOrSigner) => {
if (typeof privateKeyOrSigner === 'object') {
// type is signer
return await privateKeyOrSigner.getPublicKey();
}
// type is private key
const accountKeyPair = generateAccountKeyPair(hexToBytes(privateKeyOrSigner));
return bytesToHex(accountKeyPair.publicKey);
};
/**
* validates a seed.
*
* @memberof BananoUtil
* @param {string} seed the seed to use to validate.
* @param {string} seedIx the index to use with the seed.
* @return {object} {valid:[true/false] message:[if false, why]}.
*/
const isSeedValid = (seed) => {
const regex = new RegExp(SEED_ALPHABET_REGEX_STR);
const isValid = regex.test(seed);
const retval = {};
retval.valid = isValid;
if (isValid) {
retval.message = '';
} else {
retval.message = `does not match regex '${SEED_ALPHABET_REGEX_STR}'`;
}
return retval;
};
/**
* Get the private key for a given seed.
*
* @memberof BananoUtil
* @param {string} seed the seed to use to find the account.
* @param {number} seedIx the index to use with the seed.
* @return {string} the private key.
*/
const getPrivateKey = (seed, seedIx) => {
/* istanbul ignore if */
if (seed === undefined) {
throw Error('seed is a required parameter.');
}
/* istanbul ignore if */
if (seedIx === undefined) {
throw Error('seedIx is a required parameter.');
}
const isValid = isSeedValid(seed);
if (!isValid.valid) {
throw Error(`Invalid BANANO seed '${seed}', ${isValid.message}`);
}
const seedBytes = hexToBytes(seed);
const accountBytes = generateAccountSecretKeyBytes(seedBytes, seedIx);
return bytesToHex(accountBytes);
};
const send = async (
bananodeApi,
seed,
seedIx,
destAccount,
amountRaw,
successCallback,
failureCallback,
accountPrefix,
) => {
/* istanbul ignore if */
if (bananodeApi === undefined) {
throw Error('bananodeApi is a required parameter.');
}
/* istanbul ignore if */
if (seed === undefined) {
throw Error('privateKey is a required parameter.');
}
/* istanbul ignore if */
if (seedIx === undefined) {
throw Error('privateKey is a required parameter.');
}
/* istanbul ignore if */
if (destAccount === undefined) {
throw Error('destAccount is a required parameter.');
}
/* istanbul ignore if */
if (amountRaw === undefined) {
throw Error('amountRaw is a required parameter.');
}
/* istanbul ignore if */
if (successCallback === undefined) {
throw Error('successCallback is a required parameter.');
}
/* istanbul ignore if */
if (failureCallback === undefined) {
throw Error('failureCallback is a required parameter.');
}
/* istanbul ignore if */
if (accountPrefix === undefined) {
throw Error('accountPrefix is a required parameter.');
}
/* istanbul ignore if */
if (LOG_SEND) {
console.log(`STARTED send ${seed} ${seedIx}`);
}
const privateKey = getPrivateKey(seed, seedIx);
/* istanbul ignore if */
if (LOG_SEND) {
console.log(`INTERIM send ${seed} ${seedIx} ${privateKey}`);
}
await sendFromPrivateKey(
bananodeApi,
privateKey,
destAccount,
amountRaw,
accountPrefix,
)
.then((hash) => {
/* istanbul ignore if */
if (LOG_SEND) {
console.log(`SUCCESS send ${seed} ${seedIx} ${hash}`);
}
successCallback(hash);
})
.catch((error) => {
/* istanbul ignore if */
if (LOG_SEND) {
console.log('FAILURE send', error);
}
failureCallback(error);
});
};
const sendFromPrivateKey = async (
bananodeApi,
privateKey,
destAccount,
amountRaw,
accountPrefix,
) => {
/* istanbul ignore if */
if (bananodeApi === undefined) {
throw Error('bananodeApi is a required parameter.');
}
/* istanbul ignore if */
if (privateKey === undefined) {
throw Error('privateKey is a required parameter.');
}
/* istanbul ignore if */
if (destAccount === undefined) {
throw Error('destAccount is a required parameter.');
}
/* istanbul ignore if */
if (amountRaw === undefined) {
throw Error('amountRaw is a required parameter.');
}
/* istanbul ignore if */
if (accountPrefix === undefined) {
throw Error('accountPrefix is a required parameter.');
}
return await sendFromPrivateKeyWithRepresentative(
bananodeApi,
privateKey,
destAccount,
amountRaw,
undefined,
accountPrefix,
);
};
const sendFromPrivateKeyWithRepresentative = async (
bananodeApi,
privateKey,
destAccount,
amountRaw,
newRepresentative,
accountPrefix,
) => {
/* istanbul ignore if */
if (bananodeApi === undefined) {
throw Error('bananodeApi is a required parameter.');
}
/* istanbul ignore if */
if (privateKey === undefined) {
throw Error('privateKey is a required parameter.');
}
/* istanbul ignore if */
if (destAccount === undefined) {
throw Error('destAccount is a required parameter.');
}
/* istanbul ignore if */
if (amountRaw === undefined) {
throw Error('amountRaw is a required parameter.');
}
/* istanbul ignore if */
if (accountPrefix === undefined) {
throw Error('accountPrefix is a required parameter.');
}
return await sendFromPrivateKeyWithRepresentativeAndPrevious(
bananodeApi,
privateKey,
destAccount,
amountRaw,
newRepresentative,
undefined,
accountPrefix,
);
};
const sendFromPrivateKeyWithRepresentativeAndPrevious = async (
bananodeApi,
privateKey,
destAccount,
amountRaw,
newRepresentative,
newPrevious,
accountPrefix,
) => {
/* istanbul ignore if */
if (bananodeApi === undefined) {
throw Error('bananodeApi is a required parameter.');
}
/* istanbul ignore if */