Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [Pallet Pass] Configuration extensions #25

Merged
merged 10 commits into from
Oct 12, 2024
Merged
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ target/

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
.vscode
.vscode
.DS_Store
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pallet-transaction-payment = { git = "https://github.com/virto-network/polkadot-
pallet-utility = { git = "https://github.com/virto-network/polkadot-sdk", branch = "release-virto-v1.13.0", default-features = false }

[workspace]
resolver = "2"
members = [
"pallets/gas-transaction-payment",
"pallets/referenda-tracks",
Expand Down
101 changes: 101 additions & 0 deletions pallets/pass/src/extension.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use core::marker::PhantomData;

use codec::{Decode, Encode};
use frame_support::pallet_prelude::TransactionValidityError;
use scale_info::{StaticTypeInfo, TypeInfo};
use sp_runtime::traits::{DispatchInfoOf, SignedExtension};

use crate::{Config, Pallet};

#[derive(Encode, Decode)]
pub struct ChargeTransactionToPassAccount<S, T, I = ()>(S, PhantomData<(T, I)>);

impl<S: SignedExtension, T, I> ChargeTransactionToPassAccount<S, T, I> {
pub fn new(s: S) -> Self {
Self(s, PhantomData)
}
}

impl<S: Clone, T, I> Clone for ChargeTransactionToPassAccount<S, T, I> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}

impl<S: Eq, T, I> Eq for ChargeTransactionToPassAccount<S, T, I> {}
impl<S: PartialEq, T, I> PartialEq for ChargeTransactionToPassAccount<S, T, I> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}

impl<S: SignedExtension + StaticTypeInfo, T, I> TypeInfo
for ChargeTransactionToPassAccount<S, T, I>
{
type Identity = S;
fn type_info() -> scale_info::Type {
S::type_info()
}
}

impl<S: SignedExtension + Encode, T, I> core::fmt::Debug
for ChargeTransactionToPassAccount<S, T, I>
{
#[cfg(feature = "std")]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "ChargeTransactionToPassAccount<{:?}>", self.0.encode())
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
Ok(())
}
}

impl<S, T, I> SignedExtension for ChargeTransactionToPassAccount<S, T, I>
where
T: Config<I> + Send + Sync,
I: 'static + Send + Sync,
S: SignedExtension<AccountId = T::AccountId, Call = <T as frame_system::Config>::RuntimeCall>,
{
const IDENTIFIER: &'static str = S::IDENTIFIER;
type AccountId = S::AccountId;
type Call = S::Call;
type AdditionalSigned = S::AdditionalSigned;
type Pre = S::Pre;

fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
self.0.additional_signed()
}

fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
let who = Pallet::<T, I>::signer_from_session_key(who).unwrap_or(who.clone());
self.0.pre_dispatch(&who, call, info, len)
}

fn validate(
&self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> frame_support::pallet_prelude::TransactionValidity {
let who = Pallet::<T, I>::signer_from_session_key(who).unwrap_or(who.clone());
jgutierrezre marked this conversation as resolved.
Show resolved Hide resolved
self.0.validate(&who, call, info, len)
}

fn post_dispatch(
pre: Option<Self::Pre>,
info: &DispatchInfoOf<Self::Call>,
post_info: &sp_runtime::traits::PostDispatchInfoOf<Self::Call>,
len: usize,
result: &sp_runtime::DispatchResult,
) -> Result<(), frame_support::pallet_prelude::TransactionValidityError> {
S::post_dispatch(pre, info, post_info, len, result)
}
}
50 changes: 37 additions & 13 deletions pallets/pass/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@
mod mock;
#[cfg(test)]
mod tests;

mod extension;
mod types;

pub mod weights;
pub use extension::*;
pub use pallet::*;
pub use types::*;
pub use weights::*;
Expand Down Expand Up @@ -77,7 +80,7 @@
type BenchmarkHelper: BenchmarkHelper<Self, I>;
}

#[pallet::pallet]

Check warning on line 83 in pallets/pass/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

using `map_err` over `inspect_err`

warning: using `map_err` over `inspect_err` --> pallets/pass/src/lib.rs:83:15 | 83 | #[pallet::pallet] | ^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_inspect = note: `#[warn(clippy::manual_inspect)]` on by default help: try | 83 - #[pallet::pallet] 83 + #[pallet::&inspect_err] |
pub struct Pallet<T, I = ()>(_);

// Storage
Expand Down Expand Up @@ -149,6 +152,11 @@
Self::do_add_device(&account_id, attestation)
}

#[pallet::feeless_if(
jgutierrezre marked this conversation as resolved.
Show resolved Hide resolved
|_: &OriginFor<T>, device_id: &DeviceId, credential: &CredentialOf<T, I>, _: &Option<BlockNumberFor<T>>| -> bool {
Pallet::<T, I>::try_authenticate(device_id, credential).is_ok()
}
)]
#[pallet::call_index(3)]
pub fn authenticate(
origin: OriginFor<T>,
Expand All @@ -157,18 +165,7 @@
duration: Option<BlockNumberFor<T>>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let account_id = Self::account_id_for(credential.user_id())?;
ensure!(
Self::account_exists(&account_id),
Error::<T, I>::AccountNotFound
);

let device = Devices::<T, I>::get(&account_id, device_id)
.ok_or(Error::<T, I>::DeviceNotFound)?;
device
.verify_user(&credential)
.ok_or(Error::<T, I>::CredentialInvalid)?;

let account_id = Self::try_authenticate(&device_id, &credential)?;
Self::do_add_session(&who, &account_id, duration);
Ok(())
}
Expand Down Expand Up @@ -222,7 +219,7 @@
Ok(account_id)
}

pub(crate) fn account_exists(who: &T::AccountId) -> bool {
pub fn account_exists(who: &T::AccountId) -> bool {
frame_system::Pallet::<T>::account_exists(who)
}

Expand All @@ -247,6 +244,24 @@
Ok(())
}

pub(crate) fn try_authenticate(
device_id: &DeviceId,
credential: &CredentialOf<T, I>,
) -> Result<T::AccountId, DispatchError> {
let account_id = Self::account_id_for(credential.user_id())?;
ensure!(
Self::account_exists(&account_id),
Error::<T, I>::AccountNotFound
);
let device =
Devices::<T, I>::get(&account_id, device_id).ok_or(Error::<T, I>::DeviceNotFound)?;
device
.verify_user(credential)
.ok_or(Error::<T, I>::CredentialInvalid)?;

Ok(account_id)
}

pub(crate) fn do_add_device(
who: &T::AccountId,
attestation: DeviceAttestationOf<T, I>,
Expand Down Expand Up @@ -279,6 +294,15 @@
Ok(account_id)
}

pub(crate) fn signer_from_session_key(who: &T::AccountId) -> Option<T::AccountId> {
let (account_id, until) = Sessions::<T, I>::get(who)?;
if frame_system::Pallet::<T>::block_number() <= until {
Some(account_id)
} else {
None
}
}

pub(crate) fn do_authenticate(
credential: CredentialOf<T, I>,
device_id: DeviceId,
Expand Down
Loading