-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecoverUtxoBackupBitgo.ts
198 lines (187 loc) · 5 KB
/
recoverUtxoBackupBitgo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import * as dotenv from "dotenv";
dotenv.config();
import {
BaseCoin,
EnvironmentName,
Keychains,
Wallet,
isTriple,
} from "@bitgo/sdk-core";
import { BitGo } from "bitgo";
import { command, run } from "cmd-ts";
import {
walletIdFlag,
envFlag,
passwordFlag,
accessTokenFlag,
recoveryDestinationFlag,
blockChairApiKeyFlag,
} from "./common";
import {
AbstractUtxoCoin,
FormattedOfflineVaultTxInfo,
backupKeyRecovery,
signAndVerifyWalletTransaction,
} from "@bitgo/abstract-utxo";
import { Transaction, bip32 } from "@bitgo/utxo-lib";
import * as utxolib from "@bitgo/utxo-lib";
import { BlockchairApi } from "@bitgo/blockapis";
function assertIsUtxo(coin: BaseCoin): asserts coin is AbstractUtxoCoin {
if (!(coin instanceof AbstractUtxoCoin)) {
throw new Error("coin must be a utxo coin");
}
}
export async function main(args: {
walletId: string;
env: EnvironmentName;
walletPassword: string;
accessToken: string;
recoveryDestination: string;
blockChairApiKey: string;
}) {
console.log({
...args,
accessToken: "REDACTED",
walletPassword: "REDACTED",
blockChairApiKey: "REDACTED",
});
const sdk = new BitGo({ env: args.env, accessToken: args.accessToken });
const walletJSON = await sdk
.get(sdk.url(`/wallet/${args.walletId}`, 2))
.result();
const coin = sdk.coin(walletJSON.coin);
assertIsUtxo(coin);
const wallet = new Wallet(sdk, coin, walletJSON);
const keychains = new Keychains(sdk, coin);
const userKey = await keychains.get({
id: wallet.keyIds()[0],
});
const backupKey = await keychains.get({
id: wallet.keyIds()[1],
});
const bitgoKey = await keychains.get({
id: wallet.keyIds()[2],
});
if (!userKey.pub || !backupKey.pub || !bitgoKey.pub) {
throw new Error("keys are missing pubs");
}
if (!backupKey.encryptedPrv) {
throw new Error("backup key missing encryptedPrv");
}
// build unsigned sweep
const { txBuilder, unspents } = await (async () => {
const { txHex, txInfo } = (await backupKeyRecovery(coin, sdk, {
userKey: userKey.pub!,
backupKey: backupKey.pub!,
bitgoKey: bitgoKey.pub!,
walletPassphrase: args.walletPassword,
recoveryDestination: args.recoveryDestination,
scan: 20,
ignoreAddressTypes: ["p2wsh"],
recoveryProvider: BlockchairApi.forCoin(coin.getChain(), {
apiToken: args.blockChairApiKey,
}),
})) as FormattedOfflineVaultTxInfo;
const output = Transaction.fromHex(txHex).outs[0];
txInfo.unspents = txInfo.unspents.map((u) => {
return {
...u,
address: utxolib.addressFormat.toCanonicalFormat(
u.address,
coin.network
),
};
});
const txBuilder = utxolib.bitgo.createTransactionBuilderForNetwork<number>(
coin.network
);
txInfo.unspents.forEach((unspent) => {
const { txid, vout } = utxolib.bitgo.parseOutputId(unspent.id);
txBuilder.addInput(
txid,
vout,
0xffffffff,
utxolib.address.toOutputScript(unspent.address, coin.network),
unspent.value
);
});
console.log("txHex", txHex);
console.log("txInfo", JSON.stringify(txInfo, null, 2));
txBuilder.addOutput(
utxolib.addressFormat.toCanonicalFormat(
args.recoveryDestination,
coin.network
),
output.value
);
return {
txBuilder,
unspents: txInfo.unspents,
};
})();
// Transaction
// sign with backup key
const keys = [
bip32.fromBase58(userKey.pub),
bip32.fromBase58(
sdk.decrypt({
password: args.walletPassword,
input: backupKey.encryptedPrv,
})
),
bip32.fromBase58(bitgoKey.pub),
];
if (!isTriple(keys)) {
throw new Error(`expected key triple`);
}
const walletKeys = new utxolib.bitgo.RootWalletKeys(keys, [
utxolib.bitgo.RootWalletKeys.defaultPrefix,
utxolib.bitgo.RootWalletKeys.defaultPrefix,
utxolib.bitgo.RootWalletKeys.defaultPrefix,
]);
const tx = signAndVerifyWalletTransaction<number>(
txBuilder,
unspents,
new utxolib.bitgo.WalletUnspentSigner<utxolib.bitgo.RootWalletKeys>(
walletKeys,
walletKeys.backup,
walletKeys.bitgo
),
{ isLastSignature: false }
);
// send half signed
try {
const sendParams = {
txHex: tx.toHex(),
};
const sendRes = await sdk
.post(sdk.url(`/${coin.getChain()}/wallet/${wallet.id()}/tx/send`, 2))
.send(sendParams)
.result();
console.log(JSON.stringify(sendRes, null, 2));
} catch (e) {
console.error(e);
throw e;
}
}
const app = command({
name: "yarn start",
args: {
walletId: walletIdFlag,
env: envFlag,
walletPassword: passwordFlag,
accessToken: accessTokenFlag,
recoveryDestination: recoveryDestinationFlag,
blockChairApiKey: blockChairApiKeyFlag,
},
handler: async (args) => {
try {
await main(args);
} catch (e) {
console.trace(e);
}
},
});
run(app, process.argv.slice(2))
.then(() => console.log("done"))
.catch((e) => console.trace(e));