Skip to content

Commit 7e699d2

Browse files
committed
fix: stable with most test passed
1 parent 8e7fde9 commit 7e699d2

15 files changed

+327
-200
lines changed

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/mpcCoreKit.ts

Lines changed: 59 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,14 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
212212
// return this._sigType === "ed25519" && this.options.useClientGeneratedTSSKey === undefined ? true : !!this.options.useClientGeneratedTSSKey;
213213
// }
214214

215+
public getSupportedSigTypes(): Array<SigType> {
216+
return Array.from(this.supportedSigTypes);
217+
}
218+
219+
public getSupportedCurveKeyTypes(): Array<KeyType> {
220+
return Array.from(this.supportedCurveKeyTypes);
221+
}
222+
215223
/**
216224
* The threshold signing library to use.
217225
*/
@@ -314,7 +322,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
314322
const nodeDetails = fetchLocalConfig(this.options.web3AuthNetwork, KeyType.ed25519);
315323

316324
// multicurve only support for secp256k1 torus/ sss
317-
const keyType = this.getServiceProviderKeyType();
325+
const spKeyType = this.getServiceProviderKeyType();
318326

319327
this.torusSp = new TSSTorusServiceProvider({
320328
customAuthArgs: {
@@ -325,7 +333,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
325333
redirectPathName: this.options.redirectPathName,
326334
locationReplaceOnRedirect: true,
327335
serverTimeOffset: this.options.serverTimeOffset,
328-
keyType,
336+
keyType: spKeyType,
329337
useDkg: this.options.useDKG,
330338
},
331339
});
@@ -475,12 +483,12 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
475483
throw CoreKitError.invalidConfig("Cannot import TSS key and register SFA key at the same time.");
476484
}
477485

478-
const spKeyType = this.getServiceProviderKeyType();
486+
const fisrtKeyType = this.getSupportedCurveKeyTypes()[0];
479487
try {
480488
// prefetch tss pub keys.
481489
const prefetchTssPubs = [];
482490
for (let i = 0; i < prefetchTssPublicKeys; i++) {
483-
prefetchTssPubs.push(this.torusSp.getTSSPubKey(this.tkey.tssTag, i, spKeyType));
491+
prefetchTssPubs.push(this.torusSp.getTSSPubKey(this.tkey.tssTag, i, fisrtKeyType));
484492
}
485493

486494
// get postbox key.
@@ -505,10 +513,14 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
505513
if (loginResponse.metadata.typeOfUser === "v1") {
506514
throw CoreKitError.invalidConfig("Cannot register existing SFA key for v1 users, please contact web3auth support.");
507515
}
516+
const spKeyType = this.getServiceProviderKeyType();
517+
if (!this.supportedCurveKeyTypes.has(spKeyType)) {
518+
throw CoreKitError.invalidConfig("Cannot register existing SFA key for secp256k1 users to ed25519, please contact web3auth support.");
519+
}
508520
const existingSFAKey = loginResponse.finalKeyData.privKey.padStart(64, "0");
509521

510522
await this.setupTkey({
511-
providedImportKey: { [spKeyType]: existingSFAKey },
523+
providedImportKey: { [fisrtKeyType]: existingSFAKey },
512524
importingSFAKey: true,
513525
sfaLoginResponse: loginResponse,
514526
userInfo: { ...parseToken(idToken), verifier, verifierId },
@@ -693,8 +705,8 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
693705
if (!this.state.factorKey) {
694706
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when getting tss factor public key.");
695707
}
696-
const spKeyType = this.getServiceProviderKeyType();
697-
const tssData = this.getTssData({ keyType: spKeyType });
708+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
709+
const tssData = this.getTssData({ keyType: firstKeyType });
698710
const factorPubsList = tssData.factorPubs;
699711
return factorPubsList.map((factorPub) => factorPub.toSEC1(factorKeyCurve, true).toString("hex"));
700712
};
@@ -879,7 +891,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
879891
};
880892
}
881893

882-
public async signECDSA(data: Uint8Array, opts: { hashed?: boolean; secp256k1Precompute?: Secp256k1PrecomputedClient }) {
894+
public async signECDSA(data: Uint8Array, opts?: { hashed?: boolean; secp256k1Precompute?: Secp256k1PrecomputedClient }) {
883895
if (!this.supportedCurveKeyTypes.has(KeyType.secp256k1)) {
884896
throw CoreKitError.default(`secp256k1 KeyTYpe is not supported, please configure secp256k1 curve key type `);
885897
}
@@ -909,7 +921,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
909921
if (!frostlib) {
910922
throw CoreKitError.default(`frostlib not loaded for ed25519`);
911923
}
912-
return this.sign_frost({ data: Buffer.from(data), keyType: KeyType.secp256k1, sigType: SIG_TYPE.BIP340, frostlib, keyTweak: opts.keyTweak });
924+
return this.sign_frost({ data: Buffer.from(data), keyType: KeyType.secp256k1, sigType: SIG_TYPE.BIP340, frostlib, keyTweak: opts?.keyTweak });
913925
}
914926

915927
public async signEd25519(data: Uint8Array, opts?: { hashed?: boolean }) {
@@ -937,8 +949,8 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
937949
if (!this.state.factorKey) {
938950
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when deleting a factor.");
939951
}
940-
const spKeyType = this.getServiceProviderKeyType();
941-
const tssData = this.getTssData({ keyType: spKeyType });
952+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
953+
const tssData = this.getTssData({ keyType: firstKeyType });
942954
if (!tssData.factorPubs) {
943955
throw CoreKitError.factorPubsMissing();
944956
}
@@ -1155,20 +1167,22 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
11551167
sp.verifierName = userInfo.aggregateVerifier || userInfo.verifier;
11561168
}
11571169

1158-
const spKeyType = this.getServiceProviderKeyType();
11591170
const existingUser = await this.isMetadataPresent(this.state.postBoxKey);
11601171
const importKey = providedImportKey ?? {};
11611172
if (!existingUser) {
11621173
// if (!importKey && this.useClientGeneratedTSSKey) {
1163-
if (!importKey) {
1164-
if (spKeyType === KeyType.ed25519) {
1165-
const k = generateEd25519Seed();
1166-
importKey.ed25519 = k.toString("hex");
1167-
} else if (spKeyType === KeyType.secp256k1) {
1168-
const k = secp256k1.genKeyPair().getPrivate();
1169-
importKey.secp256k1 = scalarBNToBufferSEC1(k).toString("hex");
1170-
} else {
1171-
throw CoreKitError.default(`Unsupported key type and sig type combination `);
1174+
const keyTypes = this.getSupportedCurveKeyTypes();
1175+
for (const keyType of keyTypes) {
1176+
if (!importKey[keyType]) {
1177+
if (keyType === KeyType.ed25519) {
1178+
const k = generateEd25519Seed();
1179+
importKey.ed25519 = k.toString("hex");
1180+
} else if (keyType === KeyType.secp256k1) {
1181+
const k = secp256k1.genKeyPair().getPrivate();
1182+
importKey.secp256k1 = scalarBNToBufferSEC1(k).toString("hex");
1183+
} else {
1184+
throw CoreKitError.default(`Unsupported key type and sig type combination `);
1185+
}
11721186
}
11731187
}
11741188
if (importingSFAKey && sfaLoginResponse && sfaLoginResponse.metadata.upgraded) {
@@ -1259,12 +1273,25 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
12591273
authSignatures: this.state.signatures,
12601274
},
12611275
});
1262-
}
1263-
if (this.supportedCurveKeyTypes.has(KeyType.ed25519)) {
1276+
1277+
if (this.supportedCurveKeyTypes.has(KeyType.ed25519)) {
1278+
const importTssBufEd25519 = importTssKey.ed25519 ? Buffer.from(importTssKey.ed25519, "hex") : undefined;
1279+
// check if key is in the tsslib and keytype exists
1280+
await this.tKey.initializeTss({
1281+
importKey: importTssBufEd25519,
1282+
tssKeyType: KeyType.ed25519,
1283+
serverOpts: {
1284+
// selectedServers: [],
1285+
authSignatures: this.state.signatures,
1286+
},
1287+
});
1288+
}
1289+
} else {
12641290
const importTssBuf = importTssKey.ed25519 ? Buffer.from(importTssKey.ed25519, "hex") : undefined;
1265-
// check if key is in the tsslib and keytype exists
12661291
await this.tKey.initializeTss({
12671292
importKey: importTssBuf,
1293+
factorPub,
1294+
deviceTSSIndex,
12681295
tssKeyType: KeyType.ed25519,
12691296
serverOpts: {
12701297
// selectedServers: [],
@@ -1367,9 +1394,9 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
13671394
});
13681395
}
13691396

1370-
const spKeyType = this.getServiceProviderKeyType();
1397+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
13711398
// Read tss meta data.
1372-
const { tssIndex: tssShareIndex } = await this.getTssShare({ keyType: spKeyType, factorkey: factorKey });
1399+
const { tssIndex: tssShareIndex } = await this.getTssShare({ keyType: firstKeyType, factorkey: factorKey });
13731400
this.updateState({ tssShareIndex, factorKey });
13741401

13751402
await this.createSession();
@@ -1429,8 +1456,8 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
14291456
if (!this.state.factorKey) {
14301457
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when creating session.");
14311458
}
1432-
const spKeyType = this.getServiceProviderKeyType();
1433-
const { tssShare } = await this.getTssShare({ keyType: spKeyType, factorkey: this.state.factorKey });
1459+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
1460+
const { tssShare } = await this.getTssShare({ keyType: firstKeyType, factorkey: this.state.factorKey });
14341461
if (!postBoxKey || !factorKey || !tssShare || !userInfo) {
14351462
throw CoreKitError.userNotLoggedIn();
14361463
}
@@ -1486,8 +1513,8 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
14861513
*/
14871514
private async copyOrCreateShare(newFactorTSSIndex: number, newFactorPub: Point) {
14881515
this.checkReady();
1489-
const spKeyType = this.getServiceProviderKeyType();
1490-
const tssData = this.getTssData({ keyType: spKeyType });
1516+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
1517+
const tssData = this.getTssData({ keyType: firstKeyType });
14911518
if (!tssData.factorPubs || !Array.isArray(tssData.factorPubs)) {
14921519
throw CoreKitError.factorPubsMissing("'factorPubs' is missing in the metadata. Failed to copy factor public key.");
14931520
}
@@ -1565,8 +1592,8 @@ export class Web3AuthMPCCoreKit implements ICoreKit, IMPCContext {
15651592
additionalMetadata = {};
15661593
}
15671594

1568-
const spKeyType = this.getServiceProviderKeyType();
1569-
const { tssIndex } = await this.getTssShare({ keyType: spKeyType, factorkey: factorKey });
1595+
const firstKeyType = this.getSupportedCurveKeyTypes()[0];
1596+
const { tssIndex } = await this.getTssShare({ keyType: firstKeyType, factorkey: factorKey });
15701597
const factorPoint = getPubKeyPoint(factorKey, factorKeyCurve);
15711598
const factorPub = factorPoint.toSEC1(factorKeyCurve, true).toString("hex");
15721599

src/utils.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,5 +211,37 @@ export function makeEthereumSigner(kit: CoreKitSigner): EthereumSigner {
211211
};
212212
}
213213

214+
// export function makeBip340Signer(kit: CoreKitSigner): EthereumSigner {
215+
// if (kit.keyType !== KeyType.secp256k1) {
216+
// throw new Error(`Invalid key type: expected secp256k1, got ${kit.keyType}`);
217+
// }
218+
// return {
219+
// sign: async (msgHash: Buffer) => {
220+
// const sig = await kit.sign(msgHash, { hashed: true });
221+
// return sigToRSV(sig);
222+
// },
223+
// getPublic: async () => {
224+
// const pk = Point.fromSEC1(secp256k1, kit.getPubKey().toString("hex"));
225+
// return pk.toSEC1(secp256k1).subarray(1);
226+
// },
227+
// };
228+
// }
229+
230+
export function makeEd25519Signer(kit: CoreKitSigner): EthereumSigner {
231+
if (kit.keyType !== KeyType.secp256k1) {
232+
throw new Error(`Invalid key type: expected secp256k1, got ${kit.keyType}`);
233+
}
234+
return {
235+
sign: async (msgHash: Buffer) => {
236+
const sig = await kit.sign(msgHash, { hashed: true });
237+
return sigToRSV(sig);
238+
},
239+
getPublic: async () => {
240+
const pk = Point.fromSEC1(secp256k1, kit.getPubKey().toString("hex"));
241+
return pk.toSEC1(secp256k1).subarray(1);
242+
},
243+
};
244+
}
245+
214246
export const log = loglevel.getLogger("mpc-core-kit");
215247
log.disableAll();

tests/backwardCompatible.spec.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import assert from "node:assert";
22
import test from "node:test";
33

4-
import { EllipticPoint } from "@tkey/common-types";
4+
import { EllipticPoint, KeyType } from "@tkey/common-types";
55
import { UX_MODE_TYPE } from "@toruslabs/customauth";
66
import { keccak256 } from "@toruslabs/metadata-helpers";
77
import { tssLib } from "@toruslabs/tss-dkls-lib";
@@ -33,24 +33,29 @@ const checkLogin = async (coreKitInstance: Web3AuthMPCCoreKit) => {
3333
assert.strictEqual(coreKitInstance.status, COREKIT_STATUS.LOGGED_IN);
3434
assert.strictEqual(keyDetails.requiredFactors, 0);
3535
const factorkey = coreKitInstance.getCurrentFactorKey();
36-
await coreKitInstance.getTssShare(new BN(factorkey.factorKey, "hex"));
36+
const keyType = coreKitInstance.getSupportedCurveKeyTypes()[0];
37+
await coreKitInstance.getTssShare({keyType, factorkey: new BN(factorkey.factorKey, "hex")});
3738
};
3839

3940
variable.forEach((testVariable) => {
4041
const { web3AuthNetwork, uxMode, manualSync, email } = testVariable;
42+
const keyType = tssLib.keyType as KeyType;
4143

4244
const storageInstance = new MemoryStorage();
43-
const newCoreKitInstance = () =>
44-
new Web3AuthMPCCoreKit({
45+
const newCoreKitInstance = () => {
46+
const instance = new Web3AuthMPCCoreKit({
4547
web3AuthClientId: "torus-key-test",
4648
web3AuthNetwork,
4749
baseUrl: "http://localhost:3000",
4850
uxMode,
49-
tssLibs: [tssLib],
51+
supportedKeyTypes: [keyType],
5052
storage: storageInstance,
5153
manualSync,
5254
legacyFlag: true,
5355
});
56+
instance.addTssLibs([tssLib])
57+
return instance;
58+
}
5459

5560
const coreKitInstance = newCoreKitInstance();
5661

@@ -75,14 +80,11 @@ variable.forEach((testVariable) => {
7580
// get key details
7681
await checkLogin(coreKitInstance);
7782

78-
const tssPublicPoint = bufferToElliptic(coreKitInstance.getPubKey());
79-
const { metadataPubKey, tssPubKey } = coreKitInstance.getKeyDetails();
83+
const tssPublicPoint = bufferToElliptic(coreKitInstance.getPubKey(keyType));
84+
const { metadataPubKey } = coreKitInstance.getKeyDetails();
8085
assert.strictEqual(tssPublicPoint.getX().toString("hex"), "d2869f27c3e226d90b275b008f7dc67b8f4b208900a7b98ecc4e5266807d382c");
8186
assert.strictEqual(tssPublicPoint.getY().toString("hex"), "15860fd569413eb7f177e655c4bf855f37920b800235de344fdd518196becfe0");
8287

83-
assert.strictEqual(tssPubKey.x.toString("hex"), "d2869f27c3e226d90b275b008f7dc67b8f4b208900a7b98ecc4e5266807d382c");
84-
assert.strictEqual(tssPubKey.y.toString("hex"), "15860fd569413eb7f177e655c4bf855f37920b800235de344fdd518196becfe0");
85-
8688
assert.strictEqual(metadataPubKey.x.toString("hex"), "b3951a441f87ecea4672edc82894ac023316723cf164a93adec72b58a27a1f06");
8789
assert.strictEqual(metadataPubKey.y.toString("hex"), "3be6c118d94242a650e8aebbefcd37ebeceeb927d0ed51f3d2ba723b8fd2740b");
8890
});
@@ -122,11 +124,11 @@ variable.forEach((testVariable) => {
122124
const msg = "hello world";
123125
const msgBuffer = Buffer.from(msg);
124126
const msgHash = keccak256(msgBuffer);
125-
const signature = sigToRSV(await coreKitInstance.sign(msgHash, { hashed: true } ));
127+
const signature = sigToRSV(await coreKitInstance.signECDSA(msgHash, { hashed: true } ));
126128

127129
const secp256k1 = new EC("secp256k1");
128130
const pubkey = secp256k1.recoverPubKey(msgHash, signature, signature.v) as EllipticPoint;
129-
const publicKeyPoint = bufferToElliptic(coreKitInstance.getPubKey());
131+
const publicKeyPoint = bufferToElliptic(coreKitInstance.getPubKey(keyType));
130132
assert(pubkey.eq(publicKeyPoint));
131133
});
132134
});

0 commit comments

Comments
 (0)