SignerP256.sol 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {AbstractSigner} from "./AbstractSigner.sol";
  4. import {P256} from "../P256.sol";
  5. /**
  6. * @dev Implementation of {AbstractSigner} using xref:api:utils/cryptography#P256[P256] signatures.
  7. *
  8. * For {Account} usage, a {_setSigner} function is provided to set the {signer} public key.
  9. * Doing so is easier for a factory, who is likely to use initializable clones of this contract.
  10. *
  11. * Example of usage:
  12. *
  13. * ```solidity
  14. * contract MyAccountP256 is Account, SignerP256, Initializable {
  15. * function initialize(bytes32 qx, bytes32 qy) public initializer {
  16. * _setSigner(qx, qy);
  17. * }
  18. * }
  19. * ```
  20. *
  21. * IMPORTANT: Failing to call {_setSigner} either during construction (if used standalone)
  22. * or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
  23. */
  24. abstract contract SignerP256 is AbstractSigner {
  25. bytes32 private _qx;
  26. bytes32 private _qy;
  27. error SignerP256InvalidPublicKey(bytes32 qx, bytes32 qy);
  28. constructor(bytes32 qx, bytes32 qy) {
  29. _setSigner(qx, qy);
  30. }
  31. /**
  32. * @dev Sets the signer with a P256 public key. This function should be called during construction
  33. * or through an initializer.
  34. */
  35. function _setSigner(bytes32 qx, bytes32 qy) internal {
  36. if (!P256.isValidPublicKey(qx, qy)) revert SignerP256InvalidPublicKey(qx, qy);
  37. _qx = qx;
  38. _qy = qy;
  39. }
  40. /// @dev Return the signer's P256 public key.
  41. function signer() public view virtual returns (bytes32 qx, bytes32 qy) {
  42. return (_qx, _qy);
  43. }
  44. /// @inheritdoc AbstractSigner
  45. function _rawSignatureValidation(
  46. bytes32 hash,
  47. bytes calldata signature
  48. ) internal view virtual override returns (bool) {
  49. if (signature.length < 0x40) return false;
  50. bytes32 r = bytes32(signature[0x00:0x20]);
  51. bytes32 s = bytes32(signature[0x20:0x40]);
  52. (bytes32 qx, bytes32 qy) = signer();
  53. return P256.verify(hash, r, s, qx, qy);
  54. }
  55. }