-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy patheth.ts
More file actions
552 lines (483 loc) · 18.6 KB
/
eth.ts
File metadata and controls
552 lines (483 loc) · 18.6 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/**
* @prettier
*/
import { bip32 } from '@bitgo/secp256k1';
import _ from 'lodash';
import request from 'superagent';
import {
BaseCoin,
BitGoBase,
checkKrsProvider,
common,
FullySignedTransaction,
getIsKrsRecovery,
getIsUnsignedSweep,
HalfSignedTransaction,
MPCAlgorithm,
MultisigType,
multisigTypes,
Recipient,
Util,
} from '@bitgo/sdk-core';
import {
AbstractEthLikeNewCoins,
BuildOptions,
BuildTransactionParams,
EIP1559,
FeesUsed,
GetBatchExecutionInfoRT,
GetSendMethodArgsOptions,
OfflineVaultTxInfo,
optionalDeps,
RecoverOptions,
RecoveryInfo,
ReplayProtectionOptions,
SendMethodArgs,
SignedTransaction,
SignFinalOptions,
SignTransactionOptions,
TransactionPrebuild,
UnsignedSweepTxMPCv2,
} from '@bitgo/abstract-eth';
import { BaseCoin as StaticsBaseCoin, coins } from '@bitgo/statics';
import type * as EthTxLib from '@ethereumjs/tx';
import { BigNumber } from 'bignumber.js';
import { TransactionBuilder } from './lib';
import { Erc20Token } from './erc20Token';
export {
BuildTransactionParams,
Recipient,
HalfSignedTransaction,
FeesUsed,
FullySignedTransaction,
GetBatchExecutionInfoRT,
GetSendMethodArgsOptions,
TransactionPrebuild,
OfflineVaultTxInfo,
optionalDeps,
RecoverOptions,
RecoveryInfo,
SendMethodArgs,
SignFinalOptions,
SignedTransaction,
SignTransactionOptions,
};
export class Eth extends AbstractEthLikeNewCoins {
protected constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
super(bitgo, staticsCoin);
}
static createInstance(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>): BaseCoin {
return new Eth(bitgo, staticsCoin);
}
allowsAccountConsolidations(): boolean {
return true;
}
/** @inheritDoc */
supportsTss(): boolean {
return true;
}
/** inherited doc */
getDefaultMultisigType(): MultisigType {
return multisigTypes.tss;
}
getMPCAlgorithm(): MPCAlgorithm {
return 'ecdsa';
}
/**
* Gets correct Eth Common object based on params from either recovery or tx building
* @param eip1559 {EIP1559} configs that specify whether we should construct an eip1559 tx
* @param replayProtectionOptions {ReplayProtectionOptions} check if chain id supports replay protection
*/
private static getEthCommon(eip1559?: EIP1559, replayProtectionOptions?: ReplayProtectionOptions) {
// if eip1559 params are specified, default to london hardfork, otherwise,
// default to tangerine whistle to avoid replay protection issues
const defaultHardfork = !!eip1559 ? 'london' : optionalDeps.EthCommon.Hardfork.TangerineWhistle;
const defaultCommon = new optionalDeps.EthCommon.default({
chain: optionalDeps.EthCommon.Chain.Mainnet,
hardfork: defaultHardfork,
});
// if replay protection options are set, override the default common setting
const ethCommon = replayProtectionOptions
? optionalDeps.EthCommon.default.isSupportedChainId(new optionalDeps.ethUtil.BN(replayProtectionOptions.chain))
? new optionalDeps.EthCommon.default({
chain: replayProtectionOptions.chain,
hardfork: replayProtectionOptions.hardfork,
})
: optionalDeps.EthCommon.default.custom({
chainId: new optionalDeps.ethUtil.BN(replayProtectionOptions.chain),
defaultHardfork: replayProtectionOptions.hardfork,
})
: defaultCommon;
return ethCommon;
}
static buildTransaction(params: BuildTransactionParams): EthTxLib.FeeMarketEIP1559Transaction | EthTxLib.Transaction {
// if eip1559 params are specified, default to london hardfork, otherwise,
// default to tangerine whistle to avoid replay protection issues
const ethCommon = Eth.getEthCommon(params.eip1559, params.replayProtectionOptions);
const baseParams = {
to: params.to,
nonce: params.nonce,
value: params.value,
data: params.data,
gasLimit: new optionalDeps.ethUtil.BN(params.gasLimit),
};
const unsignedEthTx = !!params.eip1559
? optionalDeps.EthTx.FeeMarketEIP1559Transaction.fromTxData(
{
...baseParams,
maxFeePerGas: new optionalDeps.ethUtil.BN(params.eip1559.maxFeePerGas),
maxPriorityFeePerGas: new optionalDeps.ethUtil.BN(params.eip1559.maxPriorityFeePerGas),
},
{ common: ethCommon }
)
: optionalDeps.EthTx.Transaction.fromTxData(
{
...baseParams,
gasPrice: new optionalDeps.ethUtil.BN(params.gasPrice),
},
{ common: ethCommon }
);
return unsignedEthTx;
}
/**
* Make a query to Etherscan for information such as balance, token balance, solidity calls
* @param query {Object} key-value pairs of parameters to append after /api
* @param apiKey {string} optional API key to use instead of the one from the environment
* @returns {Object} response from Etherscan
*/
async recoveryBlockchainExplorerQuery(query: Record<string, string>, apiKey?: string): Promise<any> {
const token = apiKey || common.Environments[this.bitgo.getEnv()].etherscanApiToken;
if (token) {
query.apikey = token;
}
const response = await request.get(common.Environments[this.bitgo.getEnv()].etherscanBaseUrl + '/api').query(query);
if (!response.ok) {
throw new Error('could not reach Etherscan');
}
if (response.body.status === '0' && response.body.message === 'NOTOK') {
throw new Error('Etherscan rate limit reached');
}
return response.body;
}
/**
* Recovers a tx with non-TSS keys
* same expected arguments as recover method (original logic before adding TSS recover path)
*/
protected async recoverEthLike(params: RecoverOptions): Promise<RecoveryInfo | OfflineVaultTxInfo> {
// bitgoFeeAddress is only defined when it is a evm cross chain recovery
// as we use fee from this wrong chain address for the recovery txn on the correct chain.
if (params.bitgoFeeAddress) {
return this.recoverEthLikeforEvmBasedRecovery(params);
}
this.validateRecoveryParams(params);
const isKrsRecovery = getIsKrsRecovery(params);
const isUnsignedSweep = params.isUnsignedSweep ?? getIsUnsignedSweep(params);
if (isKrsRecovery) {
checkKrsProvider(this, params.krsProvider, { checkCoinFamilySupport: false });
}
// Clean up whitespace from entered values
let userKey = params.userKey.replace(/\s/g, '');
const backupKey = params.backupKey.replace(/\s/g, '');
// Set new eth tx fees (using default config values from platform)
const gasLimit = new optionalDeps.ethUtil.BN(this.setGasLimit(params.gasLimit));
const gasPrice = params.eip1559
? new optionalDeps.ethUtil.BN(params.eip1559.maxFeePerGas)
: new optionalDeps.ethUtil.BN(this.setGasPrice(params.gasPrice));
if (!isUnsignedSweep) {
try {
userKey = this.bitgo.decrypt({
input: userKey,
password: params.walletPassphrase,
});
} catch (e) {
throw new Error(`Error decrypting user keychain: ${e.message}`);
}
}
let backupKeyAddress: string;
let backupSigningKey;
if (isKrsRecovery || isUnsignedSweep) {
const backupHDNode = bip32.fromBase58(backupKey);
backupSigningKey = backupHDNode.publicKey;
backupKeyAddress = `0x${optionalDeps.ethUtil.publicToAddress(backupSigningKey, true).toString('hex')}`;
} else {
// Decrypt backup private key and get address
let backupPrv;
try {
backupPrv = this.bitgo.decrypt({
input: backupKey,
password: params.walletPassphrase,
});
} catch (e) {
throw new Error(`Error decrypting backup keychain: ${e.message}`);
}
const backupHDNode = bip32.fromBase58(backupPrv);
backupSigningKey = backupHDNode.privateKey;
if (!backupHDNode) {
throw new Error('no private key');
}
backupKeyAddress = `0x${optionalDeps.ethUtil.privateToAddress(backupSigningKey).toString('hex')}`;
}
const backupKeyNonce = await this.getAddressNonce(backupKeyAddress, params.apiKey);
// get balance of backupKey to ensure funds are available to pay fees
const backupKeyBalance = await this.queryAddressBalance(backupKeyAddress, params.apiKey);
const totalGasNeeded = gasPrice.mul(gasLimit);
const weiToGwei = 10 ** 9;
if (backupKeyBalance.lt(totalGasNeeded)) {
throw new Error(
`Backup key address ${backupKeyAddress} has balance ${(backupKeyBalance / weiToGwei).toString()} Gwei.` +
`This address must have a balance of at least ${(totalGasNeeded / weiToGwei).toString()}` +
` Gwei to perform recoveries. Try sending some ETH to this address then retry.`
);
}
// get balance of wallet and deduct fees to get transaction amount
const txAmount = await this.queryAddressBalance(params.walletContractAddress, params.apiKey);
if (new BigNumber(txAmount).isLessThanOrEqualTo(0)) {
throw new Error('Wallet does not have enough funds to recover');
}
// build recipients object
const recipients = [
{
address: params.recoveryDestination,
amount: txAmount.toString(10),
},
];
// Get sequence ID using contract call
// we need to wait between making two etherscan calls to avoid getting banned
await new Promise((resolve) => setTimeout(resolve, 1000));
const sequenceId = await this.querySequenceId(params.walletContractAddress, params.apiKey);
let operationHash, signature;
// Get operation hash and sign it
if (!isUnsignedSweep) {
operationHash = this.getOperationSha3ForExecuteAndConfirm(recipients, this.getDefaultExpireTime(), sequenceId);
signature = Util.ethSignMsgHash(operationHash, Util.xprvToEthPrivateKey(userKey));
try {
Util.ecRecoverEthAddress(operationHash, signature);
} catch (e) {
throw new Error('Invalid signature');
}
}
const txInfo = {
recipient: recipients[0],
expireTime: this.getDefaultExpireTime(),
contractSequenceId: sequenceId,
operationHash: operationHash,
signature: signature,
gasLimit: gasLimit.toString(10),
};
// calculate send data
const sendMethodArgs = this.getSendMethodArgs(txInfo);
const methodSignature = optionalDeps.ethAbi.methodID(this.sendMethodName, _.map(sendMethodArgs, 'type'));
const encodedArgs = optionalDeps.ethAbi.rawEncode(_.map(sendMethodArgs, 'type'), _.map(sendMethodArgs, 'value'));
const sendData = Buffer.concat([methodSignature, encodedArgs]);
const txParams = {
to: params.walletContractAddress,
nonce: backupKeyNonce,
value: 0,
gasPrice: gasPrice,
gasLimit: gasLimit,
data: sendData,
eip1559: params.eip1559,
replayProtectionOptions: params.replayProtectionOptions,
};
// Build contract call and sign it
let tx = Eth.buildTransaction(txParams);
if (isUnsignedSweep) {
return this.formatForOfflineVault(
txInfo,
tx,
userKey,
backupKey,
gasPrice,
gasLimit,
params.eip1559,
params.replayProtectionOptions,
params.apiKey
);
}
if (!isKrsRecovery) {
tx = tx.sign(backupSigningKey);
}
const signedTx: RecoveryInfo = {
id: optionalDeps.ethUtil.bufferToHex(tx.hash()),
tx: tx.serialize().toString('hex'),
};
if (isKrsRecovery) {
signedTx.backupKey = backupKey;
signedTx.coin = this.getChain();
}
return signedTx;
}
protected async buildUnsignedSweepTxnTSS(params: RecoverOptions): Promise<OfflineVaultTxInfo | UnsignedSweepTxMPCv2> {
// Coin-specific logic for ETH
return this.buildUnsignedSweepTxnMPCv2(params);
}
/**
* Return boolean indicating whether input is valid public key for the coin.
*
* @param {String} pub the pub to be checked
* @returns {Boolean} is it valid?
*/
isValidPub(pub: string): boolean {
try {
return bip32.fromBase58(pub).isNeutered();
} catch (e) {
return false;
}
}
/**
* Helper function for signTransaction for the rare case that SDK is doing the second signature
* Note: we are expecting this to be called from the offline vault
* @param params.txPrebuild
* @param params.signingKeyNonce
* @param params.walletContractAddress
* @param params.prv
* @returns {{txHex: *}}
*/
signFinal(params: SignFinalOptions): FullySignedTransaction {
const txPrebuild = params.txPrebuild;
if (!_.isNumber(params.signingKeyNonce) && !_.isNumber(params.txPrebuild.halfSigned?.backupKeyNonce)) {
throw new Error(
'must have at least one of signingKeyNonce and backupKeyNonce as a parameter, and it must be a number'
);
}
if (_.isUndefined(params.walletContractAddress)) {
throw new Error('params must include walletContractAddress, but got undefined');
}
const signingNode = bip32.fromBase58(params.prv);
const signingKey = signingNode.privateKey;
if (_.isUndefined(signingKey)) {
throw new Error('missing private key');
}
let recipient: Recipient;
let txInfo;
if (txPrebuild.recipients) {
recipient = txPrebuild.recipients[0];
txInfo = {
recipient,
expireTime: txPrebuild.halfSigned?.expireTime as number,
contractSequenceId: txPrebuild.halfSigned?.contractSequenceId as number,
signature: txPrebuild.halfSigned?.signature as string,
};
}
const sendMethodArgs = this.getSendMethodArgs(txInfo);
const methodSignature = optionalDeps.ethAbi.methodID(this.sendMethodName, _.map(sendMethodArgs, 'type'));
const encodedArgs = optionalDeps.ethAbi.rawEncode(_.map(sendMethodArgs, 'type'), _.map(sendMethodArgs, 'value'));
const sendData = Buffer.concat([methodSignature, encodedArgs]);
const ethTxParams = {
to: params.walletContractAddress,
nonce:
params.signingKeyNonce !== undefined ? params.signingKeyNonce : params.txPrebuild.halfSigned?.backupKeyNonce,
value: 0,
gasPrice: new optionalDeps.ethUtil.BN(txPrebuild.gasPrice),
gasLimit: new optionalDeps.ethUtil.BN(txPrebuild.gasLimit),
data: sendData,
};
const unsignedEthTx = Eth.buildTransaction({
...ethTxParams,
eip1559: params.txPrebuild.eip1559,
replayProtectionOptions: params.txPrebuild.replayProtectionOptions,
});
const ethTx = unsignedEthTx.sign(signingKey);
return { txHex: ethTx.serialize().toString('hex') };
}
/**
* Assemble keychain and half-sign prebuilt transaction
* @param params
* - txPrebuild
* - prv
* @returns {Promise<SignedTransaction>}
*/
async signTransaction(params: SignTransactionOptions): Promise<SignedTransaction> {
if (params.isEvmBasedCrossChainRecovery) {
return super.signTransaction(params);
}
const txPrebuild = params.txPrebuild;
const userPrv = params.prv;
const EXPIRETIME_DEFAULT = 60 * 60 * 24 * 7; // This signature will be valid for 1 week
if (_.isUndefined(txPrebuild) || !_.isObject(txPrebuild)) {
if (!_.isUndefined(txPrebuild) && !_.isObject(txPrebuild)) {
throw new Error(`txPrebuild must be an object, got type ${typeof txPrebuild}`);
}
throw new Error('missing txPrebuild parameter');
}
if (_.isUndefined(userPrv) || !_.isString(userPrv)) {
if (!_.isUndefined(userPrv) && !_.isString(userPrv)) {
throw new Error(`prv must be a string, got type ${typeof userPrv}`);
}
throw new Error('missing prv parameter to sign transaction');
}
params.recipients = txPrebuild.recipients || params.recipients;
// if no recipients in either params or txPrebuild, then throw an error
if (!params.recipients || !Array.isArray(params.recipients)) {
throw new Error('recipients missing or not array');
}
if (params.recipients.length == 0) {
throw new Error('recipients empty');
}
// Normally the SDK provides the first signature for an ETH tx, but occasionally it provides the second and final one.
if (params.isLastSignature) {
// In this case when we're doing the second (final) signature, the logic is different.
return this.signFinal(params);
}
const secondsSinceEpoch = Math.floor(new Date().getTime() / 1000);
const expireTime = params.expireTime || secondsSinceEpoch + EXPIRETIME_DEFAULT;
const sequenceId = txPrebuild.nextContractSequenceId;
if (_.isUndefined(sequenceId)) {
throw new Error('transaction prebuild missing required property nextContractSequenceId');
}
const operationHash = this.getOperationSha3ForExecuteAndConfirm(params.recipients, expireTime, sequenceId);
const signature = Util.ethSignMsgHash(operationHash, Util.xprvToEthPrivateKey(userPrv));
const txParams = {
eip1559: params.txPrebuild.eip1559,
isBatch: params.txPrebuild.isBatch,
recipients: params.recipients,
expireTime: expireTime,
contractSequenceId: sequenceId,
sequenceId: params.sequenceId,
operationHash: operationHash,
signature: signature,
gasLimit: params.gasLimit,
gasPrice: params.gasPrice,
hopTransaction: txPrebuild.hopTransaction,
backupKeyNonce: txPrebuild.backupKeyNonce,
custodianTransactionId: params.custodianTransactionId,
};
return { halfSigned: txParams };
}
/**
* Modify prebuild before sending it to the server. Add things like hop transaction params
* @param buildParams The whitelisted parameters for this prebuild
* @param buildParams.hop True if this should prebuild a hop tx, else false
* @param buildParams.recipients The recipients array of this transaction
* @param buildParams.wallet The wallet sending this tx
* @param buildParams.walletPassphrase the passphrase for this wallet
*/
async getExtraPrebuildParams(buildParams: BuildOptions): Promise<BuildOptions> {
if (
!_.isUndefined(buildParams.hop) &&
buildParams.hop &&
!_.isUndefined(buildParams.wallet) &&
!_.isUndefined(buildParams.recipients) &&
!_.isUndefined(buildParams.walletPassphrase)
) {
if (this instanceof Erc20Token) {
throw new Error(
`Hop transactions are not enabled for ERC-20 tokens, nor are they necessary. Please remove the 'hop' parameter and try again.`
);
}
return (await this.createHopTransactionParams({
wallet: buildParams.wallet,
recipients: buildParams.recipients,
walletPassphrase: buildParams.walletPassphrase,
})) as any;
}
return {};
}
/**
* Create a new transaction builder for the current chain
* @return a new transaction builder
*/
protected getTransactionBuilder(): TransactionBuilder {
return new TransactionBuilder(coins.get(this.getBaseChain()));
}
}