bitcoin-main-lib 0.0.1-security → 7.0.1

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

Potentially problematic release.


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

Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +203 -3
  3. package/package.json +111 -3
  4. package/src/cjs/address.cjs +260 -0
  5. package/src/cjs/address.d.ts +72 -0
  6. package/src/cjs/bip66.cjs +115 -0
  7. package/src/cjs/bip66.d.ts +20 -0
  8. package/src/cjs/block.cjs +268 -0
  9. package/src/cjs/block.d.ts +29 -0
  10. package/src/cjs/bufferutils.cjs +207 -0
  11. package/src/cjs/bufferutils.d.ts +44 -0
  12. package/src/cjs/crypto.cjs +197 -0
  13. package/src/cjs/crypto.d.ts +55 -0
  14. package/src/cjs/ecc_lib.cjs +156 -0
  15. package/src/cjs/ecc_lib.d.ts +20 -0
  16. package/src/cjs/index.cjs +110 -0
  17. package/src/cjs/index.d.ts +19 -0
  18. package/src/cjs/merkle.cjs +74 -0
  19. package/src/cjs/merkle.d.ts +9 -0
  20. package/src/cjs/networks.cjs +69 -0
  21. package/src/cjs/networks.d.ts +35 -0
  22. package/src/cjs/ops.cjs +126 -0
  23. package/src/cjs/ops.d.ts +122 -0
  24. package/src/cjs/payments/bip341.cjs +192 -0
  25. package/src/cjs/payments/bip341.d.ts +68 -0
  26. package/src/cjs/payments/embed.cjs +97 -0
  27. package/src/cjs/payments/embed.d.ts +9 -0
  28. package/src/cjs/payments/index.cjs +69 -0
  29. package/src/cjs/payments/index.d.ts +55 -0
  30. package/src/cjs/payments/lazy.cjs +31 -0
  31. package/src/cjs/payments/lazy.d.ts +2 -0
  32. package/src/cjs/payments/p2ms.cjs +220 -0
  33. package/src/cjs/payments/p2ms.d.ts +9 -0
  34. package/src/cjs/payments/p2pk.cjs +130 -0
  35. package/src/cjs/payments/p2pk.d.ts +10 -0
  36. package/src/cjs/payments/p2pkh.cjs +192 -0
  37. package/src/cjs/payments/p2pkh.d.ts +10 -0
  38. package/src/cjs/payments/p2sh.cjs +253 -0
  39. package/src/cjs/payments/p2sh.d.ts +10 -0
  40. package/src/cjs/payments/p2tr.cjs +348 -0
  41. package/src/cjs/payments/p2tr.d.ts +10 -0
  42. package/src/cjs/payments/p2wpkh.cjs +186 -0
  43. package/src/cjs/payments/p2wpkh.d.ts +10 -0
  44. package/src/cjs/payments/p2wsh.cjs +269 -0
  45. package/src/cjs/payments/p2wsh.d.ts +10 -0
  46. package/src/cjs/psbt/bip371.cjs +556 -0
  47. package/src/cjs/psbt/bip371.d.ts +89 -0
  48. package/src/cjs/psbt/psbtutils.cjs +228 -0
  49. package/src/cjs/psbt/psbtutils.d.ts +49 -0
  50. package/src/cjs/psbt.cjs +1856 -0
  51. package/src/cjs/psbt.d.ts +206 -0
  52. package/src/cjs/push_data.cjs +133 -0
  53. package/src/cjs/push_data.d.ts +28 -0
  54. package/src/cjs/script.cjs +339 -0
  55. package/src/cjs/script.d.ts +89 -0
  56. package/src/cjs/script_number.cjs +122 -0
  57. package/src/cjs/script_number.d.ts +18 -0
  58. package/src/cjs/script_signature.cjs +123 -0
  59. package/src/cjs/script_signature.d.ts +20 -0
  60. package/src/cjs/transaction.cjs +607 -0
  61. package/src/cjs/transaction.d.ts +60 -0
  62. package/src/cjs/types.cjs +147 -0
  63. package/src/cjs/types.d.ts +45 -0
  64. package/src/esm/address.js +200 -0
  65. package/src/esm/bip66.js +110 -0
  66. package/src/esm/block.js +225 -0
  67. package/src/esm/bufferutils.js +156 -0
  68. package/src/esm/crypto.js +123 -0
  69. package/src/esm/ecc_lib.js +108 -0
  70. package/src/esm/index.js +12 -0
  71. package/src/esm/merkle.js +27 -0
  72. package/src/esm/networks.js +66 -0
  73. package/src/esm/ops.js +125 -0
  74. package/src/esm/payments/bip341.js +135 -0
  75. package/src/esm/payments/embed.js +50 -0
  76. package/src/esm/payments/index.js +11 -0
  77. package/src/esm/payments/lazy.js +27 -0
  78. package/src/esm/payments/p2ms.js +167 -0
  79. package/src/esm/payments/p2pk.js +82 -0
  80. package/src/esm/payments/p2pkh.js +144 -0
  81. package/src/esm/payments/p2sh.js +201 -0
  82. package/src/esm/payments/p2tr.js +301 -0
  83. package/src/esm/payments/p2wpkh.js +139 -0
  84. package/src/esm/payments/p2wsh.js +228 -0
  85. package/src/esm/psbt/bip371.js +490 -0
  86. package/src/esm/psbt/psbtutils.js +168 -0
  87. package/src/esm/psbt.js +1774 -0
  88. package/src/esm/push_data.js +77 -0
  89. package/src/esm/script.js +277 -0
  90. package/src/esm/script_number.js +74 -0
  91. package/src/esm/script_signature.js +75 -0
  92. package/src/esm/transaction.js +550 -0
  93. package/src/esm/types.js +83 -0
@@ -0,0 +1,144 @@
1
+ import * as bcrypto from '../crypto.js';
2
+ import { bitcoin as BITCOIN_NETWORK } from '../networks.js';
3
+ import * as bscript from '../script.js';
4
+ import {
5
+ isPoint,
6
+ Hash160bitSchema,
7
+ NBufferSchemaFactory,
8
+ BufferSchema,
9
+ } from '../types.js';
10
+ import * as lazy from './lazy.js';
11
+ import bs58check from 'bs58check';
12
+ import * as tools from 'uint8array-tools';
13
+ import * as v from 'valibot';
14
+ const OPS = bscript.OPS;
15
+ // input: {signature} {pubkey}
16
+ // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG
17
+ /**
18
+ * Creates a Pay-to-Public-Key-Hash (P2PKH) payment object.
19
+ *
20
+ * @param a - The payment object containing the necessary data.
21
+ * @param opts - Optional payment options.
22
+ * @returns The P2PKH payment object.
23
+ * @throws {TypeError} If the required data is not provided or if the data is invalid.
24
+ */
25
+ export function p2pkh(a, opts) {
26
+ if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input)
27
+ throw new TypeError('Not enough data');
28
+ opts = Object.assign({ validate: true }, opts || {});
29
+ v.parse(
30
+ v.partial(
31
+ v.object({
32
+ network: v.object({}),
33
+ address: v.string(),
34
+ hash: Hash160bitSchema,
35
+ output: NBufferSchemaFactory(25),
36
+ pubkey: v.custom(isPoint),
37
+ signature: v.custom(bscript.isCanonicalScriptSignature),
38
+ input: BufferSchema,
39
+ }),
40
+ ),
41
+ a,
42
+ );
43
+ const _address = lazy.value(() => {
44
+ const payload = bs58check.decode(a.address);
45
+ const version = tools.readUInt8(payload, 0);
46
+ const hash = payload.slice(1);
47
+ return { version, hash };
48
+ });
49
+ const _chunks = lazy.value(() => {
50
+ return bscript.decompile(a.input);
51
+ });
52
+ const network = a.network || BITCOIN_NETWORK;
53
+ const o = { name: 'p2pkh', network };
54
+ lazy.prop(o, 'address', () => {
55
+ if (!o.hash) return;
56
+ const payload = new Uint8Array(21);
57
+ tools.writeUInt8(payload, 0, network.pubKeyHash);
58
+ payload.set(o.hash, 1);
59
+ return bs58check.encode(payload);
60
+ });
61
+ lazy.prop(o, 'hash', () => {
62
+ if (a.output) return a.output.slice(3, 23);
63
+ if (a.address) return _address().hash;
64
+ if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey);
65
+ });
66
+ lazy.prop(o, 'output', () => {
67
+ if (!o.hash) return;
68
+ return bscript.compile([
69
+ OPS.OP_DUP,
70
+ OPS.OP_HASH160,
71
+ o.hash,
72
+ OPS.OP_EQUALVERIFY,
73
+ OPS.OP_CHECKSIG,
74
+ ]);
75
+ });
76
+ lazy.prop(o, 'pubkey', () => {
77
+ if (!a.input) return;
78
+ return _chunks()[1];
79
+ });
80
+ lazy.prop(o, 'signature', () => {
81
+ if (!a.input) return;
82
+ return _chunks()[0];
83
+ });
84
+ lazy.prop(o, 'input', () => {
85
+ if (!a.pubkey) return;
86
+ if (!a.signature) return;
87
+ return bscript.compile([a.signature, a.pubkey]);
88
+ });
89
+ lazy.prop(o, 'witness', () => {
90
+ if (!o.input) return;
91
+ return [];
92
+ });
93
+ // extended validation
94
+ if (opts.validate) {
95
+ let hash = Uint8Array.from([]);
96
+ if (a.address) {
97
+ if (_address().version !== network.pubKeyHash)
98
+ throw new TypeError('Invalid version or Network mismatch');
99
+ if (_address().hash.length !== 20) throw new TypeError('Invalid address');
100
+ hash = _address().hash;
101
+ }
102
+ if (a.hash) {
103
+ if (hash.length > 0 && tools.compare(hash, a.hash) !== 0)
104
+ throw new TypeError('Hash mismatch');
105
+ else hash = a.hash;
106
+ }
107
+ if (a.output) {
108
+ if (
109
+ a.output.length !== 25 ||
110
+ a.output[0] !== OPS.OP_DUP ||
111
+ a.output[1] !== OPS.OP_HASH160 ||
112
+ a.output[2] !== 0x14 ||
113
+ a.output[23] !== OPS.OP_EQUALVERIFY ||
114
+ a.output[24] !== OPS.OP_CHECKSIG
115
+ )
116
+ throw new TypeError('Output is invalid');
117
+ const hash2 = a.output.slice(3, 23);
118
+ if (hash.length > 0 && tools.compare(hash, hash2) !== 0)
119
+ throw new TypeError('Hash mismatch');
120
+ else hash = hash2;
121
+ }
122
+ if (a.pubkey) {
123
+ const pkh = bcrypto.hash160(a.pubkey);
124
+ if (hash.length > 0 && tools.compare(hash, pkh) !== 0)
125
+ throw new TypeError('Hash mismatch');
126
+ else hash = pkh;
127
+ }
128
+ if (a.input) {
129
+ const chunks = _chunks();
130
+ if (chunks.length !== 2) throw new TypeError('Input is invalid');
131
+ if (!bscript.isCanonicalScriptSignature(chunks[0]))
132
+ throw new TypeError('Input has invalid signature');
133
+ if (!isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey');
134
+ if (a.signature && tools.compare(a.signature, chunks[0]) !== 0)
135
+ throw new TypeError('Signature mismatch');
136
+ if (a.pubkey && tools.compare(a.pubkey, chunks[1]) !== 0)
137
+ throw new TypeError('Pubkey mismatch');
138
+ const pkh = bcrypto.hash160(chunks[1]);
139
+ if (hash.length > 0 && tools.compare(hash, pkh) !== 0)
140
+ throw new TypeError('Hash mismatch');
141
+ }
142
+ }
143
+ return Object.assign(o, a);
144
+ }
@@ -0,0 +1,201 @@
1
+ import * as bcrypto from '../crypto.js';
2
+ import { bitcoin as BITCOIN_NETWORK } from '../networks.js';
3
+ import * as bscript from '../script.js';
4
+ import { BufferSchema, NBufferSchemaFactory, stacksEqual } from '../types.js';
5
+ import * as lazy from './lazy.js';
6
+ import bs58check from 'bs58check';
7
+ import * as tools from 'uint8array-tools';
8
+ import * as v from 'valibot';
9
+ const OPS = bscript.OPS;
10
+ // input: [redeemScriptSig ...] {redeemScript}
11
+ // witness: <?>
12
+ // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL
13
+ /**
14
+ * Creates a Pay-to-Script-Hash (P2SH) payment object.
15
+ *
16
+ * @param a - The payment object containing the necessary data.
17
+ * @param opts - Optional payment options.
18
+ * @returns The P2SH payment object.
19
+ * @throws {TypeError} If the required data is not provided or if the data is invalid.
20
+ */
21
+ export function p2sh(a, opts) {
22
+ if (!a.address && !a.hash && !a.output && !a.redeem && !a.input)
23
+ throw new TypeError('Not enough data');
24
+ opts = Object.assign({ validate: true }, opts || {});
25
+ v.parse(
26
+ v.partial(
27
+ v.object({
28
+ network: v.object({}),
29
+ address: v.string(),
30
+ hash: NBufferSchemaFactory(20),
31
+ output: NBufferSchemaFactory(23),
32
+ redeem: v.partial(
33
+ v.object({
34
+ network: v.object({}),
35
+ output: BufferSchema,
36
+ input: BufferSchema,
37
+ witness: v.array(BufferSchema),
38
+ }),
39
+ ),
40
+ input: BufferSchema,
41
+ witness: v.array(BufferSchema),
42
+ }),
43
+ ),
44
+ a,
45
+ );
46
+ let network = a.network;
47
+ if (!network) {
48
+ network = (a.redeem && a.redeem.network) || BITCOIN_NETWORK;
49
+ }
50
+ const o = { network };
51
+ const _address = lazy.value(() => {
52
+ const payload = bs58check.decode(a.address);
53
+ const version = tools.readUInt8(payload, 0);
54
+ const hash = payload.slice(1);
55
+ return { version, hash };
56
+ });
57
+ const _chunks = lazy.value(() => {
58
+ return bscript.decompile(a.input);
59
+ });
60
+ const _redeem = lazy.value(() => {
61
+ const chunks = _chunks();
62
+ const lastChunk = chunks[chunks.length - 1];
63
+ return {
64
+ network,
65
+ output: lastChunk === OPS.OP_FALSE ? Uint8Array.from([]) : lastChunk,
66
+ input: bscript.compile(chunks.slice(0, -1)),
67
+ witness: a.witness || [],
68
+ };
69
+ });
70
+ // output dependents
71
+ lazy.prop(o, 'address', () => {
72
+ if (!o.hash) return;
73
+ const payload = new Uint8Array(21);
74
+ tools.writeUInt8(payload, 0, o.network.scriptHash);
75
+ payload.set(o.hash, 1);
76
+ return bs58check.encode(payload);
77
+ });
78
+ lazy.prop(o, 'hash', () => {
79
+ // in order of least effort
80
+ if (a.output) return a.output.slice(2, 22);
81
+ if (a.address) return _address().hash;
82
+ if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output);
83
+ });
84
+ lazy.prop(o, 'output', () => {
85
+ if (!o.hash) return;
86
+ return bscript.compile([OPS.OP_HASH160, o.hash, OPS.OP_EQUAL]);
87
+ });
88
+ // input dependents
89
+ lazy.prop(o, 'redeem', () => {
90
+ if (!a.input) return;
91
+ return _redeem();
92
+ });
93
+ lazy.prop(o, 'input', () => {
94
+ if (!a.redeem || !a.redeem.input || !a.redeem.output) return;
95
+ return bscript.compile(
96
+ [].concat(bscript.decompile(a.redeem.input), a.redeem.output),
97
+ );
98
+ });
99
+ lazy.prop(o, 'witness', () => {
100
+ if (o.redeem && o.redeem.witness) return o.redeem.witness;
101
+ if (o.input) return [];
102
+ });
103
+ lazy.prop(o, 'name', () => {
104
+ const nameParts = ['p2sh'];
105
+ if (o.redeem !== undefined && o.redeem.name !== undefined)
106
+ nameParts.push(o.redeem.name);
107
+ return nameParts.join('-');
108
+ });
109
+ if (opts.validate) {
110
+ let hash = Uint8Array.from([]);
111
+ if (a.address) {
112
+ if (_address().version !== network.scriptHash)
113
+ throw new TypeError('Invalid version or Network mismatch');
114
+ if (_address().hash.length !== 20) throw new TypeError('Invalid address');
115
+ hash = _address().hash;
116
+ }
117
+ if (a.hash) {
118
+ if (hash.length > 0 && tools.compare(hash, a.hash) !== 0)
119
+ throw new TypeError('Hash mismatch');
120
+ else hash = a.hash;
121
+ }
122
+ if (a.output) {
123
+ if (
124
+ a.output.length !== 23 ||
125
+ a.output[0] !== OPS.OP_HASH160 ||
126
+ a.output[1] !== 0x14 ||
127
+ a.output[22] !== OPS.OP_EQUAL
128
+ )
129
+ throw new TypeError('Output is invalid');
130
+ const hash2 = a.output.slice(2, 22);
131
+ if (hash.length > 0 && tools.compare(hash, hash2) !== 0)
132
+ throw new TypeError('Hash mismatch');
133
+ else hash = hash2;
134
+ }
135
+ // inlined to prevent 'no-inner-declarations' failing
136
+ const checkRedeem = redeem => {
137
+ // is the redeem output empty/invalid?
138
+ if (redeem.output) {
139
+ const decompile = bscript.decompile(redeem.output);
140
+ if (!decompile || decompile.length < 1)
141
+ throw new TypeError('Redeem.output too short');
142
+ if (redeem.output.byteLength > 520)
143
+ throw new TypeError(
144
+ 'Redeem.output unspendable if larger than 520 bytes',
145
+ );
146
+ if (bscript.countNonPushOnlyOPs(decompile) > 201)
147
+ throw new TypeError(
148
+ 'Redeem.output unspendable with more than 201 non-push ops',
149
+ );
150
+ // match hash against other sources
151
+ const hash2 = bcrypto.hash160(redeem.output);
152
+ if (hash.length > 0 && tools.compare(hash, hash2) !== 0)
153
+ throw new TypeError('Hash mismatch');
154
+ else hash = hash2;
155
+ }
156
+ if (redeem.input) {
157
+ const hasInput = redeem.input.length > 0;
158
+ const hasWitness = redeem.witness && redeem.witness.length > 0;
159
+ if (!hasInput && !hasWitness) throw new TypeError('Empty input');
160
+ if (hasInput && hasWitness)
161
+ throw new TypeError('Input and witness provided');
162
+ if (hasInput) {
163
+ const richunks = bscript.decompile(redeem.input);
164
+ if (!bscript.isPushOnly(richunks))
165
+ throw new TypeError('Non push-only scriptSig');
166
+ }
167
+ }
168
+ };
169
+ if (a.input) {
170
+ const chunks = _chunks();
171
+ if (!chunks || chunks.length < 1) throw new TypeError('Input too short');
172
+ if (!(_redeem().output instanceof Uint8Array))
173
+ throw new TypeError('Input is invalid');
174
+ checkRedeem(_redeem());
175
+ }
176
+ if (a.redeem) {
177
+ if (a.redeem.network && a.redeem.network !== network)
178
+ throw new TypeError('Network mismatch');
179
+ if (a.input) {
180
+ const redeem = _redeem();
181
+ if (
182
+ a.redeem.output &&
183
+ tools.compare(a.redeem.output, redeem.output) !== 0
184
+ )
185
+ throw new TypeError('Redeem.output mismatch');
186
+ if (a.redeem.input && tools.compare(a.redeem.input, redeem.input) !== 0)
187
+ throw new TypeError('Redeem.input mismatch');
188
+ }
189
+ checkRedeem(a.redeem);
190
+ }
191
+ if (a.witness) {
192
+ if (
193
+ a.redeem &&
194
+ a.redeem.witness &&
195
+ !stacksEqual(a.redeem.witness, a.witness)
196
+ )
197
+ throw new TypeError('Witness and redeem.witness mismatch');
198
+ }
199
+ }
200
+ return Object.assign(o, a);
201
+ }
@@ -0,0 +1,301 @@
1
+ import { bitcoin as BITCOIN_NETWORK } from '../networks.js';
2
+ import * as bscript from '../script.js';
3
+ import {
4
+ isTaptree,
5
+ TAPLEAF_VERSION_MASK,
6
+ stacksEqual,
7
+ NBufferSchemaFactory,
8
+ BufferSchema,
9
+ } from '../types.js';
10
+ import { getEccLib } from '../ecc_lib.js';
11
+ import {
12
+ toHashTree,
13
+ rootHashFromPath,
14
+ findScriptPath,
15
+ tapleafHash,
16
+ tweakKey,
17
+ LEAF_VERSION_TAPSCRIPT,
18
+ } from './bip341.js';
19
+ import * as lazy from './lazy.js';
20
+ import { bech32m } from 'bech32';
21
+ import { fromBech32 } from '../address.js';
22
+ import * as tools from 'uint8array-tools';
23
+ import * as v from 'valibot';
24
+ const OPS = bscript.OPS;
25
+ const TAPROOT_WITNESS_VERSION = 0x01;
26
+ const ANNEX_PREFIX = 0x50;
27
+ /**
28
+ * Creates a Pay-to-Taproot (P2TR) payment object.
29
+ *
30
+ * @param a - The payment object containing the necessary data for P2TR.
31
+ * @param opts - Optional payment options.
32
+ * @returns The P2TR payment object.
33
+ * @throws {TypeError} If the provided data is invalid or insufficient.
34
+ */
35
+ export function p2tr(a, opts) {
36
+ if (
37
+ !a.address &&
38
+ !a.output &&
39
+ !a.pubkey &&
40
+ !a.internalPubkey &&
41
+ !(a.witness && a.witness.length > 1)
42
+ )
43
+ throw new TypeError('Not enough data');
44
+ opts = Object.assign({ validate: true }, opts || {});
45
+ v.parse(
46
+ v.partial(
47
+ v.object({
48
+ address: v.string(),
49
+ input: NBufferSchemaFactory(0),
50
+ network: v.object({}),
51
+ output: NBufferSchemaFactory(34),
52
+ internalPubkey: NBufferSchemaFactory(32),
53
+ hash: NBufferSchemaFactory(32), // merkle root hash, the tweak
54
+ pubkey: NBufferSchemaFactory(32), // tweaked with `hash` from `internalPubkey`
55
+ signature: v.union([
56
+ NBufferSchemaFactory(64),
57
+ NBufferSchemaFactory(65),
58
+ ]),
59
+ witness: v.array(BufferSchema),
60
+ scriptTree: v.custom(isTaptree, 'Taptree is not of type isTaptree'),
61
+ redeem: v.partial(
62
+ v.object({
63
+ output: BufferSchema, // tapleaf script
64
+ redeemVersion: v.number(), // tapleaf version
65
+ witness: v.array(BufferSchema),
66
+ }),
67
+ ),
68
+ redeemVersion: v.number(),
69
+ }),
70
+ ),
71
+ a,
72
+ );
73
+ const _address = lazy.value(() => {
74
+ return fromBech32(a.address);
75
+ });
76
+ // remove annex if present, ignored by taproot
77
+ const _witness = lazy.value(() => {
78
+ if (!a.witness || !a.witness.length) return;
79
+ if (
80
+ a.witness.length >= 2 &&
81
+ a.witness[a.witness.length - 1][0] === ANNEX_PREFIX
82
+ ) {
83
+ return a.witness.slice(0, -1);
84
+ }
85
+ return a.witness.slice();
86
+ });
87
+ const _hashTree = lazy.value(() => {
88
+ if (a.scriptTree) return toHashTree(a.scriptTree);
89
+ if (a.hash) return { hash: a.hash };
90
+ return;
91
+ });
92
+ const network = a.network || BITCOIN_NETWORK;
93
+ const o = { name: 'p2tr', network };
94
+ lazy.prop(o, 'address', () => {
95
+ if (!o.pubkey) return;
96
+ const words = bech32m.toWords(o.pubkey);
97
+ words.unshift(TAPROOT_WITNESS_VERSION);
98
+ return bech32m.encode(network.bech32, words);
99
+ });
100
+ lazy.prop(o, 'hash', () => {
101
+ const hashTree = _hashTree();
102
+ if (hashTree) return hashTree.hash;
103
+ const w = _witness();
104
+ if (w && w.length > 1) {
105
+ const controlBlock = w[w.length - 1];
106
+ const leafVersion = controlBlock[0] & TAPLEAF_VERSION_MASK;
107
+ const script = w[w.length - 2];
108
+ const leafHash = tapleafHash({ output: script, version: leafVersion });
109
+ return rootHashFromPath(controlBlock, leafHash);
110
+ }
111
+ return null;
112
+ });
113
+ lazy.prop(o, 'output', () => {
114
+ if (!o.pubkey) return;
115
+ return bscript.compile([OPS.OP_1, o.pubkey]);
116
+ });
117
+ lazy.prop(o, 'redeemVersion', () => {
118
+ if (a.redeemVersion) return a.redeemVersion;
119
+ if (
120
+ a.redeem &&
121
+ a.redeem.redeemVersion !== undefined &&
122
+ a.redeem.redeemVersion !== null
123
+ ) {
124
+ return a.redeem.redeemVersion;
125
+ }
126
+ return LEAF_VERSION_TAPSCRIPT;
127
+ });
128
+ lazy.prop(o, 'redeem', () => {
129
+ const witness = _witness(); // witness without annex
130
+ if (!witness || witness.length < 2) return;
131
+ return {
132
+ output: witness[witness.length - 2],
133
+ witness: witness.slice(0, -2),
134
+ redeemVersion: witness[witness.length - 1][0] & TAPLEAF_VERSION_MASK,
135
+ };
136
+ });
137
+ lazy.prop(o, 'pubkey', () => {
138
+ if (a.pubkey) return a.pubkey;
139
+ if (a.output) return a.output.slice(2);
140
+ if (a.address) return _address().data;
141
+ if (o.internalPubkey) {
142
+ const tweakedKey = tweakKey(o.internalPubkey, o.hash);
143
+ if (tweakedKey) return tweakedKey.x;
144
+ }
145
+ });
146
+ lazy.prop(o, 'internalPubkey', () => {
147
+ if (a.internalPubkey) return a.internalPubkey;
148
+ const witness = _witness();
149
+ if (witness && witness.length > 1)
150
+ return witness[witness.length - 1].slice(1, 33);
151
+ });
152
+ lazy.prop(o, 'signature', () => {
153
+ if (a.signature) return a.signature;
154
+ const witness = _witness(); // witness without annex
155
+ if (!witness || witness.length !== 1) return;
156
+ return witness[0];
157
+ });
158
+ lazy.prop(o, 'witness', () => {
159
+ if (a.witness) return a.witness;
160
+ const hashTree = _hashTree();
161
+ if (hashTree && a.redeem && a.redeem.output && a.internalPubkey) {
162
+ const leafHash = tapleafHash({
163
+ output: a.redeem.output,
164
+ version: o.redeemVersion,
165
+ });
166
+ const path = findScriptPath(hashTree, leafHash);
167
+ if (!path) return;
168
+ const outputKey = tweakKey(a.internalPubkey, hashTree.hash);
169
+ if (!outputKey) return;
170
+ const controlBock = tools.concat(
171
+ [
172
+ Uint8Array.from([o.redeemVersion | outputKey.parity]),
173
+ a.internalPubkey,
174
+ ].concat(path),
175
+ );
176
+ return [a.redeem.output, controlBock];
177
+ }
178
+ if (a.signature) return [a.signature];
179
+ });
180
+ // extended validation
181
+ if (opts.validate) {
182
+ let pubkey = Uint8Array.from([]);
183
+ if (a.address) {
184
+ if (network && network.bech32 !== _address().prefix)
185
+ throw new TypeError('Invalid prefix or Network mismatch');
186
+ if (_address().version !== TAPROOT_WITNESS_VERSION)
187
+ throw new TypeError('Invalid address version');
188
+ if (_address().data.length !== 32)
189
+ throw new TypeError('Invalid address data');
190
+ pubkey = _address().data;
191
+ }
192
+ if (a.pubkey) {
193
+ if (pubkey.length > 0 && tools.compare(pubkey, a.pubkey) !== 0)
194
+ throw new TypeError('Pubkey mismatch');
195
+ else pubkey = a.pubkey;
196
+ }
197
+ if (a.output) {
198
+ if (
199
+ a.output.length !== 34 ||
200
+ a.output[0] !== OPS.OP_1 ||
201
+ a.output[1] !== 0x20
202
+ )
203
+ throw new TypeError('Output is invalid');
204
+ if (pubkey.length > 0 && tools.compare(pubkey, a.output.slice(2)) !== 0)
205
+ throw new TypeError('Pubkey mismatch');
206
+ else pubkey = a.output.slice(2);
207
+ }
208
+ if (a.internalPubkey) {
209
+ const tweakedKey = tweakKey(a.internalPubkey, o.hash);
210
+ if (pubkey.length > 0 && tools.compare(pubkey, tweakedKey.x) !== 0)
211
+ throw new TypeError('Pubkey mismatch');
212
+ else pubkey = tweakedKey.x;
213
+ }
214
+ if (pubkey && pubkey.length) {
215
+ if (!getEccLib().isXOnlyPoint(pubkey))
216
+ throw new TypeError('Invalid pubkey for p2tr');
217
+ }
218
+ const hashTree = _hashTree();
219
+ if (a.hash && hashTree) {
220
+ if (tools.compare(a.hash, hashTree.hash) !== 0)
221
+ throw new TypeError('Hash mismatch');
222
+ }
223
+ if (a.redeem && a.redeem.output && hashTree) {
224
+ const leafHash = tapleafHash({
225
+ output: a.redeem.output,
226
+ version: o.redeemVersion,
227
+ });
228
+ if (!findScriptPath(hashTree, leafHash))
229
+ throw new TypeError('Redeem script not in tree');
230
+ }
231
+ const witness = _witness();
232
+ // compare the provided redeem data with the one computed from witness
233
+ if (a.redeem && o.redeem) {
234
+ if (a.redeem.redeemVersion) {
235
+ if (a.redeem.redeemVersion !== o.redeem.redeemVersion)
236
+ throw new TypeError('Redeem.redeemVersion and witness mismatch');
237
+ }
238
+ if (a.redeem.output) {
239
+ if (bscript.decompile(a.redeem.output).length === 0)
240
+ throw new TypeError('Redeem.output is invalid');
241
+ // output redeem is constructed from the witness
242
+ if (
243
+ o.redeem.output &&
244
+ tools.compare(a.redeem.output, o.redeem.output) !== 0
245
+ )
246
+ throw new TypeError('Redeem.output and witness mismatch');
247
+ }
248
+ if (a.redeem.witness) {
249
+ if (
250
+ o.redeem.witness &&
251
+ !stacksEqual(a.redeem.witness, o.redeem.witness)
252
+ )
253
+ throw new TypeError('Redeem.witness and witness mismatch');
254
+ }
255
+ }
256
+ if (witness && witness.length) {
257
+ if (witness.length === 1) {
258
+ // key spending
259
+ if (a.signature && tools.compare(a.signature, witness[0]) !== 0)
260
+ throw new TypeError('Signature mismatch');
261
+ } else {
262
+ // script path spending
263
+ const controlBlock = witness[witness.length - 1];
264
+ if (controlBlock.length < 33)
265
+ throw new TypeError(
266
+ `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`,
267
+ );
268
+ if ((controlBlock.length - 33) % 32 !== 0)
269
+ throw new TypeError(
270
+ `The control-block length of ${controlBlock.length} is incorrect!`,
271
+ );
272
+ const m = (controlBlock.length - 33) / 32;
273
+ if (m > 128)
274
+ throw new TypeError(
275
+ `The script path is too long. Got ${m}, expected max 128.`,
276
+ );
277
+ const internalPubkey = controlBlock.slice(1, 33);
278
+ if (
279
+ a.internalPubkey &&
280
+ tools.compare(a.internalPubkey, internalPubkey) !== 0
281
+ )
282
+ throw new TypeError('Internal pubkey mismatch');
283
+ if (!getEccLib().isXOnlyPoint(internalPubkey))
284
+ throw new TypeError('Invalid internalPubkey for p2tr witness');
285
+ const leafVersion = controlBlock[0] & TAPLEAF_VERSION_MASK;
286
+ const script = witness[witness.length - 2];
287
+ const leafHash = tapleafHash({ output: script, version: leafVersion });
288
+ const hash = rootHashFromPath(controlBlock, leafHash);
289
+ const outputKey = tweakKey(internalPubkey, hash);
290
+ if (!outputKey)
291
+ // todo: needs test data
292
+ throw new TypeError('Invalid outputKey for p2tr witness');
293
+ if (pubkey.length && tools.compare(pubkey, outputKey.x) !== 0)
294
+ throw new TypeError('Pubkey mismatch for p2tr witness');
295
+ if (outputKey.parity !== (controlBlock[0] & 1))
296
+ throw new Error('Incorrect parity');
297
+ }
298
+ }
299
+ }
300
+ return Object.assign(o, a);
301
+ }