@noble/curves 1.9.7 → 2.0.0-beta.2

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.
Files changed (242) hide show
  1. package/README.md +520 -505
  2. package/abstract/bls.d.ts +58 -120
  3. package/abstract/bls.d.ts.map +1 -1
  4. package/abstract/bls.js +108 -152
  5. package/abstract/bls.js.map +1 -1
  6. package/abstract/curve.d.ts +18 -54
  7. package/abstract/curve.d.ts.map +1 -1
  8. package/abstract/curve.js +30 -49
  9. package/abstract/curve.js.map +1 -1
  10. package/abstract/edwards.d.ts +18 -77
  11. package/abstract/edwards.d.ts.map +1 -1
  12. package/abstract/edwards.js +68 -144
  13. package/abstract/edwards.js.map +1 -1
  14. package/abstract/fft.js +14 -27
  15. package/abstract/fft.js.map +1 -1
  16. package/abstract/hash-to-curve.d.ts +35 -47
  17. package/abstract/hash-to-curve.d.ts.map +1 -1
  18. package/abstract/hash-to-curve.js +42 -46
  19. package/abstract/hash-to-curve.js.map +1 -1
  20. package/abstract/modular.d.ts +5 -17
  21. package/abstract/modular.d.ts.map +1 -1
  22. package/abstract/modular.js +170 -169
  23. package/abstract/modular.js.map +1 -1
  24. package/abstract/montgomery.d.ts +7 -12
  25. package/abstract/montgomery.d.ts.map +1 -1
  26. package/abstract/montgomery.js +22 -29
  27. package/abstract/montgomery.js.map +1 -1
  28. package/abstract/oprf.d.ts +282 -0
  29. package/abstract/oprf.d.ts.map +1 -0
  30. package/abstract/oprf.js +297 -0
  31. package/abstract/oprf.js.map +1 -0
  32. package/abstract/poseidon.d.ts.map +1 -1
  33. package/abstract/poseidon.js +26 -31
  34. package/abstract/poseidon.js.map +1 -1
  35. package/abstract/tower.d.ts.map +1 -1
  36. package/abstract/tower.js +43 -19
  37. package/abstract/tower.js.map +1 -1
  38. package/abstract/weierstrass.d.ts +77 -168
  39. package/abstract/weierstrass.d.ts.map +1 -1
  40. package/abstract/weierstrass.js +184 -389
  41. package/abstract/weierstrass.js.map +1 -1
  42. package/bls12-381.d.ts +5 -11
  43. package/bls12-381.d.ts.map +1 -1
  44. package/bls12-381.js +161 -181
  45. package/bls12-381.js.map +1 -1
  46. package/bn254.d.ts +59 -11
  47. package/bn254.d.ts.map +1 -1
  48. package/bn254.js +69 -97
  49. package/bn254.js.map +1 -1
  50. package/ed25519.d.ts +33 -48
  51. package/ed25519.d.ts.map +1 -1
  52. package/ed25519.js +147 -161
  53. package/ed25519.js.map +1 -1
  54. package/ed448.d.ts +27 -36
  55. package/ed448.d.ts.map +1 -1
  56. package/ed448.js +143 -164
  57. package/ed448.js.map +1 -1
  58. package/index.d.ts +1 -0
  59. package/index.js +20 -4
  60. package/index.js.map +1 -1
  61. package/misc.d.ts +10 -14
  62. package/misc.d.ts.map +1 -1
  63. package/misc.js +53 -62
  64. package/misc.js.map +1 -1
  65. package/nist.d.ts +31 -16
  66. package/nist.d.ts.map +1 -1
  67. package/nist.js +75 -64
  68. package/nist.js.map +1 -1
  69. package/package.json +20 -234
  70. package/secp256k1.d.ts +17 -30
  71. package/secp256k1.d.ts.map +1 -1
  72. package/secp256k1.js +59 -73
  73. package/secp256k1.js.map +1 -1
  74. package/src/abstract/bls.ts +207 -354
  75. package/src/abstract/curve.ts +25 -84
  76. package/src/abstract/edwards.ts +68 -193
  77. package/src/abstract/hash-to-curve.ts +71 -85
  78. package/src/abstract/modular.ts +150 -134
  79. package/src/abstract/montgomery.ts +28 -35
  80. package/src/abstract/oprf.ts +600 -0
  81. package/src/abstract/poseidon.ts +6 -8
  82. package/src/abstract/tower.ts +0 -3
  83. package/src/abstract/weierstrass.ts +203 -525
  84. package/src/bls12-381.ts +133 -139
  85. package/src/bn254.ts +69 -93
  86. package/src/ed25519.ts +106 -133
  87. package/src/ed448.ts +111 -138
  88. package/src/index.ts +19 -3
  89. package/src/misc.ts +68 -51
  90. package/src/nist.ts +77 -70
  91. package/src/secp256k1.ts +46 -81
  92. package/src/utils.ts +67 -137
  93. package/src/webcrypto.ts +403 -0
  94. package/utils.d.ts +31 -38
  95. package/utils.d.ts.map +1 -1
  96. package/utils.js +66 -185
  97. package/utils.js.map +1 -1
  98. package/webcrypto.d.ts +99 -0
  99. package/webcrypto.d.ts.map +1 -0
  100. package/webcrypto.js +256 -0
  101. package/webcrypto.js.map +1 -0
  102. package/_shortw_utils.d.ts +0 -19
  103. package/_shortw_utils.d.ts.map +0 -1
  104. package/_shortw_utils.js +0 -20
  105. package/_shortw_utils.js.map +0 -1
  106. package/abstract/utils.d.ts +0 -78
  107. package/abstract/utils.d.ts.map +0 -1
  108. package/abstract/utils.js +0 -73
  109. package/abstract/utils.js.map +0 -1
  110. package/esm/_shortw_utils.d.ts +0 -19
  111. package/esm/_shortw_utils.d.ts.map +0 -1
  112. package/esm/_shortw_utils.js +0 -16
  113. package/esm/_shortw_utils.js.map +0 -1
  114. package/esm/abstract/bls.d.ts +0 -190
  115. package/esm/abstract/bls.d.ts.map +0 -1
  116. package/esm/abstract/bls.js +0 -408
  117. package/esm/abstract/bls.js.map +0 -1
  118. package/esm/abstract/curve.d.ts +0 -231
  119. package/esm/abstract/curve.d.ts.map +0 -1
  120. package/esm/abstract/curve.js +0 -465
  121. package/esm/abstract/curve.js.map +0 -1
  122. package/esm/abstract/edwards.d.ts +0 -243
  123. package/esm/abstract/edwards.d.ts.map +0 -1
  124. package/esm/abstract/edwards.js +0 -627
  125. package/esm/abstract/edwards.js.map +0 -1
  126. package/esm/abstract/fft.d.ts +0 -122
  127. package/esm/abstract/fft.d.ts.map +0 -1
  128. package/esm/abstract/fft.js +0 -425
  129. package/esm/abstract/fft.js.map +0 -1
  130. package/esm/abstract/hash-to-curve.d.ts +0 -102
  131. package/esm/abstract/hash-to-curve.d.ts.map +0 -1
  132. package/esm/abstract/hash-to-curve.js +0 -203
  133. package/esm/abstract/hash-to-curve.js.map +0 -1
  134. package/esm/abstract/modular.d.ts +0 -171
  135. package/esm/abstract/modular.d.ts.map +0 -1
  136. package/esm/abstract/modular.js +0 -530
  137. package/esm/abstract/modular.js.map +0 -1
  138. package/esm/abstract/montgomery.d.ts +0 -30
  139. package/esm/abstract/montgomery.d.ts.map +0 -1
  140. package/esm/abstract/montgomery.js +0 -157
  141. package/esm/abstract/montgomery.js.map +0 -1
  142. package/esm/abstract/poseidon.d.ts +0 -68
  143. package/esm/abstract/poseidon.d.ts.map +0 -1
  144. package/esm/abstract/poseidon.js +0 -296
  145. package/esm/abstract/poseidon.js.map +0 -1
  146. package/esm/abstract/tower.d.ts +0 -95
  147. package/esm/abstract/tower.d.ts.map +0 -1
  148. package/esm/abstract/tower.js +0 -714
  149. package/esm/abstract/tower.js.map +0 -1
  150. package/esm/abstract/utils.d.ts +0 -78
  151. package/esm/abstract/utils.d.ts.map +0 -1
  152. package/esm/abstract/utils.js +0 -70
  153. package/esm/abstract/utils.js.map +0 -1
  154. package/esm/abstract/weierstrass.d.ts +0 -416
  155. package/esm/abstract/weierstrass.d.ts.map +0 -1
  156. package/esm/abstract/weierstrass.js +0 -1413
  157. package/esm/abstract/weierstrass.js.map +0 -1
  158. package/esm/bls12-381.d.ts +0 -16
  159. package/esm/bls12-381.d.ts.map +0 -1
  160. package/esm/bls12-381.js +0 -705
  161. package/esm/bls12-381.js.map +0 -1
  162. package/esm/bn254.d.ts +0 -18
  163. package/esm/bn254.d.ts.map +0 -1
  164. package/esm/bn254.js +0 -214
  165. package/esm/bn254.js.map +0 -1
  166. package/esm/ed25519.d.ts +0 -106
  167. package/esm/ed25519.d.ts.map +0 -1
  168. package/esm/ed25519.js +0 -467
  169. package/esm/ed25519.js.map +0 -1
  170. package/esm/ed448.d.ts +0 -100
  171. package/esm/ed448.d.ts.map +0 -1
  172. package/esm/ed448.js +0 -459
  173. package/esm/ed448.js.map +0 -1
  174. package/esm/index.d.ts +0 -2
  175. package/esm/index.d.ts.map +0 -1
  176. package/esm/index.js +0 -17
  177. package/esm/index.js.map +0 -1
  178. package/esm/jubjub.d.ts +0 -12
  179. package/esm/jubjub.d.ts.map +0 -1
  180. package/esm/jubjub.js +0 -12
  181. package/esm/jubjub.js.map +0 -1
  182. package/esm/misc.d.ts +0 -19
  183. package/esm/misc.d.ts.map +0 -1
  184. package/esm/misc.js +0 -109
  185. package/esm/misc.js.map +0 -1
  186. package/esm/nist.d.ts +0 -21
  187. package/esm/nist.d.ts.map +0 -1
  188. package/esm/nist.js +0 -132
  189. package/esm/nist.js.map +0 -1
  190. package/esm/p256.d.ts +0 -16
  191. package/esm/p256.d.ts.map +0 -1
  192. package/esm/p256.js +0 -16
  193. package/esm/p256.js.map +0 -1
  194. package/esm/p384.d.ts +0 -16
  195. package/esm/p384.d.ts.map +0 -1
  196. package/esm/p384.js +0 -16
  197. package/esm/p384.js.map +0 -1
  198. package/esm/p521.d.ts +0 -16
  199. package/esm/p521.d.ts.map +0 -1
  200. package/esm/p521.js +0 -16
  201. package/esm/p521.js.map +0 -1
  202. package/esm/package.json +0 -4
  203. package/esm/pasta.d.ts +0 -10
  204. package/esm/pasta.d.ts.map +0 -1
  205. package/esm/pasta.js +0 -10
  206. package/esm/pasta.js.map +0 -1
  207. package/esm/secp256k1.d.ts +0 -89
  208. package/esm/secp256k1.d.ts.map +0 -1
  209. package/esm/secp256k1.js +0 -294
  210. package/esm/secp256k1.js.map +0 -1
  211. package/esm/utils.d.ts +0 -110
  212. package/esm/utils.d.ts.map +0 -1
  213. package/esm/utils.js +0 -322
  214. package/esm/utils.js.map +0 -1
  215. package/jubjub.d.ts +0 -12
  216. package/jubjub.d.ts.map +0 -1
  217. package/jubjub.js +0 -15
  218. package/jubjub.js.map +0 -1
  219. package/p256.d.ts +0 -16
  220. package/p256.d.ts.map +0 -1
  221. package/p256.js +0 -13
  222. package/p256.js.map +0 -1
  223. package/p384.d.ts +0 -16
  224. package/p384.d.ts.map +0 -1
  225. package/p384.js +0 -13
  226. package/p384.js.map +0 -1
  227. package/p521.d.ts +0 -16
  228. package/p521.d.ts.map +0 -1
  229. package/p521.js +0 -13
  230. package/p521.js.map +0 -1
  231. package/pasta.d.ts +0 -10
  232. package/pasta.d.ts.map +0 -1
  233. package/pasta.js +0 -13
  234. package/pasta.js.map +0 -1
  235. package/src/_shortw_utils.ts +0 -21
  236. package/src/abstract/utils.ts +0 -80
  237. package/src/jubjub.ts +0 -12
  238. package/src/p256.ts +0 -15
  239. package/src/p384.ts +0 -15
  240. package/src/p521.ts +0 -15
  241. package/src/package.json +0 -3
  242. package/src/pasta.ts +0 -9
@@ -1,1413 +0,0 @@
1
- /**
2
- * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
3
- *
4
- * ### Design rationale for types
5
- *
6
- * * Interaction between classes from different curves should fail:
7
- * `k256.Point.BASE.add(p256.Point.BASE)`
8
- * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
9
- * * Different calls of `curve()` would return different classes -
10
- * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
11
- * it won't affect others
12
- *
13
- * TypeScript can't infer types for classes created inside a function. Classes is one instance
14
- * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
15
- * unique type for every function call.
16
- *
17
- * We can use generic types via some param, like curve opts, but that would:
18
- * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
19
- * which is hard to debug.
20
- * 2. Params can be generic and we can't enforce them to be constant value:
21
- * if somebody creates curve from non-constant params,
22
- * it would be allowed to interact with other curves with non-constant params
23
- *
24
- * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
25
- * @module
26
- */
27
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
28
- import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
29
- import { ahash } from '@noble/hashes/utils';
30
- import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
31
- import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
32
- import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
33
- // We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
34
- const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
35
- /**
36
- * Splits scalar for GLV endomorphism.
37
- */
38
- export function _splitEndoScalar(k, basis, n) {
39
- // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
40
- // Since part can be negative, we need to do this on point.
41
- // TODO: verifyScalar function which consumes lambda
42
- const [[a1, b1], [a2, b2]] = basis;
43
- const c1 = divNearest(b2 * k, n);
44
- const c2 = divNearest(-b1 * k, n);
45
- // |k1|/|k2| is < sqrt(N), but can be negative.
46
- // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
47
- let k1 = k - c1 * a1 - c2 * a2;
48
- let k2 = -c1 * b1 - c2 * b2;
49
- const k1neg = k1 < _0n;
50
- const k2neg = k2 < _0n;
51
- if (k1neg)
52
- k1 = -k1;
53
- if (k2neg)
54
- k2 = -k2;
55
- // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
56
- // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
57
- const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
58
- if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
59
- throw new Error('splitScalar (endomorphism): failed, k=' + k);
60
- }
61
- return { k1neg, k1, k2neg, k2 };
62
- }
63
- function validateSigFormat(format) {
64
- if (!['compact', 'recovered', 'der'].includes(format))
65
- throw new Error('Signature format must be "compact", "recovered", or "der"');
66
- return format;
67
- }
68
- function validateSigOpts(opts, def) {
69
- const optsn = {};
70
- for (let optName of Object.keys(def)) {
71
- // @ts-ignore
72
- optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
73
- }
74
- abool(optsn.lowS, 'lowS');
75
- abool(optsn.prehash, 'prehash');
76
- if (optsn.format !== undefined)
77
- validateSigFormat(optsn.format);
78
- return optsn;
79
- }
80
- export class DERErr extends Error {
81
- constructor(m = '') {
82
- super(m);
83
- }
84
- }
85
- /**
86
- * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
87
- *
88
- * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
89
- *
90
- * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
91
- */
92
- export const DER = {
93
- // asn.1 DER encoding utils
94
- Err: DERErr,
95
- // Basic building block is TLV (Tag-Length-Value)
96
- _tlv: {
97
- encode: (tag, data) => {
98
- const { Err: E } = DER;
99
- if (tag < 0 || tag > 256)
100
- throw new E('tlv.encode: wrong tag');
101
- if (data.length & 1)
102
- throw new E('tlv.encode: unpadded data');
103
- const dataLen = data.length / 2;
104
- const len = numberToHexUnpadded(dataLen);
105
- if ((len.length / 2) & 128)
106
- throw new E('tlv.encode: long form length too big');
107
- // length of length with long form flag
108
- const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
109
- const t = numberToHexUnpadded(tag);
110
- return t + lenLen + len + data;
111
- },
112
- // v - value, l - left bytes (unparsed)
113
- decode(tag, data) {
114
- const { Err: E } = DER;
115
- let pos = 0;
116
- if (tag < 0 || tag > 256)
117
- throw new E('tlv.encode: wrong tag');
118
- if (data.length < 2 || data[pos++] !== tag)
119
- throw new E('tlv.decode: wrong tlv');
120
- const first = data[pos++];
121
- const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
122
- let length = 0;
123
- if (!isLong)
124
- length = first;
125
- else {
126
- // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
127
- const lenLen = first & 127;
128
- if (!lenLen)
129
- throw new E('tlv.decode(long): indefinite length not supported');
130
- if (lenLen > 4)
131
- throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
132
- const lengthBytes = data.subarray(pos, pos + lenLen);
133
- if (lengthBytes.length !== lenLen)
134
- throw new E('tlv.decode: length bytes not complete');
135
- if (lengthBytes[0] === 0)
136
- throw new E('tlv.decode(long): zero leftmost byte');
137
- for (const b of lengthBytes)
138
- length = (length << 8) | b;
139
- pos += lenLen;
140
- if (length < 128)
141
- throw new E('tlv.decode(long): not minimal encoding');
142
- }
143
- const v = data.subarray(pos, pos + length);
144
- if (v.length !== length)
145
- throw new E('tlv.decode: wrong value length');
146
- return { v, l: data.subarray(pos + length) };
147
- },
148
- },
149
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
150
- // since we always use positive integers here. It must always be empty:
151
- // - add zero byte if exists
152
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
153
- _int: {
154
- encode(num) {
155
- const { Err: E } = DER;
156
- if (num < _0n)
157
- throw new E('integer: negative integers are not allowed');
158
- let hex = numberToHexUnpadded(num);
159
- // Pad with zero byte if negative flag is present
160
- if (Number.parseInt(hex[0], 16) & 0b1000)
161
- hex = '00' + hex;
162
- if (hex.length & 1)
163
- throw new E('unexpected DER parsing assertion: unpadded hex');
164
- return hex;
165
- },
166
- decode(data) {
167
- const { Err: E } = DER;
168
- if (data[0] & 128)
169
- throw new E('invalid signature integer: negative');
170
- if (data[0] === 0x00 && !(data[1] & 128))
171
- throw new E('invalid signature integer: unnecessary leading zero');
172
- return bytesToNumberBE(data);
173
- },
174
- },
175
- toSig(hex) {
176
- // parse DER signature
177
- const { Err: E, _int: int, _tlv: tlv } = DER;
178
- const data = ensureBytes('signature', hex);
179
- const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
180
- if (seqLeftBytes.length)
181
- throw new E('invalid signature: left bytes after parsing');
182
- const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
183
- const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
184
- if (sLeftBytes.length)
185
- throw new E('invalid signature: left bytes after parsing');
186
- return { r: int.decode(rBytes), s: int.decode(sBytes) };
187
- },
188
- hexFromSig(sig) {
189
- const { _tlv: tlv, _int: int } = DER;
190
- const rs = tlv.encode(0x02, int.encode(sig.r));
191
- const ss = tlv.encode(0x02, int.encode(sig.s));
192
- const seq = rs + ss;
193
- return tlv.encode(0x30, seq);
194
- },
195
- };
196
- // Be friendly to bad ECMAScript parsers by not using bigint literals
197
- // prettier-ignore
198
- const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
199
- export function _normFnElement(Fn, key) {
200
- const { BYTES: expected } = Fn;
201
- let num;
202
- if (typeof key === 'bigint') {
203
- num = key;
204
- }
205
- else {
206
- let bytes = ensureBytes('private key', key);
207
- try {
208
- num = Fn.fromBytes(bytes);
209
- }
210
- catch (error) {
211
- throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
212
- }
213
- }
214
- if (!Fn.isValidNot0(num))
215
- throw new Error('invalid private key: out of range [1..N-1]');
216
- return num;
217
- }
218
- /**
219
- * Creates weierstrass Point constructor, based on specified curve options.
220
- *
221
- * @example
222
- ```js
223
- const opts = {
224
- p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
225
- n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
226
- h: BigInt(1),
227
- a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
228
- b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
229
- Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
230
- Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
231
- };
232
- const p256_Point = weierstrass(opts);
233
- ```
234
- */
235
- export function weierstrassN(params, extraOpts = {}) {
236
- const validated = _createCurveFields('weierstrass', params, extraOpts);
237
- const { Fp, Fn } = validated;
238
- let CURVE = validated.CURVE;
239
- const { h: cofactor, n: CURVE_ORDER } = CURVE;
240
- _validateObject(extraOpts, {}, {
241
- allowInfinityPoint: 'boolean',
242
- clearCofactor: 'function',
243
- isTorsionFree: 'function',
244
- fromBytes: 'function',
245
- toBytes: 'function',
246
- endo: 'object',
247
- wrapPrivateKey: 'boolean',
248
- });
249
- const { endo } = extraOpts;
250
- if (endo) {
251
- // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
252
- if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
253
- throw new Error('invalid endo: expected "beta": bigint and "basises": array');
254
- }
255
- }
256
- const lengths = getWLengths(Fp, Fn);
257
- function assertCompressionIsSupported() {
258
- if (!Fp.isOdd)
259
- throw new Error('compression is not supported: Field does not have .isOdd()');
260
- }
261
- // Implements IEEE P1363 point encoding
262
- function pointToBytes(_c, point, isCompressed) {
263
- const { x, y } = point.toAffine();
264
- const bx = Fp.toBytes(x);
265
- abool(isCompressed, 'isCompressed');
266
- if (isCompressed) {
267
- assertCompressionIsSupported();
268
- const hasEvenY = !Fp.isOdd(y);
269
- return concatBytes(pprefix(hasEvenY), bx);
270
- }
271
- else {
272
- return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
273
- }
274
- }
275
- function pointFromBytes(bytes) {
276
- abytes(bytes, undefined, 'Point');
277
- const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
278
- const length = bytes.length;
279
- const head = bytes[0];
280
- const tail = bytes.subarray(1);
281
- // No actual validation is done here: use .assertValidity()
282
- if (length === comp && (head === 0x02 || head === 0x03)) {
283
- const x = Fp.fromBytes(tail);
284
- if (!Fp.isValid(x))
285
- throw new Error('bad point: is not on curve, wrong x');
286
- const y2 = weierstrassEquation(x); // y² = x³ + ax + b
287
- let y;
288
- try {
289
- y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
290
- }
291
- catch (sqrtError) {
292
- const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
293
- throw new Error('bad point: is not on curve, sqrt error' + err);
294
- }
295
- assertCompressionIsSupported();
296
- const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
297
- const isHeadOdd = (head & 1) === 1; // ECDSA-specific
298
- if (isHeadOdd !== isYOdd)
299
- y = Fp.neg(y);
300
- return { x, y };
301
- }
302
- else if (length === uncomp && head === 0x04) {
303
- // TODO: more checks
304
- const L = Fp.BYTES;
305
- const x = Fp.fromBytes(tail.subarray(0, L));
306
- const y = Fp.fromBytes(tail.subarray(L, L * 2));
307
- if (!isValidXY(x, y))
308
- throw new Error('bad point: is not on curve');
309
- return { x, y };
310
- }
311
- else {
312
- throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
313
- }
314
- }
315
- const encodePoint = extraOpts.toBytes || pointToBytes;
316
- const decodePoint = extraOpts.fromBytes || pointFromBytes;
317
- function weierstrassEquation(x) {
318
- const x2 = Fp.sqr(x); // x * x
319
- const x3 = Fp.mul(x2, x); // x² * x
320
- return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
321
- }
322
- // TODO: move top-level
323
- /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
324
- function isValidXY(x, y) {
325
- const left = Fp.sqr(y); // y²
326
- const right = weierstrassEquation(x); // x³ + ax + b
327
- return Fp.eql(left, right);
328
- }
329
- // Validate whether the passed curve params are valid.
330
- // Test 1: equation y² = x³ + ax + b should work for generator point.
331
- if (!isValidXY(CURVE.Gx, CURVE.Gy))
332
- throw new Error('bad curve params: generator point');
333
- // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
334
- // Guarantees curve is genus-1, smooth (non-singular).
335
- const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
336
- const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
337
- if (Fp.is0(Fp.add(_4a3, _27b2)))
338
- throw new Error('bad curve params: a or b');
339
- /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
340
- function acoord(title, n, banZero = false) {
341
- if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
342
- throw new Error(`bad point coordinate ${title}`);
343
- return n;
344
- }
345
- function aprjpoint(other) {
346
- if (!(other instanceof Point))
347
- throw new Error('ProjectivePoint expected');
348
- }
349
- function splitEndoScalarN(k) {
350
- if (!endo || !endo.basises)
351
- throw new Error('no endo');
352
- return _splitEndoScalar(k, endo.basises, Fn.ORDER);
353
- }
354
- // Memoized toAffine / validity check. They are heavy. Points are immutable.
355
- // Converts Projective point to affine (x, y) coordinates.
356
- // Can accept precomputed Z^-1 - for example, from invertBatch.
357
- // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
358
- const toAffineMemo = memoized((p, iz) => {
359
- const { X, Y, Z } = p;
360
- // Fast-path for normalized points
361
- if (Fp.eql(Z, Fp.ONE))
362
- return { x: X, y: Y };
363
- const is0 = p.is0();
364
- // If invZ was 0, we return zero point. However we still want to execute
365
- // all operations, so we replace invZ with a random number, 1.
366
- if (iz == null)
367
- iz = is0 ? Fp.ONE : Fp.inv(Z);
368
- const x = Fp.mul(X, iz);
369
- const y = Fp.mul(Y, iz);
370
- const zz = Fp.mul(Z, iz);
371
- if (is0)
372
- return { x: Fp.ZERO, y: Fp.ZERO };
373
- if (!Fp.eql(zz, Fp.ONE))
374
- throw new Error('invZ was invalid');
375
- return { x, y };
376
- });
377
- // NOTE: on exception this will crash 'cached' and no value will be set.
378
- // Otherwise true will be return
379
- const assertValidMemo = memoized((p) => {
380
- if (p.is0()) {
381
- // (0, 1, 0) aka ZERO is invalid in most contexts.
382
- // In BLS, ZERO can be serialized, so we allow it.
383
- // (0, 0, 0) is invalid representation of ZERO.
384
- if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
385
- return;
386
- throw new Error('bad point: ZERO');
387
- }
388
- // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
389
- const { x, y } = p.toAffine();
390
- if (!Fp.isValid(x) || !Fp.isValid(y))
391
- throw new Error('bad point: x or y not field elements');
392
- if (!isValidXY(x, y))
393
- throw new Error('bad point: equation left != right');
394
- if (!p.isTorsionFree())
395
- throw new Error('bad point: not in prime-order subgroup');
396
- return true;
397
- });
398
- function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
399
- k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
400
- k1p = negateCt(k1neg, k1p);
401
- k2p = negateCt(k2neg, k2p);
402
- return k1p.add(k2p);
403
- }
404
- /**
405
- * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
406
- * Default Point works in 2d / affine coordinates: (x, y).
407
- * We're doing calculations in projective, because its operations don't require costly inversion.
408
- */
409
- class Point {
410
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
411
- constructor(X, Y, Z) {
412
- this.X = acoord('x', X);
413
- this.Y = acoord('y', Y, true);
414
- this.Z = acoord('z', Z);
415
- Object.freeze(this);
416
- }
417
- static CURVE() {
418
- return CURVE;
419
- }
420
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
421
- static fromAffine(p) {
422
- const { x, y } = p || {};
423
- if (!p || !Fp.isValid(x) || !Fp.isValid(y))
424
- throw new Error('invalid affine point');
425
- if (p instanceof Point)
426
- throw new Error('projective point not allowed');
427
- // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
428
- if (Fp.is0(x) && Fp.is0(y))
429
- return Point.ZERO;
430
- return new Point(x, y, Fp.ONE);
431
- }
432
- static fromBytes(bytes) {
433
- const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
434
- P.assertValidity();
435
- return P;
436
- }
437
- static fromHex(hex) {
438
- return Point.fromBytes(ensureBytes('pointHex', hex));
439
- }
440
- get x() {
441
- return this.toAffine().x;
442
- }
443
- get y() {
444
- return this.toAffine().y;
445
- }
446
- /**
447
- *
448
- * @param windowSize
449
- * @param isLazy true will defer table computation until the first multiplication
450
- * @returns
451
- */
452
- precompute(windowSize = 8, isLazy = true) {
453
- wnaf.createCache(this, windowSize);
454
- if (!isLazy)
455
- this.multiply(_3n); // random number
456
- return this;
457
- }
458
- // TODO: return `this`
459
- /** A point on curve is valid if it conforms to equation. */
460
- assertValidity() {
461
- assertValidMemo(this);
462
- }
463
- hasEvenY() {
464
- const { y } = this.toAffine();
465
- if (!Fp.isOdd)
466
- throw new Error("Field doesn't support isOdd");
467
- return !Fp.isOdd(y);
468
- }
469
- /** Compare one point to another. */
470
- equals(other) {
471
- aprjpoint(other);
472
- const { X: X1, Y: Y1, Z: Z1 } = this;
473
- const { X: X2, Y: Y2, Z: Z2 } = other;
474
- const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
475
- const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
476
- return U1 && U2;
477
- }
478
- /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
479
- negate() {
480
- return new Point(this.X, Fp.neg(this.Y), this.Z);
481
- }
482
- // Renes-Costello-Batina exception-free doubling formula.
483
- // There is 30% faster Jacobian formula, but it is not complete.
484
- // https://eprint.iacr.org/2015/1060, algorithm 3
485
- // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
486
- double() {
487
- const { a, b } = CURVE;
488
- const b3 = Fp.mul(b, _3n);
489
- const { X: X1, Y: Y1, Z: Z1 } = this;
490
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
491
- let t0 = Fp.mul(X1, X1); // step 1
492
- let t1 = Fp.mul(Y1, Y1);
493
- let t2 = Fp.mul(Z1, Z1);
494
- let t3 = Fp.mul(X1, Y1);
495
- t3 = Fp.add(t3, t3); // step 5
496
- Z3 = Fp.mul(X1, Z1);
497
- Z3 = Fp.add(Z3, Z3);
498
- X3 = Fp.mul(a, Z3);
499
- Y3 = Fp.mul(b3, t2);
500
- Y3 = Fp.add(X3, Y3); // step 10
501
- X3 = Fp.sub(t1, Y3);
502
- Y3 = Fp.add(t1, Y3);
503
- Y3 = Fp.mul(X3, Y3);
504
- X3 = Fp.mul(t3, X3);
505
- Z3 = Fp.mul(b3, Z3); // step 15
506
- t2 = Fp.mul(a, t2);
507
- t3 = Fp.sub(t0, t2);
508
- t3 = Fp.mul(a, t3);
509
- t3 = Fp.add(t3, Z3);
510
- Z3 = Fp.add(t0, t0); // step 20
511
- t0 = Fp.add(Z3, t0);
512
- t0 = Fp.add(t0, t2);
513
- t0 = Fp.mul(t0, t3);
514
- Y3 = Fp.add(Y3, t0);
515
- t2 = Fp.mul(Y1, Z1); // step 25
516
- t2 = Fp.add(t2, t2);
517
- t0 = Fp.mul(t2, t3);
518
- X3 = Fp.sub(X3, t0);
519
- Z3 = Fp.mul(t2, t1);
520
- Z3 = Fp.add(Z3, Z3); // step 30
521
- Z3 = Fp.add(Z3, Z3);
522
- return new Point(X3, Y3, Z3);
523
- }
524
- // Renes-Costello-Batina exception-free addition formula.
525
- // There is 30% faster Jacobian formula, but it is not complete.
526
- // https://eprint.iacr.org/2015/1060, algorithm 1
527
- // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
528
- add(other) {
529
- aprjpoint(other);
530
- const { X: X1, Y: Y1, Z: Z1 } = this;
531
- const { X: X2, Y: Y2, Z: Z2 } = other;
532
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
533
- const a = CURVE.a;
534
- const b3 = Fp.mul(CURVE.b, _3n);
535
- let t0 = Fp.mul(X1, X2); // step 1
536
- let t1 = Fp.mul(Y1, Y2);
537
- let t2 = Fp.mul(Z1, Z2);
538
- let t3 = Fp.add(X1, Y1);
539
- let t4 = Fp.add(X2, Y2); // step 5
540
- t3 = Fp.mul(t3, t4);
541
- t4 = Fp.add(t0, t1);
542
- t3 = Fp.sub(t3, t4);
543
- t4 = Fp.add(X1, Z1);
544
- let t5 = Fp.add(X2, Z2); // step 10
545
- t4 = Fp.mul(t4, t5);
546
- t5 = Fp.add(t0, t2);
547
- t4 = Fp.sub(t4, t5);
548
- t5 = Fp.add(Y1, Z1);
549
- X3 = Fp.add(Y2, Z2); // step 15
550
- t5 = Fp.mul(t5, X3);
551
- X3 = Fp.add(t1, t2);
552
- t5 = Fp.sub(t5, X3);
553
- Z3 = Fp.mul(a, t4);
554
- X3 = Fp.mul(b3, t2); // step 20
555
- Z3 = Fp.add(X3, Z3);
556
- X3 = Fp.sub(t1, Z3);
557
- Z3 = Fp.add(t1, Z3);
558
- Y3 = Fp.mul(X3, Z3);
559
- t1 = Fp.add(t0, t0); // step 25
560
- t1 = Fp.add(t1, t0);
561
- t2 = Fp.mul(a, t2);
562
- t4 = Fp.mul(b3, t4);
563
- t1 = Fp.add(t1, t2);
564
- t2 = Fp.sub(t0, t2); // step 30
565
- t2 = Fp.mul(a, t2);
566
- t4 = Fp.add(t4, t2);
567
- t0 = Fp.mul(t1, t4);
568
- Y3 = Fp.add(Y3, t0);
569
- t0 = Fp.mul(t5, t4); // step 35
570
- X3 = Fp.mul(t3, X3);
571
- X3 = Fp.sub(X3, t0);
572
- t0 = Fp.mul(t3, t1);
573
- Z3 = Fp.mul(t5, Z3);
574
- Z3 = Fp.add(Z3, t0); // step 40
575
- return new Point(X3, Y3, Z3);
576
- }
577
- subtract(other) {
578
- return this.add(other.negate());
579
- }
580
- is0() {
581
- return this.equals(Point.ZERO);
582
- }
583
- /**
584
- * Constant time multiplication.
585
- * Uses wNAF method. Windowed method may be 10% faster,
586
- * but takes 2x longer to generate and consumes 2x memory.
587
- * Uses precomputes when available.
588
- * Uses endomorphism for Koblitz curves.
589
- * @param scalar by which the point would be multiplied
590
- * @returns New point
591
- */
592
- multiply(scalar) {
593
- const { endo } = extraOpts;
594
- if (!Fn.isValidNot0(scalar))
595
- throw new Error('invalid scalar: out of range'); // 0 is invalid
596
- let point, fake; // Fake point is used to const-time mult
597
- const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
598
- /** See docs for {@link EndomorphismOpts} */
599
- if (endo) {
600
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
601
- const { p: k1p, f: k1f } = mul(k1);
602
- const { p: k2p, f: k2f } = mul(k2);
603
- fake = k1f.add(k2f);
604
- point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
605
- }
606
- else {
607
- const { p, f } = mul(scalar);
608
- point = p;
609
- fake = f;
610
- }
611
- // Normalize `z` for both points, but return only real one
612
- return normalizeZ(Point, [point, fake])[0];
613
- }
614
- /**
615
- * Non-constant-time multiplication. Uses double-and-add algorithm.
616
- * It's faster, but should only be used when you don't care about
617
- * an exposed secret key e.g. sig verification, which works over *public* keys.
618
- */
619
- multiplyUnsafe(sc) {
620
- const { endo } = extraOpts;
621
- const p = this;
622
- if (!Fn.isValid(sc))
623
- throw new Error('invalid scalar: out of range'); // 0 is valid
624
- if (sc === _0n || p.is0())
625
- return Point.ZERO;
626
- if (sc === _1n)
627
- return p; // fast-path
628
- if (wnaf.hasCache(this))
629
- return this.multiply(sc);
630
- if (endo) {
631
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
632
- const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
633
- return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
634
- }
635
- else {
636
- return wnaf.unsafe(p, sc);
637
- }
638
- }
639
- multiplyAndAddUnsafe(Q, a, b) {
640
- const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
641
- return sum.is0() ? undefined : sum;
642
- }
643
- /**
644
- * Converts Projective point to affine (x, y) coordinates.
645
- * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
646
- */
647
- toAffine(invertedZ) {
648
- return toAffineMemo(this, invertedZ);
649
- }
650
- /**
651
- * Checks whether Point is free of torsion elements (is in prime subgroup).
652
- * Always torsion-free for cofactor=1 curves.
653
- */
654
- isTorsionFree() {
655
- const { isTorsionFree } = extraOpts;
656
- if (cofactor === _1n)
657
- return true;
658
- if (isTorsionFree)
659
- return isTorsionFree(Point, this);
660
- return wnaf.unsafe(this, CURVE_ORDER).is0();
661
- }
662
- clearCofactor() {
663
- const { clearCofactor } = extraOpts;
664
- if (cofactor === _1n)
665
- return this; // Fast-path
666
- if (clearCofactor)
667
- return clearCofactor(Point, this);
668
- return this.multiplyUnsafe(cofactor);
669
- }
670
- isSmallOrder() {
671
- // can we use this.clearCofactor()?
672
- return this.multiplyUnsafe(cofactor).is0();
673
- }
674
- toBytes(isCompressed = true) {
675
- abool(isCompressed, 'isCompressed');
676
- this.assertValidity();
677
- return encodePoint(Point, this, isCompressed);
678
- }
679
- toHex(isCompressed = true) {
680
- return bytesToHex(this.toBytes(isCompressed));
681
- }
682
- toString() {
683
- return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
684
- }
685
- // TODO: remove
686
- get px() {
687
- return this.X;
688
- }
689
- get py() {
690
- return this.X;
691
- }
692
- get pz() {
693
- return this.Z;
694
- }
695
- toRawBytes(isCompressed = true) {
696
- return this.toBytes(isCompressed);
697
- }
698
- _setWindowSize(windowSize) {
699
- this.precompute(windowSize);
700
- }
701
- static normalizeZ(points) {
702
- return normalizeZ(Point, points);
703
- }
704
- static msm(points, scalars) {
705
- return pippenger(Point, Fn, points, scalars);
706
- }
707
- static fromPrivateKey(privateKey) {
708
- return Point.BASE.multiply(_normFnElement(Fn, privateKey));
709
- }
710
- }
711
- // base / generator point
712
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
713
- // zero / infinity / identity point
714
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
715
- // math field
716
- Point.Fp = Fp;
717
- // scalar field
718
- Point.Fn = Fn;
719
- const bits = Fn.BITS;
720
- const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
721
- Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
722
- return Point;
723
- }
724
- // Points start with byte 0x02 when y is even; otherwise 0x03
725
- function pprefix(hasEvenY) {
726
- return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
727
- }
728
- /**
729
- * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
730
- * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
731
- * b = True and y = sqrt(u / v) if (u / v) is square in F, and
732
- * b = False and y = sqrt(Z * (u / v)) otherwise.
733
- * @param Fp
734
- * @param Z
735
- * @returns
736
- */
737
- export function SWUFpSqrtRatio(Fp, Z) {
738
- // Generic implementation
739
- const q = Fp.ORDER;
740
- let l = _0n;
741
- for (let o = q - _1n; o % _2n === _0n; o /= _2n)
742
- l += _1n;
743
- const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
744
- // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
745
- // 2n ** c1 == 2n << (c1-1)
746
- const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
747
- const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
748
- const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
749
- const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
750
- const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
751
- const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic
752
- const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
753
- const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
754
- let sqrtRatio = (u, v) => {
755
- let tv1 = c6; // 1. tv1 = c6
756
- let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
757
- let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
758
- tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
759
- let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
760
- tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
761
- tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
762
- tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
763
- tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
764
- let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
765
- tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
766
- let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
767
- tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
768
- tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
769
- tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
770
- tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
771
- // 17. for i in (c1, c1 - 1, ..., 2):
772
- for (let i = c1; i > _1n; i--) {
773
- let tv5 = i - _2n; // 18. tv5 = i - 2
774
- tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5
775
- let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
776
- const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
777
- tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
778
- tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
779
- tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
780
- tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
781
- tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
782
- }
783
- return { isValid: isQR, value: tv3 };
784
- };
785
- if (Fp.ORDER % _4n === _3n) {
786
- // sqrt_ratio_3mod4(u, v)
787
- const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
788
- const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
789
- sqrtRatio = (u, v) => {
790
- let tv1 = Fp.sqr(v); // 1. tv1 = v^2
791
- const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
792
- tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
793
- let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
794
- y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
795
- const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
796
- const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
797
- const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
798
- let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
799
- return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
800
- };
801
- }
802
- // No curves uses that
803
- // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
804
- return sqrtRatio;
805
- }
806
- /**
807
- * Simplified Shallue-van de Woestijne-Ulas Method
808
- * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
809
- */
810
- export function mapToCurveSimpleSWU(Fp, opts) {
811
- validateField(Fp);
812
- const { A, B, Z } = opts;
813
- if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
814
- throw new Error('mapToCurveSimpleSWU: invalid opts');
815
- const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
816
- if (!Fp.isOdd)
817
- throw new Error('Field does not have .isOdd()');
818
- // Input: u, an element of F.
819
- // Output: (x, y), a point on E.
820
- return (u) => {
821
- // prettier-ignore
822
- let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
823
- tv1 = Fp.sqr(u); // 1. tv1 = u^2
824
- tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1
825
- tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
826
- tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
827
- tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
828
- tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3
829
- tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
830
- tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4
831
- tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
832
- tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
833
- tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
834
- tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
835
- tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
836
- tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
837
- tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
838
- tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
839
- x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
840
- const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
841
- y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
842
- y = Fp.mul(y, value); // 20. y = y * y1
843
- x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
844
- y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
845
- const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
846
- y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
847
- const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
848
- x = Fp.mul(x, tv4_inv); // 25. x = x / tv4
849
- return { x, y };
850
- };
851
- }
852
- function getWLengths(Fp, Fn) {
853
- return {
854
- secretKey: Fn.BYTES,
855
- publicKey: 1 + Fp.BYTES,
856
- publicKeyUncompressed: 1 + 2 * Fp.BYTES,
857
- publicKeyHasPrefix: true,
858
- signature: 2 * Fn.BYTES,
859
- };
860
- }
861
- /**
862
- * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
863
- * This helper ensures no signature functionality is present. Less code, smaller bundle size.
864
- */
865
- export function ecdh(Point, ecdhOpts = {}) {
866
- const { Fn } = Point;
867
- const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
868
- const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
869
- function isValidSecretKey(secretKey) {
870
- try {
871
- return !!_normFnElement(Fn, secretKey);
872
- }
873
- catch (error) {
874
- return false;
875
- }
876
- }
877
- function isValidPublicKey(publicKey, isCompressed) {
878
- const { publicKey: comp, publicKeyUncompressed } = lengths;
879
- try {
880
- const l = publicKey.length;
881
- if (isCompressed === true && l !== comp)
882
- return false;
883
- if (isCompressed === false && l !== publicKeyUncompressed)
884
- return false;
885
- return !!Point.fromBytes(publicKey);
886
- }
887
- catch (error) {
888
- return false;
889
- }
890
- }
891
- /**
892
- * Produces cryptographically secure secret key from random of size
893
- * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
894
- */
895
- function randomSecretKey(seed = randomBytes_(lengths.seed)) {
896
- return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
897
- }
898
- /**
899
- * Computes public key for a secret key. Checks for validity of the secret key.
900
- * @param isCompressed whether to return compact (default), or full key
901
- * @returns Public key, full when isCompressed=false; short when isCompressed=true
902
- */
903
- function getPublicKey(secretKey, isCompressed = true) {
904
- return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
905
- }
906
- function keygen(seed) {
907
- const secretKey = randomSecretKey(seed);
908
- return { secretKey, publicKey: getPublicKey(secretKey) };
909
- }
910
- /**
911
- * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
912
- */
913
- function isProbPub(item) {
914
- if (typeof item === 'bigint')
915
- return false;
916
- if (item instanceof Point)
917
- return true;
918
- const { secretKey, publicKey, publicKeyUncompressed } = lengths;
919
- if (Fn.allowedLengths || secretKey === publicKey)
920
- return undefined;
921
- const l = ensureBytes('key', item).length;
922
- return l === publicKey || l === publicKeyUncompressed;
923
- }
924
- /**
925
- * ECDH (Elliptic Curve Diffie Hellman).
926
- * Computes shared public key from secret key A and public key B.
927
- * Checks: 1) secret key validity 2) shared key is on-curve.
928
- * Does NOT hash the result.
929
- * @param isCompressed whether to return compact (default), or full key
930
- * @returns shared public key
931
- */
932
- function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
933
- if (isProbPub(secretKeyA) === true)
934
- throw new Error('first arg must be private key');
935
- if (isProbPub(publicKeyB) === false)
936
- throw new Error('second arg must be public key');
937
- const s = _normFnElement(Fn, secretKeyA);
938
- const b = Point.fromHex(publicKeyB); // checks for being on-curve
939
- return b.multiply(s).toBytes(isCompressed);
940
- }
941
- const utils = {
942
- isValidSecretKey,
943
- isValidPublicKey,
944
- randomSecretKey,
945
- // TODO: remove
946
- isValidPrivateKey: isValidSecretKey,
947
- randomPrivateKey: randomSecretKey,
948
- normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
949
- precompute(windowSize = 8, point = Point.BASE) {
950
- return point.precompute(windowSize, false);
951
- },
952
- };
953
- return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
954
- }
955
- /**
956
- * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
957
- * We need `hash` for 2 features:
958
- * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
959
- * 2. k generation in `sign`, using HMAC-drbg(hash)
960
- *
961
- * ECDSAOpts are only rarely needed.
962
- *
963
- * @example
964
- * ```js
965
- * const p256_Point = weierstrass(...);
966
- * const p256_sha256 = ecdsa(p256_Point, sha256);
967
- * const p256_sha224 = ecdsa(p256_Point, sha224);
968
- * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
969
- * ```
970
- */
971
- export function ecdsa(Point, hash, ecdsaOpts = {}) {
972
- ahash(hash);
973
- _validateObject(ecdsaOpts, {}, {
974
- hmac: 'function',
975
- lowS: 'boolean',
976
- randomBytes: 'function',
977
- bits2int: 'function',
978
- bits2int_modN: 'function',
979
- });
980
- const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
981
- const hmac = ecdsaOpts.hmac ||
982
- ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
983
- const { Fp, Fn } = Point;
984
- const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
985
- const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
986
- const defaultSigOpts = {
987
- prehash: false,
988
- lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
989
- format: undefined, //'compact' as ECDSASigFormat,
990
- extraEntropy: false,
991
- };
992
- const defaultSigOpts_format = 'compact';
993
- function isBiggerThanHalfOrder(number) {
994
- const HALF = CURVE_ORDER >> _1n;
995
- return number > HALF;
996
- }
997
- function validateRS(title, num) {
998
- if (!Fn.isValidNot0(num))
999
- throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
1000
- return num;
1001
- }
1002
- function validateSigLength(bytes, format) {
1003
- validateSigFormat(format);
1004
- const size = lengths.signature;
1005
- const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
1006
- return abytes(bytes, sizer, `${format} signature`);
1007
- }
1008
- /**
1009
- * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
1010
- */
1011
- class Signature {
1012
- constructor(r, s, recovery) {
1013
- this.r = validateRS('r', r); // r in [1..N-1];
1014
- this.s = validateRS('s', s); // s in [1..N-1];
1015
- if (recovery != null)
1016
- this.recovery = recovery;
1017
- Object.freeze(this);
1018
- }
1019
- static fromBytes(bytes, format = defaultSigOpts_format) {
1020
- validateSigLength(bytes, format);
1021
- let recid;
1022
- if (format === 'der') {
1023
- const { r, s } = DER.toSig(abytes(bytes));
1024
- return new Signature(r, s);
1025
- }
1026
- if (format === 'recovered') {
1027
- recid = bytes[0];
1028
- format = 'compact';
1029
- bytes = bytes.subarray(1);
1030
- }
1031
- const L = Fn.BYTES;
1032
- const r = bytes.subarray(0, L);
1033
- const s = bytes.subarray(L, L * 2);
1034
- return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
1035
- }
1036
- static fromHex(hex, format) {
1037
- return this.fromBytes(hexToBytes(hex), format);
1038
- }
1039
- addRecoveryBit(recovery) {
1040
- return new Signature(this.r, this.s, recovery);
1041
- }
1042
- recoverPublicKey(messageHash) {
1043
- const FIELD_ORDER = Fp.ORDER;
1044
- const { r, s, recovery: rec } = this;
1045
- if (rec == null || ![0, 1, 2, 3].includes(rec))
1046
- throw new Error('recovery id invalid');
1047
- // ECDSA recovery is hard for cofactor > 1 curves.
1048
- // In sign, `r = q.x mod n`, and here we recover q.x from r.
1049
- // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
1050
- // However, for cofactor>1, r+n may not get q.x:
1051
- // r+n*i would need to be done instead where i is unknown.
1052
- // To easily get i, we either need to:
1053
- // a. increase amount of valid recid values (4, 5...); OR
1054
- // b. prohibit non-prime-order signatures (recid > 1).
1055
- const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
1056
- if (hasCofactor && rec > 1)
1057
- throw new Error('recovery id is ambiguous for h>1 curve');
1058
- const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
1059
- if (!Fp.isValid(radj))
1060
- throw new Error('recovery id 2 or 3 invalid');
1061
- const x = Fp.toBytes(radj);
1062
- const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
1063
- const ir = Fn.inv(radj); // r^-1
1064
- const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
1065
- const u1 = Fn.create(-h * ir); // -hr^-1
1066
- const u2 = Fn.create(s * ir); // sr^-1
1067
- // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
1068
- const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
1069
- if (Q.is0())
1070
- throw new Error('point at infinify');
1071
- Q.assertValidity();
1072
- return Q;
1073
- }
1074
- // Signatures should be low-s, to prevent malleability.
1075
- hasHighS() {
1076
- return isBiggerThanHalfOrder(this.s);
1077
- }
1078
- toBytes(format = defaultSigOpts_format) {
1079
- validateSigFormat(format);
1080
- if (format === 'der')
1081
- return hexToBytes(DER.hexFromSig(this));
1082
- const r = Fn.toBytes(this.r);
1083
- const s = Fn.toBytes(this.s);
1084
- if (format === 'recovered') {
1085
- if (this.recovery == null)
1086
- throw new Error('recovery bit must be present');
1087
- return concatBytes(Uint8Array.of(this.recovery), r, s);
1088
- }
1089
- return concatBytes(r, s);
1090
- }
1091
- toHex(format) {
1092
- return bytesToHex(this.toBytes(format));
1093
- }
1094
- // TODO: remove
1095
- assertValidity() { }
1096
- static fromCompact(hex) {
1097
- return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
1098
- }
1099
- static fromDER(hex) {
1100
- return Signature.fromBytes(ensureBytes('sig', hex), 'der');
1101
- }
1102
- normalizeS() {
1103
- return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
1104
- }
1105
- toDERRawBytes() {
1106
- return this.toBytes('der');
1107
- }
1108
- toDERHex() {
1109
- return bytesToHex(this.toBytes('der'));
1110
- }
1111
- toCompactRawBytes() {
1112
- return this.toBytes('compact');
1113
- }
1114
- toCompactHex() {
1115
- return bytesToHex(this.toBytes('compact'));
1116
- }
1117
- }
1118
- // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
1119
- // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
1120
- // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
1121
- // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
1122
- const bits2int = ecdsaOpts.bits2int ||
1123
- function bits2int_def(bytes) {
1124
- // Our custom check "just in case", for protection against DoS
1125
- if (bytes.length > 8192)
1126
- throw new Error('input is too large');
1127
- // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
1128
- // for some cases, since bytes.length * 8 is not actual bitLength.
1129
- const num = bytesToNumberBE(bytes); // check for == u8 done here
1130
- const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
1131
- return delta > 0 ? num >> BigInt(delta) : num;
1132
- };
1133
- const bits2int_modN = ecdsaOpts.bits2int_modN ||
1134
- function bits2int_modN_def(bytes) {
1135
- return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
1136
- };
1137
- // Pads output with zero as per spec
1138
- const ORDER_MASK = bitMask(fnBits);
1139
- /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
1140
- function int2octets(num) {
1141
- // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
1142
- aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
1143
- return Fn.toBytes(num);
1144
- }
1145
- function validateMsgAndHash(message, prehash) {
1146
- abytes(message, undefined, 'message');
1147
- return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
1148
- }
1149
- /**
1150
- * Steps A, D of RFC6979 3.2.
1151
- * Creates RFC6979 seed; converts msg/privKey to numbers.
1152
- * Used only in sign, not in verify.
1153
- *
1154
- * Warning: we cannot assume here that message has same amount of bytes as curve order,
1155
- * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
1156
- */
1157
- function prepSig(message, privateKey, opts) {
1158
- if (['recovered', 'canonical'].some((k) => k in opts))
1159
- throw new Error('sign() legacy options not supported');
1160
- const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
1161
- message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
1162
- // We can't later call bits2octets, since nested bits2int is broken for curves
1163
- // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
1164
- // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
1165
- const h1int = bits2int_modN(message);
1166
- const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
1167
- const seedArgs = [int2octets(d), int2octets(h1int)];
1168
- // extraEntropy. RFC6979 3.6: additional k' (optional).
1169
- if (extraEntropy != null && extraEntropy !== false) {
1170
- // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
1171
- // gen random bytes OR pass as-is
1172
- const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
1173
- seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
1174
- }
1175
- const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
1176
- const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
1177
- // Converts signature params into point w r/s, checks result for validity.
1178
- // To transform k => Signature:
1179
- // q = k⋅G
1180
- // r = q.x mod n
1181
- // s = k^-1(m + rd) mod n
1182
- // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
1183
- // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
1184
- // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
1185
- function k2sig(kBytes) {
1186
- // RFC 6979 Section 3.2, step 3: k = bits2int(T)
1187
- // Important: all mod() calls here must be done over N
1188
- const k = bits2int(kBytes); // mod n, not mod p
1189
- if (!Fn.isValidNot0(k))
1190
- return; // Valid scalars (including k) must be in 1..N-1
1191
- const ik = Fn.inv(k); // k^-1 mod n
1192
- const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
1193
- const r = Fn.create(q.x); // r = q.x mod n
1194
- if (r === _0n)
1195
- return;
1196
- const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
1197
- if (s === _0n)
1198
- return;
1199
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
1200
- let normS = s;
1201
- if (lowS && isBiggerThanHalfOrder(s)) {
1202
- normS = Fn.neg(s); // if lowS was passed, ensure s is always
1203
- recovery ^= 1; // // in the bottom half of N
1204
- }
1205
- return new Signature(r, normS, recovery); // use normS, not s
1206
- }
1207
- return { seed, k2sig };
1208
- }
1209
- /**
1210
- * Signs message hash with a secret key.
1211
- *
1212
- * ```
1213
- * sign(m, d) where
1214
- * k = rfc6979_hmac_drbg(m, d)
1215
- * (x, y) = G × k
1216
- * r = x mod n
1217
- * s = (m + dr) / k mod n
1218
- * ```
1219
- */
1220
- function sign(message, secretKey, opts = {}) {
1221
- message = ensureBytes('message', message);
1222
- const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
1223
- const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
1224
- const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
1225
- return sig;
1226
- }
1227
- function tryParsingSig(sg) {
1228
- // Try to deduce format
1229
- let sig = undefined;
1230
- const isHex = typeof sg === 'string' || isBytes(sg);
1231
- const isObj = !isHex &&
1232
- sg !== null &&
1233
- typeof sg === 'object' &&
1234
- typeof sg.r === 'bigint' &&
1235
- typeof sg.s === 'bigint';
1236
- if (!isHex && !isObj)
1237
- throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
1238
- if (isObj) {
1239
- sig = new Signature(sg.r, sg.s);
1240
- }
1241
- else if (isHex) {
1242
- try {
1243
- sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
1244
- }
1245
- catch (derError) {
1246
- if (!(derError instanceof DER.Err))
1247
- throw derError;
1248
- }
1249
- if (!sig) {
1250
- try {
1251
- sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
1252
- }
1253
- catch (error) {
1254
- return false;
1255
- }
1256
- }
1257
- }
1258
- if (!sig)
1259
- return false;
1260
- return sig;
1261
- }
1262
- /**
1263
- * Verifies a signature against message and public key.
1264
- * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
1265
- * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
1266
- *
1267
- * ```
1268
- * verify(r, s, h, P) where
1269
- * u1 = hs^-1 mod n
1270
- * u2 = rs^-1 mod n
1271
- * R = u1⋅G + u2⋅P
1272
- * mod(R.x, n) == r
1273
- * ```
1274
- */
1275
- function verify(signature, message, publicKey, opts = {}) {
1276
- const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
1277
- publicKey = ensureBytes('publicKey', publicKey);
1278
- message = validateMsgAndHash(ensureBytes('message', message), prehash);
1279
- if ('strict' in opts)
1280
- throw new Error('options.strict was renamed to lowS');
1281
- const sig = format === undefined
1282
- ? tryParsingSig(signature)
1283
- : Signature.fromBytes(ensureBytes('sig', signature), format);
1284
- if (sig === false)
1285
- return false;
1286
- try {
1287
- const P = Point.fromBytes(publicKey);
1288
- if (lowS && sig.hasHighS())
1289
- return false;
1290
- const { r, s } = sig;
1291
- const h = bits2int_modN(message); // mod n, not mod p
1292
- const is = Fn.inv(s); // s^-1 mod n
1293
- const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
1294
- const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
1295
- const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
1296
- if (R.is0())
1297
- return false;
1298
- const v = Fn.create(R.x); // v = r.x mod n
1299
- return v === r;
1300
- }
1301
- catch (e) {
1302
- return false;
1303
- }
1304
- }
1305
- function recoverPublicKey(signature, message, opts = {}) {
1306
- const { prehash } = validateSigOpts(opts, defaultSigOpts);
1307
- message = validateMsgAndHash(message, prehash);
1308
- return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
1309
- }
1310
- return Object.freeze({
1311
- keygen,
1312
- getPublicKey,
1313
- getSharedSecret,
1314
- utils,
1315
- lengths,
1316
- Point,
1317
- sign,
1318
- verify,
1319
- recoverPublicKey,
1320
- Signature,
1321
- hash,
1322
- });
1323
- }
1324
- /** @deprecated use `weierstrass` in newer releases */
1325
- export function weierstrassPoints(c) {
1326
- const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
1327
- const Point = weierstrassN(CURVE, curveOpts);
1328
- return _weierstrass_new_output_to_legacy(c, Point);
1329
- }
1330
- function _weierstrass_legacy_opts_to_new(c) {
1331
- const CURVE = {
1332
- a: c.a,
1333
- b: c.b,
1334
- p: c.Fp.ORDER,
1335
- n: c.n,
1336
- h: c.h,
1337
- Gx: c.Gx,
1338
- Gy: c.Gy,
1339
- };
1340
- const Fp = c.Fp;
1341
- let allowedLengths = c.allowedPrivateKeyLengths
1342
- ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
1343
- : undefined;
1344
- const Fn = Field(CURVE.n, {
1345
- BITS: c.nBitLength,
1346
- allowedLengths: allowedLengths,
1347
- modFromBytes: c.wrapPrivateKey,
1348
- });
1349
- const curveOpts = {
1350
- Fp,
1351
- Fn,
1352
- allowInfinityPoint: c.allowInfinityPoint,
1353
- endo: c.endo,
1354
- isTorsionFree: c.isTorsionFree,
1355
- clearCofactor: c.clearCofactor,
1356
- fromBytes: c.fromBytes,
1357
- toBytes: c.toBytes,
1358
- };
1359
- return { CURVE, curveOpts };
1360
- }
1361
- function _ecdsa_legacy_opts_to_new(c) {
1362
- const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
1363
- const ecdsaOpts = {
1364
- hmac: c.hmac,
1365
- randomBytes: c.randomBytes,
1366
- lowS: c.lowS,
1367
- bits2int: c.bits2int,
1368
- bits2int_modN: c.bits2int_modN,
1369
- };
1370
- return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
1371
- }
1372
- export function _legacyHelperEquat(Fp, a, b) {
1373
- /**
1374
- * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
1375
- * @returns y²
1376
- */
1377
- function weierstrassEquation(x) {
1378
- const x2 = Fp.sqr(x); // x * x
1379
- const x3 = Fp.mul(x2, x); // x² * x
1380
- return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
1381
- }
1382
- return weierstrassEquation;
1383
- }
1384
- function _weierstrass_new_output_to_legacy(c, Point) {
1385
- const { Fp, Fn } = Point;
1386
- function isWithinCurveOrder(num) {
1387
- return inRange(num, _1n, Fn.ORDER);
1388
- }
1389
- const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
1390
- return Object.assign({}, {
1391
- CURVE: c,
1392
- Point: Point,
1393
- ProjectivePoint: Point,
1394
- normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
1395
- weierstrassEquation,
1396
- isWithinCurveOrder,
1397
- });
1398
- }
1399
- function _ecdsa_new_output_to_legacy(c, _ecdsa) {
1400
- const Point = _ecdsa.Point;
1401
- return Object.assign({}, _ecdsa, {
1402
- ProjectivePoint: Point,
1403
- CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
1404
- });
1405
- }
1406
- // _ecdsa_legacy
1407
- export function weierstrass(c) {
1408
- const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
1409
- const Point = weierstrassN(CURVE, curveOpts);
1410
- const signs = ecdsa(Point, hash, ecdsaOpts);
1411
- return _ecdsa_new_output_to_legacy(c, signs);
1412
- }
1413
- //# sourceMappingURL=weierstrass.js.map