@btc-vision/bitcoin 6.3.3 → 6.3.4

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.
@@ -76,11 +76,13 @@ export function p2pkh(a, opts) {
76
76
  let pubKey = a.pubkey;
77
77
  if (a.useHybrid || a.useUncompressed) {
78
78
  const decompressed = decompressPublicKey(a.pubkey);
79
- if (a.useUncompressed) {
80
- pubKey = decompressed.uncompressed;
81
- }
82
- else {
83
- pubKey = decompressed.hybrid;
79
+ if (decompressed) {
80
+ if (a.useUncompressed) {
81
+ pubKey = decompressed.uncompressed;
82
+ }
83
+ else {
84
+ pubKey = decompressed.hybrid;
85
+ }
84
86
  }
85
87
  }
86
88
  return bscript.compile([a.signature, pubKey]);
@@ -131,17 +133,19 @@ export function p2pkh(a, opts) {
131
133
  if ((a.pubkey.length === 33 && (a.pubkey[0] === 0x02 || a.pubkey[0] === 0x03)) ||
132
134
  (a.pubkey.length === 65 && a.pubkey[0] === 0x04)) {
133
135
  const uncompressed = decompressPublicKey(a.pubkey);
134
- const pkh2 = bcrypto.hash160(uncompressed.uncompressed);
135
- if (!hash.equals(pkh2)) {
136
- const pkh3 = bcrypto.hash160(uncompressed.hybrid);
137
- badHash = !hash.equals(pkh3);
138
- if (!badHash) {
139
- a.useHybrid = true;
136
+ if (uncompressed) {
137
+ const pkh2 = bcrypto.hash160(uncompressed.uncompressed);
138
+ if (!hash.equals(pkh2)) {
139
+ const pkh3 = bcrypto.hash160(uncompressed.hybrid);
140
+ badHash = !hash.equals(pkh3);
141
+ if (!badHash) {
142
+ a.useHybrid = true;
143
+ }
144
+ }
145
+ else {
146
+ badHash = false;
147
+ a.useUncompressed = true;
140
148
  }
141
- }
142
- else {
143
- badHash = false;
144
- a.useUncompressed = true;
145
149
  }
146
150
  }
147
151
  }
@@ -11,7 +11,7 @@ export interface UncompressedPublicKey {
11
11
  hybrid: Buffer;
12
12
  uncompressed: Buffer;
13
13
  }
14
- export declare function decompressPublicKey(realPubKey: Uint8Array | Buffer): UncompressedPublicKey;
14
+ export declare function decompressPublicKey(realPubKey: Uint8Array | Buffer): UncompressedPublicKey | undefined;
15
15
  export declare function bigIntTo32Bytes(num: bigint): Buffer;
16
16
  export declare function pubkeysMatch(a: Buffer, b: Buffer): boolean;
17
17
  export declare function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number;
@@ -52,6 +52,9 @@ export function witnessStackToScriptWitness(witness) {
52
52
  return buffer;
53
53
  }
54
54
  export function decompressPublicKey(realPubKey) {
55
+ if (realPubKey.length === 32) {
56
+ return;
57
+ }
55
58
  if (![33, 65].includes(realPubKey.length)) {
56
59
  throw new Error(`Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`);
57
60
  }
@@ -105,8 +108,10 @@ export function pubkeyPositionInScript(pubkey, script) {
105
108
  const pubkeyHash = hash160(pubkey);
106
109
  const pubkeyXOnly = toXOnly(pubkey);
107
110
  const uncompressed = decompressPublicKey(pubkey);
108
- const pubkeyHybridHash = hash160(uncompressed.hybrid);
109
- const pubkeyUncompressedHash = hash160(uncompressed.uncompressed);
111
+ const pubkeyHybridHash = uncompressed?.hybrid ? hash160(uncompressed.hybrid) : undefined;
112
+ const pubkeyUncompressedHash = uncompressed?.uncompressed
113
+ ? hash160(uncompressed.uncompressed)
114
+ : undefined;
110
115
  return decompiled.findIndex((element) => {
111
116
  if (typeof element === 'number')
112
117
  return false;
@@ -117,12 +122,15 @@ export function pubkeyPositionInScript(pubkey, script) {
117
122
  if (element.equals(pubkeyHash)) {
118
123
  return true;
119
124
  }
120
- if (pubkeysMatch(element, uncompressed.uncompressed))
121
- return true;
122
- if (pubkeysMatch(element, uncompressed.hybrid))
123
- return true;
124
- if (element.equals(pubkeyHybridHash) || element.equals(pubkeyUncompressedHash)) {
125
- return true;
125
+ if (uncompressed) {
126
+ if (pubkeysMatch(element, uncompressed.uncompressed))
127
+ return true;
128
+ if (pubkeysMatch(element, uncompressed.hybrid))
129
+ return true;
130
+ if ((pubkeyHybridHash && element.equals(pubkeyHybridHash)) ||
131
+ (pubkeyUncompressedHash && element.equals(pubkeyUncompressedHash))) {
132
+ return true;
133
+ }
126
134
  }
127
135
  });
128
136
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@btc-vision/bitcoin",
3
3
  "type": "module",
4
- "version": "6.3.3",
4
+ "version": "6.3.4",
5
5
  "description": "Client-side Bitcoin JavaScript library",
6
6
  "engines": {
7
7
  "node": ">=16.0.0"
@@ -1,206 +1,210 @@
1
- import * as bs58check from 'bs58check';
2
- import * as bcrypto from '../crypto.js';
3
- import { bitcoin as BITCOIN_NETWORK } from '../networks.js';
4
- import * as bscript from '../script.js';
5
- import { isPoint, typeforce as typef } from '../types.js';
6
- import { Payment, PaymentOpts, StackFunction } from './index.js';
7
- import * as lazy from './lazy.js';
8
- import { decompressPublicKey } from '../psbt/psbtutils.js';
9
-
10
- const OPS = bscript.OPS;
11
-
12
- // input: {signature} {pubkey}
13
- // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG
14
- /**
15
- * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object.
16
- *
17
- * @param a - The payment object containing the necessary data.
18
- * @param opts - Optional payment options.
19
- * @returns The P2PKH payment object.
20
- * @throws {TypeError} If the required data is not provided or if the data is invalid.
21
- */
22
- export function p2pkh(a: Payment, opts?: PaymentOpts): Payment {
23
- if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) {
24
- throw new TypeError('Not enough data');
25
- }
26
-
27
- opts = Object.assign({ validate: true }, opts || {});
28
-
29
- typef(
30
- {
31
- network: typef.maybe(typef.Object),
32
- address: typef.maybe(typef.String),
33
- hash: typef.maybe(typef.BufferN(20)),
34
- output: typef.maybe(typef.BufferN(25)),
35
-
36
- pubkey: typef.maybe(isPoint),
37
- signature: typef.maybe(bscript.isCanonicalScriptSignature),
38
- input: typef.maybe(typef.Buffer),
39
- },
40
- a,
41
- );
42
-
43
- const _address = lazy.value(() => {
44
- const payload = Buffer.from(bs58check.default.decode(a.address!));
45
- const version = payload.readUInt8(0);
46
- const hash = payload.slice(1);
47
- return { version, hash };
48
- });
49
-
50
- const _chunks = lazy.value(() => {
51
- return bscript.decompile(a.input!);
52
- }) as StackFunction;
53
-
54
- const network = a.network || BITCOIN_NETWORK;
55
- const o: Payment = { name: 'p2pkh', network };
56
-
57
- lazy.prop(o, 'address', () => {
58
- if (!o.hash) return;
59
-
60
- const payload = Buffer.allocUnsafe(21);
61
- payload.writeUInt8(network.pubKeyHash, 0);
62
- o.hash.copy(payload, 1);
63
- return bs58check.default.encode(payload);
64
- });
65
-
66
- lazy.prop(o, 'hash', () => {
67
- if (a.output) return a.output.slice(3, 23);
68
- if (a.address) return _address().hash;
69
- if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey! || o.pubkey!);
70
- });
71
-
72
- lazy.prop(o, 'output', () => {
73
- if (!o.hash) return;
74
- return bscript.compile([
75
- OPS.OP_DUP,
76
- OPS.OP_HASH160,
77
- o.hash,
78
- OPS.OP_EQUALVERIFY,
79
- OPS.OP_CHECKSIG,
80
- ]);
81
- });
82
-
83
- lazy.prop(o, 'pubkey', () => {
84
- if (!a.input) return;
85
- return _chunks()[1] as Buffer;
86
- });
87
-
88
- lazy.prop(o, 'signature', () => {
89
- if (!a.input) return;
90
- return _chunks()[0] as Buffer;
91
- });
92
-
93
- lazy.prop(o, 'input', () => {
94
- if (!a.pubkey) return;
95
- if (!a.signature) return;
96
-
97
- let pubKey: Buffer = a.pubkey;
98
- if (a.useHybrid || a.useUncompressed) {
99
- const decompressed = decompressPublicKey(a.pubkey);
100
- if (a.useUncompressed) {
101
- pubKey = decompressed.uncompressed;
102
- } else {
103
- pubKey = decompressed.hybrid;
104
- }
105
- }
106
-
107
- return bscript.compile([a.signature, pubKey]);
108
- });
109
-
110
- lazy.prop(o, 'witness', () => {
111
- if (!o.input) return;
112
- return [];
113
- });
114
-
115
- // extended validation
116
- if (opts.validate) {
117
- let hash: Buffer = Buffer.from([]);
118
- if (a.address) {
119
- if (_address().version !== network.pubKeyHash) {
120
- throw new TypeError('Invalid version or Network mismatch');
121
- }
122
-
123
- if (_address().hash.length !== 20) {
124
- throw new TypeError('Invalid address');
125
- }
126
-
127
- hash = _address().hash;
128
- }
129
-
130
- if (a.hash) {
131
- if (hash.length > 0 && !hash.equals(a.hash)) {
132
- throw new TypeError('Hash mismatch');
133
- } else {
134
- hash = a.hash;
135
- }
136
- }
137
-
138
- if (a.output) {
139
- if (
140
- a.output.length !== 25 ||
141
- a.output[0] !== OPS.OP_DUP ||
142
- a.output[1] !== OPS.OP_HASH160 ||
143
- a.output[2] !== 0x14 ||
144
- a.output[23] !== OPS.OP_EQUALVERIFY ||
145
- a.output[24] !== OPS.OP_CHECKSIG
146
- ) {
147
- throw new TypeError('Output is invalid');
148
- }
149
-
150
- const hash2 = a.output.slice(3, 23);
151
- if (hash.length > 0 && !hash.equals(hash2)) throw new TypeError('Hash mismatch');
152
- else hash = hash2;
153
- }
154
-
155
- if (a.pubkey) {
156
- const pkh = bcrypto.hash160(a.pubkey);
157
-
158
- let badHash = hash.length > 0 && !hash.equals(pkh);
159
- if (badHash) {
160
- if (
161
- (a.pubkey.length === 33 && (a.pubkey[0] === 0x02 || a.pubkey[0] === 0x03)) ||
162
- (a.pubkey.length === 65 && a.pubkey[0] === 0x04)
163
- ) {
164
- const uncompressed = decompressPublicKey(a.pubkey);
165
- const pkh2 = bcrypto.hash160(uncompressed.uncompressed);
166
-
167
- if (!hash.equals(pkh2)) {
168
- const pkh3 = bcrypto.hash160(uncompressed.hybrid);
169
- badHash = !hash.equals(pkh3);
170
-
171
- if (!badHash) {
172
- a.useHybrid = true;
173
- }
174
- } else {
175
- badHash = false;
176
- a.useUncompressed = true;
177
- }
178
- }
179
- }
180
-
181
- if (badHash) {
182
- throw new TypeError('Hash mismatch');
183
- } else {
184
- hash = pkh;
185
- }
186
- }
187
-
188
- if (a.input) {
189
- const chunks = _chunks();
190
- if (chunks.length !== 2) throw new TypeError('Input is invalid');
191
- if (!bscript.isCanonicalScriptSignature(chunks[0] as Buffer))
192
- throw new TypeError('Input has invalid signature');
193
- if (!isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey');
194
-
195
- if (a.signature && !a.signature.equals(chunks[0] as Buffer))
196
- throw new TypeError('Signature mismatch');
197
- if (a.pubkey && !a.pubkey.equals(chunks[1] as Buffer))
198
- throw new TypeError('Pubkey mismatch');
199
-
200
- const pkh = bcrypto.hash160(chunks[1] as Buffer);
201
- if (hash.length > 0 && !hash.equals(pkh)) throw new TypeError('Hash mismatch (input)');
202
- }
203
- }
204
-
205
- return Object.assign(o, a);
206
- }
1
+ import * as bs58check from 'bs58check';
2
+ import * as bcrypto from '../crypto.js';
3
+ import { bitcoin as BITCOIN_NETWORK } from '../networks.js';
4
+ import * as bscript from '../script.js';
5
+ import { isPoint, typeforce as typef } from '../types.js';
6
+ import { Payment, PaymentOpts, StackFunction } from './index.js';
7
+ import * as lazy from './lazy.js';
8
+ import { decompressPublicKey } from '../psbt/psbtutils.js';
9
+
10
+ const OPS = bscript.OPS;
11
+
12
+ // input: {signature} {pubkey}
13
+ // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG
14
+ /**
15
+ * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object.
16
+ *
17
+ * @param a - The payment object containing the necessary data.
18
+ * @param opts - Optional payment options.
19
+ * @returns The P2PKH payment object.
20
+ * @throws {TypeError} If the required data is not provided or if the data is invalid.
21
+ */
22
+ export function p2pkh(a: Payment, opts?: PaymentOpts): Payment {
23
+ if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) {
24
+ throw new TypeError('Not enough data');
25
+ }
26
+
27
+ opts = Object.assign({ validate: true }, opts || {});
28
+
29
+ typef(
30
+ {
31
+ network: typef.maybe(typef.Object),
32
+ address: typef.maybe(typef.String),
33
+ hash: typef.maybe(typef.BufferN(20)),
34
+ output: typef.maybe(typef.BufferN(25)),
35
+
36
+ pubkey: typef.maybe(isPoint),
37
+ signature: typef.maybe(bscript.isCanonicalScriptSignature),
38
+ input: typef.maybe(typef.Buffer),
39
+ },
40
+ a,
41
+ );
42
+
43
+ const _address = lazy.value(() => {
44
+ const payload = Buffer.from(bs58check.default.decode(a.address!));
45
+ const version = payload.readUInt8(0);
46
+ const hash = payload.slice(1);
47
+ return { version, hash };
48
+ });
49
+
50
+ const _chunks = lazy.value(() => {
51
+ return bscript.decompile(a.input!);
52
+ }) as StackFunction;
53
+
54
+ const network = a.network || BITCOIN_NETWORK;
55
+ const o: Payment = { name: 'p2pkh', network };
56
+
57
+ lazy.prop(o, 'address', () => {
58
+ if (!o.hash) return;
59
+
60
+ const payload = Buffer.allocUnsafe(21);
61
+ payload.writeUInt8(network.pubKeyHash, 0);
62
+ o.hash.copy(payload, 1);
63
+ return bs58check.default.encode(payload);
64
+ });
65
+
66
+ lazy.prop(o, 'hash', () => {
67
+ if (a.output) return a.output.slice(3, 23);
68
+ if (a.address) return _address().hash;
69
+ if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey! || o.pubkey!);
70
+ });
71
+
72
+ lazy.prop(o, 'output', () => {
73
+ if (!o.hash) return;
74
+ return bscript.compile([
75
+ OPS.OP_DUP,
76
+ OPS.OP_HASH160,
77
+ o.hash,
78
+ OPS.OP_EQUALVERIFY,
79
+ OPS.OP_CHECKSIG,
80
+ ]);
81
+ });
82
+
83
+ lazy.prop(o, 'pubkey', () => {
84
+ if (!a.input) return;
85
+ return _chunks()[1] as Buffer;
86
+ });
87
+
88
+ lazy.prop(o, 'signature', () => {
89
+ if (!a.input) return;
90
+ return _chunks()[0] as Buffer;
91
+ });
92
+
93
+ lazy.prop(o, 'input', () => {
94
+ if (!a.pubkey) return;
95
+ if (!a.signature) return;
96
+
97
+ let pubKey: Buffer = a.pubkey;
98
+ if (a.useHybrid || a.useUncompressed) {
99
+ const decompressed = decompressPublicKey(a.pubkey);
100
+ if (decompressed) {
101
+ if (a.useUncompressed) {
102
+ pubKey = decompressed.uncompressed;
103
+ } else {
104
+ pubKey = decompressed.hybrid;
105
+ }
106
+ }
107
+ }
108
+
109
+ return bscript.compile([a.signature, pubKey]);
110
+ });
111
+
112
+ lazy.prop(o, 'witness', () => {
113
+ if (!o.input) return;
114
+ return [];
115
+ });
116
+
117
+ // extended validation
118
+ if (opts.validate) {
119
+ let hash: Buffer = Buffer.from([]);
120
+ if (a.address) {
121
+ if (_address().version !== network.pubKeyHash) {
122
+ throw new TypeError('Invalid version or Network mismatch');
123
+ }
124
+
125
+ if (_address().hash.length !== 20) {
126
+ throw new TypeError('Invalid address');
127
+ }
128
+
129
+ hash = _address().hash;
130
+ }
131
+
132
+ if (a.hash) {
133
+ if (hash.length > 0 && !hash.equals(a.hash)) {
134
+ throw new TypeError('Hash mismatch');
135
+ } else {
136
+ hash = a.hash;
137
+ }
138
+ }
139
+
140
+ if (a.output) {
141
+ if (
142
+ a.output.length !== 25 ||
143
+ a.output[0] !== OPS.OP_DUP ||
144
+ a.output[1] !== OPS.OP_HASH160 ||
145
+ a.output[2] !== 0x14 ||
146
+ a.output[23] !== OPS.OP_EQUALVERIFY ||
147
+ a.output[24] !== OPS.OP_CHECKSIG
148
+ ) {
149
+ throw new TypeError('Output is invalid');
150
+ }
151
+
152
+ const hash2 = a.output.slice(3, 23);
153
+ if (hash.length > 0 && !hash.equals(hash2)) throw new TypeError('Hash mismatch');
154
+ else hash = hash2;
155
+ }
156
+
157
+ if (a.pubkey) {
158
+ const pkh = bcrypto.hash160(a.pubkey);
159
+
160
+ let badHash = hash.length > 0 && !hash.equals(pkh);
161
+ if (badHash) {
162
+ if (
163
+ (a.pubkey.length === 33 && (a.pubkey[0] === 0x02 || a.pubkey[0] === 0x03)) ||
164
+ (a.pubkey.length === 65 && a.pubkey[0] === 0x04)
165
+ ) {
166
+ const uncompressed = decompressPublicKey(a.pubkey);
167
+ if (uncompressed) {
168
+ const pkh2 = bcrypto.hash160(uncompressed.uncompressed);
169
+
170
+ if (!hash.equals(pkh2)) {
171
+ const pkh3 = bcrypto.hash160(uncompressed.hybrid);
172
+ badHash = !hash.equals(pkh3);
173
+
174
+ if (!badHash) {
175
+ a.useHybrid = true;
176
+ }
177
+ } else {
178
+ badHash = false;
179
+ a.useUncompressed = true;
180
+ }
181
+ }
182
+ }
183
+ }
184
+
185
+ if (badHash) {
186
+ throw new TypeError('Hash mismatch');
187
+ } else {
188
+ hash = pkh;
189
+ }
190
+ }
191
+
192
+ if (a.input) {
193
+ const chunks = _chunks();
194
+ if (chunks.length !== 2) throw new TypeError('Input is invalid');
195
+ if (!bscript.isCanonicalScriptSignature(chunks[0] as Buffer))
196
+ throw new TypeError('Input has invalid signature');
197
+ if (!isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey');
198
+
199
+ if (a.signature && !a.signature.equals(chunks[0] as Buffer))
200
+ throw new TypeError('Signature mismatch');
201
+ if (a.pubkey && !a.pubkey.equals(chunks[1] as Buffer))
202
+ throw new TypeError('Pubkey mismatch');
203
+
204
+ const pkh = bcrypto.hash160(chunks[1] as Buffer);
205
+ if (hash.length > 0 && !hash.equals(pkh)) throw new TypeError('Hash mismatch (input)');
206
+ }
207
+ }
208
+
209
+ return Object.assign(o, a);
210
+ }
@@ -1,301 +1,315 @@
1
- import { ProjectivePoint } from '@noble/secp256k1';
2
- import * as varuint from 'bip174/src/lib/converter/varint.js';
3
- import { PartialSig, PsbtInput } from 'bip174/src/lib/interfaces.js';
4
- import { hash160 } from '../crypto.js';
5
- import { p2ms } from '../payments/p2ms.js';
6
- import { p2pk } from '../payments/p2pk.js';
7
- import { p2pkh } from '../payments/p2pkh.js';
8
- import { p2sh } from '../payments/p2sh.js';
9
- import { p2tr } from '../payments/p2tr.js';
10
- import { p2wpkh } from '../payments/p2wpkh.js';
11
- import { p2wsh } from '../payments/p2wsh.js';
12
- import * as bscript from '../script.js';
13
- import { Transaction } from '../transaction.js';
14
- import { toXOnly } from './bip371.js';
15
-
16
- function isPaymentFactory(payment: any): (script: Buffer) => boolean {
17
- return (script: Buffer): boolean => {
18
- try {
19
- payment({ output: script });
20
- return true;
21
- } catch (err) {
22
- return false;
23
- }
24
- };
25
- }
26
-
27
- export const isP2MS = isPaymentFactory(p2ms);
28
- export const isP2PK = isPaymentFactory(p2pk);
29
- export const isP2PKH = isPaymentFactory(p2pkh);
30
- export const isP2WPKH = isPaymentFactory(p2wpkh);
31
- export const isP2WSHScript = isPaymentFactory(p2wsh);
32
- export const isP2SHScript = isPaymentFactory(p2sh);
33
- export const isP2TR = isPaymentFactory(p2tr);
34
-
35
- /**
36
- * Converts a witness stack to a script witness.
37
- * @param witness The witness stack to convert.
38
- * @returns The script witness as a Buffer.
39
- */
40
- /**
41
- * Converts a witness stack to a script witness.
42
- * @param witness The witness stack to convert.
43
- * @returns The converted script witness.
44
- */
45
- export function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
46
- let buffer = Buffer.allocUnsafe(0);
47
-
48
- function writeSlice(slice: Buffer): void {
49
- buffer = Buffer.concat([buffer, Buffer.from(slice)]);
50
- }
51
-
52
- function writeVarInt(i: number): void {
53
- const currentLen = buffer.length;
54
- const varintLen = varuint.encodingLength(i);
55
-
56
- buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
57
- varuint.encode(i, buffer, currentLen);
58
- }
59
-
60
- function writeVarSlice(slice: Buffer): void {
61
- writeVarInt(slice.length);
62
- writeSlice(slice);
63
- }
64
-
65
- function writeVector(vector: Buffer[]): void {
66
- writeVarInt(vector.length);
67
- vector.forEach(writeVarSlice);
68
- }
69
-
70
- writeVector(witness);
71
-
72
- return buffer;
73
- }
74
-
75
- export interface UncompressedPublicKey {
76
- hybrid: Buffer;
77
- uncompressed: Buffer;
78
- }
79
-
80
- /**
81
- * Converts an existing real Bitcoin public key (compressed or uncompressed)
82
- * to its "hybrid" form (prefix 0x06/0x07), then derives a P2PKH address from it.
83
- *
84
- * @param realPubKey - 33-byte compressed (0x02/0x03) or 65-byte uncompressed (0x04) pubkey
85
- * @returns Buffer
86
- */
87
- export function decompressPublicKey(realPubKey: Uint8Array | Buffer): UncompressedPublicKey {
88
- if (![33, 65].includes(realPubKey.length)) {
89
- throw new Error(
90
- `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
91
- );
92
- }
93
-
94
- // 1) Parse the public key to get an actual Point on secp256k1
95
- // If it fails, the pubkey is invalid/corrupted.
96
- let point: ProjectivePoint;
97
- try {
98
- point = ProjectivePoint.fromHex(realPubKey);
99
- } catch (err) {
100
- throw new Error('Invalid secp256k1 public key bytes. Cannot parse.');
101
- }
102
-
103
- // 2) Extract X and Y as 32-byte big-endian buffers
104
- const xBuf = bigIntTo32Bytes(point.x);
105
- const yBuf = bigIntTo32Bytes(point.y);
106
-
107
- // 3) Determine if Y is even or odd. That decides the hybrid prefix:
108
- // - 0x06 => "uncompressed + even Y"
109
- // - 0x07 => "uncompressed + odd Y"
110
- const isEven = point.y % 2n === 0n;
111
- const prefix = isEven ? 0x06 : 0x07;
112
-
113
- // 4) Construct 65-byte hybrid pubkey
114
- // [prefix(1) || X(32) || Y(32)]
115
- const hybridPubKey = Buffer.alloc(65);
116
- hybridPubKey[0] = prefix;
117
- xBuf.copy(hybridPubKey, 1);
118
- yBuf.copy(hybridPubKey, 33);
119
-
120
- const uncompressedPubKey = Buffer.concat([Buffer.from([0x04]), xBuf, yBuf]);
121
-
122
- return {
123
- hybrid: hybridPubKey,
124
- uncompressed: uncompressedPubKey,
125
- };
126
- }
127
-
128
- /****************************************
129
- * Convert bigint -> 32-byte Buffer
130
- ****************************************/
131
- export function bigIntTo32Bytes(num: bigint): Buffer {
132
- let hex = num.toString(16);
133
- // Pad to 64 hex chars => 32 bytes
134
- hex = hex.padStart(64, '0');
135
- // In case it's bigger than 64 chars, slice the rightmost 64 (mod 2^256)
136
- if (hex.length > 64) {
137
- hex = hex.slice(-64);
138
- }
139
- return Buffer.from(hex, 'hex');
140
- }
141
-
142
- /**
143
- * Compare two potential pubkey Buffers, treating hybrid keys (0x06/0x07)
144
- * as equivalent to uncompressed (0x04).
145
- */
146
- export function pubkeysMatch(a: Buffer, b: Buffer): boolean {
147
- // If they’re literally the same bytes, no further check needed
148
- if (a.equals(b)) return true;
149
-
150
- // If both are 65 bytes, see if one is hybrid and the other is uncompressed
151
- if (a.length === 65 && b.length === 65) {
152
- const aCopy = Buffer.from(a);
153
- const bCopy = Buffer.from(b);
154
-
155
- // Convert 0x06/0x07 to 0x04
156
- if (aCopy[0] === 0x06 || aCopy[0] === 0x07) aCopy[0] = 0x04;
157
- if (bCopy[0] === 0x06 || bCopy[0] === 0x07) bCopy[0] = 0x04;
158
-
159
- return aCopy.equals(bCopy);
160
- }
161
-
162
- return false;
163
- }
164
-
165
- /**
166
- * Finds the position of a public key in a script.
167
- * @param pubkey The public key to search for.
168
- * @param script The script to search in.
169
- * @returns The index of the public key in the script, or -1 if not found.
170
- * @throws {Error} If there is an unknown script error.
171
- */
172
- export function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number {
173
- const decompiled = bscript.decompile(script);
174
- if (decompiled === null) throw new Error('Unknown script error');
175
-
176
- // For P2PKH or P2PK
177
- const pubkeyHash = hash160(pubkey);
178
-
179
- // For Taproot or some cases, we might also check the x-only
180
- const pubkeyXOnly = toXOnly(pubkey);
181
- const uncompressed = decompressPublicKey(pubkey);
182
- const pubkeyHybridHash = hash160(uncompressed.hybrid);
183
- const pubkeyUncompressedHash = hash160(uncompressed.uncompressed);
184
-
185
- return decompiled.findIndex((element) => {
186
- if (typeof element === 'number') return false;
187
-
188
- if (pubkeysMatch(element, pubkey)) return true;
189
-
190
- if (pubkeysMatch(element, pubkeyXOnly)) return true;
191
-
192
- if (element.equals(pubkeyHash)) {
193
- return true;
194
- }
195
-
196
- if (pubkeysMatch(element, uncompressed.uncompressed)) return true;
197
-
198
- if (pubkeysMatch(element, uncompressed.hybrid)) return true;
199
-
200
- if (element.equals(pubkeyHybridHash) || element.equals(pubkeyUncompressedHash)) {
201
- return true;
202
- }
203
- });
204
- }
205
-
206
- /**
207
- * Checks if a public key is present in a script.
208
- * @param pubkey The public key to check.
209
- * @param script The script to search in.
210
- * @returns A boolean indicating whether the public key is present in the script.
211
- */
212
- export function pubkeyInScript(pubkey: Buffer, script: Buffer): boolean {
213
- return pubkeyPositionInScript(pubkey, script) !== -1;
214
- }
215
-
216
- /**
217
- * Checks if an input contains a signature for a specific action.
218
- * @param input - The input to check.
219
- * @param action - The action to check for.
220
- * @returns A boolean indicating whether the input contains a signature for the specified action.
221
- */
222
- export function checkInputForSig(input: PsbtInput, action: string): boolean {
223
- const pSigs = extractPartialSigs(input);
224
- return pSigs.some((pSig) => signatureBlocksAction(pSig, bscript.signature.decode, action));
225
- }
226
-
227
- type SignatureDecodeFunc = (buffer: Buffer) => {
228
- signature: Buffer;
229
- hashType: number;
230
- };
231
-
232
- /**
233
- * Determines if a given action is allowed for a signature block.
234
- * @param signature - The signature block.
235
- * @param signatureDecodeFn - The function used to decode the signature.
236
- * @param action - The action to be checked.
237
- * @returns True if the action is allowed, false otherwise.
238
- */
239
- export function signatureBlocksAction(
240
- signature: Buffer,
241
- signatureDecodeFn: SignatureDecodeFunc,
242
- action: string,
243
- ): boolean {
244
- const { hashType } = signatureDecodeFn(signature);
245
- const whitelist: string[] = [];
246
- const isAnyoneCanPay = hashType & Transaction.SIGHASH_ANYONECANPAY;
247
- if (isAnyoneCanPay) whitelist.push('addInput');
248
- const hashMod = hashType & 0x1f;
249
- switch (hashMod) {
250
- case Transaction.SIGHASH_ALL:
251
- break;
252
- case Transaction.SIGHASH_SINGLE:
253
- case Transaction.SIGHASH_NONE:
254
- whitelist.push('addOutput');
255
- whitelist.push('setInputSequence');
256
- break;
257
- }
258
- return whitelist.indexOf(action) === -1;
259
- }
260
-
261
- /**
262
- * Extracts the signatures from a PsbtInput object.
263
- * If the input has partial signatures, it returns an array of the signatures.
264
- * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness.
265
- * If it does, it extracts the signatures from the final scripts and returns them.
266
- * If none of the above conditions are met, it returns an empty array.
267
- *
268
- * @param input - The PsbtInput object from which to extract the signatures.
269
- * @returns An array of signatures extracted from the PsbtInput object.
270
- */
271
- function extractPartialSigs(input: PsbtInput): Buffer[] {
272
- let pSigs: PartialSig[] = [];
273
- if ((input.partialSig || []).length === 0) {
274
- if (!input.finalScriptSig && !input.finalScriptWitness) return [];
275
- pSigs = getPsigsFromInputFinalScripts(input);
276
- } else {
277
- pSigs = input.partialSig!;
278
- }
279
- return pSigs.map((p) => p.signature);
280
- }
281
-
282
- /**
283
- * Retrieves the partial signatures (Psigs) from the input's final scripts.
284
- * Psigs are extracted from both the final scriptSig and final scriptWitness of the input.
285
- * Only canonical script signatures are considered.
286
- *
287
- * @param input - The PsbtInput object representing the input.
288
- * @returns An array of PartialSig objects containing the extracted Psigs.
289
- */
290
- export function getPsigsFromInputFinalScripts(input: PsbtInput): PartialSig[] {
291
- const scriptItems = !input.finalScriptSig ? [] : bscript.decompile(input.finalScriptSig) || [];
292
- const witnessItems = !input.finalScriptWitness
293
- ? []
294
- : bscript.decompile(input.finalScriptWitness) || [];
295
- return scriptItems
296
- .concat(witnessItems)
297
- .filter((item) => {
298
- return Buffer.isBuffer(item) && bscript.isCanonicalScriptSignature(item);
299
- })
300
- .map((sig) => ({ signature: sig })) as PartialSig[];
301
- }
1
+ import { ProjectivePoint } from '@noble/secp256k1';
2
+ import * as varuint from 'bip174/src/lib/converter/varint.js';
3
+ import { PartialSig, PsbtInput } from 'bip174/src/lib/interfaces.js';
4
+ import { hash160 } from '../crypto.js';
5
+ import { p2ms } from '../payments/p2ms.js';
6
+ import { p2pk } from '../payments/p2pk.js';
7
+ import { p2pkh } from '../payments/p2pkh.js';
8
+ import { p2sh } from '../payments/p2sh.js';
9
+ import { p2tr } from '../payments/p2tr.js';
10
+ import { p2wpkh } from '../payments/p2wpkh.js';
11
+ import { p2wsh } from '../payments/p2wsh.js';
12
+ import * as bscript from '../script.js';
13
+ import { Transaction } from '../transaction.js';
14
+ import { toXOnly } from './bip371.js';
15
+
16
+ function isPaymentFactory(payment: any): (script: Buffer) => boolean {
17
+ return (script: Buffer): boolean => {
18
+ try {
19
+ payment({ output: script });
20
+ return true;
21
+ } catch (err) {
22
+ return false;
23
+ }
24
+ };
25
+ }
26
+
27
+ export const isP2MS = isPaymentFactory(p2ms);
28
+ export const isP2PK = isPaymentFactory(p2pk);
29
+ export const isP2PKH = isPaymentFactory(p2pkh);
30
+ export const isP2WPKH = isPaymentFactory(p2wpkh);
31
+ export const isP2WSHScript = isPaymentFactory(p2wsh);
32
+ export const isP2SHScript = isPaymentFactory(p2sh);
33
+ export const isP2TR = isPaymentFactory(p2tr);
34
+
35
+ /**
36
+ * Converts a witness stack to a script witness.
37
+ * @param witness The witness stack to convert.
38
+ * @returns The script witness as a Buffer.
39
+ */
40
+ /**
41
+ * Converts a witness stack to a script witness.
42
+ * @param witness The witness stack to convert.
43
+ * @returns The converted script witness.
44
+ */
45
+ export function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
46
+ let buffer = Buffer.allocUnsafe(0);
47
+
48
+ function writeSlice(slice: Buffer): void {
49
+ buffer = Buffer.concat([buffer, Buffer.from(slice)]);
50
+ }
51
+
52
+ function writeVarInt(i: number): void {
53
+ const currentLen = buffer.length;
54
+ const varintLen = varuint.encodingLength(i);
55
+
56
+ buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
57
+ varuint.encode(i, buffer, currentLen);
58
+ }
59
+
60
+ function writeVarSlice(slice: Buffer): void {
61
+ writeVarInt(slice.length);
62
+ writeSlice(slice);
63
+ }
64
+
65
+ function writeVector(vector: Buffer[]): void {
66
+ writeVarInt(vector.length);
67
+ vector.forEach(writeVarSlice);
68
+ }
69
+
70
+ writeVector(witness);
71
+
72
+ return buffer;
73
+ }
74
+
75
+ export interface UncompressedPublicKey {
76
+ hybrid: Buffer;
77
+ uncompressed: Buffer;
78
+ }
79
+
80
+ /**
81
+ * Converts an existing real Bitcoin public key (compressed or uncompressed)
82
+ * to its "hybrid" form (prefix 0x06/0x07), then derives a P2PKH address from it.
83
+ *
84
+ * @param realPubKey - 33-byte compressed (0x02/0x03) or 65-byte uncompressed (0x04) pubkey
85
+ * @returns Buffer | undefined
86
+ */
87
+ export function decompressPublicKey(
88
+ realPubKey: Uint8Array | Buffer,
89
+ ): UncompressedPublicKey | undefined {
90
+ if (realPubKey.length === 32) {
91
+ return;
92
+ }
93
+
94
+ if (![33, 65].includes(realPubKey.length)) {
95
+ throw new Error(
96
+ `Unsupported key length=${realPubKey.length}. Must be 33 (compressed) or 65 (uncompressed).`,
97
+ );
98
+ }
99
+
100
+ // 1) Parse the public key to get an actual Point on secp256k1
101
+ // If it fails, the pubkey is invalid/corrupted.
102
+ let point: ProjectivePoint;
103
+ try {
104
+ point = ProjectivePoint.fromHex(realPubKey);
105
+ } catch (err) {
106
+ throw new Error('Invalid secp256k1 public key bytes. Cannot parse.');
107
+ }
108
+
109
+ // 2) Extract X and Y as 32-byte big-endian buffers
110
+ const xBuf = bigIntTo32Bytes(point.x);
111
+ const yBuf = bigIntTo32Bytes(point.y);
112
+
113
+ // 3) Determine if Y is even or odd. That decides the hybrid prefix:
114
+ // - 0x06 => "uncompressed + even Y"
115
+ // - 0x07 => "uncompressed + odd Y"
116
+ const isEven = point.y % 2n === 0n;
117
+ const prefix = isEven ? 0x06 : 0x07;
118
+
119
+ // 4) Construct 65-byte hybrid pubkey
120
+ // [prefix(1) || X(32) || Y(32)]
121
+ const hybridPubKey = Buffer.alloc(65);
122
+ hybridPubKey[0] = prefix;
123
+ xBuf.copy(hybridPubKey, 1);
124
+ yBuf.copy(hybridPubKey, 33);
125
+
126
+ const uncompressedPubKey = Buffer.concat([Buffer.from([0x04]), xBuf, yBuf]);
127
+
128
+ return {
129
+ hybrid: hybridPubKey,
130
+ uncompressed: uncompressedPubKey,
131
+ };
132
+ }
133
+
134
+ /****************************************
135
+ * Convert bigint -> 32-byte Buffer
136
+ ****************************************/
137
+ export function bigIntTo32Bytes(num: bigint): Buffer {
138
+ let hex = num.toString(16);
139
+ // Pad to 64 hex chars => 32 bytes
140
+ hex = hex.padStart(64, '0');
141
+ // In case it's bigger than 64 chars, slice the rightmost 64 (mod 2^256)
142
+ if (hex.length > 64) {
143
+ hex = hex.slice(-64);
144
+ }
145
+ return Buffer.from(hex, 'hex');
146
+ }
147
+
148
+ /**
149
+ * Compare two potential pubkey Buffers, treating hybrid keys (0x06/0x07)
150
+ * as equivalent to uncompressed (0x04).
151
+ */
152
+ export function pubkeysMatch(a: Buffer, b: Buffer): boolean {
153
+ // If they’re literally the same bytes, no further check needed
154
+ if (a.equals(b)) return true;
155
+
156
+ // If both are 65 bytes, see if one is hybrid and the other is uncompressed
157
+ if (a.length === 65 && b.length === 65) {
158
+ const aCopy = Buffer.from(a);
159
+ const bCopy = Buffer.from(b);
160
+
161
+ // Convert 0x06/0x07 to 0x04
162
+ if (aCopy[0] === 0x06 || aCopy[0] === 0x07) aCopy[0] = 0x04;
163
+ if (bCopy[0] === 0x06 || bCopy[0] === 0x07) bCopy[0] = 0x04;
164
+
165
+ return aCopy.equals(bCopy);
166
+ }
167
+
168
+ return false;
169
+ }
170
+
171
+ /**
172
+ * Finds the position of a public key in a script.
173
+ * @param pubkey The public key to search for.
174
+ * @param script The script to search in.
175
+ * @returns The index of the public key in the script, or -1 if not found.
176
+ * @throws {Error} If there is an unknown script error.
177
+ */
178
+ export function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number {
179
+ const decompiled = bscript.decompile(script);
180
+ if (decompiled === null) throw new Error('Unknown script error');
181
+
182
+ // For P2PKH or P2PK
183
+ const pubkeyHash = hash160(pubkey);
184
+
185
+ // For Taproot or some cases, we might also check the x-only
186
+ const pubkeyXOnly = toXOnly(pubkey);
187
+ const uncompressed = decompressPublicKey(pubkey);
188
+
189
+ const pubkeyHybridHash = uncompressed?.hybrid ? hash160(uncompressed.hybrid) : undefined;
190
+ const pubkeyUncompressedHash = uncompressed?.uncompressed
191
+ ? hash160(uncompressed.uncompressed)
192
+ : undefined;
193
+
194
+ return decompiled.findIndex((element) => {
195
+ if (typeof element === 'number') return false;
196
+
197
+ if (pubkeysMatch(element, pubkey)) return true;
198
+
199
+ if (pubkeysMatch(element, pubkeyXOnly)) return true;
200
+
201
+ if (element.equals(pubkeyHash)) {
202
+ return true;
203
+ }
204
+
205
+ if (uncompressed) {
206
+ if (pubkeysMatch(element, uncompressed.uncompressed)) return true;
207
+
208
+ if (pubkeysMatch(element, uncompressed.hybrid)) return true;
209
+
210
+ if (
211
+ (pubkeyHybridHash && element.equals(pubkeyHybridHash)) ||
212
+ (pubkeyUncompressedHash && element.equals(pubkeyUncompressedHash))
213
+ ) {
214
+ return true;
215
+ }
216
+ }
217
+ });
218
+ }
219
+
220
+ /**
221
+ * Checks if a public key is present in a script.
222
+ * @param pubkey The public key to check.
223
+ * @param script The script to search in.
224
+ * @returns A boolean indicating whether the public key is present in the script.
225
+ */
226
+ export function pubkeyInScript(pubkey: Buffer, script: Buffer): boolean {
227
+ return pubkeyPositionInScript(pubkey, script) !== -1;
228
+ }
229
+
230
+ /**
231
+ * Checks if an input contains a signature for a specific action.
232
+ * @param input - The input to check.
233
+ * @param action - The action to check for.
234
+ * @returns A boolean indicating whether the input contains a signature for the specified action.
235
+ */
236
+ export function checkInputForSig(input: PsbtInput, action: string): boolean {
237
+ const pSigs = extractPartialSigs(input);
238
+ return pSigs.some((pSig) => signatureBlocksAction(pSig, bscript.signature.decode, action));
239
+ }
240
+
241
+ type SignatureDecodeFunc = (buffer: Buffer) => {
242
+ signature: Buffer;
243
+ hashType: number;
244
+ };
245
+
246
+ /**
247
+ * Determines if a given action is allowed for a signature block.
248
+ * @param signature - The signature block.
249
+ * @param signatureDecodeFn - The function used to decode the signature.
250
+ * @param action - The action to be checked.
251
+ * @returns True if the action is allowed, false otherwise.
252
+ */
253
+ export function signatureBlocksAction(
254
+ signature: Buffer,
255
+ signatureDecodeFn: SignatureDecodeFunc,
256
+ action: string,
257
+ ): boolean {
258
+ const { hashType } = signatureDecodeFn(signature);
259
+ const whitelist: string[] = [];
260
+ const isAnyoneCanPay = hashType & Transaction.SIGHASH_ANYONECANPAY;
261
+ if (isAnyoneCanPay) whitelist.push('addInput');
262
+ const hashMod = hashType & 0x1f;
263
+ switch (hashMod) {
264
+ case Transaction.SIGHASH_ALL:
265
+ break;
266
+ case Transaction.SIGHASH_SINGLE:
267
+ case Transaction.SIGHASH_NONE:
268
+ whitelist.push('addOutput');
269
+ whitelist.push('setInputSequence');
270
+ break;
271
+ }
272
+ return whitelist.indexOf(action) === -1;
273
+ }
274
+
275
+ /**
276
+ * Extracts the signatures from a PsbtInput object.
277
+ * If the input has partial signatures, it returns an array of the signatures.
278
+ * If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness.
279
+ * If it does, it extracts the signatures from the final scripts and returns them.
280
+ * If none of the above conditions are met, it returns an empty array.
281
+ *
282
+ * @param input - The PsbtInput object from which to extract the signatures.
283
+ * @returns An array of signatures extracted from the PsbtInput object.
284
+ */
285
+ function extractPartialSigs(input: PsbtInput): Buffer[] {
286
+ let pSigs: PartialSig[] = [];
287
+ if ((input.partialSig || []).length === 0) {
288
+ if (!input.finalScriptSig && !input.finalScriptWitness) return [];
289
+ pSigs = getPsigsFromInputFinalScripts(input);
290
+ } else {
291
+ pSigs = input.partialSig!;
292
+ }
293
+ return pSigs.map((p) => p.signature);
294
+ }
295
+
296
+ /**
297
+ * Retrieves the partial signatures (Psigs) from the input's final scripts.
298
+ * Psigs are extracted from both the final scriptSig and final scriptWitness of the input.
299
+ * Only canonical script signatures are considered.
300
+ *
301
+ * @param input - The PsbtInput object representing the input.
302
+ * @returns An array of PartialSig objects containing the extracted Psigs.
303
+ */
304
+ export function getPsigsFromInputFinalScripts(input: PsbtInput): PartialSig[] {
305
+ const scriptItems = !input.finalScriptSig ? [] : bscript.decompile(input.finalScriptSig) || [];
306
+ const witnessItems = !input.finalScriptWitness
307
+ ? []
308
+ : bscript.decompile(input.finalScriptWitness) || [];
309
+ return scriptItems
310
+ .concat(witnessItems)
311
+ .filter((item) => {
312
+ return Buffer.isBuffer(item) && bscript.isCanonicalScriptSignature(item);
313
+ })
314
+ .map((sig) => ({ signature: sig })) as PartialSig[];
315
+ }