Skip to content

Commit 5f267cc

Browse files
committed
feat: enable Safe recovery for ICP (offline mode)
Add an offline mode to Icp.recover() - Icp.recover() gains broadcast?: boolean (default true); when false it returns the signed transaction payload ({ id, tx, txHex, coin }) without submitting it to the network - buildSafeRecoverKeyParams() gains the ecdsaMpc (slot 3) arm: signed mode re-encrypts the derived child reduced shares under a fresh v1 passphrase, unsigned mode returns the child common keychain; both set broadcast: false so the coin-agnostic Safe engine stays offline - RecoveryOptions.userKey/backupKey/walletPassphrase are now optional so typed unsigned sweeps compile - Icp.recover() fails closed with RecoveryKeyMismatchError when bitgoKey or rootAddress does not match the recovery keys - getBuilderFactory() uses _staticsCoin so ticp builds testnet transactions Ticket: WCN-2886
1 parent 02a718e commit 5f267cc

6 files changed

Lines changed: 402 additions & 27 deletions

File tree

‎modules/sdk-coin-icp/src/icp.ts‎

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
multisigTypes,
1717
ParsedTransaction,
1818
ParseTransactionOptions,
19+
RecoveryKeyMismatchError,
1920
RecoveryProviderError,
2021
SignedTransaction,
2122
SigningError,
@@ -24,7 +25,7 @@ import {
2425
verifyMPCWalletAddress,
2526
UnexpectedAddressError,
2627
} from '@bitgo/sdk-core';
27-
import { coins, NetworkType, BaseCoin as StaticsBaseCoin } from '@bitgo/statics';
28+
import { NetworkType, BaseCoin as StaticsBaseCoin } from '@bitgo/statics';
2829
import { Principal } from '@dfinity/principal';
2930
import axios from 'axios';
3031
import BigNumber from 'bignumber.js';
@@ -345,7 +346,7 @@ export class Icp extends BaseCoin {
345346
}
346347

347348
private getBuilderFactory(): TransactionBuilderFactory {
348-
return new TransactionBuilderFactory(coins.get(this.getBaseChain()));
349+
return new TransactionBuilderFactory(this._staticsCoin);
349350
}
350351

351352
/**
@@ -390,44 +391,51 @@ export class Icp extends BaseCoin {
390391
/**
391392
* Builds a funds recovery transaction without BitGo
392393
* @param params
394+
* @returns the broadcast result when broadcasting, or the signed transaction payload when `broadcast` is false
393395
*/
394396
async recover(params: RecoveryOptions): Promise<RecoveryTransaction | UnsignedSweepRecoveryTransaction> {
395397
try {
396398
if (!params.recoveryDestination || !this.isValidAddress(params.recoveryDestination)) {
397399
throw new Error('invalid recoveryDestination');
398400
}
399401

400-
const isUnsignedSweep = !params.userKey && !params.backupKey && !params.walletPassphrase;
402+
const userKey = params.userKey?.replace(/\s/g, '');
403+
const backupKey = params.backupKey?.replace(/\s/g, '');
404+
const bitgoKey = params.bitgoKey?.replace(/\s/g, '');
405+
const isUnsignedSweep = !userKey && !backupKey && !params.walletPassphrase;
401406

402407
let publicKey: string | undefined;
403-
let userKeyShare, backupKeyShare, commonKeyChain;
408+
let userKeyShare: Buffer | undefined;
409+
let backupKeyShare: Buffer | undefined;
410+
let commonKeyChain: string | undefined;
404411
const MPC = new Ecdsa();
405412

406413
if (!isUnsignedSweep) {
407-
if (!params.userKey) {
414+
if (!userKey) {
408415
throw new Error('missing userKey');
409416
}
410417

411-
if (!params.backupKey) {
418+
if (!backupKey) {
412419
throw new Error('missing backupKey');
413420
}
414421

415422
if (!params.walletPassphrase) {
416423
throw new Error('missing wallet passphrase');
417424
}
418425

419-
const userKey = params.userKey.replace(/\s/g, '');
420-
const backupKey = params.backupKey.replace(/\s/g, '');
421-
422426
({ userKeyShare, backupKeyShare, commonKeyChain } = await ECDSAUtils.getMpcV2RecoveryKeyShares(
423427
userKey,
424428
backupKey,
425429
params.walletPassphrase,
426430
this.bitgo
427431
));
432+
433+
if (bitgoKey && commonKeyChain !== bitgoKey) {
434+
throw new RecoveryKeyMismatchError('commonKeyChain from recovery keys does not match bitgoKey');
435+
}
436+
428437
publicKey = MPC.deriveUnhardened(commonKeyChain, ROOT_PATH).slice(0, 66);
429438
} else {
430-
const bitgoKey = params.bitgoKey;
431439
if (!bitgoKey) {
432440
throw new Error('missing bitgoKey');
433441
}
@@ -450,6 +458,11 @@ export class Icp extends BaseCoin {
450458
}
451459

452460
const senderAddress = this.getAddressFromPublicKey(publicKey);
461+
if (params.rootAddress && senderAddress !== params.rootAddress) {
462+
throw new RecoveryKeyMismatchError(
463+
`derived address ${senderAddress} does not match rootAddress ${params.rootAddress}`
464+
);
465+
}
453466
const balance = await this.getAccountBalance(publicKey);
454467
const feeData = await this.getFeeData();
455468
if (balance.isLessThanOrEqualTo(0)) {
@@ -462,7 +475,7 @@ export class Icp extends BaseCoin {
462475

463476
const factory = this.getBuilderFactory();
464477
const txBuilder = factory.getTransferBuilder();
465-
txBuilder.sender(senderAddress, publicKey as string);
478+
txBuilder.sender(senderAddress, publicKey);
466479
txBuilder.receiverId(params.recoveryDestination);
467480
txBuilder.amount(actualBalance.toString());
468481
if (params.memo !== undefined && utils.validateMemo(params.memo)) {
@@ -480,6 +493,10 @@ export class Icp extends BaseCoin {
480493
};
481494
}
482495

496+
if (!userKeyShare || !backupKeyShare || !commonKeyChain) {
497+
throw new Error('failed to derive key shares');
498+
}
499+
483500
const signatures = await this.signatures(
484501
txBuilder.transaction.payloadsData,
485502
publicKey,
@@ -493,15 +510,31 @@ export class Icp extends BaseCoin {
493510
txBuilder.transaction.addSignature(signatures);
494511
txBuilder.combine();
495512
const broadcastableTxn = txBuilder.transaction.toBroadcastFormat();
496-
await this.broadcastTransaction({ serializedSignedTransaction: broadcastableTxn });
497513
const txId = txBuilder.transaction.id;
514+
515+
if (params.broadcast === false) {
516+
// Offline / Safe mode: return the signed payload without any network mutation.
517+
// The payload is byte-identical to what legacy broadcasting would have submitted.
518+
return {
519+
id: txId,
520+
tx: broadcastableTxn,
521+
txHex: broadcastableTxn,
522+
coin: this.getChain(),
523+
};
524+
}
525+
526+
await this.broadcastTransaction({ serializedSignedTransaction: broadcastableTxn });
498527
const recoveredTransaction: RecoveryTransaction = {
499528
id: txId,
500529
tx: broadcastableTxn,
501530
};
502531
return recoveredTransaction;
503532
} catch (error) {
504-
if (error instanceof RecoveryProviderError || error instanceof ErrorNoInputToRecover) {
533+
if (
534+
error instanceof RecoveryProviderError ||
535+
error instanceof ErrorNoInputToRecover ||
536+
error instanceof RecoveryKeyMismatchError
537+
) {
505538
throw error;
506539
}
507540
throw new Error(`Error during ICP recovery: ${error.message || error}`);

‎modules/sdk-coin-icp/src/lib/iface.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,18 +186,35 @@ export interface RawTransaction {
186186
}
187187

188188
export interface RecoveryOptions {
189-
userKey: string; // Box A
190-
backupKey: string; // Box B
189+
/** Box A: encrypted user key share. Required for signed recovery. */
190+
userKey?: string;
191+
/** Box B: encrypted backup key share. Required for signed recovery. */
192+
backupKey?: string;
193+
/** Child common keychain. Required for unsigned sweep; when provided in signed mode, must match the keys. */
191194
bitgoKey?: string;
195+
/** Expected sender address; when provided, must match the address derived from the keys. */
192196
rootAddress?: string;
193197
recoveryDestination: string;
194-
walletPassphrase: string;
198+
/** Passphrase to decrypt `userKey`/`backupKey`. Required for signed recovery. */
199+
walletPassphrase?: string;
195200
memo?: number | BigInt;
201+
/**
202+
* Whether to submit the signed transaction to the network.
203+
* When false, the signed transaction payload is returned without broadcasting (offline / Safe mode).
204+
* Defaults to true.
205+
*/
206+
broadcast?: boolean;
196207
}
197208

198209
export interface RecoveryTransaction {
199210
id: string;
200211
tx: string;
212+
/**
213+
* Present when the transaction was produced offline (`broadcast: false`): the same signed
214+
* payload as `tx`, named for the offline / Safe recovery hand-off.
215+
*/
216+
txHex?: string;
217+
coin?: string;
201218
}
202219

203220
export interface UnsignedSweepRecoveryTransaction {
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import assert from 'assert';
2+
import Sinon from 'sinon';
3+
import { createHash } from 'crypto';
4+
import { secp256k1 } from '@noble/curves/secp256k1';
5+
import BigNumber from 'bignumber.js';
6+
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
7+
import { BitGoAPI } from '@bitgo/sdk-api';
8+
import { DklsUtils, DklsVrfUtils } from '@bitgo/sdk-lib-mpc';
9+
import { buildSafeRecoverKeyParams, deriveSafeWalletKeys, Ecdsa, type DecryptedSafeRoots } from '@bitgo/sdk-core';
10+
import { Icp } from '../../src/index';
11+
import { HttpCanisterUpdate } from '../../src/lib/iface';
12+
import { IcpAgent } from '../../src/lib/icpAgent';
13+
import utils from '../../src/lib/utils';
14+
import * as testData from '../resources/icp';
15+
16+
/**
17+
* End-to-end Safe ICP recovery: real DKG roots -> deriveSafeWalletKeys (slot-3 ecdsaMpc child)
18+
* -> buildSafeRecoverKeyParams -> Icp.recover({ broadcast: false }) with the real DKLS 2-of-2
19+
* signing path (icp.signatures is NOT stubbed). Only chain queries are mocked.
20+
*
21+
* This proves the whole WCN-2886 chain: the signed payload is produced offline, is byte-identical
22+
* to what legacy broadcasting would have submitted, and its secp256k1 signature verifies against
23+
* the derived child public key.
24+
*/
25+
describe('Safe ICP recovery end-to-end', function () {
26+
const sandbox = Sinon.createSandbox();
27+
let bitgo: TestBitGoAPI;
28+
let icp: Icp;
29+
30+
before(function () {
31+
bitgo = TestBitGo.decorate(BitGoAPI, { env: 'mock' });
32+
bitgo.safeRegister('icp', Icp.createInstance);
33+
bitgo.initializeTestVars();
34+
icp = bitgo.coin('icp') as Icp;
35+
});
36+
37+
afterEach(function () {
38+
sandbox.restore();
39+
});
40+
41+
it('recovers a Safe ICP wallet offline: derive -> map -> sign -> no broadcast', async function () {
42+
// Real DKG + VRF roots, exactly as a decrypted Safe keycard would provide for the ecdsaMpc slot.
43+
const [userDkg, backupDkg] = await DklsUtils.generateDKGKeyShares();
44+
const [vrfUser, vrfBackup] = await DklsVrfUtils.generateVrfDKGKeyShares();
45+
const roots: DecryptedSafeRoots = {
46+
secp256k1Multisig: { user: 'u', backup: 'b', bitgo: 'g' },
47+
ed25519Multisig: { user: 'u', backup: { prv: 'b', chainCode: 'c' }, bitgo: 'g' },
48+
ecdsaMpc: {
49+
user: { signing: userDkg.getReducedKeyShare(), vrf: vrfUser.getKeyShare() },
50+
backup: { signing: backupDkg.getReducedKeyShare(), vrf: vrfBackup.getKeyShare() },
51+
bitgo: 'g',
52+
},
53+
eddsaMpc: {
54+
user: { signing: Buffer.alloc(0), vrf: Buffer.alloc(0) },
55+
backup: { signing: Buffer.alloc(0), vrf: Buffer.alloc(0) },
56+
bitgo: 'g',
57+
},
58+
};
59+
60+
const derived = await deriveSafeWalletKeys({ coin: 'icp', slot: 'ecdsaMpc', account: 0, roots });
61+
assert(derived.slot === 'ecdsaMpc');
62+
63+
const keyParams = await buildSafeRecoverKeyParams({
64+
bitgo,
65+
coin: 'icp',
66+
slot: 'ecdsaMpc',
67+
keys: derived.keys,
68+
mode: 'signed',
69+
});
70+
assert(keyParams.slot === 'ecdsaMpc' && keyParams.mode === 'signed');
71+
assert.strictEqual(keyParams.broadcast, false);
72+
assert.strictEqual(keyParams.isTss, true);
73+
assert.strictEqual(keyParams.bitgoKey, derived.keys.commonKeychain);
74+
75+
// Only chain queries are mocked; icp.signatures runs the real DKLS 2-of-2 signing.
76+
sandbox.stub(IcpAgent.prototype, 'getBalance').resolves(BigNumber(1000000000));
77+
sandbox.stub(IcpAgent.prototype, 'getFee').resolves(BigNumber(10000));
78+
sandbox.stub(utils, 'getMetaData').returns({
79+
metaData: testData.MetaDataWithDefaultMemo,
80+
ingressEndTime: testData.MetaDataWithDefaultMemo.ingress_end ?? 0,
81+
});
82+
const broadcastStub = sandbox.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast'));
83+
84+
const recovery = await icp.recover({
85+
...keyParams,
86+
recoveryDestination: testData.Accounts.account2.address,
87+
broadcast: false,
88+
});
89+
90+
assert('tx' in recovery);
91+
assert.strictEqual(recovery.txHex, recovery.tx);
92+
assert.strictEqual(recovery.coin, 'icp');
93+
assert.strictEqual(typeof recovery.id, 'string');
94+
Sinon.assert.notCalled(broadcastStub);
95+
96+
// The signed envelope's secp256k1 signature verifies against the derived child public key.
97+
const envelope = utils.cborDecode(utils.blobFromHex(recovery.tx)) as {
98+
content: HttpCanisterUpdate;
99+
sender_pubkey: Uint8Array;
100+
sender_sig: Uint8Array;
101+
};
102+
const representationIndependentHash = utils.HttpCanisterUpdateRepresentationIndependentHash(envelope.content);
103+
const message = Buffer.concat([Buffer.from('0a', 'hex'), Buffer.from('ic-request'), representationIndependentHash]);
104+
const messageHash = createHash('sha256').update(message).digest();
105+
const rawPub = Buffer.from(envelope.sender_pubkey).subarray(-65);
106+
assert.strictEqual(secp256k1.verify(Buffer.from(envelope.sender_sig), messageHash, rawPub), true);
107+
108+
// The signing public key is exactly the derived slot-3 child public key (uncompressed in the envelope).
109+
const mpc = new Ecdsa();
110+
const compressedChildPub = Buffer.from(
111+
mpc.deriveUnhardened(derived.keys.commonKeychain, 'm/0').slice(0, 66),
112+
'hex'
113+
);
114+
const uncompressedChildPub = secp256k1.ProjectivePoint.fromHex(compressedChildPub).toRawBytes(false);
115+
assert.strictEqual(
116+
Buffer.from(envelope.sender_pubkey).subarray(-65).toString('hex'),
117+
Buffer.from(uncompressedChildPub).toString('hex')
118+
);
119+
});
120+
});

0 commit comments

Comments
 (0)