Skip to content
Open
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
93 changes: 66 additions & 27 deletions modules/sdk-coin-iota/src/iota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
EDDSAMethods,
EDDSAMethodTypes,
Environments,
getEddsaSigningMaterial,
KeyPair,
MPCAlgorithm,
MPCConsolidationRecoveryOptions,
Expand All @@ -20,6 +21,7 @@ import {
PopulatedIntent,
PrebuildTransactionWithIntentOptions,
RecoveryTxRequest,
signEddsaMpcV2RecoveryTx,
SignedTransaction,
SignTransactionOptions,
TransactionRecipient,
Expand Down Expand Up @@ -303,6 +305,9 @@ export class Iota extends BaseCoin {
const bitgoKey = params.bitgoKey.replace(/\s/g, '');
const MPC = await EDDSAMethods.getInitializedMpcInstance();

// Detect MPCv2 keycard format once up front, to avoid decrypting on every scan iteration.
const isMpcV2 = await this.isMpcv2SigningMaterial(params.userKey, params.backupKey, params.walletPassphrase);

for (let idx = startIdx; idx < endIdx; idx++) {
const derivationPath = (params.seed ? getDerivationPath(params.seed) : 'm') + `/${idx}`;
const derivedPublicKey = MPC.deriveUnhardened(bitgoKey, derivationPath).slice(0, 64);
Expand Down Expand Up @@ -337,7 +342,8 @@ export class Iota extends BaseCoin {
derivationPath,
derivedPublicKey,
idx,
bitgoKey
bitgoKey,
isMpcV2
);
} catch (e) {
continue;
Expand Down Expand Up @@ -398,7 +404,9 @@ export class Iota extends BaseCoin {
params,
derivationPath,
derivedPublicKey,
unsignedTx
unsignedTx,
isMpcV2,
bitgoKey
);

// Build and return signed transaction
Expand Down Expand Up @@ -706,7 +714,8 @@ export class Iota extends BaseCoin {
derivationPath: string,
derivedPublicKey: string,
idx: number,
bitgoKey: string
bitgoKey: string,
isMpcV2: boolean
): Promise<MPCTxs | MPCSweepTxs> {
tokenObjectsWithBalance = tokenObjectsWithBalance.sort((a, b) => (BigInt(b.balance) > BigInt(a.balance) ? 1 : -1));
if (tokenObjectsWithBalance.length > MAX_OBJECT_LIMIT) {
Expand Down Expand Up @@ -780,7 +789,9 @@ export class Iota extends BaseCoin {
params,
derivationPath,
derivedPublicKey,
unsignedTx
unsignedTx,
isMpcV2,
bitgoKey
);

const finalTx = (await txBuilder.build()) as TransferTransaction;
Expand All @@ -800,12 +811,26 @@ export class Iota extends BaseCoin {
};
}

private async isMpcv2SigningMaterial(
userKey?: string,
backupKey?: string,
walletPassphrase?: string
): Promise<boolean> {
if (!walletPassphrase) return false;
if (!userKey) throw new Error('missing userKey');
if (!backupKey) throw new Error('missing backupKey');
const material = await getEddsaSigningMaterial(userKey.replace(/\s/g, ''), walletPassphrase, this.bitgo);
return material.version === 'v2';
}

private async signRecoveryTransaction(
txBuilder: TransactionBuilder,
params: IotaRecoveryOptions,
derivationPath: string,
derivedPublicKey: string,
unsignedTx: TransferTransaction
unsignedTx: TransferTransaction,
isMpcV2: boolean,
bitgoKey: string
): Promise<string> {
if (!params.userKey) {
throw new Error('missing userKey');
Expand All @@ -820,30 +845,44 @@ export class Iota extends BaseCoin {
const userKey = params.userKey.replace(/\s/g, '');
const backupKey = params.backupKey.replace(/\s/g, '');

// Decrypt private keys from KeyCard values
let userPrv: string;
try {
userPrv = await this.bitgo.decrypt({ input: userKey, password: params.walletPassphrase });
} catch (e) {
throw new Error(`Error decrypting user keychain: ${(e as Error).message}`);
}
const userSigningMaterial = JSON.parse(userPrv) as EDDSAMethodTypes.UserSigningMaterial;
let signatureBuffer: Buffer;

let backupPrv: string;
try {
backupPrv = await this.bitgo.decrypt({ input: backupKey, password: params.walletPassphrase });
} catch (e) {
throw new Error(`Error decrypting backup keychain: ${(e as Error).message}`);
}
const backupSigningMaterial = JSON.parse(backupPrv) as EDDSAMethodTypes.BackupSigningMaterial;
if (!isMpcV2) {
// Decrypt private keys from KeyCard values
let userPrv: string;
try {
userPrv = await this.bitgo.decrypt({ input: userKey, password: params.walletPassphrase });
} catch (e) {
throw new Error(`Error decrypting user keychain: ${(e as Error).message}`);
}
const userSigningMaterial = JSON.parse(userPrv) as EDDSAMethodTypes.UserSigningMaterial;

// Generate TSS signature
const signatureBuffer = await EDDSAMethods.getTSSSignature(
userSigningMaterial,
backupSigningMaterial,
derivationPath,
unsignedTx
);
let backupPrv: string;
try {
backupPrv = await this.bitgo.decrypt({ input: backupKey, password: params.walletPassphrase });
} catch (e) {
throw new Error(`Error decrypting backup keychain: ${(e as Error).message}`);
}
const backupSigningMaterial = JSON.parse(backupPrv) as EDDSAMethodTypes.BackupSigningMaterial;

// Generate TSS signature
signatureBuffer = await EDDSAMethods.getTSSSignature(
userSigningMaterial,
backupSigningMaterial,
derivationPath,
unsignedTx
);
} else {
signatureBuffer = await signEddsaMpcV2RecoveryTx({
message: unsignedTx.signablePayload,
userKey,
backupKey,
walletPassphrase: params.walletPassphrase,
bitgoKey,
derivationPath,
bitgo: this.bitgo,
});
}

// Build full signature: scheme_flag (1 byte) + signature (64 bytes) + public_key (32 bytes)
const schemeFlag = Buffer.alloc(1, 0x00); // Ed25519 scheme
Expand Down
199 changes: 197 additions & 2 deletions modules/sdk-coin-iota/test/unit/iota.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import should from 'should';
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
import { BitGoAPI } from '@bitgo/sdk-api';
import { BitGoAPI, encrypt } from '@bitgo/sdk-api';
import { Iota, TransactionBuilderFactory, TransferTransaction } from '../../src';
import assert from 'assert';
import { coins, GasTankAccountCoin } from '@bitgo/statics';
import * as testData from '../resources/iota';
import { TransactionType } from '@bitgo/sdk-core';
import { EDDSAMethods, TransactionType } from '@bitgo/sdk-core';
import { createTransferBuilderWithGas } from './helpers/testHelpers';
import sinon from 'sinon';
import { keys } from '../resources/iota';
import { MPSUtil } from '@bitgo/sdk-lib-mpc';
import utils from '../../src/lib/utils';

describe('IOTA:', function () {
let bitgo: TestBitGoAPI;
Expand Down Expand Up @@ -671,6 +673,199 @@ describe('IOTA:', function () {
sandBox.assert.callCount(basecoin.fetchOwnedObjects, 1);
sandBox.assert.callCount(basecoin.estimateGas, 1);
});

it('should handle error in recover function if a required field is missing', async function () {
// missing userKey
await basecoin
.recover({
backupKey: keys.backupKey,
bitgoKey: keys.bitgoKey,
recoveryDestination,
walletPassphrase,
})
.should.be.rejectedWith('missing userKey');

// missing backupKey
await basecoin
.recover({
userKey: keys.userKey,
bitgoKey: keys.bitgoKey,
recoveryDestination,
walletPassphrase,
})
.should.be.rejectedWith('missing backupKey');
});
});

describe('Recover Transactions (MPCv2):', () => {
const sandBox = sinon.createSandbox();
const recoveryDestination = '0xda97e166d40fa6a0c949b6aeb862e391c29139b563ae0430b2419c589a02a6e0';
const walletPassphrase = 'p$Sw<RjvAgf{nYAYI2xM';
const tokenContractAddress = '0xabcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
const validDigest = '7BJLb32LKN7wt5uv4xgXW4AbFKoMNcPE76o41TQEvUZb';

let mpcV2UserKey: string;
let mpcV2BackupKey: string;
let mpcV2CommonKeyChain: string;
let mpcV2SenderAddress: string;
let mismatchedBitgoKey: string;

before(async function () {
const [userDkg, backupDkg] = await MPSUtil.generateEdDsaDKGKeyShares();
const [otherUserDkg] = await MPSUtil.generateEdDsaDKGKeyShares();

mpcV2UserKey = await encrypt(walletPassphrase, userDkg.getReducedKeyShare().toString('base64'));
mpcV2BackupKey = await encrypt(walletPassphrase, backupDkg.getReducedKeyShare().toString('base64'));
mpcV2CommonKeyChain = userDkg.getCommonKeychain();
mismatchedBitgoKey = otherUserDkg.getCommonKeychain();

const mpc = await EDDSAMethods.getInitializedMpcInstance();
const derivedPublicKey = mpc.deriveUnhardened(mpcV2CommonKeyChain, 'm/0').slice(0, 64);
mpcV2SenderAddress = utils.getAddressFromPublicKey(derivedPublicKey);
});

afterEach(() => {
sandBox.restore();
});

it('should route to MPCv2 path for native IOTA recovery when keycard is MPCv2', async function () {
sandBox.stub(Iota.prototype, 'fetchOwnedObjects' as keyof Iota).resolves([
{
objectId: '0xc05c765e26e6ae84c78fa245f38a23fb20406a5cf3f61b57bd323a0df9d98003',
version: '195',
digest: validDigest,
balance: '1900000000',
},
]);
sandBox.stub(Iota.prototype, 'fetchGasPrice' as keyof Iota).resolves(1000);
sandBox.stub(Iota.prototype, 'estimateGas' as keyof Iota).resolves(1997880);
const getTSSSignatureSpy = sandBox.spy(EDDSAMethods, 'getTSSSignature');

const res = await basecoin.recover({
userKey: mpcV2UserKey,
backupKey: mpcV2BackupKey,
bitgoKey: mpcV2CommonKeyChain,
recoveryDestination,
walletPassphrase,
});

res.should.not.be.empty();
res.should.hasOwnProperty('transactions');
const tx = res.transactions[0];
tx.scanIndex.should.equal(0);
tx.recoveryAmount.should.equal('1897802332');

const sigBuffer = Buffer.from(tx.signature, 'base64');
sigBuffer.length.should.equal(97); // 1 flag byte + 64-byte signature + 32-byte public key
sigBuffer[0].should.equal(0x00);

sandBox.assert.notCalled(getTSSSignatureSpy);
});

it('should throw when MPCv2 commonKeyChain does not match bitgoKey', async function () {
sandBox.stub(Iota.prototype, 'fetchOwnedObjects' as keyof Iota).resolves([
{
objectId: '0xc05c765e26e6ae84c78fa245f38a23fb20406a5cf3f61b57bd323a0df9d98003',
version: '195',
digest: validDigest,
balance: '1900000000',
},
]);
sandBox.stub(Iota.prototype, 'fetchGasPrice' as keyof Iota).resolves(1000);
sandBox.stub(Iota.prototype, 'estimateGas' as keyof Iota).resolves(1997880);

await basecoin
.recover({
userKey: mpcV2UserKey,
backupKey: mpcV2BackupKey,
bitgoKey: mismatchedBitgoKey,
recoveryDestination,
walletPassphrase,
})
.should.be.rejectedWith('EdDSA MPCv2 recovery: commonKeyChain from keycard does not match bitgoKey');
});

it('should route to MPCv2 path for token recovery when keycard is MPCv2', async function () {
sandBox.stub(Iota.prototype, 'hasTokenBalance' as keyof Iota).callsFake(function (addr: string) {
return Promise.resolve(addr === mpcV2SenderAddress);
});
sandBox
.stub(Iota.prototype, 'fetchOwnedObjects' as keyof Iota)
.callsFake(function (addr: string, _rpc: unknown, coinType: string) {
if (addr === mpcV2SenderAddress && coinType === tokenContractAddress) {
return Promise.resolve([
{
objectId: '0xaaaa' + mpcV2SenderAddress.slice(6),
version: '100',
digest: validDigest,
balance: '1000',
},
]);
}
if (addr === mpcV2SenderAddress && !coinType) {
return Promise.resolve([
{
objectId: '0xbbbb' + mpcV2SenderAddress.slice(6),
version: '200',
digest: validDigest,
balance: '500000000',
},
]);
}
return Promise.resolve([]);
});
sandBox.stub(Iota.prototype, 'fetchGasPrice' as keyof Iota).resolves(1000);
sandBox.stub(Iota.prototype, 'estimateGas' as keyof Iota).resolves(2345504);
const getTSSSignatureSpy = sandBox.spy(EDDSAMethods, 'getTSSSignature');

const res = await basecoin.recover({
userKey: mpcV2UserKey,
backupKey: mpcV2BackupKey,
bitgoKey: mpcV2CommonKeyChain,
recoveryDestination,
walletPassphrase,
tokenContractAddress,
});

res.should.not.be.empty();
res.should.hasOwnProperty('transactions');
const tx = res.transactions[0];
tx.scanIndex.should.equal(0);
tx.recoveryAmount.should.equal('1000');
tx.coin.should.equal(tokenContractAddress);

const sigBuffer = Buffer.from(tx.signature, 'base64');
sigBuffer.length.should.equal(97);
sigBuffer[0].should.equal(0x00);

sandBox.assert.notCalled(getTSSSignatureSpy);
});

it('should still use the MPCv1 signing path when the keycard is MPCv1 (regression)', async function () {
sandBox.stub(Iota.prototype, 'fetchOwnedObjects' as keyof Iota).resolves([
{
objectId: '0xc05c765e26e6ae84c78fa245f38a23fb20406a5cf3f61b57bd323a0df9d98003',
version: '195',
digest: validDigest,
balance: '1900000000',
},
]);
sandBox.stub(Iota.prototype, 'fetchGasPrice' as keyof Iota).resolves(1000);
sandBox.stub(Iota.prototype, 'estimateGas' as keyof Iota).resolves(1997880);
const getTSSSignatureSpy = sandBox.spy(EDDSAMethods, 'getTSSSignature');

const res = await basecoin.recover({
userKey: keys.userKey,
backupKey: keys.backupKey,
bitgoKey: keys.bitgoKey,
recoveryDestination,
walletPassphrase: 'p$Sw<RjvAgf{nYAYI2xM',
});

res.should.not.be.empty();
res.should.hasOwnProperty('transactions');
sandBox.assert.calledOnce(getTSSSignatureSpy);
});
});

describe('Recover Transactions for wallet with multiple addresses:', () => {
Expand Down
Loading