Skip to content
Merged
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
22 changes: 11 additions & 11 deletions packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ class ThresholdKey implements ITKey {
shareArr.push(this.shares[pubPolyID][polyShares[i]].share.share);
shareIndexArr.push(this.shares[pubPolyID][polyShares[i]].share.shareIndex);
}
const privKey = lagrangeInterpolation(shareArr, shareIndexArr);
const privKey = lagrangeInterpolation(shareArr, shareIndexArr, this.ecCurve);
// check that priv key regenerated is correct
const reconstructedPubKey = getPubKeyPoint(privKey, this.keyType);
if (this.metadata.pubKey.x.cmp(reconstructedPubKey.x) !== 0) {
Expand Down Expand Up @@ -484,7 +484,7 @@ class ThresholdKey implements ITKey {
for (let i = 0; i < threshold; i += 1) {
pointsArr.push(new Point(new BN(sharesForExistingPoly[i], "hex"), this.shares[pubPolyID][sharesForExistingPoly[i]].share.share, this.keyType));
}
return lagrangeInterpolatePolynomial(pointsArr);
return lagrangeInterpolatePolynomial(pointsArr, this.ecCurve);
}

async deleteShare(shareIndex: BNString): Promise<DeleteShareResult> {
Expand Down Expand Up @@ -571,7 +571,7 @@ class ThresholdKey implements ITKey {
new Point(new BN(sharesForExistingPoly[i], "hex"), this.shares[previousPolyID][sharesForExistingPoly[i]].share.share, this.keyType)
);
}
const oldPoly = lagrangeInterpolatePolynomial(pointsArr);
const oldPoly = lagrangeInterpolatePolynomial(pointsArr, this.ecCurve);

const shareIndexesNeedingEncryption: string[] = [];
for (let index = 0; index < existingShareIndexes.length; index += 1) {
Expand Down Expand Up @@ -659,7 +659,7 @@ class ThresholdKey implements ITKey {
delete1OutOf1?: boolean;
} = {}): Promise<InitializeNewKeyResult> {
if (this.keyType === KeyType.secp256k1) {
const tmpPriv = importedKey ? importedKey : generatePrivate(this.ecCurve);
const tmpPriv = importedKey || generatePrivate(this.ecCurve);
this._setKey(new BN(tmpPriv));
} else {
const seed = importedKey ? importedKey.toBuffer() : nacl.randomBytes(32);
Expand All @@ -668,11 +668,11 @@ class ThresholdKey implements ITKey {
// need to decode from le ??
const tempPriv = new BN(keyPair.secretKey);
this._setKey(tempPriv);

// encrypt and add to local metadata transitions
const encMsg = await this.encrypt(Buffer.from(seed));
await this.addLocalMetadataTransitions({ input: [{ message: JSON.stringify(encMsg), dateAdded: Date.now() }], privKey: [tempPriv] });

// testing and checking code - to remove
// const decMsg = await this.decrypt(encMsg);
// const decSeed = Buffer.from(decMsg).toString("hex");
Expand Down Expand Up @@ -1298,8 +1298,8 @@ class ThresholdKey implements ITKey {
await this.inputShareStoreSafe(shareStore);
}

// Export Tkey
async exportFinalKey(): Promise<String> {
// Export Tkey
async exportFinalKey(): Promise<string> {
if (!this.metadata) {
throw CoreError.metadataUndefined();
}
Expand All @@ -1310,8 +1310,8 @@ class ThresholdKey implements ITKey {
if (this.keyType === KeyType.secp256k1) {
return this.privKey.toString("hex");
} else if (this.keyType === KeyType.ed25519) {
let result: EncryptedMessage = await this.storageLayer.getMetadata({privKey: this.privKey});
let seed = await this.decrypt(result);
const result: EncryptedMessage = await this.storageLayer.getMetadata({ privKey: this.privKey });
const seed = await this.decrypt(result);
return seed.toString("hex");
}
throw CoreError.default("Invalid KeyType");
Expand Down Expand Up @@ -1345,7 +1345,7 @@ class ThresholdKey implements ITKey {
for (let i = 0; i < threshold; i += 1) {
pointsArr.push(new Point(new BN(sharesForExistingPoly[i], "hex"), this.shares[pubPolyID][sharesForExistingPoly[i]].share.share, this.keyType));
}
const currentPoly = lagrangeInterpolatePolynomial(pointsArr);
const currentPoly = lagrangeInterpolatePolynomial(pointsArr, this.ecCurve);
const allExistingShares = currentPoly.generateShares(existingShareIndexes);
const shareArray = existingShareIndexes.map((shareIndex) => {
return this.metadata.shareToShareStore(allExistingShares[shareIndex].share);
Expand Down
31 changes: 16 additions & 15 deletions packages/core/src/lagrangeInterpolatePolynomial.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ecCurve, generatePrivateExcludingIndexes, KeyType, Point, Polynomial, Share } from "@tkey/common-types";
import { generatePrivateExcludingIndexes, KeyType, keyTypeToCurve, Point, Polynomial, Share } from "@tkey/common-types";
import { generatePrivate } from "@toruslabs/eccrypto";
import BN from "bn.js";
import { curve, ec as EllipticCurve } from "elliptic";
Expand All @@ -7,7 +7,7 @@ import CoreError from "./errors";

const generateEmptyBNArray = (length: number): BN[] => Array.from({ length }, () => new BN(0));

const denominator = (i: number, innerPoints: Array<Point>) => {
const denominator = (i: number, innerPoints: Array<Point>, ecCurve: EllipticCurve) => {
let result = new BN(1);
const xi = innerPoints[i].x;
for (let j = innerPoints.length - 1; j >= 0; j -= 1) {
Expand All @@ -22,9 +22,9 @@ const denominator = (i: number, innerPoints: Array<Point>) => {
return result;
};

const interpolationPoly = (i: number, innerPoints: Array<Point>): BN[] => {
const interpolationPoly = (i: number, innerPoints: Array<Point>, ecCurve: EllipticCurve): BN[] => {
let coefficients = generateEmptyBNArray(innerPoints.length);
const d = denominator(i, innerPoints);
const d = denominator(i, innerPoints, ecCurve);
if (d.cmp(new BN(0)) === 0) {
throw CoreError.default("Denominator for interpolationPoly is 0");
}
Expand Down Expand Up @@ -60,11 +60,11 @@ const pointSort = (innerPoints: Point[]): Point[] => {
return pointArrClone;
};

const lagrange = (unsortedPoints: Point[]) => {
const lagrange = (unsortedPoints: Point[], ecCurve: EllipticCurve) => {
const sortedPoints = pointSort(unsortedPoints);
const polynomial = generateEmptyBNArray(sortedPoints.length);
for (let i = 0; i < sortedPoints.length; i += 1) {
const coefficients = interpolationPoly(i, sortedPoints);
const coefficients = interpolationPoly(i, sortedPoints, ecCurve);
for (let k = 0; k < sortedPoints.length; k += 1) {
let tmp = new BN(sortedPoints[i].y);
tmp = tmp.mul(coefficients[k]);
Expand All @@ -75,11 +75,11 @@ const lagrange = (unsortedPoints: Point[]) => {
return new Polynomial(polynomial);
};

export function lagrangeInterpolatePolynomial(points: Array<Point>): Polynomial {
return lagrange(points);
export function lagrangeInterpolatePolynomial(points: Array<Point>, ecCurve: EllipticCurve): Polynomial {
return lagrange(points, ecCurve);
}

export function lagrangeInterpolation(shares: BN[], nodeIndex: BN[]): BN {
export function lagrangeInterpolation(shares: BN[], nodeIndex: BN[], ecCurve: EllipticCurve): BN {
if (shares.length !== nodeIndex.length) {
throw CoreError.default("shares not equal to nodeIndex length in lagrangeInterpolation");
}
Expand All @@ -106,19 +106,19 @@ export function lagrangeInterpolation(shares: BN[], nodeIndex: BN[]): BN {
// generateRandomPolynomial - determinisiticShares are assumed random
export function generateRandomPolynomial(
degree: number,
eCurve: EllipticCurve,
ecCurve: EllipticCurve,
secret?: BN,
deterministicShares?: Array<Share>,
keyType?: KeyType
): Polynomial {
let actualS = secret;
if (!secret) {
actualS = generatePrivateExcludingIndexes([new BN(0)], eCurve);
actualS = generatePrivateExcludingIndexes([new BN(0)], ecCurve);
}
if (!deterministicShares) {
const poly = [actualS];
for (let i = 0; i < degree; i += 1) {
const share = generatePrivateExcludingIndexes(poly, eCurve);
const share = generatePrivateExcludingIndexes(poly, ecCurve);
poly.push(share);
}
return new Polynomial(poly);
Expand All @@ -135,18 +135,19 @@ export function generateRandomPolynomial(
points[share.shareIndex.toString("hex") as string] = new Point(share.shareIndex, share.share, keyType);
});
for (let i = 0; i < degree - deterministicShares.length; i += 1) {
let shareIndex = generatePrivateExcludingIndexes([new BN(0)], eCurve);
let shareIndex = generatePrivateExcludingIndexes([new BN(0)], ecCurve);
while (points[shareIndex.toString("hex")] !== undefined) {
shareIndex = generatePrivateExcludingIndexes([new BN(0)], eCurve);
shareIndex = generatePrivateExcludingIndexes([new BN(0)], ecCurve);
}
points[shareIndex.toString("hex")] = new Point(shareIndex, new BN(generatePrivate()), keyType);
}
points["0"] = new Point(new BN(0), actualS, keyType);
return lagrangeInterpolatePolynomial(Object.values(points));
return lagrangeInterpolatePolynomial(Object.values(points), ecCurve);
}

// 2 + 3x = y | secret for index 1 is 5 >>> g^5 is the commitment | now we have g^2, g^3 and 1, |
export function polyCommitmentEval(polyCommitments: Array<Point>, index: BN, keyType?: KeyType): Point {
const ecCurve = keyTypeToCurve(keyType);
// convert to base points, this is badly written, its the only way to access the point rn zzz TODO: refactor
const basePtPolyCommitments: Array<curve.base.BasePoint> = [];
for (let i = 0; i < polyCommitments.length; i += 1) {
Expand Down