SignerP256.sol 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. /**
  29. * @dev Sets the signer with a P256 public key. This function should be called during construction
  30. * or through an initializer.
  31. */
  32. function _setSigner(bytes32 qx, bytes32 qy) internal {
  33. if (!P256.isValidPublicKey(qx, qy)) revert SignerP256InvalidPublicKey(qx, qy);
  34. _qx = qx;
  35. _qy = qy;
  36. }
  37. /// @dev Return the signer's P256 public key.
  38. function signer() public view virtual returns (bytes32 qx, bytes32 qy) {
  39. return (_qx, _qy);
  40. }
  41. /// @inheritdoc AbstractSigner
  42. function _rawSignatureValidation(
  43. bytes32 hash,
  44. bytes calldata signature
  45. ) internal view virtual override returns (bool) {
  46. if (signature.length < 0x40) return false;
  47. bytes32 r = bytes32(signature[0x00:0x20]);
  48. bytes32 s = bytes32(signature[0x20:0x40]);
  49. (bytes32 qx, bytes32 qy) = signer();
  50. return P256.verify(hash, r, s, qx, qy);
  51. }
  52. }