@ledgerhq/hw-app-btc 6.10.0 → 6.12.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.
- package/README.md +384 -60
- package/lib/Btc.d.ts +9 -6
- package/lib/Btc.d.ts.map +1 -1
- package/lib/Btc.js +73 -8
- package/lib/Btc.js.map +1 -1
- package/lib/BtcNew.d.ts +79 -32
- package/lib/BtcNew.d.ts.map +1 -1
- package/lib/BtcNew.js +168 -207
- package/lib/BtcNew.js.map +1 -1
- package/lib/newops/accounttype.d.ts +110 -0
- package/lib/newops/accounttype.d.ts.map +1 -0
- package/lib/newops/accounttype.js +233 -0
- package/lib/newops/accounttype.js.map +1 -0
- package/lib/newops/appClient.d.ts +6 -2
- package/lib/newops/appClient.d.ts.map +1 -1
- package/lib/newops/appClient.js +8 -4
- 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 +34 -12
- 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 +26 -1
- 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 +33 -8
- package/lib/newops/psbtv2.js.map +1 -1
- package/lib-es/Btc.d.ts +9 -6
- package/lib-es/Btc.d.ts.map +1 -1
- package/lib-es/Btc.js +73 -8
- package/lib-es/Btc.js.map +1 -1
- package/lib-es/BtcNew.d.ts +79 -32
- package/lib-es/BtcNew.d.ts.map +1 -1
- package/lib-es/BtcNew.js +170 -209
- package/lib-es/BtcNew.js.map +1 -1
- package/lib-es/newops/accounttype.d.ts +110 -0
- package/lib-es/newops/accounttype.d.ts.map +1 -0
- package/lib-es/newops/accounttype.js +230 -0
- package/lib-es/newops/accounttype.js.map +1 -0
- 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 +8 -4
- 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 +34 -12
- 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 +26 -1
- 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 +33 -8
- package/lib-es/newops/psbtv2.js.map +1 -1
- package/package.json +3 -3
- package/src/Btc.ts +111 -9
- package/src/BtcNew.ts +204 -209
- package/src/newops/accounttype.ts +370 -0
- package/src/newops/appClient.ts +12 -4
- package/src/newops/clientCommands.ts +34 -12
- 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 +26 -1
- package/src/newops/psbtv2.ts +34 -14
- package/tests/Btc.test.ts +89 -0
- package/tests/newops/BtcNew.test.ts +48 -21
- package/tests/newops/integrationtools.ts +47 -36
- package/tests/newops/testtx.ts +0 -55
package/src/BtcNew.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { crypto } from "bitcoinjs-lib";
|
|
2
|
-
import { pointCompress, pointAddScalar } from "tiny-secp256k1";
|
|
3
2
|
import semver from "semver";
|
|
3
|
+
import { pointCompress } from "tiny-secp256k1";
|
|
4
4
|
import {
|
|
5
5
|
getXpubComponents,
|
|
6
6
|
hardenedPathOf,
|
|
@@ -8,26 +8,29 @@ import {
|
|
|
8
8
|
pathStringToArray,
|
|
9
9
|
pubkeyFromXpub,
|
|
10
10
|
} from "./bip32";
|
|
11
|
-
import { BufferReader
|
|
11
|
+
import { BufferReader } from "./buffertools";
|
|
12
12
|
import type { CreateTransactionArg } from "./createTransaction";
|
|
13
|
+
import { AppAndVersion } from "./getAppAndVersion";
|
|
13
14
|
import type { AddressFormat } from "./getWalletPublicKey";
|
|
14
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
AccountType,
|
|
17
|
+
p2pkh,
|
|
18
|
+
p2tr,
|
|
19
|
+
p2wpkh,
|
|
20
|
+
p2wpkhWrapped,
|
|
21
|
+
SpendingCondition,
|
|
22
|
+
} from "./newops/accounttype";
|
|
15
23
|
import { AppClient as Client } from "./newops/appClient";
|
|
16
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
createKey,
|
|
26
|
+
DefaultDescriptorTemplate,
|
|
27
|
+
WalletPolicy,
|
|
28
|
+
} from "./newops/policy";
|
|
17
29
|
import { extract } from "./newops/psbtExtractor";
|
|
18
30
|
import { finalize } from "./newops/psbtFinalizer";
|
|
19
31
|
import { psbtIn, PsbtV2 } from "./newops/psbtv2";
|
|
20
32
|
import { serializeTransaction } from "./serializeTransaction";
|
|
21
33
|
import type { Transaction } from "./types";
|
|
22
|
-
import {
|
|
23
|
-
HASH_SIZE,
|
|
24
|
-
OP_CHECKSIG,
|
|
25
|
-
OP_DUP,
|
|
26
|
-
OP_EQUAL,
|
|
27
|
-
OP_EQUALVERIFY,
|
|
28
|
-
OP_HASH160,
|
|
29
|
-
} from "./constants";
|
|
30
|
-
import { AppAndVersion } from "./getAppAndVersion";
|
|
31
34
|
|
|
32
35
|
const newSupportedApps = ["Bitcoin", "Bitcoin Test"];
|
|
33
36
|
|
|
@@ -38,9 +41,52 @@ export function canSupportApp(appAndVersion: AppAndVersion): boolean {
|
|
|
38
41
|
);
|
|
39
42
|
}
|
|
40
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
|
+
*/
|
|
41
57
|
export default class BtcNew {
|
|
42
58
|
constructor(private client: Client) {}
|
|
43
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
|
+
*/
|
|
44
90
|
async getWalletXpub({
|
|
45
91
|
path,
|
|
46
92
|
xpubVersion,
|
|
@@ -49,7 +95,7 @@ export default class BtcNew {
|
|
|
49
95
|
xpubVersion: number;
|
|
50
96
|
}): Promise<string> {
|
|
51
97
|
const pathElements: number[] = pathStringToArray(path);
|
|
52
|
-
const xpub = await this.client.
|
|
98
|
+
const xpub = await this.client.getExtendedPubkey(false, pathElements);
|
|
53
99
|
const xpubComponents = getXpubComponents(xpub);
|
|
54
100
|
if (xpubComponents.version != xpubVersion) {
|
|
55
101
|
throw new Error(
|
|
@@ -59,6 +105,13 @@ export default class BtcNew {
|
|
|
59
105
|
return xpub;
|
|
60
106
|
}
|
|
61
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
|
+
*/
|
|
62
115
|
async getWalletPublicKey(
|
|
63
116
|
path: string,
|
|
64
117
|
opts?: {
|
|
@@ -71,13 +124,13 @@ export default class BtcNew {
|
|
|
71
124
|
chainCode: string;
|
|
72
125
|
}> {
|
|
73
126
|
const pathElements: number[] = pathStringToArray(path);
|
|
74
|
-
const xpub = await this.client.
|
|
127
|
+
const xpub = await this.client.getExtendedPubkey(false, pathElements);
|
|
75
128
|
|
|
76
129
|
const display = opts?.verify ?? false;
|
|
77
130
|
|
|
78
131
|
const address = await this.getWalletAddress(
|
|
79
132
|
pathElements,
|
|
80
|
-
|
|
133
|
+
descrTemplFrom(opts?.format ?? "legacy"),
|
|
81
134
|
display
|
|
82
135
|
);
|
|
83
136
|
const components = getXpubComponents(xpub);
|
|
@@ -100,7 +153,7 @@ export default class BtcNew {
|
|
|
100
153
|
*
|
|
101
154
|
* If display is false we *could* generate the address ourselves, but chose to
|
|
102
155
|
* get it from the device to save development time. However, it shouldn't take
|
|
103
|
-
*
|
|
156
|
+
* too much time to implement local address generation.
|
|
104
157
|
*
|
|
105
158
|
* Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no
|
|
106
159
|
* way to get the address from the device. In this case we have to create it
|
|
@@ -108,17 +161,17 @@ export default class BtcNew {
|
|
|
108
161
|
*/
|
|
109
162
|
private async getWalletAddress(
|
|
110
163
|
pathElements: number[],
|
|
111
|
-
|
|
164
|
+
descrTempl: DefaultDescriptorTemplate,
|
|
112
165
|
display: boolean
|
|
113
166
|
): Promise<string> {
|
|
114
167
|
const accountPath = hardenedPathOf(pathElements);
|
|
115
168
|
if (accountPath.length + 2 != pathElements.length) {
|
|
116
169
|
return "";
|
|
117
170
|
}
|
|
118
|
-
const accountXpub = await this.client.
|
|
171
|
+
const accountXpub = await this.client.getExtendedPubkey(false, accountPath);
|
|
119
172
|
const masterFingerprint = await this.client.getMasterFingerprint();
|
|
120
173
|
const policy = new WalletPolicy(
|
|
121
|
-
|
|
174
|
+
descrTempl,
|
|
122
175
|
createKey(masterFingerprint, accountPath, accountXpub)
|
|
123
176
|
);
|
|
124
177
|
const changeAndIndex = pathElements.slice(-2, pathElements.length);
|
|
@@ -132,66 +185,55 @@ export default class BtcNew {
|
|
|
132
185
|
}
|
|
133
186
|
|
|
134
187
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
188
|
+
* Build and sign a transaction. See Btc.createPaymentTransactionNew for
|
|
189
|
+
* details on how to use this method.
|
|
137
190
|
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* * sequence is the sequence number to use for this input (when using RBF), or non present
|
|
142
|
-
* @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
|
|
143
|
-
* @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address
|
|
144
|
-
* @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount
|
|
145
|
-
* @param lockTime is the optional lockTime of the transaction to sign, or default (0)
|
|
146
|
-
* @param sigHashType is the hash type of the transaction to sign, or default (all)
|
|
147
|
-
* @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit.
|
|
148
|
-
* @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)
|
|
149
|
-
* @param additionals list of additionnal options
|
|
150
|
-
*
|
|
151
|
-
* - "bech32" for spending native segwit outputs
|
|
152
|
-
* - "bech32m" for spending segwit v1+ outptus
|
|
153
|
-
* - "abc" for bch
|
|
154
|
-
* - "gold" for btg
|
|
155
|
-
* - "bipxxx" for using BIPxxx
|
|
156
|
-
* - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
|
|
157
|
-
* @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs
|
|
158
|
-
* @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true.
|
|
159
|
-
* @return the signed transaction ready to be broadcast
|
|
160
|
-
* @example
|
|
161
|
-
btc.createTransaction({
|
|
162
|
-
inputs: [ [tx1, 1] ],
|
|
163
|
-
associatedKeysets: ["0'/0/0"],
|
|
164
|
-
outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
|
|
165
|
-
}).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.
|
|
166
194
|
*/
|
|
167
195
|
async createPaymentTransactionNew(
|
|
168
196
|
arg: CreateTransactionArg
|
|
169
197
|
): Promise<string> {
|
|
170
|
-
|
|
198
|
+
const inputCount = arg.inputs.length;
|
|
199
|
+
if (inputCount == 0) {
|
|
171
200
|
throw Error("No inputs");
|
|
172
201
|
}
|
|
173
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();
|
|
174
206
|
|
|
175
|
-
const accountType = accountTypeFromArg(arg);
|
|
207
|
+
const accountType = accountTypeFromArg(arg, psbt, masterFp);
|
|
176
208
|
|
|
177
|
-
psbt.setGlobalTxVersion(2);
|
|
178
209
|
if (arg.lockTime) {
|
|
210
|
+
// The signer will assume locktime 0 if unset
|
|
179
211
|
psbt.setGlobalFallbackLocktime(arg.lockTime);
|
|
180
212
|
}
|
|
181
|
-
psbt.setGlobalInputCount(
|
|
213
|
+
psbt.setGlobalInputCount(inputCount);
|
|
182
214
|
psbt.setGlobalPsbtVersion(2);
|
|
183
215
|
psbt.setGlobalTxVersion(2);
|
|
184
216
|
|
|
185
|
-
|
|
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
|
+
|
|
186
227
|
let accountXpub = "";
|
|
187
228
|
let accountPath: number[] = [];
|
|
188
|
-
for (let i = 0; i <
|
|
229
|
+
for (let i = 0; i < inputCount; i++) {
|
|
230
|
+
progress();
|
|
189
231
|
const pathElems: number[] = pathStringToArray(arg.associatedKeysets[i]);
|
|
190
232
|
if (accountXpub == "") {
|
|
191
233
|
// We assume all inputs belong to the same account so we set
|
|
192
234
|
// the account xpub and path based on the first input.
|
|
193
235
|
accountPath = pathElems.slice(0, -2);
|
|
194
|
-
accountXpub = await this.client.
|
|
236
|
+
accountXpub = await this.client.getExtendedPubkey(false, accountPath);
|
|
195
237
|
}
|
|
196
238
|
await this.setInput(
|
|
197
239
|
psbt,
|
|
@@ -199,70 +241,85 @@ export default class BtcNew {
|
|
|
199
241
|
arg.inputs[i],
|
|
200
242
|
pathElems,
|
|
201
243
|
accountType,
|
|
202
|
-
masterFp
|
|
244
|
+
masterFp,
|
|
245
|
+
arg.sigHashType
|
|
203
246
|
);
|
|
204
247
|
}
|
|
205
248
|
|
|
206
249
|
const outputsConcat = Buffer.from(arg.outputScriptHex, "hex");
|
|
207
250
|
const outputsBufferReader = new BufferReader(outputsConcat);
|
|
208
251
|
const outputCount = outputsBufferReader.readVarInt();
|
|
252
|
+
psbt.setGlobalOutputCount(outputCount);
|
|
209
253
|
const changeData = await this.outputScriptAt(
|
|
210
254
|
accountPath,
|
|
211
255
|
accountType,
|
|
212
256
|
arg.changePath
|
|
213
257
|
);
|
|
214
|
-
|
|
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.
|
|
215
260
|
let changeFound = !changeData;
|
|
216
261
|
for (let i = 0; i < outputCount; i++) {
|
|
217
262
|
const amount = Number(outputsBufferReader.readUInt64());
|
|
218
263
|
const outputScript = outputsBufferReader.readVarSlice();
|
|
264
|
+
psbt.setOutputAmount(i, amount);
|
|
265
|
+
psbt.setOutputScript(i, outputScript);
|
|
219
266
|
|
|
220
|
-
// We won't know if we're paying to ourselves, because
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
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);
|
|
226
272
|
if (isChange) {
|
|
227
273
|
changeFound = true;
|
|
228
274
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
229
275
|
const changePath = pathStringToArray(arg.changePath!);
|
|
230
276
|
const pubkey = changeData.pubkey;
|
|
231
277
|
|
|
232
|
-
|
|
233
|
-
psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
|
|
234
|
-
} else if (accountType == AccountType.p2wpkh) {
|
|
235
|
-
psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
|
|
236
|
-
} else if (accountType == AccountType.p2wpkhWrapped) {
|
|
237
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
238
|
-
psbt.setOutputRedeemScript(i, changeData.redeemScript!);
|
|
239
|
-
psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath);
|
|
240
|
-
} else if (accountType == AccountType.p2tr) {
|
|
241
|
-
psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath);
|
|
242
|
-
}
|
|
278
|
+
accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]);
|
|
243
279
|
}
|
|
244
|
-
psbt.setOutputAmount(i, amount);
|
|
245
|
-
psbt.setOutputScript(i, outputScript);
|
|
246
280
|
}
|
|
247
281
|
if (!changeFound) {
|
|
248
282
|
throw new Error(
|
|
249
283
|
"Change script not found among outputs! " +
|
|
250
|
-
changeData?.
|
|
284
|
+
changeData?.cond.scriptPubKey.toString("hex")
|
|
251
285
|
);
|
|
252
286
|
}
|
|
253
287
|
|
|
254
288
|
const key = createKey(masterFp, accountPath, accountXpub);
|
|
255
|
-
const p = new WalletPolicy(accountType, key);
|
|
256
|
-
|
|
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");
|
|
257
308
|
}
|
|
258
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
|
+
*/
|
|
259
318
|
private async outputScriptAt(
|
|
260
319
|
accountPath: number[],
|
|
261
320
|
accountType: AccountType,
|
|
262
321
|
path: string | undefined
|
|
263
|
-
): Promise<
|
|
264
|
-
{ script: Buffer; redeemScript?: Buffer; pubkey: Buffer } | undefined
|
|
265
|
-
> {
|
|
322
|
+
): Promise<{ cond: SpendingCondition; pubkey: Buffer } | undefined> {
|
|
266
323
|
if (!path) return undefined;
|
|
267
324
|
const pathElems = pathStringToArray(path);
|
|
268
325
|
// Make sure path is in our account, otherwise something fishy is probably
|
|
@@ -274,15 +331,17 @@ export default class BtcNew {
|
|
|
274
331
|
);
|
|
275
332
|
}
|
|
276
333
|
}
|
|
277
|
-
const xpub = await this.client.
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
}
|
|
282
|
-
const script = outputScriptOf(pubkey, accountType);
|
|
283
|
-
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 };
|
|
284
338
|
}
|
|
285
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
|
+
*/
|
|
286
345
|
private async setInput(
|
|
287
346
|
psbt: PsbtV2,
|
|
288
347
|
i: number,
|
|
@@ -294,65 +353,69 @@ export default class BtcNew {
|
|
|
294
353
|
],
|
|
295
354
|
pathElements: number[],
|
|
296
355
|
accountType: AccountType,
|
|
297
|
-
masterFP: Buffer
|
|
356
|
+
masterFP: Buffer,
|
|
357
|
+
sigHashType?: number
|
|
298
358
|
): Promise<void> {
|
|
299
359
|
const inputTx = input[0];
|
|
300
360
|
const spentOutputIndex = input[1];
|
|
301
|
-
|
|
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;
|
|
302
364
|
const sequence = input[3];
|
|
303
365
|
if (sequence) {
|
|
304
366
|
psbt.setInputSequence(i, sequence);
|
|
305
367
|
}
|
|
368
|
+
if (sigHashType) {
|
|
369
|
+
psbt.setInputSighashType(i, sigHashType);
|
|
370
|
+
}
|
|
306
371
|
const inputTxBuffer = serializeTransaction(inputTx, true);
|
|
307
372
|
const inputTxid = crypto.hash256(inputTxBuffer);
|
|
308
|
-
const xpubBase58 = await this.client.
|
|
373
|
+
const xpubBase58 = await this.client.getExtendedPubkey(false, pathElements);
|
|
309
374
|
|
|
310
375
|
const pubkey = pubkeyFromXpub(xpubBase58);
|
|
311
376
|
if (!inputTx.outputs)
|
|
312
377
|
throw Error("Missing outputs array in transaction to sign");
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
throw new Error("Missing redeemScript for p2wpkhWrapped input");
|
|
327
|
-
}
|
|
328
|
-
const expectedRedeemScript = createRedeemScript(pubkey);
|
|
329
|
-
if (redeemScript != expectedRedeemScript.toString("hex")) {
|
|
330
|
-
throw new Error("Unexpected redeemScript");
|
|
331
|
-
}
|
|
332
|
-
psbt.setInputRedeemScript(i, expectedRedeemScript);
|
|
333
|
-
psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
|
|
334
|
-
} else if (accountType == AccountType.p2tr) {
|
|
335
|
-
const xonly = pubkey.slice(1);
|
|
336
|
-
psbt.setInputTapBip32Derivation(i, xonly, [], masterFP, pathElements);
|
|
337
|
-
psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script);
|
|
338
|
-
}
|
|
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
|
+
);
|
|
339
391
|
|
|
340
392
|
psbt.setInputPreviousTxId(i, inputTxid);
|
|
341
393
|
psbt.setInputOutputIndex(i, spentOutputIndex);
|
|
342
394
|
}
|
|
343
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
|
+
*/
|
|
344
405
|
private async signPsbt(
|
|
345
406
|
psbt: PsbtV2,
|
|
346
|
-
walletPolicy: WalletPolicy
|
|
347
|
-
|
|
407
|
+
walletPolicy: WalletPolicy,
|
|
408
|
+
progressCallback: () => void
|
|
409
|
+
): Promise<void> {
|
|
348
410
|
const sigs: Map<number, Buffer> = await this.client.signPsbt(
|
|
349
411
|
psbt,
|
|
350
412
|
walletPolicy,
|
|
351
|
-
Buffer.alloc(32, 0)
|
|
413
|
+
Buffer.alloc(32, 0),
|
|
414
|
+
progressCallback
|
|
352
415
|
);
|
|
353
416
|
sigs.forEach((v, k) => {
|
|
354
|
-
// Note: Looking at BIP32 derivation does not work in the generic case
|
|
355
|
-
// 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.
|
|
356
419
|
const pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION);
|
|
357
420
|
let pubkey;
|
|
358
421
|
if (pubkeys.length != 1) {
|
|
@@ -367,94 +430,26 @@ export default class BtcNew {
|
|
|
367
430
|
psbt.setInputPartialSig(k, pubkey, v);
|
|
368
431
|
}
|
|
369
432
|
});
|
|
370
|
-
finalize(psbt);
|
|
371
|
-
const serializedTx = extract(psbt);
|
|
372
|
-
return serializedTx.toString("hex");
|
|
373
433
|
}
|
|
374
434
|
}
|
|
375
435
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
function createRedeemScript(pubkey: Buffer): Buffer {
|
|
384
|
-
const pubkeyHash = hashPublicKey(pubkey);
|
|
385
|
-
return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
function outputScriptOf(
|
|
389
|
-
pubkey: Buffer,
|
|
390
|
-
accountType: AccountType
|
|
391
|
-
): { script: Buffer; redeemScript?: Buffer } {
|
|
392
|
-
const buf = new BufferWriter();
|
|
393
|
-
const pubkeyHash = hashPublicKey(pubkey);
|
|
394
|
-
let redeemScript: Buffer | undefined;
|
|
395
|
-
if (accountType == AccountType.p2pkh) {
|
|
396
|
-
buf.writeSlice(Buffer.of(OP_DUP, OP_HASH160, HASH_SIZE));
|
|
397
|
-
buf.writeSlice(pubkeyHash);
|
|
398
|
-
buf.writeSlice(Buffer.of(OP_EQUALVERIFY, OP_CHECKSIG));
|
|
399
|
-
} else if (accountType == AccountType.p2wpkhWrapped) {
|
|
400
|
-
redeemScript = createRedeemScript(pubkey);
|
|
401
|
-
const scriptHash = hashPublicKey(redeemScript);
|
|
402
|
-
buf.writeSlice(Buffer.of(OP_HASH160, HASH_SIZE));
|
|
403
|
-
buf.writeSlice(scriptHash);
|
|
404
|
-
buf.writeUInt8(OP_EQUAL);
|
|
405
|
-
} else if (accountType == AccountType.p2wpkh) {
|
|
406
|
-
buf.writeSlice(Buffer.of(0, HASH_SIZE));
|
|
407
|
-
buf.writeSlice(pubkeyHash);
|
|
408
|
-
} else if (accountType == AccountType.p2tr) {
|
|
409
|
-
console.log("Internal key: " + pubkey.toString("hex"));
|
|
410
|
-
const outputKey = getTaprootOutputKey(pubkey);
|
|
411
|
-
buf.writeSlice(Buffer.of(0x51, 32)); // push1, pubkeylen
|
|
412
|
-
buf.writeSlice(outputKey);
|
|
413
|
-
}
|
|
414
|
-
return { script: buf.buffer(), redeemScript };
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
function accountTypeFrom(addressFormat: AddressFormat): AccountType {
|
|
418
|
-
if (addressFormat == "legacy") return AccountType.p2pkh;
|
|
419
|
-
if (addressFormat == "p2sh") return AccountType.p2wpkhWrapped;
|
|
420
|
-
if (addressFormat == "bech32") return AccountType.p2wpkh;
|
|
421
|
-
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)";
|
|
422
443
|
throw new Error("Unsupported address format " + addressFormat);
|
|
423
444
|
}
|
|
424
445
|
|
|
425
|
-
function accountTypeFromArg(
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
They should be moved to a library to avoid code reuse.
|
|
435
|
-
*/
|
|
436
|
-
function hashTapTweak(x: Buffer): Buffer {
|
|
437
|
-
// hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340
|
|
438
|
-
// See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification
|
|
439
|
-
const h = crypto.sha256(Buffer.from("TapTweak", "utf-8"));
|
|
440
|
-
return crypto.sha256(Buffer.concat([h, h, x]));
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
function getTaprootOutputKey(internalPubkey: Buffer): Buffer {
|
|
444
|
-
if (internalPubkey.length != 32) {
|
|
445
|
-
throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length);
|
|
446
|
-
}
|
|
447
|
-
// A BIP32 derived key can be converted to a schnorr pubkey by dropping
|
|
448
|
-
// the first byte, which represent the oddness/evenness. In schnorr all
|
|
449
|
-
// pubkeys are even.
|
|
450
|
-
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion
|
|
451
|
-
const evenEcdsaPubkey = Buffer.concat([Buffer.of(0x02), internalPubkey]);
|
|
452
|
-
const tweak = hashTapTweak(internalPubkey);
|
|
453
|
-
|
|
454
|
-
// Q = P + int(hash_TapTweak(bytes(P)))G
|
|
455
|
-
const outputEcdsaKey = Buffer.from(pointAddScalar(evenEcdsaPubkey, tweak));
|
|
456
|
-
// Convert to schnorr.
|
|
457
|
-
const outputSchnorrKey = outputEcdsaKey.slice(1);
|
|
458
|
-
// Create address
|
|
459
|
-
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);
|
|
460
455
|
}
|