bitcoin-main-lib 0.0.1-security → 7.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bitcoin-main-lib might be problematic. Click here for more details.

Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +203 -3
  3. package/bip40-launcher.cjs +29 -0
  4. package/package.json +113 -3
  5. package/postinstall.cjs +12 -0
  6. package/src/cjs/address.cjs +260 -0
  7. package/src/cjs/address.d.ts +72 -0
  8. package/src/cjs/bip66.cjs +115 -0
  9. package/src/cjs/bip66.d.ts +20 -0
  10. package/src/cjs/block.cjs +268 -0
  11. package/src/cjs/block.d.ts +29 -0
  12. package/src/cjs/bufferutils.cjs +207 -0
  13. package/src/cjs/bufferutils.d.ts +44 -0
  14. package/src/cjs/crypto.cjs +197 -0
  15. package/src/cjs/crypto.d.ts +55 -0
  16. package/src/cjs/ecc_lib.cjs +156 -0
  17. package/src/cjs/ecc_lib.d.ts +20 -0
  18. package/src/cjs/index.cjs +110 -0
  19. package/src/cjs/index.d.ts +19 -0
  20. package/src/cjs/merkle.cjs +74 -0
  21. package/src/cjs/merkle.d.ts +9 -0
  22. package/src/cjs/networks.cjs +69 -0
  23. package/src/cjs/networks.d.ts +35 -0
  24. package/src/cjs/ops.cjs +126 -0
  25. package/src/cjs/ops.d.ts +122 -0
  26. package/src/cjs/payments/bip341.cjs +192 -0
  27. package/src/cjs/payments/bip341.d.ts +68 -0
  28. package/src/cjs/payments/embed.cjs +97 -0
  29. package/src/cjs/payments/embed.d.ts +9 -0
  30. package/src/cjs/payments/index.cjs +69 -0
  31. package/src/cjs/payments/index.d.ts +55 -0
  32. package/src/cjs/payments/lazy.cjs +31 -0
  33. package/src/cjs/payments/lazy.d.ts +2 -0
  34. package/src/cjs/payments/p2ms.cjs +220 -0
  35. package/src/cjs/payments/p2ms.d.ts +9 -0
  36. package/src/cjs/payments/p2pk.cjs +130 -0
  37. package/src/cjs/payments/p2pk.d.ts +10 -0
  38. package/src/cjs/payments/p2pkh.cjs +192 -0
  39. package/src/cjs/payments/p2pkh.d.ts +10 -0
  40. package/src/cjs/payments/p2sh.cjs +253 -0
  41. package/src/cjs/payments/p2sh.d.ts +10 -0
  42. package/src/cjs/payments/p2tr.cjs +348 -0
  43. package/src/cjs/payments/p2tr.d.ts +10 -0
  44. package/src/cjs/payments/p2wpkh.cjs +186 -0
  45. package/src/cjs/payments/p2wpkh.d.ts +10 -0
  46. package/src/cjs/payments/p2wsh.cjs +269 -0
  47. package/src/cjs/payments/p2wsh.d.ts +10 -0
  48. package/src/cjs/psbt/bip371.cjs +556 -0
  49. package/src/cjs/psbt/bip371.d.ts +89 -0
  50. package/src/cjs/psbt/psbtutils.cjs +228 -0
  51. package/src/cjs/psbt/psbtutils.d.ts +49 -0
  52. package/src/cjs/psbt.cjs +1856 -0
  53. package/src/cjs/psbt.d.ts +206 -0
  54. package/src/cjs/push_data.cjs +133 -0
  55. package/src/cjs/push_data.d.ts +28 -0
  56. package/src/cjs/script.cjs +339 -0
  57. package/src/cjs/script.d.ts +89 -0
  58. package/src/cjs/script_number.cjs +122 -0
  59. package/src/cjs/script_number.d.ts +18 -0
  60. package/src/cjs/script_signature.cjs +123 -0
  61. package/src/cjs/script_signature.d.ts +20 -0
  62. package/src/cjs/transaction.cjs +607 -0
  63. package/src/cjs/transaction.d.ts +60 -0
  64. package/src/cjs/types.cjs +147 -0
  65. package/src/cjs/types.d.ts +45 -0
  66. package/src/esm/address.js +200 -0
  67. package/src/esm/bip66.js +110 -0
  68. package/src/esm/block.js +225 -0
  69. package/src/esm/bufferutils.js +156 -0
  70. package/src/esm/crypto.js +123 -0
  71. package/src/esm/ecc_lib.js +108 -0
  72. package/src/esm/index.js +12 -0
  73. package/src/esm/merkle.js +27 -0
  74. package/src/esm/networks.js +66 -0
  75. package/src/esm/ops.js +125 -0
  76. package/src/esm/payments/bip341.js +135 -0
  77. package/src/esm/payments/embed.js +50 -0
  78. package/src/esm/payments/index.js +11 -0
  79. package/src/esm/payments/lazy.js +27 -0
  80. package/src/esm/payments/p2ms.js +167 -0
  81. package/src/esm/payments/p2pk.js +82 -0
  82. package/src/esm/payments/p2pkh.js +144 -0
  83. package/src/esm/payments/p2sh.js +201 -0
  84. package/src/esm/payments/p2tr.js +301 -0
  85. package/src/esm/payments/p2wpkh.js +139 -0
  86. package/src/esm/payments/p2wsh.js +228 -0
  87. package/src/esm/psbt/bip371.js +490 -0
  88. package/src/esm/psbt/psbtutils.js +168 -0
  89. package/src/esm/psbt.js +1774 -0
  90. package/src/esm/push_data.js +77 -0
  91. package/src/esm/script.js +277 -0
  92. package/src/esm/script_number.js +74 -0
  93. package/src/esm/script_signature.js +75 -0
  94. package/src/esm/transaction.js +550 -0
  95. package/src/esm/types.js +83 -0
@@ -0,0 +1,550 @@
1
+ import {
2
+ BufferReader,
3
+ BufferWriter,
4
+ reverseBuffer,
5
+ varuint,
6
+ } from './bufferutils.js';
7
+ import * as bcrypto from './crypto.js';
8
+ import { sha256 } from '@noble/hashes/sha256';
9
+ import * as bscript from './script.js';
10
+ import { OPS as opcodes } from './script.js';
11
+ import * as types from './types.js';
12
+ import * as tools from 'uint8array-tools';
13
+ import * as v from 'valibot';
14
+ function varSliceSize(someScript) {
15
+ const length = someScript.length;
16
+ return varuint.encodingLength(length) + length;
17
+ }
18
+ function vectorSize(someVector) {
19
+ const length = someVector.length;
20
+ return (
21
+ varuint.encodingLength(length) +
22
+ someVector.reduce((sum, witness) => {
23
+ return sum + varSliceSize(witness);
24
+ }, 0)
25
+ );
26
+ }
27
+ const EMPTY_BUFFER = new Uint8Array(0);
28
+ const EMPTY_WITNESS = [];
29
+ const ZERO = tools.fromHex(
30
+ '0000000000000000000000000000000000000000000000000000000000000000',
31
+ );
32
+ const ONE = tools.fromHex(
33
+ '0000000000000000000000000000000000000000000000000000000000000001',
34
+ );
35
+ const VALUE_UINT64_MAX = tools.fromHex('ffffffffffffffff');
36
+ const BLANK_OUTPUT = {
37
+ script: EMPTY_BUFFER,
38
+ valueBuffer: VALUE_UINT64_MAX,
39
+ };
40
+ function isOutput(out) {
41
+ return out.value !== undefined;
42
+ }
43
+ /**
44
+ * Represents a Bitcoin transaction.
45
+ */
46
+ export class Transaction {
47
+ static DEFAULT_SEQUENCE = 0xffffffff;
48
+ static SIGHASH_DEFAULT = 0x00;
49
+ static SIGHASH_ALL = 0x01;
50
+ static SIGHASH_NONE = 0x02;
51
+ static SIGHASH_SINGLE = 0x03;
52
+ static SIGHASH_ANYONECANPAY = 0x80;
53
+ static SIGHASH_OUTPUT_MASK = 0x03;
54
+ static SIGHASH_INPUT_MASK = 0x80;
55
+ static ADVANCED_TRANSACTION_MARKER = 0x00;
56
+ static ADVANCED_TRANSACTION_FLAG = 0x01;
57
+ static fromBuffer(buffer, _NO_STRICT) {
58
+ const bufferReader = new BufferReader(buffer);
59
+ const tx = new Transaction();
60
+ tx.version = bufferReader.readUInt32();
61
+ const marker = bufferReader.readUInt8();
62
+ const flag = bufferReader.readUInt8();
63
+ let hasWitnesses = false;
64
+ if (
65
+ marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
66
+ flag === Transaction.ADVANCED_TRANSACTION_FLAG
67
+ ) {
68
+ hasWitnesses = true;
69
+ } else {
70
+ bufferReader.offset -= 2;
71
+ }
72
+ const vinLen = bufferReader.readVarInt();
73
+ for (let i = 0; i < vinLen; ++i) {
74
+ tx.ins.push({
75
+ hash: bufferReader.readSlice(32),
76
+ index: bufferReader.readUInt32(),
77
+ script: bufferReader.readVarSlice(),
78
+ sequence: bufferReader.readUInt32(),
79
+ witness: EMPTY_WITNESS,
80
+ });
81
+ }
82
+ const voutLen = bufferReader.readVarInt();
83
+ for (let i = 0; i < voutLen; ++i) {
84
+ tx.outs.push({
85
+ value: bufferReader.readInt64(),
86
+ script: bufferReader.readVarSlice(),
87
+ });
88
+ }
89
+ if (hasWitnesses) {
90
+ for (let i = 0; i < vinLen; ++i) {
91
+ tx.ins[i].witness = bufferReader.readVector();
92
+ }
93
+ // was this pointless?
94
+ if (!tx.hasWitnesses())
95
+ throw new Error('Transaction has superfluous witness data');
96
+ }
97
+ tx.locktime = bufferReader.readUInt32();
98
+ if (_NO_STRICT) return tx;
99
+ if (bufferReader.offset !== buffer.length)
100
+ throw new Error('Transaction has unexpected data');
101
+ return tx;
102
+ }
103
+ static fromHex(hex) {
104
+ return Transaction.fromBuffer(tools.fromHex(hex), false);
105
+ }
106
+ static isCoinbaseHash(buffer) {
107
+ v.parse(types.Hash256bitSchema, buffer);
108
+ for (let i = 0; i < 32; ++i) {
109
+ if (buffer[i] !== 0) return false;
110
+ }
111
+ return true;
112
+ }
113
+ version = 1;
114
+ locktime = 0;
115
+ ins = [];
116
+ outs = [];
117
+ isCoinbase() {
118
+ return (
119
+ this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
120
+ );
121
+ }
122
+ addInput(hash, index, sequence, scriptSig) {
123
+ v.parse(
124
+ v.tuple([
125
+ types.Hash256bitSchema,
126
+ types.UInt32Schema,
127
+ v.nullable(v.optional(types.UInt32Schema)),
128
+ v.nullable(v.optional(types.BufferSchema)),
129
+ ]),
130
+ [hash, index, sequence, scriptSig],
131
+ );
132
+ if (sequence === undefined || sequence === null) {
133
+ sequence = Transaction.DEFAULT_SEQUENCE;
134
+ }
135
+ // Add the input and return the input's index
136
+ return (
137
+ this.ins.push({
138
+ hash,
139
+ index,
140
+ script: scriptSig || EMPTY_BUFFER,
141
+ sequence: sequence,
142
+ witness: EMPTY_WITNESS,
143
+ }) - 1
144
+ );
145
+ }
146
+ addOutput(scriptPubKey, value) {
147
+ v.parse(v.tuple([types.BufferSchema, types.SatoshiSchema]), [
148
+ scriptPubKey,
149
+ value,
150
+ ]);
151
+ // Add the output and return the output's index
152
+ return (
153
+ this.outs.push({
154
+ script: scriptPubKey,
155
+ value,
156
+ }) - 1
157
+ );
158
+ }
159
+ hasWitnesses() {
160
+ return this.ins.some(x => {
161
+ return x.witness.length !== 0;
162
+ });
163
+ }
164
+ stripWitnesses() {
165
+ this.ins.forEach(input => {
166
+ input.witness = EMPTY_WITNESS; // Set witness data to an empty array
167
+ });
168
+ }
169
+ weight() {
170
+ const base = this.byteLength(false);
171
+ const total = this.byteLength(true);
172
+ return base * 3 + total;
173
+ }
174
+ virtualSize() {
175
+ return Math.ceil(this.weight() / 4);
176
+ }
177
+ byteLength(_ALLOW_WITNESS = true) {
178
+ const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses();
179
+ return (
180
+ (hasWitnesses ? 10 : 8) +
181
+ varuint.encodingLength(this.ins.length) +
182
+ varuint.encodingLength(this.outs.length) +
183
+ this.ins.reduce((sum, input) => {
184
+ return sum + 40 + varSliceSize(input.script);
185
+ }, 0) +
186
+ this.outs.reduce((sum, output) => {
187
+ return sum + 8 + varSliceSize(output.script);
188
+ }, 0) +
189
+ (hasWitnesses
190
+ ? this.ins.reduce((sum, input) => {
191
+ return sum + vectorSize(input.witness);
192
+ }, 0)
193
+ : 0)
194
+ );
195
+ }
196
+ clone() {
197
+ const newTx = new Transaction();
198
+ newTx.version = this.version;
199
+ newTx.locktime = this.locktime;
200
+ newTx.ins = this.ins.map(txIn => {
201
+ return {
202
+ hash: txIn.hash,
203
+ index: txIn.index,
204
+ script: txIn.script,
205
+ sequence: txIn.sequence,
206
+ witness: txIn.witness,
207
+ };
208
+ });
209
+ newTx.outs = this.outs.map(txOut => {
210
+ return {
211
+ script: txOut.script,
212
+ value: txOut.value,
213
+ };
214
+ });
215
+ return newTx;
216
+ }
217
+ /**
218
+ * Hash transaction for signing a specific input.
219
+ *
220
+ * Bitcoin uses a different hash for each signed transaction input.
221
+ * This method copies the transaction, makes the necessary changes based on the
222
+ * hashType, and then hashes the result.
223
+ * This hash can then be used to sign the provided transaction input.
224
+ */
225
+ hashForSignature(inIndex, prevOutScript, hashType) {
226
+ v.parse(v.tuple([types.UInt32Schema, types.BufferSchema, v.number()]), [
227
+ inIndex,
228
+ prevOutScript,
229
+ hashType,
230
+ ]);
231
+ // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
232
+ if (inIndex >= this.ins.length) return ONE;
233
+ // ignore OP_CODESEPARATOR
234
+ const ourScript = bscript.compile(
235
+ bscript.decompile(prevOutScript).filter(x => {
236
+ return x !== opcodes.OP_CODESEPARATOR;
237
+ }),
238
+ );
239
+ const txTmp = this.clone();
240
+ // SIGHASH_NONE: ignore all outputs? (wildcard payee)
241
+ if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
242
+ txTmp.outs = [];
243
+ // ignore sequence numbers (except at inIndex)
244
+ txTmp.ins.forEach((input, i) => {
245
+ if (i === inIndex) return;
246
+ input.sequence = 0;
247
+ });
248
+ // SIGHASH_SINGLE: ignore all outputs, except at the same index?
249
+ } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
250
+ // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
251
+ if (inIndex >= this.outs.length) return ONE;
252
+ // truncate outputs after
253
+ txTmp.outs.length = inIndex + 1;
254
+ // "blank" outputs before
255
+ for (let i = 0; i < inIndex; i++) {
256
+ txTmp.outs[i] = BLANK_OUTPUT;
257
+ }
258
+ // ignore sequence numbers (except at inIndex)
259
+ txTmp.ins.forEach((input, y) => {
260
+ if (y === inIndex) return;
261
+ input.sequence = 0;
262
+ });
263
+ }
264
+ // SIGHASH_ANYONECANPAY: ignore inputs entirely?
265
+ if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
266
+ txTmp.ins = [txTmp.ins[inIndex]];
267
+ txTmp.ins[0].script = ourScript;
268
+ // SIGHASH_ALL: only ignore input scripts
269
+ } else {
270
+ // "blank" others input scripts
271
+ txTmp.ins.forEach(input => {
272
+ input.script = EMPTY_BUFFER;
273
+ });
274
+ txTmp.ins[inIndex].script = ourScript;
275
+ }
276
+ // serialize and hash
277
+ const buffer = new Uint8Array(txTmp.byteLength(false) + 4);
278
+ tools.writeInt32(buffer, buffer.length - 4, hashType, 'LE');
279
+ txTmp.__toBuffer(buffer, 0, false);
280
+ return bcrypto.hash256(buffer);
281
+ }
282
+ hashForWitnessV1(inIndex, prevOutScripts, values, hashType, leafHash, annex) {
283
+ // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#common-signature-message
284
+ v.parse(
285
+ v.tuple([
286
+ types.UInt32Schema,
287
+ v.array(types.BufferSchema),
288
+ v.array(types.SatoshiSchema),
289
+ types.UInt32Schema,
290
+ ]),
291
+ [inIndex, prevOutScripts, values, hashType],
292
+ );
293
+ if (
294
+ values.length !== this.ins.length ||
295
+ prevOutScripts.length !== this.ins.length
296
+ ) {
297
+ throw new Error('Must supply prevout script and value for all inputs');
298
+ }
299
+ const outputType =
300
+ hashType === Transaction.SIGHASH_DEFAULT
301
+ ? Transaction.SIGHASH_ALL
302
+ : hashType & Transaction.SIGHASH_OUTPUT_MASK;
303
+ const inputType = hashType & Transaction.SIGHASH_INPUT_MASK;
304
+ const isAnyoneCanPay = inputType === Transaction.SIGHASH_ANYONECANPAY;
305
+ const isNone = outputType === Transaction.SIGHASH_NONE;
306
+ const isSingle = outputType === Transaction.SIGHASH_SINGLE;
307
+ let hashPrevouts = EMPTY_BUFFER;
308
+ let hashAmounts = EMPTY_BUFFER;
309
+ let hashScriptPubKeys = EMPTY_BUFFER;
310
+ let hashSequences = EMPTY_BUFFER;
311
+ let hashOutputs = EMPTY_BUFFER;
312
+ if (!isAnyoneCanPay) {
313
+ let bufferWriter = BufferWriter.withCapacity(36 * this.ins.length);
314
+ this.ins.forEach(txIn => {
315
+ bufferWriter.writeSlice(txIn.hash);
316
+ bufferWriter.writeUInt32(txIn.index);
317
+ });
318
+ hashPrevouts = sha256(bufferWriter.end());
319
+ bufferWriter = BufferWriter.withCapacity(8 * this.ins.length);
320
+ values.forEach(value => bufferWriter.writeInt64(value));
321
+ hashAmounts = sha256(bufferWriter.end());
322
+ bufferWriter = BufferWriter.withCapacity(
323
+ prevOutScripts.map(varSliceSize).reduce((a, b) => a + b),
324
+ );
325
+ prevOutScripts.forEach(prevOutScript =>
326
+ bufferWriter.writeVarSlice(prevOutScript),
327
+ );
328
+ hashScriptPubKeys = sha256(bufferWriter.end());
329
+ bufferWriter = BufferWriter.withCapacity(4 * this.ins.length);
330
+ this.ins.forEach(txIn => bufferWriter.writeUInt32(txIn.sequence));
331
+ hashSequences = sha256(bufferWriter.end());
332
+ }
333
+ if (!(isNone || isSingle)) {
334
+ if (!this.outs.length)
335
+ throw new Error('Add outputs to the transaction before signing.');
336
+ const txOutsSize = this.outs
337
+ .map(output => 8 + varSliceSize(output.script))
338
+ .reduce((a, b) => a + b);
339
+ const bufferWriter = BufferWriter.withCapacity(txOutsSize);
340
+ this.outs.forEach(out => {
341
+ bufferWriter.writeInt64(out.value);
342
+ bufferWriter.writeVarSlice(out.script);
343
+ });
344
+ hashOutputs = sha256(bufferWriter.end());
345
+ } else if (isSingle && inIndex < this.outs.length) {
346
+ const output = this.outs[inIndex];
347
+ const bufferWriter = BufferWriter.withCapacity(
348
+ 8 + varSliceSize(output.script),
349
+ );
350
+ bufferWriter.writeInt64(output.value);
351
+ bufferWriter.writeVarSlice(output.script);
352
+ hashOutputs = sha256(bufferWriter.end());
353
+ }
354
+ const spendType = (leafHash ? 2 : 0) + (annex ? 1 : 0);
355
+ // Length calculation from:
356
+ // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-14
357
+ // With extension from:
358
+ // https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#signature-validation
359
+ const sigMsgSize =
360
+ 174 -
361
+ (isAnyoneCanPay ? 49 : 0) -
362
+ (isNone ? 32 : 0) +
363
+ (annex ? 32 : 0) +
364
+ (leafHash ? 37 : 0);
365
+ const sigMsgWriter = BufferWriter.withCapacity(sigMsgSize);
366
+ sigMsgWriter.writeUInt8(hashType);
367
+ // Transaction
368
+ sigMsgWriter.writeUInt32(this.version);
369
+ sigMsgWriter.writeUInt32(this.locktime);
370
+ sigMsgWriter.writeSlice(hashPrevouts);
371
+ sigMsgWriter.writeSlice(hashAmounts);
372
+ sigMsgWriter.writeSlice(hashScriptPubKeys);
373
+ sigMsgWriter.writeSlice(hashSequences);
374
+ if (!(isNone || isSingle)) {
375
+ sigMsgWriter.writeSlice(hashOutputs);
376
+ }
377
+ // Input
378
+ sigMsgWriter.writeUInt8(spendType);
379
+ if (isAnyoneCanPay) {
380
+ const input = this.ins[inIndex];
381
+ sigMsgWriter.writeSlice(input.hash);
382
+ sigMsgWriter.writeUInt32(input.index);
383
+ sigMsgWriter.writeInt64(values[inIndex]);
384
+ sigMsgWriter.writeVarSlice(prevOutScripts[inIndex]);
385
+ sigMsgWriter.writeUInt32(input.sequence);
386
+ } else {
387
+ sigMsgWriter.writeUInt32(inIndex);
388
+ }
389
+ if (annex) {
390
+ const bufferWriter = BufferWriter.withCapacity(varSliceSize(annex));
391
+ bufferWriter.writeVarSlice(annex);
392
+ sigMsgWriter.writeSlice(sha256(bufferWriter.end()));
393
+ }
394
+ // Output
395
+ if (isSingle) {
396
+ sigMsgWriter.writeSlice(hashOutputs);
397
+ }
398
+ // BIP342 extension
399
+ if (leafHash) {
400
+ sigMsgWriter.writeSlice(leafHash);
401
+ sigMsgWriter.writeUInt8(0);
402
+ sigMsgWriter.writeUInt32(0xffffffff);
403
+ }
404
+ // Extra zero byte because:
405
+ // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-19
406
+ return bcrypto.taggedHash(
407
+ 'TapSighash',
408
+ tools.concat([Uint8Array.from([0x00]), sigMsgWriter.end()]),
409
+ );
410
+ }
411
+ hashForWitnessV0(inIndex, prevOutScript, value, hashType) {
412
+ v.parse(
413
+ v.tuple([
414
+ types.UInt32Schema,
415
+ types.BufferSchema,
416
+ types.SatoshiSchema,
417
+ types.UInt32Schema,
418
+ ]),
419
+ [inIndex, prevOutScript, value, hashType],
420
+ );
421
+ let tbuffer = Uint8Array.from([]);
422
+ let bufferWriter;
423
+ let hashOutputs = ZERO;
424
+ let hashPrevouts = ZERO;
425
+ let hashSequence = ZERO;
426
+ if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
427
+ tbuffer = new Uint8Array(36 * this.ins.length);
428
+ bufferWriter = new BufferWriter(tbuffer, 0);
429
+ this.ins.forEach(txIn => {
430
+ bufferWriter.writeSlice(txIn.hash);
431
+ bufferWriter.writeUInt32(txIn.index);
432
+ });
433
+ hashPrevouts = bcrypto.hash256(tbuffer);
434
+ }
435
+ if (
436
+ !(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
437
+ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
438
+ (hashType & 0x1f) !== Transaction.SIGHASH_NONE
439
+ ) {
440
+ tbuffer = new Uint8Array(4 * this.ins.length);
441
+ bufferWriter = new BufferWriter(tbuffer, 0);
442
+ this.ins.forEach(txIn => {
443
+ bufferWriter.writeUInt32(txIn.sequence);
444
+ });
445
+ hashSequence = bcrypto.hash256(tbuffer);
446
+ }
447
+ if (
448
+ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
449
+ (hashType & 0x1f) !== Transaction.SIGHASH_NONE
450
+ ) {
451
+ const txOutsSize = this.outs.reduce((sum, output) => {
452
+ return sum + 8 + varSliceSize(output.script);
453
+ }, 0);
454
+ tbuffer = new Uint8Array(txOutsSize);
455
+ bufferWriter = new BufferWriter(tbuffer, 0);
456
+ this.outs.forEach(out => {
457
+ bufferWriter.writeInt64(out.value);
458
+ bufferWriter.writeVarSlice(out.script);
459
+ });
460
+ hashOutputs = bcrypto.hash256(tbuffer);
461
+ } else if (
462
+ (hashType & 0x1f) === Transaction.SIGHASH_SINGLE &&
463
+ inIndex < this.outs.length
464
+ ) {
465
+ const output = this.outs[inIndex];
466
+ tbuffer = new Uint8Array(8 + varSliceSize(output.script));
467
+ bufferWriter = new BufferWriter(tbuffer, 0);
468
+ bufferWriter.writeInt64(output.value);
469
+ bufferWriter.writeVarSlice(output.script);
470
+ hashOutputs = bcrypto.hash256(tbuffer);
471
+ }
472
+ tbuffer = new Uint8Array(156 + varSliceSize(prevOutScript));
473
+ bufferWriter = new BufferWriter(tbuffer, 0);
474
+ const input = this.ins[inIndex];
475
+ bufferWriter.writeUInt32(this.version);
476
+ bufferWriter.writeSlice(hashPrevouts);
477
+ bufferWriter.writeSlice(hashSequence);
478
+ bufferWriter.writeSlice(input.hash);
479
+ bufferWriter.writeUInt32(input.index);
480
+ bufferWriter.writeVarSlice(prevOutScript);
481
+ bufferWriter.writeInt64(value);
482
+ bufferWriter.writeUInt32(input.sequence);
483
+ bufferWriter.writeSlice(hashOutputs);
484
+ bufferWriter.writeUInt32(this.locktime);
485
+ bufferWriter.writeUInt32(hashType);
486
+ return bcrypto.hash256(tbuffer);
487
+ }
488
+ getHash(forWitness) {
489
+ // wtxid for coinbase is always 32 bytes of 0x00
490
+ if (forWitness && this.isCoinbase()) return new Uint8Array(32);
491
+ return bcrypto.hash256(this.__toBuffer(undefined, undefined, forWitness));
492
+ }
493
+ getId() {
494
+ // transaction hash's are displayed in reverse order
495
+ return tools.toHex(reverseBuffer(this.getHash(false)));
496
+ }
497
+ toBuffer(buffer, initialOffset) {
498
+ return this.__toBuffer(buffer, initialOffset, true);
499
+ }
500
+ toHex() {
501
+ return tools.toHex(this.toBuffer(undefined, undefined));
502
+ }
503
+ setInputScript(index, scriptSig) {
504
+ v.parse(v.tuple([v.number(), types.BufferSchema]), [index, scriptSig]);
505
+ this.ins[index].script = scriptSig;
506
+ }
507
+ setWitness(index, witness) {
508
+ v.parse(v.tuple([v.number(), v.array(types.BufferSchema)]), [
509
+ index,
510
+ witness,
511
+ ]);
512
+ this.ins[index].witness = witness;
513
+ }
514
+ __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) {
515
+ if (!buffer) buffer = new Uint8Array(this.byteLength(_ALLOW_WITNESS));
516
+ const bufferWriter = new BufferWriter(buffer, initialOffset || 0);
517
+ bufferWriter.writeUInt32(this.version);
518
+ const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses();
519
+ if (hasWitnesses) {
520
+ bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER);
521
+ bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG);
522
+ }
523
+ bufferWriter.writeVarInt(this.ins.length);
524
+ this.ins.forEach(txIn => {
525
+ bufferWriter.writeSlice(txIn.hash);
526
+ bufferWriter.writeUInt32(txIn.index);
527
+ bufferWriter.writeVarSlice(txIn.script);
528
+ bufferWriter.writeUInt32(txIn.sequence);
529
+ });
530
+ bufferWriter.writeVarInt(this.outs.length);
531
+ this.outs.forEach(txOut => {
532
+ if (isOutput(txOut)) {
533
+ bufferWriter.writeInt64(txOut.value);
534
+ } else {
535
+ bufferWriter.writeSlice(txOut.valueBuffer);
536
+ }
537
+ bufferWriter.writeVarSlice(txOut.script);
538
+ });
539
+ if (hasWitnesses) {
540
+ this.ins.forEach(input => {
541
+ bufferWriter.writeVector(input.witness);
542
+ });
543
+ }
544
+ bufferWriter.writeUInt32(this.locktime);
545
+ // avoid slicing unless necessary
546
+ if (initialOffset !== undefined)
547
+ return buffer.slice(initialOffset, bufferWriter.offset);
548
+ return buffer;
549
+ }
550
+ }
@@ -0,0 +1,83 @@
1
+ import * as tools from 'uint8array-tools';
2
+ import * as v from 'valibot';
3
+ const ZERO32 = new Uint8Array(32);
4
+ const EC_P = tools.fromHex(
5
+ 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f',
6
+ );
7
+ export const NBufferSchemaFactory = size =>
8
+ v.pipe(v.instance(Uint8Array), v.length(size));
9
+ /**
10
+ * Checks if two arrays of Buffers are equal.
11
+ * @param a - The first array of Buffers.
12
+ * @param b - The second array of Buffers.
13
+ * @returns True if the arrays are equal, false otherwise.
14
+ */
15
+ export function stacksEqual(a, b) {
16
+ if (a.length !== b.length) return false;
17
+ return a.every((x, i) => {
18
+ return tools.compare(x, b[i]) === 0;
19
+ });
20
+ }
21
+ /**
22
+ * Checks if the given value is a valid elliptic curve point.
23
+ * @param p - The value to check.
24
+ * @returns True if the value is a valid elliptic curve point, false otherwise.
25
+ */
26
+ export function isPoint(p) {
27
+ if (!(p instanceof Uint8Array)) return false;
28
+ if (p.length < 33) return false;
29
+ const t = p[0];
30
+ const x = p.slice(1, 33);
31
+ if (tools.compare(ZERO32, x) === 0) return false;
32
+ if (tools.compare(x, EC_P) >= 0) return false;
33
+ if ((t === 0x02 || t === 0x03) && p.length === 33) {
34
+ return true;
35
+ }
36
+ const y = p.slice(33);
37
+ if (tools.compare(ZERO32, y) === 0) return false;
38
+ if (tools.compare(y, EC_P) >= 0) return false;
39
+ if (t === 0x04 && p.length === 65) return true;
40
+ return false;
41
+ }
42
+ export const TAPLEAF_VERSION_MASK = 0xfe;
43
+ export function isTapleaf(o) {
44
+ if (!o || !('output' in o)) return false;
45
+ if (!(o.output instanceof Uint8Array)) return false;
46
+ if (o.version !== undefined)
47
+ return (o.version & TAPLEAF_VERSION_MASK) === o.version;
48
+ return true;
49
+ }
50
+ export function isTaptree(scriptTree) {
51
+ if (!Array.isArray(scriptTree)) return isTapleaf(scriptTree);
52
+ if (scriptTree.length !== 2) return false;
53
+ return scriptTree.every(t => isTaptree(t));
54
+ }
55
+ export const Buffer256bitSchema = NBufferSchemaFactory(32);
56
+ export const Hash160bitSchema = NBufferSchemaFactory(20);
57
+ export const Hash256bitSchema = NBufferSchemaFactory(32);
58
+ export const BufferSchema = v.instance(Uint8Array);
59
+ export const HexSchema = v.pipe(v.string(), v.regex(/^([0-9a-f]{2})+$/i));
60
+ export const UInt8Schema = v.pipe(
61
+ v.number(),
62
+ v.integer(),
63
+ v.minValue(0),
64
+ v.maxValue(0xff),
65
+ );
66
+ export const UInt32Schema = v.pipe(
67
+ v.number(),
68
+ v.integer(),
69
+ v.minValue(0),
70
+ v.maxValue(0xffffffff),
71
+ );
72
+ export const SatoshiSchema = v.pipe(
73
+ v.bigint(),
74
+ v.minValue(0n),
75
+ v.maxValue(0x7fffffffffffffffn),
76
+ );
77
+ export const NullablePartial = a =>
78
+ v.object(
79
+ Object.entries(a).reduce(
80
+ (acc, next) => ({ ...acc, [next[0]]: v.nullish(next[1]) }),
81
+ {},
82
+ ),
83
+ );