JoshOrndorff / recipes

A Hands-On Cookbook for Aspiring Blockchain Chefs
GNU General Public License v3.0
379 stars 187 forks source link

Recipe for explicitly verifying signatures in the runtime #142

Open JoshOrndorff opened 4 years ago

JoshOrndorff commented 4 years ago

Quoting @riusricardo from Substrate Technical Chat Feb 6 2020:

An alterantive way to validate a signature is:

Import the codec and traits:

use codec::{Decode, Encode};
use sp_runtime::traits::{IdentifyAccount, Member, Verify};

Add new types to the trait:

pub trait Trait: system::Trait {
    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
    type Public: IdentifyAccount<AccountId = Self::AccountId> + Clone;
    type Signature: Verify<Signer = Self::Public> + Member + Decode + Encode;
}

Example function to verify the signature.

pub fn check_signature(
    signature: &T::Signature,
    msg: &[u8],
    signer: &T::AccountId,
) -> DispatchResult {
    if signature.verify(msg, signer) {
        Ok(())
    } else {
        Err(Error::<T>::MyError.into())
    }
}

This should verify Ed25519,Sr25519, and Ecdsa signatures.

riusricardo commented 4 years ago

Nice! I've been planning to add this recipe for some time ;)