@btc-vision/bitcoin 7.0.0-alpha.1 → 7.0.0-alpha.3

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.
Files changed (180) hide show
  1. package/README.md +334 -161
  2. package/browser/address.d.ts +5 -1
  3. package/browser/address.d.ts.map +1 -1
  4. package/browser/branded.d.ts +3 -14
  5. package/browser/branded.d.ts.map +1 -1
  6. package/browser/ecc/context.d.ts +22 -21
  7. package/browser/ecc/context.d.ts.map +1 -1
  8. package/browser/ecc/index.d.ts +1 -1
  9. package/browser/ecc/index.d.ts.map +1 -1
  10. package/browser/ecc/types.d.ts +10 -123
  11. package/browser/ecc/types.d.ts.map +1 -1
  12. package/browser/index.d.ts +3 -2
  13. package/browser/index.d.ts.map +1 -1
  14. package/browser/index.js +6465 -4692
  15. package/browser/opcodes.d.ts +11 -0
  16. package/browser/opcodes.d.ts.map +1 -1
  17. package/browser/payments/p2tr.d.ts.map +1 -1
  18. package/browser/psbt/PsbtCache.d.ts +54 -0
  19. package/browser/psbt/PsbtCache.d.ts.map +1 -0
  20. package/browser/psbt/PsbtFinalizer.d.ts +21 -0
  21. package/browser/psbt/PsbtFinalizer.d.ts.map +1 -0
  22. package/browser/psbt/PsbtSigner.d.ts +32 -0
  23. package/browser/psbt/PsbtSigner.d.ts.map +1 -0
  24. package/browser/psbt/PsbtTransaction.d.ts +25 -0
  25. package/browser/psbt/PsbtTransaction.d.ts.map +1 -0
  26. package/browser/psbt/types.d.ts +4 -70
  27. package/browser/psbt/types.d.ts.map +1 -1
  28. package/browser/psbt/validation.d.ts +1 -1
  29. package/browser/psbt/validation.d.ts.map +1 -1
  30. package/browser/psbt.d.ts +26 -40
  31. package/browser/psbt.d.ts.map +1 -1
  32. package/browser/script.d.ts.map +1 -1
  33. package/browser/transaction.d.ts +4 -4
  34. package/browser/transaction.d.ts.map +1 -1
  35. package/browser/types.d.ts +5 -3
  36. package/browser/types.d.ts.map +1 -1
  37. package/browser/workers/index.d.ts +3 -50
  38. package/browser/workers/index.d.ts.map +1 -1
  39. package/browser/workers/index.node.d.ts +24 -0
  40. package/browser/workers/index.node.d.ts.map +1 -0
  41. package/build/address.d.ts +5 -1
  42. package/build/address.d.ts.map +1 -1
  43. package/build/address.js +29 -17
  44. package/build/address.js.map +1 -1
  45. package/build/branded.d.ts +3 -14
  46. package/build/branded.d.ts.map +1 -1
  47. package/build/branded.js +0 -5
  48. package/build/branded.js.map +1 -1
  49. package/build/ecc/context.d.ts +22 -21
  50. package/build/ecc/context.d.ts.map +1 -1
  51. package/build/ecc/context.js +23 -95
  52. package/build/ecc/context.js.map +1 -1
  53. package/build/ecc/index.d.ts +1 -1
  54. package/build/ecc/index.d.ts.map +1 -1
  55. package/build/ecc/types.d.ts +7 -126
  56. package/build/ecc/types.d.ts.map +1 -1
  57. package/build/ecc/types.js +4 -1
  58. package/build/ecc/types.js.map +1 -1
  59. package/build/index.d.ts +3 -2
  60. package/build/index.d.ts.map +1 -1
  61. package/build/index.js +1 -1
  62. package/build/index.js.map +1 -1
  63. package/build/opcodes.d.ts +11 -0
  64. package/build/opcodes.d.ts.map +1 -1
  65. package/build/opcodes.js +19 -4
  66. package/build/opcodes.js.map +1 -1
  67. package/build/payments/p2tr.d.ts.map +1 -1
  68. package/build/payments/p2tr.js +2 -3
  69. package/build/payments/p2tr.js.map +1 -1
  70. package/build/psbt/PsbtCache.d.ts +54 -0
  71. package/build/psbt/PsbtCache.d.ts.map +1 -0
  72. package/build/psbt/PsbtCache.js +249 -0
  73. package/build/psbt/PsbtCache.js.map +1 -0
  74. package/build/psbt/PsbtFinalizer.d.ts +21 -0
  75. package/build/psbt/PsbtFinalizer.d.ts.map +1 -0
  76. package/build/psbt/PsbtFinalizer.js +157 -0
  77. package/build/psbt/PsbtFinalizer.js.map +1 -0
  78. package/build/psbt/PsbtSigner.d.ts +32 -0
  79. package/build/psbt/PsbtSigner.d.ts.map +1 -0
  80. package/build/psbt/PsbtSigner.js +192 -0
  81. package/build/psbt/PsbtSigner.js.map +1 -0
  82. package/build/psbt/PsbtTransaction.d.ts +25 -0
  83. package/build/psbt/PsbtTransaction.d.ts.map +1 -0
  84. package/build/psbt/PsbtTransaction.js +61 -0
  85. package/build/psbt/PsbtTransaction.js.map +1 -0
  86. package/build/psbt/types.d.ts +4 -70
  87. package/build/psbt/types.d.ts.map +1 -1
  88. package/build/psbt/validation.d.ts +1 -1
  89. package/build/psbt/validation.d.ts.map +1 -1
  90. package/build/psbt.d.ts +26 -40
  91. package/build/psbt.d.ts.map +1 -1
  92. package/build/psbt.js +177 -799
  93. package/build/psbt.js.map +1 -1
  94. package/build/script.d.ts.map +1 -1
  95. package/build/script.js +2 -2
  96. package/build/script.js.map +1 -1
  97. package/build/transaction.d.ts +4 -4
  98. package/build/transaction.d.ts.map +1 -1
  99. package/build/transaction.js +5 -4
  100. package/build/transaction.js.map +1 -1
  101. package/build/tsconfig.build.tsbuildinfo +1 -1
  102. package/build/types.d.ts +5 -3
  103. package/build/types.d.ts.map +1 -1
  104. package/build/types.js +9 -0
  105. package/build/types.js.map +1 -1
  106. package/build/workers/WorkerSigningPool.js +1 -1
  107. package/build/workers/WorkerSigningPool.js.map +1 -1
  108. package/build/workers/index.d.ts +3 -3
  109. package/build/workers/index.d.ts.map +1 -1
  110. package/build/workers/index.js +0 -3
  111. package/build/workers/index.js.map +1 -1
  112. package/build/workers/index.node.d.ts +24 -0
  113. package/build/workers/index.node.d.ts.map +1 -0
  114. package/build/workers/index.node.js +26 -0
  115. package/build/workers/index.node.js.map +1 -0
  116. package/package.json +27 -8
  117. package/src/address.ts +41 -18
  118. package/src/branded.ts +15 -13
  119. package/src/ecc/context.ts +30 -133
  120. package/src/ecc/index.ts +2 -2
  121. package/src/ecc/types.ts +7 -138
  122. package/src/index.ts +36 -2
  123. package/src/opcodes.ts +21 -4
  124. package/src/payments/p2tr.ts +2 -2
  125. package/src/psbt/PsbtCache.ts +325 -0
  126. package/src/psbt/PsbtFinalizer.ts +213 -0
  127. package/src/psbt/PsbtSigner.ts +302 -0
  128. package/src/psbt/PsbtTransaction.ts +82 -0
  129. package/src/psbt/types.ts +4 -86
  130. package/src/psbt/validation.ts +1 -1
  131. package/src/psbt.ts +348 -1197
  132. package/src/script.ts +2 -2
  133. package/src/transaction.ts +9 -8
  134. package/src/types.ts +14 -1
  135. package/src/workers/WorkerSigningPool.ts +1 -1
  136. package/src/workers/index.node.ts +27 -0
  137. package/src/workers/index.ts +7 -9
  138. package/test/address.spec.ts +2 -2
  139. package/test/bitcoin.core.spec.ts +5 -2
  140. package/test/browser/payments.spec.ts +151 -0
  141. package/test/browser/psbt.spec.ts +1510 -0
  142. package/test/browser/script.spec.ts +223 -0
  143. package/test/browser/setup.ts +13 -0
  144. package/test/browser/workers-signing.spec.ts +537 -0
  145. package/test/crypto.spec.ts +2 -2
  146. package/test/fixtures/core/base58_encode_decode.json +12 -48
  147. package/test/fixtures/core/base58_keys_invalid.json +50 -150
  148. package/test/fixtures/core/sighash.json +1 -3
  149. package/test/fixtures/core/tx_valid.json +133 -501
  150. package/test/fixtures/embed.json +3 -11
  151. package/test/fixtures/p2ms.json +21 -91
  152. package/test/fixtures/p2pk.json +5 -24
  153. package/test/fixtures/p2pkh.json +7 -36
  154. package/test/fixtures/p2sh.json +8 -54
  155. package/test/fixtures/p2tr.json +2 -6
  156. package/test/fixtures/p2wpkh.json +7 -36
  157. package/test/fixtures/p2wsh.json +14 -59
  158. package/test/fixtures/psbt.json +2 -6
  159. package/test/fixtures/script.json +12 -48
  160. package/test/integration/addresses.spec.ts +11 -5
  161. package/test/integration/bip32.spec.ts +1 -1
  162. package/test/integration/cltv.spec.ts +10 -6
  163. package/test/integration/csv.spec.ts +10 -9
  164. package/test/integration/payments.spec.ts +8 -4
  165. package/test/integration/taproot.spec.ts +26 -6
  166. package/test/integration/transactions.spec.ts +22 -8
  167. package/test/payments.spec.ts +1 -1
  168. package/test/payments.utils.ts +1 -1
  169. package/test/psbt.spec.ts +250 -64
  170. package/test/script_signature.spec.ts +1 -1
  171. package/test/transaction.spec.ts +18 -5
  172. package/test/tsconfig.json +6 -20
  173. package/test/workers-pool.spec.ts +22 -23
  174. package/test/workers-signing.spec.ts +7 -3
  175. package/test/workers.spec.ts +6 -7
  176. package/typedoc.json +11 -1
  177. package/vitest.config.browser.ts +68 -0
  178. package/browser/ecpair.d.ts +0 -99
  179. package/src/ecpair.d.ts +0 -99
  180. package/test/taproot-cache.spec.ts +0 -694
@@ -0,0 +1,213 @@
1
+ import type { PartialSig, PsbtInput } from 'bip174';
2
+ import { equals } from '../io/index.js';
3
+ import type { P2SHPayment, P2WSHPayment, Payment } from '../payments/index.js';
4
+ import * as payments from '../payments/index.js';
5
+ import { witnessStackToScriptWitness } from './psbtutils.js';
6
+ import { classifyScript, compressPubkey } from './utils.js';
7
+ import type { Transaction } from '../transaction.js';
8
+ import type { PublicKey, Script, Signature } from '../types.js';
9
+ import type { PsbtCache } from './PsbtCache.js';
10
+ import type { GetScriptReturn } from './types.js';
11
+
12
+ export interface FinalScriptsResult {
13
+ readonly finalScriptSig: Script | undefined;
14
+ readonly finalScriptWitness: Uint8Array | undefined;
15
+ }
16
+
17
+ /**
18
+ * Class wrapping all finalization logic for PSBT.
19
+ */
20
+ export class PsbtFinalizer {
21
+ readonly #cache: PsbtCache;
22
+ readonly #txFromBuffer: (buf: Uint8Array) => Transaction;
23
+
24
+ public constructor(cache: PsbtCache, txFromBuffer: (buf: Uint8Array) => Transaction) {
25
+ this.#cache = cache;
26
+ this.#txFromBuffer = txFromBuffer;
27
+ }
28
+
29
+ public getFinalScripts(
30
+ inputIndex: number,
31
+ input: PsbtInput,
32
+ script: Script,
33
+ isSegwit: boolean,
34
+ isP2SH: boolean,
35
+ isP2WSH: boolean,
36
+ canRunChecks: boolean = true,
37
+ solution?: Uint8Array[],
38
+ ): FinalScriptsResult {
39
+ const scriptType = classifyScript(script);
40
+ if (!canFinalize(input, script, scriptType) && canRunChecks) {
41
+ throw new Error(`Can not finalize input #${inputIndex}`);
42
+ }
43
+
44
+ if (!input.partialSig) throw new Error('Input missing partial signatures');
45
+ return prepareFinalScripts(
46
+ script,
47
+ scriptType,
48
+ input.partialSig,
49
+ isSegwit,
50
+ isP2SH,
51
+ isP2WSH,
52
+ solution,
53
+ );
54
+ }
55
+
56
+ public getScriptFromInput(inputIndex: number, input: PsbtInput): GetScriptReturn {
57
+ return this.#cache.getScriptFromInput(inputIndex, input, this.#txFromBuffer);
58
+ }
59
+ }
60
+
61
+ export function getFinalScripts(
62
+ inputIndex: number,
63
+ input: PsbtInput,
64
+ script: Script,
65
+ isSegwit: boolean,
66
+ isP2SH: boolean,
67
+ isP2WSH: boolean,
68
+ canRunChecks: boolean = true,
69
+ solution?: Uint8Array[],
70
+ ): FinalScriptsResult {
71
+ const scriptType = classifyScript(script);
72
+ if (!canFinalize(input, script, scriptType) && canRunChecks) {
73
+ throw new Error(`Can not finalize input #${inputIndex}`);
74
+ }
75
+
76
+ if (!input.partialSig) throw new Error('Input missing partial signatures');
77
+ return prepareFinalScripts(
78
+ script,
79
+ scriptType,
80
+ input.partialSig,
81
+ isSegwit,
82
+ isP2SH,
83
+ isP2WSH,
84
+ solution,
85
+ );
86
+ }
87
+
88
+ export function prepareFinalScripts(
89
+ script: Uint8Array,
90
+ scriptType: string,
91
+ partialSig: PartialSig[],
92
+ isSegwit: boolean,
93
+ isP2SH: boolean,
94
+ isP2WSH: boolean,
95
+ solution?: Uint8Array[],
96
+ ): FinalScriptsResult {
97
+ let finalScriptSig: Script | undefined;
98
+ let finalScriptWitness: Uint8Array | undefined;
99
+
100
+ const payment: Payment = getPayment(script, scriptType, partialSig);
101
+ const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment } as P2WSHPayment);
102
+ const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment } as P2SHPayment);
103
+
104
+ if (isSegwit) {
105
+ if (p2wsh && p2wsh.witness) {
106
+ finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness);
107
+ } else if (payment && payment.witness) {
108
+ finalScriptWitness = witnessStackToScriptWitness(payment.witness);
109
+ } else {
110
+ finalScriptWitness = witnessStackToScriptWitness(solution ?? [new Uint8Array([0x00])]);
111
+ }
112
+ if (p2sh) {
113
+ finalScriptSig = p2sh?.input as Script | undefined;
114
+ }
115
+ } else {
116
+ if (p2sh) {
117
+ finalScriptSig = p2sh?.input as Script | undefined;
118
+ } else {
119
+ if (!payment) {
120
+ finalScriptSig = (
121
+ Array.isArray(solution) && solution[0] ? solution[0] : new Uint8Array([0x01])
122
+ ) as Script;
123
+ } else {
124
+ finalScriptSig = payment.input as Script | undefined;
125
+ }
126
+ }
127
+ }
128
+ return { finalScriptSig, finalScriptWitness };
129
+ }
130
+
131
+ function canFinalize(input: PsbtInput, script: Uint8Array, scriptType: string): boolean {
132
+ switch (scriptType) {
133
+ case 'pubkey':
134
+ case 'pubkeyhash':
135
+ case 'witnesspubkeyhash':
136
+ return hasSigs(1, input.partialSig);
137
+ case 'multisig': {
138
+ const p2ms = payments.p2ms({
139
+ output: script as Script,
140
+ });
141
+ if (p2ms.m === undefined) throw new Error('Cannot determine m for multisig');
142
+ return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys);
143
+ }
144
+ case 'nonstandard':
145
+ return true;
146
+ default:
147
+ return false;
148
+ }
149
+ }
150
+
151
+ function hasSigs(neededSigs: number, partialSig?: PartialSig[], pubkeys?: Uint8Array[]): boolean {
152
+ if (!partialSig) return false;
153
+ let sigs: PartialSig[];
154
+ if (pubkeys) {
155
+ sigs = pubkeys
156
+ .map((pkey) => {
157
+ const pubkey = compressPubkey(pkey);
158
+ return partialSig.find((pSig) => equals(pSig.pubkey, pubkey));
159
+ })
160
+ .filter((v): v is PartialSig => !!v);
161
+ } else {
162
+ sigs = partialSig;
163
+ }
164
+ if (sigs.length > neededSigs) throw new Error('Too many signatures');
165
+ return sigs.length === neededSigs;
166
+ }
167
+
168
+ function getPayment(script: Uint8Array, scriptType: string, partialSig: PartialSig[]): Payment {
169
+ const scriptBranded = script as Script;
170
+ switch (scriptType) {
171
+ case 'multisig': {
172
+ const sigs = getSortedSigs(script, partialSig);
173
+ return payments.p2ms({
174
+ output: scriptBranded,
175
+ signatures: sigs as Signature[],
176
+ });
177
+ }
178
+ case 'pubkey':
179
+ return payments.p2pk({
180
+ output: scriptBranded,
181
+ signature: partialSig[0]!.signature as Signature,
182
+ });
183
+ case 'pubkeyhash':
184
+ return payments.p2pkh({
185
+ output: scriptBranded,
186
+ pubkey: partialSig[0]!.pubkey as PublicKey,
187
+ signature: partialSig[0]!.signature as Signature,
188
+ });
189
+ case 'witnesspubkeyhash':
190
+ return payments.p2wpkh({
191
+ output: scriptBranded,
192
+ pubkey: partialSig[0]!.pubkey as PublicKey,
193
+ signature: partialSig[0]!.signature as Signature,
194
+ });
195
+ default:
196
+ throw new Error(`Unknown script type: ${scriptType}`);
197
+ }
198
+ }
199
+
200
+ function getSortedSigs(script: Uint8Array, partialSig: PartialSig[]): Uint8Array[] {
201
+ const p2ms = payments.p2ms({ output: script as Script });
202
+ if (!p2ms.pubkeys) throw new Error('Cannot extract pubkeys from multisig script');
203
+ const result: Uint8Array[] = [];
204
+ for (const pk of p2ms.pubkeys) {
205
+ const matched = partialSig.filter((ps) => {
206
+ return equals(ps.pubkey, pk);
207
+ })[0];
208
+ if (matched) {
209
+ result.push(new Uint8Array(matched.signature));
210
+ }
211
+ }
212
+ return result;
213
+ }
@@ -0,0 +1,302 @@
1
+ import type { Bip32Derivation, PsbtInput } from 'bip174';
2
+ import { checkForInput } from 'bip174';
3
+ import { equals, toHex } from '../io/index.js';
4
+ import * as payments from '../payments/index.js';
5
+ import { tapleafHash } from '../payments/bip341.js';
6
+ import { toXOnly } from '../pubkey.js';
7
+ import { isP2WPKH, pubkeyInScript } from './psbtutils.js';
8
+ import { getMeaningfulScript, sighashTypeToString } from './utils.js';
9
+ import { checkScriptForPubkey } from './validation.js';
10
+ import type { Output } from '../transaction.js';
11
+ import { Transaction } from '../transaction.js';
12
+ import type { Bytes20, Bytes32, MessageHash, PublicKey, Satoshi, Script } from '../types.js';
13
+ import type { PsbtCache } from './PsbtCache.js';
14
+ import type { HDSigner, HDSignerAsync } from './types.js';
15
+
16
+ export interface HashForSig {
17
+ readonly pubkey: PublicKey;
18
+ readonly hash: MessageHash;
19
+ readonly leafHash?: Bytes32;
20
+ }
21
+
22
+ /**
23
+ * Class wrapping all signing-related logic for PSBT.
24
+ */
25
+ export class PsbtSigner {
26
+ readonly #cache: PsbtCache;
27
+ readonly #txFromBuffer: (buf: Uint8Array) => Transaction;
28
+
29
+ public constructor(cache: PsbtCache, txFromBuffer: (buf: Uint8Array) => Transaction) {
30
+ this.#cache = cache;
31
+ this.#txFromBuffer = txFromBuffer;
32
+ }
33
+
34
+ public getHashAndSighashType(
35
+ inputs: PsbtInput[],
36
+ inputIndex: number,
37
+ pubkey: Uint8Array,
38
+ sighashTypes: number[],
39
+ ): { hash: MessageHash; sighashType: number } {
40
+ const input = checkForInput(inputs, inputIndex);
41
+ const { hash, sighashType, script } = this.getHashForSig(
42
+ inputIndex,
43
+ input,
44
+ false,
45
+ sighashTypes,
46
+ );
47
+
48
+ checkScriptForPubkey(pubkey as PublicKey, script, 'sign');
49
+ return { hash, sighashType };
50
+ }
51
+
52
+ public getHashForSig(
53
+ inputIndex: number,
54
+ input: PsbtInput,
55
+ forValidate: boolean,
56
+ sighashTypes?: number[],
57
+ ): { script: Script; hash: MessageHash; sighashType: number } {
58
+ const unsignedTx = this.#cache.tx;
59
+ const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
60
+ checkSighashTypeAllowed(sighashType, sighashTypes);
61
+
62
+ let hash: MessageHash;
63
+ let prevout: Output;
64
+
65
+ if (input.nonWitnessUtxo) {
66
+ const nonWitnessUtxoTx = this.#cache.getNonWitnessUtxoTx(
67
+ input,
68
+ inputIndex,
69
+ this.#txFromBuffer,
70
+ );
71
+
72
+ const prevoutHash = unsignedTx.ins[inputIndex]!.hash;
73
+ const utxoHash = nonWitnessUtxoTx.getHash();
74
+
75
+ if (!equals(prevoutHash, utxoHash)) {
76
+ throw new Error(
77
+ `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`,
78
+ );
79
+ }
80
+
81
+ const prevoutIndex = unsignedTx.ins[inputIndex]!.index;
82
+ prevout = nonWitnessUtxoTx.outs[prevoutIndex]!;
83
+ } else if (input.witnessUtxo) {
84
+ prevout = {
85
+ script: input.witnessUtxo.script as Script,
86
+ value: input.witnessUtxo.value as Satoshi,
87
+ };
88
+ } else {
89
+ throw new Error('Need a Utxo input item for signing');
90
+ }
91
+
92
+ const { meaningfulScript, type } = getMeaningfulScript(
93
+ prevout.script,
94
+ inputIndex,
95
+ 'input',
96
+ input.redeemScript,
97
+ input.witnessScript,
98
+ );
99
+
100
+ const script = meaningfulScript as Script;
101
+
102
+ if (['p2sh-p2wsh', 'p2wsh'].includes(type)) {
103
+ hash = unsignedTx.hashForWitnessV0(inputIndex, script, prevout.value, sighashType);
104
+ } else if (isP2WPKH(meaningfulScript)) {
105
+ const p2pkhPayment = payments.p2pkh({
106
+ hash: meaningfulScript.subarray(2) as Bytes20,
107
+ });
108
+ if (!p2pkhPayment.output) throw new Error('Unable to create signing script');
109
+ hash = unsignedTx.hashForWitnessV0(
110
+ inputIndex,
111
+ p2pkhPayment.output as Script,
112
+ prevout.value,
113
+ sighashType,
114
+ );
115
+ } else {
116
+ // non-segwit
117
+ if (input.nonWitnessUtxo === undefined && !this.#cache.unsafeSignNonSegwit)
118
+ throw new Error(
119
+ `Input #${inputIndex} has witnessUtxo but non-segwit script: ` +
120
+ toHex(meaningfulScript),
121
+ );
122
+ if (!forValidate && this.#cache.unsafeSignNonSegwit)
123
+ console.warn(
124
+ 'Warning: Signing non-segwit inputs without the full parent transaction ' +
125
+ 'means there is a chance that a miner could feed you incorrect information ' +
126
+ "to trick you into paying large fees. This behavior is the same as Psbt's predecessor " +
127
+ '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' +
128
+ 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' +
129
+ 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' +
130
+ '*********************',
131
+ );
132
+ hash = unsignedTx.hashForSignature(inputIndex, script, sighashType);
133
+ }
134
+
135
+ return { script, sighashType, hash };
136
+ }
137
+
138
+ public getTaprootHashesForSig(
139
+ inputIndex: number,
140
+ input: PsbtInput,
141
+ inputs: PsbtInput[],
142
+ pubkey: Uint8Array,
143
+ tapLeafHashToSign?: Uint8Array,
144
+ allowedSighashTypes?: number[],
145
+ ): HashForSig[] {
146
+ const unsignedTx = this.#cache.tx;
147
+ const sighashType = input.sighashType || Transaction.SIGHASH_DEFAULT;
148
+ checkSighashTypeAllowed(sighashType, allowedSighashTypes);
149
+
150
+ if (!this.#cache.prevOuts) {
151
+ const prevOuts = inputs.map((i, index) =>
152
+ this.#cache.getScriptAndAmountFromUtxo(index, i, this.#txFromBuffer),
153
+ );
154
+ this.#cache.prevOuts = prevOuts;
155
+ this.#cache.signingScripts = prevOuts.map((o) => o.script);
156
+ this.#cache.values = prevOuts.map((o) => o.value);
157
+ }
158
+ const signingScripts = this.#cache.signingScripts as readonly Script[];
159
+ const values = this.#cache.values as readonly Satoshi[];
160
+
161
+ if (!this.#cache.taprootHashCache) {
162
+ this.#cache.taprootHashCache = unsignedTx.getTaprootHashCache(signingScripts, values);
163
+ }
164
+ const taprootCache = this.#cache.taprootHashCache;
165
+
166
+ const hashes: HashForSig[] = [];
167
+ if (input.tapInternalKey && !tapLeafHashToSign) {
168
+ const outputKey =
169
+ this.#cache.getPrevoutTaprootKey(inputIndex, input, this.#txFromBuffer) ||
170
+ new Uint8Array(0);
171
+ if (equals(toXOnly(pubkey as PublicKey), outputKey)) {
172
+ const tapKeyHash = unsignedTx.hashForWitnessV1(
173
+ inputIndex,
174
+ signingScripts,
175
+ values,
176
+ sighashType,
177
+ undefined,
178
+ undefined,
179
+ taprootCache,
180
+ );
181
+ hashes.push({ pubkey: pubkey as PublicKey, hash: tapKeyHash });
182
+ }
183
+ }
184
+
185
+ const tapLeafHashes = (input.tapLeafScript || [])
186
+ .filter((tapLeaf) => pubkeyInScript(pubkey, tapLeaf.script))
187
+ .map((tapLeaf) => {
188
+ const hash = tapleafHash({
189
+ output: tapLeaf.script,
190
+ version: tapLeaf.leafVersion,
191
+ });
192
+ return Object.assign({ hash }, tapLeaf);
193
+ })
194
+ .filter((tapLeaf) => !tapLeafHashToSign || equals(tapLeafHashToSign, tapLeaf.hash))
195
+ .map((tapLeaf) => {
196
+ const tapScriptHash = unsignedTx.hashForWitnessV1(
197
+ inputIndex,
198
+ signingScripts,
199
+ values,
200
+ sighashType,
201
+ tapLeaf.hash as Bytes32,
202
+ undefined,
203
+ taprootCache,
204
+ );
205
+
206
+ return {
207
+ pubkey: pubkey as PublicKey,
208
+ hash: tapScriptHash,
209
+ leafHash: tapLeaf.hash as Bytes32,
210
+ };
211
+ });
212
+
213
+ return hashes.concat(tapLeafHashes);
214
+ }
215
+
216
+ public getAllTaprootHashesForSig(
217
+ inputIndex: number,
218
+ input: PsbtInput,
219
+ inputs: PsbtInput[],
220
+ ): HashForSig[] {
221
+ const allPublicKeys: Uint8Array[] = [];
222
+ if (input.tapInternalKey) {
223
+ const key = this.#cache.getPrevoutTaprootKey(inputIndex, input, this.#txFromBuffer);
224
+ if (key) {
225
+ allPublicKeys.push(key);
226
+ }
227
+ }
228
+
229
+ if (input.tapScriptSig) {
230
+ const tapScriptPubkeys = input.tapScriptSig.map((tss) => tss.pubkey);
231
+ allPublicKeys.push(...tapScriptPubkeys);
232
+ }
233
+
234
+ const allHashes = allPublicKeys.map((pubicKey) =>
235
+ this.getTaprootHashesForSig(inputIndex, input, inputs, pubicKey),
236
+ );
237
+
238
+ return allHashes.flat();
239
+ }
240
+
241
+ public trimTaprootSig(signature: Uint8Array): Uint8Array {
242
+ return signature.length === 64 ? signature : signature.subarray(0, 64);
243
+ }
244
+
245
+ public getSignersFromHD<T extends HDSigner | HDSignerAsync>(
246
+ inputIndex: number,
247
+ inputs: PsbtInput[],
248
+ hdKeyPair: T,
249
+ ): T[] {
250
+ const input = checkForInput(inputs, inputIndex);
251
+ if (!input.bip32Derivation || input.bip32Derivation.length === 0) {
252
+ throw new Error('Need bip32Derivation to sign with HD');
253
+ }
254
+ const myDerivations = input.bip32Derivation
255
+ .map((bipDv) => {
256
+ if (equals(bipDv.masterFingerprint, hdKeyPair.fingerprint)) {
257
+ return bipDv;
258
+ } else {
259
+ return;
260
+ }
261
+ })
262
+ .filter((v) => !!v);
263
+ if (myDerivations.length === 0) {
264
+ throw new Error(
265
+ 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint',
266
+ );
267
+ }
268
+
269
+ return myDerivations.map((bipDv) => {
270
+ const node = hdKeyPair.derivePath(bipDv.path) as T;
271
+ if (!equals(bipDv.pubkey, node.publicKey)) {
272
+ throw new Error('pubkey did not match bip32Derivation');
273
+ }
274
+ return node;
275
+ });
276
+ }
277
+
278
+ public bip32DerivationIsMine(root: HDSigner): (d: Bip32Derivation) => boolean {
279
+ return (d: Bip32Derivation): boolean => {
280
+ const fingerprint =
281
+ root.fingerprint instanceof Uint8Array
282
+ ? root.fingerprint
283
+ : new Uint8Array(root.fingerprint);
284
+ if (!equals(d.masterFingerprint, fingerprint)) return false;
285
+ const derivedPubkey = root.derivePath(d.path).publicKey;
286
+ const pubkey =
287
+ derivedPubkey instanceof Uint8Array ? derivedPubkey : new Uint8Array(derivedPubkey);
288
+ if (!equals(pubkey, d.pubkey)) return false;
289
+ return true;
290
+ };
291
+ }
292
+ }
293
+
294
+ function checkSighashTypeAllowed(sighashType: number, sighashTypes?: number[]): void {
295
+ if (sighashTypes && !sighashTypes.includes(sighashType)) {
296
+ const str = sighashTypeToString(sighashType);
297
+ throw new Error(
298
+ `Sighash type is not allowed. Retry the sign method passing the ` +
299
+ `sighashTypes array of whitelisted types. Sighash type: ${str}`,
300
+ );
301
+ }
302
+ }
@@ -0,0 +1,82 @@
1
+ import type { Transaction as ITransaction, TransactionFromBuffer } from 'bip174';
2
+ import { fromHex, reverse } from '../io/index.js';
3
+ import { Transaction } from '../transaction.js';
4
+ import type { Bytes32 } from '../types.js';
5
+ import { checkTxEmpty } from './validation.js';
6
+ import type { TransactionInput, TransactionOutput } from './types.js';
7
+
8
+ /**
9
+ * Empty version-2 transaction with zero inputs and zero outputs.
10
+ * Used as the default buffer when constructing a new PsbtTransaction.
11
+ *
12
+ * Layout: [version(4LE)] [inputCount(varint)] [outputCount(varint)] [locktime(4LE)]
13
+ * [02 00 00 00] [00] [00] [00 00 00 00]
14
+ */
15
+ const EMPTY_TX_V2 = new Uint8Array([2, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
16
+
17
+ /**
18
+ * This class implements the Transaction interface from bip174 library.
19
+ * It contains a bitcoinjs-lib Transaction object.
20
+ */
21
+ export class PsbtTransaction implements ITransaction {
22
+ public tx: Transaction;
23
+
24
+ public constructor(buffer: Uint8Array = EMPTY_TX_V2) {
25
+ this.tx = Transaction.fromBuffer(buffer);
26
+ checkTxEmpty(this.tx);
27
+ Object.defineProperty(this, 'tx', {
28
+ enumerable: false,
29
+ writable: true,
30
+ });
31
+ }
32
+
33
+ public getInputOutputCounts(): {
34
+ inputCount: number;
35
+ outputCount: number;
36
+ } {
37
+ return {
38
+ inputCount: this.tx.ins.length,
39
+ outputCount: this.tx.outs.length,
40
+ };
41
+ }
42
+
43
+ public addInput(input: TransactionInput): void {
44
+ if (
45
+ input.hash === undefined ||
46
+ input.index === undefined ||
47
+ (!(input.hash instanceof Uint8Array) && typeof input.hash !== 'string') ||
48
+ typeof input.index !== 'number'
49
+ ) {
50
+ throw new Error('Error adding input.');
51
+ }
52
+ const hash = (
53
+ typeof input.hash === 'string' ? reverse(fromHex(input.hash)) : input.hash
54
+ ) as Bytes32;
55
+
56
+ this.tx.addInput(hash, input.index, input.sequence);
57
+ }
58
+
59
+ public addOutput(output: TransactionOutput): void {
60
+ if (
61
+ output.script === undefined ||
62
+ output.value === undefined ||
63
+ !(output.script instanceof Uint8Array) ||
64
+ typeof output.value !== 'bigint'
65
+ ) {
66
+ throw new Error('Error adding output.');
67
+ }
68
+ this.tx.addOutput(output.script, output.value);
69
+ }
70
+
71
+ public toBuffer(): Uint8Array {
72
+ return this.tx.toBuffer();
73
+ }
74
+ }
75
+
76
+ /**
77
+ * This function is needed to pass to the bip174 base class's fromBuffer.
78
+ * It takes the "transaction buffer" portion of the psbt buffer and returns a
79
+ * Transaction (From the bip174 library) interface.
80
+ */
81
+ export const transactionFromBuffer: TransactionFromBuffer = (buffer: Uint8Array): ITransaction =>
82
+ new PsbtTransaction(buffer);