Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 46 additions & 13 deletions modules/sdk-coin-icp/src/icp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
multisigTypes,
ParsedTransaction,
ParseTransactionOptions,
RecoveryKeyMismatchError,
RecoveryProviderError,
SignedTransaction,
SigningError,
Expand All @@ -24,7 +25,7 @@ import {
verifyMPCWalletAddress,
UnexpectedAddressError,
} from '@bitgo/sdk-core';
import { coins, NetworkType, BaseCoin as StaticsBaseCoin } from '@bitgo/statics';
import { NetworkType, BaseCoin as StaticsBaseCoin } from '@bitgo/statics';
import { Principal } from '@dfinity/principal';
import axios from 'axios';
import BigNumber from 'bignumber.js';
Expand Down Expand Up @@ -345,7 +346,7 @@ export class Icp extends BaseCoin {
}

private getBuilderFactory(): TransactionBuilderFactory {
return new TransactionBuilderFactory(coins.get(this.getBaseChain()));
return new TransactionBuilderFactory(this._staticsCoin);
}

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

const isUnsignedSweep = !params.userKey && !params.backupKey && !params.walletPassphrase;
const userKey = params.userKey?.replace(/\s/g, '');
const backupKey = params.backupKey?.replace(/\s/g, '');
const bitgoKey = params.bitgoKey?.replace(/\s/g, '');
const isUnsignedSweep = !userKey && !backupKey && !params.walletPassphrase;

let publicKey: string | undefined;
let userKeyShare, backupKeyShare, commonKeyChain;
let userKeyShare: Buffer | undefined;
let backupKeyShare: Buffer | undefined;
let commonKeyChain: string | undefined;
const MPC = new Ecdsa();

if (!isUnsignedSweep) {
if (!params.userKey) {
if (!userKey) {
throw new Error('missing userKey');
}

if (!params.backupKey) {
if (!backupKey) {
throw new Error('missing backupKey');
}

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

const userKey = params.userKey.replace(/\s/g, '');
const backupKey = params.backupKey.replace(/\s/g, '');

({ userKeyShare, backupKeyShare, commonKeyChain } = await ECDSAUtils.getMpcV2RecoveryKeyShares(
userKey,
backupKey,
params.walletPassphrase,
this.bitgo
));

if (bitgoKey && commonKeyChain !== bitgoKey) {
throw new RecoveryKeyMismatchError('commonKeyChain from recovery keys does not match bitgoKey');
}
Comment thread
pranishnepal marked this conversation as resolved.
Resolved

publicKey = MPC.deriveUnhardened(commonKeyChain, ROOT_PATH).slice(0, 66);
} else {
const bitgoKey = params.bitgoKey;
if (!bitgoKey) {
throw new Error('missing bitgoKey');
}
Expand All @@ -450,6 +458,11 @@ export class Icp extends BaseCoin {
}

const senderAddress = this.getAddressFromPublicKey(publicKey);
if (params.rootAddress && senderAddress !== params.rootAddress) {
throw new RecoveryKeyMismatchError(
`derived address ${senderAddress} does not match rootAddress ${params.rootAddress}`
);
}
Comment thread
pranishnepal marked this conversation as resolved.
Resolved
const balance = await this.getAccountBalance(publicKey);
const feeData = await this.getFeeData();
if (balance.isLessThanOrEqualTo(0)) {
Expand All @@ -462,7 +475,7 @@ export class Icp extends BaseCoin {

const factory = this.getBuilderFactory();
const txBuilder = factory.getTransferBuilder();
txBuilder.sender(senderAddress, publicKey as string);
txBuilder.sender(senderAddress, publicKey);
txBuilder.receiverId(params.recoveryDestination);
txBuilder.amount(actualBalance.toString());
if (params.memo !== undefined && utils.validateMemo(params.memo)) {
Expand All @@ -480,6 +493,10 @@ export class Icp extends BaseCoin {
};
}

if (!userKeyShare || !backupKeyShare || !commonKeyChain) {
throw new Error('failed to derive key shares');
}

const signatures = await this.signatures(
txBuilder.transaction.payloadsData,
publicKey,
Expand All @@ -493,15 +510,31 @@ export class Icp extends BaseCoin {
txBuilder.transaction.addSignature(signatures);
txBuilder.combine();
const broadcastableTxn = txBuilder.transaction.toBroadcastFormat();
await this.broadcastTransaction({ serializedSignedTransaction: broadcastableTxn });
const txId = txBuilder.transaction.id;

if (params.broadcast === false) {
// Offline / Safe mode: return the signed payload without any network mutation.
// The payload is byte-identical to what legacy broadcasting would have submitted.
return {
id: txId,
tx: broadcastableTxn,
txHex: broadcastableTxn,
coin: this.getChain(),
};
}

await this.broadcastTransaction({ serializedSignedTransaction: broadcastableTxn });
const recoveredTransaction: RecoveryTransaction = {
id: txId,
tx: broadcastableTxn,
};
return recoveredTransaction;
} catch (error) {
if (error instanceof RecoveryProviderError || error instanceof ErrorNoInputToRecover) {
if (
error instanceof RecoveryProviderError ||
error instanceof ErrorNoInputToRecover ||
error instanceof RecoveryKeyMismatchError
) {
throw error;
}
throw new Error(`Error during ICP recovery: ${error.message || error}`);
Expand Down
23 changes: 20 additions & 3 deletions modules/sdk-coin-icp/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,35 @@ export interface RawTransaction {
}

export interface RecoveryOptions {
userKey: string; // Box A
backupKey: string; // Box B
/** Box A: encrypted user key share. Required for signed recovery. */
userKey?: string;
/** Box B: encrypted backup key share. Required for signed recovery. */
backupKey?: string;
/** Child common keychain. Required for unsigned sweep; when provided in signed mode, must match the keys. */
bitgoKey?: string;
/** Expected sender address; when provided, must match the address derived from the keys. */
rootAddress?: string;
recoveryDestination: string;
walletPassphrase: string;
/** Passphrase to decrypt `userKey`/`backupKey`. Required for signed recovery. */
walletPassphrase?: string;
memo?: number | BigInt;
/**
* Whether to submit the signed transaction to the network.
* When false, the signed transaction payload is returned without broadcasting (offline / Safe mode).
* Defaults to true.
*/
broadcast?: boolean;
}

export interface RecoveryTransaction {
id: string;
tx: string;
/**
* Present when the transaction was produced offline (`broadcast: false`): the same signed
* payload as `tx`, named for the offline / Safe recovery hand-off.
*/
txHex?: string;
coin?: string;
}

export interface UnsignedSweepRecoveryTransaction {
Expand Down
120 changes: 120 additions & 0 deletions modules/sdk-coin-icp/test/unit/icpSafeRecovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import assert from 'assert';
import Sinon from 'sinon';
import { createHash } from 'crypto';
import { secp256k1 } from '@noble/curves/secp256k1';
import BigNumber from 'bignumber.js';
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
import { BitGoAPI } from '@bitgo/sdk-api';
import { DklsUtils, DklsVrfUtils } from '@bitgo/sdk-lib-mpc';
import { buildSafeRecoverKeyParams, deriveSafeWalletKeys, Ecdsa, type DecryptedSafeRoots } from '@bitgo/sdk-core';
import { Icp } from '../../src/index';
import { HttpCanisterUpdate } from '../../src/lib/iface';
import { IcpAgent } from '../../src/lib/icpAgent';
import utils from '../../src/lib/utils';
import * as testData from '../resources/icp';

/**
* End-to-end Safe ICP recovery: real DKG roots -> deriveSafeWalletKeys (slot-3 ecdsaMpc child)
* -> buildSafeRecoverKeyParams -> Icp.recover({ broadcast: false }) with the real DKLS 2-of-2
* signing path (icp.signatures is NOT stubbed). Only chain queries are mocked.
*
* This proves the whole WCN-2886 chain: the signed payload is produced offline, is byte-identical
* to what legacy broadcasting would have submitted, and its secp256k1 signature verifies against
* the derived child public key.
*/
describe('Safe ICP recovery end-to-end', function () {
const sandbox = Sinon.createSandbox();
let bitgo: TestBitGoAPI;
let icp: Icp;

before(function () {
bitgo = TestBitGo.decorate(BitGoAPI, { env: 'mock' });
bitgo.safeRegister('icp', Icp.createInstance);
bitgo.initializeTestVars();
icp = bitgo.coin('icp') as Icp;
});

afterEach(function () {
sandbox.restore();
});

it('recovers a Safe ICP wallet offline: derive -> map -> sign -> no broadcast', async function () {
// Real DKG + VRF roots, exactly as a decrypted Safe keycard would provide for the ecdsaMpc slot.
const [userDkg, backupDkg] = await DklsUtils.generateDKGKeyShares();
const [vrfUser, vrfBackup] = await DklsVrfUtils.generateVrfDKGKeyShares();
const roots: DecryptedSafeRoots = {
secp256k1Multisig: { user: 'u', backup: 'b', bitgo: 'g' },
ed25519Multisig: { user: 'u', backup: { prv: 'b', chainCode: 'c' }, bitgo: 'g' },
ecdsaMpc: {
user: { signing: userDkg.getReducedKeyShare(), vrf: vrfUser.getKeyShare() },
backup: { signing: backupDkg.getReducedKeyShare(), vrf: vrfBackup.getKeyShare() },
bitgo: 'g',
},
eddsaMpc: {
user: { signing: Buffer.alloc(0), vrf: Buffer.alloc(0) },
backup: { signing: Buffer.alloc(0), vrf: Buffer.alloc(0) },
bitgo: 'g',
},
};

const derived = await deriveSafeWalletKeys({ coin: 'icp', slot: 'ecdsaMpc', account: 0, roots });
assert(derived.slot === 'ecdsaMpc');

const keyParams = await buildSafeRecoverKeyParams({
bitgo,
coin: 'icp',
slot: 'ecdsaMpc',
keys: derived.keys,
mode: 'signed',
});
assert(keyParams.slot === 'ecdsaMpc' && keyParams.mode === 'signed');
assert.strictEqual(keyParams.broadcast, false);
assert.strictEqual(keyParams.isTss, true);
assert.strictEqual(keyParams.bitgoKey, derived.keys.commonKeychain);

// Only chain queries are mocked; icp.signatures runs the real DKLS 2-of-2 signing.
sandbox.stub(IcpAgent.prototype, 'getBalance').resolves(BigNumber(1000000000));
sandbox.stub(IcpAgent.prototype, 'getFee').resolves(BigNumber(10000));
sandbox.stub(utils, 'getMetaData').returns({
metaData: testData.MetaDataWithDefaultMemo,
ingressEndTime: testData.MetaDataWithDefaultMemo.ingress_end ?? 0,
});
const broadcastStub = sandbox.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast'));

const recovery = await icp.recover({
...keyParams,
recoveryDestination: testData.Accounts.account2.address,
broadcast: false,
});

assert('tx' in recovery);
assert.strictEqual(recovery.txHex, recovery.tx);
assert.strictEqual(recovery.coin, 'icp');
assert.strictEqual(typeof recovery.id, 'string');
Sinon.assert.notCalled(broadcastStub);

// The signed envelope's secp256k1 signature verifies against the derived child public key.
const envelope = utils.cborDecode(utils.blobFromHex(recovery.tx)) as {
content: HttpCanisterUpdate;
sender_pubkey: Uint8Array;
sender_sig: Uint8Array;
};
const representationIndependentHash = utils.HttpCanisterUpdateRepresentationIndependentHash(envelope.content);
const message = Buffer.concat([Buffer.from('0a', 'hex'), Buffer.from('ic-request'), representationIndependentHash]);
const messageHash = createHash('sha256').update(message).digest();
const rawPub = Buffer.from(envelope.sender_pubkey).subarray(-65);
assert.strictEqual(secp256k1.verify(Buffer.from(envelope.sender_sig), messageHash, rawPub), true);

// The signing public key is exactly the derived slot-3 child public key (uncompressed in the envelope).
const mpc = new Ecdsa();
const compressedChildPub = Buffer.from(
mpc.deriveUnhardened(derived.keys.commonKeychain, 'm/0').slice(0, 66),
'hex'
);
const uncompressedChildPub = secp256k1.ProjectivePoint.fromHex(compressedChildPub).toRawBytes(false);
assert.strictEqual(
Buffer.from(envelope.sender_pubkey).subarray(-65).toString('hex'),
Buffer.from(uncompressedChildPub).toString('hex')
);
});
});
Loading
Loading