Skip to content

Commit

Permalink
Merge pull request #154 from torusresearch/feat/review-changes
Browse files Browse the repository at this point in the history
minor refactor
  • Loading branch information
himanshuchawla009 authored Jul 30, 2024
2 parents 7fa95fb + fcaba4b commit 7df0374
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 146 deletions.
58 changes: 29 additions & 29 deletions package-lock.json

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

12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@
"@toruslabs/eccrypto": "^5.0.4",
"@toruslabs/http-helpers": "^7.0.0",
"bn.js": "^5.2.1",
"elliptic": "^6.5.5",
"bs58": "^5.0.0",
"elliptic": "^6.5.6",
"bs58": "^6.0.0",
"ethereum-cryptography": "^2.2.1",
"json-stable-stringify": "^1.1.1",
"loglevel": "^1.9.1"
},
"devDependencies": {
"@babel/register": "^7.24.6",
"@babel/runtime": "^7.24.8",
"@babel/runtime": "^7.25.0",
"@toruslabs/config": "^2.1.0",
"@toruslabs/eslint-config-typescript": "^3.3.1",
"@toruslabs/fetch-node-details": "^14.0.1",
Expand All @@ -53,15 +53,15 @@
"dotenv": "^16.4.5",
"eslint": "^8.57.0",
"faker": "^5.5.3",
"husky": "^9.0.11",
"husky": "^9.1.4",
"jsonwebtoken": "^9.0.2",
"lint-staged": "^15.2.7",
"mocha": "^10.6.0",
"mocha": "^10.7.0",
"prettier": "^3.3.3",
"rimraf": "^6.0.1",
"sinon": "^18.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.5.3"
"typescript": "^5.5.4"
},
"repository": {
"type": "git",
Expand Down
4 changes: 2 additions & 2 deletions src/Polynomial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ class Polynomial {
for (let i = 1; i < this.polynomial.length; i += 1) {
const tmp = xi.mul(this.polynomial[i]);
sum = sum.add(tmp);
sum = sum.umod(this.ecCurve.curve.n);
sum = sum.umod(this.ecCurve.n);
xi = xi.mul(new BN(tmpX));
xi = xi.umod(this.ecCurve.curve.n);
xi = xi.umod(this.ecCurve.n);
}
return sum;
}
Expand Down
11 changes: 10 additions & 1 deletion src/helpers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@ import { JRPCResponse, KEY_TYPE } from "@toruslabs/constants";
import { Ecies } from "@toruslabs/eccrypto";
import { BN } from "bn.js";
import { ec as EC } from "elliptic";
import { keccak256 as keccakHash } from "ethereum-cryptography/keccak";
import JsonStringify from "json-stable-stringify";

import { CommitmentRequestResult, EciesHex, KeyType, VerifierLookupResponse } from "../interfaces";
import { keccak256 } from "./keyUtils";

export function keccak256(a: Buffer): string {
const hash = Buffer.from(keccakHash(a)).toString("hex");
return `0x${hash}`;
}

export const generatePrivateKey = (ecCurve: EC, buf: typeof Buffer): Buffer => {
return ecCurve.genKeyPair().getPrivate().toArrayLike(buf);
};

export const getKeyCurve = (keyType: KeyType) => {
if (keyType === KEY_TYPE.ED25519) {
Expand Down
72 changes: 17 additions & 55 deletions src/helpers/keyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,9 @@ import stringify from "json-stable-stringify";
import log from "loglevel";

import { EncryptedSeed, ImportedShare, KeyType, PrivateKeyData } from "../interfaces";
import { encParamsBufToHex, getKeyCurve } from "./common";
import { encParamsBufToHex, generatePrivateKey, getKeyCurve, keccak256 } from "./common";
import { generateRandomPolynomial } from "./langrangeInterpolatePoly";
import { generateNonceMetadataParams } from "./metadataUtils";

export function keccak256(a: Buffer): string {
const hash = Buffer.from(keccakHash(a)).toString("hex");
return `0x${hash}`;
}

export const generatePrivateKey = (ecCurve: EC, buf: typeof Buffer): Buffer => {
return ecCurve.genKeyPair().getPrivate().toArrayLike(buf);
};
import { generateNonceMetadataParams, getSecpKeyFromEd25519 } from "./metadataUtils";

export function stripHexPrefix(str: string): string {
return str.startsWith("0x") ? str.slice(2) : str;
Expand Down Expand Up @@ -81,30 +72,6 @@ export function getEd25519ExtendedPublicKey(keyBuffer: Buffer): {
return { scalar, point };
}

export const getSecpKeyFromEd25519 = (
ed25519Scalar: BN
): {
scalar: BN;
point: curve.base.BasePoint;
} => {
const secp256k1Curve = getKeyCurve(KEY_TYPE.SECP256K1);

const ed25519Key = ed25519Scalar.toString("hex", 64);
const keyHash = keccakHash(Buffer.from(ed25519Key, "hex"));
const secpKey = new BN(keyHash).umod(secp256k1Curve.curve.n).toString("hex", 64);
const bufferKey = Buffer.from(secpKey, "hex");

const secpKeyPair = secp256k1Curve.keyFromPrivate(bufferKey);

if (bufferKey.length < 32) {
throw new Error("Invalid key length, please try again");
}
return {
scalar: secpKeyPair.getPrivate(),
point: secpKeyPair.getPublic(),
};
};

export function encodeEd25519Point(point: curve.base.BasePoint) {
const ed25519Curve = getKeyCurve(KEY_TYPE.ED25519);

Expand Down Expand Up @@ -149,11 +116,11 @@ export const generateSecp256k1KeyData = async (scalarBuffer: Buffer): Promise<Pr

const scalar = new BN(scalarBuffer);
const randomNonce = new BN(generatePrivateKey(secp256k1Curve, Buffer));
const oAuthKey = scalar.sub(randomNonce).umod(secp256k1Curve.curve.n);
const oAuthKeyPair = secp256k1Curve.keyFromPrivate(oAuthKey.toString("hex").padStart(64, "0"));
const oAuthKey = scalar.sub(randomNonce).umod(secp256k1Curve.n);
const oAuthKeyPair = secp256k1Curve.keyFromPrivate(oAuthKey.toArrayLike(Buffer));
const oAuthPubKey = oAuthKeyPair.getPublic();

const finalUserKeyPair = secp256k1Curve.keyFromPrivate(scalar.toString("hex", 64));
const finalUserKeyPair = secp256k1Curve.keyFromPrivate(scalar.toString("hex", 64), "hex");

return {
oAuthKeyScalar: oAuthKeyPair.getPrivate(),
Expand All @@ -168,9 +135,7 @@ export const generateSecp256k1KeyData = async (scalarBuffer: Buffer): Promise<Pr
};
};

export function generateAddressFromPrivKey(keyType: KeyType, privateKey: BN): string {
const ecCurve = getKeyCurve(keyType);
const key = ecCurve.keyFromPrivate(privateKey.toString("hex", 64), "hex");
function generateAddressFromEcKey(keyType: KeyType, key: EC.KeyPair): string {
if (keyType === KEY_TYPE.SECP256K1) {
const publicKey = key.getPublic().encode("hex", false).slice(2);
const evmAddressLower = `0x${keccak256(Buffer.from(publicKey, "hex")).slice(64 - 38)}`;
Expand All @@ -183,30 +148,27 @@ export function generateAddressFromPrivKey(keyType: KeyType, privateKey: BN): st
throw new Error(`Invalid keyType: ${keyType}`);
}

export function generateAddressFromPrivKey(keyType: KeyType, privateKey: BN): string {
const ecCurve = getKeyCurve(keyType);
const key = ecCurve.keyFromPrivate(privateKey.toString("hex", 64), "hex");
return generateAddressFromEcKey(keyType, key);
}

export function generateAddressFromPubKey(keyType: KeyType, publicKeyX: BN, publicKeyY: BN): string {
const ecCurve = getKeyCurve(keyType);
const key = ecCurve.keyFromPublic({ x: publicKeyX.toString("hex", 64), y: publicKeyY.toString("hex", 64) });
if (keyType === KEY_TYPE.SECP256K1) {
const publicKey = key.getPublic().encode("hex", false).slice(2);
const evmAddressLower = `0x${keccak256(Buffer.from(publicKey, "hex")).slice(64 - 38)}`;
return toChecksumAddress(evmAddressLower);
} else if (keyType === KEY_TYPE.ED25519) {
const publicKey = encodeEd25519Point(key.getPublic());
const address = base58.encode(publicKey);
return address;
}
throw new Error(`Invalid keyType: ${keyType}`);
return generateAddressFromEcKey(keyType, key);
}

export function getPostboxKeyFrom1OutOf1(ecCurve: EC, privKey: string, nonce: string): string {
const privKeyBN = new BN(privKey, 16);
const nonceBN = new BN(nonce, 16);
return privKeyBN.sub(nonceBN).umod(ecCurve.curve.n).toString("hex");
return privKeyBN.sub(nonceBN).umod(ecCurve.n).toString("hex");
}

export function derivePubKey(ecCurve: EC, sk: BN): curve.base.BasePoint {
const skHex = sk.toString(16, 64);
return ecCurve.keyFromPrivate(skHex).getPublic();
return ecCurve.keyFromPrivate(skHex, "hex").getPublic();
}

export const getEncryptionEC = (): EC => {
Expand All @@ -230,7 +192,7 @@ export const generateShares = async (
for (const nodeIndex of nodeIndexes) {
nodeIndexesBn.push(new BN(nodeIndex));
}
const oAuthPubKey = ecCurve.keyFromPrivate(oAuthKey.toString("hex").padStart(64, "0")).getPublic();
const oAuthPubKey = ecCurve.keyFromPrivate(oAuthKey.toString("hex", 64), "hex").getPublic();
const poly = generateRandomPolynomial(ecCurve, degree, oAuthKey);
const shares = poly.generateShares(nodeIndexesBn);
const nonceParams = generateNonceMetadataParams(serverTimeOffset, "getOrSetNonce", metadataSigningKey, keyType, metadataNonce, encryptedSeed);
Expand All @@ -248,7 +210,7 @@ export const generateShares = async (
);
}
const encShares = await Promise.all(encPromises);
for (let i = 0; i < nodeIndexesBn.length; i++) {
for (let i = 0; i < nodeIndexesBn.length; i += 1) {
const shareJson = shares[nodeIndexesBn[i].toString("hex", 64)].toJSON() as Record<string, string>;
const encParams = encShares[i];
const encParamsMetadata = encParamsBufToHex(encParams);
Expand Down
Loading

0 comments on commit 7df0374

Please sign in to comment.