@decryption/curves 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/abstract/bls.d.ts +410 -0
- package/abstract/bls.js +433 -0
- package/abstract/curve.d.ts +441 -0
- package/abstract/curve.js +622 -0
- package/abstract/edwards.d.ts +319 -0
- package/abstract/edwards.js +697 -0
- package/abstract/fft.d.ts +438 -0
- package/abstract/fft.js +580 -0
- package/abstract/frost.d.ts +292 -0
- package/abstract/frost.js +705 -0
- package/abstract/hash-to-curve.d.ts +238 -0
- package/abstract/hash-to-curve.js +353 -0
- package/abstract/modular.d.ts +550 -0
- package/abstract/modular.js +872 -0
- package/abstract/montgomery.d.ts +95 -0
- package/abstract/montgomery.js +180 -0
- package/abstract/oprf.d.ts +354 -0
- package/abstract/oprf.js +358 -0
- package/abstract/poseidon.d.ts +198 -0
- package/abstract/poseidon.js +471 -0
- package/abstract/tower.d.ts +213 -0
- package/abstract/tower.js +963 -0
- package/abstract/weierstrass.d.ts +587 -0
- package/abstract/weierstrass.js +1421 -0
- package/bls12-381.d.ts +23 -0
- package/bls12-381.js +680 -0
- package/bn254.d.ts +74 -0
- package/bn254.js +248 -0
- package/ed25519.d.ts +211 -0
- package/ed25519.js +626 -0
- package/ed448.d.ts +184 -0
- package/ed448.js +596 -0
- package/esm/abstract/bls.js +429 -0
- package/esm/abstract/curve.js +610 -0
- package/esm/abstract/edwards.js +691 -0
- package/esm/abstract/fft.js +567 -0
- package/esm/abstract/frost.js +702 -0
- package/esm/abstract/hash-to-curve.js +345 -0
- package/esm/abstract/modular.js +849 -0
- package/esm/abstract/montgomery.js +177 -0
- package/esm/abstract/oprf.js +355 -0
- package/esm/abstract/poseidon.js +462 -0
- package/esm/abstract/tower.js +925 -0
- package/esm/abstract/weierstrass.js +1411 -0
- package/esm/bls12-381.js +677 -0
- package/esm/bn254.js +244 -0
- package/esm/ed25519.js +622 -0
- package/esm/ed448.js +593 -0
- package/esm/index.js +38 -0
- package/esm/misc.js +211 -0
- package/esm/nist.js +266 -0
- package/esm/secp256k1.js +465 -0
- package/esm/utils.js +597 -0
- package/esm/webcrypto.js +362 -0
- package/index.d.ts +0 -0
- package/index.js +38 -0
- package/misc.d.ts +113 -0
- package/misc.js +216 -0
- package/nist.d.ts +136 -0
- package/nist.js +269 -0
- package/package.json +46 -0
- package/secp256k1.d.ts +152 -0
- package/secp256k1.js +468 -0
- package/utils.d.ts +535 -0
- package/utils.js +626 -0
- package/webcrypto.d.ts +240 -0
- package/webcrypto.js +365 -0
package/secp256k1.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { type CurveLengths } from './abstract/curve';
|
|
2
|
+
import { type FROST } from './abstract/frost';
|
|
3
|
+
import { type H2CHasher } from './abstract/hash-to-curve';
|
|
4
|
+
import { type ECDSA, type WeierstrassPoint as PointType, type WeierstrassPointCons } from './abstract/weierstrass';
|
|
5
|
+
import { type TArg, type TRet } from './utils';
|
|
6
|
+
/**
|
|
7
|
+
* secp256k1 curve: ECDSA and ECDH methods.
|
|
8
|
+
*
|
|
9
|
+
* Uses sha256 to hash messages. To use a different hash,
|
|
10
|
+
* pass `{ prehash: false }` to sign / verify.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* Generate one secp256k1 keypair, sign a message, and verify it.
|
|
14
|
+
*
|
|
15
|
+
* ```js
|
|
16
|
+
* import { secp256k1 } from './secp256k1';
|
|
17
|
+
* const { secretKey, publicKey } = secp256k1.keygen();
|
|
18
|
+
* // const publicKey = secp256k1.getPublicKey(secretKey);
|
|
19
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
20
|
+
* const sig = secp256k1.sign(msg, secretKey);
|
|
21
|
+
* const isValid = secp256k1.verify(sig, msg, publicKey);
|
|
22
|
+
* // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare const secp256k1: ECDSA;
|
|
26
|
+
declare function taggedHash(tag: string, ...messages: TArg<Uint8Array[]>): TRet<Uint8Array>;
|
|
27
|
+
/**
|
|
28
|
+
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
|
|
29
|
+
* @returns valid point checked for being on-curve
|
|
30
|
+
*/
|
|
31
|
+
declare function lift_x(x: bigint): PointType<bigint>;
|
|
32
|
+
/** Schnorr public key is just `x` coordinate of Point as per BIP340. */
|
|
33
|
+
declare function schnorrGetPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array>;
|
|
34
|
+
/**
|
|
35
|
+
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
|
|
36
|
+
* `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not
|
|
37
|
+
* be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden
|
|
38
|
+
* deterministic signing against side-channel and fault-injection attacks.
|
|
39
|
+
*/
|
|
40
|
+
declare function schnorrSign(message: TArg<Uint8Array>, secretKey: TArg<Uint8Array>, auxRand?: TArg<Uint8Array>): TRet<Uint8Array>;
|
|
41
|
+
/**
|
|
42
|
+
* Verifies Schnorr signature.
|
|
43
|
+
* Will swallow errors & return false except for initial type validation of arguments.
|
|
44
|
+
*/
|
|
45
|
+
declare function schnorrVerify(signature: TArg<Uint8Array>, message: TArg<Uint8Array>, publicKey: TArg<Uint8Array>): boolean;
|
|
46
|
+
export declare const __TEST: {
|
|
47
|
+
lift_x: typeof lift_x;
|
|
48
|
+
};
|
|
49
|
+
/** Schnorr-specific secp256k1 API from BIP340. */
|
|
50
|
+
export type SecpSchnorr = {
|
|
51
|
+
/**
|
|
52
|
+
* Generate one Schnorr secret/public keypair.
|
|
53
|
+
* @param seed - Optional seed for deterministic testing or custom randomness.
|
|
54
|
+
* @returns Fresh secret/public keypair.
|
|
55
|
+
*/
|
|
56
|
+
keygen: (seed?: TArg<Uint8Array>) => {
|
|
57
|
+
secretKey: TRet<Uint8Array>;
|
|
58
|
+
publicKey: TRet<Uint8Array>;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Derive the x-only public key from a secret key.
|
|
62
|
+
* @param secretKey - Secret key bytes.
|
|
63
|
+
* @returns X-only public key bytes.
|
|
64
|
+
*/
|
|
65
|
+
getPublicKey: typeof schnorrGetPublicKey;
|
|
66
|
+
/**
|
|
67
|
+
* Create one BIP340 Schnorr signature.
|
|
68
|
+
* @param message - Message bytes to sign.
|
|
69
|
+
* @param secretKey - Secret key bytes.
|
|
70
|
+
* @param auxRand - Optional auxiliary randomness.
|
|
71
|
+
* @returns Compact Schnorr signature bytes.
|
|
72
|
+
*/
|
|
73
|
+
sign: typeof schnorrSign;
|
|
74
|
+
/**
|
|
75
|
+
* Verify one BIP340 Schnorr signature.
|
|
76
|
+
* @param signature - Compact signature bytes.
|
|
77
|
+
* @param message - Signed message bytes.
|
|
78
|
+
* @param publicKey - X-only public key bytes.
|
|
79
|
+
* @returns `true` when the signature is valid.
|
|
80
|
+
*/
|
|
81
|
+
verify: typeof schnorrVerify;
|
|
82
|
+
/** Underlying secp256k1 point constructor. */
|
|
83
|
+
Point: WeierstrassPointCons<bigint>;
|
|
84
|
+
/** Helper utilities for Schnorr-specific key handling and tagged hashing. */
|
|
85
|
+
utils: {
|
|
86
|
+
/** Generate one Schnorr secret key. */
|
|
87
|
+
randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
|
88
|
+
/** Convert one point into its x-only BIP340 byte encoding. */
|
|
89
|
+
pointToBytes: (point: TArg<PointType<bigint>>) => TRet<Uint8Array>;
|
|
90
|
+
/** Lift one x coordinate into the unique even-Y point. */
|
|
91
|
+
lift_x: typeof lift_x;
|
|
92
|
+
/** Compute a BIP340 tagged hash. */
|
|
93
|
+
taggedHash: typeof taggedHash;
|
|
94
|
+
};
|
|
95
|
+
/** Public byte lengths for keys, signatures, and seeds. */
|
|
96
|
+
lengths: CurveLengths;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Schnorr signatures over secp256k1.
|
|
100
|
+
* See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.
|
|
101
|
+
* @example
|
|
102
|
+
* Generate one BIP340 Schnorr keypair, sign a message, and verify it.
|
|
103
|
+
*
|
|
104
|
+
* ```js
|
|
105
|
+
* import { schnorr } from './secp256k1';
|
|
106
|
+
* const { secretKey, publicKey } = schnorr.keygen();
|
|
107
|
+
* // const publicKey = schnorr.getPublicKey(secretKey);
|
|
108
|
+
* const msg = new TextEncoder().encode('hello');
|
|
109
|
+
* const sig = schnorr.sign(msg, secretKey);
|
|
110
|
+
* const isValid = schnorr.verify(sig, msg, publicKey);
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
export declare const schnorr: SecpSchnorr;
|
|
114
|
+
/**
|
|
115
|
+
* Hashing / encoding to secp256k1 points / field. RFC 9380 methods.
|
|
116
|
+
* @example
|
|
117
|
+
* Hash one message onto secp256k1.
|
|
118
|
+
*
|
|
119
|
+
* ```ts
|
|
120
|
+
* const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export declare const secp256k1_hasher: H2CHasher<WeierstrassPointCons<bigint>>;
|
|
124
|
+
/**
|
|
125
|
+
* FROST threshold signatures over secp256k1. RFC 9591.
|
|
126
|
+
* @example
|
|
127
|
+
* Create one trusted-dealer package for 2-of-3 secp256k1 signing.
|
|
128
|
+
*
|
|
129
|
+
* ```ts
|
|
130
|
+
* const alice = secp256k1_FROST.Identifier.derive('alice@example.com');
|
|
131
|
+
* const bob = secp256k1_FROST.Identifier.derive('bob@example.com');
|
|
132
|
+
* const carol = secp256k1_FROST.Identifier.derive('carol@example.com');
|
|
133
|
+
* const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
export declare const secp256k1_FROST: TRet<FROST>;
|
|
137
|
+
/**
|
|
138
|
+
* FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.
|
|
139
|
+
* DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while
|
|
140
|
+
* `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.
|
|
141
|
+
* @example
|
|
142
|
+
* Create one trusted-dealer package for Taproot-compatible FROST signing.
|
|
143
|
+
*
|
|
144
|
+
* ```ts
|
|
145
|
+
* const alice = schnorr_FROST.Identifier.derive('alice@example.com');
|
|
146
|
+
* const bob = schnorr_FROST.Identifier.derive('bob@example.com');
|
|
147
|
+
* const carol = schnorr_FROST.Identifier.derive('carol@example.com');
|
|
148
|
+
* const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
export declare const schnorr_FROST: TRet<FROST>;
|
|
152
|
+
export {};
|
package/secp256k1.js
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.schnorr_FROST = exports.secp256k1_FROST = exports.secp256k1_hasher = exports.schnorr = exports.__TEST = exports.secp256k1 = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
|
|
6
|
+
*
|
|
7
|
+
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
|
|
8
|
+
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
12
|
+
const sha2_1 = require("@decryption/hashes/sha2");
|
|
13
|
+
const utils_1 = require("@decryption/hashes/utils");
|
|
14
|
+
const curve_1 = require("./abstract/curve");
|
|
15
|
+
const frost_1 = require("./abstract/frost");
|
|
16
|
+
const hash_to_curve_1 = require("./abstract/hash-to-curve");
|
|
17
|
+
const modular_1 = require("./abstract/modular");
|
|
18
|
+
const weierstrass_1 = require("./abstract/weierstrass");
|
|
19
|
+
const utils_2 = require("./utils");
|
|
20
|
+
// Seems like generator was produced from some seed:
|
|
21
|
+
// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`
|
|
22
|
+
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
|
|
23
|
+
const secp256k1_CURVE = {
|
|
24
|
+
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
|
|
25
|
+
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
|
|
26
|
+
h: BigInt(1),
|
|
27
|
+
a: BigInt(0),
|
|
28
|
+
b: BigInt(7),
|
|
29
|
+
Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
|
|
30
|
+
Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
|
|
31
|
+
};
|
|
32
|
+
const secp256k1_ENDO = {
|
|
33
|
+
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
|
|
34
|
+
basises: [
|
|
35
|
+
[BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
|
|
36
|
+
[BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
|
|
37
|
+
],
|
|
38
|
+
};
|
|
39
|
+
const _0n = /* @__PURE__ */ BigInt(0);
|
|
40
|
+
const _2n = /* @__PURE__ */ BigInt(2);
|
|
41
|
+
/**
|
|
42
|
+
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
|
|
43
|
+
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
|
|
44
|
+
*/
|
|
45
|
+
function sqrtMod(y) {
|
|
46
|
+
const P = secp256k1_CURVE.p;
|
|
47
|
+
// prettier-ignore
|
|
48
|
+
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
49
|
+
// prettier-ignore
|
|
50
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
51
|
+
const b2 = (y * y * y) % P; // x^3, 11
|
|
52
|
+
const b3 = (b2 * b2 * y) % P; // x^7
|
|
53
|
+
const b6 = ((0, modular_1.pow2)(b3, _3n, P) * b3) % P;
|
|
54
|
+
const b9 = ((0, modular_1.pow2)(b6, _3n, P) * b3) % P;
|
|
55
|
+
const b11 = ((0, modular_1.pow2)(b9, _2n, P) * b2) % P;
|
|
56
|
+
const b22 = ((0, modular_1.pow2)(b11, _11n, P) * b11) % P;
|
|
57
|
+
const b44 = ((0, modular_1.pow2)(b22, _22n, P) * b22) % P;
|
|
58
|
+
const b88 = ((0, modular_1.pow2)(b44, _44n, P) * b44) % P;
|
|
59
|
+
const b176 = ((0, modular_1.pow2)(b88, _88n, P) * b88) % P;
|
|
60
|
+
const b220 = ((0, modular_1.pow2)(b176, _44n, P) * b44) % P;
|
|
61
|
+
const b223 = ((0, modular_1.pow2)(b220, _3n, P) * b3) % P;
|
|
62
|
+
const t1 = ((0, modular_1.pow2)(b223, _23n, P) * b22) % P;
|
|
63
|
+
const t2 = ((0, modular_1.pow2)(t1, _6n, P) * b2) % P;
|
|
64
|
+
const root = (0, modular_1.pow2)(t2, _2n, P);
|
|
65
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
66
|
+
throw new Error('Cannot find square root');
|
|
67
|
+
return root;
|
|
68
|
+
}
|
|
69
|
+
const Fpk1 = (0, modular_1.Field)(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
70
|
+
const Pointk1 = /* @__PURE__ */ (0, weierstrass_1.weierstrass)(secp256k1_CURVE, {
|
|
71
|
+
Fp: Fpk1,
|
|
72
|
+
endo: secp256k1_ENDO,
|
|
73
|
+
});
|
|
74
|
+
/**
|
|
75
|
+
* secp256k1 curve: ECDSA and ECDH methods.
|
|
76
|
+
*
|
|
77
|
+
* Uses sha256 to hash messages. To use a different hash,
|
|
78
|
+
* pass `{ prehash: false }` to sign / verify.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* Generate one secp256k1 keypair, sign a message, and verify it.
|
|
82
|
+
*
|
|
83
|
+
* ```js
|
|
84
|
+
* import { secp256k1 } from './secp256k1';
|
|
85
|
+
* const { secretKey, publicKey } = secp256k1.keygen();
|
|
86
|
+
* // const publicKey = secp256k1.getPublicKey(secretKey);
|
|
87
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
88
|
+
* const sig = secp256k1.sign(msg, secretKey);
|
|
89
|
+
* const isValid = secp256k1.verify(sig, msg, publicKey);
|
|
90
|
+
* // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
exports.secp256k1 = (0, weierstrass_1.ecdsa)(Pointk1, sha2_1.sha256);
|
|
94
|
+
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
|
|
95
|
+
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
|
|
96
|
+
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
|
|
97
|
+
const TAGGED_HASH_PREFIXES = {};
|
|
98
|
+
// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.
|
|
99
|
+
function taggedHash(tag, ...messages) {
|
|
100
|
+
let tagP = TAGGED_HASH_PREFIXES[tag];
|
|
101
|
+
if (tagP === undefined) {
|
|
102
|
+
const tagH = (0, sha2_1.sha256)((0, utils_2.asciiToBytes)(tag));
|
|
103
|
+
tagP = (0, utils_2.concatBytes)(tagH, tagH);
|
|
104
|
+
TAGGED_HASH_PREFIXES[tag] = tagP;
|
|
105
|
+
}
|
|
106
|
+
return (0, sha2_1.sha256)((0, utils_2.concatBytes)(tagP, ...messages));
|
|
107
|
+
}
|
|
108
|
+
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
|
|
109
|
+
const pointToBytes = (point) => point.toBytes(true).slice(1);
|
|
110
|
+
const hasEven = (y) => y % _2n === _0n;
|
|
111
|
+
// Calculate point, scalar and bytes
|
|
112
|
+
function schnorrGetExtPubKey(priv) {
|
|
113
|
+
const { Fn, BASE } = Pointk1;
|
|
114
|
+
const d_ = Fn.fromBytes(priv);
|
|
115
|
+
const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
|
|
116
|
+
const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
|
|
117
|
+
return { scalar, bytes: pointToBytes(p) };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
|
|
121
|
+
* @returns valid point checked for being on-curve
|
|
122
|
+
*/
|
|
123
|
+
function lift_x(x) {
|
|
124
|
+
const Fp = Fpk1;
|
|
125
|
+
if (!Fp.isValidNot0(x))
|
|
126
|
+
throw new Error('invalid x: Fail if x ≥ p');
|
|
127
|
+
const xx = Fp.create(x * x);
|
|
128
|
+
const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
|
|
129
|
+
let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
|
|
130
|
+
// Return the unique point P such that x(P) = x and
|
|
131
|
+
// y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
|
|
132
|
+
if (!hasEven(y))
|
|
133
|
+
y = Fp.neg(y);
|
|
134
|
+
const p = Pointk1.fromAffine({ x, y });
|
|
135
|
+
p.assertValidity();
|
|
136
|
+
return p;
|
|
137
|
+
}
|
|
138
|
+
// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only
|
|
139
|
+
// parses big-endian bytes and does not enforce the fixed-width contract itself.
|
|
140
|
+
const num = utils_2.bytesToNumberBE;
|
|
141
|
+
/** Create tagged hash, convert it to bigint, reduce modulo-n. */
|
|
142
|
+
function challenge(...args) {
|
|
143
|
+
return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
|
|
144
|
+
}
|
|
145
|
+
/** Schnorr public key is just `x` coordinate of Point as per BIP340. */
|
|
146
|
+
function schnorrGetPublicKey(secretKey) {
|
|
147
|
+
return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
|
|
151
|
+
* `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not
|
|
152
|
+
* be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden
|
|
153
|
+
* deterministic signing against side-channel and fault-injection attacks.
|
|
154
|
+
*/
|
|
155
|
+
function schnorrSign(message, secretKey, auxRand = (0, utils_1.randomBytes)(32)) {
|
|
156
|
+
const { Fn, BASE } = Pointk1;
|
|
157
|
+
const m = (0, utils_2.abytes)(message, undefined, 'message');
|
|
158
|
+
const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
|
|
159
|
+
const a = (0, utils_2.abytes)(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array
|
|
160
|
+
// Let t be the byte-wise xor of bytes(d) and hash/aux(a).
|
|
161
|
+
const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));
|
|
162
|
+
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
|
|
163
|
+
// BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)
|
|
164
|
+
// here: that helper parses canonical secret keys and rejects rand >= n instead
|
|
165
|
+
// of reducing the nonce hash modulo the group order.
|
|
166
|
+
const k_ = Fn.create(num(rand));
|
|
167
|
+
// BIP-340: "Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G."
|
|
168
|
+
if (k_ === 0n)
|
|
169
|
+
throw new Error('sign failed: k is zero');
|
|
170
|
+
const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.
|
|
171
|
+
const k = hasEven(p.y) ? k_ : Fn.neg(k_);
|
|
172
|
+
const rx = pointToBytes(p);
|
|
173
|
+
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
|
|
174
|
+
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
|
|
175
|
+
sig.set(rx, 0);
|
|
176
|
+
sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
|
|
177
|
+
// If Verify(bytes(P), m, sig) (see below) returns failure, abort
|
|
178
|
+
if (!schnorrVerify(sig, m, px))
|
|
179
|
+
throw new Error('sign: Invalid signature produced');
|
|
180
|
+
return sig;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Verifies Schnorr signature.
|
|
184
|
+
* Will swallow errors & return false except for initial type validation of arguments.
|
|
185
|
+
*/
|
|
186
|
+
function schnorrVerify(signature, message, publicKey) {
|
|
187
|
+
const { Fp, Fn, BASE } = Pointk1;
|
|
188
|
+
const sig = (0, utils_2.abytes)(signature, 64, 'signature');
|
|
189
|
+
const m = (0, utils_2.abytes)(message, undefined, 'message');
|
|
190
|
+
const pub = (0, utils_2.abytes)(publicKey, 32, 'publicKey');
|
|
191
|
+
try {
|
|
192
|
+
const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
|
|
193
|
+
const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
|
|
194
|
+
if (!Fp.isValidNot0(r))
|
|
195
|
+
return false;
|
|
196
|
+
const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
|
|
197
|
+
// Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches
|
|
198
|
+
// s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as
|
|
199
|
+
// crafted edge cases and fail closed instead of carrying that extra verification surface.
|
|
200
|
+
if (!Fn.isValidNot0(s))
|
|
201
|
+
return false;
|
|
202
|
+
// int(challenge(bytes(r) || bytes(P) || m)) % n
|
|
203
|
+
const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
|
|
204
|
+
// R = s⋅G - e⋅P, where -eP == (n-e)P
|
|
205
|
+
const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
|
|
206
|
+
const { x, y } = R.toAffine();
|
|
207
|
+
// Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
|
|
208
|
+
if (R.is0() || !hasEven(y) || x !== r)
|
|
209
|
+
return false;
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
exports.__TEST = Object.freeze({ lift_x });
|
|
217
|
+
/**
|
|
218
|
+
* Schnorr signatures over secp256k1.
|
|
219
|
+
* See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.
|
|
220
|
+
* @example
|
|
221
|
+
* Generate one BIP340 Schnorr keypair, sign a message, and verify it.
|
|
222
|
+
*
|
|
223
|
+
* ```js
|
|
224
|
+
* import { schnorr } from './secp256k1';
|
|
225
|
+
* const { secretKey, publicKey } = schnorr.keygen();
|
|
226
|
+
* // const publicKey = schnorr.getPublicKey(secretKey);
|
|
227
|
+
* const msg = new TextEncoder().encode('hello');
|
|
228
|
+
* const sig = schnorr.sign(msg, secretKey);
|
|
229
|
+
* const isValid = schnorr.verify(sig, msg, publicKey);
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
exports.schnorr = (() => {
|
|
233
|
+
const size = 32;
|
|
234
|
+
const seedLength = 48;
|
|
235
|
+
const randomSecretKey = (seed) => {
|
|
236
|
+
seed = seed === undefined ? (0, utils_1.randomBytes)(seedLength) : seed;
|
|
237
|
+
return (0, modular_1.mapHashToField)(seed, secp256k1_CURVE.n);
|
|
238
|
+
};
|
|
239
|
+
return Object.freeze({
|
|
240
|
+
keygen: (0, curve_1.createKeygen)(randomSecretKey, schnorrGetPublicKey),
|
|
241
|
+
getPublicKey: schnorrGetPublicKey,
|
|
242
|
+
sign: schnorrSign,
|
|
243
|
+
verify: schnorrVerify,
|
|
244
|
+
Point: Pointk1,
|
|
245
|
+
utils: Object.freeze({
|
|
246
|
+
randomSecretKey,
|
|
247
|
+
taggedHash,
|
|
248
|
+
lift_x,
|
|
249
|
+
pointToBytes,
|
|
250
|
+
}),
|
|
251
|
+
lengths: Object.freeze({
|
|
252
|
+
secretKey: size,
|
|
253
|
+
publicKey: size,
|
|
254
|
+
publicKeyHasPrefix: false,
|
|
255
|
+
signature: size * 2,
|
|
256
|
+
seed: seedLength,
|
|
257
|
+
}),
|
|
258
|
+
});
|
|
259
|
+
})();
|
|
260
|
+
// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.
|
|
261
|
+
// The final `1` in each denominator array is the explicit monic leading term.
|
|
262
|
+
const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_1.isogenyMap)(Fpk1, [
|
|
263
|
+
// xNum
|
|
264
|
+
[
|
|
265
|
+
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
|
|
266
|
+
'0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
|
|
267
|
+
'0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
|
|
268
|
+
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
|
|
269
|
+
],
|
|
270
|
+
// xDen
|
|
271
|
+
[
|
|
272
|
+
'0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
|
|
273
|
+
'0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
|
|
274
|
+
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
|
|
275
|
+
],
|
|
276
|
+
// yNum
|
|
277
|
+
[
|
|
278
|
+
'0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
|
|
279
|
+
'0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
|
|
280
|
+
'0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
|
|
281
|
+
'0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
|
|
282
|
+
],
|
|
283
|
+
// yDen
|
|
284
|
+
[
|
|
285
|
+
'0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
|
|
286
|
+
'0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
|
|
287
|
+
'0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
|
|
288
|
+
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
|
|
289
|
+
],
|
|
290
|
+
].map((i) => i.map((j) => BigInt(j)))))();
|
|
291
|
+
// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.
|
|
292
|
+
let mapSWU;
|
|
293
|
+
const getMapSWU = () => mapSWU ||
|
|
294
|
+
(mapSWU = (0, weierstrass_1.mapToCurveSimpleSWU)(Fpk1, {
|
|
295
|
+
// Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so
|
|
296
|
+
// defer it to first use; after that the cached mapper is reused directly.
|
|
297
|
+
A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
|
|
298
|
+
B: BigInt('1771'),
|
|
299
|
+
Z: Fpk1.create(BigInt('-11')),
|
|
300
|
+
}));
|
|
301
|
+
/**
|
|
302
|
+
* Hashing / encoding to secp256k1 points / field. RFC 9380 methods.
|
|
303
|
+
* @example
|
|
304
|
+
* Hash one message onto secp256k1.
|
|
305
|
+
*
|
|
306
|
+
* ```ts
|
|
307
|
+
* const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
|
|
308
|
+
* ```
|
|
309
|
+
*/
|
|
310
|
+
exports.secp256k1_hasher = (() => (0, hash_to_curve_1.createHasher)(Pointk1, (scalars) => {
|
|
311
|
+
const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));
|
|
312
|
+
return isoMap(x, y);
|
|
313
|
+
}, {
|
|
314
|
+
DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
|
|
315
|
+
encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
|
|
316
|
+
p: Fpk1.ORDER,
|
|
317
|
+
m: 1,
|
|
318
|
+
k: 128,
|
|
319
|
+
expand: 'xmd',
|
|
320
|
+
hash: sha2_1.sha256,
|
|
321
|
+
}))();
|
|
322
|
+
/**
|
|
323
|
+
* FROST threshold signatures over secp256k1. RFC 9591.
|
|
324
|
+
* @example
|
|
325
|
+
* Create one trusted-dealer package for 2-of-3 secp256k1 signing.
|
|
326
|
+
*
|
|
327
|
+
* ```ts
|
|
328
|
+
* const alice = secp256k1_FROST.Identifier.derive('alice@example.com');
|
|
329
|
+
* const bob = secp256k1_FROST.Identifier.derive('bob@example.com');
|
|
330
|
+
* const carol = secp256k1_FROST.Identifier.derive('carol@example.com');
|
|
331
|
+
* const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
|
|
332
|
+
* ```
|
|
333
|
+
*/
|
|
334
|
+
exports.secp256k1_FROST = (() => (0, frost_1.createFROST)({
|
|
335
|
+
name: 'FROST-secp256k1-SHA256-v1',
|
|
336
|
+
Point: Pointk1,
|
|
337
|
+
hashToScalar: exports.secp256k1_hasher.hashToScalar,
|
|
338
|
+
hash: sha2_1.sha256,
|
|
339
|
+
}))();
|
|
340
|
+
// Taproot utils
|
|
341
|
+
// `undefined` means "disable TapTweak entirely"; callers that want the BIP-341/BIP-386 empty
|
|
342
|
+
// merkle root must pass `new Uint8Array(0)` explicitly.
|
|
343
|
+
function tweak(point, merkleRoot) {
|
|
344
|
+
if (merkleRoot === undefined)
|
|
345
|
+
return _0n;
|
|
346
|
+
const x = pointToBytes(point);
|
|
347
|
+
const t = (0, utils_2.bytesToNumberBE)(taggedHash('TapTweak', x, merkleRoot));
|
|
348
|
+
// BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: "if t >= SECP256K1_ORDER:
|
|
349
|
+
// raise ValueError". TapTweak must reject overflow instead of reducing modulo n.
|
|
350
|
+
if (!Pointk1.Fn.isValid(t))
|
|
351
|
+
throw new Error('invalid TapTweak hash');
|
|
352
|
+
return t;
|
|
353
|
+
}
|
|
354
|
+
function frostPubToEvenY(pub) {
|
|
355
|
+
const VK = Pointk1.fromBytes(pub.commitments[0]);
|
|
356
|
+
// Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.
|
|
357
|
+
if (hasEven(VK.y))
|
|
358
|
+
return pub;
|
|
359
|
+
return {
|
|
360
|
+
signers: { min: pub.signers.min, max: pub.signers.max },
|
|
361
|
+
commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),
|
|
362
|
+
verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [
|
|
363
|
+
k,
|
|
364
|
+
Pointk1.fromBytes(v).negate().toBytes(),
|
|
365
|
+
])),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function frostSecretToEvenY(s, pub) {
|
|
369
|
+
const VK = Pointk1.fromBytes(pub.commitments[0]);
|
|
370
|
+
// Keep aliasing on the already-even path so wrapper callers can preserve package identity.
|
|
371
|
+
if (hasEven(VK.y))
|
|
372
|
+
return s;
|
|
373
|
+
const Fn = Pointk1.Fn;
|
|
374
|
+
return {
|
|
375
|
+
...s,
|
|
376
|
+
signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
function frostNoncesToEvenY(PK, nonces) {
|
|
380
|
+
if (hasEven(PK.y))
|
|
381
|
+
return nonces;
|
|
382
|
+
const Fn = Pointk1.Fn;
|
|
383
|
+
return {
|
|
384
|
+
binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),
|
|
385
|
+
hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function frostTweakSecret(s, pub, merkleRoot) {
|
|
389
|
+
const Fn = Pointk1.Fn;
|
|
390
|
+
const keyPackage = frostSecretToEvenY(s, pub);
|
|
391
|
+
const evenPub = frostPubToEvenY(pub);
|
|
392
|
+
const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);
|
|
393
|
+
const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));
|
|
394
|
+
return {
|
|
395
|
+
identifier: keyPackage.identifier,
|
|
396
|
+
signingShare,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
function frostTweakPublic(pub, merkleRoot) {
|
|
400
|
+
const PKPackage = frostPubToEvenY(pub);
|
|
401
|
+
const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);
|
|
402
|
+
const tp = Pointk1.BASE.multiply(t);
|
|
403
|
+
const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());
|
|
404
|
+
const verifyingShares = {};
|
|
405
|
+
for (const k in PKPackage.verifyingShares) {
|
|
406
|
+
verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();
|
|
407
|
+
}
|
|
408
|
+
return {
|
|
409
|
+
signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },
|
|
410
|
+
commitments,
|
|
411
|
+
verifyingShares,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.
|
|
416
|
+
* DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while
|
|
417
|
+
* `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.
|
|
418
|
+
* @example
|
|
419
|
+
* Create one trusted-dealer package for Taproot-compatible FROST signing.
|
|
420
|
+
*
|
|
421
|
+
* ```ts
|
|
422
|
+
* const alice = schnorr_FROST.Identifier.derive('alice@example.com');
|
|
423
|
+
* const bob = schnorr_FROST.Identifier.derive('bob@example.com');
|
|
424
|
+
* const carol = schnorr_FROST.Identifier.derive('carol@example.com');
|
|
425
|
+
* const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
|
|
426
|
+
* ```
|
|
427
|
+
*/
|
|
428
|
+
exports.schnorr_FROST = (() => (0, frost_1.createFROST)({
|
|
429
|
+
name: 'FROST-secp256k1-SHA256-TR-v1',
|
|
430
|
+
Point: Pointk1,
|
|
431
|
+
hashToScalar: exports.secp256k1_hasher.hashToScalar,
|
|
432
|
+
hash: sha2_1.sha256,
|
|
433
|
+
// Taproot related hacks
|
|
434
|
+
parsePublicKey(publicKey) {
|
|
435
|
+
// External Taproot keys are x-only, but local key packages still use compressed points.
|
|
436
|
+
if (publicKey.length === 32)
|
|
437
|
+
return lift_x((0, utils_2.bytesToNumberBE)(publicKey));
|
|
438
|
+
if (publicKey.length === 33)
|
|
439
|
+
return Pointk1.fromBytes(publicKey);
|
|
440
|
+
throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);
|
|
441
|
+
},
|
|
442
|
+
adjustScalar(n) {
|
|
443
|
+
const PK = Pointk1.BASE.multiply(n);
|
|
444
|
+
return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);
|
|
445
|
+
},
|
|
446
|
+
adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),
|
|
447
|
+
challenge(R, PK, msg) {
|
|
448
|
+
return challenge(pointToBytes(R), pointToBytes(PK), msg);
|
|
449
|
+
},
|
|
450
|
+
adjustNonces: frostNoncesToEvenY,
|
|
451
|
+
adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),
|
|
452
|
+
adjustPublic: frostPubToEvenY,
|
|
453
|
+
adjustSecret: frostSecretToEvenY,
|
|
454
|
+
adjustTx: {
|
|
455
|
+
// Compat with official implementation
|
|
456
|
+
encode: (tx) => tx.subarray(1),
|
|
457
|
+
decode: (tx) => (0, utils_2.concatBytes)(Uint8Array.of(0x02), tx),
|
|
458
|
+
},
|
|
459
|
+
adjustDKG: (k) => {
|
|
460
|
+
// Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the
|
|
461
|
+
// empty Taproot merkle root, while dealer-generated keys stay untweaked.
|
|
462
|
+
const merkleRoot = new Uint8Array(0);
|
|
463
|
+
return {
|
|
464
|
+
public: frostTweakPublic(k.public, merkleRoot),
|
|
465
|
+
secret: frostTweakSecret(k.secret, k.public, merkleRoot),
|
|
466
|
+
};
|
|
467
|
+
},
|
|
468
|
+
}))();
|