@ledgerhq/hw-app-btc 6.2.0 → 6.9.1-6.9.1-taproot.0.0

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 (187) hide show
  1. package/lib/Btc.d.ts +7 -3
  2. package/lib/Btc.d.ts.map +1 -1
  3. package/lib/Btc.js +99 -30
  4. package/lib/Btc.js.map +1 -1
  5. package/lib/BtcNew.d.ts +70 -0
  6. package/lib/BtcNew.d.ts.map +1 -0
  7. package/lib/BtcNew.js +372 -0
  8. package/lib/BtcNew.js.map +1 -0
  9. package/lib/BtcOld.d.ts +114 -0
  10. package/lib/BtcOld.d.ts.map +1 -0
  11. package/lib/BtcOld.js +138 -0
  12. package/lib/BtcOld.js.map +1 -0
  13. package/lib/bip32.d.ts +8 -0
  14. package/lib/bip32.d.ts.map +1 -1
  15. package/lib/bip32.js +32 -3
  16. package/lib/bip32.js.map +1 -1
  17. package/lib/buffertools.d.ts +28 -0
  18. package/lib/buffertools.d.ts.map +1 -0
  19. package/lib/buffertools.js +100 -0
  20. package/lib/buffertools.js.map +1 -0
  21. package/lib/createTransaction.d.ts.map +1 -1
  22. package/lib/createTransaction.js +16 -16
  23. package/lib/createTransaction.js.map +1 -1
  24. package/lib/finalizeInput.js +1 -1
  25. package/lib/finalizeInput.js.map +1 -1
  26. package/lib/getAppAndVersion.js +1 -1
  27. package/lib/getAppAndVersion.js.map +1 -1
  28. package/lib/getTrustedInput.js +6 -6
  29. package/lib/getTrustedInput.js.map +1 -1
  30. package/lib/getTrustedInputBIP143.js +2 -2
  31. package/lib/getTrustedInputBIP143.js.map +1 -1
  32. package/lib/getWalletPublicKey.d.ts +1 -1
  33. package/lib/getWalletPublicKey.d.ts.map +1 -1
  34. package/lib/getWalletPublicKey.js +1 -1
  35. package/lib/getWalletPublicKey.js.map +1 -1
  36. package/lib/hashPublicKey.d.ts +1 -1
  37. package/lib/hashPublicKey.d.ts.map +1 -1
  38. package/lib/hashPublicKey.js +1 -1
  39. package/lib/hashPublicKey.js.map +1 -1
  40. package/lib/index.d.ts +3 -0
  41. package/lib/index.d.ts.map +1 -0
  42. package/lib/index.js +8 -0
  43. package/lib/index.js.map +1 -0
  44. package/lib/newops/appClient.d.ts +14 -0
  45. package/lib/newops/appClient.d.ts.map +1 -0
  46. package/lib/newops/appClient.js +242 -0
  47. package/lib/newops/appClient.js.map +1 -0
  48. package/lib/newops/clientCommands.d.ts +61 -0
  49. package/lib/newops/clientCommands.d.ts.map +1 -0
  50. package/lib/newops/clientCommands.js +331 -0
  51. package/lib/newops/clientCommands.js.map +1 -0
  52. package/lib/newops/merkelizedPsbt.d.ts +15 -0
  53. package/lib/newops/merkelizedPsbt.d.ts.map +1 -0
  54. package/lib/newops/merkelizedPsbt.js +91 -0
  55. package/lib/newops/merkelizedPsbt.js.map +1 -0
  56. package/lib/newops/merkle.d.ts +29 -0
  57. package/lib/newops/merkle.d.ts.map +1 -0
  58. package/lib/newops/merkle.js +133 -0
  59. package/lib/newops/merkle.js.map +1 -0
  60. package/lib/newops/merkleMap.d.ts +15 -0
  61. package/lib/newops/merkleMap.d.ts.map +1 -0
  62. package/lib/newops/merkleMap.js +37 -0
  63. package/lib/newops/merkleMap.js.map +1 -0
  64. package/lib/newops/policy.d.ts +14 -0
  65. package/lib/newops/policy.d.ts.map +1 -0
  66. package/lib/newops/policy.js +40 -0
  67. package/lib/newops/policy.js.map +1 -0
  68. package/lib/newops/psbtExtractor.d.ts +4 -0
  69. package/lib/newops/psbtExtractor.d.ts.map +1 -0
  70. package/lib/newops/psbtExtractor.js +36 -0
  71. package/lib/newops/psbtExtractor.js.map +1 -0
  72. package/lib/newops/psbtFinalizer.d.ts +7 -0
  73. package/lib/newops/psbtFinalizer.d.ts.map +1 -0
  74. package/lib/newops/psbtFinalizer.js +111 -0
  75. package/lib/newops/psbtFinalizer.js.map +1 -0
  76. package/lib/newops/psbtv2.d.ts +129 -0
  77. package/lib/newops/psbtv2.d.ts.map +1 -0
  78. package/lib/newops/psbtv2.js +478 -0
  79. package/lib/newops/psbtv2.js.map +1 -0
  80. package/lib/serializeTransaction.js +4 -4
  81. package/lib/serializeTransaction.js.map +1 -1
  82. package/lib/signP2SHTransaction.js +5 -5
  83. package/lib/signP2SHTransaction.js.map +1 -1
  84. package/lib/signTransaction.js +1 -1
  85. package/lib/signTransaction.js.map +1 -1
  86. package/lib/splitTransaction.js +7 -7
  87. package/lib/splitTransaction.js.map +1 -1
  88. package/lib/startUntrustedHashTransactionInput.js +2 -2
  89. package/lib/startUntrustedHashTransactionInput.js.map +1 -1
  90. package/lib/varint.d.ts.map +1 -1
  91. package/lib/varint.js +1 -0
  92. package/lib/varint.js.map +1 -1
  93. package/lib-es/Btc.d.ts +7 -3
  94. package/lib-es/Btc.d.ts.map +1 -1
  95. package/lib-es/Btc.js +92 -26
  96. package/lib-es/Btc.js.map +1 -1
  97. package/lib-es/BtcNew.d.ts +70 -0
  98. package/lib-es/BtcNew.d.ts.map +1 -0
  99. package/lib-es/BtcNew.js +370 -0
  100. package/lib-es/BtcNew.js.map +1 -0
  101. package/lib-es/BtcOld.d.ts +114 -0
  102. package/lib-es/BtcOld.d.ts.map +1 -0
  103. package/lib-es/BtcOld.js +136 -0
  104. package/lib-es/BtcOld.js.map +1 -0
  105. package/lib-es/bip32.d.ts +8 -0
  106. package/lib-es/bip32.d.ts.map +1 -1
  107. package/lib-es/bip32.js +26 -2
  108. package/lib-es/bip32.js.map +1 -1
  109. package/lib-es/buffertools.d.ts +28 -0
  110. package/lib-es/buffertools.d.ts.map +1 -0
  111. package/lib-es/buffertools.js +94 -0
  112. package/lib-es/buffertools.js.map +1 -0
  113. package/lib-es/createTransaction.d.ts.map +1 -1
  114. package/lib-es/getWalletPublicKey.d.ts +1 -1
  115. package/lib-es/getWalletPublicKey.d.ts.map +1 -1
  116. package/lib-es/getWalletPublicKey.js.map +1 -1
  117. package/lib-es/hashPublicKey.d.ts +1 -1
  118. package/lib-es/hashPublicKey.d.ts.map +1 -1
  119. package/lib-es/index.d.ts +3 -0
  120. package/lib-es/index.d.ts.map +1 -0
  121. package/lib-es/index.js +3 -0
  122. package/lib-es/index.js.map +1 -0
  123. package/lib-es/newops/appClient.d.ts +14 -0
  124. package/lib-es/newops/appClient.d.ts.map +1 -0
  125. package/lib-es/newops/appClient.js +239 -0
  126. package/lib-es/newops/appClient.js.map +1 -0
  127. package/lib-es/newops/clientCommands.d.ts +61 -0
  128. package/lib-es/newops/clientCommands.d.ts.map +1 -0
  129. package/lib-es/newops/clientCommands.js +328 -0
  130. package/lib-es/newops/clientCommands.js.map +1 -0
  131. package/lib-es/newops/merkelizedPsbt.d.ts +15 -0
  132. package/lib-es/newops/merkelizedPsbt.d.ts.map +1 -0
  133. package/lib-es/newops/merkelizedPsbt.js +88 -0
  134. package/lib-es/newops/merkelizedPsbt.js.map +1 -0
  135. package/lib-es/newops/merkle.d.ts +29 -0
  136. package/lib-es/newops/merkle.d.ts.map +1 -0
  137. package/lib-es/newops/merkle.js +129 -0
  138. package/lib-es/newops/merkle.js.map +1 -0
  139. package/lib-es/newops/merkleMap.d.ts +15 -0
  140. package/lib-es/newops/merkleMap.d.ts.map +1 -0
  141. package/lib-es/newops/merkleMap.js +34 -0
  142. package/lib-es/newops/merkleMap.js.map +1 -0
  143. package/lib-es/newops/policy.d.ts +14 -0
  144. package/lib-es/newops/policy.d.ts.map +1 -0
  145. package/lib-es/newops/policy.js +36 -0
  146. package/lib-es/newops/policy.js.map +1 -0
  147. package/lib-es/newops/psbtExtractor.d.ts +4 -0
  148. package/lib-es/newops/psbtExtractor.d.ts.map +1 -0
  149. package/lib-es/newops/psbtExtractor.js +32 -0
  150. package/lib-es/newops/psbtExtractor.js.map +1 -0
  151. package/lib-es/newops/psbtFinalizer.d.ts +7 -0
  152. package/lib-es/newops/psbtFinalizer.d.ts.map +1 -0
  153. package/lib-es/newops/psbtFinalizer.js +107 -0
  154. package/lib-es/newops/psbtFinalizer.js.map +1 -0
  155. package/lib-es/newops/psbtv2.d.ts +129 -0
  156. package/lib-es/newops/psbtv2.d.ts.map +1 -0
  157. package/lib-es/newops/psbtv2.js +475 -0
  158. package/lib-es/newops/psbtv2.js.map +1 -0
  159. package/lib-es/varint.d.ts.map +1 -1
  160. package/lib-es/varint.js +1 -0
  161. package/lib-es/varint.js.map +1 -1
  162. package/package.json +7 -4
  163. package/src/Btc.ts +42 -25
  164. package/src/BtcNew.ts +326 -0
  165. package/src/BtcOld.ts +156 -0
  166. package/src/bip32.ts +34 -2
  167. package/src/buffertools.ts +102 -0
  168. package/src/createTransaction.ts +2 -2
  169. package/src/getWalletPublicKey.ts +6 -1
  170. package/src/hashPublicKey.ts +1 -1
  171. package/src/index.ts +2 -0
  172. package/src/newops/appClient.ts +178 -0
  173. package/src/newops/clientCommands.ts +312 -0
  174. package/src/newops/merkelizedPsbt.ts +55 -0
  175. package/src/newops/merkle.ts +123 -0
  176. package/src/newops/merkleMap.ts +39 -0
  177. package/src/newops/policy.ts +52 -0
  178. package/src/newops/psbtExtractor.ts +33 -0
  179. package/src/newops/psbtFinalizer.ts +110 -0
  180. package/src/newops/psbtv2.ts +548 -0
  181. package/src/varint.ts +2 -0
  182. package/tests/Btc.integration.test.ts +89 -0
  183. package/tests/Btc.test.ts +6 -0
  184. package/tests/newops/BtcNew.test.ts +646 -0
  185. package/tests/newops/common.ts +25 -0
  186. package/tests/newops/merkle.test.ts +97 -0
  187. package/tests/trustedInputs.test.ts +4 -0
package/src/Btc.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import type Transport from "@ledgerhq/hw-transport";
2
- import { signMessage } from "./signMessage";
3
- import { getWalletPublicKey } from "./getWalletPublicKey";
4
- import type { AddressFormat } from "./getWalletPublicKey";
5
- import { splitTransaction } from "./splitTransaction";
2
+ import semver from "semver";
3
+ import BtcNew from "./BtcNew";
4
+ import BtcOld from "./BtcOld";
5
+ import type { CreateTransactionArg } from "./createTransaction";
6
+ import { getAppAndVersion } from "./getAppAndVersion";
6
7
  import { getTrustedInput } from "./getTrustedInput";
7
8
  import { getTrustedInputBIP143 } from "./getTrustedInputBIP143";
8
- import type { Transaction } from "./types";
9
- import { createTransaction } from "./createTransaction";
10
- import type { CreateTransactionArg } from "./createTransaction";
11
- import { signP2SHTransaction } from "./signP2SHTransaction";
12
- import type { SignP2SHTransactionArg } from "./signP2SHTransaction";
9
+ import type { AddressFormat } from "./getWalletPublicKey";
10
+ import { AppClient } from "./newops/appClient";
13
11
  import { serializeTransactionOutputs } from "./serializeTransaction";
12
+ import type { SignP2SHTransactionArg } from "./signP2SHTransaction";
13
+ import { splitTransaction } from "./splitTransaction";
14
+ import type { Transaction } from "./types";
14
15
  export type { AddressFormat };
15
16
  /**
16
17
  * Bitcoin API.
@@ -45,7 +46,7 @@ export default class Btc {
45
46
  *
46
47
  * - verify (boolean) will ask user to confirm the address on the device
47
48
  *
48
- * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter.
49
+ * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter.
49
50
  *
50
51
  * NB The normal usage is to use:
51
52
  *
@@ -85,8 +86,9 @@ export default class Btc {
85
86
  } else {
86
87
  options = opts || {};
87
88
  }
88
-
89
- return getWalletPublicKey(this.transport, { ...options, path });
89
+ return this.getCorrectImpl().then((impl) => {
90
+ return impl.getWalletPublicKey(path, options);
91
+ });
90
92
  }
91
93
 
92
94
  /**
@@ -106,10 +108,7 @@ export default class Btc {
106
108
  r: string;
107
109
  s: string;
108
110
  }> {
109
- return signMessage(this.transport, {
110
- path,
111
- messageHex,
112
- });
111
+ return this.old().signMessageNew(path, messageHex);
113
112
  }
114
113
 
115
114
  /**
@@ -150,8 +149,9 @@ export default class Btc {
150
149
  "@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."
151
150
  );
152
151
  }
153
-
154
- return createTransaction(this.transport, arg);
152
+ return this.getCorrectImpl().then((impl) => {
153
+ return impl.createPaymentTransactionNew(arg);
154
+ });
155
155
  }
156
156
 
157
157
  /**
@@ -174,13 +174,7 @@ export default class Btc {
174
174
  }).then(result => ...);
175
175
  */
176
176
  signP2SHTransaction(arg: SignP2SHTransactionArg): Promise<string[]> {
177
- if (arguments.length > 1) {
178
- console.warn(
179
- "@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."
180
- );
181
- }
182
-
183
- return signP2SHTransaction(this.transport, arg);
177
+ return this.old().signP2SHTransaction(arg);
184
178
  }
185
179
 
186
180
  /**
@@ -238,4 +232,27 @@ export default class Btc {
238
232
  additionals
239
233
  );
240
234
  }
235
+
236
+ private async getCorrectImpl(): Promise<BtcOld | BtcNew> {
237
+ const isNewApp = await this.useNewApp();
238
+ if (isNewApp) {
239
+ return this.new();
240
+ } else {
241
+ return this.old();
242
+ }
243
+ }
244
+ private old(): BtcOld {
245
+ return new BtcOld(this.transport);
246
+ }
247
+ private new(): BtcNew {
248
+ return new BtcNew(new AppClient(this.transport));
249
+ }
250
+ private async useNewApp(): Promise<boolean> {
251
+ const a = await getAppAndVersion(this.transport);
252
+ const isNewApp = semver.major(a.version) >= 2;
253
+ if ((a.name == "Bitcoin" || a.name == "Bitcoin Test") && isNewApp) {
254
+ return true;
255
+ }
256
+ return false;
257
+ }
241
258
  }
package/src/BtcNew.ts ADDED
@@ -0,0 +1,326 @@
1
+ import { crypto } from "bitcoinjs-lib";
2
+ import { getXpubComponents, pathStringToArray, pubkeyFromXpub } from "./bip32";
3
+ import { BufferReader } from "./buffertools";
4
+ import type { CreateTransactionArg } from "./createTransaction";
5
+ import type { AddressFormat } from "./getWalletPublicKey";
6
+ import { hashPublicKey } from "./hashPublicKey";
7
+ import { AppClient as Client } from "./newops/appClient";
8
+ import { createKey, WalletPolicy } from "./newops/policy";
9
+ import { extract } from "./newops/psbtExtractor";
10
+ import { finalize } from "./newops/psbtFinalizer";
11
+ import { psbtIn, PsbtV2 } from "./newops/psbtv2";
12
+ import { serializeTransaction } from "./serializeTransaction";
13
+ import type { Transaction } from "./types";
14
+ import { pointCompress } from "tiny-secp256k1";
15
+
16
+ export default class BtcNew {
17
+ constructor(private client: Client) {}
18
+
19
+ async getWalletPublicKey(
20
+ path: string,
21
+ opts?: {
22
+ verify?: boolean;
23
+ format?: AddressFormat;
24
+ }
25
+ ): Promise<{
26
+ publicKey: string;
27
+ bitcoinAddress: string;
28
+ chainCode: string;
29
+ }> {
30
+ const pathElements: number[] = pathStringToArray(path);
31
+ const xpub = await this.client.getPubkey(false, pathElements);
32
+
33
+ const display = opts?.verify ?? false;
34
+
35
+ const address = await this.getWalletAddress(
36
+ pathElements,
37
+ accountTypeFrom(opts?.format ?? "legacy"),
38
+ display
39
+ );
40
+ const components = getXpubComponents(xpub);
41
+ const uncompressedPubkey = Buffer.from(
42
+ pointCompress(components.pubkey, false)
43
+ );
44
+ return {
45
+ publicKey: uncompressedPubkey.toString("hex"),
46
+ bitcoinAddress: address,
47
+ chainCode: components.chaincode.toString("hex"),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Get an address for the specified path.
53
+ *
54
+ * If display is true, we must get the address from the device, which would require
55
+ * us to determine WalletPolicy. This requires two *extra* queries to the device, one
56
+ * for the account xpub and one for master key fingerprint.
57
+ *
58
+ * If display is false we *could* generate the address ourselves, but chose to
59
+ * get it from the device to save development time. However, it shouldn't take
60
+ * more than a few hours to implement local address generation.
61
+ *
62
+ * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no
63
+ * way to get the address from the device. In this case we have to create it
64
+ * ourselves, but we don't at this time, and instead return an empty ("") address.
65
+ */
66
+ private async getWalletAddress(
67
+ pathElements: number[],
68
+ accountType: AccountType,
69
+ display: boolean
70
+ ): Promise<string> {
71
+ const accountPathLength = this.accountPathLength(pathElements);
72
+ if (accountPathLength + 2 != pathElements.length) {
73
+ return "";
74
+ }
75
+ const accountPath = pathElements.slice(0, accountPathLength);
76
+ const accountXpub = await this.client.getPubkey(false, accountPath);
77
+ const masterFingerprint = await this.client.getMasterFingerprint();
78
+ const policy = new WalletPolicy(
79
+ accountType,
80
+ createKey(masterFingerprint, accountPath, accountXpub)
81
+ );
82
+ const changeAndIndex = pathElements.slice(-2, pathElements.length);
83
+ return this.client.getWalletAddress(
84
+ policy,
85
+ Buffer.alloc(32, 0),
86
+ changeAndIndex[0],
87
+ changeAndIndex[1],
88
+ display
89
+ );
90
+ }
91
+
92
+ private accountPathLength(pathElements: number[]): number {
93
+ for (let i = pathElements.length - 1; i >= 0; i--) {
94
+ if (pathElements[i] >= 0x80000000) {
95
+ return i + 1;
96
+ }
97
+ }
98
+ return 0;
99
+ }
100
+
101
+ /**
102
+ * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters
103
+ * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where
104
+ *
105
+ * * transaction is the previously computed transaction object for this UTXO
106
+ * * output_index is the output in the transaction used as input for this UTXO (counting from 0)
107
+ * * redeem script is the optional redeem script to use when consuming a Segregated Witness input
108
+ * * sequence is the sequence number to use for this input (when using RBF), or non present
109
+ * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
110
+ * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address
111
+ * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount
112
+ * @param lockTime is the optional lockTime of the transaction to sign, or default (0)
113
+ * @param sigHashType is the hash type of the transaction to sign, or default (all)
114
+ * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit.
115
+ * @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)
116
+ * @param additionals list of additionnal options
117
+ *
118
+ * - "bech32" for spending native segwit outputs
119
+ * - "bech32m" for spending segwit v1+ outptus
120
+ * - "abc" for bch
121
+ * - "gold" for btg
122
+ * - "bipxxx" for using BIPxxx
123
+ * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
124
+ * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs
125
+ * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true.
126
+ * @return the signed transaction ready to be broadcast
127
+ * @example
128
+ btc.createTransaction({
129
+ inputs: [ [tx1, 1] ],
130
+ associatedKeysets: ["0'/0/0"],
131
+ outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
132
+ }).then(res => ...);
133
+ */
134
+ async createPaymentTransactionNew(
135
+ arg: CreateTransactionArg
136
+ ): Promise<string> {
137
+ if (arg.inputs.length == 0) {
138
+ throw Error("No inputs");
139
+ }
140
+ const psbt = new PsbtV2();
141
+
142
+ const accountType = accountTypeFromArg(arg);
143
+
144
+ psbt.setGlobalTxVersion(2);
145
+ if (arg.lockTime) {
146
+ psbt.setGlobalFallbackLocktime(arg.lockTime);
147
+ }
148
+ psbt.setGlobalInputCount(arg.inputs.length);
149
+ psbt.setGlobalPsbtVersion(2);
150
+ psbt.setGlobalTxVersion(2);
151
+
152
+ const masterFp = await this.client.getMasterFingerprint();
153
+ let accountXpub = "";
154
+ let accountPath: number[] = [];
155
+ for (let i = 0; i < arg.inputs.length; i++) {
156
+ const pathElems: number[] = pathStringToArray(arg.associatedKeysets[i]);
157
+ if (accountXpub == "") {
158
+ // We assume all inputs belong to the same account so we set
159
+ // the account xpub and path based on the first input.
160
+ accountPath = pathElems.slice(0, -2);
161
+ accountXpub = await this.client.getPubkey(false, accountPath);
162
+ }
163
+ await this.setInput(
164
+ psbt,
165
+ i,
166
+ arg.inputs[i],
167
+ pathElems,
168
+ accountType,
169
+ masterFp
170
+ );
171
+ }
172
+
173
+ const outputsConcat = Buffer.from(arg.outputScriptHex, "hex");
174
+ const outputsBufferReader = new BufferReader(outputsConcat);
175
+ const outputCount = outputsBufferReader.readVarInt();
176
+ psbt.setGlobalOutputCount(outputCount);
177
+ for (let i = 0; i < outputCount; i++) {
178
+ const amount = Number(outputsBufferReader.readUInt64());
179
+ const outputScript = outputsBufferReader.readVarSlice();
180
+
181
+ // The wallet always places the change output last.
182
+ // But we won't know if we're paying to ourselves, because
183
+ // we'd have one output at index <outputCount-1 for ourselves
184
+ // and one change output.
185
+ const isChange = arg.changePath && i == outputCount - 1;
186
+ if (isChange) {
187
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
188
+ const changePath = pathStringToArray(arg.changePath!);
189
+ const xpubBase58 = await this.client.getPubkey(false, changePath);
190
+ const pubkey = pubkeyFromXpub(xpubBase58);
191
+
192
+ if (accountType == AccountType.p2pkh) {
193
+ psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
194
+ } else if (accountType == AccountType.p2wpkh) {
195
+ psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
196
+ } else if (accountType == AccountType.p2wpkhWrapped) {
197
+ const redeemScript = this.createRedeemScript(pubkey);
198
+ psbt.setOutputRedeemScript(i, redeemScript);
199
+ psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
200
+ } else if (accountType == AccountType.p2tr) {
201
+ psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath);
202
+ }
203
+ }
204
+ psbt.setOutputAmount(i, amount);
205
+ psbt.setOutputScript(i, outputScript);
206
+ }
207
+
208
+ const key = createKey(masterFp, accountPath, accountXpub);
209
+ const p = new WalletPolicy(accountType, key);
210
+ return await this.signPsbt(psbt, p);
211
+ }
212
+
213
+ private async setInput(
214
+ psbt: PsbtV2,
215
+ i: number,
216
+ input: [
217
+ Transaction,
218
+ number,
219
+ string | null | undefined,
220
+ number | null | undefined
221
+ ],
222
+ pathElements: number[],
223
+ accountType: AccountType,
224
+ masterFP: Buffer
225
+ ): Promise<void> {
226
+ const inputTx = input[0];
227
+ const spentOutputIndex = input[1];
228
+ const redeemScript = input[2];
229
+ const sequence = input[3];
230
+ if (sequence) {
231
+ psbt.setInputSequence(i, sequence);
232
+ }
233
+ const inputTxBuffer = serializeTransaction(inputTx, true);
234
+ const inputTxid = crypto.hash256(inputTxBuffer);
235
+ const xpubBase58 = await this.client.getPubkey(false, pathElements);
236
+
237
+ const pubkey = pubkeyFromXpub(xpubBase58);
238
+ if (!inputTx.outputs)
239
+ throw Error("Missing outputs array in transaction to sign");
240
+ const spentOutput = inputTx.outputs[spentOutputIndex];
241
+
242
+ if (accountType == AccountType.p2pkh) {
243
+ psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
244
+ psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
245
+ } else if (accountType == AccountType.p2wpkh) {
246
+ psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
247
+ psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
248
+ psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
249
+ } else if (accountType == AccountType.p2wpkhWrapped) {
250
+ psbt.setInputNonWitnessUtxo(i, inputTxBuffer);
251
+ psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements);
252
+ if (!redeemScript) {
253
+ throw new Error("Missing redeemScript for p2wpkhWrapped input");
254
+ }
255
+ const expectedRedeemScript = this.createRedeemScript(pubkey);
256
+ if (redeemScript != expectedRedeemScript.toString("hex")) {
257
+ throw new Error("Unexpected redeemScript");
258
+ }
259
+ psbt.setInputRedeemScript(i, expectedRedeemScript);
260
+ psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
261
+ } else if (accountType == AccountType.p2tr) {
262
+ psbt.setInputTapBip32Derivation(i, pubkey, [], masterFP, pathElements);
263
+ psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
264
+ }
265
+
266
+ psbt.setInputPreviousTxId(i, inputTxid);
267
+ psbt.setInputOutputIndex(i, spentOutputIndex);
268
+ }
269
+
270
+ private async signPsbt(
271
+ psbt: PsbtV2,
272
+ walletPolicy: WalletPolicy
273
+ ): Promise<string> {
274
+ const sigs: Map<number, Buffer> = await this.client.signPsbt(
275
+ psbt,
276
+ walletPolicy,
277
+ Buffer.alloc(32, 0)
278
+ );
279
+ sigs.forEach((v, k) => {
280
+ // Note: Looking at BIP32 derivation does not work in the generic case.
281
+ // some inputs might not have a BIP32-derived pubkey.
282
+ const pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION);
283
+ let pubkey;
284
+ if (pubkeys.length != 1) {
285
+ pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION);
286
+ if (pubkey.length == 0) {
287
+ throw Error(`Missing pubkey derivation for input ${k}`);
288
+ }
289
+ psbt.setInputTapKeySig(k, v);
290
+ } else {
291
+ pubkey = pubkeys[0];
292
+ psbt.setInputPartialSig(k, pubkey, v);
293
+ }
294
+ });
295
+ finalize(psbt);
296
+ const serializedTx = extract(psbt);
297
+ return serializedTx.toString("hex");
298
+ }
299
+
300
+ private createRedeemScript(pubkey: Buffer): Buffer {
301
+ const pubkeyHash = hashPublicKey(pubkey);
302
+ return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]);
303
+ }
304
+ }
305
+
306
+ enum AccountType {
307
+ p2pkh = "pkh(@0)",
308
+ p2wpkh = "wpkh(@0)",
309
+ p2wpkhWrapped = "sh(wpkh(@0))",
310
+ p2tr = "tr(@0)",
311
+ }
312
+
313
+ function accountTypeFrom(addressFormat: AddressFormat): AccountType {
314
+ if (addressFormat == "legacy") return AccountType.p2pkh;
315
+ if (addressFormat == "p2sh") return AccountType.p2wpkhWrapped;
316
+ if (addressFormat == "bech32") return AccountType.p2wpkh;
317
+ if (addressFormat == "bech32m") return AccountType.p2tr;
318
+ throw new Error("Unsupported address format " + addressFormat);
319
+ }
320
+
321
+ function accountTypeFromArg(arg: CreateTransactionArg): AccountType {
322
+ if (arg.additionals.includes("bech32m")) return AccountType.p2tr;
323
+ if (arg.additionals.includes("bech32")) return AccountType.p2wpkh;
324
+ if (arg.segwit) return AccountType.p2wpkhWrapped;
325
+ return AccountType.p2pkh;
326
+ }
package/src/BtcOld.ts ADDED
@@ -0,0 +1,156 @@
1
+ import type Transport from "@ledgerhq/hw-transport";
2
+ import type { CreateTransactionArg } from "./createTransaction";
3
+ import { createTransaction } from "./createTransaction";
4
+ import type { AddressFormat } from "./getWalletPublicKey";
5
+ import { getWalletPublicKey } from "./getWalletPublicKey";
6
+ import { signMessage } from "./signMessage";
7
+ import type { SignP2SHTransactionArg } from "./signP2SHTransaction";
8
+ import { signP2SHTransaction } from "./signP2SHTransaction";
9
+ export type { AddressFormat };
10
+ /**
11
+ * Bitcoin API.
12
+ *
13
+ * @example
14
+ * import Btc from "@ledgerhq/hw-app-btc";
15
+ * const btc = new Btc(transport)
16
+ */
17
+
18
+ export default class BtcOld {
19
+ transport: Transport;
20
+
21
+ constructor(transport: Transport) {
22
+ this.transport = transport;
23
+ }
24
+
25
+ /**
26
+ * @param path a BIP 32 path
27
+ * @param options an object with optional these fields:
28
+ *
29
+ * - verify (boolean) will ask user to confirm the address on the device
30
+ *
31
+ * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter.
32
+ *
33
+ * NB The normal usage is to use:
34
+ *
35
+ * - legacy format with 44' paths
36
+ *
37
+ * - p2sh format with 49' paths
38
+ *
39
+ * - bech32 format with 173' paths
40
+ *
41
+ * - cashaddr in case of Bitcoin Cash
42
+ *
43
+ * @example
44
+ * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress)
45
+ * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress)
46
+ */
47
+ getWalletPublicKey(
48
+ path: string,
49
+ opts?: {
50
+ verify?: boolean;
51
+ format?: AddressFormat;
52
+ }
53
+ ): Promise<{
54
+ publicKey: string;
55
+ bitcoinAddress: string;
56
+ chainCode: string;
57
+ }> {
58
+ if (opts?.format === "bech32m") {
59
+ throw new Error("Unsupported address format bech32m");
60
+ }
61
+ return getWalletPublicKey(this.transport, { ...opts, path });
62
+ }
63
+
64
+ /**
65
+ * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign.
66
+ * @example
67
+ btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) {
68
+ var v = result['v'] + 27 + 4;
69
+ var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64');
70
+ console.log("Signature : " + signature);
71
+ }).catch(function(ex) {console.log(ex);});
72
+ */
73
+ signMessageNew(
74
+ path: string,
75
+ messageHex: string
76
+ ): Promise<{
77
+ v: number;
78
+ r: string;
79
+ s: string;
80
+ }> {
81
+ return signMessage(this.transport, {
82
+ path,
83
+ messageHex,
84
+ });
85
+ }
86
+
87
+ /**
88
+ * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters
89
+ * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where
90
+ *
91
+ * * transaction is the previously computed transaction object for this UTXO
92
+ * * output_index is the output in the transaction used as input for this UTXO (counting from 0)
93
+ * * redeem script is the optional redeem script to use when consuming a Segregated Witness input
94
+ * * sequence is the sequence number to use for this input (when using RBF), or non present
95
+ * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
96
+ * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address
97
+ * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign
98
+ * @param lockTime is the optional lockTime of the transaction to sign, or default (0)
99
+ * @param sigHashType is the hash type of the transaction to sign, or default (all)
100
+ * @param segwit is an optional boolean indicating wether to use segwit or not
101
+ * @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)
102
+ * @param additionals list of additionnal options
103
+ *
104
+ * - "bech32" for spending native segwit outputs
105
+ * - "abc" for bch
106
+ * - "gold" for btg
107
+ * - "bipxxx" for using BIPxxx
108
+ * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
109
+ * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs
110
+ * @param useTrustedInputForSegwit trust inputs for segwit transactions
111
+ * @return the signed transaction ready to be broadcast
112
+ * @example
113
+ btc.createTransaction({
114
+ inputs: [ [tx1, 1] ],
115
+ associatedKeysets: ["0'/0/0"],
116
+ outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
117
+ }).then(res => ...);
118
+ */
119
+ createPaymentTransactionNew(arg: CreateTransactionArg): Promise<string> {
120
+ if (arguments.length > 1) {
121
+ console.warn(
122
+ "@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."
123
+ );
124
+ }
125
+ return createTransaction(this.transport, arg);
126
+ }
127
+
128
+ /**
129
+ * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters
130
+ * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where
131
+ * * transaction is the previously computed transaction object for this UTXO
132
+ * * output_index is the output in the transaction used as input for this UTXO (counting from 0)
133
+ * * redeem script is the mandatory redeem script associated to the current P2SH input
134
+ * * sequence is the sequence number to use for this input (when using RBF), or non present
135
+ * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
136
+ * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign
137
+ * @param lockTime is the optional lockTime of the transaction to sign, or default (0)
138
+ * @param sigHashType is the hash type of the transaction to sign, or default (all)
139
+ * @return the signed transaction ready to be broadcast
140
+ * @example
141
+ btc.signP2SHTransaction({
142
+ inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ],
143
+ associatedKeysets: ["0'/0/0"],
144
+ outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
145
+ }).then(result => ...);
146
+ */
147
+ signP2SHTransaction(arg: SignP2SHTransactionArg): Promise<string[]> {
148
+ if (arguments.length > 1) {
149
+ console.warn(
150
+ "@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."
151
+ );
152
+ }
153
+
154
+ return signP2SHTransaction(this.transport, arg);
155
+ }
156
+ }
package/src/bip32.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import bippath from "bip32-path";
2
- export function bip32asBuffer(path: string): Buffer {
3
- const paths = !path ? [] : bippath.fromString(path).toPathArray();
2
+ import bs58check from "bs58check";
3
+
4
+ export function pathElementsToBuffer(paths: number[]): Buffer {
4
5
  const buffer = Buffer.alloc(1 + paths.length * 4);
5
6
  buffer[0] = paths.length;
6
7
  paths.forEach((element, index) => {
@@ -8,3 +9,34 @@ export function bip32asBuffer(path: string): Buffer {
8
9
  });
9
10
  return buffer;
10
11
  }
12
+
13
+ export function bip32asBuffer(path: string): Buffer {
14
+ const pathElements = !path ? [] : pathStringToArray(path);
15
+ return pathElementsToBuffer(pathElements);
16
+ }
17
+
18
+ export function pathArrayToString(pathElements: number[]): string {
19
+ // Limitation: bippath can't handle and empty path. It shouldn't affect us
20
+ // right now, but might in the future.
21
+ // TODO: Fix support for empty path.
22
+ return bippath.fromPathArray(pathElements).toString();
23
+ }
24
+
25
+ export function pathStringToArray(path: string): number[] {
26
+ return bippath.fromString(path).toPathArray();
27
+ }
28
+
29
+ export function pubkeyFromXpub(xpub: string): Buffer {
30
+ const xpubBuf = bs58check.decode(xpub);
31
+ return xpubBuf.slice(xpubBuf.length - 33);
32
+ }
33
+
34
+ export function getXpubComponents(
35
+ xpub: string
36
+ ): { chaincode: Buffer; pubkey: Buffer } {
37
+ const xpubBuf = bs58check.decode(xpub);
38
+ return {
39
+ chaincode: xpubBuf.slice(13, 13 + 32),
40
+ pubkey: xpubBuf.slice(xpubBuf.length - 33),
41
+ };
42
+ }