rustfmt the ghost-claims pallet

Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
This commit is contained in:
Uncle Stinky 2025-06-25 18:17:14 +03:00
parent 116ca39dc4
commit 40a8152f69
Signed by: st1nky
GPG Key ID: 016064BD97603B40
6 changed files with 302 additions and 208 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.3" version = "0.2.4"
description = "Ghost balance and rank claims based on EVM actions" description = "Ghost balance and rank claims based on EVM actions"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View File

@ -6,14 +6,14 @@ use frame_benchmarking::v2::*;
#[instance_benchmarks] #[instance_benchmarks]
mod benchmarks { mod benchmarks {
use super::*; use super::*;
use pallet_ranked_collective::Pallet as Club;
use frame_support::dispatch::RawOrigin; use frame_support::dispatch::RawOrigin;
use pallet_ranked_collective::Pallet as Club;
#[benchmark] #[benchmark]
fn claim() { fn claim() {
let i = 1337u32; let i = 1337u32;
let ethereum_secret_key = libsecp256k1::SecretKey::parse( let ethereum_secret_key =
&keccak_256(&i.to_le_bytes())).unwrap(); libsecp256k1::SecretKey::parse(&keccak_256(&i.to_le_bytes())).unwrap();
let eth_address = crate::secp_utils::eth(&ethereum_secret_key); let eth_address = crate::secp_utils::eth(&ethereum_secret_key);
let balance = CurrencyOf::<T, I>::minimum_balance(); let balance = CurrencyOf::<T, I>::minimum_balance();
@ -22,23 +22,30 @@ mod benchmarks {
Total::<T, I>::put(balance); Total::<T, I>::put(balance);
let pseudo_rank = 5u16; let pseudo_rank = 5u16;
let _ = Club::<T, I>::do_add_member_to_rank( let _ = Club::<T, I>::do_add_member_to_rank(pseudo_account.clone(), pseudo_rank, false);
pseudo_account.clone(),
pseudo_rank,
false,
);
let user_account: T::AccountId = account("user", i, 0); let user_account: T::AccountId = account("user", i, 0);
let signature = crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode()); let signature =
crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode());
let prev_balance = CurrencyOf::<T, I>::free_balance(&user_account); let prev_balance = CurrencyOf::<T, I>::free_balance(&user_account);
let prev_rank = Club::<T, I>::rank_of(&user_account); let prev_rank = Club::<T, I>::rank_of(&user_account);
#[extrinsic_call] #[extrinsic_call]
claim(RawOrigin::Signed(user_account.clone()), eth_address, signature); claim(
RawOrigin::Signed(user_account.clone()),
eth_address,
signature,
);
assert_eq!(CurrencyOf::<T, I>::free_balance(&user_account), prev_balance + balance); assert_eq!(
assert_eq!(CurrencyOf::<T, I>::free_balance(&pseudo_account), balance - balance); CurrencyOf::<T, I>::free_balance(&user_account),
prev_balance + balance
);
assert_eq!(
CurrencyOf::<T, I>::free_balance(&pseudo_account),
balance - balance
);
let rank = match prev_rank { let rank = match prev_rank {
Some(current_rank) if pseudo_rank <= current_rank => Some(current_rank), Some(current_rank) if pseudo_rank <= current_rank => Some(current_rank),
@ -48,9 +55,5 @@ mod benchmarks {
assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None); assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None);
} }
impl_benchmark_test_suite!( impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test,);
Pallet,
crate::mock::new_test_ext(),
crate::mock::Test,
);
} }

View File

@ -1,19 +1,20 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{ use frame_support::{
ensure, pallet_prelude::*, ensure,
pallet_prelude::*,
traits::{ traits::{
Currency, ExistenceRequirement, Get, RankedMembers, Currency, ExistenceRequirement, Get, RankedMembers, RankedMembersSwapHandler,
RankedMembersSwapHandler, VestingSchedule, VestingSchedule,
}, },
DefaultNoBound, DefaultNoBound,
}; };
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
pub use pallet::*; pub use pallet::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256}; use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
use sp_runtime::traits::{CheckedSub, CheckedDiv, BlockNumberProvider}; use sp_runtime::traits::{BlockNumberProvider, CheckedDiv, CheckedSub};
use sp_std::prelude::*; use sp_std::prelude::*;
extern crate alloc; extern crate alloc;
@ -23,10 +24,10 @@ use alloc::{format, string::String};
mod weights; mod weights;
pub use crate::weights::WeightInfo; pub use crate::weights::WeightInfo;
mod tests;
mod mock;
mod benchmarking; mod benchmarking;
mod mock;
mod secp_utils; mod secp_utils;
mod tests;
/// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account). /// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account).
/// ///
@ -56,7 +57,7 @@ impl<'de> Deserialize<'de> for EthereumAddress {
Err(serde::de::Error::custom( Err(serde::de::Error::custom(
"Bad length of Ethereum address (should be 42 including `0x`)", "Bad length of Ethereum address (should be 42 including `0x`)",
))?; ))?;
} }
let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s) let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s)
.map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?; .map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?;
let mut r = Self::default(); let mut r = Self::default();
@ -81,15 +82,14 @@ impl sp_std::fmt::Debug for EcdsaSignature {
} }
type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule< type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId <T as frame_system::Config>::AccountId,
>>::Currency; >>::Currency;
type BalanceOf<T, I> = <CurrencyOf<T, I> as Currency< type BalanceOf<T, I> =
<T as frame_system::Config>::AccountId> <CurrencyOf<T, I> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
>::Balance;
type RankOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::Rank; type RankOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::Rank;
type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::AccountId; type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::AccountId;
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet { pub mod pallet {
@ -100,8 +100,11 @@ pub mod pallet {
pub struct Pallet<T, I = ()>(_); pub struct Pallet<T, I = ()>(_);
#[pallet::config] #[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config + pallet_ranked_collective::Config<I> { pub trait Config<I: 'static = ()>:
type RuntimeEvent: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; frame_system::Config + pallet_ranked_collective::Config<I>
{
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>; type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>; type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
@ -118,13 +121,13 @@ pub mod pallet {
type WeightInfo: WeightInfo; type WeightInfo: WeightInfo;
} }
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> { pub enum Event<T: Config<I>, I: 'static = ()> {
Claimed { Claimed {
receiver: T::AccountId, receiver: T::AccountId,
donor: T::AccountId, donor: T::AccountId,
amount: BalanceOf<T, I>, amount: BalanceOf<T, I>,
rank: Option<RankOf<T, I>>, rank: Option<RankOf<T, I>>,
}, },
@ -159,12 +162,16 @@ pub mod pallet {
.map(|(account_id, rank)| { .map(|(account_id, rank)| {
assert!( assert!(
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank( pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(
account_id.clone(), *rank, false).is_ok(), account_id.clone(),
"error during adding and promotion" *rank,
false
)
.is_ok(),
"error during adding and promotion"
); );
account_id account_id
}) })
.collect(); .collect();
assert!( assert!(
self.members_and_ranks.len() == cult_accounts.len(), self.members_and_ranks.len() == cult_accounts.len(),
@ -186,13 +193,13 @@ pub mod pallet {
) -> DispatchResult { ) -> DispatchResult {
let who = ensure_signed(origin)?; let who = ensure_signed(origin)?;
let data = who.using_encoded(to_ascii_hex); let data = who.using_encoded(to_ascii_hex);
let recovered_address = Self::recover_ethereum_address( let recovered_address = Self::recover_ethereum_address(&ethereum_signature, &data)
&ethereum_signature, .ok_or(Error::<T, I>::InvalidEthereumSignature)?;
&data,
).ok_or(Error::<T, I>::InvalidEthereumSignature)?;
ensure!(recovered_address == ethereum_address, ensure!(
Error::<T, I>::InvalidEthereumAddress); recovered_address == ethereum_address,
Error::<T, I>::InvalidEthereumAddress
);
Self::do_claim(who, ethereum_address) Self::do_claim(who, ethereum_address)
} }
@ -200,37 +207,37 @@ pub mod pallet {
} }
fn to_ascii_hex(data: &[u8]) -> Vec<u8> { fn to_ascii_hex(data: &[u8]) -> Vec<u8> {
let mut r = Vec::with_capacity(data.len() * 2); let mut r = Vec::with_capacity(data.len() * 2);
let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n }); let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n });
for &b in data.iter() { for &b in data.iter() {
push_nibble(b / 16); push_nibble(b / 16);
push_nibble(b % 16); push_nibble(b % 16);
} }
r r
} }
impl<T: Config<I>, I: 'static> Pallet<T, I> { impl<T: Config<I>, I: 'static> Pallet<T, I> {
fn ethereum_signable_message(what: &[u8]) -> Vec<u8> { fn ethereum_signable_message(what: &[u8]) -> Vec<u8> {
let prefix = T::Prefix::get(); let prefix = T::Prefix::get();
let mut l = prefix.len() + what.len(); let mut l = prefix.len() + what.len();
let mut rev = Vec::new(); let mut rev = Vec::new();
while l > 0 { while l > 0 {
rev.push(b'0' + (l % 10) as u8); rev.push(b'0' + (l % 10) as u8);
l /= 10; l /= 10;
} }
let mut v = b"\x19Ethereum Signed Message:\n".to_vec(); let mut v = b"\x19Ethereum Signed Message:\n".to_vec();
v.extend(rev.into_iter().rev()); v.extend(rev.into_iter().rev());
v.extend_from_slice(prefix); v.extend_from_slice(prefix);
v.extend_from_slice(what); v.extend_from_slice(what);
v v
} }
fn recover_ethereum_address(s: &EcdsaSignature, what: &[u8]) -> Option<EthereumAddress> { fn recover_ethereum_address(s: &EcdsaSignature, what: &[u8]) -> Option<EthereumAddress> {
let msg = keccak_256(&Self::ethereum_signable_message(what)); let msg = keccak_256(&Self::ethereum_signable_message(what));
let mut res = EthereumAddress::default(); let mut res = EthereumAddress::default();
res.0 res.0
.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]); .copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
Some(res) Some(res)
} }
fn into_account_id(address: EthereumAddress) -> Result<T::AccountId, codec::Error> { fn into_account_id(address: EthereumAddress) -> Result<T::AccountId, codec::Error> {
@ -243,21 +250,24 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
} }
fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult { fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult {
let donor = Self::into_account_id(ethereum_address).ok() let donor = Self::into_account_id(ethereum_address)
.ok()
.ok_or(Error::<T, I>::AddressDecodingFailed)?; .ok_or(Error::<T, I>::AddressDecodingFailed)?;
let balance_due = CurrencyOf::<T, I>::free_balance(&donor); let balance_due = CurrencyOf::<T, I>::free_balance(&donor);
ensure!(balance_due >= CurrencyOf::<T, I>::minimum_balance(), ensure!(
Error::<T, I>::NoBalanceToClaim); balance_due >= CurrencyOf::<T, I>::minimum_balance(),
Error::<T, I>::NoBalanceToClaim
);
let new_total = Total::<T, I>::get() let new_total = Total::<T, I>::get()
.checked_sub(&balance_due) .checked_sub(&balance_due)
.ok_or(Error::<T, I>::PotUnderflow)?; .ok_or(Error::<T, I>::PotUnderflow)?;
CurrencyOf::<T, I>::transfer( CurrencyOf::<T, I>::transfer(
&donor, &donor,
&receiver, &receiver,
balance_due, balance_due,
ExistenceRequirement::AllowDeath, ExistenceRequirement::AllowDeath,
)?; )?;
@ -273,28 +283,40 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
.ok_or(Error::<T, I>::ArithmeticError)?; .ok_or(Error::<T, I>::ArithmeticError)?;
T::VestingSchedule::add_vesting_schedule( T::VestingSchedule::add_vesting_schedule(
&receiver, &receiver,
vesting_balance, vesting_balance,
per_block_balance, per_block_balance,
T::BlockNumberProvider::current_block_number(), T::BlockNumberProvider::current_block_number(),
)?; )?;
} }
let rank = if let Some(rank) = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&donor) { let rank = if let Some(rank) =
<pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&donor)
{
pallet_ranked_collective::Pallet::<T, I>::do_remove_member_from_rank(&donor, rank)?; pallet_ranked_collective::Pallet::<T, I>::do_remove_member_from_rank(&donor, rank)?;
let new_rank = match <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&receiver) { let new_rank =
Some(current_rank) if current_rank >= rank => current_rank, match <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&receiver)
Some(current_rank) if current_rank < rank => { {
for _ in 0..rank - current_rank { Some(current_rank) if current_rank >= rank => current_rank,
pallet_ranked_collective::Pallet::<T, I>::do_promote_member(receiver.clone(), None, false)?; Some(current_rank) if current_rank < rank => {
for _ in 0..rank - current_rank {
pallet_ranked_collective::Pallet::<T, I>::do_promote_member(
receiver.clone(),
None,
false,
)?;
}
rank
} }
rank _ => {
}, pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(
_ => { receiver.clone(),
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(receiver.clone(), rank, false)?; rank,
rank false,
}, )?;
}; rank
}
};
<T as pallet::Config<I>>::MemberSwappedHandler::swapped(&donor, &receiver, new_rank); <T as pallet::Config<I>>::MemberSwappedHandler::swapped(&donor, &receiver, new_rank);
Some(new_rank) Some(new_rank)
} else { } else {
@ -303,7 +325,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
Total::<T, I>::put(new_total); Total::<T, I>::put(new_total);
Self::deposit_event(Event::<T, I>::Claimed { Self::deposit_event(Event::<T, I>::Claimed {
receiver, receiver,
donor, donor,
amount: balance_due, amount: balance_due,
rank, rank,

View File

@ -4,51 +4,113 @@ use super::*;
pub use crate as ghost_claims; pub use crate as ghost_claims;
use frame_support::{ use frame_support::{
parameter_types, derive_impl, derive_impl, parameter_types,
traits::{PollStatus, Polling, WithdrawReasons, ConstU16, ConstU64}, traits::{ConstU16, ConstU64, PollStatus, Polling, WithdrawReasons},
}; };
use frame_system::EnsureRootWithSuccess; use frame_system::EnsureRootWithSuccess;
use sp_runtime::{BuildStorage, traits::Convert}; pub use pallet_ranked_collective::{Rank, TallyOf};
pub use pallet_ranked_collective::{TallyOf, Rank}; use sp_runtime::{traits::Convert, BuildStorage};
pub mod eth_keys { pub mod eth_keys {
use crate::{ use crate::{mock::Test, EcdsaSignature, EthereumAddress};
mock::Test,
EcdsaSignature, EthereumAddress,
};
use hex_literal::hex;
use codec::Encode; use codec::Encode;
use hex_literal::hex;
pub fn total_claims() -> u64 { 10 + 100 + 1000 } pub fn total_claims() -> u64 {
pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId { 69 } 10 + 100 + 1000
pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId { 1337 } }
pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId {
69
}
pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId {
1337
}
pub fn first_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760")) } pub fn first_eth_public_known() -> EthereumAddress {
pub fn second_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12")) } EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760"))
pub fn third_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D")) } }
pub fn fourth_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63")) } pub fn second_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"))
}
pub fn third_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"))
}
pub fn fourth_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63"))
}
fn first_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198")).unwrap() } fn first_eth_private_key() -> libsecp256k1::SecretKey {
fn second_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139")).unwrap() } libsecp256k1::SecretKey::parse(&hex!(
fn third_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc")).unwrap() } "01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198"
fn fourth_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4")).unwrap() } ))
fn wrong_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")).unwrap() } .unwrap()
}
fn second_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139"
))
.unwrap()
}
fn third_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc"
))
.unwrap()
}
fn fourth_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4"
))
.unwrap()
}
fn wrong_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
))
.unwrap()
}
pub fn first_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&first_eth_private_key()) } pub fn first_eth_public_key() -> EthereumAddress {
pub fn second_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&second_eth_private_key()) } crate::secp_utils::eth(&first_eth_private_key())
pub fn third_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&third_eth_private_key()) } }
pub fn fourth_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&fourth_eth_private_key()) } pub fn second_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&second_eth_private_key())
}
pub fn third_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&third_eth_private_key())
}
pub fn fourth_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&fourth_eth_private_key())
}
pub fn first_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key()) } pub fn first_account_id() -> <Test as frame_system::Config>::AccountId {
pub fn second_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key()) } crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key())
pub fn third_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key()) } }
pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key()) } pub fn second_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key())
}
pub fn third_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key())
}
pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key())
}
pub fn first_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode()) } pub fn first_signature() -> EcdsaSignature {
pub fn second_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode()) } crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode())
pub fn third_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode()) } }
pub fn fourth_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode()) } pub fn second_signature() -> EcdsaSignature {
pub fn wrong_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode()) } crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode())
}
pub fn third_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode())
}
pub fn fourth_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode())
}
pub fn wrong_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode())
}
} }
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] #[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
@ -66,10 +128,9 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
} }
parameter_types! { parameter_types! {
pub const MinVestedTransfer: u64 = 1; pub const MinVestedTransfer: u64 = 1;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
} }
@ -79,9 +140,8 @@ impl pallet_vesting::Config for Test {
type BlockNumberToBalance = sp_runtime::traits::ConvertInto; type BlockNumberToBalance = sp_runtime::traits::ConvertInto;
type MinVestedTransfer = MinVestedTransfer; type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = (); type WeightInfo = ();
type UnvestedFundsAllowedWithdrawReasons = type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System; type BlockNumberProvider = System;
const MAX_VESTING_SCHEDULES: u32 = 28; const MAX_VESTING_SCHEDULES: u32 = 28;
} }
@ -148,7 +208,7 @@ impl pallet_ranked_collective::Config for Test {
type PromoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>; type PromoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type DemoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>; type DemoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type ExchangeOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>; type ExchangeOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type Polls = TestPolls; type Polls = TestPolls;
type MemberSwappedHandler = (); type MemberSwappedHandler = ();
type MinRankOfClass = MinRankOfClass<MinRankOfClassDelta>; type MinRankOfClass = MinRankOfClass<MinRankOfClassDelta>;
@ -200,8 +260,8 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(crate::mock::eth_keys::third_account_id(), 1000), (crate::mock::eth_keys::third_account_id(), 1000),
], ],
} }
.assimilate_storage(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
ghost_claims::GenesisConfig::<Test> { ghost_claims::GenesisConfig::<Test> {
total: crate::mock::eth_keys::total_claims(), total: crate::mock::eth_keys::total_claims(),
@ -210,8 +270,8 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(crate::mock::eth_keys::third_account_id(), 3), (crate::mock::eth_keys::third_account_id(), 3),
], ],
} }
.assimilate_storage(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
let mut ext = sp_io::TestExternalities::new(t); let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| { ext.execute_with(|| {

View File

@ -8,7 +8,8 @@ pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress { pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress {
let mut res = EthereumAddress::default(); let mut res = EthereumAddress::default();
res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]); res.0
.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
res res
} }
@ -18,17 +19,14 @@ pub fn into_account_id<T: Config<I>, I: 'static>(address: EthereumAddress) -> T:
} }
pub fn sig<T: Config<I>, I: 'static>( pub fn sig<T: Config<I>, I: 'static>(
secret: &libsecp256k1::SecretKey, secret: &libsecp256k1::SecretKey,
what: &[u8], what: &[u8],
) -> EcdsaSignature { ) -> EcdsaSignature {
let msg = keccak_256(&super::Pallet::<T, I>::ethereum_signable_message( let msg = keccak_256(&super::Pallet::<T, I>::ethereum_signable_message(
&crate::to_ascii_hex(what)[..], &crate::to_ascii_hex(what)[..],
)); ));
let (sig, recovery_id) = libsecp256k1::sign( let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);
&libsecp256k1::Message::parse(&msg),
secret,
);
let mut r = [0u8; 65]; let mut r = [0u8; 65];
r[0..64].copy_from_slice(&sig.serialize()[..]); r[0..64].copy_from_slice(&sig.serialize()[..]);

View File

@ -1,21 +1,19 @@
#![cfg(test)] #![cfg(test)]
use mock::{
new_test_ext, ghost_claims,
Test, System, Balances, Club, Vesting, Claims, RuntimeOrigin, RuntimeEvent,
eth_keys::{
alice_account_id, total_claims, first_eth_public_known,
first_eth_public_key, first_account_id, first_signature,
second_eth_public_known, second_eth_public_key, second_account_id,
second_signature, third_eth_public_known, third_eth_public_key,
third_account_id, third_signature, fourth_eth_public_known,
fourth_eth_public_key, fourth_account_id, fourth_signature,
wrong_signature, bob_account_id,
}
};
use hex_literal::hex;
use frame_support::{assert_err, assert_ok};
use super::*; use super::*;
use frame_support::{assert_err, assert_ok};
use hex_literal::hex;
use mock::{
eth_keys::{
alice_account_id, bob_account_id, first_account_id, first_eth_public_key,
first_eth_public_known, first_signature, fourth_account_id, fourth_eth_public_key,
fourth_eth_public_known, fourth_signature, second_account_id, second_eth_public_key,
second_eth_public_known, second_signature, third_account_id, third_eth_public_key,
third_eth_public_known, third_signature, total_claims, wrong_signature,
},
ghost_claims, new_test_ext, Balances, Claims, Club, RuntimeEvent, RuntimeOrigin, System, Test,
Vesting,
};
#[test] #[test]
fn serde_works() { fn serde_works() {
@ -41,12 +39,12 @@ fn basic_setup_works() {
assert_eq!(Balances::usable_balance(&first_account_id()), 10); assert_eq!(Balances::usable_balance(&first_account_id()), 10);
assert_eq!(Balances::usable_balance(&second_account_id()), 100); assert_eq!(Balances::usable_balance(&second_account_id()), 100);
assert_eq!(Balances::usable_balance(&third_account_id()), 1000); assert_eq!(Balances::usable_balance(&third_account_id()), 1000);
assert_eq!(Club::rank_of(&alice_account_id()), None); assert_eq!(Club::rank_of(&alice_account_id()), None);
assert_eq!(Club::rank_of(&first_account_id()), None); assert_eq!(Club::rank_of(&first_account_id()), None);
assert_eq!(Club::rank_of(&second_account_id()), Some(1)); assert_eq!(Club::rank_of(&second_account_id()), Some(1));
assert_eq!(Club::rank_of(&third_account_id()), Some(3)); assert_eq!(Club::rank_of(&third_account_id()), Some(3));
assert_eq!(Vesting::vesting_balance(&alice_account_id()), None); assert_eq!(Vesting::vesting_balance(&alice_account_id()), None);
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims()); assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims());
}); });
@ -56,9 +54,10 @@ fn basic_setup_works() {
fn small_claiming_works() { fn small_claiming_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature())); first_signature()
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 10); assert_eq!(Balances::usable_balance(&alice_account_id()), 10);
assert_eq!(Balances::usable_balance(&first_account_id()), 0); assert_eq!(Balances::usable_balance(&first_account_id()), 0);
@ -77,9 +76,9 @@ fn small_claiming_works() {
fn medium_claiming_works() { fn medium_claiming_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(), second_eth_public_key(),
second_signature(), second_signature(),
)); ));
assert_eq!(Balances::usable_balance(&alice_account_id()), 100); assert_eq!(Balances::usable_balance(&alice_account_id()), 100);
@ -99,9 +98,9 @@ fn medium_claiming_works() {
fn big_claiming_works() { fn big_claiming_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(), third_eth_public_key(),
third_signature(), third_signature(),
)); ));
assert_eq!(Balances::usable_balance(&alice_account_id()), 200); assert_eq!(Balances::usable_balance(&alice_account_id()), 200);
@ -113,11 +112,15 @@ fn big_claiming_works() {
assert_eq!(Club::rank_of(&third_account_id()), None); assert_eq!(Club::rank_of(&third_account_id()), None);
assert_eq!(Vesting::vesting_balance(&alice_account_id()), Some(800)); assert_eq!(Vesting::vesting_balance(&alice_account_id()), Some(800));
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims() - 1000); assert_eq!(
ghost_claims::Total::<Test, ()>::get(),
total_claims() - 1000
);
assert_ok!(Balances::transfer_allow_death( assert_ok!(Balances::transfer_allow_death(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
bob_account_id(), bob_account_id(),
200)); 200
));
}) })
} }
@ -125,19 +128,19 @@ fn big_claiming_works() {
fn multiple_accounts_claiming_works() { fn multiple_accounts_claiming_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature(), first_signature(),
)); ));
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(), second_eth_public_key(),
second_signature(), second_signature(),
)); ));
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(), third_eth_public_key(),
third_signature(), third_signature(),
)); ));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310); assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
@ -157,19 +160,19 @@ fn multiple_accounts_claiming_works() {
fn multiple_accounts_reverese_claiming_works() { fn multiple_accounts_reverese_claiming_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(), third_eth_public_key(),
third_signature(), third_signature(),
)); ));
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(), second_eth_public_key(),
second_signature(), second_signature(),
)); ));
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature(), first_signature(),
)); ));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310); assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
@ -188,11 +191,14 @@ fn multiple_accounts_reverese_claiming_works() {
#[test] #[test]
fn cannot_claim_with_bad_signature() { fn cannot_claim_with_bad_signature() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!(Claims::claim( assert_err!(
Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
wrong_signature()), wrong_signature()
crate::Error::<Test>::InvalidEthereumAddress); ),
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0); assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
assert_eq!(Balances::usable_balance(&first_account_id()), 10); assert_eq!(Balances::usable_balance(&first_account_id()), 10);
@ -212,11 +218,14 @@ fn cannot_claim_with_bad_signature() {
#[test] #[test]
fn cannot_claim_with_wrong_address() { fn cannot_claim_with_wrong_address() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!(Claims::claim( assert_err!(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()), RuntimeOrigin::signed(bob_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature()), first_signature()
crate::Error::<Test>::InvalidEthereumAddress); ),
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0); assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0); assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
@ -237,11 +246,14 @@ fn cannot_claim_with_wrong_address() {
#[test] #[test]
fn cannot_claim_nothing() { fn cannot_claim_nothing() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!(Claims::claim( assert_err!(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()), RuntimeOrigin::signed(bob_account_id()),
fourth_eth_public_key(), fourth_eth_public_key(),
fourth_signature()), fourth_signature()
crate::Error::<Test>::NoBalanceToClaim); ),
crate::Error::<Test>::NoBalanceToClaim
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0); assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&fourth_account_id()), 0); assert_eq!(Balances::usable_balance(&fourth_account_id()), 0);
assert_eq!(Vesting::vesting_balance(&bob_account_id()), None); assert_eq!(Vesting::vesting_balance(&bob_account_id()), None);
@ -259,16 +271,15 @@ fn event_emitted_during_claim() {
System::reset_events(); System::reset_events();
assert_eq!(System::event_count(), 0); assert_eq!(System::event_count(), 0);
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(), third_eth_public_key(),
third_signature(), third_signature(),
)); ));
System::assert_has_event(RuntimeEvent::Claims( System::assert_has_event(RuntimeEvent::Claims(crate::Event::Claimed {
crate::Event::Claimed { receiver: alice_account_id(),
receiver: alice_account_id(), donor: account,
donor: account, amount,
amount, rank,
rank, }));
}));
}) })
} }