UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

83 lines 3.38 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PointInFiniteField = void 0; const BigNumber_js_1 = __importDefault(require("./BigNumber.js")); const Curve_js_1 = __importDefault(require("./Curve.js")); const Random_js_1 = __importDefault(require("./Random.js")); const utils_js_1 = require("./utils.js"); class PointInFiniteField { constructor(x, y) { const P = new Curve_js_1.default().p; // arithmetic is mod P this.x = x.umod(P); this.y = y.umod(P); } toString() { return (0, utils_js_1.toBase58)(this.x.toArray()) + '.' + (0, utils_js_1.toBase58)(this.y.toArray()); } static fromString(str) { const [x, y] = str.split('.'); return new PointInFiniteField(new BigNumber_js_1.default((0, utils_js_1.fromBase58)(x)), new BigNumber_js_1.default((0, utils_js_1.fromBase58)(y))); } } exports.PointInFiniteField = PointInFiniteField; /** * Polynomial class * * This class is used to create a polynomial with a given threshold and a private key. * The polynomial is used to create shares of the private key. * * @param key - The private key to split * @param threshold - The number of shares required to recombine the private key * * @example * const key = new PrivateKey() * const threshold = 2 * const polynomial = new Polynomial(key, threshold) * */ class Polynomial { constructor(points, threshold) { this.points = points; this.threshold = threshold ?? points.length; // ✅ Handles undefined safely } static fromPrivateKey(key, threshold) { const P = new Curve_js_1.default().p; // arithmetic is mod P // The key is the y-intercept of the polynomial where x=0. const points = [ new PointInFiniteField(new BigNumber_js_1.default(0), new BigNumber_js_1.default(key.toArray())) ]; // The other values are random for (let i = 1; i < threshold; i++) { const randomX = new BigNumber_js_1.default((0, Random_js_1.default)(32)).umod(P); const randomY = new BigNumber_js_1.default((0, Random_js_1.default)(32)).umod(P); points.push(new PointInFiniteField(randomX, randomY)); } return new Polynomial(points); } // Evaluate the polynomial at x by using Lagrange interpolation valueAt(x) { const P = new Curve_js_1.default().p; // arithmetic is mod P let y = new BigNumber_js_1.default(0); for (let i = 0; i < this.threshold; i++) { let term = this.points[i].y; for (let j = 0; j < this.threshold; j++) { if (i !== j) { const xj = this.points[j].x; const xi = this.points[i].x; const numerator = x.sub(xj).umod(P); const denominator = xi.sub(xj).umod(P); const denominatorInverse = denominator.invm(P); const fraction = numerator.mul(denominatorInverse).umod(P); term = term.mul(fraction).umod(P); } } y = y.add(term).umod(P); } return y; } } exports.default = Polynomial; //# sourceMappingURL=Polynomial.js.map