P256.sol 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/P256.sol)
  3. pragma solidity ^0.8.20;
  4. import {Math} from "../math/Math.sol";
  5. import {Errors} from "../Errors.sol";
  6. /**
  7. * @dev Implementation of secp256r1 verification and recovery functions.
  8. *
  9. * The secp256r1 curve (also known as P256) is a NIST standard curve with wide support in modern devices
  10. * and cryptographic standards. Some notable examples include Apple's Secure Enclave and Android's Keystore
  11. * as well as authentication protocols like FIDO2.
  12. *
  13. * Based on the original https://github.com/itsobvioustech/aa-passkeys-wallet/blob/d3d423f28a4d8dfcb203c7fa0c47f42592a7378e/src/Secp256r1.sol[implementation of itsobvioustech] (GNU General Public License v3.0).
  14. * Heavily inspired in https://github.com/maxrobot/elliptic-solidity/blob/c4bb1b6e8ae89534d8db3a6b3a6b52219100520f/contracts/Secp256r1.sol[maxrobot] and
  15. * https://github.com/tdrerup/elliptic-curve-solidity/blob/59a9c25957d4d190eff53b6610731d81a077a15e/contracts/curves/EllipticCurve.sol[tdrerup] implementations.
  16. *
  17. * _Available since v5.1._
  18. */
  19. library P256 {
  20. struct JPoint {
  21. uint256 x;
  22. uint256 y;
  23. uint256 z;
  24. }
  25. /// @dev Generator (x component)
  26. uint256 internal constant GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296;
  27. /// @dev Generator (y component)
  28. uint256 internal constant GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5;
  29. /// @dev P (size of the field)
  30. uint256 internal constant P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF;
  31. /// @dev N (order of G)
  32. uint256 internal constant N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551;
  33. /// @dev A parameter of the weierstrass equation
  34. uint256 internal constant A = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC;
  35. /// @dev B parameter of the weierstrass equation
  36. uint256 internal constant B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B;
  37. /// @dev (P + 1) / 4. Useful to compute sqrt
  38. uint256 private constant P1DIV4 = 0x3fffffffc0000000400000000000000000000000400000000000000000000000;
  39. /// @dev N/2 for excluding higher order `s` values
  40. uint256 private constant HALF_N = 0x7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8;
  41. /**
  42. * @dev Verifies a secp256r1 signature using the RIP-7212 precompile and falls back to the Solidity implementation
  43. * if the precompile is not available. This version should work on all chains, but requires the deployment of more
  44. * bytecode.
  45. *
  46. * @param h - hashed message
  47. * @param r - signature half R
  48. * @param s - signature half S
  49. * @param qx - public key coordinate X
  50. * @param qy - public key coordinate Y
  51. *
  52. * IMPORTANT: This function disallows signatures where the `s` value is above `N/2` to prevent malleability.
  53. * To flip the `s` value, compute `s = N - s`.
  54. */
  55. function verify(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) {
  56. (bool valid, bool supported) = _tryVerifyNative(h, r, s, qx, qy);
  57. return supported ? valid : verifySolidity(h, r, s, qx, qy);
  58. }
  59. /**
  60. * @dev Same as {verify}, but it will revert if the required precompile is not available.
  61. *
  62. * Make sure any logic (code or precompile) deployed at that address is the expected one,
  63. * otherwise the returned value may be misinterpreted as a positive boolean.
  64. */
  65. function verifyNative(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) {
  66. (bool valid, bool supported) = _tryVerifyNative(h, r, s, qx, qy);
  67. if (supported) {
  68. return valid;
  69. } else {
  70. revert Errors.MissingPrecompile(address(0x100));
  71. }
  72. }
  73. /**
  74. * @dev Same as {verify}, but it will return false if the required precompile is not available.
  75. */
  76. function _tryVerifyNative(
  77. bytes32 h,
  78. bytes32 r,
  79. bytes32 s,
  80. bytes32 qx,
  81. bytes32 qy
  82. ) private view returns (bool valid, bool supported) {
  83. if (!_isProperSignature(r, s) || !isValidPublicKey(qx, qy)) {
  84. return (false, true); // signature is invalid, and its not because the precompile is missing
  85. } else if (_rip7212(h, r, s, qx, qy)) {
  86. return (true, true); // precompile is present, signature is valid
  87. } else if (
  88. // Given precompiles have no bytecode (i.e. `address(0x100).code.length == 0`), we use
  89. // a valid signature with small `r` and `s` values to check if the precompile is present. Taken from
  90. // https://github.com/C2SP/wycheproof/blob/4672ff74d68766e7785c2cac4c597effccef2c5c/testvectors/ecdsa_secp256r1_sha256_p1363_test.json#L1173-L1204
  91. _rip7212(
  92. 0xbb5a52f42f9c9261ed4361f59422a1e30036e7c32b270c8807a419feca605023, // sha256("123400")
  93. 0x0000000000000000000000000000000000000000000000000000000000000005,
  94. 0x0000000000000000000000000000000000000000000000000000000000000001,
  95. 0xa71af64de5126a4a4e02b7922d66ce9415ce88a4c9d25514d91082c8725ac957,
  96. 0x5d47723c8fbe580bb369fec9c2665d8e30a435b9932645482e7c9f11e872296b
  97. )
  98. ) {
  99. return (false, true); // precompile is present, signature is invalid
  100. } else {
  101. return (false, false); // precompile is absent
  102. }
  103. }
  104. /**
  105. * @dev Low level helper for {_tryVerifyNative}. Calls the precompile and checks if there is a return value.
  106. */
  107. function _rip7212(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) private view returns (bool isValid) {
  108. assembly ("memory-safe") {
  109. // Use the free memory pointer without updating it at the end of the function
  110. let ptr := mload(0x40)
  111. mstore(ptr, h)
  112. mstore(add(ptr, 0x20), r)
  113. mstore(add(ptr, 0x40), s)
  114. mstore(add(ptr, 0x60), qx)
  115. mstore(add(ptr, 0x80), qy)
  116. // RIP-7212 precompiles return empty bytes when an invalid signature is passed, making it impossible
  117. // to distinguish the presence of the precompile. Custom precompile implementations may decide to
  118. // return `bytes32(0)` (i.e. false) without developers noticing, so we decide to evaluate the return value
  119. // without expanding memory using scratch space.
  120. mstore(0x00, 0) // zero out scratch space in case the precompile doesn't return anything
  121. if iszero(staticcall(gas(), 0x100, ptr, 0xa0, 0x00, 0x20)) {
  122. invalid()
  123. }
  124. isValid := mload(0x00)
  125. }
  126. }
  127. /**
  128. * @dev Same as {verify}, but only the Solidity implementation is used.
  129. */
  130. function verifySolidity(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) {
  131. if (!_isProperSignature(r, s) || !isValidPublicKey(qx, qy)) {
  132. return false;
  133. }
  134. JPoint[16] memory points = _preComputeJacobianPoints(uint256(qx), uint256(qy));
  135. uint256 w = Math.invModPrime(uint256(s), N);
  136. uint256 u1 = mulmod(uint256(h), w, N);
  137. uint256 u2 = mulmod(uint256(r), w, N);
  138. (uint256 x, ) = _jMultShamir(points, u1, u2);
  139. return ((x % N) == uint256(r));
  140. }
  141. /**
  142. * @dev Public key recovery
  143. *
  144. * @param h - hashed message
  145. * @param v - signature recovery param
  146. * @param r - signature half R
  147. * @param s - signature half S
  148. *
  149. * IMPORTANT: This function disallows signatures where the `s` value is above `N/2` to prevent malleability.
  150. * To flip the `s` value, compute `s = N - s` and `v = 1 - v` if (`v = 0 | 1`).
  151. */
  152. function recovery(bytes32 h, uint8 v, bytes32 r, bytes32 s) internal view returns (bytes32 x, bytes32 y) {
  153. if (!_isProperSignature(r, s) || v > 1) {
  154. return (0, 0);
  155. }
  156. uint256 p = P; // cache P on the stack
  157. uint256 rx = uint256(r);
  158. uint256 ry2 = addmod(mulmod(addmod(mulmod(rx, rx, p), A, p), rx, p), B, p); // weierstrass equation y² = x³ + a.x + b
  159. uint256 ry = Math.modExp(ry2, P1DIV4, p); // This formula for sqrt work because P ≡ 3 (mod 4)
  160. if (mulmod(ry, ry, p) != ry2) return (0, 0); // Sanity check
  161. if (ry % 2 != v) ry = p - ry;
  162. JPoint[16] memory points = _preComputeJacobianPoints(rx, ry);
  163. uint256 w = Math.invModPrime(uint256(r), N);
  164. uint256 u1 = mulmod(N - (uint256(h) % N), w, N);
  165. uint256 u2 = mulmod(uint256(s), w, N);
  166. (uint256 xU, uint256 yU) = _jMultShamir(points, u1, u2);
  167. return (bytes32(xU), bytes32(yU));
  168. }
  169. /**
  170. * @dev Checks if (x, y) are valid coordinates of a point on the curve.
  171. * In particular this function checks that x < P and y < P.
  172. */
  173. function isValidPublicKey(bytes32 x, bytes32 y) internal pure returns (bool result) {
  174. assembly ("memory-safe") {
  175. let p := P
  176. let lhs := mulmod(y, y, p) // y^2
  177. let rhs := addmod(mulmod(addmod(mulmod(x, x, p), A, p), x, p), B, p) // ((x^2 + a) * x) + b = x^3 + ax + b
  178. result := and(and(lt(x, p), lt(y, p)), eq(lhs, rhs)) // Should conform with the Weierstrass equation
  179. }
  180. }
  181. /**
  182. * @dev Checks if (r, s) is a proper signature.
  183. * In particular, this checks that `s` is in the "lower-range", making the signature non-malleable.
  184. */
  185. function _isProperSignature(bytes32 r, bytes32 s) private pure returns (bool) {
  186. return uint256(r) > 0 && uint256(r) < N && uint256(s) > 0 && uint256(s) <= HALF_N;
  187. }
  188. /**
  189. * @dev Reduce from jacobian to affine coordinates
  190. * @param jx - jacobian coordinate x
  191. * @param jy - jacobian coordinate y
  192. * @param jz - jacobian coordinate z
  193. * @return ax - affine coordinate x
  194. * @return ay - affine coordinate y
  195. */
  196. function _affineFromJacobian(uint256 jx, uint256 jy, uint256 jz) private view returns (uint256 ax, uint256 ay) {
  197. if (jz == 0) return (0, 0);
  198. uint256 p = P; // cache P on the stack
  199. uint256 zinv = Math.invModPrime(jz, p);
  200. assembly ("memory-safe") {
  201. let zzinv := mulmod(zinv, zinv, p)
  202. ax := mulmod(jx, zzinv, p)
  203. ay := mulmod(jy, mulmod(zzinv, zinv, p), p)
  204. }
  205. }
  206. /**
  207. * @dev Point addition on the jacobian coordinates
  208. * Reference: https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-1998-cmo-2
  209. *
  210. * Note that:
  211. *
  212. * - `addition-add-1998-cmo-2` doesn't support identical input points. This version is modified to use
  213. * the `h` and `r` values computed by `addition-add-1998-cmo-2` to detect identical inputs, and fallback to
  214. * `doubling-dbl-1998-cmo-2` if needed.
  215. * - if one of the points is at infinity (i.e. `z=0`), the result is undefined.
  216. */
  217. function _jAdd(
  218. JPoint memory p1,
  219. uint256 x2,
  220. uint256 y2,
  221. uint256 z2
  222. ) private pure returns (uint256 rx, uint256 ry, uint256 rz) {
  223. assembly ("memory-safe") {
  224. let p := P
  225. let z1 := mload(add(p1, 0x40))
  226. let zz1 := mulmod(z1, z1, p) // zz1 = z1²
  227. let s1 := mulmod(mload(add(p1, 0x20)), mulmod(mulmod(z2, z2, p), z2, p), p) // s1 = y1*z2³
  228. let r := addmod(mulmod(y2, mulmod(zz1, z1, p), p), sub(p, s1), p) // r = s2-s1 = y2*z1³-s1 = y2*z1³-y1*z2³
  229. let u1 := mulmod(mload(p1), mulmod(z2, z2, p), p) // u1 = x1*z2²
  230. let h := addmod(mulmod(x2, zz1, p), sub(p, u1), p) // h = u2-u1 = x2*z1²-u1 = x2*z1²-x1*z2²
  231. // detect edge cases where inputs are identical
  232. switch and(iszero(r), iszero(h))
  233. // case 0: points are different
  234. case 0 {
  235. let hh := mulmod(h, h, p) // h²
  236. // x' = r²-h³-2*u1*h²
  237. rx := addmod(
  238. addmod(mulmod(r, r, p), sub(p, mulmod(h, hh, p)), p),
  239. sub(p, mulmod(2, mulmod(u1, hh, p), p)),
  240. p
  241. )
  242. // y' = r*(u1*h²-x')-s1*h³
  243. ry := addmod(
  244. mulmod(r, addmod(mulmod(u1, hh, p), sub(p, rx), p), p),
  245. sub(p, mulmod(s1, mulmod(h, hh, p), p)),
  246. p
  247. )
  248. // z' = h*z1*z2
  249. rz := mulmod(h, mulmod(z1, z2, p), p)
  250. }
  251. // case 1: points are equal
  252. case 1 {
  253. let x := x2
  254. let y := y2
  255. let z := z2
  256. let yy := mulmod(y, y, p)
  257. let zz := mulmod(z, z, p)
  258. let m := addmod(mulmod(3, mulmod(x, x, p), p), mulmod(A, mulmod(zz, zz, p), p), p) // m = 3*x²+a*z⁴
  259. let s := mulmod(4, mulmod(x, yy, p), p) // s = 4*x*y²
  260. // x' = t = m²-2*s
  261. rx := addmod(mulmod(m, m, p), sub(p, mulmod(2, s, p)), p)
  262. // y' = m*(s-t)-8*y⁴ = m*(s-x')-8*y⁴
  263. // cut the computation to avoid stack too deep
  264. let rytmp1 := sub(p, mulmod(8, mulmod(yy, yy, p), p)) // -8*y⁴
  265. let rytmp2 := addmod(s, sub(p, rx), p) // s-x'
  266. ry := addmod(mulmod(m, rytmp2, p), rytmp1, p) // m*(s-x')-8*y⁴
  267. // z' = 2*y*z
  268. rz := mulmod(2, mulmod(y, z, p), p)
  269. }
  270. }
  271. }
  272. /**
  273. * @dev Point doubling on the jacobian coordinates
  274. * Reference: https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2
  275. */
  276. function _jDouble(uint256 x, uint256 y, uint256 z) private pure returns (uint256 rx, uint256 ry, uint256 rz) {
  277. assembly ("memory-safe") {
  278. let p := P
  279. let yy := mulmod(y, y, p)
  280. let zz := mulmod(z, z, p)
  281. let m := addmod(mulmod(3, mulmod(x, x, p), p), mulmod(A, mulmod(zz, zz, p), p), p) // m = 3*x²+a*z⁴
  282. let s := mulmod(4, mulmod(x, yy, p), p) // s = 4*x*y²
  283. // x' = t = m²-2*s
  284. rx := addmod(mulmod(m, m, p), sub(p, mulmod(2, s, p)), p)
  285. // y' = m*(s-t)-8*y⁴ = m*(s-x')-8*y⁴
  286. ry := addmod(mulmod(m, addmod(s, sub(p, rx), p), p), sub(p, mulmod(8, mulmod(yy, yy, p), p)), p)
  287. // z' = 2*y*z
  288. rz := mulmod(2, mulmod(y, z, p), p)
  289. }
  290. }
  291. /**
  292. * @dev Compute G·u1 + P·u2 using the precomputed points for G and P (see {_preComputeJacobianPoints}).
  293. *
  294. * Uses Strauss Shamir trick for EC multiplication
  295. * https://stackoverflow.com/questions/50993471/ec-scalar-multiplication-with-strauss-shamir-method
  296. *
  297. * We optimize this for 2 bits at a time rather than a single bit. The individual points for a single pass are
  298. * precomputed. Overall this reduces the number of additions while keeping the same number of
  299. * doublings
  300. */
  301. function _jMultShamir(
  302. JPoint[16] memory points,
  303. uint256 u1,
  304. uint256 u2
  305. ) private view returns (uint256 rx, uint256 ry) {
  306. uint256 x = 0;
  307. uint256 y = 0;
  308. uint256 z = 0;
  309. unchecked {
  310. for (uint256 i = 0; i < 128; ++i) {
  311. if (z > 0) {
  312. (x, y, z) = _jDouble(x, y, z);
  313. (x, y, z) = _jDouble(x, y, z);
  314. }
  315. // Read 2 bits of u1, and 2 bits of u2. Combining the two gives the lookup index in the table.
  316. uint256 pos = ((u1 >> 252) & 0xc) | ((u2 >> 254) & 0x3);
  317. // Points that have z = 0 are points at infinity. They are the additive 0 of the group
  318. // - if the lookup point is a 0, we can skip it
  319. // - otherwise:
  320. // - if the current point (x, y, z) is 0, we use the lookup point as our new value (0+P=P)
  321. // - if the current point (x, y, z) is not 0, both points are valid and we can use `_jAdd`
  322. if (points[pos].z != 0) {
  323. if (z == 0) {
  324. (x, y, z) = (points[pos].x, points[pos].y, points[pos].z);
  325. } else {
  326. (x, y, z) = _jAdd(points[pos], x, y, z);
  327. }
  328. }
  329. u1 <<= 2;
  330. u2 <<= 2;
  331. }
  332. }
  333. return _affineFromJacobian(x, y, z);
  334. }
  335. /**
  336. * @dev Precompute a matrice of useful jacobian points associated with a given P. This can be seen as a 4x4 matrix
  337. * that contains combination of P and G (generator) up to 3 times each. See the table below:
  338. *
  339. * ┌────┬─────────────────────┐
  340. * │ i │ 0 1 2 3 │
  341. * ├────┼─────────────────────┤
  342. * │ 0 │ 0 p 2p 3p │
  343. * │ 4 │ g g+p g+2p g+3p │
  344. * │ 8 │ 2g 2g+p 2g+2p 2g+3p │
  345. * │ 12 │ 3g 3g+p 3g+2p 3g+3p │
  346. * └────┴─────────────────────┘
  347. *
  348. * Note that `_jAdd` (and thus `_jAddPoint`) does not handle the case where one of the inputs is a point at
  349. * infinity (z = 0). However, we know that since `N ≡ 1 mod 2` and `N ≡ 1 mod 3`, there is no point P such that
  350. * 2P = 0 or 3P = 0. This guarantees that g, 2g, 3g, p, 2p, 3p are all non-zero, and that all `_jAddPoint` calls
  351. * have valid inputs.
  352. */
  353. function _preComputeJacobianPoints(uint256 px, uint256 py) private pure returns (JPoint[16] memory points) {
  354. points[0x00] = JPoint(0, 0, 0); // 0,0
  355. points[0x01] = JPoint(px, py, 1); // 1,0 (p)
  356. points[0x04] = JPoint(GX, GY, 1); // 0,1 (g)
  357. points[0x02] = _jDoublePoint(points[0x01]); // 2,0 (2p)
  358. points[0x08] = _jDoublePoint(points[0x04]); // 0,2 (2g)
  359. points[0x03] = _jAddPoint(points[0x01], points[0x02]); // 3,0 (p+2p = 3p)
  360. points[0x05] = _jAddPoint(points[0x01], points[0x04]); // 1,1 (p+g)
  361. points[0x06] = _jAddPoint(points[0x02], points[0x04]); // 2,1 (2p+g)
  362. points[0x07] = _jAddPoint(points[0x03], points[0x04]); // 3,1 (3p+g)
  363. points[0x09] = _jAddPoint(points[0x01], points[0x08]); // 1,2 (p+2g)
  364. points[0x0a] = _jAddPoint(points[0x02], points[0x08]); // 2,2 (2p+2g)
  365. points[0x0b] = _jAddPoint(points[0x03], points[0x08]); // 3,2 (3p+2g)
  366. points[0x0c] = _jAddPoint(points[0x04], points[0x08]); // 0,3 (g+2g = 3g)
  367. points[0x0d] = _jAddPoint(points[0x01], points[0x0c]); // 1,3 (p+3g)
  368. points[0x0e] = _jAddPoint(points[0x02], points[0x0c]); // 2,3 (2p+3g)
  369. points[0x0f] = _jAddPoint(points[0x03], points[0x0c]); // 3,3 (3p+3g)
  370. }
  371. function _jAddPoint(JPoint memory p1, JPoint memory p2) private pure returns (JPoint memory) {
  372. (uint256 x, uint256 y, uint256 z) = _jAdd(p1, p2.x, p2.y, p2.z);
  373. return JPoint(x, y, z);
  374. }
  375. function _jDoublePoint(JPoint memory p) private pure returns (JPoint memory) {
  376. (uint256 x, uint256 y, uint256 z) = _jDouble(p.x, p.y, p.z);
  377. return JPoint(x, y, z);
  378. }
  379. }