@ledgerhq/hw-app-btc 6.10.0-taproot.0 → 6.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +660 -107
  2. package/lib/Btc.d.ts +9 -6
  3. package/lib/Btc.d.ts.map +1 -1
  4. package/lib/Btc.js +74 -11
  5. package/lib/Btc.js.map +1 -1
  6. package/lib/BtcNew.d.ts +80 -32
  7. package/lib/BtcNew.d.ts.map +1 -1
  8. package/lib/BtcNew.js +179 -209
  9. package/lib/BtcNew.js.map +1 -1
  10. package/lib/newops/accounttype.d.ts +110 -0
  11. package/lib/newops/accounttype.d.ts.map +1 -0
  12. package/lib/newops/accounttype.js +233 -0
  13. package/lib/newops/accounttype.js.map +1 -0
  14. package/lib/newops/appClient.d.ts +6 -2
  15. package/lib/newops/appClient.d.ts.map +1 -1
  16. package/lib/newops/appClient.js +8 -4
  17. package/lib/newops/appClient.js.map +1 -1
  18. package/lib/newops/clientCommands.d.ts +18 -2
  19. package/lib/newops/clientCommands.d.ts.map +1 -1
  20. package/lib/newops/clientCommands.js +34 -12
  21. package/lib/newops/clientCommands.js.map +1 -1
  22. package/lib/newops/merkelizedPsbt.d.ts +11 -0
  23. package/lib/newops/merkelizedPsbt.d.ts.map +1 -1
  24. package/lib/newops/merkelizedPsbt.js +11 -0
  25. package/lib/newops/merkelizedPsbt.js.map +1 -1
  26. package/lib/newops/merkle.d.ts +5 -0
  27. package/lib/newops/merkle.d.ts.map +1 -1
  28. package/lib/newops/merkle.js +5 -0
  29. package/lib/newops/merkle.js.map +1 -1
  30. package/lib/newops/merkleMap.d.ts +10 -0
  31. package/lib/newops/merkleMap.d.ts.map +1 -1
  32. package/lib/newops/merkleMap.js +10 -0
  33. package/lib/newops/merkleMap.js.map +1 -1
  34. package/lib/newops/policy.d.ts +8 -0
  35. package/lib/newops/policy.d.ts.map +1 -1
  36. package/lib/newops/policy.js +9 -1
  37. package/lib/newops/policy.js.map +1 -1
  38. package/lib/newops/psbtExtractor.d.ts +6 -0
  39. package/lib/newops/psbtExtractor.d.ts.map +1 -1
  40. package/lib/newops/psbtExtractor.js +6 -0
  41. package/lib/newops/psbtExtractor.js.map +1 -1
  42. package/lib/newops/psbtFinalizer.d.ts +11 -1
  43. package/lib/newops/psbtFinalizer.d.ts.map +1 -1
  44. package/lib/newops/psbtFinalizer.js +26 -1
  45. package/lib/newops/psbtFinalizer.js.map +1 -1
  46. package/lib/newops/psbtv2.d.ts +22 -2
  47. package/lib/newops/psbtv2.d.ts.map +1 -1
  48. package/lib/newops/psbtv2.js +33 -8
  49. package/lib/newops/psbtv2.js.map +1 -1
  50. package/lib-es/Btc.d.ts +9 -6
  51. package/lib-es/Btc.d.ts.map +1 -1
  52. package/lib-es/Btc.js +75 -12
  53. package/lib-es/Btc.js.map +1 -1
  54. package/lib-es/BtcNew.d.ts +80 -32
  55. package/lib-es/BtcNew.d.ts.map +1 -1
  56. package/lib-es/BtcNew.js +176 -210
  57. package/lib-es/BtcNew.js.map +1 -1
  58. package/lib-es/newops/accounttype.d.ts +110 -0
  59. package/lib-es/newops/accounttype.d.ts.map +1 -0
  60. package/lib-es/newops/accounttype.js +230 -0
  61. package/lib-es/newops/accounttype.js.map +1 -0
  62. package/lib-es/newops/appClient.d.ts +6 -2
  63. package/lib-es/newops/appClient.d.ts.map +1 -1
  64. package/lib-es/newops/appClient.js +8 -4
  65. package/lib-es/newops/appClient.js.map +1 -1
  66. package/lib-es/newops/clientCommands.d.ts +18 -2
  67. package/lib-es/newops/clientCommands.d.ts.map +1 -1
  68. package/lib-es/newops/clientCommands.js +34 -12
  69. package/lib-es/newops/clientCommands.js.map +1 -1
  70. package/lib-es/newops/merkelizedPsbt.d.ts +11 -0
  71. package/lib-es/newops/merkelizedPsbt.d.ts.map +1 -1
  72. package/lib-es/newops/merkelizedPsbt.js +11 -0
  73. package/lib-es/newops/merkelizedPsbt.js.map +1 -1
  74. package/lib-es/newops/merkle.d.ts +5 -0
  75. package/lib-es/newops/merkle.d.ts.map +1 -1
  76. package/lib-es/newops/merkle.js +5 -0
  77. package/lib-es/newops/merkle.js.map +1 -1
  78. package/lib-es/newops/merkleMap.d.ts +10 -0
  79. package/lib-es/newops/merkleMap.d.ts.map +1 -1
  80. package/lib-es/newops/merkleMap.js +10 -0
  81. package/lib-es/newops/merkleMap.js.map +1 -1
  82. package/lib-es/newops/policy.d.ts +8 -0
  83. package/lib-es/newops/policy.d.ts.map +1 -1
  84. package/lib-es/newops/policy.js +10 -2
  85. package/lib-es/newops/policy.js.map +1 -1
  86. package/lib-es/newops/psbtExtractor.d.ts +6 -0
  87. package/lib-es/newops/psbtExtractor.d.ts.map +1 -1
  88. package/lib-es/newops/psbtExtractor.js +6 -0
  89. package/lib-es/newops/psbtExtractor.js.map +1 -1
  90. package/lib-es/newops/psbtFinalizer.d.ts +11 -1
  91. package/lib-es/newops/psbtFinalizer.d.ts.map +1 -1
  92. package/lib-es/newops/psbtFinalizer.js +26 -1
  93. package/lib-es/newops/psbtFinalizer.js.map +1 -1
  94. package/lib-es/newops/psbtv2.d.ts +22 -2
  95. package/lib-es/newops/psbtv2.d.ts.map +1 -1
  96. package/lib-es/newops/psbtv2.js +33 -8
  97. package/lib-es/newops/psbtv2.js.map +1 -1
  98. package/package.json +4 -4
  99. package/src/Btc.ts +113 -15
  100. package/src/BtcNew.ts +213 -209
  101. package/src/newops/accounttype.ts +370 -0
  102. package/src/newops/appClient.ts +12 -4
  103. package/src/newops/clientCommands.ts +34 -12
  104. package/src/newops/merkelizedPsbt.ts +11 -0
  105. package/src/newops/merkle.ts +5 -0
  106. package/src/newops/merkleMap.ts +10 -0
  107. package/src/newops/policy.ts +10 -2
  108. package/src/newops/psbtExtractor.ts +6 -0
  109. package/src/newops/psbtFinalizer.ts +26 -1
  110. package/src/newops/psbtv2.ts +34 -14
  111. package/tests/Btc.integration.test.ts +7 -1
  112. package/tests/Btc.test.ts +88 -0
  113. package/tests/newops/BtcNew.test.ts +54 -20
  114. package/tests/newops/integrationtools.ts +49 -39
  115. package/tests/newops/testtx.ts +0 -55
package/src/BtcNew.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { crypto } from "bitcoinjs-lib";
2
+ import semver from "semver";
3
+ import { pointCompress } from "tiny-secp256k1";
2
4
  import {
3
5
  getXpubComponents,
4
6
  hardenedPathOf,
@@ -6,32 +8,85 @@ import {
6
8
  pathStringToArray,
7
9
  pubkeyFromXpub,
8
10
  } from "./bip32";
9
- import { BufferReader, BufferWriter } from "./buffertools";
11
+ import { BufferReader } from "./buffertools";
10
12
  import type { CreateTransactionArg } from "./createTransaction";
13
+ import { AppAndVersion } from "./getAppAndVersion";
11
14
  import type { AddressFormat } from "./getWalletPublicKey";
12
- import { hashPublicKey } from "./hashPublicKey";
15
+ import {
16
+ AccountType,
17
+ p2pkh,
18
+ p2tr,
19
+ p2wpkh,
20
+ p2wpkhWrapped,
21
+ SpendingCondition,
22
+ } from "./newops/accounttype";
13
23
  import { AppClient as Client } from "./newops/appClient";
14
- import { createKey, WalletPolicy } from "./newops/policy";
24
+ import {
25
+ createKey,
26
+ DefaultDescriptorTemplate,
27
+ WalletPolicy,
28
+ } from "./newops/policy";
15
29
  import { extract } from "./newops/psbtExtractor";
16
30
  import { finalize } from "./newops/psbtFinalizer";
17
31
  import { psbtIn, PsbtV2 } from "./newops/psbtv2";
18
32
  import { serializeTransaction } from "./serializeTransaction";
19
33
  import type { Transaction } from "./types";
20
- import { pointCompress, pointAddScalar } from "tiny-secp256k1";
21
- import {
22
- HASH_SIZE,
23
- OP_CHECKSIG,
24
- OP_DUP,
25
- OP_EQUAL,
26
- OP_EQUALVERIFY,
27
- OP_HASH160,
28
- } from "./constants";
29
34
 
30
- export const newSupportedApps = ["Bitcoin", "Bitcoin Test"];
35
+ const newSupportedApps = ["Bitcoin", "Bitcoin Test"];
36
+
37
+ export function canSupportApp(appAndVersion: AppAndVersion): boolean {
38
+ return (
39
+ newSupportedApps.includes(appAndVersion.name) &&
40
+ semver.major(appAndVersion.version) >= 2
41
+ );
42
+ }
31
43
 
44
+ /**
45
+ * This class implements the same interface as BtcOld (formerly
46
+ * named Btc), but interacts with Bitcoin hardware app version 2+
47
+ * which uses a totally new APDU protocol. This new
48
+ * protocol is documented at
49
+ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md
50
+ *
51
+ * Since the interface must remain compatible with BtcOld, the methods
52
+ * of this class are quite clunky, because it needs to adapt legacy
53
+ * input data into the PSBT process. In the future, a new interface should
54
+ * be developed that exposes PSBT to the outer world, which would render
55
+ * a much cleaner implementation.
56
+ */
32
57
  export default class BtcNew {
33
58
  constructor(private client: Client) {}
34
59
 
60
+ /**
61
+ * This is a new method that allow users to get an xpub at a standard path.
62
+ * Standard paths are described at
63
+ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description
64
+ *
65
+ * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet):
66
+ * M/44'/N'/x'/**
67
+ * M/48'/N'/x'/y'/**
68
+ * M/49'/N'/x'/**
69
+ * M/84'/N'/x'/**
70
+ * M/86'/N'/x'/**
71
+ *
72
+ * The method was added because of added security in the hardware app v2+. The
73
+ * new hardware app will allow export of any xpub up to and including the
74
+ * deepest hardened key of standard derivation paths, whereas the old app
75
+ * would allow export of any key.
76
+ *
77
+ * This caused an issue for callers of this class, who only had
78
+ * getWalletPublicKey() to call which means they have to constuct xpub
79
+ * themselves:
80
+ *
81
+ * Suppose a user of this class wants to create an account xpub on a standard
82
+ * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32)
83
+ * by requesting the parent key M/44'/0'. The new app won't allow that, because
84
+ * it only allows exporting deepest level hardened path. So the options are to
85
+ * allow requesting M/44'/0' from the app, or to add a new function
86
+ * "getWalletXpub".
87
+ *
88
+ * We opted for adding a new function, which can greatly simplify client code.
89
+ */
35
90
  async getWalletXpub({
36
91
  path,
37
92
  xpubVersion,
@@ -40,7 +95,7 @@ export default class BtcNew {
40
95
  xpubVersion: number;
41
96
  }): Promise<string> {
42
97
  const pathElements: number[] = pathStringToArray(path);
43
- const xpub = await this.client.getPubkey(false, pathElements);
98
+ const xpub = await this.client.getExtendedPubkey(false, pathElements);
44
99
  const xpubComponents = getXpubComponents(xpub);
45
100
  if (xpubComponents.version != xpubVersion) {
46
101
  throw new Error(
@@ -50,6 +105,13 @@ export default class BtcNew {
50
105
  return xpub;
51
106
  }
52
107
 
108
+ /**
109
+ * This method returns a public key, a bitcoin address, and and a chaincode
110
+ * for a specific derivation path.
111
+ *
112
+ * Limitation: If the path is not a leaf node of a standard path, the address
113
+ * will be the empty string "", see this.getWalletAddress() for details.
114
+ */
53
115
  async getWalletPublicKey(
54
116
  path: string,
55
117
  opts?: {
@@ -62,13 +124,13 @@ export default class BtcNew {
62
124
  chainCode: string;
63
125
  }> {
64
126
  const pathElements: number[] = pathStringToArray(path);
65
- const xpub = await this.client.getPubkey(false, pathElements);
127
+ const xpub = await this.client.getExtendedPubkey(false, pathElements);
66
128
 
67
129
  const display = opts?.verify ?? false;
68
130
 
69
131
  const address = await this.getWalletAddress(
70
132
  pathElements,
71
- accountTypeFrom(opts?.format ?? "legacy"),
133
+ descrTemplFrom(opts?.format ?? "legacy"),
72
134
  display
73
135
  );
74
136
  const components = getXpubComponents(xpub);
@@ -91,7 +153,7 @@ export default class BtcNew {
91
153
  *
92
154
  * If display is false we *could* generate the address ourselves, but chose to
93
155
  * get it from the device to save development time. However, it shouldn't take
94
- * more than a few hours to implement local address generation.
156
+ * too much time to implement local address generation.
95
157
  *
96
158
  * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no
97
159
  * way to get the address from the device. In this case we have to create it
@@ -99,17 +161,17 @@ export default class BtcNew {
99
161
  */
100
162
  private async getWalletAddress(
101
163
  pathElements: number[],
102
- accountType: AccountType,
164
+ descrTempl: DefaultDescriptorTemplate,
103
165
  display: boolean
104
166
  ): Promise<string> {
105
167
  const accountPath = hardenedPathOf(pathElements);
106
168
  if (accountPath.length + 2 != pathElements.length) {
107
169
  return "";
108
170
  }
109
- const accountXpub = await this.client.getPubkey(false, accountPath);
171
+ const accountXpub = await this.client.getExtendedPubkey(false, accountPath);
110
172
  const masterFingerprint = await this.client.getMasterFingerprint();
111
173
  const policy = new WalletPolicy(
112
- accountType,
174
+ descrTempl,
113
175
  createKey(masterFingerprint, accountPath, accountXpub)
114
176
  );
115
177
  const changeAndIndex = pathElements.slice(-2, pathElements.length);
@@ -123,66 +185,55 @@ export default class BtcNew {
123
185
  }
124
186
 
125
187
  /**
126
- * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters
127
- * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where
188
+ * Build and sign a transaction. See Btc.createPaymentTransactionNew for
189
+ * details on how to use this method.
128
190
  *
129
- * * transaction is the previously computed transaction object for this UTXO
130
- * * output_index is the output in the transaction used as input for this UTXO (counting from 0)
131
- * * redeem script is the optional redeem script to use when consuming a Segregated Witness input
132
- * * sequence is the sequence number to use for this input (when using RBF), or non present
133
- * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
134
- * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address
135
- * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount
136
- * @param lockTime is the optional lockTime of the transaction to sign, or default (0)
137
- * @param sigHashType is the hash type of the transaction to sign, or default (all)
138
- * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit.
139
- * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include)
140
- * @param additionals list of additionnal options
141
- *
142
- * - "bech32" for spending native segwit outputs
143
- * - "bech32m" for spending segwit v1+ outptus
144
- * - "abc" for bch
145
- * - "gold" for btg
146
- * - "bipxxx" for using BIPxxx
147
- * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
148
- * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs
149
- * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true.
150
- * @return the signed transaction ready to be broadcast
151
- * @example
152
- btc.createTransaction({
153
- inputs: [ [tx1, 1] ],
154
- associatedKeysets: ["0'/0/0"],
155
- outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
156
- }).then(res => ...);
191
+ * This method will convert the legacy arguments, CreateTransactionArg, into
192
+ * a psbt which is finally signed and finalized, and the extracted fully signed
193
+ * transaction is returned.
157
194
  */
158
195
  async createPaymentTransactionNew(
159
196
  arg: CreateTransactionArg
160
197
  ): Promise<string> {
161
- if (arg.inputs.length == 0) {
198
+ const inputCount = arg.inputs.length;
199
+ if (inputCount == 0) {
162
200
  throw Error("No inputs");
163
201
  }
164
202
  const psbt = new PsbtV2();
203
+ // The master fingerprint is needed when adding BIP32 derivation paths on
204
+ // the psbt.
205
+ const masterFp = await this.client.getMasterFingerprint();
165
206
 
166
- const accountType = accountTypeFromArg(arg);
207
+ const accountType = accountTypeFromArg(arg, psbt, masterFp);
167
208
 
168
- psbt.setGlobalTxVersion(2);
169
209
  if (arg.lockTime) {
210
+ // The signer will assume locktime 0 if unset
170
211
  psbt.setGlobalFallbackLocktime(arg.lockTime);
171
212
  }
172
- psbt.setGlobalInputCount(arg.inputs.length);
213
+ psbt.setGlobalInputCount(inputCount);
173
214
  psbt.setGlobalPsbtVersion(2);
174
215
  psbt.setGlobalTxVersion(2);
175
216
 
176
- const masterFp = await this.client.getMasterFingerprint();
217
+ let notifyCount = 0;
218
+ const progress = () => {
219
+ if (!arg.onDeviceStreaming) return;
220
+ arg.onDeviceStreaming({
221
+ total: 2 * inputCount,
222
+ index: notifyCount,
223
+ progress: ++notifyCount / (2 * inputCount),
224
+ });
225
+ };
226
+
177
227
  let accountXpub = "";
178
228
  let accountPath: number[] = [];
179
- for (let i = 0; i < arg.inputs.length; i++) {
229
+ for (let i = 0; i < inputCount; i++) {
230
+ progress();
180
231
  const pathElems: number[] = pathStringToArray(arg.associatedKeysets[i]);
181
232
  if (accountXpub == "") {
182
233
  // We assume all inputs belong to the same account so we set
183
234
  // the account xpub and path based on the first input.
184
235
  accountPath = pathElems.slice(0, -2);
185
- accountXpub = await this.client.getPubkey(false, accountPath);
236
+ accountXpub = await this.client.getExtendedPubkey(false, accountPath);
186
237
  }
187
238
  await this.setInput(
188
239
  psbt,
@@ -190,70 +241,85 @@ export default class BtcNew {
190
241
  arg.inputs[i],
191
242
  pathElems,
192
243
  accountType,
193
- masterFp
244
+ masterFp,
245
+ arg.sigHashType
194
246
  );
195
247
  }
196
248
 
197
249
  const outputsConcat = Buffer.from(arg.outputScriptHex, "hex");
198
250
  const outputsBufferReader = new BufferReader(outputsConcat);
199
251
  const outputCount = outputsBufferReader.readVarInt();
252
+ psbt.setGlobalOutputCount(outputCount);
200
253
  const changeData = await this.outputScriptAt(
201
254
  accountPath,
202
255
  accountType,
203
256
  arg.changePath
204
257
  );
205
- psbt.setGlobalOutputCount(outputCount);
258
+ // If the caller supplied a changePath, we must make sure there actually is
259
+ // a change output. If no change output found, we'll throw an error.
206
260
  let changeFound = !changeData;
207
261
  for (let i = 0; i < outputCount; i++) {
208
262
  const amount = Number(outputsBufferReader.readUInt64());
209
263
  const outputScript = outputsBufferReader.readVarSlice();
264
+ psbt.setOutputAmount(i, amount);
265
+ psbt.setOutputScript(i, outputScript);
210
266
 
211
- // We won't know if we're paying to ourselves, because
212
- // there's no information in the input arg to support this.
213
- // We only have the changePath.
214
- // One exception is if there are multiple outputs to the
215
- // change address.
216
- const isChange = changeData && outputScript.equals(changeData?.script);
267
+ // We won't know if we're paying to ourselves, because there's no
268
+ // information in arg to support multiple "change paths". One exception is
269
+ // if there are multiple outputs to the change address.
270
+ const isChange =
271
+ changeData && outputScript.equals(changeData?.cond.scriptPubKey);
217
272
  if (isChange) {
218
273
  changeFound = true;
219
274
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
220
275
  const changePath = pathStringToArray(arg.changePath!);
221
276
  const pubkey = changeData.pubkey;
222
277
 
223
- if (accountType == AccountType.p2pkh) {
224
- psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
225
- } else if (accountType == AccountType.p2wpkh) {
226
- psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
227
- } else if (accountType == AccountType.p2wpkhWrapped) {
228
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
229
- psbt.setOutputRedeemScript(i, changeData.redeemScript!);
230
- psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
231
- } else if (accountType == AccountType.p2tr) {
232
- psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath);
233
- }
278
+ accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]);
234
279
  }
235
- psbt.setOutputAmount(i, amount);
236
- psbt.setOutputScript(i, outputScript);
237
280
  }
238
281
  if (!changeFound) {
239
282
  throw new Error(
240
283
  "Change script not found among outputs! " +
241
- changeData?.script.toString("hex")
284
+ changeData?.cond.scriptPubKey.toString("hex")
242
285
  );
243
286
  }
244
287
 
245
288
  const key = createKey(masterFp, accountPath, accountXpub);
246
- const p = new WalletPolicy(accountType, key);
247
- return await this.signPsbt(psbt, p);
289
+ const p = new WalletPolicy(accountType.getDescriptorTemplate(), key);
290
+ // This is cheating, because it's not actually requested on the
291
+ // device yet, but it will be, soonish.
292
+ if (arg.onDeviceSignatureRequested) arg.onDeviceSignatureRequested();
293
+
294
+ let firstSigned = false;
295
+ // This callback will be called once for each signature yielded.
296
+ const progressCallback = () => {
297
+ if (!firstSigned) {
298
+ firstSigned = true;
299
+ arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted();
300
+ }
301
+ progress();
302
+ };
303
+
304
+ await this.signPsbt(psbt, p, progressCallback);
305
+ finalize(psbt);
306
+ const serializedTx = extract(psbt);
307
+ return serializedTx.toString("hex");
248
308
  }
249
309
 
310
+ /**
311
+ * Calculates an output script along with public key and possible redeemScript
312
+ * from a path and accountType. The accountPath must be a prefix of path.
313
+ *
314
+ * @returns an object with output script (property "script"), redeemScript (if
315
+ * wrapped p2wpkh), and pubkey at provided path. The values of these three
316
+ * properties depend on the accountType used.
317
+ */
250
318
  private async outputScriptAt(
251
319
  accountPath: number[],
252
320
  accountType: AccountType,
253
321
  path: string | undefined
254
- ): Promise<
255
- { script: Buffer; redeemScript?: Buffer; pubkey: Buffer } | undefined
256
- > {
322
+ ): Promise<{ cond: SpendingCondition; pubkey: Buffer } | undefined> {
257
323
  if (!path) return undefined;
258
324
  const pathElems = pathStringToArray(path);
259
325
  // Make sure path is in our account, otherwise something fishy is probably
@@ -265,15 +331,17 @@ export default class BtcNew {
265
331
  );
266
332
  }
267
333
  }
268
- const xpub = await this.client.getPubkey(false, pathElems);
269
- let pubkey = pubkeyFromXpub(xpub);
270
- if (accountType == AccountType.p2tr) {
271
- pubkey = pubkey.slice(1);
272
- }
273
- const script = outputScriptOf(pubkey, accountType);
274
- return { ...script, pubkey };
334
+ const xpub = await this.client.getExtendedPubkey(false, pathElems);
335
+ const pubkey = pubkeyFromXpub(xpub);
336
+ const cond = accountType.spendingCondition([pubkey]);
337
+ return { cond, pubkey };
275
338
  }
276
339
 
340
+ /**
341
+ * Adds relevant data about an input to the psbt. This includes sequence,
342
+ * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh,
343
+ * public key and its derivation path.
344
+ */
277
345
  private async setInput(
278
346
  psbt: PsbtV2,
279
347
  i: number,
@@ -285,65 +353,69 @@ export default class BtcNew {
285
353
  ],
286
354
  pathElements: number[],
287
355
  accountType: AccountType,
288
- masterFP: Buffer
356
+ masterFP: Buffer,
357
+ sigHashType?: number
289
358
  ): Promise<void> {
290
359
  const inputTx = input[0];
291
360
  const spentOutputIndex = input[1];
292
- const redeemScript = input[2];
361
+ // redeemScript will be null for wrapped p2wpkh, we need to create it
362
+ // ourselves. But if set, it should be used.
363
+ const redeemScript = input[2] ? Buffer.from(input[2], "hex") : undefined;
293
364
  const sequence = input[3];
294
365
  if (sequence) {
295
366
  psbt.setInputSequence(i, sequence);
296
367
  }
368
+ if (sigHashType) {
369
+ psbt.setInputSighashType(i, sigHashType);
370
+ }
297
371
  const inputTxBuffer = serializeTransaction(inputTx, true);
298
372
  const inputTxid = crypto.hash256(inputTxBuffer);
299
- const xpubBase58 = await this.client.getPubkey(false, pathElements);
373
+ const xpubBase58 = await this.client.getExtendedPubkey(false, pathElements);
300
374
 
301
375
  const pubkey = pubkeyFromXpub(xpubBase58);
302
376
  if (!inputTx.outputs)
303
377
  throw Error("Missing outputs array in transaction to sign");
304
- const spentOutput = inputTx.outputs[spentOutputIndex];
305
-
306
- if (accountType == AccountType.p2pkh) {
307
- psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
308
- psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
309
- } else if (accountType == AccountType.p2wpkh) {
310
- psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
311
- psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
312
- psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
313
- } else if (accountType == AccountType.p2wpkhWrapped) {
314
- psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
315
- psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
316
- if (!redeemScript) {
317
- throw new Error("Missing redeemScript for p2wpkhWrapped input");
318
- }
319
- const expectedRedeemScript = createRedeemScript(pubkey);
320
- if (redeemScript != expectedRedeemScript.toString("hex")) {
321
- throw new Error("Unexpected redeemScript");
322
- }
323
- psbt.setInputRedeemScript(i, expectedRedeemScript);
324
- psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
325
- } else if (accountType == AccountType.p2tr) {
326
- const xonly = pubkey.slice(1);
327
- psbt.setInputTapBip32Derivation(i, xonly, [], masterFP, pathElements);
328
- psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
329
- }
378
+ const spentTxOutput = inputTx.outputs[spentOutputIndex];
379
+ const spendCondition: SpendingCondition = {
380
+ scriptPubKey: spentTxOutput.script,
381
+ redeemScript: redeemScript,
382
+ };
383
+ const spentOutput = { cond: spendCondition, amount: spentTxOutput.amount };
384
+ accountType.setInput(
385
+ i,
386
+ inputTxBuffer,
387
+ spentOutput,
388
+ [pubkey],
389
+ [pathElements]
390
+ );
330
391
 
331
392
  psbt.setInputPreviousTxId(i, inputTxid);
332
393
  psbt.setInputOutputIndex(i, spentOutputIndex);
333
394
  }
334
395
 
396
+ /**
397
+ * This implements the "Signer" role of the BIP370 transaction signing
398
+ * process.
399
+ *
400
+ * It ssks the hardware device to sign the a psbt using the specified wallet
401
+ * policy. This method assumes BIP32 derived keys are used for all inputs, see
402
+ * comment in-line. The signatures returned from the hardware device is added
403
+ * to the appropriate input fields of the PSBT.
404
+ */
335
405
  private async signPsbt(
336
406
  psbt: PsbtV2,
337
- walletPolicy: WalletPolicy
338
- ): Promise<string> {
407
+ walletPolicy: WalletPolicy,
408
+ progressCallback: () => void
409
+ ): Promise<void> {
339
410
  const sigs: Map<number, Buffer> = await this.client.signPsbt(
340
411
  psbt,
341
412
  walletPolicy,
342
- Buffer.alloc(32, 0)
413
+ Buffer.alloc(32, 0),
414
+ progressCallback
343
415
  );
344
416
  sigs.forEach((v, k) => {
345
- // Note: Looking at BIP32 derivation does not work in the generic case.
346
- // some inputs might not have a BIP32-derived pubkey.
417
+ // Note: Looking at BIP32 derivation does not work in the generic case,
418
+ // since some inputs might not have a BIP32-derived pubkey.
347
419
  const pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION);
348
420
  let pubkey;
349
421
  if (pubkeys.length != 1) {
@@ -358,94 +430,26 @@ export default class BtcNew {
358
430
  psbt.setInputPartialSig(k, pubkey, v);
359
431
  }
360
432
  });
361
- finalize(psbt);
362
- const serializedTx = extract(psbt);
363
- return serializedTx.toString("hex");
364
433
  }
365
434
  }
366
435
 
367
- enum AccountType {
368
- p2pkh = "pkh(@0)",
369
- p2wpkh = "wpkh(@0)",
370
- p2wpkhWrapped = "sh(wpkh(@0))",
371
- p2tr = "tr(@0)",
372
- }
373
-
374
- function createRedeemScript(pubkey: Buffer): Buffer {
375
- const pubkeyHash = hashPublicKey(pubkey);
376
- return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]);
377
- }
378
-
379
- function outputScriptOf(
380
- pubkey: Buffer,
381
- accountType: AccountType
382
- ): { script: Buffer; redeemScript?: Buffer } {
383
- const buf = new BufferWriter();
384
- const pubkeyHash = hashPublicKey(pubkey);
385
- let redeemScript: Buffer | undefined;
386
- if (accountType == AccountType.p2pkh) {
387
- buf.writeSlice(Buffer.of(OP_DUP, OP_HASH160, HASH_SIZE));
388
- buf.writeSlice(pubkeyHash);
389
- buf.writeSlice(Buffer.of(OP_EQUALVERIFY, OP_CHECKSIG));
390
- } else if (accountType == AccountType.p2wpkhWrapped) {
391
- redeemScript = createRedeemScript(pubkey);
392
- const scriptHash = hashPublicKey(redeemScript);
393
- buf.writeSlice(Buffer.of(OP_HASH160, HASH_SIZE));
394
- buf.writeSlice(scriptHash);
395
- buf.writeUInt8(OP_EQUAL);
396
- } else if (accountType == AccountType.p2wpkh) {
397
- buf.writeSlice(Buffer.of(0, HASH_SIZE));
398
- buf.writeSlice(pubkeyHash);
399
- } else if (accountType == AccountType.p2tr) {
400
- console.log("Internal key: " + pubkey.toString("hex"));
401
- const outputKey = getTaprootOutputKey(pubkey);
402
- buf.writeSlice(Buffer.of(0x51, 32)); // push1, pubkeylen
403
- buf.writeSlice(outputKey);
404
- }
405
- return { script: buf.buffer(), redeemScript };
406
- }
407
-
408
- function accountTypeFrom(addressFormat: AddressFormat): AccountType {
409
- if (addressFormat == "legacy") return AccountType.p2pkh;
410
- if (addressFormat == "p2sh") return AccountType.p2wpkhWrapped;
411
- if (addressFormat == "bech32") return AccountType.p2wpkh;
412
- if (addressFormat == "bech32m") return AccountType.p2tr;
436
+ function descrTemplFrom(
437
+ addressFormat: AddressFormat
438
+ ): DefaultDescriptorTemplate {
439
+ if (addressFormat == "legacy") return "pkh(@0)";
440
+ if (addressFormat == "p2sh") return "sh(wpkh(@0))";
441
+ if (addressFormat == "bech32") return "wpkh(@0)";
442
+ if (addressFormat == "bech32m") return "tr(@0)";
413
443
  throw new Error("Unsupported address format " + addressFormat);
414
444
  }
415
445
 
416
- function accountTypeFromArg(arg: CreateTransactionArg): AccountType {
417
- if (arg.additionals.includes("bech32m")) return AccountType.p2tr;
418
- if (arg.additionals.includes("bech32")) return AccountType.p2wpkh;
419
- if (arg.segwit) return AccountType.p2wpkhWrapped;
420
- return AccountType.p2pkh;
421
- }
422
-
423
- /*
424
- The following two functions are copied from wallet-btc and adapte.
425
- They should be moved to a library to avoid code reuse.
426
- */
427
- function hashTapTweak(x: Buffer): Buffer {
428
- // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340
429
- // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification
430
- const h = crypto.sha256(Buffer.from("TapTweak", "utf-8"));
431
- return crypto.sha256(Buffer.concat([h, h, x]));
432
- }
433
-
434
- function getTaprootOutputKey(internalPubkey: Buffer): Buffer {
435
- if (internalPubkey.length != 32) {
436
- throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length);
437
- }
438
- // A BIP32 derived key can be converted to a schnorr pubkey by dropping
439
- // the first byte, which represent the oddness/evenness. In schnorr all
440
- // pubkeys are even.
441
- // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion
442
- const evenEcdsaPubkey = Buffer.concat([Buffer.of(0x02), internalPubkey]);
443
- const tweak = hashTapTweak(internalPubkey);
444
-
445
- // Q = P + int(hash_TapTweak(bytes(P)))G
446
- const outputEcdsaKey = Buffer.from(pointAddScalar(evenEcdsaPubkey, tweak));
447
- // Convert to schnorr.
448
- const outputSchnorrKey = outputEcdsaKey.slice(1);
449
- // Create address
450
- return outputSchnorrKey;
446
+ function accountTypeFromArg(
447
+ arg: CreateTransactionArg,
448
+ psbt: PsbtV2,
449
+ masterFp: Buffer
450
+ ): AccountType {
451
+ if (arg.additionals.includes("bech32m")) return new p2tr(psbt, masterFp);
452
+ if (arg.additionals.includes("bech32")) return new p2wpkh(psbt, masterFp);
453
+ if (arg.segwit) return new p2wpkhWrapped(psbt, masterFp);
454
+ return new p2pkh(psbt, masterFp);
451
455
  }