Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make ed25519 to use import flow by default #163

Merged
merged 11 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
60 changes: 30 additions & 30 deletions demo/redirect-flow-example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions demo/redirect-flow-example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const coreKitInstance = new Web3AuthMPCCoreKit(
storage: window.localStorage,
// sessionTime: 3600, // <== can provide variable session time based on user subscribed plan
tssLib,
useDkg: false
}
);

Expand Down
4 changes: 2 additions & 2 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export type MPCKeyDetails = {
tssPubKey?: TkeyPoint;
};

export type OAuthLoginParams = (SubVerifierDetailsParams | AggregateVerifierLoginParams) & { importTssKey?: string; useDkg?: boolean };
export type OAuthLoginParams = (SubVerifierDetailsParams | AggregateVerifierLoginParams) & { importTssKey?: string };
export type UserInfo = TorusVerifierResponse & LoginWindowResponse;

export interface EnableMFAParams {
Expand Down Expand Up @@ -407,7 +407,7 @@ export interface Web3AuthOptions {
/**
* Set this flag to false to generate keys on client side
* by default keys are generated on using dkg protocol on a distributed network
* @defaultValue undefined
* @defaultValue true if keyType is ed25519, false for secp256k1 keys
matthiasgeihs marked this conversation as resolved.
Show resolved Hide resolved
*/
useDkg?: boolean;
}
Expand Down
33 changes: 28 additions & 5 deletions src/mpcCoreKit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
Web3AuthState,
} from "./interfaces";
import {
bytesToHex,
deriveShareCoefficients,
ed25519,
generateFactorKey,
Expand All @@ -62,6 +63,7 @@ import {
getSessionId,
log,
parseToken,
randomBytes,
sampleEndpoints,
scalarBNToBufferSEC1,
} from "./utils";
Expand Down Expand Up @@ -245,7 +247,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
locationReplaceOnRedirect: true,
serverTimeOffset: this.options.serverTimeOffset,
keyType: this.keyType,
useDkg: this.options.useDkg,
useDkg: this.keyType === KeyType.ed25519 && this.options.useDkg === undefined ? true : this.options.useDkg,
himanshuchawla009 marked this conversation as resolved.
Show resolved Hide resolved
},
});

Expand Down Expand Up @@ -312,9 +314,21 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
if (this.isNodejsOrRN(this.options.uxMode)) {
throw CoreKitError.oauthLoginUnsupported(`Oauth login is NOT supported in ${this.options.uxMode} mode.`);
}
const { importTssKey } = params;
const { importTssKey: providedImportTssKey } = params;
const tkeyServiceProvider = this.torusSp;

let importTssKey = providedImportTssKey;

if (!importTssKey && !this.options.useDkg) {
if (this.keyType === KeyType.ed25519) {
importTssKey = bytesToHex(randomBytes(32));
} else if (this.keyType === KeyType.secp256k1) {
importTssKey = generateFactorKey().private.toString("hex", 64);
} else {
throw CoreKitError.default("Unsupported key type");
}
}

try {
// oAuth login.
const verifierParams = params as SubVerifierDetailsParams;
Expand Down Expand Up @@ -365,8 +379,17 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
throw CoreKitError.prefetchValueExceeded(`The prefetch value '${prefetchTssPublicKeys}' exceeds the maximum allowed limit of 3.`);
}

const { verifier, verifierId, idToken, importTssKey } = params;

const { verifier, verifierId, idToken, importTssKey: providedImportTssKey } = params;
let importTssKey = providedImportTssKey;
if (!importTssKey && !this.options.useDkg) {
if (this.keyType === KeyType.ed25519) {
importTssKey = bytesToHex(randomBytes(32));
} else if (this.keyType === KeyType.secp256k1) {
importTssKey = generateFactorKey().private.toString("hex", 64);
} else {
throw CoreKitError.default("Unsupported key type");
}
}
this.torusSp.verifierName = verifier;
this.torusSp.verifierId = verifierId;

Expand Down Expand Up @@ -643,7 +666,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
*/
public getPubKeyEd25519(): Buffer {
const p = this.tkey.tssCurve.keyFromPublic(this.getPubKey()).getPublic();
return ed25519.keyFromPublic(p).getPublic();
return ed25519().keyFromPublic(p).getPublic();
}

public async sign(data: Buffer, hashed: boolean = false): Promise<Buffer> {
Expand Down
29 changes: 28 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,35 @@ import loglevel from "loglevel";
import { DELIMITERS, SCALAR_LEN } from "./constants";
import { CoreKitSigner, EthereumSigner, IAsyncStorage, IStorage } from "./interfaces";

export const ed25519 = new EDDSA("ed25519");
export const ed25519 = () => {
return new EDDSA("ed25519");
};
matthiasgeihs marked this conversation as resolved.
Show resolved Hide resolved

const cr = () =>
himanshuchawla009 marked this conversation as resolved.
Show resolved Hide resolved
// We support: 1) browsers 2) node.js 19+
typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined;

// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
/**
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export function bytesToHex(bytes: Uint8Array): string {
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}

export const randomBytes = (len = 32): Uint8Array => {
// CSPRNG (random number generator)
const crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error:
// import { webcrypto } from 'node:crypto';
// if (!globalThis.crypto) globalThis.crypto = webcrypto;
if (!crypto || !crypto.getRandomValues) throw new Error("crypto.getRandomValues must be defined");
return crypto.getRandomValues(new Uint8Array(len));
};
himanshuchawla009 marked this conversation as resolved.
Show resolved Hide resolved
export const generateFactorKey = (): { private: BN; pub: TkeyPoint } => {
const keyPair = factorKeyCurve.genKeyPair();
const pub = Point.fromElliptic(keyPair.getPublic());
Expand Down
4 changes: 2 additions & 2 deletions tests/ed25519.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ variable.forEach((testVariable) => {
const msg = "hello world";
const msgBuffer = Buffer.from(msg);

const signature = ed25519.makeSignature((await coreKitInstance.sign(msgBuffer)).toString("hex"));
const valid = ed25519.verify(msgBuffer, signature, coreKitInstance.getPubKeyEd25519());
const signature = ed25519().makeSignature((await coreKitInstance.sign(msgBuffer)).toString("hex"));
const valid = ed25519().verify(msgBuffer, signature, coreKitInstance.getPubKeyEd25519());
assert(valid);
});
});
Expand Down
Loading