@btc-vision/bitcoin 7.0.0-alpha.1 → 7.0.0-alpha.2
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.
- package/browser/address.d.ts +5 -1
- package/browser/address.d.ts.map +1 -1
- package/browser/branded.d.ts +3 -14
- package/browser/branded.d.ts.map +1 -1
- package/browser/ecc/context.d.ts.map +1 -1
- package/browser/index.d.ts +2 -1
- package/browser/index.d.ts.map +1 -1
- package/browser/index.js +2964 -2919
- package/browser/opcodes.d.ts +11 -0
- package/browser/opcodes.d.ts.map +1 -1
- package/browser/psbt/PsbtCache.d.ts +54 -0
- package/browser/psbt/PsbtCache.d.ts.map +1 -0
- package/browser/psbt/PsbtFinalizer.d.ts +21 -0
- package/browser/psbt/PsbtFinalizer.d.ts.map +1 -0
- package/browser/psbt/PsbtSigner.d.ts +32 -0
- package/browser/psbt/PsbtSigner.d.ts.map +1 -0
- package/browser/psbt/PsbtTransaction.d.ts +25 -0
- package/browser/psbt/PsbtTransaction.d.ts.map +1 -0
- package/browser/psbt/types.d.ts +13 -13
- package/browser/psbt/types.d.ts.map +1 -1
- package/browser/psbt/validation.d.ts +1 -1
- package/browser/psbt/validation.d.ts.map +1 -1
- package/browser/psbt.d.ts +27 -39
- package/browser/psbt.d.ts.map +1 -1
- package/browser/script.d.ts.map +1 -1
- package/browser/transaction.d.ts +4 -4
- package/browser/transaction.d.ts.map +1 -1
- package/browser/types.d.ts +4 -2
- package/browser/types.d.ts.map +1 -1
- package/browser/workers/index.d.ts +3 -50
- package/browser/workers/index.d.ts.map +1 -1
- package/browser/workers/index.node.d.ts +24 -0
- package/browser/workers/index.node.d.ts.map +1 -0
- package/build/address.d.ts +5 -1
- package/build/address.d.ts.map +1 -1
- package/build/address.js +29 -17
- package/build/address.js.map +1 -1
- package/build/branded.d.ts +3 -14
- package/build/branded.d.ts.map +1 -1
- package/build/branded.js +0 -5
- package/build/branded.js.map +1 -1
- package/build/ecc/context.d.ts.map +1 -1
- package/build/ecc/context.js +68 -45
- package/build/ecc/context.js.map +1 -1
- package/build/index.d.ts +2 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -1
- package/build/index.js.map +1 -1
- package/build/opcodes.d.ts +11 -0
- package/build/opcodes.d.ts.map +1 -1
- package/build/opcodes.js +19 -4
- package/build/opcodes.js.map +1 -1
- package/build/psbt/PsbtCache.d.ts +54 -0
- package/build/psbt/PsbtCache.d.ts.map +1 -0
- package/build/psbt/PsbtCache.js +249 -0
- package/build/psbt/PsbtCache.js.map +1 -0
- package/build/psbt/PsbtFinalizer.d.ts +21 -0
- package/build/psbt/PsbtFinalizer.d.ts.map +1 -0
- package/build/psbt/PsbtFinalizer.js +157 -0
- package/build/psbt/PsbtFinalizer.js.map +1 -0
- package/build/psbt/PsbtSigner.d.ts +32 -0
- package/build/psbt/PsbtSigner.d.ts.map +1 -0
- package/build/psbt/PsbtSigner.js +192 -0
- package/build/psbt/PsbtSigner.js.map +1 -0
- package/build/psbt/PsbtTransaction.d.ts +25 -0
- package/build/psbt/PsbtTransaction.d.ts.map +1 -0
- package/build/psbt/PsbtTransaction.js +61 -0
- package/build/psbt/PsbtTransaction.js.map +1 -0
- package/build/psbt/types.d.ts +13 -13
- package/build/psbt/types.d.ts.map +1 -1
- package/build/psbt/validation.d.ts +1 -1
- package/build/psbt/validation.d.ts.map +1 -1
- package/build/psbt.d.ts +27 -39
- package/build/psbt.d.ts.map +1 -1
- package/build/psbt.js +139 -746
- package/build/psbt.js.map +1 -1
- package/build/script.d.ts.map +1 -1
- package/build/script.js +2 -2
- package/build/script.js.map +1 -1
- package/build/transaction.d.ts +4 -4
- package/build/transaction.d.ts.map +1 -1
- package/build/transaction.js +5 -4
- package/build/transaction.js.map +1 -1
- package/build/tsconfig.build.tsbuildinfo +1 -1
- package/build/types.d.ts +4 -2
- package/build/types.d.ts.map +1 -1
- package/build/types.js +9 -0
- package/build/types.js.map +1 -1
- package/build/workers/WorkerSigningPool.js +1 -1
- package/build/workers/WorkerSigningPool.js.map +1 -1
- package/build/workers/index.d.ts +3 -3
- package/build/workers/index.d.ts.map +1 -1
- package/build/workers/index.js +0 -3
- package/build/workers/index.js.map +1 -1
- package/build/workers/index.node.d.ts +24 -0
- package/build/workers/index.node.d.ts.map +1 -0
- package/build/workers/index.node.js +26 -0
- package/build/workers/index.node.js.map +1 -0
- package/package.json +28 -9
- package/src/address.ts +41 -18
- package/src/branded.ts +15 -13
- package/src/ecc/context.ts +75 -57
- package/src/index.ts +36 -1
- package/src/opcodes.ts +21 -4
- package/src/psbt/PsbtCache.ts +325 -0
- package/src/psbt/PsbtFinalizer.ts +213 -0
- package/src/psbt/PsbtSigner.ts +302 -0
- package/src/psbt/PsbtTransaction.ts +82 -0
- package/src/psbt/types.ts +13 -13
- package/src/psbt/validation.ts +1 -1
- package/src/psbt.ts +299 -1090
- package/src/script.ts +2 -2
- package/src/transaction.ts +9 -8
- package/src/types.ts +13 -0
- package/src/workers/WorkerSigningPool.ts +1 -1
- package/src/workers/index.node.ts +27 -0
- package/src/workers/index.ts +7 -9
- package/test/address.spec.ts +2 -2
- package/test/bitcoin.core.spec.ts +5 -2
- package/test/browser/payments.spec.ts +151 -0
- package/test/browser/psbt.spec.ts +1510 -0
- package/test/browser/script.spec.ts +223 -0
- package/test/browser/setup.ts +13 -0
- package/test/browser/workers-signing.spec.ts +537 -0
- package/test/crypto.spec.ts +2 -2
- package/test/fixtures/core/base58_encode_decode.json +12 -48
- package/test/fixtures/core/base58_keys_invalid.json +50 -150
- package/test/fixtures/core/sighash.json +1 -3
- package/test/fixtures/core/tx_valid.json +133 -501
- package/test/fixtures/embed.json +3 -11
- package/test/fixtures/p2ms.json +21 -91
- package/test/fixtures/p2pk.json +5 -24
- package/test/fixtures/p2pkh.json +7 -36
- package/test/fixtures/p2sh.json +8 -54
- package/test/fixtures/p2tr.json +2 -6
- package/test/fixtures/p2wpkh.json +7 -36
- package/test/fixtures/p2wsh.json +14 -59
- package/test/fixtures/psbt.json +2 -6
- package/test/fixtures/script.json +12 -48
- package/test/integration/addresses.spec.ts +11 -5
- package/test/integration/bip32.spec.ts +1 -1
- package/test/integration/cltv.spec.ts +10 -6
- package/test/integration/csv.spec.ts +10 -9
- package/test/integration/payments.spec.ts +8 -4
- package/test/integration/taproot.spec.ts +26 -6
- package/test/integration/transactions.spec.ts +22 -8
- package/test/payments.spec.ts +1 -1
- package/test/payments.utils.ts +1 -1
- package/test/psbt.spec.ts +250 -64
- package/test/script_signature.spec.ts +1 -1
- package/test/transaction.spec.ts +18 -5
- package/test/tsconfig.json +6 -20
- package/test/workers-pool.spec.ts +22 -23
- package/test/workers-signing.spec.ts +7 -3
- package/test/workers.spec.ts +6 -7
- package/typedoc.json +11 -1
- package/vitest.config.browser.ts +68 -0
- package/browser/ecpair.d.ts +0 -99
- package/src/ecpair.d.ts +0 -99
- package/test/taproot-cache.spec.ts +0 -694
package/build/psbt.js
CHANGED
|
@@ -1,32 +1,44 @@
|
|
|
1
1
|
import { checkForInput, checkForOutput, Psbt as PsbtBase } from 'bip174';
|
|
2
|
-
import { clone, equals, fromBase64, fromHex,
|
|
3
|
-
import { fromOutputScript,
|
|
2
|
+
import { clone, equals, fromBase64, fromHex, toHex } from './io/index.js';
|
|
3
|
+
import { fromOutputScript, toOutputScript } from './address.js';
|
|
4
4
|
import { bitcoin as btcNetwork } from './networks.js';
|
|
5
5
|
import * as payments from './payments/index.js';
|
|
6
|
-
import { tapleafHash } from './payments/bip341.js';
|
|
7
6
|
import { checkTaprootInputFields, checkTaprootOutputFields, isTaprootInput, serializeTaprootSignature, tapScriptFinalizer, } from './psbt/bip371.js';
|
|
8
7
|
import { toXOnly } from './pubkey.js';
|
|
9
|
-
import { isP2TR, isP2WPKH, pubkeyInScript, witnessStackToScriptWitness } from './psbt/psbtutils.js';
|
|
10
|
-
import { check32Bit, checkCache, checkInputsForPartialSig, checkPartialSigSighashes, checkScriptForPubkey, checkTxEmpty, checkTxForDupeIns, checkTxInputCache, isFinalized, } from './psbt/validation.js';
|
|
11
|
-
import { checkInvalidP2WSH, classifyScript, compressPubkey, getMeaningfulScript, isPubkeyLike, isSigLike, range, scriptWitnessToWitnessStack, sighashTypeToString, } from './psbt/utils.js';
|
|
12
8
|
import * as bscript from './script.js';
|
|
13
9
|
import { Transaction } from './transaction.js';
|
|
10
|
+
// Import composition classes
|
|
11
|
+
import { PsbtCache } from './psbt/PsbtCache.js';
|
|
12
|
+
import { PsbtSigner } from './psbt/PsbtSigner.js';
|
|
13
|
+
import { getFinalScripts as _getFinalScripts, prepareFinalScripts as _prepareFinalScripts, PsbtFinalizer, } from './psbt/PsbtFinalizer.js';
|
|
14
|
+
import { PsbtTransaction, transactionFromBuffer } from './psbt/PsbtTransaction.js';
|
|
15
|
+
import { check32Bit, checkCache, checkInputsForPartialSig, checkPartialSigSighashes, checkScriptForPubkey, checkTxForDupeIns, checkTxInputCache, isFinalized, } from './psbt/validation.js';
|
|
16
|
+
import { checkInvalidP2WSH, classifyScript, getMeaningfulScript, range } from './psbt/utils.js';
|
|
17
|
+
import { witnessStackToScriptWitness } from './psbt/psbtutils.js';
|
|
18
|
+
// Re-export for backwards compatibility
|
|
19
|
+
export { getFinalScripts, prepareFinalScripts };
|
|
20
|
+
export { PsbtCache } from './psbt/PsbtCache.js';
|
|
21
|
+
export { PsbtSigner } from './psbt/PsbtSigner.js';
|
|
22
|
+
export { PsbtFinalizer } from './psbt/PsbtFinalizer.js';
|
|
23
|
+
export { PsbtTransaction, transactionFromBuffer } from './psbt/PsbtTransaction.js';
|
|
14
24
|
/**
|
|
15
25
|
* These are the default arguments for a Psbt instance.
|
|
16
26
|
*/
|
|
17
27
|
const DEFAULT_OPTS = {
|
|
18
|
-
/**
|
|
19
|
-
* A bitcoinjs Network object. This is only used if you pass an `address`
|
|
20
|
-
* parameter to addOutput. Otherwise it is not needed and can be left default.
|
|
21
|
-
*/
|
|
22
28
|
network: btcNetwork,
|
|
23
|
-
|
|
24
|
-
* When extractTransaction is called, the fee rate is checked.
|
|
25
|
-
* THIS IS NOT TO BE RELIED ON.
|
|
26
|
-
* It is only here as a last ditch effort to prevent sending a 500 BTC fee etc.
|
|
27
|
-
*/
|
|
28
|
-
maximumFeeRate: 5000, // satoshi per byte
|
|
29
|
+
maximumFeeRate: 5000,
|
|
29
30
|
};
|
|
31
|
+
/** Helper to create a Transaction from a buffer */
|
|
32
|
+
function txFromBuffer(buf) {
|
|
33
|
+
return Transaction.fromBuffer(buf);
|
|
34
|
+
}
|
|
35
|
+
// Standalone exports that delegate to PsbtFinalizer
|
|
36
|
+
function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks = true, solution) {
|
|
37
|
+
return _getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks, solution);
|
|
38
|
+
}
|
|
39
|
+
function prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution) {
|
|
40
|
+
return _prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution);
|
|
41
|
+
}
|
|
30
42
|
/**
|
|
31
43
|
* Psbt class can parse and generate a PSBT binary based off of the BIP174.
|
|
32
44
|
* There are 6 roles that this class fulfills. (Explained in BIP174)
|
|
@@ -64,39 +76,23 @@ const DEFAULT_OPTS = {
|
|
|
64
76
|
* Transaction Extractor: This role will perform some checks before returning a
|
|
65
77
|
* Transaction object. Such as fee rate not being larger than maximumFeeRate etc.
|
|
66
78
|
*/
|
|
67
|
-
/**
|
|
68
|
-
* Psbt class can parse and generate a PSBT binary based off of the BIP174.
|
|
69
|
-
*/
|
|
70
79
|
export class Psbt {
|
|
71
80
|
data;
|
|
72
81
|
#cache;
|
|
82
|
+
#signer;
|
|
83
|
+
#finalizer;
|
|
73
84
|
#opts;
|
|
74
85
|
constructor(opts = {}, data = new PsbtBase(new PsbtTransaction())) {
|
|
75
86
|
this.data = data;
|
|
76
87
|
this.#opts = Object.assign({}, DEFAULT_OPTS, opts);
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
nonWitnessUtxoBufCache: [],
|
|
80
|
-
txInCache: {},
|
|
81
|
-
// unsignedTx.tx property is dynamically added by PsbtBase
|
|
82
|
-
tx: this.data.globalMap.unsignedTx.tx,
|
|
83
|
-
unsafeSignNonSegwit: false,
|
|
84
|
-
hasSignatures: false,
|
|
85
|
-
};
|
|
88
|
+
const tx = this.data.globalMap.unsignedTx.tx;
|
|
89
|
+
this.#cache = new PsbtCache(tx);
|
|
86
90
|
if (opts.version === 3) {
|
|
87
91
|
this.setVersionTRUC();
|
|
88
92
|
}
|
|
89
93
|
else if (this.data.inputs.length === 0)
|
|
90
94
|
this.setVersion(2);
|
|
91
95
|
}
|
|
92
|
-
/** @internal - Exposed for testing. Do not use in production code. */
|
|
93
|
-
get __CACHE() {
|
|
94
|
-
return this.#cache;
|
|
95
|
-
}
|
|
96
|
-
/** @internal - Exposed for testing. Do not use in production code. */
|
|
97
|
-
get opts() {
|
|
98
|
-
return this.#opts;
|
|
99
|
-
}
|
|
100
96
|
get inputCount() {
|
|
101
97
|
return this.data.inputs.length;
|
|
102
98
|
}
|
|
@@ -125,7 +121,9 @@ export class Psbt {
|
|
|
125
121
|
try {
|
|
126
122
|
address = fromOutputScript(output.script, this.#opts.network);
|
|
127
123
|
}
|
|
128
|
-
catch (_) {
|
|
124
|
+
catch (_) {
|
|
125
|
+
// Not all scripts can be converted to an address
|
|
126
|
+
}
|
|
129
127
|
return {
|
|
130
128
|
script: clone(output.script),
|
|
131
129
|
value: output.value,
|
|
@@ -133,6 +131,20 @@ export class Psbt {
|
|
|
133
131
|
};
|
|
134
132
|
});
|
|
135
133
|
}
|
|
134
|
+
/** Lazily initialized signer - created on first access */
|
|
135
|
+
get #lazySigner() {
|
|
136
|
+
if (!this.#signer) {
|
|
137
|
+
this.#signer = new PsbtSigner(this.#cache, txFromBuffer);
|
|
138
|
+
}
|
|
139
|
+
return this.#signer;
|
|
140
|
+
}
|
|
141
|
+
/** Lazily initialized finalizer - created on first access */
|
|
142
|
+
get #lazyFinalizer() {
|
|
143
|
+
if (!this.#finalizer) {
|
|
144
|
+
this.#finalizer = new PsbtFinalizer(this.#cache, txFromBuffer);
|
|
145
|
+
}
|
|
146
|
+
return this.#finalizer;
|
|
147
|
+
}
|
|
136
148
|
static fromBase64(data, opts = {}) {
|
|
137
149
|
const buffer = fromBase64(data);
|
|
138
150
|
return this.fromBuffer(buffer, opts);
|
|
@@ -145,7 +157,6 @@ export class Psbt {
|
|
|
145
157
|
const psbtBase = PsbtBase.fromBuffer(buffer, transactionFromBuffer);
|
|
146
158
|
const psbt = new Psbt(opts, psbtBase);
|
|
147
159
|
checkTxForDupeIns(psbt.#cache.tx, psbt.#cache);
|
|
148
|
-
// Check if restored PSBT has any signatures (partial or finalized)
|
|
149
160
|
psbt.#cache.hasSignatures = psbt.data.inputs.some((input) => input.partialSig?.length ||
|
|
150
161
|
input.tapKeySig ||
|
|
151
162
|
input.tapScriptSig?.length ||
|
|
@@ -158,20 +169,21 @@ export class Psbt {
|
|
|
158
169
|
return this;
|
|
159
170
|
}
|
|
160
171
|
clone() {
|
|
161
|
-
|
|
162
|
-
const clonedOpts = JSON.parse(JSON.stringify(this.#opts));
|
|
172
|
+
const clonedOpts = structuredClone(this.#opts);
|
|
163
173
|
return Psbt.fromBuffer(new Uint8Array(this.data.toBuffer()), clonedOpts);
|
|
164
174
|
}
|
|
175
|
+
get maximumFeeRate() {
|
|
176
|
+
return this.#opts.maximumFeeRate;
|
|
177
|
+
}
|
|
165
178
|
setMaximumFeeRate(satoshiPerByte) {
|
|
166
|
-
check32Bit(satoshiPerByte);
|
|
179
|
+
check32Bit(satoshiPerByte);
|
|
167
180
|
this.#opts.maximumFeeRate = satoshiPerByte;
|
|
168
181
|
}
|
|
169
182
|
setVersion(version) {
|
|
170
183
|
check32Bit(version);
|
|
171
184
|
checkInputsForPartialSig(this.data.inputs, 'setVersion', this.#cache.hasSignatures);
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
c.extractedTx = undefined;
|
|
185
|
+
this.#cache.tx.version = version;
|
|
186
|
+
this.#cache.invalidate('outputs');
|
|
175
187
|
return this;
|
|
176
188
|
}
|
|
177
189
|
setVersionTRUC() {
|
|
@@ -180,20 +192,18 @@ export class Psbt {
|
|
|
180
192
|
setLocktime(locktime) {
|
|
181
193
|
check32Bit(locktime);
|
|
182
194
|
checkInputsForPartialSig(this.data.inputs, 'setLocktime', this.#cache.hasSignatures);
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
c.extractedTx = undefined;
|
|
195
|
+
this.#cache.tx.locktime = locktime;
|
|
196
|
+
this.#cache.invalidate('outputs');
|
|
186
197
|
return this;
|
|
187
198
|
}
|
|
188
199
|
setInputSequence(inputIndex, sequence) {
|
|
189
200
|
check32Bit(sequence);
|
|
190
201
|
checkInputsForPartialSig(this.data.inputs, 'setInputSequence', this.#cache.hasSignatures);
|
|
191
|
-
|
|
192
|
-
if (c.tx.ins.length <= inputIndex) {
|
|
202
|
+
if (this.#cache.tx.ins.length <= inputIndex) {
|
|
193
203
|
throw new Error('Input index too high');
|
|
194
204
|
}
|
|
195
|
-
|
|
196
|
-
|
|
205
|
+
this.#cache.tx.ins[inputIndex].sequence = sequence;
|
|
206
|
+
this.#cache.invalidate('outputs');
|
|
197
207
|
return this;
|
|
198
208
|
}
|
|
199
209
|
addInputs(inputDatas, checkPartialSigs = true) {
|
|
@@ -211,7 +221,6 @@ export class Psbt {
|
|
|
211
221
|
}
|
|
212
222
|
if (inputData.witnessScript)
|
|
213
223
|
checkInvalidP2WSH(inputData.witnessScript);
|
|
214
|
-
// Convert witnessUtxo for bip174 v3 compatibility (value: bigint, script: Uint8Array)
|
|
215
224
|
const normalizedInputData = inputData.witnessUtxo
|
|
216
225
|
? {
|
|
217
226
|
...inputData,
|
|
@@ -223,39 +232,21 @@ export class Psbt {
|
|
|
223
232
|
},
|
|
224
233
|
}
|
|
225
234
|
: inputData;
|
|
226
|
-
const c = this.#cache;
|
|
227
235
|
this.data.addInput(normalizedInputData);
|
|
228
|
-
const txIn =
|
|
229
|
-
checkTxInputCache(
|
|
236
|
+
const txIn = this.#cache.tx.ins[this.#cache.tx.ins.length - 1];
|
|
237
|
+
checkTxInputCache(this.#cache, txIn);
|
|
230
238
|
const inputIndex = this.data.inputs.length - 1;
|
|
231
239
|
const input = this.data.inputs[inputIndex];
|
|
232
240
|
if (input.nonWitnessUtxo) {
|
|
233
|
-
|
|
241
|
+
this.#cache.addNonWitnessTxCache(input, inputIndex, txFromBuffer);
|
|
234
242
|
}
|
|
235
|
-
|
|
236
|
-
c.feeRate = undefined;
|
|
237
|
-
c.extractedTx = undefined;
|
|
238
|
-
c.prevOuts = undefined;
|
|
239
|
-
c.signingScripts = undefined;
|
|
240
|
-
c.values = undefined;
|
|
241
|
-
c.taprootHashCache = undefined;
|
|
243
|
+
this.#cache.invalidate('full');
|
|
242
244
|
return this;
|
|
243
245
|
}
|
|
244
246
|
addOutputs(outputDatas, checkPartialSigs = true) {
|
|
245
247
|
outputDatas.forEach((outputData) => this.addOutput(outputData, checkPartialSigs));
|
|
246
248
|
return this;
|
|
247
249
|
}
|
|
248
|
-
/**
|
|
249
|
-
* Add an output to the PSBT.
|
|
250
|
-
*
|
|
251
|
-
* **PERFORMANCE WARNING:** Passing an `address` string is ~10x slower than passing
|
|
252
|
-
* a `script` directly due to address parsing overhead (bech32 decode, etc.).
|
|
253
|
-
* For high-performance use cases with many outputs, pre-compute the script using
|
|
254
|
-
* `toOutputScript(address, network)` and pass `{ script, value }` instead.
|
|
255
|
-
*
|
|
256
|
-
* @param outputData - Output data with either `address` or `script`, and `value`
|
|
257
|
-
* @param checkPartialSigs - Whether to check for existing signatures (default: true)
|
|
258
|
-
*/
|
|
259
250
|
addOutput(outputData, checkPartialSigs = true) {
|
|
260
251
|
const hasAddress = 'address' in outputData;
|
|
261
252
|
const hasScript = 'script' in outputData;
|
|
@@ -273,12 +264,8 @@ export class Psbt {
|
|
|
273
264
|
outputData = Object.assign({}, outputData, { script });
|
|
274
265
|
}
|
|
275
266
|
checkTaprootOutputFields(outputData, outputData, 'addOutput');
|
|
276
|
-
const c = this.#cache;
|
|
277
267
|
this.data.addOutput(outputData);
|
|
278
|
-
|
|
279
|
-
c.feeRate = undefined;
|
|
280
|
-
c.extractedTx = undefined;
|
|
281
|
-
c.taprootHashCache = undefined;
|
|
268
|
+
this.#cache.invalidate('outputs');
|
|
282
269
|
return this;
|
|
283
270
|
}
|
|
284
271
|
extractTransaction(disableFeeCheck, disableOutputChecks) {
|
|
@@ -287,24 +274,24 @@ export class Psbt {
|
|
|
287
274
|
}
|
|
288
275
|
if (!this.data.inputs.every(isFinalized))
|
|
289
276
|
throw new Error('Not finalized');
|
|
290
|
-
const c = this.#cache;
|
|
291
277
|
if (!disableFeeCheck) {
|
|
292
|
-
|
|
278
|
+
this.#cache.computeFeeRate(this.data.inputs, disableOutputChecks, txFromBuffer);
|
|
279
|
+
this.#cache.checkFees(this.#opts);
|
|
293
280
|
}
|
|
294
|
-
if (
|
|
295
|
-
return
|
|
296
|
-
const tx =
|
|
297
|
-
|
|
281
|
+
if (this.#cache.extractedTx)
|
|
282
|
+
return this.#cache.extractedTx;
|
|
283
|
+
const tx = this.#cache.tx.clone();
|
|
284
|
+
this.#cache.finalizeAndComputeAmounts(this.data.inputs, tx, true, disableOutputChecks, txFromBuffer);
|
|
298
285
|
return tx;
|
|
299
286
|
}
|
|
300
287
|
getFeeRate(disableOutputChecks = false) {
|
|
301
|
-
return
|
|
288
|
+
return this.#cache.computeFeeRate(this.data.inputs, disableOutputChecks, txFromBuffer);
|
|
302
289
|
}
|
|
303
290
|
getFee(disableOutputChecks = false) {
|
|
304
|
-
return
|
|
291
|
+
return this.#cache.computeFee(this.data.inputs, disableOutputChecks, txFromBuffer);
|
|
305
292
|
}
|
|
306
293
|
finalizeAllInputs() {
|
|
307
|
-
checkForInput(this.data.inputs, 0);
|
|
294
|
+
checkForInput(this.data.inputs, 0);
|
|
308
295
|
range(this.data.inputs.length).forEach((idx) => this.finalizeInput(idx));
|
|
309
296
|
return this;
|
|
310
297
|
}
|
|
@@ -323,34 +310,35 @@ export class Psbt {
|
|
|
323
310
|
}
|
|
324
311
|
getInputType(inputIndex) {
|
|
325
312
|
const input = checkForInput(this.data.inputs, inputIndex);
|
|
326
|
-
const script = getScriptFromUtxo(inputIndex, input,
|
|
327
|
-
const result = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), input.witnessScript ||
|
|
313
|
+
const script = this.#cache.getScriptFromUtxo(inputIndex, input, txFromBuffer);
|
|
314
|
+
const result = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript || this.#cache.redeemFromFinalScriptSig(input.finalScriptSig), input.witnessScript ||
|
|
315
|
+
this.#cache.redeemFromFinalWitnessScript(input.finalScriptWitness));
|
|
328
316
|
const type = result.type === 'raw' ? '' : result.type + '-';
|
|
329
317
|
const mainType = classifyScript(result.meaningfulScript);
|
|
330
318
|
return (type + mainType);
|
|
331
319
|
}
|
|
332
320
|
inputHasPubkey(inputIndex, pubkey) {
|
|
333
321
|
const input = checkForInput(this.data.inputs, inputIndex);
|
|
334
|
-
return pubkeyInInput(pubkey, input, inputIndex,
|
|
322
|
+
return this.#cache.pubkeyInInput(pubkey, input, inputIndex, txFromBuffer);
|
|
335
323
|
}
|
|
336
324
|
inputHasHDKey(inputIndex, root) {
|
|
337
325
|
const input = checkForInput(this.data.inputs, inputIndex);
|
|
338
|
-
const derivationIsMine = bip32DerivationIsMine(root);
|
|
326
|
+
const derivationIsMine = this.#lazySigner.bip32DerivationIsMine(root);
|
|
339
327
|
return !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine);
|
|
340
328
|
}
|
|
341
329
|
outputHasPubkey(outputIndex, pubkey) {
|
|
342
330
|
const output = checkForOutput(this.data.outputs, outputIndex);
|
|
343
|
-
return pubkeyInOutput(pubkey, output, outputIndex
|
|
331
|
+
return this.#cache.pubkeyInOutput(pubkey, output, outputIndex);
|
|
344
332
|
}
|
|
345
333
|
outputHasHDKey(outputIndex, root) {
|
|
346
334
|
const output = checkForOutput(this.data.outputs, outputIndex);
|
|
347
|
-
const derivationIsMine = bip32DerivationIsMine(root);
|
|
335
|
+
const derivationIsMine = this.#lazySigner.bip32DerivationIsMine(root);
|
|
348
336
|
return !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine);
|
|
349
337
|
}
|
|
350
338
|
validateSignaturesOfAllInputs(validator) {
|
|
351
|
-
checkForInput(this.data.inputs, 0);
|
|
339
|
+
checkForInput(this.data.inputs, 0);
|
|
352
340
|
const results = range(this.data.inputs.length).map((idx) => this.validateSignaturesOfInput(idx, validator));
|
|
353
|
-
return results.
|
|
341
|
+
return results.every((res) => res);
|
|
354
342
|
}
|
|
355
343
|
validateSignaturesOfInput(inputIndex, validator, pubkey) {
|
|
356
344
|
const input = this.data.inputs[inputIndex];
|
|
@@ -377,56 +365,43 @@ export class Psbt {
|
|
|
377
365
|
}
|
|
378
366
|
return this;
|
|
379
367
|
}
|
|
380
|
-
signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
}
|
|
398
|
-
resolve();
|
|
399
|
-
});
|
|
400
|
-
});
|
|
368
|
+
async signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
|
|
369
|
+
if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
|
|
370
|
+
throw new Error('Need HDSigner to sign input');
|
|
371
|
+
}
|
|
372
|
+
const results = [];
|
|
373
|
+
const promises = [];
|
|
374
|
+
for (const i of range(this.data.inputs.length)) {
|
|
375
|
+
promises.push(this.signInputHDAsync(i, hdKeyPair, sighashTypes).then(() => {
|
|
376
|
+
results.push(true);
|
|
377
|
+
}, () => {
|
|
378
|
+
results.push(false);
|
|
379
|
+
}));
|
|
380
|
+
}
|
|
381
|
+
await Promise.all(promises);
|
|
382
|
+
if (results.every((v) => !v)) {
|
|
383
|
+
throw new Error('No inputs were signed');
|
|
384
|
+
}
|
|
401
385
|
}
|
|
402
386
|
signInputHD(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
|
|
403
387
|
if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
|
|
404
388
|
throw new Error('Need HDSigner to sign input');
|
|
405
389
|
}
|
|
406
|
-
const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
|
|
390
|
+
const signers = this.#lazySigner.getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
|
|
407
391
|
signers.forEach((signer) => this.signInput(inputIndex, signer, sighashTypes));
|
|
408
392
|
return this;
|
|
409
393
|
}
|
|
410
|
-
signInputHDAsync(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
return Promise.all(promises)
|
|
418
|
-
.then(() => {
|
|
419
|
-
resolve();
|
|
420
|
-
})
|
|
421
|
-
.catch(reject);
|
|
422
|
-
});
|
|
394
|
+
async signInputHDAsync(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
|
|
395
|
+
if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
|
|
396
|
+
throw new Error('Need HDSigner to sign input');
|
|
397
|
+
}
|
|
398
|
+
const signers = this.#lazySigner.getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
|
|
399
|
+
const promises = signers.map((signer) => this.signInputAsync(inputIndex, signer, sighashTypes));
|
|
400
|
+
await Promise.all(promises);
|
|
423
401
|
}
|
|
424
402
|
signAllInputs(keyPair, sighashTypes) {
|
|
425
403
|
if (!keyPair || !keyPair.publicKey)
|
|
426
404
|
throw new Error('Need Signer to sign input');
|
|
427
|
-
// TODO: Add a pubkey/pubkeyhash cache to each input
|
|
428
|
-
// as input information is added, then eventually
|
|
429
|
-
// optimize this method.
|
|
430
405
|
const results = [];
|
|
431
406
|
for (const i of range(this.data.inputs.length)) {
|
|
432
407
|
try {
|
|
@@ -442,29 +417,22 @@ export class Psbt {
|
|
|
442
417
|
}
|
|
443
418
|
return this;
|
|
444
419
|
}
|
|
445
|
-
signAllInputsAsync(keyPair, sighashTypes) {
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
return Promise.all(promises).then(() => {
|
|
462
|
-
if (results.every((v) => !v)) {
|
|
463
|
-
return reject(new Error('No inputs were signed'));
|
|
464
|
-
}
|
|
465
|
-
resolve();
|
|
466
|
-
});
|
|
467
|
-
});
|
|
420
|
+
async signAllInputsAsync(keyPair, sighashTypes) {
|
|
421
|
+
if (!keyPair || !keyPair.publicKey)
|
|
422
|
+
throw new Error('Need Signer to sign input');
|
|
423
|
+
const results = [];
|
|
424
|
+
const promises = [];
|
|
425
|
+
for (const [i] of this.data.inputs.entries()) {
|
|
426
|
+
promises.push(this.signInputAsync(i, keyPair, sighashTypes).then(() => {
|
|
427
|
+
results.push(true);
|
|
428
|
+
}, () => {
|
|
429
|
+
results.push(false);
|
|
430
|
+
}));
|
|
431
|
+
}
|
|
432
|
+
await Promise.all(promises);
|
|
433
|
+
if (results.every((v) => !v)) {
|
|
434
|
+
throw new Error('No inputs were signed');
|
|
435
|
+
}
|
|
468
436
|
}
|
|
469
437
|
signInput(inputIndex, keyPair, sighashTypes) {
|
|
470
438
|
if (!keyPair || !keyPair.publicKey) {
|
|
@@ -526,7 +494,6 @@ export class Psbt {
|
|
|
526
494
|
if (updateData.witnessScript)
|
|
527
495
|
checkInvalidP2WSH(updateData.witnessScript);
|
|
528
496
|
checkTaprootInputFields(this.data.inputs[inputIndex], updateData, 'updateInput');
|
|
529
|
-
// Convert witnessUtxo for bip174 v3 compatibility (value: bigint, script: Uint8Array)
|
|
530
497
|
const normalizedUpdate = updateData.witnessUtxo
|
|
531
498
|
? {
|
|
532
499
|
...updateData,
|
|
@@ -540,7 +507,7 @@ export class Psbt {
|
|
|
540
507
|
: updateData;
|
|
541
508
|
this.data.updateInput(inputIndex, normalizedUpdate);
|
|
542
509
|
if (updateData.nonWitnessUtxo) {
|
|
543
|
-
|
|
510
|
+
this.#cache.addNonWitnessTxCache(this.data.inputs[inputIndex], inputIndex, txFromBuffer);
|
|
544
511
|
}
|
|
545
512
|
return this;
|
|
546
513
|
}
|
|
@@ -572,13 +539,13 @@ export class Psbt {
|
|
|
572
539
|
const pubkey = keyPair.publicKey instanceof Uint8Array
|
|
573
540
|
? keyPair.publicKey
|
|
574
541
|
: new Uint8Array(keyPair.publicKey);
|
|
575
|
-
const hashesForSig = getTaprootHashesForSig(inputIndex, input, this.data.inputs, pubkey,
|
|
542
|
+
const hashesForSig = this.#lazySigner.getTaprootHashesForSig(inputIndex, input, this.data.inputs, pubkey, tapLeafHashToSign, allowedSighashTypes);
|
|
576
543
|
if (!hashesForSig || !hashesForSig.length)
|
|
577
544
|
throw new Error(`Can not sign for input #${inputIndex} with the key ${toHex(pubkey)}`);
|
|
578
545
|
return hashesForSig;
|
|
579
546
|
}
|
|
580
547
|
#finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts, canRunChecks = true) {
|
|
581
|
-
const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput(inputIndex, input
|
|
548
|
+
const { script, isP2SH, isP2WSH, isSegwit } = this.#lazyFinalizer.getScriptFromInput(inputIndex, input);
|
|
582
549
|
if (!script)
|
|
583
550
|
throw new Error(`No script found for input #${inputIndex}`);
|
|
584
551
|
checkPartialSigSighashes(input);
|
|
@@ -595,7 +562,6 @@ export class Psbt {
|
|
|
595
562
|
#finalizeTaprootInput(inputIndex, input, tapLeafHashToFinalize, finalScriptsFunc = tapScriptFinalizer) {
|
|
596
563
|
if (!input.witnessUtxo)
|
|
597
564
|
throw new Error(`Cannot finalize input #${inputIndex}. Missing witness utxo.`);
|
|
598
|
-
// Check key spend first. Increased privacy and reduced block space.
|
|
599
565
|
if (input.tapKeySig) {
|
|
600
566
|
const payment = payments.p2tr({
|
|
601
567
|
output: input.witnessUtxo.script,
|
|
@@ -615,7 +581,7 @@ export class Psbt {
|
|
|
615
581
|
}
|
|
616
582
|
#validateSignaturesOfInput(inputIndex, validator, pubkey) {
|
|
617
583
|
const input = this.data.inputs[inputIndex];
|
|
618
|
-
const partialSig =
|
|
584
|
+
const partialSig = input?.partialSig;
|
|
619
585
|
if (!input || !partialSig || partialSig.length < 1)
|
|
620
586
|
throw new Error('No signatures to validate');
|
|
621
587
|
if (typeof validator !== 'function')
|
|
@@ -632,9 +598,9 @@ export class Psbt {
|
|
|
632
598
|
const pSigPubkey = pSig.pubkey;
|
|
633
599
|
const sig = bscript.signature.decode(pSigSignature);
|
|
634
600
|
const { hash, script } = sighashCache !== sig.hashType || !hashCache || !scriptCache
|
|
635
|
-
? getHashForSig(inputIndex, Object.assign({}, input, {
|
|
601
|
+
? this.#lazySigner.getHashForSig(inputIndex, Object.assign({}, input, {
|
|
636
602
|
sighashType: sig.hashType,
|
|
637
|
-
}),
|
|
603
|
+
}), true)
|
|
638
604
|
: { hash: hashCache, script: scriptCache };
|
|
639
605
|
sighashCache = sig.hashType;
|
|
640
606
|
hashCache = hash;
|
|
@@ -646,22 +612,22 @@ export class Psbt {
|
|
|
646
612
|
}
|
|
647
613
|
#validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) {
|
|
648
614
|
const input = this.data.inputs[inputIndex];
|
|
649
|
-
const tapKeySig =
|
|
650
|
-
const tapScriptSig =
|
|
615
|
+
const tapKeySig = input?.tapKeySig;
|
|
616
|
+
const tapScriptSig = input?.tapScriptSig;
|
|
651
617
|
if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length))
|
|
652
618
|
throw new Error('No signatures to validate');
|
|
653
619
|
if (typeof validator !== 'function')
|
|
654
620
|
throw new Error('Need validator function to validate signatures');
|
|
655
621
|
const xPubkey = pubkey ? toXOnly(pubkey) : undefined;
|
|
656
622
|
const allHashses = xPubkey
|
|
657
|
-
? getTaprootHashesForSig(inputIndex, input, this.data.inputs, xPubkey
|
|
658
|
-
: getAllTaprootHashesForSig(inputIndex, input, this.data.inputs
|
|
623
|
+
? this.#lazySigner.getTaprootHashesForSig(inputIndex, input, this.data.inputs, xPubkey)
|
|
624
|
+
: this.#lazySigner.getAllTaprootHashesForSig(inputIndex, input, this.data.inputs);
|
|
659
625
|
if (!allHashses.length)
|
|
660
626
|
throw new Error('No signatures for this pubkey');
|
|
661
627
|
const tapKeyHash = allHashses.find((h) => !h.leafHash);
|
|
662
628
|
let validationResultCount = 0;
|
|
663
629
|
if (tapKeySig && tapKeyHash) {
|
|
664
|
-
const isValidTapkeySig = validator(tapKeyHash.pubkey, tapKeyHash.hash, trimTaprootSig(tapKeySig));
|
|
630
|
+
const isValidTapkeySig = validator(tapKeyHash.pubkey, tapKeyHash.hash, this.#lazySigner.trimTaprootSig(tapKeySig));
|
|
665
631
|
if (!isValidTapkeySig)
|
|
666
632
|
return false;
|
|
667
633
|
validationResultCount++;
|
|
@@ -671,7 +637,7 @@ export class Psbt {
|
|
|
671
637
|
const tapSigPubkey = tapSig.pubkey;
|
|
672
638
|
const tapSigHash = allHashses.find((h) => equals(tapSigPubkey, h.pubkey));
|
|
673
639
|
if (tapSigHash) {
|
|
674
|
-
const isValidTapScriptSig = validator(tapSigPubkey, tapSigHash.hash, trimTaprootSig(tapSig.signature));
|
|
640
|
+
const isValidTapScriptSig = validator(tapSigPubkey, tapSigHash.hash, this.#lazySigner.trimTaprootSig(tapSig.signature));
|
|
675
641
|
if (!isValidTapScriptSig)
|
|
676
642
|
return false;
|
|
677
643
|
validationResultCount++;
|
|
@@ -684,7 +650,7 @@ export class Psbt {
|
|
|
684
650
|
const pubkey = keyPair.publicKey instanceof Uint8Array
|
|
685
651
|
? keyPair.publicKey
|
|
686
652
|
: new Uint8Array(keyPair.publicKey);
|
|
687
|
-
const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, pubkey,
|
|
653
|
+
const { hash, sighashType } = this.#lazySigner.getHashAndSighashType(this.data.inputs, inputIndex, pubkey, sighashTypes);
|
|
688
654
|
const sig = keyPair.sign(hash);
|
|
689
655
|
const partialSig = [
|
|
690
656
|
{
|
|
@@ -702,7 +668,6 @@ export class Psbt {
|
|
|
702
668
|
: new Uint8Array(keyPair.publicKey));
|
|
703
669
|
if (!('signSchnorr' in keyPair) || typeof keyPair.signSchnorr !== 'function')
|
|
704
670
|
throw new Error(`Need Schnorr Signer to sign taproot input #${inputIndex}.`);
|
|
705
|
-
// checkTaprootHashesForSig validates signSchnorr exists
|
|
706
671
|
const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHashToSign, allowedSighashTypes);
|
|
707
672
|
const signSchnorr = keyPair.signSchnorr.bind(keyPair);
|
|
708
673
|
const tapKeySig = hashesForSig
|
|
@@ -729,7 +694,7 @@ export class Psbt {
|
|
|
729
694
|
const pubkey = keyPair.publicKey instanceof Uint8Array
|
|
730
695
|
? keyPair.publicKey
|
|
731
696
|
: new Uint8Array(keyPair.publicKey);
|
|
732
|
-
const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, pubkey,
|
|
697
|
+
const { hash, sighashType } = this.#lazySigner.getHashAndSighashType(this.data.inputs, inputIndex, pubkey, sighashTypes);
|
|
733
698
|
return Promise.resolve(keyPair.sign(hash)).then((signature) => {
|
|
734
699
|
const sig = signature instanceof Uint8Array ? signature : new Uint8Array(signature);
|
|
735
700
|
const partialSig = [
|
|
@@ -748,7 +713,6 @@ export class Psbt {
|
|
|
748
713
|
: new Uint8Array(keyPair.publicKey));
|
|
749
714
|
if (!('signSchnorr' in keyPair) || typeof keyPair.signSchnorr !== 'function')
|
|
750
715
|
throw new Error(`Need Schnorr Signer to sign taproot input #${inputIndex}.`);
|
|
751
|
-
// checkTaprootHashesForSig validates signSchnorr exists
|
|
752
716
|
const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
|
|
753
717
|
const signSchnorr = keyPair.signSchnorr.bind(keyPair);
|
|
754
718
|
const signaturePromises = [];
|
|
@@ -783,575 +747,4 @@ export class Psbt {
|
|
|
783
747
|
}
|
|
784
748
|
}
|
|
785
749
|
}
|
|
786
|
-
/**
|
|
787
|
-
* This function is needed to pass to the bip174 base class's fromBuffer.
|
|
788
|
-
* It takes the "transaction buffer" portion of the psbt buffer and returns a
|
|
789
|
-
* Transaction (From the bip174 library) interface.
|
|
790
|
-
*/
|
|
791
|
-
const transactionFromBuffer = (buffer) => new PsbtTransaction(buffer);
|
|
792
|
-
/**
|
|
793
|
-
* This class implements the Transaction interface from bip174 library.
|
|
794
|
-
* It contains a bitcoinjs-lib Transaction object.
|
|
795
|
-
*/
|
|
796
|
-
class PsbtTransaction {
|
|
797
|
-
tx;
|
|
798
|
-
constructor(buffer = new Uint8Array([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) {
|
|
799
|
-
this.tx = Transaction.fromBuffer(buffer);
|
|
800
|
-
checkTxEmpty(this.tx);
|
|
801
|
-
Object.defineProperty(this, 'tx', {
|
|
802
|
-
enumerable: false,
|
|
803
|
-
writable: true,
|
|
804
|
-
});
|
|
805
|
-
}
|
|
806
|
-
getInputOutputCounts() {
|
|
807
|
-
return {
|
|
808
|
-
inputCount: this.tx.ins.length,
|
|
809
|
-
outputCount: this.tx.outs.length,
|
|
810
|
-
};
|
|
811
|
-
}
|
|
812
|
-
addInput(input) {
|
|
813
|
-
if (input.hash === undefined ||
|
|
814
|
-
input.index === undefined ||
|
|
815
|
-
(!(input.hash instanceof Uint8Array) && typeof input.hash !== 'string') ||
|
|
816
|
-
typeof input.index !== 'number') {
|
|
817
|
-
throw new Error('Error adding input.');
|
|
818
|
-
}
|
|
819
|
-
const hash = (typeof input.hash === 'string' ? reverse(fromHex(input.hash)) : input.hash);
|
|
820
|
-
this.tx.addInput(hash, input.index, input.sequence);
|
|
821
|
-
}
|
|
822
|
-
addOutput(output) {
|
|
823
|
-
if (output.script === undefined ||
|
|
824
|
-
output.value === undefined ||
|
|
825
|
-
!(output.script instanceof Uint8Array) ||
|
|
826
|
-
typeof output.value !== 'bigint') {
|
|
827
|
-
throw new Error('Error adding output.');
|
|
828
|
-
}
|
|
829
|
-
this.tx.addOutput(output.script, output.value);
|
|
830
|
-
}
|
|
831
|
-
toBuffer() {
|
|
832
|
-
return this.tx.toBuffer();
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
function canFinalize(input, script, scriptType) {
|
|
836
|
-
switch (scriptType) {
|
|
837
|
-
case 'pubkey':
|
|
838
|
-
case 'pubkeyhash':
|
|
839
|
-
case 'witnesspubkeyhash':
|
|
840
|
-
return hasSigs(1, input.partialSig);
|
|
841
|
-
case 'multisig': {
|
|
842
|
-
const p2ms = payments.p2ms({
|
|
843
|
-
output: script,
|
|
844
|
-
});
|
|
845
|
-
if (p2ms.m === undefined)
|
|
846
|
-
throw new Error('Cannot determine m for multisig');
|
|
847
|
-
return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys);
|
|
848
|
-
}
|
|
849
|
-
case 'nonstandard':
|
|
850
|
-
return true;
|
|
851
|
-
default:
|
|
852
|
-
return false;
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
function hasSigs(neededSigs, partialSig, pubkeys) {
|
|
856
|
-
if (!partialSig)
|
|
857
|
-
return false;
|
|
858
|
-
let sigs;
|
|
859
|
-
if (pubkeys) {
|
|
860
|
-
sigs = pubkeys
|
|
861
|
-
.map((pkey) => {
|
|
862
|
-
const pubkey = compressPubkey(pkey);
|
|
863
|
-
return partialSig.find((pSig) => equals(pSig.pubkey, pubkey));
|
|
864
|
-
})
|
|
865
|
-
.filter((v) => !!v);
|
|
866
|
-
}
|
|
867
|
-
else {
|
|
868
|
-
sigs = partialSig;
|
|
869
|
-
}
|
|
870
|
-
if (sigs.length > neededSigs)
|
|
871
|
-
throw new Error('Too many signatures');
|
|
872
|
-
return sigs.length === neededSigs;
|
|
873
|
-
}
|
|
874
|
-
function bip32DerivationIsMine(root) {
|
|
875
|
-
return (d) => {
|
|
876
|
-
const fingerprint = root.fingerprint instanceof Uint8Array
|
|
877
|
-
? root.fingerprint
|
|
878
|
-
: new Uint8Array(root.fingerprint);
|
|
879
|
-
if (!equals(d.masterFingerprint, fingerprint))
|
|
880
|
-
return false;
|
|
881
|
-
const derivedPubkey = root.derivePath(d.path).publicKey;
|
|
882
|
-
const pubkey = derivedPubkey instanceof Uint8Array ? derivedPubkey : new Uint8Array(derivedPubkey);
|
|
883
|
-
if (!equals(pubkey, d.pubkey))
|
|
884
|
-
return false;
|
|
885
|
-
return true;
|
|
886
|
-
};
|
|
887
|
-
}
|
|
888
|
-
function checkFees(psbt, cache, opts) {
|
|
889
|
-
const feeRate = cache.feeRate || psbt.getFeeRate();
|
|
890
|
-
if (!cache.extractedTx)
|
|
891
|
-
throw new Error('Transaction not extracted');
|
|
892
|
-
const vsize = cache.extractedTx.virtualSize();
|
|
893
|
-
const satoshis = feeRate * vsize;
|
|
894
|
-
if (feeRate >= opts.maximumFeeRate) {
|
|
895
|
-
throw new Error(`Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` +
|
|
896
|
-
`fees, which is ${feeRate} satoshi per byte for a transaction ` +
|
|
897
|
-
`with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` +
|
|
898
|
-
`byte). Use setMaximumFeeRate method to raise your threshold, or ` +
|
|
899
|
-
`pass true to the first arg of extractTransaction.`);
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
function getTxCacheValue(key, name, inputs, c, disableOutputChecks = false) {
|
|
903
|
-
if (!inputs.every(isFinalized))
|
|
904
|
-
throw new Error(`PSBT must be finalized to calculate ${name}`);
|
|
905
|
-
if (key === 'feeRate' && c.feeRate)
|
|
906
|
-
return c.feeRate;
|
|
907
|
-
if (key === 'fee' && c.fee)
|
|
908
|
-
return c.fee;
|
|
909
|
-
let tx;
|
|
910
|
-
let mustFinalize = true;
|
|
911
|
-
if (c.extractedTx) {
|
|
912
|
-
tx = c.extractedTx;
|
|
913
|
-
mustFinalize = false;
|
|
914
|
-
}
|
|
915
|
-
else {
|
|
916
|
-
tx = c.tx.clone();
|
|
917
|
-
}
|
|
918
|
-
inputFinalizeGetAmts(inputs, tx, c, mustFinalize, disableOutputChecks);
|
|
919
|
-
const value = key === 'feeRate' ? c.feeRate : c.fee;
|
|
920
|
-
if (value === undefined)
|
|
921
|
-
throw new Error(`Failed to calculate ${name}`);
|
|
922
|
-
return value;
|
|
923
|
-
}
|
|
924
|
-
export function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks = true, solution) {
|
|
925
|
-
const scriptType = classifyScript(script);
|
|
926
|
-
if (!canFinalize(input, script, scriptType) && canRunChecks) {
|
|
927
|
-
throw new Error(`Can not finalize input #${inputIndex}`);
|
|
928
|
-
}
|
|
929
|
-
if (!input.partialSig)
|
|
930
|
-
throw new Error('Input missing partial signatures');
|
|
931
|
-
return prepareFinalScripts(script, scriptType, input.partialSig, isSegwit, isP2SH, isP2WSH, solution);
|
|
932
|
-
}
|
|
933
|
-
export function prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution) {
|
|
934
|
-
let finalScriptSig;
|
|
935
|
-
let finalScriptWitness;
|
|
936
|
-
// Wow, the payments API is very handy
|
|
937
|
-
const payment = getPayment(script, scriptType, partialSig);
|
|
938
|
-
const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment });
|
|
939
|
-
const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment });
|
|
940
|
-
if (isSegwit) {
|
|
941
|
-
if (p2wsh && p2wsh.witness) {
|
|
942
|
-
finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness);
|
|
943
|
-
}
|
|
944
|
-
else if (payment && payment.witness) {
|
|
945
|
-
finalScriptWitness = witnessStackToScriptWitness(payment.witness);
|
|
946
|
-
}
|
|
947
|
-
else {
|
|
948
|
-
// nonstandard segwit script
|
|
949
|
-
finalScriptWitness = witnessStackToScriptWitness(solution ?? [new Uint8Array([0x00])]);
|
|
950
|
-
}
|
|
951
|
-
if (p2sh) {
|
|
952
|
-
finalScriptSig = p2sh?.input;
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
else {
|
|
956
|
-
if (p2sh) {
|
|
957
|
-
finalScriptSig = p2sh?.input;
|
|
958
|
-
}
|
|
959
|
-
else {
|
|
960
|
-
if (!payment) {
|
|
961
|
-
finalScriptSig = (Array.isArray(solution) && solution[0] ? solution[0] : new Uint8Array([0x01]));
|
|
962
|
-
}
|
|
963
|
-
else {
|
|
964
|
-
finalScriptSig = payment.input;
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
return {
|
|
969
|
-
finalScriptSig,
|
|
970
|
-
finalScriptWitness,
|
|
971
|
-
};
|
|
972
|
-
}
|
|
973
|
-
function getHashAndSighashType(inputs, inputIndex, pubkey, cache, sighashTypes) {
|
|
974
|
-
const input = checkForInput(inputs, inputIndex);
|
|
975
|
-
const { hash, sighashType, script } = getHashForSig(inputIndex, input, cache, false, sighashTypes);
|
|
976
|
-
checkScriptForPubkey(pubkey, script, 'sign');
|
|
977
|
-
return {
|
|
978
|
-
hash,
|
|
979
|
-
sighashType,
|
|
980
|
-
};
|
|
981
|
-
}
|
|
982
|
-
function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) {
|
|
983
|
-
const unsignedTx = cache.tx;
|
|
984
|
-
const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
|
|
985
|
-
checkSighashTypeAllowed(sighashType, sighashTypes);
|
|
986
|
-
let hash;
|
|
987
|
-
let prevout;
|
|
988
|
-
if (input.nonWitnessUtxo) {
|
|
989
|
-
const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
|
|
990
|
-
const prevoutHash = unsignedTx.ins[inputIndex].hash;
|
|
991
|
-
const utxoHash = nonWitnessUtxoTx.getHash();
|
|
992
|
-
// If a non-witness UTXO is provided, its hash must match the hash specified in the prevout
|
|
993
|
-
if (!equals(prevoutHash, utxoHash)) {
|
|
994
|
-
throw new Error(`Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`);
|
|
995
|
-
}
|
|
996
|
-
const prevoutIndex = unsignedTx.ins[inputIndex].index;
|
|
997
|
-
prevout = nonWitnessUtxoTx.outs[prevoutIndex];
|
|
998
|
-
}
|
|
999
|
-
else if (input.witnessUtxo) {
|
|
1000
|
-
prevout = {
|
|
1001
|
-
script: input.witnessUtxo.script,
|
|
1002
|
-
value: input.witnessUtxo.value,
|
|
1003
|
-
};
|
|
1004
|
-
}
|
|
1005
|
-
else {
|
|
1006
|
-
throw new Error('Need a Utxo input item for signing');
|
|
1007
|
-
}
|
|
1008
|
-
const { meaningfulScript, type } = getMeaningfulScript(prevout.script, inputIndex, 'input', input.redeemScript, input.witnessScript);
|
|
1009
|
-
const script = meaningfulScript;
|
|
1010
|
-
if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) {
|
|
1011
|
-
hash = unsignedTx.hashForWitnessV0(inputIndex, script, prevout.value, sighashType);
|
|
1012
|
-
}
|
|
1013
|
-
else if (isP2WPKH(meaningfulScript)) {
|
|
1014
|
-
// P2WPKH uses the P2PKH template for prevoutScript when signing
|
|
1015
|
-
const p2pkhPayment = payments.p2pkh({
|
|
1016
|
-
hash: meaningfulScript.subarray(2),
|
|
1017
|
-
});
|
|
1018
|
-
if (!p2pkhPayment.output)
|
|
1019
|
-
throw new Error('Unable to create signing script');
|
|
1020
|
-
hash = unsignedTx.hashForWitnessV0(inputIndex, p2pkhPayment.output, prevout.value, sighashType);
|
|
1021
|
-
}
|
|
1022
|
-
else {
|
|
1023
|
-
// non-segwit
|
|
1024
|
-
if (input.nonWitnessUtxo === undefined && !cache.unsafeSignNonSegwit)
|
|
1025
|
-
throw new Error(`Input #${inputIndex} has witnessUtxo but non-segwit script: ` +
|
|
1026
|
-
toHex(meaningfulScript));
|
|
1027
|
-
if (!forValidate && cache.unsafeSignNonSegwit)
|
|
1028
|
-
console.warn('Warning: Signing non-segwit inputs without the full parent transaction ' +
|
|
1029
|
-
'means there is a chance that a miner could feed you incorrect information ' +
|
|
1030
|
-
"to trick you into paying large fees. This behavior is the same as Psbt's predecessor " +
|
|
1031
|
-
'(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' +
|
|
1032
|
-
'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' +
|
|
1033
|
-
'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' +
|
|
1034
|
-
'*********************');
|
|
1035
|
-
hash = unsignedTx.hashForSignature(inputIndex, script, sighashType);
|
|
1036
|
-
}
|
|
1037
|
-
return {
|
|
1038
|
-
script,
|
|
1039
|
-
sighashType,
|
|
1040
|
-
hash,
|
|
1041
|
-
};
|
|
1042
|
-
}
|
|
1043
|
-
function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) {
|
|
1044
|
-
const allPublicKeys = [];
|
|
1045
|
-
if (input.tapInternalKey) {
|
|
1046
|
-
const key = getPrevoutTaprootKey(inputIndex, input, cache);
|
|
1047
|
-
if (key) {
|
|
1048
|
-
allPublicKeys.push(key);
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
if (input.tapScriptSig) {
|
|
1052
|
-
const tapScriptPubkeys = input.tapScriptSig.map((tss) => tss.pubkey);
|
|
1053
|
-
allPublicKeys.push(...tapScriptPubkeys);
|
|
1054
|
-
}
|
|
1055
|
-
const allHashes = allPublicKeys.map((pubicKey) => getTaprootHashesForSig(inputIndex, input, inputs, pubicKey, cache));
|
|
1056
|
-
return allHashes.flat();
|
|
1057
|
-
}
|
|
1058
|
-
function getPrevoutTaprootKey(inputIndex, input, cache) {
|
|
1059
|
-
const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
|
|
1060
|
-
return isP2TR(script) ? script.subarray(2, 34) : null;
|
|
1061
|
-
}
|
|
1062
|
-
function trimTaprootSig(signature) {
|
|
1063
|
-
return signature.length === 64 ? signature : signature.subarray(0, 64);
|
|
1064
|
-
}
|
|
1065
|
-
function getTaprootHashesForSig(inputIndex, input, inputs, pubkey, cache, tapLeafHashToSign, allowedSighashTypes) {
|
|
1066
|
-
const unsignedTx = cache.tx;
|
|
1067
|
-
const sighashType = input.sighashType || Transaction.SIGHASH_DEFAULT;
|
|
1068
|
-
checkSighashTypeAllowed(sighashType, allowedSighashTypes);
|
|
1069
|
-
if (!cache.prevOuts) {
|
|
1070
|
-
const prevOuts = inputs.map((i, index) => getScriptAndAmountFromUtxo(index, i, cache));
|
|
1071
|
-
cache.prevOuts = prevOuts;
|
|
1072
|
-
cache.signingScripts = prevOuts.map((o) => o.script);
|
|
1073
|
-
cache.values = prevOuts.map((o) => o.value);
|
|
1074
|
-
}
|
|
1075
|
-
const signingScripts = cache.signingScripts;
|
|
1076
|
-
const values = cache.values;
|
|
1077
|
-
// Compute taproot hash cache once for all inputs (O(n) -> O(1) per input)
|
|
1078
|
-
if (!cache.taprootHashCache) {
|
|
1079
|
-
cache.taprootHashCache = unsignedTx.getTaprootHashCache(signingScripts, values);
|
|
1080
|
-
}
|
|
1081
|
-
const taprootCache = cache.taprootHashCache;
|
|
1082
|
-
const hashes = [];
|
|
1083
|
-
if (input.tapInternalKey && !tapLeafHashToSign) {
|
|
1084
|
-
const outputKey = getPrevoutTaprootKey(inputIndex, input, cache) || new Uint8Array(0);
|
|
1085
|
-
if (equals(toXOnly(pubkey), outputKey)) {
|
|
1086
|
-
const tapKeyHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType, undefined, undefined, taprootCache);
|
|
1087
|
-
hashes.push({ pubkey: pubkey, hash: tapKeyHash });
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
const tapLeafHashes = (input.tapLeafScript || [])
|
|
1091
|
-
.filter((tapLeaf) => pubkeyInScript(pubkey, tapLeaf.script))
|
|
1092
|
-
.map((tapLeaf) => {
|
|
1093
|
-
const hash = tapleafHash({
|
|
1094
|
-
output: tapLeaf.script,
|
|
1095
|
-
version: tapLeaf.leafVersion,
|
|
1096
|
-
});
|
|
1097
|
-
return Object.assign({ hash }, tapLeaf);
|
|
1098
|
-
})
|
|
1099
|
-
.filter((tapLeaf) => !tapLeafHashToSign || equals(tapLeafHashToSign, tapLeaf.hash))
|
|
1100
|
-
.map((tapLeaf) => {
|
|
1101
|
-
const tapScriptHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType, tapLeaf.hash, undefined, taprootCache);
|
|
1102
|
-
return {
|
|
1103
|
-
pubkey: pubkey,
|
|
1104
|
-
hash: tapScriptHash,
|
|
1105
|
-
leafHash: tapLeaf.hash,
|
|
1106
|
-
};
|
|
1107
|
-
});
|
|
1108
|
-
return hashes.concat(tapLeafHashes);
|
|
1109
|
-
}
|
|
1110
|
-
function checkSighashTypeAllowed(sighashType, sighashTypes) {
|
|
1111
|
-
if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) {
|
|
1112
|
-
const str = sighashTypeToString(sighashType);
|
|
1113
|
-
throw new Error(`Sighash type is not allowed. Retry the sign method passing the ` +
|
|
1114
|
-
`sighashTypes array of whitelisted types. Sighash type: ${str}`);
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
function getPayment(script, scriptType, partialSig) {
|
|
1118
|
-
const scriptBranded = script;
|
|
1119
|
-
switch (scriptType) {
|
|
1120
|
-
case 'multisig': {
|
|
1121
|
-
const sigs = getSortedSigs(script, partialSig);
|
|
1122
|
-
return payments.p2ms({
|
|
1123
|
-
output: scriptBranded,
|
|
1124
|
-
signatures: sigs,
|
|
1125
|
-
});
|
|
1126
|
-
}
|
|
1127
|
-
case 'pubkey':
|
|
1128
|
-
return payments.p2pk({
|
|
1129
|
-
output: scriptBranded,
|
|
1130
|
-
signature: partialSig[0].signature,
|
|
1131
|
-
});
|
|
1132
|
-
case 'pubkeyhash':
|
|
1133
|
-
return payments.p2pkh({
|
|
1134
|
-
output: scriptBranded,
|
|
1135
|
-
pubkey: partialSig[0].pubkey,
|
|
1136
|
-
signature: partialSig[0].signature,
|
|
1137
|
-
});
|
|
1138
|
-
case 'witnesspubkeyhash':
|
|
1139
|
-
return payments.p2wpkh({
|
|
1140
|
-
output: scriptBranded,
|
|
1141
|
-
pubkey: partialSig[0].pubkey,
|
|
1142
|
-
signature: partialSig[0].signature,
|
|
1143
|
-
});
|
|
1144
|
-
default:
|
|
1145
|
-
throw new Error(`Unknown script type: ${scriptType}`);
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
function getScriptFromInput(inputIndex, input, cache) {
|
|
1149
|
-
const unsignedTx = cache.tx;
|
|
1150
|
-
const res = {
|
|
1151
|
-
script: null,
|
|
1152
|
-
isSegwit: false,
|
|
1153
|
-
isP2SH: false,
|
|
1154
|
-
isP2WSH: false,
|
|
1155
|
-
};
|
|
1156
|
-
res.isP2SH = !!input.redeemScript;
|
|
1157
|
-
res.isP2WSH = !!input.witnessScript;
|
|
1158
|
-
if (input.witnessScript) {
|
|
1159
|
-
res.script = input.witnessScript;
|
|
1160
|
-
}
|
|
1161
|
-
else if (input.redeemScript) {
|
|
1162
|
-
res.script = input.redeemScript;
|
|
1163
|
-
}
|
|
1164
|
-
else {
|
|
1165
|
-
if (input.nonWitnessUtxo) {
|
|
1166
|
-
const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
|
|
1167
|
-
const prevoutIndex = unsignedTx.ins[inputIndex].index;
|
|
1168
|
-
res.script = nonWitnessUtxoTx.outs[prevoutIndex].script;
|
|
1169
|
-
}
|
|
1170
|
-
else if (input.witnessUtxo) {
|
|
1171
|
-
res.script = input.witnessUtxo.script;
|
|
1172
|
-
}
|
|
1173
|
-
}
|
|
1174
|
-
if (input.witnessScript || (res.script && isP2WPKH(res.script))) {
|
|
1175
|
-
res.isSegwit = true;
|
|
1176
|
-
}
|
|
1177
|
-
else {
|
|
1178
|
-
try {
|
|
1179
|
-
const output = res.script;
|
|
1180
|
-
if (!output)
|
|
1181
|
-
throw new TypeError('Invalid script for segwit address');
|
|
1182
|
-
res.isSegwit = isUnknownSegwitVersion(output);
|
|
1183
|
-
}
|
|
1184
|
-
catch (e) { }
|
|
1185
|
-
}
|
|
1186
|
-
return res;
|
|
1187
|
-
}
|
|
1188
|
-
function getSignersFromHD(inputIndex, inputs, hdKeyPair) {
|
|
1189
|
-
const input = checkForInput(inputs, inputIndex);
|
|
1190
|
-
if (!input.bip32Derivation || input.bip32Derivation.length === 0) {
|
|
1191
|
-
throw new Error('Need bip32Derivation to sign with HD');
|
|
1192
|
-
}
|
|
1193
|
-
const myDerivations = input.bip32Derivation
|
|
1194
|
-
.map((bipDv) => {
|
|
1195
|
-
if (equals(bipDv.masterFingerprint, hdKeyPair.fingerprint)) {
|
|
1196
|
-
return bipDv;
|
|
1197
|
-
}
|
|
1198
|
-
else {
|
|
1199
|
-
return;
|
|
1200
|
-
}
|
|
1201
|
-
})
|
|
1202
|
-
.filter((v) => !!v);
|
|
1203
|
-
if (myDerivations.length === 0) {
|
|
1204
|
-
throw new Error('Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint');
|
|
1205
|
-
}
|
|
1206
|
-
return myDerivations.map((bipDv) => {
|
|
1207
|
-
const node = hdKeyPair.derivePath(bipDv.path);
|
|
1208
|
-
if (!equals(bipDv.pubkey, node.publicKey)) {
|
|
1209
|
-
throw new Error('pubkey did not match bip32Derivation');
|
|
1210
|
-
}
|
|
1211
|
-
return node;
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
function getSortedSigs(script, partialSig) {
|
|
1215
|
-
const p2ms = payments.p2ms({ output: script });
|
|
1216
|
-
if (!p2ms.pubkeys)
|
|
1217
|
-
throw new Error('Cannot extract pubkeys from multisig script');
|
|
1218
|
-
// for each pubkey in order of p2ms script
|
|
1219
|
-
const result = [];
|
|
1220
|
-
for (const pk of p2ms.pubkeys) {
|
|
1221
|
-
// filter partialSig array by pubkey being equal
|
|
1222
|
-
const matched = partialSig.filter((ps) => {
|
|
1223
|
-
return equals(ps.pubkey, pk);
|
|
1224
|
-
})[0];
|
|
1225
|
-
if (matched) {
|
|
1226
|
-
result.push(new Uint8Array(matched.signature));
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
return result;
|
|
1230
|
-
}
|
|
1231
|
-
function addNonWitnessTxCache(cache, input, inputIndex) {
|
|
1232
|
-
if (!input.nonWitnessUtxo)
|
|
1233
|
-
throw new Error('nonWitnessUtxo is required');
|
|
1234
|
-
// Prevent prototype pollution - ensure input is a valid object
|
|
1235
|
-
if (input === null || input === Object.prototype) {
|
|
1236
|
-
throw new Error('Invalid input object');
|
|
1237
|
-
}
|
|
1238
|
-
const nonWitnessUtxoBuf = input.nonWitnessUtxo;
|
|
1239
|
-
cache.nonWitnessUtxoBufCache[inputIndex] = nonWitnessUtxoBuf;
|
|
1240
|
-
cache.nonWitnessUtxoTxCache[inputIndex] = Transaction.fromBuffer(nonWitnessUtxoBuf);
|
|
1241
|
-
const self = cache;
|
|
1242
|
-
const selfIndex = inputIndex;
|
|
1243
|
-
delete input.nonWitnessUtxo;
|
|
1244
|
-
// Using Reflect.defineProperty to avoid prototype pollution concerns
|
|
1245
|
-
Reflect.defineProperty(input, 'nonWitnessUtxo', {
|
|
1246
|
-
enumerable: true,
|
|
1247
|
-
get() {
|
|
1248
|
-
const buf = self.nonWitnessUtxoBufCache[selfIndex];
|
|
1249
|
-
const txCache = self.nonWitnessUtxoTxCache[selfIndex];
|
|
1250
|
-
if (buf !== undefined) {
|
|
1251
|
-
return buf;
|
|
1252
|
-
}
|
|
1253
|
-
else {
|
|
1254
|
-
const newBuf = txCache.toBuffer();
|
|
1255
|
-
self.nonWitnessUtxoBufCache[selfIndex] = newBuf;
|
|
1256
|
-
return newBuf;
|
|
1257
|
-
}
|
|
1258
|
-
},
|
|
1259
|
-
set(data) {
|
|
1260
|
-
self.nonWitnessUtxoBufCache[selfIndex] = data;
|
|
1261
|
-
},
|
|
1262
|
-
});
|
|
1263
|
-
}
|
|
1264
|
-
function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize, disableOutputChecks) {
|
|
1265
|
-
let inputAmount = 0n;
|
|
1266
|
-
inputs.forEach((input, idx) => {
|
|
1267
|
-
if (mustFinalize && input.finalScriptSig)
|
|
1268
|
-
tx.ins[idx].script = input.finalScriptSig;
|
|
1269
|
-
if (mustFinalize && input.finalScriptWitness) {
|
|
1270
|
-
tx.ins[idx].witness = scriptWitnessToWitnessStack(input.finalScriptWitness);
|
|
1271
|
-
}
|
|
1272
|
-
if (input.witnessUtxo) {
|
|
1273
|
-
inputAmount += input.witnessUtxo.value;
|
|
1274
|
-
}
|
|
1275
|
-
else if (input.nonWitnessUtxo) {
|
|
1276
|
-
const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx);
|
|
1277
|
-
const vout = tx.ins[idx].index;
|
|
1278
|
-
const out = nwTx.outs[vout];
|
|
1279
|
-
inputAmount += out.value;
|
|
1280
|
-
}
|
|
1281
|
-
});
|
|
1282
|
-
const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0n);
|
|
1283
|
-
const fee = inputAmount - outputAmount;
|
|
1284
|
-
if (!disableOutputChecks) {
|
|
1285
|
-
if (fee < 0n) {
|
|
1286
|
-
throw new Error(`Outputs are spending more than Inputs ${inputAmount} < ${outputAmount}`);
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
const bytes = tx.virtualSize();
|
|
1290
|
-
cache.fee = Number(fee);
|
|
1291
|
-
cache.extractedTx = tx;
|
|
1292
|
-
cache.feeRate = Math.floor(Number(fee) / bytes);
|
|
1293
|
-
}
|
|
1294
|
-
function nonWitnessUtxoTxFromCache(cache, input, inputIndex) {
|
|
1295
|
-
const c = cache.nonWitnessUtxoTxCache;
|
|
1296
|
-
if (!c[inputIndex]) {
|
|
1297
|
-
addNonWitnessTxCache(cache, input, inputIndex);
|
|
1298
|
-
}
|
|
1299
|
-
return c[inputIndex];
|
|
1300
|
-
}
|
|
1301
|
-
function getScriptFromUtxo(inputIndex, input, cache) {
|
|
1302
|
-
const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
|
|
1303
|
-
return script;
|
|
1304
|
-
}
|
|
1305
|
-
function getScriptAndAmountFromUtxo(inputIndex, input, cache) {
|
|
1306
|
-
if (input.witnessUtxo !== undefined) {
|
|
1307
|
-
return {
|
|
1308
|
-
script: input.witnessUtxo.script,
|
|
1309
|
-
value: input.witnessUtxo.value,
|
|
1310
|
-
};
|
|
1311
|
-
}
|
|
1312
|
-
else if (input.nonWitnessUtxo !== undefined) {
|
|
1313
|
-
const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
|
|
1314
|
-
const o = nonWitnessUtxoTx.outs[cache.tx.ins[inputIndex].index];
|
|
1315
|
-
return { script: o.script, value: o.value };
|
|
1316
|
-
}
|
|
1317
|
-
else {
|
|
1318
|
-
throw new Error("Can't find pubkey in input without Utxo data");
|
|
1319
|
-
}
|
|
1320
|
-
}
|
|
1321
|
-
function pubkeyInInput(pubkey, input, inputIndex, cache) {
|
|
1322
|
-
const script = getScriptFromUtxo(inputIndex, input, cache);
|
|
1323
|
-
const { meaningfulScript } = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript, input.witnessScript);
|
|
1324
|
-
return pubkeyInScript(pubkey, meaningfulScript);
|
|
1325
|
-
}
|
|
1326
|
-
function pubkeyInOutput(pubkey, output, outputIndex, cache) {
|
|
1327
|
-
const script = cache.tx.outs[outputIndex].script;
|
|
1328
|
-
const { meaningfulScript } = getMeaningfulScript(script, outputIndex, 'output', output.redeemScript, output.witnessScript);
|
|
1329
|
-
return pubkeyInScript(pubkey, meaningfulScript);
|
|
1330
|
-
}
|
|
1331
|
-
function redeemFromFinalScriptSig(finalScript) {
|
|
1332
|
-
if (!finalScript)
|
|
1333
|
-
return;
|
|
1334
|
-
const decomp = bscript.decompile(finalScript);
|
|
1335
|
-
if (!decomp)
|
|
1336
|
-
return;
|
|
1337
|
-
const lastItem = decomp[decomp.length - 1];
|
|
1338
|
-
if (!(lastItem instanceof Uint8Array) || isPubkeyLike(lastItem) || isSigLike(lastItem))
|
|
1339
|
-
return;
|
|
1340
|
-
const sDecomp = bscript.decompile(lastItem);
|
|
1341
|
-
if (!sDecomp)
|
|
1342
|
-
return;
|
|
1343
|
-
return lastItem;
|
|
1344
|
-
}
|
|
1345
|
-
function redeemFromFinalWitnessScript(finalScript) {
|
|
1346
|
-
if (!finalScript)
|
|
1347
|
-
return;
|
|
1348
|
-
const decomp = scriptWitnessToWitnessStack(finalScript);
|
|
1349
|
-
const lastItem = decomp[decomp.length - 1];
|
|
1350
|
-
if (isPubkeyLike(lastItem))
|
|
1351
|
-
return;
|
|
1352
|
-
const sDecomp = bscript.decompile(lastItem);
|
|
1353
|
-
if (!sDecomp)
|
|
1354
|
-
return;
|
|
1355
|
-
return lastItem;
|
|
1356
|
-
}
|
|
1357
750
|
//# sourceMappingURL=psbt.js.map
|