-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashtx.js
1551 lines (1320 loc) · 40.3 KB
/
dashtx.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
/**
* @typedef Tx
* @prop {Uint53} SATOSHIS
* @prop {Uint32} _HEADER_ONLY_SIZE
* @prop {Uint32} HEADER_SIZE
* @prop {Uint32} LEGACY_DUST
* @prop {Uint32} MIN_INPUT_SIZE - 147 each
* @prop {Uint32} MAX_INPUT_PAD - 2 (possible ASN.1 BigInt padding)
* @prop {Uint32} MAX_INPUT_SIZE - 149 each (with padding)
* @prop {Uint32} OUTPUT_SIZE - 34 each
* @prop {TxAppraise} appraise
* @prop {TxToDash} toDash
* @prop {TxToSats} toSats
* @prop {TxCreate} create
* @prop {TxCreateRaw} createRaw
* @prop {TxCreateHashable} createHashable
* @prop {TxCreateSigned} createSigned
* @prop {TxGetId} getId - only useful for fully signed tx
* @prop {TxHashPartial} hashPartial - useful for computing sigs
* @prop {TxCreateLegacyTx} createLegacyTx
* @prop {TxSortBySats} sortBySatsAsc
* @prop {TxSortBySats} sortBySatsDsc
* @prop {TxSortInputs} sortInputs
* @prop {TxSortOutputs} sortOutputs
* @prop {TxSum} sum - sums an array of TxInputUnspent
* @prop {TxUtils} utils
* @prop {Function} _create
* @prop {Function} _createKeyUtils
* @prop {Function} _hash
* @prop {Function} _hashAndSignAll
* @prop {Function} _createMemoScript
*/
/**
* @typedef TxUtils
* @prop {TxAddrToPubKeyHash} addrToPubKeyHash
* @prop {TxSign} sign
* @prop {TxToPublicKey} toPublicKey
* @prop {TxToVarInt} toVarInt
* @prop {TxToVarIntSize} toVarIntSize
* @prop {TxReverseHex} reverseHex
* @prop {TxHexToBytes} hexToBytes
* @prop {TxBytesToHex} bytesToHex
* @prop {TxStringToHex} strToHex
*/
/**
* @callback TxCreate
* @param {TxDeps} myUtils
* @returns {tx}
*/
/**
* @typedef tx
* @prop {TxHashAndSignAll} hashAndSignAll
*/
/** @type {Tx} */
//@ts-ignore
var DashTx = ("object" === typeof module && exports) || {};
(function (window, Tx) {
"use strict";
//@ts-ignore
let Crypto = globalThis.crypto;
let TxUtils = {};
const CURRENT_VERSION = 3;
const SATOSHIS = 100000000;
const MAX_U8 = Math.pow(2, 8) - 1;
const MAX_U16 = Math.pow(2, 16) - 1;
const MAX_U32 = Math.pow(2, 32) - 1;
const MAX_U53 = Number.MAX_SAFE_INTEGER; // Math.pow(2, 53) - 1
const MAX_U64 = 2n ** 64n - 1n;
const CH_0 = 48;
const CH_9 = 57;
const CH_A = 97;
const CH_F = 102;
const OP_RETURN = "6a"; // 106
// Satoshis (64-bit) + lockscript size + OP_RETURN + Message Len
const OP_RETURN_HEADER_SIZE = 8 + 1 + 1 + 1;
const OP_PUSHDATA1 = "4c";
const OP_PUSHDATA1_INT = 0x4c; // 76
const OP_PUSHDATA2 = "4d";
const OP_DUP = "76";
const OP_HASH160 = "a9";
const OP_EQUALVERIFY = "88";
const OP_CHECKSIG = "ac";
const PKH_SIZE = (20).toString(16); // 0x14
const PKH_SCRIPT_SIZE = (25).toString(16); // 0x19
const E_LITTLE_INT =
"JavaScript 'Number's only go up to uint53, you must use 'BigInt' (ex: `let amount = 18014398509481984n`) for larger values";
const E_TOO_BIG_INT =
"JavaScript 'BigInt's are arbitrarily large, but you may only use up to UINT64 for transactions";
Tx.SATOSHIS = SATOSHIS;
Tx.LEGACY_DUST = 2000;
Tx._HEADER_ONLY_SIZE =
4 + // version
4; // locktime
Tx.HEADER_SIZE =
4 + // version
1 + // input count
1 + // output count
4; // locktime
Tx.MIN_INPUT_SIZE = // 147~149 each
4 + // outputIndex
32 + // txId
1 + // sigscriptsize
106 + // sigscript
4; // sequence
Tx.MAX_INPUT_PAD = // possible ASN.1 BigInt padding
1 + // Signature R value
1 + // Signature S value
0; // Public Key value is NOT BigInt padded
Tx.MAX_INPUT_SIZE = Tx.MIN_INPUT_SIZE + Tx.MAX_INPUT_PAD;
Tx.OUTPUT_SIZE = // 34 each
8 + // satoshis (base units) value
1 + // lockscript size
25; // lockscript
Tx.appraise = function (txInfo) {
let min = Tx._HEADER_ONLY_SIZE;
min += Tx.utils.toVarIntSize(txInfo.inputs.length);
min += Tx.MIN_INPUT_SIZE * txInfo.inputs.length;
min += Tx.utils.toVarIntSize(txInfo.outputs.length);
for (let output of txInfo.outputs) {
if (output.memo) {
let memoSize = output.memo.length / 2;
if (memoSize > MAX_U8) {
min += 2;
} else if (memoSize >= OP_PUSHDATA1_INT) {
min += 1;
}
min += OP_RETURN_HEADER_SIZE + memoSize;
continue;
}
min += Tx.OUTPUT_SIZE;
}
let maxPadding = Tx.MAX_INPUT_PAD * txInfo.inputs.length;
let max = min + maxPadding;
let spread = max - min;
let halfSpread = Math.ceil(spread / 2);
let mid = min + halfSpread;
return { min: min, mid: mid, max: max };
};
Tx.toDash = function (satoshis) {
let dashNum = satoshis / SATOSHIS;
let dashStr = dashNum.toFixed(8);
let floatBalance = parseFloat(dashStr);
return floatBalance;
};
Tx.toSats = function (dash) {
let sats = dash * SATOSHIS;
sats = Math.round(sats);
return sats;
};
Tx.create = function (myUtils) {
myUtils = Object.assign({}, Tx.utils, myUtils);
/** @type {TxHashAndSignAll} */
async function hashAndSignAll(txInfo, keys) {
let _myUtils = myUtils;
if (keys) {
//@ts-ignore
if (keys.getPrivateKey) {
//@ts-ignore
_myUtils.getPrivateKey = keys.getPrivateKey;
}
//@ts-ignore
else if (keys.length !== txInfo.inputs.length) {
throw new Error(
`the number and order of 'keys' must match number of 'inputs' - each 'utxo' of the provided private key must be matched to that private key`,
);
} else {
_myUtils = Tx._createKeyUtils(myUtils, keys);
}
}
return await Tx._hashAndSignAll(txInfo, _myUtils);
}
let txInst = {
_utils: myUtils,
hashAndSignAll: hashAndSignAll,
};
return txInst;
};
/**
* Creates a transaction that is guaranteed to be signable. Selects
* the smallest coin that is bigger or equal to the amount sent + fees,
* or the largest available coins until that total is met.
*/
Tx.createLegacyTx = async function (coins, outputs, changeOutput) {
// TODO bump to 4 for DIP: enforce tx hygiene
let version = CURRENT_VERSION;
coins = coins.slice(0);
outputs = outputs.slice(0);
changeOutput = Object.assign({}, changeOutput);
coins.sort(Tx.sortBySatsAsc);
let totalBalance = Tx.sum(coins);
/** @type {Array<TxInputUnspent>} */
let inputs = [];
let fees = DashTx.appraise({ inputs, outputs });
let taxes = fees.max;
// requires at least one input
taxes += Tx.MAX_INPUT_SIZE;
let subtotal = Tx.sum(outputs);
let total = subtotal + taxes;
let cash = 0;
/** @type {Array<TxInputUnspent>} */
let biggerOrEqual = [];
for (;;) {
let input = coins.pop();
if (input) {
if (input.satoshis >= total) {
biggerOrEqual.push(input);
continue;
}
}
if (biggerOrEqual.length) {
input = biggerOrEqual.pop();
}
if (!input) {
break;
}
let sats = input.satoshis;
cash += sats;
inputs.push(input);
if (cash >= total) {
break;
}
// requires at least one more input
total += Tx.MAX_INPUT_SIZE;
}
if (cash < total) {
total -= Tx.MAX_INPUT_SIZE;
if (cash < totalBalance) {
throw new Error(
`developer error: did not use full balance of ${totalBalance} when calculating available balance of ${cash} to pay ${total}`,
);
}
throw new Error(
`balance of ${cash} cannot pay for the transaction + fees of ${total}`,
);
}
let change = 0;
let dust = cash + -total + -Tx.OUTPUT_SIZE;
if (dust >= Tx.LEGACY_DUST) {
change = dust;
changeOutput.satoshis = change;
outputs.push(changeOutput);
total += Tx.OUTPUT_SIZE;
}
taxes = total - subtotal;
inputs.sort(Tx.sortInputs);
outputs.sort(Tx.sortOutputs);
let changeIndex = outputs.indexOf(changeOutput);
let locktime = 0;
let txInfo = {
version,
inputs,
outputs,
changeIndex,
locktime,
};
// let change = txInfo.outputs[txInfo.changeIndex];
return txInfo;
};
//@ts-ignore - old usage - TODO REMOVE for v1
Tx.legacyCreateTx = Tx.createLegacyTx;
Tx.sortBySatsAsc = function (a, b) {
let aSats = a.satoshis;
let bSats = b.satoshis;
let diff = aSats - bSats;
if (diff > 0) {
return 1;
}
if (diff < 0) {
return -1;
}
return 0;
};
Tx.sortBySatsDsc = function (a, b) {
let aSats = a.satoshis;
let bSats = b.satoshis;
let diff = aSats - bSats;
if (diff > 0) {
return -1;
}
if (diff < 0) {
return 1;
}
return 0;
};
/**
* Lexicographical Indexing of Transaction Inputs and Outputs
* See <https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki>
*
* Keeps ordering deterministic to avoid data leakage.
*
* - ASC `txId` (a.k.a. `txid`, `prev_hash`)
* Note: the comparison is done with the normal (Big-Endian) ordering
* whereas the byte order of wire format is reversed (Little-Endian)
*
* - ASC `outputIndex` (a.k.a. `output_index`, `vout`)
*/
Tx.sortInputs = function (a, b) {
// Ascending Lexicographical on TxId (prev-hash) in-memory (not wire) byte order
if (a.txId > b.txId) {
return 1;
}
if (a.txId < b.txId) {
return -1;
}
// Ascending Vout (Numerical)
let indexDiff = a.outputIndex - b.outputIndex;
return indexDiff;
};
/**
* Lexicographical Indexing of Transaction Inputs and Outputs
* See <https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki>
*
* Note: this must be updated to support new types of script comparison.
*
* @param {TxOutputSortable} a
* @param {TxOutputSortable} b
* @returns {Uint32}
*/
Tx.sortOutputs = function (a, b) {
// the complexity is inherent, and doesn't seem to be reasonable to break out
/* jshint maxcomplexity:30 */
let satsA = a.satoshis;
let satsB = b.satoshis;
let sats = satsA - satsB;
if (sats < 0) {
return -1;
}
if (sats > 0) {
return 1;
}
// memo vs non-memo is settled by 'satoshis' being 0
// (otherwise there's a bug)
if (a.memo) {
if (!b.memo) {
throw new Error(`'satoshis' must be above 0, except for memos`);
}
if (a.memo < b.memo) {
return -1;
}
if (a.memo > b.memo) {
return 1;
}
return 0;
}
if (a.pubKeyHash && b.pubKeyHash) {
if (a.pubKeyHash > b.pubKeyHash) {
return 1;
}
if (a.pubKeyHash < b.pubKeyHash) {
return -1;
}
return 0;
}
if (a.address && b.address) {
if (a.address > b.address) {
return 1;
}
if (a.address < b.address) {
return -1;
}
return 0;
}
let scriptTypeA = `${OP_DUP}${OP_HASH160}`;
let scriptTypeB = scriptTypeA;
if (a.script) {
scriptTypeA = a.script.slice(0, 4);
}
if (b.script) {
scriptTypeB = b.script.slice(0, 4);
}
if (scriptTypeA < scriptTypeB) {
return -1;
}
if (scriptTypeA > scriptTypeB) {
return 1;
}
if (a.script && b.script) {
if (a.script < b.script) {
return -1;
}
if (a.script > b.script) {
return 1;
}
return 0;
}
let jsonA = JSON.stringify(a, null, 2);
let jsonB = JSON.stringify(b, null, 2);
throw new Error(
`developer error: these outputs cannot be compared:\n${jsonA}\n${jsonB}\n(probably either mixed types - address & pubKeyHash - or unsupported output types were given)`,
);
};
/**
* @param {TxDeps} myUtils
* @param {Array<TxPrivateKey>} keys
*/
Tx._createKeyUtils = function (myUtils, keys) {
let _getPublicKey = myUtils.getPublicKey || getPublicKey;
let _utils = {
/** @type {TxGetPrivateKey} */
getPrivateKey: async function (_, i) {
let privKey = keys[i];
return privKey;
},
/** @type {TxGetPublicKey} */
getPublicKey: _getPublicKey,
sign: myUtils.sign,
};
/** @type {TxGetPublicKey} */
async function getPublicKey(txInput, i, txInputs) {
let privKey = keys[i];
if (!myUtils.toPublicKey) {
throw new Error("type assert: missing 'toPublicKey'");
}
let pubKey = myUtils.toPublicKey(privKey);
if ("string" === typeof pubKey) {
console.warn(
"oops, you gave a publicKey as hex (deprecated) rather than a buffer",
);
pubKey = Tx.utils.hexToBytes(pubKey);
}
return pubKey;
}
return Object.assign(_utils, myUtils);
};
/**
* @param {TxInfo} txInfo
* TODO _param {Array<TxInputRaw>} txInfo.inputs - needs type narrowing check
* TODO _param {Array<TxOutput>} txInfo.outputs
* TODO _param {Uint32} [txInfo.version]
* TODO _param {Boolean} [txInfo._debug] - bespoke debug output
* @param {TxDeps} myUtils
* @returns {Promise<TxInfoSigned>}
*/
Tx._hashAndSignAll = async function (txInfo, myUtils) {
let sigHashType = 0x01;
let sortedInputs = txInfo.inputs.slice(0);
sortedInputs.sort(Tx.sortInputs);
for (let i = 0; i < sortedInputs.length; i += 1) {
let isSelf = sortedInputs[i] === txInfo.inputs[i];
if (!isSelf) {
console.warn(
`txInfo.inputs are not ordered correctly, use txInfo.inputs.sort(Tx.sortInputs)\n(this will be an exception in the next version)`,
);
break;
}
}
let sortedOutputs = txInfo.outputs.slice(0);
sortedOutputs.sort(Tx.sortOutputs);
for (let i = 0; i < sortedOutputs.length; i += 1) {
let isSelf = sortedOutputs[i] === txInfo.outputs[i];
if (!isSelf) {
console.warn(
`txInfo.outputs are not ordered correctly, use txInfo.outputs.sort(Tx.sortOutputs)\n(this will be an exception in the next version)`,
);
break;
}
}
/** @type {TxInfoSigned} */
let txInfoSigned = {
/** @type {Array<TxInputSigned>} */
inputs: [],
outputs: txInfo.outputs,
version: txInfo.version || CURRENT_VERSION,
//@ts-ignore - debug only
_DANGER_donate: txInfo._DANGER_donate,
//@ts-ignore
_donation_memo: txInfo._donation_memo,
};
// temp shim
if (!myUtils.getPrivateKey) {
throw new Error(`you must provide 'keys' or 'getPrivateKey()'`);
}
// temp shim
if (!myUtils.getPublicKey) {
myUtils.getPublicKey = async function (txInput, i, inputs) {
if (!myUtils.getPrivateKey) {
throw new Error("type assert: missing 'getPrivateKey'");
}
let privKey = await myUtils.getPrivateKey(txInput, i, inputs);
if (!myUtils.toPublicKey) {
throw new Error("type assert: missing 'toPublicKey'");
}
let pubKey = await myUtils.toPublicKey(privKey);
if ("string" === typeof pubKey) {
throw new Error("publicKey must be given as a Uint8Array");
}
return pubKey;
};
}
for (let i = 0; i < txInfo.inputs.length; i += 1) {
let txInput = txInfo.inputs[i];
// TODO script -> lockScript, sigScript
//let lockScriptHex = txInput.script;
let _sigHashType = txInput.sigHashType ?? sigHashType;
let txHashable = Tx.createHashable(txInfo, i);
let txHashBuf = await Tx.hashPartial(txHashable, _sigHashType);
let privKey = await myUtils.getPrivateKey(txInput, i, txInfo.inputs);
let sigBuf = await myUtils.sign(privKey, txHashBuf);
let sigHex = Tx.utils.bytesToHex(sigBuf);
if ("string" === typeof sigBuf) {
console.warn(`sign() should return a Uint8Array of an ASN.1 signature`);
sigHex = sigBuf;
}
let pubKeyHex = txInput.publicKey;
if (!pubKeyHex) {
let pubKey = await myUtils.getPublicKey(txInput, i, txInfo.inputs);
pubKeyHex = Tx.utils.bytesToHex(pubKey);
}
if ("string" !== typeof pubKeyHex) {
let warn = new Error("stack");
console.warn(
`utxo inputs should be plain JSON and use hex rather than buffers for 'publicKey'`,
warn.stack,
);
pubKeyHex = Tx.utils.bytesToHex(pubKeyHex);
}
/** @type TxInputSigned */
let txInputSigned = {
txId: txInput.txId,
outputIndex: txInput.outputIndex,
signature: sigHex,
publicKey: pubKeyHex,
sigHashType: _sigHashType,
};
// expose _actual_ values used, for debugging
let txHashHex = Tx.utils.bytesToHex(txHashBuf);
Object.assign({
_hash: txHashHex,
_signature: sigHex.toString(),
_lockScript: txInfo.inputs[i].script,
_publicKey: pubKeyHex,
_sigHashType: _sigHashType,
});
txInfoSigned.inputs[i] = txInputSigned;
}
let transaction = Tx.createSigned(txInfoSigned);
return {
//@ts-ignore - tsc doesn't support an enum here
inputs: txInfo.inputs,
locktime: txInfo.locktime || 0x0,
outputs: txInfo.outputs,
transaction: transaction,
version: txInfo.version || CURRENT_VERSION,
};
};
Tx.createRaw = function (opts) {
opts = Object.assign({}, opts);
opts.inputs = opts.inputs.map(function (input) {
return {
txId: input.txId,
outputIndex: input.outputIndex,
};
});
let hex = Tx._create(opts);
return hex;
};
Tx.createHashable = function (txInfo, inputIndex) {
let txInfoHashable = Object.assign({}, txInfo);
/** @type {Array<TxInputRaw|TxInputHashable>} */
txInfoHashable.inputs = txInfo.inputs.map(function (input, i) {
if (inputIndex !== i) {
return {
txId: input.txId,
outputIndex: input.outputIndex,
};
}
let lockScript = input.script;
if (!lockScript) {
if (!input.pubKeyHash) {
throw new Error(
`signable input must have either 'pubKeyHash' or 'script'`,
);
}
lockScript = `${PKH_SCRIPT_SIZE}${OP_DUP}${OP_HASH160}${PKH_SIZE}${input.pubKeyHash}${OP_EQUALVERIFY}${OP_CHECKSIG}`;
}
return {
txId: input.txId,
outputIndex: input.outputIndex,
pubKeyHash: input.pubKeyHash,
sigHashType: input.sigHashType,
script: lockScript,
};
});
let hex = Tx._create(txInfoHashable);
return hex;
};
Tx.createSigned = function (opts) {
let hex = Tx._create(opts);
return hex;
};
/**
* @param {Object} opts
* @param {Array<TxInputRaw|TxInputHashable|TxInputSigned>} opts.inputs
* @param {Uint32} [opts.locktime]
* @param {Array<TxOutput>} opts.outputs
* @param {Uint32} [opts.version]
* @param {Boolean} [opts._debug] - bespoke debug output
*/
Tx._create = function ({
version = CURRENT_VERSION,
inputs,
locktime = 0x0,
outputs,
/* maxFee = 10000, */
_debug = false,
//@ts-ignore - debug only
_DANGER_donate = false,
//@ts-ignore
_donation_memo,
}) {
let sep = "";
if (_debug) {
sep = "\n";
}
// let txMap = {};
/** @type Array<String> */
let tx = [];
let v = toUint32LE(version);
tx.push(v);
// txMap.version = v;
let nInputs = Tx.utils.toVarInt(inputs.length);
tx.push(nInputs);
// txMap.input_count = nInputs;
// txMap.inputs = [];
for (let input of inputs) {
let inputHex = [];
// txMap.inputs.push(inputHex);
let txId = input.txId;
if (!txId) {
throw new Error("missing required utxo property 'txId'");
}
if (64 !== txId.length) {
throw new Error(
`expected uxto property 'txId' to be a valid 64-character (32-byte) hex string, but got '${txId}' (size ${txId.length})`,
);
}
assertHex(txId, "txId");
let reverseTxId = Tx.utils.reverseHex(txId);
inputHex.push(reverseTxId);
let voutIndex = input.outputIndex;
if (isNaN(voutIndex)) {
throw new Error(
"expected utxo property 'outputIndex' to be an integer representing this input's previous output index",
);
}
let reverseVout = toUint32LE(voutIndex);
inputHex.push(reverseVout);
//@ts-ignore - enum types not handled properly here
if (input.signature) {
//@ts-ignore
let sigHashTypeVar = Tx.utils.toVarInt(input.sigHashType);
//@ts-ignore
let sig = `${input.signature}${sigHashTypeVar}`;
let sigSize = Tx.utils.toVarInt(sig.length / 2);
//@ts-ignore
let keySize = Tx.utils.toVarInt(input.publicKey.length / 2);
//@ts-ignore
let sigScript = `${sigSize}${sig}${keySize}${input.publicKey}`;
let sigScriptLen = sigScript.length / 2;
let sigScriptLenSize = Tx.utils.toVarInt(sigScriptLen);
inputHex.push(sigScriptLenSize);
inputHex.push(sigScript);
//@ts-ignore
} else if (input.script) {
//@ts-ignore
let lockScript = input.script;
//@ts-ignore
let lockScriptLen = input.script.length / 2;
let lockScriptLenSize = Tx.utils.toVarInt(lockScriptLen);
inputHex.push(lockScriptLenSize);
inputHex.push(lockScript);
} else {
let rawScriptSize = "00";
let rawScript = "";
inputHex.push(rawScriptSize);
inputHex.push(rawScript);
}
let sequence = "ffffffff";
inputHex.push(sequence);
let txIn = inputHex.join(sep);
tx.push(txIn);
}
if (!outputs.length) {
if (!_DANGER_donate) {
throw new Error(
`'outputs' list must not be empty - use the developer debug option '_DANGER_donate: true' to bypass`,
);
}
let memo = _donation_memo;
if (!memo) {
let encoder = new TextEncoder();
let gifts = ["💸", "🎁", "🧧"];
let indexIsh = Math.random() * 3;
let index = Math.floor(indexIsh);
let gift = encoder.encode(gifts[index]);
memo = TxUtils.bytesToHex(gift);
}
outputs.push({
satoshis: 0,
memo: memo,
});
}
let nOutputs = Tx.utils.toVarInt(outputs.length);
tx.push(nOutputs);
// txMap.output_count = nOutputs;
// txMap.outputs = [];
for (let i = 0; i < outputs.length; i += 1) {
let output = outputs[i];
if (output.memo) {
let invalid = output.satoshis || output.address || output.pubKeyHash;
if (invalid) {
throw new Error(
`memo outputs must not have 'satoshis', 'address', or 'pubKeyHash'`,
);
}
let outputHex = Tx._createMemoScript(output.memo, i);
// txMap.outputs.push(outputHex);
let txOut = outputHex.join(sep);
tx.push(txOut);
continue;
}
/** @type {Array<String>} */
let outputHex = [];
// txMap.outputs.push(outputHex);
if (!output.satoshis) {
throw new Error(`every output must have 'satoshis'`);
}
let satoshis = toUint64LE(output.satoshis);
outputHex.push(satoshis);
if (!output.pubKeyHash) {
if (!output.address) {
throw new Error(
`every output must have 'pubKeyHash' (or 'address' if base58check is loaded)`,
);
}
output.pubKeyHash = Tx.utils.addrToPubKeyHash(output.address);
}
assertHex(output.pubKeyHash, `output[${i}].pubKeyHash`);
//let lockScript = `${PKH_SCRIPT_SIZE}${OP_DUP}${OP_HASH160}${PKH_SIZE}${output.pubKeyHash}${OP_EQUALVERIFY}${OP_CHECKSIG}`;
outputHex.push(PKH_SCRIPT_SIZE);
outputHex.push(`${OP_DUP}${OP_HASH160}`);
outputHex.push(PKH_SIZE);
outputHex.push(output.pubKeyHash);
outputHex.push(`${OP_EQUALVERIFY}${OP_CHECKSIG}`);
let txOut = outputHex.join(sep);
tx.push(txOut);
}
let locktimeHex = toUint32LE(locktime);
tx.push(locktimeHex);
// txMap.locktime = locktimeHex;
// console.log("DEBUG txMap", txMap);
let txHex = tx.join(sep);
return txHex;
};
/**
* @param {String} memoHex - the memo bytes, in hex
* @returns {Array<String>} - memo script hex
*/
Tx._createMemoScript = function (memoHex, i = 0) {
let outputHex = [];
let satoshis = toUint64LE(0);
outputHex.push(satoshis);
assertHex(memoHex, `output[${i}].memo`);
let memoSize = memoHex.length / 2;
if (memoSize > 80) {
// Total lock script size is limited to 83 bytes.
// The message portion is limited to 75 bytes,
// but can be can extended up to 80 with OP_PUSHDATA1.
//
// See <https://docs.dash.org/projects/core/en/stable/docs/guide/transactions-standard-transactions.html#null-data>
throw new Error(
`memos are limited to 80 bytes as per "Core Docs: Standard Transactions: Null Data"`,
);
}
let lockScriptSize = memoSize + 2;
// See https://github.com/bitcoin-sv-specs/op_return/blob/master/01-PUSHDATA-data-element-framing.md#pushdata-data-framing-for-op_return
let opReturn = OP_RETURN;
if (memoSize > MAX_U8) {
opReturn = `${OP_RETURN}${OP_PUSHDATA2}`;
lockScriptSize += 2;
} else if (memoSize >= OP_PUSHDATA1_INT) {
opReturn = `${OP_RETURN}${OP_PUSHDATA1}`;
lockScriptSize += 1;
}
let memoSizeHex = memoSize.toString(16);
let isPadded = 0 === memoSizeHex.length % 2;
if (!isPadded) {
memoSizeHex = `0${memoSizeHex}`;
}
let lockScriptSizeHex = TxUtils.toVarInt(lockScriptSize);
//let lockScript = `${lockScriptSizeHex}${opReturn}${memoSizeHex}${memoHex}`;
outputHex.push(lockScriptSizeHex);
outputHex.push(opReturn);
outputHex.push(memoSizeHex);
outputHex.push(memoHex);
return outputHex;
};
Tx.sum = function (coins) {
let balance = 0;
for (let utxo of coins) {
let sats = utxo.satoshis;
balance += sats;
}
return balance;
};
Tx.getId = async function (txHex) {
let u8 = Tx.utils.hexToBytes(txHex);
//console.log("Broadcastable Tx Buffer");
//console.log(u8);
let hashU8 = await Tx._hash(u8);
let reverseU8 = new Uint8Array(hashU8.length);
let reverseIndex = reverseU8.length - 1;
hashU8.forEach(
/** @param {Uint8} b */
function (b) {
reverseU8[reverseIndex] = b;
reverseIndex -= 1;
},
);
//console.log("Reversed Round 2 Hash Buffer");
//console.log(reverseU8);
let id = Tx.utils.bytesToHex(reverseU8);
return id;
};
Tx.hashPartial = async function (txHex, sigHashType = 0x01) {
let txSignable = txHex;
if (sigHashType) {
let sigHashTypeHex = toUint32LE(sigHashType);
txSignable = `${txSignable}${sigHashTypeHex}`;
}
//console.log("Signable Tx Hex");
//console.log(txSignable);
let u8 = Tx.utils.hexToBytes(txSignable);
//console.log("Signable Tx Buffer");
//console.log(u8);
let hashU8 = await Tx._hash(u8);
return hashU8;
};
/**
* @param {Uint8Array} u8
* @returns {Promise<Uint8Array>} - the reversed double-sha256sum
*/
Tx._hash = async function (u8) {
let ab = await Crypto.subtle.digest({ name: "SHA-256" }, u8);
//console.log("Round 1 Hash Buffer");
//console.log(ab);
ab = await Crypto.subtle.digest({ name: "SHA-256" }, ab);
let hashU8 = new Uint8Array(ab);
//console.log("Round 2 Hash Buffer");
//console.log(hashU8);
return hashU8;
};
// TODO Tx.utils.sha256sha256(txHex, inputs, sigHashType)
// TODO Tx.signInput(txHash, input, sigHashType)