P256.test.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { secp256r1 } = require('@noble/curves/p256');
  4. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  5. const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
  6. // As in ECDSA, signatures are malleable and the tooling produce both high and low S values.
  7. // We need to ensure that the s value is in the lower half of the order of the curve.
  8. const ensureLowerOrderS = ({ s, recovery, ...rest }) => {
  9. if (s > N / 2n) {
  10. s = N - s;
  11. recovery = 1 - recovery;
  12. }
  13. return { s, recovery, ...rest };
  14. };
  15. const prepareSignature = (
  16. privateKey = secp256r1.utils.randomPrivateKey(),
  17. messageHash = ethers.hexlify(ethers.randomBytes(0x20)),
  18. ) => {
  19. const publicKey = [
  20. secp256r1.getPublicKey(privateKey, false).slice(0x01, 0x21),
  21. secp256r1.getPublicKey(privateKey, false).slice(0x21, 0x41),
  22. ].map(ethers.hexlify);
  23. const { r, s, recovery } = ensureLowerOrderS(secp256r1.sign(messageHash.replace(/0x/, ''), privateKey));
  24. const signature = [r, s].map(v => ethers.toBeHex(v, 0x20));
  25. return { privateKey, publicKey, signature, recovery, messageHash };
  26. };
  27. describe('P256', function () {
  28. async function fixture() {
  29. return { mock: await ethers.deployContract('$P256') };
  30. }
  31. beforeEach(async function () {
  32. Object.assign(this, await loadFixture(fixture));
  33. });
  34. describe('with signature', function () {
  35. beforeEach(async function () {
  36. Object.assign(this, prepareSignature());
  37. });
  38. it('verify valid signature', async function () {
  39. expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true;
  40. expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true;
  41. await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey))
  42. .to.be.revertedWithCustomError(this.mock, 'MissingPrecompile')
  43. .withArgs('0x0000000000000000000000000000000000000100');
  44. });
  45. it('recover public key', async function () {
  46. expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.deep.equal(
  47. this.publicKey,
  48. );
  49. });
  50. it('reject signature with flipped public key coordinates ([x,y] >> [y,x])', async function () {
  51. // flip public key
  52. this.publicKey.reverse();
  53. expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  54. expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  55. expect(await this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; // Flipped public key is not in the curve
  56. });
  57. it('reject signature with flipped signature values ([r,s] >> [s,r])', async function () {
  58. // Preselected signature where `r < N/2` and `s < N/2`
  59. this.signature = [
  60. '0x45350225bad31e89db662fcc4fb2f79f349adbb952b3f652eed1f2aa72fb0356',
  61. '0x513eb68424c42630012309eee4a3b43e0bdc019d179ef0e0c461800845e237ee',
  62. ];
  63. // Corresponding hash and public key
  64. this.messageHash = '0x2ad1f900fe63745deeaedfdf396cb6f0f991c4338a9edf114d52f7d1812040a0';
  65. this.publicKey = [
  66. '0x9e30de165e521257996425d9bf12a7d366925614bf204eabbb78172b48e52e59',
  67. '0x94bf0fe72f99654d7beae4780a520848e306d46a1275b965c4f4c2b8e9a2c08d',
  68. ];
  69. // Make sure it works
  70. expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true;
  71. // Flip signature
  72. this.signature.reverse();
  73. expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  74. expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  75. await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey))
  76. .to.be.revertedWithCustomError(this.mock, 'MissingPrecompile')
  77. .withArgs('0x0000000000000000000000000000000000000100');
  78. expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal(
  79. this.publicKey,
  80. );
  81. });
  82. it('reject signature with invalid message hash', async function () {
  83. // random message hash
  84. this.messageHash = ethers.hexlify(ethers.randomBytes(32));
  85. expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  86. expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false;
  87. await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey))
  88. .to.be.revertedWithCustomError(this.mock, 'MissingPrecompile')
  89. .withArgs('0x0000000000000000000000000000000000000100');
  90. expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal(
  91. this.publicKey,
  92. );
  93. });
  94. it('fail to recover signature with invalid recovery bit', async function () {
  95. // flip recovery bit
  96. this.recovery = 1 - this.recovery;
  97. expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal(
  98. this.publicKey,
  99. );
  100. });
  101. });
  102. // test cases for https://github.com/C2SP/wycheproof/blob/4672ff74d68766e7785c2cac4c597effccef2c5c/testvectors/ecdsa_secp256r1_sha256_p1363_test.json
  103. describe('wycheproof tests', function () {
  104. for (const { key, tests } of require('./ecdsa_secp256r1_sha256_p1363_test.json').testGroups) {
  105. // parse public key
  106. let [x, y] = [key.wx, key.wy].map(v => ethers.stripZerosLeft('0x' + v, 32));
  107. if (x.length > 66 || y.length > 66) continue;
  108. x = ethers.zeroPadValue(x, 32);
  109. y = ethers.zeroPadValue(y, 32);
  110. // run all tests for this key
  111. for (const { tcId, comment, msg, sig, result } of tests) {
  112. // only keep properly formatted signatures
  113. if (sig.length != 128) continue;
  114. it(`${tcId}: ${comment}`, async function () {
  115. // split signature, and reduce modulo N
  116. let [r, s] = Array(2)
  117. .fill()
  118. .map((_, i) => ethers.toBigInt('0x' + sig.substring(64 * i, 64 * (i + 1))));
  119. // move s to lower part of the curve if needed
  120. if (s <= N && s > N / 2n) s = N - s;
  121. // prepare signature
  122. r = ethers.toBeHex(r, 32);
  123. s = ethers.toBeHex(s, 32);
  124. // hash
  125. const messageHash = ethers.sha256('0x' + msg);
  126. // check verify
  127. expect(await this.mock.$verify(messageHash, r, s, x, y)).to.equal(result == 'valid');
  128. });
  129. }
  130. }
  131. });
  132. });