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