Socket
Socket
Sign inDemoInstall

@toruslabs/rss-client

Package Overview
Dependencies
84
Maintainers
5
Versions
10
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.5.0 to 2.0.0-0

4

dist/rssClient.umd.min.js.LICENSE.txt

@@ -9,5 +9,1 @@ /*!

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */

4

dist/types/mock.d.ts
import BN from "bn.js";
import { ec as EC } from "elliptic";
import { ServersInfo } from "./rss";

@@ -14,2 +15,3 @@ import { EncryptedMessage, PointHex } from "./utils";

auth: unknown;
key_type: string;
};

@@ -39,2 +41,3 @@ type RSSRound1ResponseData = {

data: RSSRound2RequestData[];
key_type: string;
};

@@ -48,2 +51,3 @@ type RSSRound2ResponseData = {

};
export declare function ecFromKeyType(keyType?: string): EC;
export declare function RSSRound1Handler(body: RSSRound1Request, getTSSShare: (label: string) => Promise<BN>): Promise<RSSRound1Response>;

@@ -50,0 +54,0 @@ export declare function RSSRound2Handler(body: RSSRound2Request, getPrivKey: () => Promise<BN>): Promise<RSSRound2Response>;

import { CustomOptions, Data } from "@toruslabs/http-helpers";
import BN from "bn.js";
import { curve, ec as EC } from "elliptic";
import { EncryptedMessage, PointHex } from "./utils";
export type KeyType = "secp256k1" | "ed25519";
export interface IMockServer {
get(path: string): Promise<any>;
post(path: string, data?: Data): Promise<any>;
get(path: string): Promise<unknown>;
post(path: string, data?: Data): Promise<unknown>;
}
export declare function getEndpoint<T>(endpoint: string | IMockServer, path: string, options_?: RequestInit, customOptions?: CustomOptions): Promise<any>;
export declare function postEndpoint<T>(endpoint: string | IMockServer, path: string, data?: Data, options_?: RequestInit, customOptions?: CustomOptions): Promise<any>;
export declare function getEndpoint<T>(endpoint: string | IMockServer, path: string, options_?: RequestInit, customOptions?: CustomOptions): Promise<unknown>;
export declare function postEndpoint<T>(endpoint: string | IMockServer, path: string, data?: Data, options_?: RequestInit, customOptions?: CustomOptions): Promise<T>;
export type ImportOptions = {
importKey: BN;
newLabel: string;
sigs: any[];
sigs: string[];
dkgNewPub: PointHex;

@@ -24,2 +26,3 @@ targetIndexes: number[];

serverPubKeys: PointHex[];
keyType: KeyType;
tempKey?: BN;

@@ -35,3 +38,3 @@ };

newLabel: string;
sigs: any[];
sigs: string[];
dkgNewPub: PointHex;

@@ -71,2 +74,3 @@ inputShare: BN;

selectedServers: number[];
keyType: KeyType;
};

@@ -76,9 +80,19 @@ export type RecoverResponse = {

};
export type IData = {
master_poly_commits: PointHex[];
server_poly_commits: PointHex[];
target_encryptions: {
user_enc: EncryptedMessage;
server_encs: EncryptedMessage[];
};
}[];
export declare class RSSClient {
tssPubKey: PointHex;
tssPubKey: curve.base.BasePoint;
tempPrivKey: BN;
tempPubKey: PointHex;
tempPubKey: curve.base.BasePoint;
serverEndpoints: string[] | IMockServer[];
serverThreshold: number;
serverPubKeys: PointHex[];
ecCurve: EC;
keyType: KeyType;
constructor(opts: RSSClientOptions);

@@ -85,0 +99,0 @@ import(opts: ImportOptions): Promise<RefreshResponse[]>;

/// <reference types="node" />
import BN from "bn.js";
export declare const ecCurve: any;
import { curve, ec as EC } from "elliptic";
export declare const ecCurveSecp256k1: EC;
export type PointHex = {

@@ -9,4 +10,4 @@ x: string | null;

export declare function randomSelection(arr: number[], num: number): number[];
export declare function ecPoint(p: PointHex): any;
export declare function hexPoint(p: any): PointHex;
export declare function ecPoint(ecCurve: EC, p: PointHex): curve.base.BasePoint;
export declare function hexPoint(p: curve.base.BasePoint): PointHex;
export type EncryptedMessage = {

@@ -20,6 +21,6 @@ ciphertext: string;

export declare function decrypt(privKey: Buffer, msg: EncryptedMessage): Promise<Buffer>;
export declare function generatePolynomial(degree: number, yIntercept: BN): BN[];
export declare function getShare(polynomial: BN[], index: BN | number): BN;
export declare function generatePolynomial(degree: number, yIntercept: BN, randomElement: () => BN): BN[];
export declare function getShare(polynomial: BN[], index: BN | number, modulus: BN): BN;
export declare function dotProduct(arr1: BN[], arr2: BN[], modulus?: BN): BN;
export declare function getLagrangeCoeffs(_allIndexes: number[] | BN[], _myIndex: number | BN, _target?: number | BN): BN;
export declare function lagrangeInterpolation(shares: BN[], nodeIndex: BN[]): BN;
export declare function getLagrangeCoeff(_allIndexes: number[] | BN[], _myIndex: number | BN, _target: number | BN, modulus: BN): BN;
export declare function lagrangeInterpolation(shares: BN[], nodeIndex: BN[], modulus: BN): BN;
{
"name": "@toruslabs/rss-client",
"version": "1.5.0",
"version": "2.0.0-0",
"description": "RSS Client",

@@ -19,3 +19,5 @@ "main": "dist/rssClient.cjs.js",

"prepack": "npm run build",
"test": "mocha",
"test:secp256k1": "CURVE=secp256k1 mocha",
"test:ed25519": "CURVE=ed25519 mocha",
"test": "npm run test:secp256k1 && npm run test:ed25519",
"lint:ts": "eslint --fix 'src/**/*.ts'",

@@ -28,4 +30,4 @@ "prepare": "husky install"

"dependencies": {
"@toruslabs/eccrypto": "^2.1.1",
"@toruslabs/http-helpers": "^3.2.0",
"@toruslabs/eccrypto": "^4.0.0",
"@toruslabs/http-helpers": "^5.0.0",
"bn.js": "^5.2.1",

@@ -35,33 +37,24 @@ "elliptic": "^6.5.4",

"loglevel": "^1.8.1",
"node-fetch": "^2.0.0",
"web3-eth-contract": "^1.8.1",
"web3-utils": "^1.8.1"
"web3-eth-contract": "^4.1.0",
"web3-utils": "^4.0.6"
},
"devDependencies": {
"@babel/register": "^7.18.9",
"@rollup/plugin-replace": "^4.0.0",
"@toruslabs/eslint-config-typescript": "^1.2.0",
"@toruslabs/torus-scripts": "^1.3.0",
"@types/mocha": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^5.43.0",
"@typescript-eslint/parser": "^5.43.0",
"assert": "^2.0.0",
"@babel/register": "^7.22.15",
"@rollup/plugin-replace": "^5.0.2",
"@toruslabs/config": "^2.0.2",
"@toruslabs/eslint-config-typescript": "^3.0.1",
"@toruslabs/torus-scripts": "^5.0.5",
"@types/elliptic": "^6.4.15",
"@types/mocha": "^10.0.2",
"assert": "^2.1.0",
"cross-env": "^7.0.3",
"dotenv": "^16.0.3",
"eslint": "^8.28.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-mocha": "^10.1.0",
"eslint-plugin-n": "^15.5.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-simple-import-sort": "^8.0.0",
"eslint-plugin-tsdoc": "^0.2.17",
"husky": "^8.0.2",
"lint-staged": "^13.0.3",
"mocha": "^10.1.0",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"dotenv": "^16.3.1",
"eslint": "^8.50.0",
"husky": "^8.0.3",
"lint-staged": "^14.0.1",
"mocha": "^10.2.0",
"prettier": "^3.0.3",
"rimraf": "^5.0.5",
"ts-node": "^10.9.1",
"typescript": "^4.9.3"
"typescript": "^5.2.2"
},

@@ -86,5 +79,5 @@ "lint-staged": {

"engines": {
"node": ">=14.17.0",
"npm": ">=6.x"
"node": ">=18.x",
"npm": ">=9.x"
}
}
/* eslint-disable camelcase */
import BN from "bn.js";
import { ec as EC } from "elliptic";
import { ServersInfo } from "./rss";
import { decrypt, ecCurve, ecPoint, encrypt, EncryptedMessage, generatePolynomial, getLagrangeCoeffs, getShare, hexPoint, PointHex } from "./utils";
import {
decrypt,
ecCurveSecp256k1,
ecPoint,
encrypt,
EncryptedMessage,
generatePolynomial,
getLagrangeCoeff,
getShare,
hexPoint,
PointHex,
} from "./utils";

@@ -22,2 +34,3 @@ type AuthData = {

auth: unknown;
key_type: string;
};

@@ -51,2 +64,3 @@

data: RSSRound2RequestData[];
key_type: string;
};

@@ -63,2 +77,14 @@

const CURVE_SECP256K1 = new EC("secp256k1");
const CURVE_ED25519 = new EC("ed25519");
export function ecFromKeyType(keyType = "secp256k1"): EC {
if (keyType === "secp256k1") {
return CURVE_SECP256K1;
} else if (keyType === "ed25519") {
return CURVE_ED25519;
}
throw new Error(`invalid key type: ${keyType}`);
}
export async function RSSRound1Handler(body: RSSRound1Request, getTSSShare: (label: string) => Promise<BN>): Promise<RSSRound1Response> {

@@ -79,2 +105,5 @@ const b = body;

const ecCurve = ecFromKeyType(b.key_type);
const genRandomScalar = () => ecCurve.genKeyPair().getPrivate();
let servers_info: ServersInfo;

@@ -99,12 +128,12 @@ if (b.server_set === "old") {

// firstly, calculate lagrange coefficient for own server sharing poly
let L = getLagrangeCoeffs(servers_info.selected, b.server_index, 0);
let L = getLagrangeCoeff(servers_info.selected, b.server_index, 0, ecCurve.n);
// secondly, calculate lagrange coefficient for master sharing poly
L = L.mul(getLagrangeCoeffs([1, b.old_user_share_index], 1, 0)).umod(ecCurve.n);
L = L.mul(getLagrangeCoeff([1, b.old_user_share_index], 1, 0, ecCurve.n)).umod(ecCurve.n);
// thirdly, calculate lagrange coefficient for new master sharing poly
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeffs([0, 1], 0, target)).umod(ecCurve.n));
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeff([0, 1], 0, target, ecCurve.n)).umod(ecCurve.n));
} else {
// firstly, calculate lagrange coefficient for own server sharing poly
const L = getLagrangeCoeffs(servers_info.selected, b.server_index, 0);
const L = getLagrangeCoeff(servers_info.selected, b.server_index, 0, ecCurve.n);
// secondly, calculate lagrange coefficient for master sharing poly
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeffs([0, 1], 1, target)).umod(ecCurve.n));
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeff([0, 1], 1, target, ecCurve.n)).umod(ecCurve.n));
}

@@ -122,3 +151,3 @@

const lc = finalLagrangeCoeffs[i];
const m = generatePolynomial(1, lc.mul(tssServerShare).umod(ecCurve.n));
const m = generatePolynomial(1, lc.mul(tssServerShare).umod(ecCurve.n), genRandomScalar);
masterPolys.push(m);

@@ -131,3 +160,3 @@ masterPolyCommits.push(

);
const s = generatePolynomial(b.new_servers_info.threshold - 1, getShare(m, 1));
const s = generatePolynomial(b.new_servers_info.threshold - 1, getShare(m, 1, ecCurve.n), genRandomScalar);
serverPolys.push(s);

@@ -149,3 +178,3 @@ serverPolyCommits.push(s.map((coeff) => hexPoint(ecCurve.g.mul(coeff))));

Buffer.from(`04${b.user_temp_pubkey.x.padStart(64, "0")}${b.user_temp_pubkey.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(masterPoly, 99).toString(16, 64), "hex")
Buffer.from(getShare(masterPoly, 99, ecCurve.n).toString(16, 64), "hex")
)

@@ -161,3 +190,3 @@ );

Buffer.from(`04${pub.x.padStart(64, "0")}${pub.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(serverPoly, j + 1).toString(16, 64), "hex")
Buffer.from(getShare(serverPoly, j + 1, ecCurve.n).toString(16, 64), "hex")
)

@@ -196,2 +225,5 @@ );

if (b.round_name !== "rss_round_2") throw new Error("incorrect round name");
const ecCurve = ecFromKeyType(b.key_type);
for (let i = 0; i < b.data.length; i++) {

@@ -201,8 +233,8 @@ const factorPubs: PointHex[] = b.data[i].factor_pubkeys;

const masterCommits = b.data[i].master_commits.map(ecPoint);
const serverCommits = b.data[i].server_commits.map(ecPoint);
const masterCommits = b.data[i].master_commits.map((p) => ecPoint(ecCurve, p));
const serverCommits = b.data[i].server_commits.map((p) => ecPoint(ecCurve, p));
const gB0 = masterCommits[0].add(masterCommits[1]);
const _gB0 = serverCommits[0];
if (!gB0.x.eq(_gB0.x) || !gB0.y.eq(_gB0.y)) {
if (!gB0.eq(_gB0)) {
throw new Error("server sharing poly commits are inconsistent with master sharing poly commits");

@@ -229,3 +261,3 @@ }

}
if (!gDec.x.eq(_gDec.x) || !gDec.y.eq(_gDec.y)) {
if (!gDec.eq(_gDec)) {
throw new Error("shares are inconsistent with the server poly commits");

@@ -288,2 +320,3 @@ }

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async post(path: string, data: any): Promise<RSSRound1Response | RSSRound2Response | Record<string, unknown>> {

@@ -298,3 +331,3 @@ const { label, tss_share_hex: tssShareHex } = data;

this.store.privKey = privKey;
this.pubKey = hexPoint(ecCurve.g.mul(privKey));
this.pubKey = hexPoint(ecCurveSecp256k1.g.mul(privKey));
return {};

@@ -335,2 +368,5 @@ }

const ecCurve = ecFromKeyType(b.key_type);
const genRandomScalar = () => ecCurve.genKeyPair().getPrivate();
let servers_info: ServersInfo;

@@ -355,12 +391,12 @@ if (b.server_set === "old") {

// firstly, calculate lagrange coefficient for own server sharing poly
let L = getLagrangeCoeffs(servers_info.selected, b.server_index, 0);
let L = getLagrangeCoeff(servers_info.selected, b.server_index, 0, ecCurve.n);
// secondly, calculate lagrange coefficient for master sharing poly
L = L.mul(getLagrangeCoeffs([1, b.old_user_share_index], 1, 0)).umod(ecCurve.n);
L = L.mul(getLagrangeCoeff([1, b.old_user_share_index], 1, 0, ecCurve.n)).umod(ecCurve.n);
// thirdly, calculate lagrange coefficient for new master sharing poly
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeffs([0, 1], 0, target)).umod(ecCurve.n));
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeff([0, 1], 0, target, ecCurve.n)).umod(ecCurve.n));
} else {
// firstly, calculate lagrange coefficient for own server sharing poly
const L = getLagrangeCoeffs(servers_info.selected, b.server_index, 0);
const L = getLagrangeCoeff(servers_info.selected, b.server_index, 0, ecCurve.n);
// secondly, calculate lagrange coefficient for master sharing poly
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeffs([0, 1], 1, target)).umod(ecCurve.n));
finalLagrangeCoeffs = b.target_index.map((target) => L.mul(getLagrangeCoeff([0, 1], 1, target, ecCurve.n)).umod(ecCurve.n));
}

@@ -378,3 +414,3 @@

const lc = finalLagrangeCoeffs[i];
const m = generatePolynomial(1, lc.mul(tssServerShare).umod(ecCurve.n));
const m = generatePolynomial(1, lc.mul(tssServerShare).umod(ecCurve.n), genRandomScalar);
masterPolys.push(m);

@@ -387,3 +423,3 @@ masterPolyCommits.push(

);
const s = generatePolynomial(b.new_servers_info.threshold - 1, getShare(m, 1));
const s = generatePolynomial(b.new_servers_info.threshold - 1, getShare(m, 1, ecCurve.n), genRandomScalar);
serverPolys.push(s);

@@ -405,3 +441,3 @@ serverPolyCommits.push(s.map((coeff) => hexPoint(ecCurve.g.mul(coeff))));

Buffer.from(`04${b.user_temp_pubkey.x.padStart(64, "0")}${b.user_temp_pubkey.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(masterPoly, 99).toString(16, 64), "hex") // Note: this is because 99 is the hardcoded value when doing rss DKG hierarchical sharing
Buffer.from(getShare(masterPoly, 99, ecCurve.n).toString(16, 64), "hex") // Note: this is because 99 is the hardcoded value when doing rss DKG hierarchical sharing
)

@@ -417,3 +453,3 @@ );

Buffer.from(`04${pub.x.padStart(64, "0")}${pub.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(serverPoly, j + 1).toString(16, 64), "hex")
Buffer.from(getShare(serverPoly, j + 1, ecCurve.n).toString(16, 64), "hex")
)

@@ -452,2 +488,5 @@ );

if (b.round_name !== "rss_round_2") throw new Error("incorrect round name");
const ecCurve = ecFromKeyType(b.key_type);
for (let i = 0; i < b.data.length; i++) {

@@ -457,8 +496,8 @@ const factorPubs: PointHex[] = b.data[i].factor_pubkeys;

const masterCommits = b.data[i].master_commits.map(ecPoint);
const serverCommits = b.data[i].server_commits.map(ecPoint);
const masterCommits = b.data[i].master_commits.map((p) => ecPoint(ecCurve, p));
const serverCommits = b.data[i].server_commits.map((p) => ecPoint(ecCurve, p));
const gB0 = masterCommits[0].add(masterCommits[1]);
const _gB0 = serverCommits[0];
if (!gB0.x.eq(_gB0.x) || !gB0.y.eq(_gB0.y)) {
if (!gB0.eq(_gB0)) {
throw new Error("server sharing poly commits are inconsistent with master sharing poly commits");

@@ -485,3 +524,3 @@ }

}
if (!gDec.x.eq(_gDec.x) || !gDec.y.eq(_gDec.y)) {
if (!gDec.eq(_gDec)) {
throw new Error("shares are inconsistent with the server poly commits");

@@ -488,0 +527,0 @@ }

@@ -1,4 +0,4 @@

import { generatePrivate } from "@toruslabs/eccrypto";
import { CustomOptions, Data, get, post } from "@toruslabs/http-helpers";
import BN from "bn.js";
import { curve, ec as EC } from "elliptic";
import log from "loglevel";

@@ -9,3 +9,3 @@

dotProduct,
ecCurve,
ecCurveSecp256k1,
ecPoint,

@@ -15,3 +15,3 @@ encrypt,

generatePolynomial,
getLagrangeCoeffs,
getLagrangeCoeff,
getShare,

@@ -22,8 +22,15 @@ hexPoint,

export type KeyType = "secp256k1" | "ed25519";
export interface IMockServer {
get(path: string): Promise<any>;
post(path: string, data?: Data): Promise<any>;
get(path: string): Promise<unknown>;
post(path: string, data?: Data): Promise<unknown>;
}
export function getEndpoint<T>(endpoint: string | IMockServer, path: string, options_?: RequestInit, customOptions?: CustomOptions): Promise<any> {
export function getEndpoint<T>(
endpoint: string | IMockServer,
path: string,
options_?: RequestInit,
customOptions?: CustomOptions
): Promise<unknown> {
if (typeof endpoint === "string") {

@@ -41,7 +48,7 @@ return get<T>(`${endpoint}${path}`, options_, customOptions);

customOptions?: CustomOptions
): Promise<any> {
): Promise<T> {
if (typeof endpoint === "string") {
return post<T>(`${endpoint}${path}`, data, options_, customOptions);
}
return endpoint.post(path, data);
return endpoint.post(path, data) as Promise<T>;
}

@@ -52,3 +59,3 @@

newLabel: string;
sigs: any[];
sigs: string[];
dkgNewPub: PointHex;

@@ -65,2 +72,3 @@ targetIndexes: number[];

serverPubKeys: PointHex[];
keyType: KeyType;
tempKey?: BN;

@@ -78,3 +86,3 @@ };

newLabel: string;
sigs: any[];
sigs: string[];
dkgNewPub: PointHex;

@@ -128,2 +136,3 @@ inputShare: BN;

selectedServers: number[];
keyType: KeyType;
};

@@ -135,8 +144,14 @@

export type IData = {
master_poly_commits: PointHex[];
server_poly_commits: PointHex[];
target_encryptions: { user_enc: EncryptedMessage; server_encs: EncryptedMessage[] };
}[];
export class RSSClient {
tssPubKey: PointHex;
tssPubKey: curve.base.BasePoint;
tempPrivKey: BN;
tempPubKey: PointHex;
tempPubKey: curve.base.BasePoint;

@@ -149,4 +164,10 @@ serverEndpoints: string[] | IMockServer[];

ecCurve: EC;
keyType: KeyType;
constructor(opts: RSSClientOptions) {
this.tssPubKey = opts.tssPubKey;
this.keyType = opts.keyType;
this.ecCurve = new EC(this.keyType);
this.tssPubKey = ecPoint(this.ecCurve, opts.tssPubKey);
this.serverEndpoints = opts.serverEndpoints;

@@ -157,6 +178,7 @@ this.serverThreshold = opts.serverThreshold;

this.tempPrivKey = opts.tempKey;
this.tempPubKey = ecCurve.g.mul(opts.tempKey);
this.tempPubKey = ecCurveSecp256k1.g.mul(opts.tempKey);
} else {
this.tempPrivKey = new BN(generatePrivate());
this.tempPubKey = ecCurve.g.mul(this.tempPrivKey);
const kp = ecCurveSecp256k1.genKeyPair();
this.tempPrivKey = kp.getPrivate();
this.tempPubKey = kp.getPublic();
}

@@ -188,2 +210,3 @@ }

},
key_type: this.keyType,
});

@@ -194,3 +217,3 @@ });

// - calculate lagrange coeffs
const _finalLagrangeCoeffs = targetIndexes.map((target) => getLagrangeCoeffs([0, 1], 0, target).umod(ecCurve.n));
const _finalLagrangeCoeffs = targetIndexes.map((target) => getLagrangeCoeff([0, 1], 0, target, this.ecCurve.n).umod(this.ecCurve.n));
const _masterPolys = [];

@@ -200,15 +223,16 @@ const _masterPolyCommits = [];

const _serverPolyCommits = [];
const generateRandomScalar = () => this.ecCurve.genKeyPair().getPrivate();
for (let i = 0; i < _finalLagrangeCoeffs.length; i++) {
const _lc = _finalLagrangeCoeffs[i];
const _m = generatePolynomial(1, _lc.mul(importKey).umod(ecCurve.n));
const _m = generatePolynomial(1, _lc.mul(importKey).umod(this.ecCurve.n), generateRandomScalar);
_masterPolys.push(_m);
_masterPolyCommits.push(
_m.map((coeff) => {
const _gCoeff = ecCurve.g.mul(coeff);
const _gCoeff = this.ecCurve.g.mul(coeff);
return hexPoint(_gCoeff);
})
);
const _s = generatePolynomial(serversInfo.threshold - 1, getShare(_m, 1));
const _s = generatePolynomial(serversInfo.threshold - 1, getShare(_m, 1, this.ecCurve.n), generateRandomScalar);
_serverPolys.push(_s);
_serverPolyCommits.push(_s.map((coeff) => hexPoint(ecCurve.g.mul(coeff))));
_serverPolyCommits.push(_s.map((coeff) => hexPoint(this.ecCurve.g.mul(coeff))));
}

@@ -226,3 +250,3 @@ const _serverEncs = [];

Buffer.from(`04${hexPoint(this.tempPubKey).x.padStart(64, "0")}${hexPoint(this.tempPubKey).y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(_masterPoly, 99).toString(16, 64), "hex")
Buffer.from(getShare(_masterPoly, 99, this.ecCurve.n).toString(16, 64), "hex")
)

@@ -232,3 +256,3 @@ );

const _serverPoly = _serverPolys[i];
const _serverEnc = _serverEncs[i];
const _serverEnc: EncryptedMessage[] = _serverEncs[i];
for (let j = 0; j < serversInfo.pubkeys.length; j++) {

@@ -239,3 +263,3 @@ const _pub = serversInfo.pubkeys[j];

Buffer.from(`04${_pub.x.padStart(64, "0")}${_pub.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(_serverPoly, j + 1).toString(16, 64), "hex")
Buffer.from(getShare(_serverPoly, j + 1, this.ecCurve.n).toString(16, 64), "hex")
)

@@ -245,3 +269,3 @@ );

}
const _data = [];
const _data: IData = [];
for (let i = 0; i < targetIndexes.length; i++) {

@@ -269,3 +293,3 @@ _data.push({

// await responses
const rssRound1Responses = await Promise.all(rssRound1Proms);
const rssRound1Responses = (await Promise.all(rssRound1Proms)) as RSSRound1Response[];

@@ -281,4 +305,4 @@ // sum up all master poly commits and sum up all server poly commits

let sumMasterPolyCommits = [];
let sumServerPolyCommits = [];
let sumMasterPolyCommits: curve.base.BasePoint[] = [];
let sumServerPolyCommits: curve.base.BasePoint[] = [];

@@ -289,11 +313,11 @@ for (let j = 0; j < rssRound1Responses.length; j++) {

if (sumMasterPolyCommits.length === 0 && sumServerPolyCommits.length === 0) {
sumMasterPolyCommits = masterPolyCommits.map(ecPoint);
sumServerPolyCommits = serverPolyCommits.map(ecPoint);
sumMasterPolyCommits = masterPolyCommits.map((p) => ecPoint(this.ecCurve, p));
sumServerPolyCommits = serverPolyCommits.map((p) => ecPoint(this.ecCurve, p));
continue;
}
sumMasterPolyCommits = sumMasterPolyCommits.map((summedCommit, k) => {
return ecPoint(masterPolyCommits[k]).add(summedCommit);
return ecPoint(this.ecCurve, masterPolyCommits[k]).add(summedCommit);
});
sumServerPolyCommits = sumServerPolyCommits.map((summedCommit, k) => {
return ecPoint(serverPolyCommits[k]).add(summedCommit);
return ecPoint(this.ecCurve, serverPolyCommits[k]).add(summedCommit);
});

@@ -312,14 +336,9 @@ }

// check master poly commits are consistent with tssPubKey
const temp1 = ecPoint(dkgNewPub).mul(getLagrangeCoeffs([1, target], 1));
const temp2 = mc[0].mul(getLagrangeCoeffs([1, target], target));
const temp1 = ecPoint(this.ecCurve, dkgNewPub).mul(getLagrangeCoeff([1, target], 1, 0, this.ecCurve.n));
const temp2 = mc[0].mul(getLagrangeCoeff([1, target], target, 0, this.ecCurve.n));
const _tssPubKey = temp1.add(temp2);
if (
_tssPubKey.x.toString(16, 64) !== ecPoint(this.tssPubKey).x.toString(16, 64) ||
_tssPubKey.y.toString(16, 64) !== ecPoint(this.tssPubKey).y.toString(16, 64)
)
throw new Error("master poly commits inconsistent with tssPubKey");
if (!_tssPubKey.eq(this.tssPubKey)) throw new Error("master poly commits inconsistent with tssPubKey");
// check server poly commits are consistent with master poly commits
if (mc[0].add(mc[1]).x.toString(16, 64) !== sc[0].x.toString(16, 64) || mc[0].add(mc[1]).y.toString(16, 64) !== sc[0].y.toString(16, 64))
throw new Error("server poly commits inconsistent with master poly commits");
if (!mc[0].add(mc[1]).eq(sc[0])) throw new Error("server poly commits inconsistent with master poly commits");
return null;

@@ -334,8 +353,7 @@ });

const userDecs = await Promise.all(userEncs.map((encMsg) => decrypt(privKeyBuffer, encMsg)));
const userShare = userDecs.map((userDec) => new BN(userDec)).reduce((acc, d) => acc.add(d).umod(ecCurve.n), new BN(0));
const userShare = userDecs.map((userDec) => new BN(userDec)).reduce((acc, d) => acc.add(d).umod(this.ecCurve.n), new BN(0));
const { mc } = sums[i];
const gU = ecCurve.g.mul(userShare);
const gU = this.ecCurve.g.mul(userShare);
const _gU = mc[0].add(mc[1].mul(new BN(99))); // master poly evaluated at x = 99
if (gU.x.toString(16, 64) !== _gU.x.toString(16, 64) || gU.y.toString(16, 64) !== _gU.y.toString(16, 64))
throw new Error("decrypted user shares inconsistent with poly commits");
if (!gU.eq(_gU)) throw new Error("decrypted user shares inconsistent with poly commits");
userShares.push(userShare);

@@ -374,3 +392,3 @@ }

// TODO: specify it's "new" server set for server indexes
const data = [];
const data: { master_commits: PointHex[]; server_commits: PointHex[]; server_encs: EncryptedMessage[]; factor_pubkeys: PointHex[] }[] = [];
targetIndexes.map((_, i) => {

@@ -393,2 +411,3 @@ const { mc, sc } = sums[i];

data,
key_type: this.keyType,
}).catch((e) => log.error(e));

@@ -438,2 +457,3 @@ })

},
key_type: this.keyType,
});

@@ -457,2 +477,3 @@ })

},
key_type: this.keyType,
});

@@ -464,4 +485,4 @@ })

// - calculate lagrange coeffs
const _L = getLagrangeCoeffs([1, inputIndex], inputIndex);
const _finalLagrangeCoeffs = targetIndexes.map((target) => _L.mul(getLagrangeCoeffs([0, 1], 0, target)).umod(ecCurve.n));
const _L = getLagrangeCoeff([1, inputIndex], inputIndex, 0, this.ecCurve.n);
const _finalLagrangeCoeffs = targetIndexes.map((target) => _L.mul(getLagrangeCoeff([0, 1], 0, target, this.ecCurve.n)).umod(this.ecCurve.n));
const _masterPolys = [];

@@ -471,15 +492,16 @@ const _masterPolyCommits = [];

const _serverPolyCommits = [];
const generateRandomScalar = () => this.ecCurve.genKeyPair().getPrivate();
for (let i = 0; i < _finalLagrangeCoeffs.length; i++) {
const _lc = _finalLagrangeCoeffs[i];
const _m = generatePolynomial(1, _lc.mul(inputShare).umod(ecCurve.n));
const _m = generatePolynomial(1, _lc.mul(inputShare).umod(this.ecCurve.n), generateRandomScalar);
_masterPolys.push(_m);
_masterPolyCommits.push(
_m.map((coeff) => {
const _gCoeff = ecCurve.g.mul(coeff);
const _gCoeff = this.ecCurve.g.mul(coeff);
return hexPoint(_gCoeff);
})
);
const _s = generatePolynomial(serversInfo.threshold - 1, getShare(_m, 1));
const _s = generatePolynomial(serversInfo.threshold - 1, getShare(_m, 1, this.ecCurve.n), generateRandomScalar);
_serverPolys.push(_s);
_serverPolyCommits.push(_s.map((coeff) => hexPoint(ecCurve.g.mul(coeff))));
_serverPolyCommits.push(_s.map((coeff) => hexPoint(this.ecCurve.g.mul(coeff))));
}

@@ -497,3 +519,3 @@ const _serverEncs = [];

Buffer.from(`04${hexPoint(this.tempPubKey).x.padStart(64, "0")}${hexPoint(this.tempPubKey).y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(_masterPoly, 99).toString(16, 64), "hex")
Buffer.from(getShare(_masterPoly, 99, this.ecCurve.n).toString(16, 64), "hex")
)

@@ -503,3 +525,3 @@ );

const _serverPoly = _serverPolys[i];
const _serverEnc = _serverEncs[i];
const _serverEnc: EncryptedMessage[] = _serverEncs[i];
for (let j = 0; j < serversInfo.pubkeys.length; j++) {

@@ -510,3 +532,3 @@ const _pub = serversInfo.pubkeys[j];

Buffer.from(`04${_pub.x.padStart(64, "0")}${_pub.y.padStart(64, "0")}`, "hex"),
Buffer.from(getShare(_serverPoly, j + 1).toString(16, 64), "hex")
Buffer.from(getShare(_serverPoly, j + 1, this.ecCurve.n).toString(16, 64), "hex")
)

@@ -516,3 +538,3 @@ );

}
const _data = [];
const _data: IData = [];
for (let i = 0; i < targetIndexes.length; i++) {

@@ -540,3 +562,3 @@ _data.push({

// await responses
const rssRound1Responses = await Promise.all(rssRound1Proms);
const rssRound1Responses = (await Promise.all(rssRound1Proms)) as RSSRound1Response[];

@@ -552,4 +574,4 @@ // sum up all master poly commits and sum up all server poly commits

let sumMasterPolyCommits = [];
let sumServerPolyCommits = [];
let sumMasterPolyCommits: curve.base.BasePoint[] = [];
let sumServerPolyCommits: curve.base.BasePoint[] = [];

@@ -560,11 +582,11 @@ for (let j = 0; j < rssRound1Responses.length; j++) {

if (sumMasterPolyCommits.length === 0 && sumServerPolyCommits.length === 0) {
sumMasterPolyCommits = masterPolyCommits.map(ecPoint);
sumServerPolyCommits = serverPolyCommits.map(ecPoint);
sumMasterPolyCommits = masterPolyCommits.map((p) => ecPoint(this.ecCurve, p));
sumServerPolyCommits = serverPolyCommits.map((p) => ecPoint(this.ecCurve, p));
continue;
}
sumMasterPolyCommits = sumMasterPolyCommits.map((summedCommit, k) => {
return ecPoint(masterPolyCommits[k]).add(summedCommit);
return ecPoint(this.ecCurve, masterPolyCommits[k]).add(summedCommit);
});
sumServerPolyCommits = sumServerPolyCommits.map((summedCommit, k) => {
return ecPoint(serverPolyCommits[k]).add(summedCommit);
return ecPoint(this.ecCurve, serverPolyCommits[k]).add(summedCommit);
});

@@ -583,14 +605,9 @@ }

// check master poly commits are consistent with tssPubKey
const temp1 = ecPoint(dkgNewPub).mul(getLagrangeCoeffs([1, target], 1));
const temp2 = mc[0].mul(getLagrangeCoeffs([1, target], target));
const temp1 = ecPoint(this.ecCurve, dkgNewPub).mul(getLagrangeCoeff([1, target], 1, 0, this.ecCurve.n));
const temp2 = mc[0].mul(getLagrangeCoeff([1, target], target, 0, this.ecCurve.n));
const _tssPubKey = temp1.add(temp2);
if (
_tssPubKey.x.toString(16, 64) !== ecPoint(this.tssPubKey).x.toString(16, 64) ||
_tssPubKey.y.toString(16, 64) !== ecPoint(this.tssPubKey).y.toString(16, 64)
)
throw new Error("master poly commits inconsistent with tssPubKey");
if (!_tssPubKey.eq(this.tssPubKey)) throw new Error("master poly commits inconsistent with tssPubKey");
// check server poly commits are consistent with master poly commits
if (mc[0].add(mc[1]).x.toString(16, 64) !== sc[0].x.toString(16, 64) || mc[0].add(mc[1]).y.toString(16, 64) !== sc[0].y.toString(16, 64))
throw new Error("server poly commits inconsistent with master poly commits");
if (!mc[0].add(mc[1]).eq(sc[0])) throw new Error("server poly commits inconsistent with master poly commits");
return null;

@@ -605,8 +622,7 @@ });

const userDecs = await Promise.all(userEncs.map((encMsg) => decrypt(privKeyBuffer, encMsg)));
const userShare = userDecs.map((userDec) => new BN(userDec)).reduce((acc, d) => acc.add(d).umod(ecCurve.n), new BN(0));
const userShare = userDecs.map((userDec) => new BN(userDec)).reduce((acc, d) => acc.add(d).umod(this.ecCurve.n), new BN(0));
const { mc } = sums[i];
const gU = ecCurve.g.mul(userShare);
const gU = this.ecCurve.g.mul(userShare);
const _gU = mc[0].add(mc[1].mul(new BN(99))); // master poly evaluated at x = 99
if (gU.x.toString(16, 64) !== _gU.x.toString(16, 64) || gU.y.toString(16, 64) !== _gU.y.toString(16, 64))
throw new Error("decrypted user shares inconsistent with poly commits");
if (!gU.eq(_gU)) throw new Error("decrypted user shares inconsistent with poly commits");
userShares.push(userShare);

@@ -643,3 +659,3 @@ }

// TODO: specify it's "new" server set for server indexes
const data = [];
const data: { master_commits: PointHex[]; server_commits: PointHex[]; server_encs: EncryptedMessage[]; factor_pubkeys: PointHex[] }[] = [];
targetIndexes.map((_, i) => {

@@ -662,2 +678,3 @@ const { mc, sc } = sums[i];

data,
key_type: this.keyType,
}).catch((e) => log.error(e));

@@ -683,3 +700,4 @@ })

export async function recover(opts: RecoverOptions): Promise<RecoverResponse> {
const { factorKey, serverEncs, userEnc, selectedServers } = opts;
const { factorKey, serverEncs, userEnc, selectedServers, keyType } = opts;
const ecCurve = new EC(keyType || "secp256k1");
const factorKeyBuf = Buffer.from(factorKey.toString(16, 64), "hex");

@@ -691,6 +709,6 @@ const prom1 = decrypt(factorKeyBuf, userEnc).then((buf) => new BN(buf));

const someDecrypted = decryptedServerEncs.filter((_, j) => selectedServers.indexOf(j + 1) >= 0);
const decryptedLCs = selectedServers.map((index) => getLagrangeCoeffs(selectedServers, index));
const temp1 = decryptedUserEnc.mul(getLagrangeCoeffs([1, 99], 99));
const decryptedLCs = selectedServers.map((index) => getLagrangeCoeff(selectedServers, index, 0, ecCurve.n));
const temp1 = decryptedUserEnc.mul(getLagrangeCoeff([1, 99], 99, 0, ecCurve.n));
const serverReconstructed = dotProduct(someDecrypted, decryptedLCs).umod(ecCurve.n);
const temp2 = serverReconstructed.mul(getLagrangeCoeffs([1, 99], 1));
const temp2 = serverReconstructed.mul(getLagrangeCoeff([1, 99], 1, 0, ecCurve.n));
const tssShare = temp1.add(temp2).umod(ecCurve.n);

@@ -697,0 +715,0 @@

@@ -1,7 +0,6 @@

import { decrypt as ecDecrypt, encrypt as ecEncrypt, generatePrivate } from "@toruslabs/eccrypto";
import { decrypt as ecDecrypt, encrypt as ecEncrypt } from "@toruslabs/eccrypto";
import BN from "bn.js";
import { ec as EC } from "elliptic";
import { curve, ec as EC } from "elliptic";
const ec = new EC("secp256k1");
export const ecCurve = ec;
export const ecCurveSecp256k1 = new EC("secp256k1");

@@ -23,17 +22,14 @@ export type PointHex = {

export function ecPoint(p: PointHex): any {
export function ecPoint(ecCurve: EC, p: PointHex): curve.base.BasePoint {
if (p.x === null && p.y === null) {
return ec.curve.g.add(ec.curve.g.neg());
return ecCurve.curve.g.add(ecCurve.curve.g.neg());
}
return ec.keyFromPublic({ x: p.x.padStart(64, "0"), y: p.y.padStart(64, "0") }).getPublic();
return ecCurve.keyFromPublic({ x: p.x.padStart(64, "0"), y: p.y.padStart(64, "0") }).getPublic();
}
export function hexPoint(p: any): PointHex {
if (p.x === null || p.y === null) {
if (p.x === null && p.y === null) {
return { x: null, y: null };
}
throw new Error("could not serialize into PointHex");
export function hexPoint(p: curve.base.BasePoint): PointHex {
if (p.isInfinity()) {
return { x: null, y: null };
}
return { x: p.x.toString(16, 64), y: p.y.toString(16, 64) };
return { x: p.getX().toString(16, 64), y: p.getY().toString(16, 64) };
}

@@ -70,3 +66,3 @@

export function generatePolynomial(degree: number, yIntercept: BN): BN[] {
export function generatePolynomial(degree: number, yIntercept: BN, randomElement: () => BN): BN[] {
const res: BN[] = [];

@@ -79,16 +75,16 @@ let i = 0;

for (; i <= degree; i++) {
res.push(new BN(generatePrivate()));
res.push(randomElement());
}
return res;
}
export function getShare(polynomial: BN[], index: BN | number) {
export function getShare(polynomial: BN[], index: BN | number, modulus: BN) {
let res = new BN(0);
for (let i = 0; i < polynomial.length; i++) {
const term = polynomial[i].mul(new BN(index).pow(new BN(i)));
res = res.add(term.umod(ec.curve.n));
res = res.add(term.umod(modulus));
}
return res.umod(ec.curve.n);
return res.umod(modulus);
}
export function dotProduct(arr1: BN[], arr2: BN[], modulus = new BN(0)) {
export function dotProduct(arr1: BN[], arr2: BN[], modulus?: BN) {
if (arr1.length !== arr2.length) {

@@ -100,3 +96,3 @@ throw new Error("arrays of different lengths");

sum = sum.add(arr1[i].mul(arr2[i]));
if (modulus.cmp(new BN(0)) !== 0) {
if (modulus) {
sum = sum.umod(modulus);

@@ -108,3 +104,3 @@ }

export function getLagrangeCoeffs(_allIndexes: number[] | BN[], _myIndex: number | BN, _target: number | BN = 0) {
export function getLagrangeCoeff(_allIndexes: number[] | BN[], _myIndex: number | BN, _target: number | BN, modulus: BN) {
const allIndexes: BN[] = _allIndexes.map((i) => new BN(i));

@@ -118,14 +114,14 @@ const myIndex: BN = new BN(_myIndex);

let tempUpper = target.sub(allIndexes[j]);
tempUpper = tempUpper.umod(ec.curve.n);
tempUpper = tempUpper.umod(modulus);
upper = upper.mul(tempUpper);
upper = upper.umod(ec.curve.n);
upper = upper.umod(modulus);
let tempLower = myIndex.sub(allIndexes[j]);
tempLower = tempLower.umod(ec.curve.n);
lower = lower.mul(tempLower).umod(ec.curve.n);
tempLower = tempLower.umod(modulus);
lower = lower.mul(tempLower).umod(modulus);
}
}
return upper.mul(lower.invm(ec.curve.n)).umod(ec.curve.n);
return upper.mul(lower.invm(modulus)).umod(modulus);
}
export function lagrangeInterpolation(shares: BN[], nodeIndex: BN[]) {
export function lagrangeInterpolation(shares: BN[], nodeIndex: BN[], modulus: BN) {
if (shares.length !== nodeIndex.length) {

@@ -141,13 +137,13 @@ return null;

upper = upper.mul(nodeIndex[j].neg());
upper = upper.umod(ec.curve.n);
upper = upper.umod(modulus);
let temp = nodeIndex[i].sub(nodeIndex[j]);
temp = temp.umod(ec.curve.n);
lower = lower.mul(temp).umod(ec.curve.n);
temp = temp.umod(modulus);
lower = lower.mul(temp).umod(modulus);
}
}
let delta = upper.mul(lower.invm(ec.curve.n)).umod(ec.curve.n);
delta = delta.mul(shares[i]).umod(ec.curve.n);
let delta = upper.mul(lower.invm(modulus)).umod(modulus);
delta = delta.mul(shares[i]).umod(modulus);
secret = secret.add(delta);
}
return secret.umod(ec.curve.n);
return secret.umod(modulus);
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc