检查签名对于给定的签名者和数据哈希是否有效

2024-07-29 13:10:39

github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/659f3063f82422cef820de746444e6f6cba6ca7c/contracts/utils/cryptography/SignatureChecker.sol

/**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        if (signer.code.length == 0) {
            (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
            return err == ECDSA.RecoverError.NoError && recovered == signer;
        } else {
            return isValidERC1271SignatureNow(signer, hash, signature);
        }
    }

测试例子

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

contract TestSignatureChecker {
    function verify(address _signer, bytes32 messageHash,  bytes memory _signature) external view returns(bool) {
        return SignatureChecker.isValidSignatureNow(_signer, messageHash, _signature);
    }
}
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »