From 5f267cc37af69cee5fa7027a1d51ec11df28e6ca Mon Sep 17 00:00:00 2001 From: Pranish Nepal Date: Fri, 23 Oct 2026 17:02:02 -0400 Subject: [PATCH] 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 --- modules/sdk-coin-icp/src/icp.ts | 59 +++++++-- modules/sdk-coin-icp/src/lib/iface.ts | 23 +++- .../sdk-coin-icp/test/unit/icpSafeRecovery.ts | 120 ++++++++++++++++++ .../transactionBuilder/transactionRecover.ts | 89 ++++++++++++- modules/sdk-core/src/bitgo/safe/recovery.ts | 77 ++++++++++- .../sdk-core/test/unit/bitgo/safe/recovery.ts | 61 +++++++++ 6 files changed, 402 insertions(+), 27 deletions(-) create mode 100644 modules/sdk-coin-icp/test/unit/icpSafeRecovery.ts diff --git a/modules/sdk-coin-icp/src/icp.ts b/modules/sdk-coin-icp/src/icp.ts index 74ae37274f8..7ae9a8622b0 100644 --- a/modules/sdk-coin-icp/src/icp.ts +++ b/modules/sdk-coin-icp/src/icp.ts @@ -16,6 +16,7 @@ import { multisigTypes, ParsedTransaction, ParseTransactionOptions, + RecoveryKeyMismatchError, RecoveryProviderError, SignedTransaction, SigningError, @@ -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'; @@ -345,7 +346,7 @@ export class Icp extends BaseCoin { } private getBuilderFactory(): TransactionBuilderFactory { - return new TransactionBuilderFactory(coins.get(this.getBaseChain())); + return new TransactionBuilderFactory(this._staticsCoin); } /** @@ -390,6 +391,7 @@ 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 { try { @@ -397,18 +399,23 @@ export class Icp extends BaseCoin { 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'); } @@ -416,18 +423,19 @@ export class Icp extends BaseCoin { 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'); + } + publicKey = MPC.deriveUnhardened(commonKeyChain, ROOT_PATH).slice(0, 66); } else { - const bitgoKey = params.bitgoKey; if (!bitgoKey) { throw new Error('missing bitgoKey'); } @@ -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}` + ); + } const balance = await this.getAccountBalance(publicKey); const feeData = await this.getFeeData(); if (balance.isLessThanOrEqualTo(0)) { @@ -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)) { @@ -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, @@ -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}`); diff --git a/modules/sdk-coin-icp/src/lib/iface.ts b/modules/sdk-coin-icp/src/lib/iface.ts index f1a83621d6b..65400340888 100644 --- a/modules/sdk-coin-icp/src/lib/iface.ts +++ b/modules/sdk-coin-icp/src/lib/iface.ts @@ -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 { diff --git a/modules/sdk-coin-icp/test/unit/icpSafeRecovery.ts b/modules/sdk-coin-icp/test/unit/icpSafeRecovery.ts new file mode 100644 index 00000000000..8fe041e60df --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/icpSafeRecovery.ts @@ -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') + ); + }); +}); diff --git a/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionRecover.ts b/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionRecover.ts index 0f6bc06b26a..cba11255656 100644 --- a/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionRecover.ts +++ b/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionRecover.ts @@ -1,4 +1,5 @@ import should from 'should'; +import assert from 'assert'; import * as testData from '../../resources/icp'; import sinon from 'sinon'; import { TestBitGo } from '@bitgo/sdk-test'; @@ -6,16 +7,16 @@ import { BitGoAPI } from '@bitgo/sdk-api'; import nock from 'nock'; import { Icp } from '../../../src/index'; import { IcpAgent } from '../../../src/lib/icpAgent'; -import { RecoveryOptions, LEDGER_CANISTER_ID } from '../../../src/lib/iface'; +import { RecoveryOptions, LEDGER_CANISTER_ID, Signatures } from '../../../src/lib/iface'; import { Principal } from '@dfinity/principal'; import BigNumber from 'bignumber.js'; -import { ErrorNoInputToRecover, RecoveryProviderError } from '@bitgo/sdk-core'; +import { Environments, ErrorNoInputToRecover, RecoveryKeyMismatchError, RecoveryProviderError } from '@bitgo/sdk-core'; import utils from '../../../src/lib/utils'; describe('ICP transaction recovery', async () => { let bitgo; let recoveryParams: RecoveryOptions; - let icp; + let icp: Icp; let broadcastEndpoint: string; let broadcastResponse: Buffer; let nodeUrl: string; @@ -28,7 +29,9 @@ describe('ICP transaction recovery', async () => { metaData: testData.MetaDataWithDefaultMemo, ingressEndTime: testData.MetaDataWithDefaultMemo.ingress_end ?? 0, }); - sinon.stub(icp, 'signatures').returns(testData.RecoverTransactionSignatureWithDefaultMemo); + sinon + .stub(icp, 'signatures') + .resolves(testData.RecoverTransactionSignatureWithDefaultMemo as unknown as Signatures[]); }; const setupMemoStubs = () => { @@ -38,7 +41,7 @@ describe('ICP transaction recovery', async () => { metaData: testData.MetaDataWithMemo, ingressEndTime: testData.MetaDataWithMemo.ingress_end ?? 0, }); - sinon.stub(icp, 'signatures').returns(testData.RecoverTransactionSignatureWithMemo); + sinon.stub(icp, 'signatures').resolves(testData.RecoverTransactionSignatureWithMemo as unknown as Signatures[]); }; const setupLowBalanceStubs = () => { @@ -62,7 +65,7 @@ describe('ICP transaction recovery', async () => { }; icp = bitgo.coin('icp'); - nodeUrl = icp.getPublicNodeUrl(); + nodeUrl = Environments[bitgo.getEnv()].icpNodeUrl; const principal = Principal.fromUint8Array(LEDGER_CANISTER_ID); const canisterIdHex = principal.toText(); broadcastEndpoint = `/api/v3/canister/${canisterIdHex}/call`; @@ -88,6 +91,7 @@ describe('ICP transaction recovery', async () => { it('should recover a transaction with default memo successfully', async () => { const recoverTxn = await icp.recover(recoveryParams); + assert('tx' in recoverTxn); recoverTxn.id.should.be.a.String(); should.equal(recoverTxn.id, testData.TxnIdWithDefaultMemo); }); @@ -97,10 +101,82 @@ describe('ICP transaction recovery', async () => { setupMemoStubs(); recoveryParams.memo = testData.MetaDataWithMemo.memo; const recoverTxn = await icp.recover(recoveryParams); + assert('tx' in recoverTxn); recoverTxn.id.should.be.a.String(); should.equal(recoverTxn.id, testData.TxnIdWithMemo); }); + it('should return a signed transaction without broadcasting when broadcast is false', async () => { + const broadcastStub = sinon.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast')); + const recoverTxn = await icp.recover({ ...recoveryParams, broadcast: false }); + assert('tx' in recoverTxn); + should.equal(recoverTxn.id, testData.TxnIdWithDefaultMemo); + should.equal(recoverTxn.tx, testData.RecoverySignedTransactionWithDefaultMemo); + should.equal(recoverTxn.txHex, testData.RecoverySignedTransactionWithDefaultMemo); + should.equal(recoverTxn.coin, 'icp'); + sinon.assert.notCalled(broadcastStub); + }); + + it('should produce the identical signed payload that legacy broadcasting would have submitted', async () => { + const legacyTxn = await icp.recover(recoveryParams); + const broadcastStub = sinon.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast')); + const offlineTxn = await icp.recover({ ...recoveryParams, broadcast: false }); + assert('tx' in legacyTxn); + assert('tx' in offlineTxn); + should.equal(offlineTxn.tx, legacyTxn.tx); + should.equal(offlineTxn.id, legacyTxn.id); + sinon.assert.notCalled(broadcastStub); + }); + + it('should fail closed on an invalid destination even in offline mode', async () => { + nock.cleanAll(); + sinon.restore(); + const broadcastStub = sinon.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast')); + const getBalanceStub = sinon.stub(IcpAgent.prototype, 'getBalance'); + const getFeeStub = sinon.stub(IcpAgent.prototype, 'getFee'); + const signaturesStub = sinon.stub(icp, 'signatures'); + await icp + .recover({ ...recoveryParams, recoveryDestination: 'invalid', broadcast: false }) + .should.rejectedWith('Error during ICP recovery: invalid recoveryDestination'); + sinon.assert.notCalled(broadcastStub); + sinon.assert.notCalled(getBalanceStub); + sinon.assert.notCalled(getFeeStub); + sinon.assert.notCalled(signaturesStub); + }); + + it('should fail closed when bitgoKey does not match the recovery keys', async () => { + await icp + .recover({ ...recoveryParams, bitgoKey: 'deadbeef', broadcast: false }) + .should.rejectedWith(RecoveryKeyMismatchError); + }); + + it('should fail closed when rootAddress does not match the derived address', async () => { + await icp + .recover({ ...recoveryParams, rootAddress: '00'.repeat(32), broadcast: false }) + .should.rejectedWith(RecoveryKeyMismatchError); + }); + + it('should ignore broadcast: false for an unsigned sweep', async () => { + sinon.restore(); + setupMemoStubs(); + const broadcastStub = sinon.stub(icp, 'broadcastTransaction').rejects(new Error('must not broadcast')); + const signaturesStub = icp.signatures as unknown as sinon.SinonStub; + + const unsignedSweepRecoveryParams = { + bitgoKey: + '0310768736a005ea5364e1b5b5288cf553224dd28b2df8ced63b72a8020478967f05ec5bce1f26cd7eb009a4bea445bb55c2f54a30f2706c1a3747e8df2d288829', + recoveryDestination: testData.Accounts.account2.address, + broadcast: false, + }; + const recoverTxn = await icp.recover(unsignedSweepRecoveryParams); + assert('txHex' in recoverTxn); + assert(!('id' in recoverTxn)); + should.equal(recoverTxn.txHex, testData.UnsignedSweepTransaction); + should.equal(recoverTxn.coin, 'icp'); + sinon.assert.notCalled(broadcastStub); + sinon.assert.notCalled(signaturesStub); + }); + it('should recover a unsigned sweep transaction successfully', async () => { sinon.restore(); setupMemoStubs(); @@ -111,6 +187,7 @@ describe('ICP transaction recovery', async () => { recoveryDestination: testData.Accounts.account2.address, }; const recoverTxn = await icp.recover(unsignedSweepRecoveryParams); + assert(!('id' in recoverTxn)); recoverTxn.txHex.should.be.a.String(); should.equal(recoverTxn.txHex, testData.UnsignedSweepTransaction); }); diff --git a/modules/sdk-core/src/bitgo/safe/recovery.ts b/modules/sdk-core/src/bitgo/safe/recovery.ts index e08ed393752..6dd94404054 100644 --- a/modules/sdk-core/src/bitgo/safe/recovery.ts +++ b/modules/sdk-core/src/bitgo/safe/recovery.ts @@ -97,6 +97,34 @@ export type SecpSafeRecoverKeyParams = { walletPassphrase?: string; }; +/** + * Slot-3 (ecdsaMpc) safe recovery key params. A discriminated union on `mode`, so the invalid + * combos are not representable: signed mode always carries the re-encrypted child reduced shares + * and the ephemeral passphrase; unsigned mode carries only the child common keychain. + * + * `broadcast: false` is always set so Safe recovery never auto-broadcasts: WRW's coin-agnostic + * engine spreads these params into `coin.recover()`, and ICP is the one coin whose `recover()` + * would otherwise submit the sweep to the network. + */ +export type EcdsaMpcSafeRecoverKeyParams = + | { + slot: 'ecdsaMpc'; + mode: 'signed'; + userKey: string; + backupKey: string; + bitgoKey: string; + walletPassphrase: string; + isTss: true; + broadcast: false; + } + | { + slot: 'ecdsaMpc'; + mode: 'unsigned'; + bitgoKey: string; + isTss: true; + broadcast: false; + }; + /** * Slot-2 (ed25519Multisig) safe recovery key params. A discriminated union on `mode`, so the invalid * combos are not representable: signed mode always carries the lazy signer and never a `backupKey`, @@ -133,7 +161,10 @@ export type Ed25519SafeRecoverKeyParams = rootAddress?: string; }; -export type SafeRecoverKeyParams = SecpSafeRecoverKeyParams | Ed25519SafeRecoverKeyParams; +export type SafeRecoverKeyParams = + | SecpSafeRecoverKeyParams + | Ed25519SafeRecoverKeyParams + | EcdsaMpcSafeRecoverKeyParams; export type DecryptedSafeRoots = { secp256k1Multisig: OnchainSafeRoot; @@ -340,10 +371,12 @@ export type SafeRecoverKeyParamsRequest = { /** * Builds the key fields `coin.recover()` expects from derived Safe child keys. - * Supports `secp256k1Multisig` (slot 1) and `ed25519Multisig` (slot 2); the MPC slots fail closed. - * Signed mode re-encrypts the child secrets under a fresh ephemeral passphrase (v1/SJCL); unsigned - * mode returns pubs. Where supported, `rootAddress` is derived from the child keys, not independently - * verified; otherwise it is omitted so the caller can supply it. + * Supports `secp256k1Multisig` (slot 1), `ed25519Multisig` (slot 2), and `ecdsaMpc` (slot 3); + * `eddsaMpc` fails closed. Signed mode re-encrypts the child secrets under a fresh ephemeral + * passphrase (v1/SJCL); unsigned mode returns pubs / the child common keychain. Where supported, + * `rootAddress` is derived from the child keys, not independently verified; otherwise it is + * omitted so the caller can supply it. `ecdsaMpc` params always carry `broadcast: false` so Safe + * recovery never auto-broadcasts. */ export async function buildSafeRecoverKeyParams( params: Extract @@ -351,6 +384,9 @@ export async function buildSafeRecoverKeyParams( export async function buildSafeRecoverKeyParams( params: Extract ): Promise; +export async function buildSafeRecoverKeyParams( + params: Extract +): Promise; export async function buildSafeRecoverKeyParams(params: SafeRecoverKeyParamsRequest): Promise; export async function buildSafeRecoverKeyParams(params: SafeRecoverKeyParamsRequest): Promise { const { bitgo, mode } = params; @@ -359,6 +395,37 @@ export async function buildSafeRecoverKeyParams(params: SafeRecoverKeyParamsRequ return buildEd25519MultisigRecoverKeyParams(bitgo, params.coin, params.keys, mode); } + if (params.slot === 'ecdsaMpc') { + const keys = params.keys; + + if (mode === 'unsigned') { + return { + slot: 'ecdsaMpc', + mode: 'unsigned', + bitgoKey: keys.commonKeychain, + isTss: true, + broadcast: false, + }; + } + + const walletPassphrase = randomBytes(32).toString('hex'); + const [userKey, backupKey] = await Promise.all([ + bitgo.encrypt({ input: keys.user, password: walletPassphrase, encryptionVersion: 1 }), + bitgo.encrypt({ input: keys.backup, password: walletPassphrase, encryptionVersion: 1 }), + ]); + + return { + slot: 'ecdsaMpc', + mode: 'signed', + userKey, + backupKey, + bitgoKey: keys.commonKeychain, + walletPassphrase, + isTss: true, + broadcast: false, + }; + } + if (params.slot === 'secp256k1Multisig') { const keys = params.keys; diff --git a/modules/sdk-core/test/unit/bitgo/safe/recovery.ts b/modules/sdk-core/test/unit/bitgo/safe/recovery.ts index 7bb788adf15..e7b67b53ec9 100644 --- a/modules/sdk-core/test/unit/bitgo/safe/recovery.ts +++ b/modules/sdk-core/test/unit/bitgo/safe/recovery.ts @@ -699,6 +699,67 @@ describe('buildSafeRecoverKeyParams', () => { }).should.be.rejectedWith(/ed25519 child public keys must be 32 bytes/); }); }); + + describe('ecdsaMpc', () => { + const mpcKeys = { commonKeychain: 'ck', user: 'user-child-share', backup: 'backup-child-share' }; + + it('signed mode re-encrypts the child reduced shares under a single ephemeral passphrase', async () => { + const passphrases: string[] = []; + const encrypt = sinon.stub().callsFake(async ({ input, password, encryptionVersion }) => { + passphrases.push(password); + encryptionVersion.should.equal(1); + return `enc(${input})`; + }); + const bitgo = { encrypt } as unknown as BitGoBase; + + const result = await buildSafeRecoverKeyParams({ + bitgo, + coin: 'icp', + slot: 'ecdsaMpc', + keys: mpcKeys, + mode: 'signed', + }); + + if (result.slot !== 'ecdsaMpc' || result.mode !== 'signed') { + throw new Error('expected signed ecdsaMpc key params'); + } + result.userKey.should.equal('enc(user-child-share)'); + result.backupKey.should.equal('enc(backup-child-share)'); + result.bitgoKey.should.equal('ck'); + result.isTss.should.equal(true); + result.broadcast.should.equal(false); + result.walletPassphrase.should.be.a.String(); + passphrases.should.have.length(2); + passphrases[0].should.equal(passphrases[1]); + passphrases[0].should.equal(result.walletPassphrase); + encrypt.callCount.should.equal(2); + }); + + it('unsigned mode returns the child common keychain and never encrypts', async () => { + const encrypt = sinon.stub().callsFake(async () => { + throw new Error('encrypt should not be called'); + }); + const bitgo = { encrypt } as unknown as BitGoBase; + + const result = await buildSafeRecoverKeyParams({ + bitgo, + coin: 'icp', + slot: 'ecdsaMpc', + keys: mpcKeys, + mode: 'unsigned', + }); + + result.slot.should.equal('ecdsaMpc'); + result.mode.should.equal('unsigned'); + result.bitgoKey.should.equal('ck'); + result.isTss.should.equal(true); + result.broadcast.should.equal(false); + result.should.not.have.property('userKey'); + result.should.not.have.property('backupKey'); + result.should.not.have.property('walletPassphrase'); + encrypt.callCount.should.equal(0); + }); + }); }); describe('Safe ecdsaMpc derive → sign (gate)', function () {