Search code examples
nearprotocol

How to verify ed25519 signature in NEAR Smart contract?


As we know that near_sdk provides ecrecover method to verify ECDSA signature in near smart contract.

  • Is there any way to verify ed25519 signature in smart contract ?

  • I have used ed25519-dalek crate to verify signature but it is expensive and consumes large number of gas.

  • Is there any official method near provides to verify ed25519 signature because it also provides ecrecover method to verify ECDSA signature.


Solution

  • I've been using ed25519_dalek many times to verify a signature in Smart Contract, and to be honest I haven't noticed quite big Gas consumption (and from my understanding, it uses plain math calculations under the hood, meaning low Gas expense).

    For those who are looking for practical implementation, here it comes:

        pub fn verify(&mut self, signature: Vec<u8>) {
            let signature = ed25519_dalek::Signature::try_from(signature.as_ref())
                .expect("Signature should be a valid array of 64 bytes [13, 254, 123, ...]");
    
            // first byte contains CurveType, so we're removing it
            let public_key =
                ed25519_dalek::PublicKey::from_bytes(&self.pub_key.as_bytes()[1..]).unwrap();
    
            let verification_result = public_key.verify(&id.to_be_bytes(), &signature);
    
            assert_condition(verification_result.is_ok(), "Invalid signature");
    
            // further execution
        }
    
    

    Also, attaching a repository for the NEARCON hackathon project which includes signature verification implementation.

    Conclusion

    Don't worry about Gas consumption. The average consumption of 8-10TGas is not a significant expense. Keep using ed25519_dalek