diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 62a755648..95cb4adf1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @drewstone @1xstj @tbraun96 +* @drewstone @1xstj @tbraun96 @salman01zp diff --git a/Cargo.lock b/Cargo.lock index f9294ba34..0c3625938 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7384,6 +7384,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "pallet-airdrop-claims" +version = "0.5.0" +dependencies = [ + "frame-support", + "frame-system", + "hex-literal 0.3.4", + "libsecp256k1", + "pallet-balances", + "pallet-evm", + "pallet-vesting", + "parity-scale-codec", + "rustc-hex", + "scale-info", + "schnorrkel", + "serde", + "serde_json", + "sp-core 21.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", + "sp-io 23.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", + "sp-runtime 24.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", + "sp-std 8.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", +] + [[package]] name = "pallet-aura" version = "4.0.0-dev" @@ -7658,27 +7681,6 @@ dependencies = [ "sp-std 8.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", ] -[[package]] -name = "pallet-ecdsa-claims" -version = "0.5.0" -dependencies = [ - "frame-support", - "frame-system", - "hex-literal 0.3.4", - "libsecp256k1", - "pallet-balances", - "pallet-vesting", - "parity-scale-codec", - "rustc-hex", - "scale-info", - "serde", - "serde_json", - "sp-core 21.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", - "sp-io 23.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", - "sp-runtime 24.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", - "sp-std 8.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0)", -] - [[package]] name = "pallet-election-provider-multi-phase" version = "4.0.0-dev" @@ -14082,6 +14084,7 @@ dependencies = [ "hex-literal 0.3.4", "log", "num_enum 0.5.11", + "pallet-airdrop-claims", "pallet-aura", "pallet-authorship", "pallet-bags-list", @@ -14093,7 +14096,6 @@ dependencies = [ "pallet-collective", "pallet-democracy", "pallet-dynamic-fee", - "pallet-ecdsa-claims", "pallet-election-provider-multi-phase", "pallet-elections-phragmen", "pallet-ethereum", @@ -14280,6 +14282,7 @@ dependencies = [ "hex-literal 0.3.4", "log", "num_enum 0.5.11", + "pallet-airdrop-claims", "pallet-aura", "pallet-authorship", "pallet-bags-list", @@ -14295,7 +14298,6 @@ dependencies = [ "pallet-dkg-proposal-handler", "pallet-dkg-proposals", "pallet-dynamic-fee", - "pallet-ecdsa-claims", "pallet-election-provider-multi-phase", "pallet-elections-phragmen", "pallet-ethereum", @@ -15150,7 +15152,7 @@ checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", "digest 0.10.7", - "rand 0.8.5", + "rand 0.4.6", "static_assertions", ] diff --git a/Cargo.toml b/Cargo.toml index fe2216f9f..9519fbf27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ members = [ "runtime/testnet/evm_tracer", "runtime/mainnet", "pallets/*", + "pallets/claims", "pallets/roles", "pallets/jobs/rpc", "pallets/jobs/rpc/runtime-api", @@ -70,6 +71,7 @@ syn = { version = "1.0" } hex = { version = "0.4.3", default-features = false } paste = "1.0.6" slices = "0.2.0" +schnorrkel = { verison = "11.4", default-features = false } # DKG Substrate Dependencies dkg-runtime-primitives = { git = "https://github.com/webb-tools/dkg-substrate.git", tag = "v0.4.7", default-features = false } @@ -86,7 +88,7 @@ tangle-testnet-runtime = { package = "tangle-testnet-runtime", path = "runtime/t tangle-mainnet-runtime = { package = "tangle-mainnet-runtime", path = "runtime/mainnet" } # Tangle Dependencies -pallet-ecdsa-claims = { path = "pallets/claims", default-features = false } +pallet-airdrop-claims = { path = "pallets/claims", default-features = false } pallet-jobs = { path = "pallets/jobs", default-features = false } pallet-roles = { path = "pallets/roles", default-features = false } pallet-dkg = { path = "pallets/dkg", default-features = false } diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs deleted file mode 100644 index 845026ebc..000000000 --- a/node/src/chain_spec.rs +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2022 Webb Technologies Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -use std::{collections::BTreeMap, marker::PhantomData}; - -use crate::{ - distributions::{combine_distributions, develop, testnet}, - testnet_fixtures::{ - get_standalone_bootnodes, get_standalone_initial_authorities, get_testnet_root_key, - }, -}; -use dkg_runtime_primitives::ResourceId; -use hex_literal::hex; -use pallet_im_online::sr25519::AuthorityId as ImOnlineId; -use sc_consensus_grandpa::AuthorityId as GrandpaId; -use sc_service::ChainType; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{sr25519, Pair, Public, H160}; -use sp_runtime::traits::{IdentifyAccount, Verify}; -use tangle_testnet_runtime::{ - AccountId, Balance, BalancesConfig, DKGConfig, DKGId, DKGProposalsConfig, EVMChainIdConfig, - EVMConfig, ElectionsConfig, Eth2ClientConfig, ImOnlineConfig, MaxNominations, Perbill, - RuntimeGenesisConfig, SessionConfig, Signature, StakerStatus, StakingConfig, SudoConfig, - SystemConfig, UNIT, WASM_BINARY, -}; -use webb_consensus_types::network_config::{Network, NetworkConfig}; - -// The URL for the telemetry server. -// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; - -/// Hermes (Evm, 5001) -const CHAIN_ID_HERMES: [u8; 6] = hex_literal::hex!("010000001389"); -/// Athena (Evm, 5002) -const CHAIN_ID_ATHENA: [u8; 6] = hex_literal::hex!("01000000138a"); -/// Demeter (Evm, 5003) -const CHAIN_ID_DEMETER: [u8; 6] = hex_literal::hex!("01000000138b"); - -const RESOURCE_ID_HERMES_ATHENA: ResourceId = ResourceId(hex_literal::hex!( - "0000000000000000e69a847cd5bc0c9480ada0b339d7f0a8cac2b6670000138a" -)); -const RESOURCE_ID_ATHENA_HERMES: ResourceId = ResourceId(hex_literal::hex!( - "000000000000d30c8839c1145609e564b986f667b273ddcb8496010000001389" -)); - -/// The default value for keygen threshold -const DEFAULT_DKG_KEYGEN_THRESHOLD: u16 = 5; - -/// The default value for signature threshold -const DEFAULT_DKG_SIGNATURE_THRESHOLD: u16 = 3; - -/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. -pub type ChainSpec = sc_service::GenericChainSpec; - -/// Generate a crypto pair from seed. -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{seed}"), None) - .expect("static values are valid; qed") - .public() -} - -type AccountPublic = ::Signer; - -/// Generate an account ID from seed. -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -/// Generate an Aura authority key. -pub fn authority_keys_from_seed( - controller: &str, - stash: &str, -) -> (AccountId, AccountId, AuraId, GrandpaId, ImOnlineId, DKGId) { - ( - get_account_id_from_seed::(controller), - get_account_id_from_seed::(stash), - get_from_seed::(controller), - get_from_seed::(controller), - get_from_seed::(stash), - get_from_seed::(controller), - ) -} - -/// Generate the session keys from individual elements. -/// -/// The input must be a tuple of individual keys (a single arg for now since we -/// have just one key). -fn dkg_session_keys( - grandpa: GrandpaId, - aura: AuraId, - im_online: ImOnlineId, - dkg: DKGId, -) -> tangle_testnet_runtime::opaque::SessionKeys { - tangle_testnet_runtime::opaque::SessionKeys { grandpa, aura, dkg, im_online } -} - -pub fn local_testnet_config(chain_id: u64) -> Result { - let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - let mut properties = sc_chain_spec::Properties::new(); - properties.insert("tokenSymbol".into(), "tTNT".into()); - properties.insert("tokenDecimals".into(), 18u32.into()); - properties.insert("ss58Format".into(), 42.into()); - - Ok(ChainSpec::from_genesis( - // Name - "Local Testnet", - // ID - "local_testnet", - ChainType::Local, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![ - authority_keys_from_seed("Alice", "Alice//stash"), - authority_keys_from_seed("Bob", "Bob//stash"), - authority_keys_from_seed("Charlie", "Charlie//stash"), - authority_keys_from_seed("Dave", "Dave//stash"), - authority_keys_from_seed("Eve", "Eve//stash"), - ], - vec![], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - ], - // Initial Chain Ids - vec![CHAIN_ID_HERMES, CHAIN_ID_ATHENA, CHAIN_ID_DEMETER], - // Initial resource Ids - vec![ - (RESOURCE_ID_HERMES_ATHENA, Default::default()), - (RESOURCE_ID_ATHENA_HERMES, Default::default()), - ], - // Initial proposers - vec![ - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - ], - chain_id, - DEFAULT_DKG_KEYGEN_THRESHOLD, - DEFAULT_DKG_SIGNATURE_THRESHOLD, - combine_distributions(vec![ - develop::get_evm_balance_distribution(), - testnet::get_evm_balance_distribution(), - ]), - testnet::get_substrate_balance_distribution(), - true, - ) - }, - // Bootnodes - vec![], - // Telemetry - None, - // Protocol ID - None, - // Fork id - None, - // Properties - Some(properties), - // Extensions - None, - )) -} - -pub fn tangle_testnet_config(chain_id: u64) -> Result { - let wasm_binary = WASM_BINARY.ok_or_else(|| "tangle wasm not available".to_string())?; - let boot_nodes = get_standalone_bootnodes(); - let mut properties = sc_chain_spec::Properties::new(); - properties.insert("tokenSymbol".into(), "tTNT".into()); - properties.insert("tokenDecimals".into(), 18u32.into()); - properties.insert("ss58Format".into(), 42.into()); - - Ok(ChainSpec::from_genesis( - "Tangle Standalone Testnet", - "tangle-standalone-testnet", - ChainType::Development, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - get_standalone_initial_authorities(), - // initial nominators - vec![], - // Sudo account - get_testnet_root_key(), - // Pre-funded accounts - vec![ - get_testnet_root_key(), - hex!["4e85271af1330e5e9384bd3ac5bdc04c0f8ef5a8cc29c1a8ae483d674164745c"].into(), - hex!["804808fb75d16340dc250871138a1a6f1dfa3cab9cc1fbd6f42960f1c39a950d"].into(), - hex!["587c2ef00ec0a1b98af4c655763acd76ece690fccbb255f01663660bc274960d"].into(), - hex!["cc195602a63bbdcf2ef4773c86fdbfefe042cb9aa8e3059d02e59a062d9c3138"].into(), - hex!["a24f729f085de51eebaeaeca97d6d499761b8f6daeca9b99d754a06ef8bcec3f"].into(), - hex!["368ea402dbd9c9888ae999d6a799cf36e08673ee53c001dfb4529c149fc2c13b"].into(), - hex!["2c7f3cc085da9175414d1a9d40aa3aa161c8584a9ca62a938684dfbe90ae9d74"].into(), - hex!["0a55e5245382700f35d16a5ea6d60a56c36c435bef7204353b8c36871f347857"].into(), - hex!["e0948453e7acbc6ac937e124eb01580191e99f4262d588d4524994deb6134349"].into(), - hex!["6c73e5ee9f8614e7c9f23fd8f7257d12e061e75fcbeb3b50ed70eb87ba91f500"].into(), - hex!["541dc9dd9cd9b47ff19c77c3b14fab50ab0774e19abe438719cd09e4f4861166"].into(), - hex!["607e948bad733780eda6c0bd9b084243276332823ca8481fc20cd01e1a2ef36f"].into(), - hex!["b2c09cb1b78c3afd2b1ea4316dfb1be9065e070db948477248e4f3e0f1a2d850"].into(), - hex!["fc156f082d789f94149f8b52b191672fbf202ef1b92b487c3cec9bca2d1fbe72"].into(), - hex!["0e87759b6eeb6891743900cba17b8b5f31b2fa9c28536d9bcf76468d6e455b23"].into(), - hex!["48cea44ac6dd245572272dc6d4d33908586fb80886bf3207344388eac279cc25"].into(), - hex!["fa2c711c82661a761cf200421b9a5ef3257aa977a3a33acad0722d7d6993f03b"].into(), - hex!["daf7985bfa22b5060a4eb212fbeddb7c47f7c29db5a356ed9500b34d2944eb3d"].into(), - hex!["4ec0389ae623884a68234fd84d85af833633668aa382007e6515020e8cc29532"].into(), - hex!["48bb70f924e7362ee55817a6628a79e522a08a31735b0129e47ac435215d6c4e"].into(), - hex!["d6a033ee1790ef28fffe1b1ffec19b8921690632d073d955b9057e701eced352"].into(), - hex!["14ecdcc058ee431166402eefb682c276cc16a5d1083409b28076fda4c4d5352f"].into(), - hex!["400d597fe03f1031a9b4e1983b7c42eeed29ef3f9da6715667d06b367bdb897f"].into(), - hex!["668cf048845804f31759decbec11cb41bf316b1901d2142a35ad3a8eb7420326"].into(), - ], - vec![], - vec![], - get_standalone_initial_authorities().iter().map(|a| a.0.clone()).collect(), - chain_id, - DEFAULT_DKG_KEYGEN_THRESHOLD, - DEFAULT_DKG_SIGNATURE_THRESHOLD, - combine_distributions(vec![ - develop::get_evm_balance_distribution(), - testnet::get_evm_balance_distribution(), - ]), - testnet::get_substrate_balance_distribution(), - true, - ) - }, - // Bootnodes - boot_nodes, - // Telemetry - None, - // Protocol ID - None, - // Fork id - None, - // Properties - Some(properties), - // Extensions - None, - )) -} - -/// Configure initial storage state for FRAME modules. -#[allow(clippy::too_many_arguments)] -fn testnet_genesis( - wasm_binary: &[u8], - initial_authorities: Vec<(AccountId, AccountId, AuraId, GrandpaId, ImOnlineId, DKGId)>, - initial_nominators: Vec, - root_key: AccountId, - endowed_accounts: Vec, - initial_chain_ids: Vec<[u8; 6]>, - initial_r_ids: Vec<(ResourceId, Vec)>, - initial_proposers: Vec, - chain_id: u64, - dkg_keygen_threshold: u16, - dkg_signature_threshold: u16, - genesis_evm_distribution: Vec<(H160, fp_evm::GenesisAccount)>, - genesis_substrate_distribution: Vec<(AccountId, Balance)>, - _enable_println: bool, -) -> RuntimeGenesisConfig { - const ENDOWMENT: Balance = 10_000_000 * UNIT; - const STASH: Balance = ENDOWMENT / 100; - - // stakers: all validators and nominators. - let mut rng = rand::thread_rng(); - let stakers = initial_authorities - .iter() - .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) - .chain(initial_nominators.iter().map(|x| { - use rand::{seq::SliceRandom, Rng}; - let limit = (MaxNominations::get() as usize).min(initial_authorities.len()); - let count = rng.gen::() % limit; - let nominations = initial_authorities - .as_slice() - .choose_multiple(&mut rng, count) - .map(|choice| choice.0.clone()) - .collect::>(); - (x.clone(), x.clone(), STASH, StakerStatus::Nominator(nominations)) - })) - .collect::>(); - - let num_endowed_accounts = endowed_accounts.len(); - RuntimeGenesisConfig { - system: SystemConfig { - // Add Wasm runtime to storage. - code: wasm_binary.to_vec(), - ..Default::default() - }, - sudo: SudoConfig { key: Some(root_key) }, - balances: BalancesConfig { - // Configure endowed accounts with initial balance of 1 << 60. - balances: endowed_accounts - .iter() - .cloned() - .map(|k| (k, ENDOWMENT)) - .chain(genesis_substrate_distribution.iter().cloned().map(|(k, v)| (k, v))) - .collect(), - }, - vesting: Default::default(), - indices: Default::default(), - session: SessionConfig { - keys: initial_authorities - .iter() - .map(|x| { - ( - x.1.clone(), - x.0.clone(), - dkg_session_keys(x.3.clone(), x.2.clone(), x.4.clone(), x.5.clone()), - ) - }) - .collect::>(), - }, - staking: StakingConfig { - validator_count: initial_authorities.len() as u32, - minimum_validator_count: initial_authorities.len() as u32 - 1, - invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), - slash_reward_fraction: Perbill::from_percent(10), - stakers, - ..Default::default() - }, - democracy: Default::default(), - council: Default::default(), - elections: ElectionsConfig { - members: endowed_accounts - .iter() - .take((num_endowed_accounts + 1) / 2) - .cloned() - .map(|member| (member, STASH)) - .collect(), - }, - treasury: Default::default(), - aura: Default::default(), - grandpa: Default::default(), - dkg: DKGConfig { - authorities: initial_authorities.iter().map(|(.., x)| x.clone()).collect::<_>(), - keygen_threshold: dkg_keygen_threshold, - signature_threshold: dkg_signature_threshold, - authority_ids: initial_authorities.iter().map(|(x, ..)| x.clone()).collect::<_>(), - }, - dkg_proposals: DKGProposalsConfig { initial_chain_ids, initial_r_ids, initial_proposers }, - bridge_registry: Default::default(), - im_online: ImOnlineConfig { keys: vec![] }, - eth_2_client: Eth2ClientConfig { - // Vec<(TypedChainId, [u8; 32], ForkVersion, u64)> - networks: vec![ - (webb_proposals::TypedChainId::Evm(1), NetworkConfig::new(&Network::Mainnet)), - (webb_proposals::TypedChainId::Evm(5), NetworkConfig::new(&Network::Goerli)), - ], - phantom: PhantomData, - }, - nomination_pools: Default::default(), - transaction_payment: Default::default(), - // EVM compatibility - evm_chain_id: EVMChainIdConfig { chain_id, ..Default::default() }, - evm: EVMConfig { - accounts: { - let mut map = BTreeMap::new(); - for (address, account) in genesis_evm_distribution { - map.insert(address, account); - } - map - }, - ..Default::default() - }, - ethereum: Default::default(), - dynamic_fee: Default::default(), - base_fee: Default::default(), - } -} diff --git a/node/src/chainspec/mainnet.rs b/node/src/chainspec/mainnet.rs index e7ac8cfac..8f4616e8d 100644 --- a/node/src/chainspec/mainnet.rs +++ b/node/src/chainspec/mainnet.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::{collections::BTreeMap, marker::PhantomData}; +use std::collections::BTreeMap; use crate::{ distributions::{combine_distributions, develop, mainnet, testnet}, @@ -319,6 +319,7 @@ fn testnet_genesis( ethereum: Default::default(), dynamic_fee: Default::default(), base_fee: Default::default(), + claims: Default::default(), } } @@ -405,5 +406,6 @@ fn mainnet_genesis( // phantom: PhantomData, // }, bridge_registry: Default::default(), + claims: Default::default(), } } diff --git a/node/src/chainspec/testnet.rs b/node/src/chainspec/testnet.rs index 5b8a5935a..5d996ccdb 100644 --- a/node/src/chainspec/testnet.rs +++ b/node/src/chainspec/testnet.rs @@ -11,7 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use std::{collections::BTreeMap, marker::PhantomData}; +use std::collections::BTreeMap; use crate::{ distributions::{combine_distributions, develop, testnet}, diff --git a/pallets/claims/Cargo.toml b/pallets/claims/Cargo.toml index db036f0e8..2b8ace808 100644 --- a/pallets/claims/Cargo.toml +++ b/pallets/claims/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pallet-ecdsa-claims" +name = "pallet-airdrop-claims" version = { workspace = true } authors = { workspace = true } edition = { workspace = true } @@ -12,16 +12,18 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } - +pallet-evm = { workspace = true } rustc-hex = { workspace = true } scale-info = { workspace = true } -serde = { workspace = true } +serde = { workspace = true, features = ["alloc"] } +schnorrkel = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } libsecp256k1 = { workspace = true } pallet-balances = { workspace = true } pallet-vesting = { workspace = true } +sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } @@ -42,11 +44,14 @@ std = [ "scale-info/std", "frame-support/std", "frame-system/std", + "sp-core/std", "sp-runtime/std", "sp-std/std", "sp-io/std", "libsecp256k1/std", "pallet-vesting/std", "pallet-balances/std", + "pallet-evm/std", + "schnorrkel/std", ] try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/claims/src/benchmarking.rs b/pallets/claims/src/benchmarking.rs new file mode 100644 index 000000000..7529bc794 --- /dev/null +++ b/pallets/claims/src/benchmarking.rs @@ -0,0 +1,226 @@ +use super::*; +use crate::claimsPalletClaimsPallet::Call; +use frame_benchmarking::{account, benchmarks}; +use frame_support::dispatch::UnfilteredDispatchable; +use frame_system::RawOrigin; +use secp_utils::*; +use sp_runtime::{traits::ValidateUnsigned, DispatchResult}; + +const SEED: u32 = 0; + +const MAX_CLAIMS: u32 = 10_000; +const VALUE: u32 = 1_000_000; + +fn create_claim(input: u32) -> DispatchResult { + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&input.encode())).unwrap(); + let eth_address = eth(&secret_key); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + None, + )?; + Ok(()) +} + +fn create_claim_attest(input: u32) -> DispatchResult { + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&input.encode())).unwrap(); + let eth_address = eth(&secret_key); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + Some(Default::default()), + )?; + Ok(()) +} + +benchmarks! { + // Benchmark `claim` including `validate_unsigned` logic. + claim { + let c = MAX_CLAIMS; + + for i in 0 .. c / 2 { + create_claim::(c)?; + create_claim_attest::(u32::MAX - c)?; + } + + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&c.encode())).unwrap(); + let eth_address = eth(&secret_key); + let account: T::AccountId = account("user", c, SEED); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + let signature = sig::(&secret_key, &account.encode(), &[][..]); + super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, None)?; + assert_eq!(ClaimsPallet::::get(eth_address), Some(VALUE.into())); + let source = sp_runtime::transaction_validity::TransactionSource::External; + let call_enc = Call::::claim { + dest: account.clone(), + ethereum_signature: signature.clone() + }.encode(); + }: { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; + call.dispatch_bypass_filter(RawOrigin::None.into())?; + } + verify { + assert_eq!(ClaimsPallet::::get(eth_address), None); + } + + // Benchmark `mint_claim` when there already exists `c` claims in storage. + mint_claim { + let c = MAX_CLAIMS; + + for i in 0 .. c / 2 { + create_claim::(c)?; + create_claim_attest::(u32::MAX - c)?; + } + + let eth_address = account("eth_address", 0, SEED); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + let statement = StatementKind::Regular; + }: _(RawOrigin::Root, eth_address, VALUE.into(), vesting, Some(statement)) + verify { + assert_eq!(ClaimsPallet::::get(eth_address), Some(VALUE.into())); + } + + // Benchmark `claim_attest` including `validate_unsigned` logic. + claim_attest { + let c = MAX_CLAIMS; + + for i in 0 .. c / 2 { + create_claim::(c)?; + create_claim_attest::(u32::MAX - c)?; + } + + // Crate signature + let attest_c = u32::MAX - c; + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let eth_address = eth(&secret_key); + let account: T::AccountId = account("user", c, SEED); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + let statement = StatementKind::Regular; + let signature = sig::(&secret_key, &account.encode(), statement.to_text()); + super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; + assert_eq!(ClaimsPallet::::get(eth_address), Some(VALUE.into())); + let call_enc = Call::::claim_attest { + dest: account.clone(), + ethereum_signature: signature.clone(), + statement: StatementKind::Regular.to_text().to_vec() + }.encode(); + let source = sp_runtime::transaction_validity::TransactionSource::External; + }: { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; + call.dispatch_bypass_filter(RawOrigin::None.into())?; + } + verify { + assert_eq!(ClaimsPallet::::get(eth_address), None); + } + + // Benchmark `attest` including prevalidate logic. + attest { + let c = MAX_CLAIMS; + + for i in 0 .. c / 2 { + create_claim::(c)?; + create_claim_attest::(u32::MAX - c)?; + } + + let attest_c = u32::MAX - c; + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let eth_address = eth(&secret_key); + let account: T::AccountId = account("user", c, SEED); + let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); + let statement = StatementKind::Regular; + let signature = sig::(&secret_key, &account.encode(), statement.to_text()); + super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; + PreclaimsPalletClaimsPallet::::insert(&account, eth_address); + assert_eq!(ClaimsPallet::::get(eth_address), Some(VALUE.into())); + + let call = super::Call::::attest { statement: StatementKind::Regular.to_text().to_vec() }; + // We have to copy the validate statement here because of trait issues... :( + let validate = |who: &T::AccountId, call: &super::Call| -> DispatchResult { + if let Call::attest{ statement: attested_statement } = call { + let signer = PreclaimsPalletClaimsPallet::::get(who).ok_or("signer has no claim")?; + if let Some(s) = Signing::::get(signer) { + ensure!(&attested_statement[..] == s.to_text(), "invalid statement"); + } + } + Ok(()) + }; + let call_enc = call.encode(); + }: { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + validate(&account, &call)?; + call.dispatch_bypass_filter(RawOrigin::Signed(account).into())?; + } + verify { + assert_eq!(ClaimsPallet::::get(eth_address), None); + } + + move_claim { + let c = MAX_CLAIMS; + + for i in 0 .. c / 2 { + create_claim::(c)?; + create_claim_attest::(u32::MAX - c)?; + } + + let attest_c = u32::MAX - c; + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let eth_address = eth(&secret_key); + + let new_secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&(u32::MAX/2).encode())).unwrap(); + let new_eth_address = eth(&new_secret_key); + + let account: T::AccountId = account("user", c, SEED); + PreclaimsPalletClaimsPallet::::insert(&account, eth_address); + + assert!(ClaimsPallet::::contains_key(eth_address)); + assert!(!ClaimsPallet::::contains_key(new_eth_address)); + }: _(RawOrigin::Root, eth_address, new_eth_address, Some(account)) + verify { + assert!(!ClaimsPallet::::contains_key(eth_address)); + assert!(ClaimsPallet::::contains_key(new_eth_address)); + } + + // Benchmark the time it takes to do `repeat` number of keccak256 hashes + #[extra] + keccak256 { + let i in 0 .. 10_000; + let bytes = (i).encode(); + }: { + for index in 0 .. i { + let _hash = keccak_256(&bytes); + } + } + + // Benchmark the time it takes to do `repeat` number of `eth_recover` + #[extra] + eth_recover { + let i in 0 .. 1_000; + // Crate signature + let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&i.encode())).unwrap(); + let account: T::AccountId = account("user", i, SEED); + let signature = sig::(&secret_key, &account.encode(), &[][..]); + let data = account.using_encoded(to_ascii_hex); + let extra = StatementKind::default().to_text(); + }: { + for _ in 0 .. i { + assert!(super::Pallet::::eth_recover(&signature, &data, extra).is_some()); + } + } + + impl_benchmark_test_suite!( + Pallet, + crate::claimsPalletClaimsPallet::tests::new_test_ext(), + crate::claimsPalletClaimsPallet::tests::Test, + ); +} diff --git a/pallets/claims/src/lib.rs b/pallets/claims/src/lib.rs index 748838efe..855a00796 100644 --- a/pallets/claims/src/lib.rs +++ b/pallets/claims/src/lib.rs @@ -18,28 +18,43 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::all)] +#[cfg(test)] +mod mock; + +#[cfg(test)] +mod tests; + +mod utils; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +use crate::utils::{ + ethereum_address::{EcdsaSignature, EthereumAddress}, + MultiAddress, MultiAddressSignature, +}; use frame_support::{ ensure, - traits::{Currency, Get, IsSubType, VestingSchedule}, + traits::{Currency, Get, VestingSchedule}, weights::Weight, }; pub use pallet::*; +use pallet_evm::AddressMapping; use parity_scale_codec::{Decode, Encode}; -use scale_info::{ - prelude::{format, string::String}, - TypeInfo, +use scale_info::TypeInfo; +use serde::{self, Deserialize, Serialize}; +use sp_core::{sr25519::Public, H160}; +use sp_io::{ + crypto::{secp256k1_ecdsa_recover, sr25519_verify}, + hashing::keccak_256, }; -use serde::{self, Deserialize, Deserializer, Serialize, Serializer}; -use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256}; use sp_runtime::{ - traits::{CheckedSub, DispatchInfoOf, SignedExtension, Zero}, - transaction_validity::{ - InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction, - }, + traits::{CheckedSub, Zero}, + transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, RuntimeDebug, }; -use sp_std::{convert::TryInto, fmt::Debug, prelude::*, vec}; - +use sp_std::{convert::TryInto, prelude::*, vec}; +use utils::Sr25519Signature; /// Custom validity errors used in Polkadot while validating transactions. #[repr(u8)] pub enum ValidityError { @@ -96,10 +111,10 @@ impl WeightInfo for TestWeightInfo { Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo, Serialize, Deserialize, )] pub enum StatementKind { - /// Statement required to be made by non-SAFT holders. + /// Statement required to be made by non-SAFE holders. Regular, - /// Statement required to be made by SAFT holders. - Saft, + /// Statement required to be made by SAFE holders. + Safe, } impl StatementKind { @@ -110,7 +125,7 @@ impl StatementKind { &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny. (This may be found at the URL: \ https://statement.polkadot.network/regular.html)"[..], - StatementKind::Saft => + StatementKind::Safe => &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ QmXEkMahfhHJPzT3RjkXiZVFi77ZeVeuxtAjhojGRNYckz. (This may be found at the URL: \ https://statement.polkadot.network/saft.html)"[..], @@ -124,58 +139,6 @@ impl Default for StatementKind { } } -/// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account). -/// -/// This gets serialized to the 0x-prefixed hex representation. -#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] -pub struct EthereumAddress([u8; 20]); - -impl Serialize for EthereumAddress { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]); - serializer.serialize_str(&format!("0x{}", hex)) - } -} - -impl<'de> Deserialize<'de> for EthereumAddress { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let base_string = String::deserialize(deserializer)?; - let offset = if base_string.starts_with("0x") { 2 } else { 0 }; - let s = &base_string[offset..]; - if s.len() != 40 { - Err(serde::de::Error::custom( - "Bad length of Ethereum address (should be 42 including '0x')", - ))?; - } - let raw: Vec = rustc_hex::FromHex::from_hex(s) - .map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?; - let mut r = Self::default(); - r.0.copy_from_slice(&raw); - Ok(r) - } -} - -#[derive(Encode, Decode, Clone, TypeInfo)] -pub struct EcdsaSignature(pub [u8; 65]); - -impl PartialEq for EcdsaSignature { - fn eq(&self, other: &Self) -> bool { - &self.0[..] == &other.0[..] - } -} - -impl sp_std::fmt::Debug for EcdsaSignature { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - write!(f, "EcdsaSignature({:?})", &self.0[..]) - } -} - #[frame_support::pallet] pub mod pallet { use super::*; @@ -195,6 +158,7 @@ pub mod pallet { #[pallet::constant] type Prefix: Get<&'static [u8]>; type MoveClaimOrigin: EnsureOrigin; + type AddressMapping: AddressMapping; /// RuntimeOrigin permitted to call force_ extrinsics type ForceOrigin: EnsureOrigin; type WeightInfo: WeightInfo; @@ -204,13 +168,17 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Someone claimed some native tokens. - Claimed { who: T::AccountId, ethereum_address: EthereumAddress, amount: BalanceOf }, + Claimed { recipient: T::AccountId, source: MultiAddress, amount: BalanceOf }, } #[pallet::error] pub enum Error { /// Invalid Ethereum signature. InvalidEthereumSignature, + /// Invalid Native (sr25519) signature + InvalidNativeSignature, + /// Invalid Native account decoding + InvalidNativeAccount, /// Ethereum address has no claim. SignerHasNoClaim, /// Account ID sending transaction has no claim. @@ -226,7 +194,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn claims)] - pub(super) type Claims = StorageMap<_, Identity, EthereumAddress, BalanceOf>; + pub(super) type Claims = StorageMap<_, Identity, MultiAddress, BalanceOf>; #[pallet::storage] #[pallet::getter(fn total)] @@ -235,7 +203,7 @@ pub mod pallet { /// Expiry block and account to deposit expired funds #[pallet::storage] #[pallet::getter(fn expiry_time)] - pub(super) type ExpiryConfig = StorageValue<_, (BlockNumberFor, T::AccountId)>; + pub(super) type ExpiryConfig = StorageValue<_, (BlockNumberFor, MultiAddress)>; /// Vesting schedule for a claim. /// First balance is the total amount that should be held for vesting. @@ -244,22 +212,17 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn vesting)] pub(super) type Vesting = - StorageMap<_, Identity, EthereumAddress, (BalanceOf, BalanceOf, BlockNumberFor)>; + StorageMap<_, Identity, MultiAddress, (BalanceOf, BalanceOf, BlockNumberFor)>; /// The statement kind that must be signed, if any. #[pallet::storage] - pub(super) type Signing = StorageMap<_, Identity, EthereumAddress, StatementKind>; - - /// Pre-claimed Ethereum accounts, by the Account ID that they are claimed to. - #[pallet::storage] - pub(super) type Preclaims = StorageMap<_, Identity, T::AccountId, EthereumAddress>; + pub(super) type Signing = StorageMap<_, Identity, MultiAddress, StatementKind>; #[pallet::genesis_config] pub struct GenesisConfig { - pub claims: - Vec<(EthereumAddress, BalanceOf, Option, Option)>, - pub vesting: Vec<(EthereumAddress, (BalanceOf, BalanceOf, BlockNumberFor))>, - pub expiry: Option<(BlockNumberFor, T::AccountId)>, + pub claims: Vec<(MultiAddress, BalanceOf, Option)>, + pub vesting: Vec<(MultiAddress, (BalanceOf, BalanceOf, BlockNumberFor))>, + pub expiry: Option<(BlockNumberFor, MultiAddress)>, } impl Default for GenesisConfig { @@ -272,17 +235,12 @@ pub mod pallet { impl BuildGenesisConfig for GenesisConfig { fn build(&self) { // build `Claims` - self.claims - .iter() - .map(|(a, b, _, _)| (a.clone(), b.clone())) - .for_each(|(a, b)| { - Claims::::insert(a, b); - }); + self.claims.iter().map(|(a, b, _)| (a.clone(), b.clone())).for_each(|(a, b)| { + Claims::::insert(a, b); + }); // build `Total` Total::::put( - self.claims - .iter() - .fold(Zero::zero(), |acc: BalanceOf, &(_, b, _, _)| acc + b), + self.claims.iter().fold(Zero::zero(), |acc: BalanceOf, &(_, b, _)| acc + b), ); // build `Vesting` self.vesting.iter().for_each(|(k, v)| { @@ -291,17 +249,10 @@ pub mod pallet { // build `Signing` self.claims .iter() - .filter_map(|(a, _, _, s)| Some((a.clone(), s.clone()?))) + .filter_map(|(a, _, s)| Some((a.clone(), s.clone()?))) .for_each(|(a, s)| { Signing::::insert(a, s); }); - // build `Preclaims` - self.claims - .iter() - .filter_map(|(a, _, i, _)| Some((i.clone()?, a.clone()))) - .for_each(|(i, a)| { - Preclaims::::insert(i, a); - }); // build expiryConfig ExpiryConfig::::set(self.expiry.clone()) } @@ -316,7 +267,12 @@ pub mod pallet { if current_block > expiry_config.0 { let unclaimed_amount = Total::::take(); frame_support::log::info!("Claims : Expiry block passed, sweeping remaining amount of {:?} to destination", unclaimed_amount); - CurrencyOf::::deposit_creating(&expiry_config.1, unclaimed_amount); + let expiry_destination = + match Self::convert_multi_address_to_account_id(expiry_config.1) { + Ok(a) => a, + Err(_) => return, + }; + CurrencyOf::::deposit_creating(&expiry_destination, unclaimed_amount); // clear the expiry detail ExpiryConfig::::take(); } @@ -326,7 +282,7 @@ pub mod pallet { #[pallet::call] impl Pallet { - /// Make a claim to collect your native tokens. + /// Make a claim to collect your tokens. /// /// The dispatch origin for this call must be _None_. /// @@ -354,16 +310,15 @@ pub mod pallet { #[pallet::call_index(0)] pub fn claim( origin: OriginFor, - dest: T::AccountId, - ethereum_signature: EcdsaSignature, + dest: Option, + signer: Option, + signature: MultiAddressSignature, ) -> DispatchResult { ensure_none(origin)?; let data = dest.using_encoded(to_ascii_hex); - let signer = Self::eth_recover(ðereum_signature, &data, &[][..]) - .ok_or(Error::::InvalidEthereumSignature)?; + let signer = Self::get_signer_multi_address(signer.clone(), signature, data, vec![])?; ensure!(Signing::::get(&signer).is_none(), Error::::InvalidStatement); - Self::process_claim(signer, dest)?; Ok(()) } @@ -387,7 +342,7 @@ pub mod pallet { #[pallet::call_index(1)] pub fn mint_claim( origin: OriginFor, - who: EthereumAddress, + who: MultiAddress, value: BalanceOf, vesting_schedule: Option<(BalanceOf, BalanceOf, BlockNumberFor)>, statement: Option, @@ -395,9 +350,9 @@ pub mod pallet { ensure_root(origin)?; >::mutate(|t| *t += value); - >::insert(who, value); + >::insert(who.clone(), value); if let Some(vs) = vesting_schedule { - >::insert(who, vs); + >::insert(who.clone(), vs); } if let Some(s) = statement { Signing::::insert(who, s); @@ -436,78 +391,35 @@ pub mod pallet { #[pallet::call_index(2)] pub fn claim_attest( origin: OriginFor, - dest: T::AccountId, - ethereum_signature: EcdsaSignature, + dest: Option, + signer: Option, + signature: MultiAddressSignature, statement: Vec, ) -> DispatchResult { ensure_none(origin)?; let data = dest.using_encoded(to_ascii_hex); - let signer = Self::eth_recover(ðereum_signature, &data, &statement) - .ok_or(Error::::InvalidEthereumSignature)?; - if let Some(s) = Signing::::get(signer) { + let signer = + Self::get_signer_multi_address(signer.clone(), signature, data, statement.clone())?; + if let Some(s) = Signing::::get(signer.clone()) { ensure!(s.to_text() == &statement[..], Error::::InvalidStatement); } Self::process_claim(signer, dest)?; Ok(()) } - /// Attest to a statement, needed to finalize the claims process. - /// - /// WARNING: Insecure unless your chain includes `PrevalidateAttests` as a - /// `SignedExtension`. - /// - /// Unsigned Validation: - /// A call to attest is deemed valid if the sender has a `Preclaim` registered - /// and provides a `statement` which is expected for the account. - /// - /// Parameters: - /// - `statement`: The identity of the statement which is being attested to in the - /// signature. - /// - /// - /// The weight of this call is invariant over the input parameters. - /// Weight includes logic to do pre-validation on `attest` call. - /// - /// Total Complexity: O(1) - /// - #[pallet::weight(( - 3, - DispatchClass::Normal, - Pays::No - ))] - #[pallet::call_index(3)] - pub fn attest(origin: OriginFor, statement: Vec) -> DispatchResult { - let who = ensure_signed(origin)?; - let signer = Preclaims::::get(&who).ok_or(Error::::SenderHasNoClaim)?; - if let Some(s) = Signing::::get(signer) { - ensure!(s.to_text() == &statement[..], Error::::InvalidStatement); - } - Self::process_claim(signer, who.clone())?; - Preclaims::::remove(&who); - Ok(()) - } - #[pallet::weight({4})] #[pallet::call_index(4)] pub fn move_claim( origin: OriginFor, - old: EthereumAddress, - new: EthereumAddress, - maybe_preclaim: Option, + old: MultiAddress, + new: MultiAddress, ) -> DispatchResultWithPostInfo { T::MoveClaimOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?; Claims::::take(&old).map(|c| Claims::::insert(&new, c)); Vesting::::take(&old).map(|c| Vesting::::insert(&new, c)); Signing::::take(&old).map(|c| Signing::::insert(&new, c)); - maybe_preclaim.map(|preclaim| { - Preclaims::::mutate(&preclaim, |maybe_o| { - if maybe_o.as_ref().map_or(false, |o| o == &old) { - *maybe_o = Some(new) - } - }) - }); Ok(Pays::No.into()) } @@ -518,7 +430,7 @@ pub mod pallet { pub fn force_set_expiry_config( origin: OriginFor, expiry_block: BlockNumberFor, - dest: T::AccountId, + dest: MultiAddress, ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; ExpiryConfig::::set(Some((expiry_block, dest))); @@ -537,19 +449,32 @@ pub mod pallet { // // The weight of this logic is included in the `claim` dispatchable. // - Call::claim { dest: account, ethereum_signature } => { + Call::claim { dest: account, signer, signature } => { let data = account.using_encoded(to_ascii_hex); - (Self::eth_recover(ðereum_signature, &data, &[][..]), None) + match Self::get_signer_multi_address( + signer.clone(), + signature.clone(), + data, + vec![], + ) { + Ok(signer) => (Some(signer), None), + Err(_) => (None, None), + } }, // // The weight of this logic is included in the `claim_attest` dispatchable. // - Call::claim_attest { dest: account, ethereum_signature, statement } => { + Call::claim_attest { dest: account, signer, signature, statement } => { let data = account.using_encoded(to_ascii_hex); - ( - Self::eth_recover(ðereum_signature, &data, &statement), - Some(statement.as_slice()), - ) + match Self::get_signer_multi_address( + signer.clone(), + signature.clone(), + data, + statement.clone(), + ) { + Ok(signer) => (Some(signer), Some(statement.as_slice())), + Err(_) => (None, None), + } }, _ => return Err(InvalidTransaction::Call.into()), }; @@ -562,7 +487,7 @@ pub mod pallet { ensure!(>::contains_key(&signer), e); let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into()); - match Signing::::get(signer) { + match Signing::::get(signer.clone()) { None => ensure!(maybe_statement.is_none(), e), Some(s) => ensure!(Some(s.to_text()) == maybe_statement, e), } @@ -609,32 +534,86 @@ impl Pallet { // Attempts to recover the Ethereum address from a message signature signed by using // the Ethereum RPC's `personal_sign` and `eth_sign`. - fn eth_recover(s: &EcdsaSignature, what: &[u8], extra: &[u8]) -> Option { + fn eth_recover(s: &EcdsaSignature, what: &[u8], extra: &[u8]) -> Option { let msg = keccak_256(&Self::ethereum_signable_message(what, extra)); let mut res = EthereumAddress::default(); res.0 .copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]); - Some(res) + Some(MultiAddress::EVM(res)) + } + + // Constructs the message that PolkadotJS would sign. + fn polkadotjs_signable_message(what: &[u8], extra: &[u8]) -> Vec { + let prefix = T::Prefix::get(); + let mut v = prefix.to_vec(); + v.extend_from_slice(what); + v.extend_from_slice(extra); + v } - fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> sp_runtime::DispatchResult { + // Attempts to recover the Substrate address from a message signature signed by using + // the Substrate RPC's `sign`. + fn sr25519_recover( + addr: MultiAddress, + s: &Sr25519Signature, + what: &[u8], + extra: &[u8], + ) -> Option { + let msg = keccak_256(&Self::polkadotjs_signable_message(what, extra)); + let public: Public = match addr.clone() { + MultiAddress::EVM(_) => return None, + MultiAddress::Native(a) => { + let mut bytes = [0u8; 32]; + bytes.copy_from_slice(&a.encode()); + Public(bytes) + }, + }; + match sr25519_verify(&s.0, &msg, &public) { + true => Some(addr), + false => None, + } + // let pk: PublicKey = match addr.clone() { + // MultiAddress::EVM(_) => return None, + // MultiAddress::Native(a) => PublicKey::from_bytes(&a.encode()).ok()?, + // }; + // println!("pk: {:?}", pk); + // let signature: Signature = Signature::from_bytes(&s.0.encode()).ok()?; + // println!("signature: {:?}", signature); + // const SIGNING_CTX: &'static [u8] = b"substrate"; + // match pk.verify_simple(SIGNING_CTX, &msg, &signature) { + // Ok(_) => Some(addr), + // Err(_) => None, + // } + } + + fn process_claim( + signer: MultiAddress, + dest: Option, + ) -> sp_runtime::DispatchResult { let balance_due = >::get(&signer).ok_or(Error::::SignerHasNoClaim)?; let new_total = Self::total().checked_sub(&balance_due).ok_or(Error::::PotUnderflow)?; + // If there is a destination, then we need to transfer the balance to it. + let recipient = match dest { + Some(d) => d, + None => signer.clone(), + }; + // Convert the destination recipient to an account ID. + let recipient = Self::convert_multi_address_to_account_id(recipient)?; let vesting = Vesting::::get(&signer); - if vesting.is_some() && T::VestingSchedule::vesting_balance(&dest).is_some() { + if vesting.is_some() && T::VestingSchedule::vesting_balance(&recipient).is_some() { return Err(Error::::VestedBalanceExists.into()) } // We first need to deposit the balance to ensure that the account exists. - CurrencyOf::::deposit_creating(&dest, balance_due); + CurrencyOf::::deposit_creating(&recipient, balance_due); // Check if this claim should have a vesting schedule. if let Some(vs) = vesting { // This can only fail if the account already has a vesting schedule, // but this is checked above. - T::VestingSchedule::add_vesting_schedule(&dest, vs.0, vs.1, vs.2) + T::VestingSchedule::add_vesting_schedule(&recipient, vs.0, vs.1, vs.2) .expect("No other vesting schedule exists, as checked above; qed"); } @@ -644,94 +623,42 @@ impl Pallet { Signing::::remove(&signer); // Let's deposit an event to let the outside world know this happened. - Self::deposit_event(Event::::Claimed { - who: dest, - ethereum_address: signer, - amount: balance_due, - }); + Self::deposit_event(Event::::Claimed { recipient, source: signer, amount: balance_due }); Ok(()) } -} -/// Validate `attest` calls prior to execution. Needed to avoid a DoS attack since they are -/// otherwise free to place on chain. -#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] -#[scale_info(skip_type_params(T))] -pub struct PrevalidateAttests(sp_std::marker::PhantomData) -where - ::RuntimeCall: IsSubType>; - -impl Debug for PrevalidateAttests -where - ::RuntimeCall: IsSubType>, -{ - #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "PrevalidateAttests") - } - - #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - Ok(()) - } -} - -impl PrevalidateAttests -where - ::RuntimeCall: IsSubType>, -{ - /// Create new `SignedExtension` to check runtime version. - pub fn new() -> Self { - Self(sp_std::marker::PhantomData) - } -} - -impl SignedExtension for PrevalidateAttests -where - ::RuntimeCall: IsSubType>, -{ - type AccountId = T::AccountId; - type Call = ::RuntimeCall; - type AdditionalSigned = (); - type Pre = (); - const IDENTIFIER: &'static str = "PrevalidateAttests"; - - fn additional_signed(&self) -> Result { - Ok(()) - } - - fn pre_dispatch( - self, - who: &Self::AccountId, - call: &Self::Call, - info: &DispatchInfoOf, - len: usize, - ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) - } - - // - // The weight of this logic is included in the `attest` dispatchable. - // - fn validate( - &self, - who: &Self::AccountId, - call: &Self::Call, - _info: &DispatchInfoOf, - _len: usize, - ) -> TransactionValidity { - if let Some(local_call) = call.is_sub_type() { - if let Call::attest { statement: attested_statement } = local_call { - let signer = Preclaims::::get(who) - .ok_or(InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()))?; - if let Some(s) = Signing::::get(signer) { - let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into()); - ensure!(&attested_statement[..] == s.to_text(), e); - } - } - } - Ok(ValidTransaction::default()) + fn get_signer_multi_address( + signer: Option, + signature: MultiAddressSignature, + data: Vec, + statement: Vec, + ) -> Result> { + let signer = match signature { + MultiAddressSignature::EVM(ethereum_signature) => + Self::eth_recover(ðereum_signature, &data, &statement[..]) + .ok_or(Error::::InvalidEthereumSignature)?, + MultiAddressSignature::Native(sr25519_signature) => { + ensure!(!signer.is_none(), Error::::InvalidNativeAccount); + Self::sr25519_recover(signer.unwrap(), &sr25519_signature, &data, &statement[..]) + .ok_or(Error::::InvalidNativeSignature)? + }, + }; + + Ok(signer) + } + + /// Convert a MultiAddress to an AccountId + fn convert_multi_address_to_account_id(dest: MultiAddress) -> Result> { + let account = match dest { + MultiAddress::EVM(a) => T::AddressMapping::into_account_id(H160::from(a)), + MultiAddress::Native(a) => match Decode::decode(&mut a.encode().as_slice()) { + Ok(a) => a, + Err(_) => return Err(Error::::InvalidNativeAccount), + }, + }; + + Ok(account) } } @@ -742,16 +669,16 @@ mod secp_utils { pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey { libsecp256k1::PublicKey::from_secret_key(secret) } - pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress { + pub fn eth(secret: &libsecp256k1::SecretKey) -> MultiAddress { let mut res = EthereumAddress::default(); res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]); - res + MultiAddress::EVM(res) } pub fn sig( secret: &libsecp256k1::SecretKey, what: &[u8], extra: &[u8], - ) -> EcdsaSignature { + ) -> MultiAddressSignature { let msg = keccak_256(&>::ethereum_signable_message( &to_ascii_hex(what)[..], extra, @@ -760,1051 +687,40 @@ mod secp_utils { let mut r = [0u8; 65]; r[0..64].copy_from_slice(&sig.serialize()[..]); r[64] = recovery_id.serialize(); - EcdsaSignature(r) + MultiAddressSignature::EVM(EcdsaSignature(r)) } } -#[cfg(test)] -mod tests { +#[cfg(any(test, feature = "runtime-benchmarks"))] +mod sr25519_utils { use super::*; - use frame_support::pallet_prelude::DispatchError; - use hex_literal::hex; - use parity_scale_codec::Encode; - use secp_utils::*; - use sp_core::H256; - use sp_runtime::TokenError::Frozen; - use sp_std::convert::TryFrom; - // The testing primitives are very useful for avoiding having to work with signatures - // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. - use crate::{pallet as pallet_ecdsa_claims, pallet::Call as ClaimsCall}; - use frame_support::{ - assert_err, assert_noop, assert_ok, - dispatch::{DispatchError::BadOrigin, GetDispatchInfo, Pays}, - ord_parameter_types, parameter_types, - traits::{ExistenceRequirement, OnFinalize, OnInitialize, WithdrawReasons}, - }; - use pallet_balances; - use sp_runtime::{ - traits::{BlakeTwo256, Identity, IdentityLookup}, - transaction_validity::TransactionLongevity, - BuildStorage, - }; - - type Block = frame_system::mocking::MockBlock; - - frame_support::construct_runtime!( - pub enum Test - { - System: frame_system, - Balances: pallet_balances, - Vesting: pallet_vesting, - Claims: pallet_ecdsa_claims, - } - ); - - parameter_types! { - pub const BlockHashCount: u32 = 250; - } - impl frame_system::Config for Test { - type BaseCallFilter = frame_support::traits::Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Block = Block; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Nonce = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - } - - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - - impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type MaxHolds = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - } - - parameter_types! { - pub const MinVestedTransfer: u64 = 1; - pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = - WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); - } - - impl pallet_vesting::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type BlockNumberToBalance = Identity; - type MinVestedTransfer = MinVestedTransfer; - type WeightInfo = (); - type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - const MAX_VESTING_SCHEDULES: u32 = 28; - } - - parameter_types! { - pub Prefix: &'static [u8] = b"Pay RUSTs to the TEST account:"; - } - ord_parameter_types! { - pub const Six: u64 = 6; - } - - impl Config for Test { - type RuntimeEvent = RuntimeEvent; - type VestingSchedule = Vesting; - type ForceOrigin = frame_system::EnsureRoot; - type Prefix = Prefix; - type MoveClaimOrigin = frame_system::EnsureSignedBy; - type WeightInfo = TestWeightInfo; - } - - pub fn run_to_block(n: u64) { - while System::block_number() < n { - Claims::on_finalize(System::block_number()); - Balances::on_finalize(System::block_number()); - System::on_finalize(System::block_number()); - System::set_block_number(System::block_number() + 1); - System::on_initialize(System::block_number()); - } - } - - fn alice() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Alice")).unwrap() - } - fn bob() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Bob")).unwrap() - } - fn dave() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Dave")).unwrap() - } - fn eve() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Eve")).unwrap() - } - fn frank() -> libsecp256k1::SecretKey { - libsecp256k1::SecretKey::parse(&keccak_256(b"Frank")).unwrap() - } - - // This function basically just builds a genesis storage key/value store according to - // our desired mockup. - pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - // We use default for brevity, but you can configure as desired if needed. - pallet_balances::GenesisConfig::::default() - .assimilate_storage(&mut t) - .unwrap(); - pallet_ecdsa_claims::GenesisConfig:: { - claims: vec![ - (eth(&alice()), 100, None, None), - (eth(&dave()), 200, None, Some(StatementKind::Regular)), - (eth(&eve()), 300, Some(42), Some(StatementKind::Saft)), - (eth(&frank()), 400, Some(43), None), - ], - vesting: vec![(eth(&alice()), (50, 10, 1))], - expiry: None, - } - .assimilate_storage(&mut t) - .unwrap(); - t.into() - } - - fn total_claims() -> u64 { - 100 + 200 + 300 + 400 - } - - #[test] - fn basic_setup_works() { - new_test_ext().execute_with(|| { - assert_eq!(Claims::total(), total_claims()); - assert_eq!(Claims::claims(ð(&alice())), Some(100)); - assert_eq!(Claims::claims(ð(&dave())), Some(200)); - assert_eq!(Claims::claims(ð(&eve())), Some(300)); - assert_eq!(Claims::claims(ð(&frank())), Some(400)); - assert_eq!(Claims::claims(&EthereumAddress::default()), None); - assert_eq!(Claims::vesting(ð(&alice())), Some((50, 10, 1))); - }); - } - - #[test] - fn serde_works() { - let x = EthereumAddress(hex!["0123456789abcdef0123456789abcdef01234567"]); - let y = serde_json::to_string(&x).unwrap(); - assert_eq!(y, "\"0x0123456789abcdef0123456789abcdef01234567\""); - let z: EthereumAddress = serde_json::from_str(&y).unwrap(); - assert_eq!(x, z); - } - - #[test] - fn claiming_works() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - )); - assert_eq!(Balances::free_balance(&42), 100); - assert_eq!(Vesting::vesting_balance(&42), Some(50)); - assert_eq!(Claims::total(), total_claims() - 100); - }); - } - - #[test] - fn basic_claim_moving_works() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::move_claim(RuntimeOrigin::signed(1), eth(&alice()), eth(&bob()), None), - BadOrigin - ); - assert_ok!(Claims::move_claim( - RuntimeOrigin::signed(6), - eth(&alice()), - eth(&bob()), - None - )); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim - ); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&bob(), &42u64.encode(), &[][..]) - )); - assert_eq!(Balances::free_balance(&42), 100); - assert_eq!(Vesting::vesting_balance(&42), Some(50)); - assert_eq!(Claims::total(), total_claims() - 100); - }); - } - - #[test] - fn claim_attest_moving_works() { - new_test_ext().execute_with(|| { - assert_ok!(Claims::move_claim( - RuntimeOrigin::signed(6), - eth(&dave()), - eth(&bob()), - None - )); - let s = sig::(&bob(), &42u64.encode(), StatementKind::Regular.to_text()); - assert_ok!(Claims::claim_attest( - RuntimeOrigin::none(), - 42, - s, - StatementKind::Regular.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&42), 200); - }); - } - - #[test] - fn attest_moving_works() { - new_test_ext().execute_with(|| { - assert_ok!(Claims::move_claim( - RuntimeOrigin::signed(6), - eth(&eve()), - eth(&bob()), - Some(42) - )); - assert_ok!(Claims::attest( - RuntimeOrigin::signed(42), - StatementKind::Saft.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&42), 300); - }); - } + use frame_support::assert_ok; + use schnorrkel::Signature; + use sp_core::{sr25519, Pair}; - #[test] - fn claiming_does_not_bypass_signing() { - new_test_ext().execute_with(|| { - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - )); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&dave(), &42u64.encode(), &[][..]) - ), - Error::::InvalidStatement, - ); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&eve(), &42u64.encode(), &[][..]) - ), - Error::::InvalidStatement, - ); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&frank(), &42u64.encode(), &[][..]) - )); - }); - } - - #[test] - fn attest_claiming_works() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - let s = sig::(&dave(), &42u64.encode(), StatementKind::Saft.to_text()); - let r = Claims::claim_attest( - RuntimeOrigin::none(), - 42, - s.clone(), - StatementKind::Saft.to_text().to_vec(), - ); - assert_noop!(r, Error::::InvalidStatement); - - let r = Claims::claim_attest( - RuntimeOrigin::none(), - 42, - s, - StatementKind::Regular.to_text().to_vec(), - ); - assert_noop!(r, Error::::SignerHasNoClaim); - // ^^^ we use ecdsa_recover, so an invalid signature just results in a random signer id - // being recovered, which realistically will never have a claim. - - let s = sig::(&dave(), &42u64.encode(), StatementKind::Regular.to_text()); - assert_ok!(Claims::claim_attest( - RuntimeOrigin::none(), - 42, - s, - StatementKind::Regular.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&42), 200); - assert_eq!(Claims::total(), total_claims() - 200); - - let s = sig::(&dave(), &42u64.encode(), StatementKind::Regular.to_text()); - let r = Claims::claim_attest( - RuntimeOrigin::none(), - 42, - s, - StatementKind::Regular.to_text().to_vec(), - ); - assert_noop!(r, Error::::SignerHasNoClaim); - }); - } - - #[test] - fn attesting_works() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::attest(RuntimeOrigin::signed(69), StatementKind::Saft.to_text().to_vec()), - Error::::SenderHasNoClaim - ); - assert_noop!( - Claims::attest( - RuntimeOrigin::signed(42), - StatementKind::Regular.to_text().to_vec() - ), - Error::::InvalidStatement - ); - assert_ok!(Claims::attest( - RuntimeOrigin::signed(42), - StatementKind::Saft.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&42), 300); - assert_eq!(Claims::total(), total_claims() - 300); - }); - } - - #[test] - fn claim_cannot_clobber_preclaim() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - // Alice's claim is 100 - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - )); - assert_eq!(Balances::free_balance(&42), 100); - // Eve's claim is 300 through Account 42 - assert_ok!(Claims::attest( - RuntimeOrigin::signed(42), - StatementKind::Saft.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&42), 100 + 300); - assert_eq!(Claims::total(), total_claims() - 400); - }); - } - - #[test] - fn valid_attest_transactions_are_free() { - new_test_ext().execute_with(|| { - let p = PrevalidateAttests::::new(); - let c = RuntimeCall::Claims(ClaimsCall::attest { - statement: StatementKind::Saft.to_text().to_vec(), - }); - let di = c.get_dispatch_info(); - assert_eq!(di.pays_fee, Pays::No); - let r = p.validate(&42, &c, &di, 20); - assert_eq!(r, TransactionValidity::Ok(ValidTransaction::default())); - }); - } - - #[test] - fn invalid_attest_transactions_are_recognized() { - new_test_ext().execute_with(|| { - let p = PrevalidateAttests::::new(); - let c = RuntimeCall::Claims(ClaimsCall::attest { - statement: StatementKind::Regular.to_text().to_vec(), - }); - let di = c.get_dispatch_info(); - let r = p.validate(&42, &c, &di, 20); - assert!(r.is_err()); - let c = RuntimeCall::Claims(ClaimsCall::attest { - statement: StatementKind::Saft.to_text().to_vec(), - }); - let di = c.get_dispatch_info(); - let r = p.validate(&69, &c, &di, 20); - assert!(r.is_err()); - }); - } - - #[test] - fn cannot_bypass_attest_claiming() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - let s = sig::(&dave(), &42u64.encode(), &[]); - let r = Claims::claim(RuntimeOrigin::none(), 42, s.clone()); - assert_noop!(r, Error::::InvalidStatement); - }); - } - - #[test] - fn add_claim_works() { - new_test_ext().execute_with(|| { - assert_noop!( - Claims::mint_claim(RuntimeOrigin::signed(42), eth(&bob()), 200, None, None), - sp_runtime::traits::BadOrigin, - ); - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 69, - sig::(&bob(), &69u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim, - ); - assert_ok!(Claims::mint_claim(RuntimeOrigin::root(), eth(&bob()), 200, None, None)); - assert_eq!(Claims::total(), total_claims() + 200); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 69, - sig::(&bob(), &69u64.encode(), &[][..]) - )); - assert_eq!(Balances::free_balance(&69), 200); - assert_eq!(Vesting::vesting_balance(&69), None); - assert_eq!(Claims::total(), total_claims()); - }); - } - - #[test] - fn add_claim_with_vesting_works() { - new_test_ext().execute_with(|| { - assert_noop!( - Claims::mint_claim( - RuntimeOrigin::signed(42), - eth(&bob()), - 200, - Some((50, 10, 1)), - None - ), - sp_runtime::traits::BadOrigin, - ); - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 69, - sig::(&bob(), &69u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim, - ); - assert_ok!(Claims::mint_claim( - RuntimeOrigin::root(), - eth(&bob()), - 200, - Some((50, 10, 1)), - None - )); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 69, - sig::(&bob(), &69u64.encode(), &[][..]) - )); - assert_eq!(Balances::free_balance(&69), 200); - assert_eq!(Vesting::vesting_balance(&69), Some(50)); - - // Make sure we can not transfer the vested balance. - assert_err!( - >::transfer( - &69, - &80, - 180, - ExistenceRequirement::AllowDeath - ), - DispatchError::Token(Frozen), - ); - }); - } - - #[test] - fn add_claim_with_statement_works() { - new_test_ext().execute_with(|| { - assert_noop!( - Claims::mint_claim( - RuntimeOrigin::signed(42), - eth(&bob()), - 200, - None, - Some(StatementKind::Regular) - ), - sp_runtime::traits::BadOrigin, - ); - assert_eq!(Balances::free_balance(42), 0); - let signature = sig::(&bob(), &69u64.encode(), StatementKind::Regular.to_text()); - assert_noop!( - Claims::claim_attest( - RuntimeOrigin::none(), - 69, - signature.clone(), - StatementKind::Regular.to_text().to_vec() - ), - Error::::SignerHasNoClaim - ); - assert_ok!(Claims::mint_claim( - RuntimeOrigin::root(), - eth(&bob()), - 200, - None, - Some(StatementKind::Regular) - )); - assert_noop!( - Claims::claim_attest(RuntimeOrigin::none(), 69, signature.clone(), vec![],), - Error::::SignerHasNoClaim - ); - assert_ok!(Claims::claim_attest( - RuntimeOrigin::none(), - 69, - signature.clone(), - StatementKind::Regular.to_text().to_vec() - )); - assert_eq!(Balances::free_balance(&69), 200); - }); - } - - #[test] - fn origin_signed_claiming_fail() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_err!( - Claims::claim( - RuntimeOrigin::signed(42), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - ), - sp_runtime::traits::BadOrigin, - ); - }); - } - - #[test] - fn double_claiming_doesnt_work() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - )); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim - ); - }); - } - - #[test] - fn claiming_while_vested_doesnt_work() { - new_test_ext().execute_with(|| { - CurrencyOf::::make_free_balance_be(&69, total_claims()); - assert_eq!(Balances::free_balance(69), total_claims()); - // A user is already vested - assert_ok!(::VestingSchedule::add_vesting_schedule( - &69, - total_claims(), - 100, - 10 - )); - assert_ok!(Claims::mint_claim( - RuntimeOrigin::root(), - eth(&bob()), - 200, - Some((50, 10, 1)), - None - )); - // New total - assert_eq!(Claims::total(), total_claims() + 200); - - // They should not be able to claim - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 69, - sig::(&bob(), &69u64.encode(), &[][..]) - ), - Error::::VestedBalanceExists, - ); - }); - } - - #[test] - fn non_sender_sig_doesnt_work() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &69u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim - ); - }); - } - - #[test] - fn non_claimant_doesnt_work() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&bob(), &69u64.encode(), &[][..]) - ), - Error::::SignerHasNoClaim - ); - }); - } - - #[test] - fn real_eth_sig_works() { - new_test_ext().execute_with(|| { - // "Pay RUSTs to the TEST account:2a00000000000000" - let sig = hex!["444023e89b67e67c0562ed0305d252a5dd12b2af5ac51d6d3cb69a0b486bc4b3191401802dc29d26d586221f7256cd3329fe82174bdf659baea149a40e1c495d1c"]; - let sig = EcdsaSignature(sig); - let who = 42u64.using_encoded(to_ascii_hex); - let signer = Claims::eth_recover(&sig, &who, &[][..]).unwrap(); - assert_eq!(signer.0, hex!["6d31165d5d932d571f3b44695653b46dcc327e84"]); - }); - } - - #[test] - fn validate_unsigned_works() { - use sp_runtime::traits::ValidateUnsigned; - let source = sp_runtime::transaction_validity::TransactionSource::External; - - new_test_ext().execute_with(|| { - assert_eq!( - >::validate_unsigned( - source, - &ClaimsCall::claim { - dest: 1, - ethereum_signature: sig::(&alice(), &1u64.encode(), &[][..]) - } - ), - Ok(ValidTransaction { - priority: 100, - requires: vec![], - provides: vec![("claims", eth(&alice())).encode()], - longevity: TransactionLongevity::max_value(), - propagate: true, - }) - ); - assert_eq!( - >::validate_unsigned( - source, - &ClaimsCall::claim { dest: 0, ethereum_signature: EcdsaSignature([0; 65]) } - ), - InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(), - ); - assert_eq!( - >::validate_unsigned( - source, - &ClaimsCall::claim { - dest: 1, - ethereum_signature: sig::(&bob(), &1u64.encode(), &[][..]) - } - ), - InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), - ); - let s = sig::(&dave(), &1u64.encode(), StatementKind::Regular.to_text()); - let call = ClaimsCall::claim_attest { - dest: 1, - ethereum_signature: s, - statement: StatementKind::Regular.to_text().to_vec(), - }; - assert_eq!( - >::validate_unsigned(source, &call), - Ok(ValidTransaction { - priority: 100, - requires: vec![], - provides: vec![("claims", eth(&dave())).encode()], - longevity: TransactionLongevity::max_value(), - propagate: true, - }) - ); - assert_eq!( - >::validate_unsigned( - source, - &ClaimsCall::claim_attest { - dest: 1, - ethereum_signature: EcdsaSignature([0; 65]), - statement: StatementKind::Regular.to_text().to_vec() - } - ), - InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(), - ); - - let s = sig::(&bob(), &1u64.encode(), StatementKind::Regular.to_text()); - let call = ClaimsCall::claim_attest { - dest: 1, - ethereum_signature: s, - statement: StatementKind::Regular.to_text().to_vec(), - }; - assert_eq!( - >::validate_unsigned(source, &call), - InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), - ); - - let s = sig::(&dave(), &1u64.encode(), StatementKind::Saft.to_text()); - let call = ClaimsCall::claim_attest { - dest: 1, - ethereum_signature: s, - statement: StatementKind::Regular.to_text().to_vec(), - }; - assert_eq!( - >::validate_unsigned(source, &call), - InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), - ); - - let s = sig::(&dave(), &1u64.encode(), StatementKind::Saft.to_text()); - let call = ClaimsCall::claim_attest { - dest: 1, - ethereum_signature: s, - statement: StatementKind::Saft.to_text().to_vec(), - }; - assert_eq!( - >::validate_unsigned(source, &call), - InvalidTransaction::Custom(ValidityError::InvalidStatement.into()).into(), - ); - }); + #[allow(dead_code)] + pub fn public(pair: &sr25519::Pair) -> sr25519::Public { + pair.public() } - #[test] - fn test_unclaimed_returned_to_destination() { - new_test_ext().execute_with(|| { - let original_total_claims = Total::::get(); - let claim_of_alice = 100; - assert_ok!(Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&alice(), &42u64.encode(), &[][..]) - )); - assert_eq!(Total::::get(), original_total_claims - claim_of_alice); - - // force set the expiry config - assert_ok!(Claims::force_set_expiry_config(RuntimeOrigin::root(), 5, 100)); - - // run to after expiry block - run_to_block(7); - assert_eq!(Total::::get(), 0); - // the dest account should receive the remaining pot balance - assert_eq!(Balances::free_balance(100), original_total_claims - claim_of_alice); - - // all further claims should fail with PotUnderflow error since the funds have been - // emptied - assert_noop!( - Claims::claim( - RuntimeOrigin::none(), - 42, - sig::(&frank(), &42u64.encode(), &[][..]) - ), - Error::::PotUnderflow - ); - }); - } -} - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarking { - use super::*; - use crate::claims::Call; - use frame_benchmarking::{account, benchmarks}; - use frame_support::dispatch::UnfilteredDispatchable; - use frame_system::RawOrigin; - use secp_utils::*; - use sp_runtime::{traits::ValidateUnsigned, DispatchResult}; - - const SEED: u32 = 0; - - const MAX_CLAIMS: u32 = 10_000; - const VALUE: u32 = 1_000_000; - - fn create_claim(input: u32) -> DispatchResult { - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&input.encode())).unwrap(); - let eth_address = eth(&secret_key); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - super::Pallet::::mint_claim( - RawOrigin::Root.into(), - eth_address, - VALUE.into(), - vesting, - None, - )?; - Ok(()) + pub fn sub(pair: &sr25519::Pair) -> MultiAddress { + MultiAddress::Native(pair.public().into()) } - fn create_claim_attest(input: u32) -> DispatchResult { - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&input.encode())).unwrap(); - let eth_address = eth(&secret_key); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - super::Pallet::::mint_claim( - RawOrigin::Root.into(), - eth_address, - VALUE.into(), - vesting, - Some(Default::default()), - )?; - Ok(()) - } - - benchmarks! { - // Benchmark `claim` including `validate_unsigned` logic. - claim { - let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { - create_claim::(c)?; - create_claim_attest::(u32::MAX - c)?; - } - - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&c.encode())).unwrap(); - let eth_address = eth(&secret_key); - let account: T::AccountId = account("user", c, SEED); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - let signature = sig::(&secret_key, &account.encode(), &[][..]); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, None)?; - assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); - let source = sp_runtime::transaction_validity::TransactionSource::External; - let call_enc = Call::::claim { - dest: account.clone(), - ethereum_signature: signature.clone() - }.encode(); - }: { - let call = as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct"); - super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; - call.dispatch_bypass_filter(RawOrigin::None.into())?; - } - verify { - assert_eq!(Claims::::get(eth_address), None); - } - - // Benchmark `mint_claim` when there already exists `c` claims in storage. - mint_claim { - let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { - create_claim::(c)?; - create_claim_attest::(u32::MAX - c)?; - } - - let eth_address = account("eth_address", 0, SEED); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - let statement = StatementKind::Regular; - }: _(RawOrigin::Root, eth_address, VALUE.into(), vesting, Some(statement)) - verify { - assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); - } - - // Benchmark `claim_attest` including `validate_unsigned` logic. - claim_attest { - let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { - create_claim::(c)?; - create_claim_attest::(u32::MAX - c)?; - } - - // Crate signature - let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); - let eth_address = eth(&secret_key); - let account: T::AccountId = account("user", c, SEED); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - let statement = StatementKind::Regular; - let signature = sig::(&secret_key, &account.encode(), statement.to_text()); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; - assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); - let call_enc = Call::::claim_attest { - dest: account.clone(), - ethereum_signature: signature.clone(), - statement: StatementKind::Regular.to_text().to_vec() - }.encode(); - let source = sp_runtime::transaction_validity::TransactionSource::External; - }: { - let call = as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct"); - super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; - call.dispatch_bypass_filter(RawOrigin::None.into())?; - } - verify { - assert_eq!(Claims::::get(eth_address), None); - } - - // Benchmark `attest` including prevalidate logic. - attest { - let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { - create_claim::(c)?; - create_claim_attest::(u32::MAX - c)?; - } - - let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); - let eth_address = eth(&secret_key); - let account: T::AccountId = account("user", c, SEED); - let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); - let statement = StatementKind::Regular; - let signature = sig::(&secret_key, &account.encode(), statement.to_text()); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; - Preclaims::::insert(&account, eth_address); - assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); - - let call = super::Call::::attest { statement: StatementKind::Regular.to_text().to_vec() }; - // We have to copy the validate statement here because of trait issues... :( - let validate = |who: &T::AccountId, call: &super::Call| -> DispatchResult { - if let Call::attest{ statement: attested_statement } = call { - let signer = Preclaims::::get(who).ok_or("signer has no claim")?; - if let Some(s) = Signing::::get(signer) { - ensure!(&attested_statement[..] == s.to_text(), "invalid statement"); - } - } - Ok(()) - }; - let call_enc = call.encode(); - }: { - let call = as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct"); - validate(&account, &call)?; - call.dispatch_bypass_filter(RawOrigin::Signed(account).into())?; - } - verify { - assert_eq!(Claims::::get(eth_address), None); - } - - move_claim { - let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { - create_claim::(c)?; - create_claim_attest::(u32::MAX - c)?; - } - - let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); - let eth_address = eth(&secret_key); - - let new_secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&(u32::MAX/2).encode())).unwrap(); - let new_eth_address = eth(&new_secret_key); - - let account: T::AccountId = account("user", c, SEED); - Preclaims::::insert(&account, eth_address); - - assert!(Claims::::contains_key(eth_address)); - assert!(!Claims::::contains_key(new_eth_address)); - }: _(RawOrigin::Root, eth_address, new_eth_address, Some(account)) - verify { - assert!(!Claims::::contains_key(eth_address)); - assert!(Claims::::contains_key(new_eth_address)); - } - - // Benchmark the time it takes to do `repeat` number of keccak256 hashes - #[extra] - keccak256 { - let i in 0 .. 10_000; - let bytes = (i).encode(); - }: { - for index in 0 .. i { - let _hash = keccak_256(&bytes); - } - } - - // Benchmark the time it takes to do `repeat` number of `eth_recover` - #[extra] - eth_recover { - let i in 0 .. 1_000; - // Crate signature - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&i.encode())).unwrap(); - let account: T::AccountId = account("user", i, SEED); - let signature = sig::(&secret_key, &account.encode(), &[][..]); - let data = account.using_encoded(to_ascii_hex); - let extra = StatementKind::default().to_text(); - }: { - for _ in 0 .. i { - assert!(super::Pallet::::eth_recover(&signature, &data, extra).is_some()); - } - } - - impl_benchmark_test_suite!( - Pallet, - crate::claims::tests::new_test_ext(), - crate::claims::tests::Test, - ); + pub fn sig( + pair: &sr25519::Pair, + what: &[u8], + extra: &[u8], + ) -> MultiAddressSignature { + let msg = keccak_256(&>::polkadotjs_signable_message( + &to_ascii_hex(what)[..], + extra, + )); + let sig = pair.sign(&msg); + let pk = schnorrkel::PublicKey::from_bytes(&pair.public().0).unwrap(); + let signature = Signature::from_bytes(&sig.0).unwrap(); + let res = pk.verify_simple(b"substrate", &msg, &signature); + assert_ok!(res); + MultiAddressSignature::Native(Sr25519Signature(sig)) } } diff --git a/pallets/claims/src/mock.rs b/pallets/claims/src/mock.rs new file mode 100644 index 000000000..faec7962e --- /dev/null +++ b/pallets/claims/src/mock.rs @@ -0,0 +1,174 @@ +use super::*; +use pallet_evm::HashedAddressMapping; +use secp_utils::*; +use sp_core::{sr25519, Pair, H256}; +use sp_std::convert::TryFrom; +// The testing primitives are very useful for avoiding having to work with signatures +// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. +use crate::{pallet as pallet_airdrop_claims, sr25519_utils::sub}; +use frame_support::{ + ord_parameter_types, parameter_types, + traits::{OnFinalize, OnInitialize, WithdrawReasons}, +}; +use pallet_balances; +use sp_runtime::{ + traits::{BlakeTwo256, Identity, IdentityLookup}, + AccountId32, BuildStorage, +}; + +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + VestingPallet: pallet_vesting, + ClaimsPallet: pallet_airdrop_claims, + } +); + +parameter_types! { + pub const BlockHashCount: u32 = 250; +} +impl frame_system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Block = Block; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId32; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +parameter_types! { + pub const ExistentialDeposit: u64 = 1; +} + +impl pallet_balances::Config for Test { + type Balance = u64; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type WeightInfo = (); + type RuntimeHoldReason = RuntimeHoldReason; + type MaxHolds = (); + type FreezeIdentifier = (); + type MaxFreezes = (); +} + +parameter_types! { + pub const MinVestedTransfer: u64 = 1; + pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = + WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); +} + +impl pallet_vesting::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type BlockNumberToBalance = Identity; + type MinVestedTransfer = MinVestedTransfer; + type WeightInfo = (); + type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; + const MAX_VESTING_SCHEDULES: u32 = 28; +} + +parameter_types! { + pub Prefix: &'static [u8] = b"Pay RUSTs to the TEST account:"; +} +ord_parameter_types! { + pub const Six: AccountId32 = get_multi_address_account_id(6).to_account_id_32(); +} + +impl Config for Test { + type RuntimeEvent = RuntimeEvent; + type VestingSchedule = VestingPallet; + type ForceOrigin = frame_system::EnsureRoot; + type AddressMapping = HashedAddressMapping; + type Prefix = Prefix; + type MoveClaimOrigin = frame_system::EnsureSignedBy; + type WeightInfo = TestWeightInfo; +} + +pub fn run_to_block(n: u64) { + while System::block_number() < n { + ClaimsPallet::on_finalize(System::block_number()); + Balances::on_finalize(System::block_number()); + System::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + } +} + +pub fn alice() -> libsecp256k1::SecretKey { + libsecp256k1::SecretKey::parse(&keccak_256(b"Alice")).unwrap() +} +pub fn bob() -> libsecp256k1::SecretKey { + libsecp256k1::SecretKey::parse(&keccak_256(b"Bob")).unwrap() +} +pub fn dave() -> libsecp256k1::SecretKey { + libsecp256k1::SecretKey::parse(&keccak_256(b"Dave")).unwrap() +} +pub fn eve() -> libsecp256k1::SecretKey { + libsecp256k1::SecretKey::parse(&keccak_256(b"Eve")).unwrap() +} +pub fn frank() -> libsecp256k1::SecretKey { + libsecp256k1::SecretKey::parse(&keccak_256(b"Frank")).unwrap() +} + +pub fn get_multi_address_account_id(id: u8) -> MultiAddress { + MultiAddress::Native(AccountId32::new([id; 32])) +} + +pub fn alice_sr25519() -> sr25519::Pair { + sr25519::Pair::from_string(&format!("//Alice"), None).expect("static values are valid; qed") +} + +pub fn bob_sr25519() -> sr25519::Pair { + sr25519::Pair::from_string(&format!("//Bob"), None).expect("static values are valid; qed") +} + +// This function basically just builds a genesis storage key/value store according to +// our desired mockup. +pub fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + // We use default for brevity, but you can configure as desired if needed. + pallet_balances::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); + pallet_airdrop_claims::GenesisConfig:: { + claims: vec![ + (eth(&alice()), 100, None), + (eth(&dave()), 200, Some(StatementKind::Regular)), + (eth(&eve()), 300, Some(StatementKind::Safe)), + (eth(&frank()), 400, None), + (sub(&alice_sr25519()), 500, None), + (sub(&bob_sr25519()), 600, None), + ], + vesting: vec![(eth(&alice()), (50, 10, 1))], + expiry: None, + } + .assimilate_storage(&mut t) + .unwrap(); + t.into() +} diff --git a/pallets/claims/src/tests.rs b/pallets/claims/src/tests.rs new file mode 100644 index 000000000..4da9a833e --- /dev/null +++ b/pallets/claims/src/tests.rs @@ -0,0 +1,841 @@ +use super::*; +use frame_support::pallet_prelude::DispatchError; +use hex_literal::hex; +use parity_scale_codec::Encode; +use secp_utils::*; +use sp_runtime::TokenError::Frozen; + +// The testing primitives are very useful for avoiding having to work with signatures +// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. +use crate::{mock::new_test_ext, pallet::Call as ClaimsCall}; +use frame_support::{ + assert_err, assert_noop, assert_ok, dispatch::DispatchError::BadOrigin, + traits::ExistenceRequirement, +}; +use sp_runtime::transaction_validity::TransactionLongevity; + +use crate::mock::*; + +fn total_claims() -> u64 { + 100 + 200 + 300 + 400 + 500 + 600 +} + +#[test] +fn basic_setup_works() { + new_test_ext().execute_with(|| { + assert_eq!(ClaimsPallet::total(), total_claims()); + assert_eq!(ClaimsPallet::claims(ð(&alice())), Some(100)); + assert_eq!(ClaimsPallet::claims(ð(&dave())), Some(200)); + assert_eq!(ClaimsPallet::claims(ð(&eve())), Some(300)); + assert_eq!(ClaimsPallet::claims(ð(&frank())), Some(400)); + assert_eq!(ClaimsPallet::claims(&MultiAddress::EVM(EthereumAddress::default())), None); + assert_eq!(ClaimsPallet::vesting(ð(&alice())), Some((50, 10, 1))); + }); +} + +#[test] +fn eth_signature_works() { + new_test_ext().execute_with(|| { + let data = Some(get_multi_address_account_id(42)).encode(); + let s = sig::(&alice(), &data, &[][..]); + let sig = match s { + MultiAddressSignature::EVM(s) => s, + _ => panic!("should be evm signature"), + }; + + assert_eq!( + ClaimsPallet::eth_recover(&sig, &to_ascii_hex(&data), &[][..]), + Some(eth(&alice())) + ); + assert!( + ClaimsPallet::eth_recover( + &sig, + &Some(get_multi_address_account_id(43)).encode(), + &[][..] + ) != Some(eth(&alice())) + ); + }); +} + +#[test] +fn serde_works() { + let x = EthereumAddress(hex!["0123456789abcdef0123456789abcdef01234567"]); + let y = serde_json::to_string(&x).unwrap(); + assert_eq!(y, "\"0x0123456789abcdef0123456789abcdef01234567\""); + let z: EthereumAddress = serde_json::from_str(&y).unwrap(); + assert_eq!(x, z); +} + +#[test] +fn claiming_works() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + assert_eq!( + Balances::free_balance(&get_multi_address_account_id(42).to_account_id_32()), + 100 + ); + assert_eq!( + VestingPallet::vesting_balance(&get_multi_address_account_id(42).to_account_id_32()), + Some(50) + ); + assert_eq!(ClaimsPallet::total(), total_claims() - 100); + }); +} + +#[test] +fn basic_claim_moving_works() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_noop!( + ClaimsPallet::move_claim( + RuntimeOrigin::signed(get_multi_address_account_id(1).to_account_id_32()), + eth(&alice()), + eth(&bob()), + ), + BadOrigin + ); + assert_ok!(ClaimsPallet::move_claim( + RuntimeOrigin::signed(get_multi_address_account_id(6).to_account_id_32()), + eth(&alice()), + eth(&bob()), + )); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim + ); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + assert_eq!( + Balances::free_balance(&get_multi_address_account_id(42).to_account_id_32()), + 100 + ); + assert_eq!( + VestingPallet::vesting_balance(&get_multi_address_account_id(42).to_account_id_32()), + Some(50) + ); + assert_eq!(ClaimsPallet::total(), total_claims() - 100); + }); +} + +#[test] +fn claim_attest_moving_works() { + new_test_ext().execute_with(|| { + assert_ok!(ClaimsPallet::move_claim( + RuntimeOrigin::signed(get_multi_address_account_id(6).to_account_id_32()), + eth(&dave()), + eth(&bob()), + )); + let s = sig::( + &bob(), + &Some(get_multi_address_account_id(42)).encode(), + StatementKind::Regular.to_text(), + ); + assert_ok!(ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s, + StatementKind::Regular.to_text().to_vec() + )); + assert_eq!( + Balances::free_balance(&get_multi_address_account_id(42).to_account_id_32()), + 200 + ); + }); +} + +#[test] +fn claiming_does_not_bypass_signing() { + new_test_ext().execute_with(|| { + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&dave(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + Error::::InvalidStatement, + ); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&eve(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + Error::::InvalidStatement, + ); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&frank(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + }); +} + +#[test] +fn attest_claiming_works() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + let data = Some(get_multi_address_account_id(42)).encode(); + let s = sig::(&dave(), &data, StatementKind::Safe.to_text()); + let r = ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s.clone(), + StatementKind::Safe.to_text().to_vec(), + ); + assert_noop!(r, Error::::InvalidStatement); + + let r = ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s, + StatementKind::Regular.to_text().to_vec(), + ); + assert_noop!(r, Error::::SignerHasNoClaim); + // ^^^ we use ecdsa_recover, so an invalid signature just results in a random signer id + // being recovered, which realistically will never have a claim. + + let s = sig::( + &dave(), + &Some(get_multi_address_account_id(42)).encode(), + StatementKind::Regular.to_text(), + ); + assert_ok!(ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s, + StatementKind::Regular.to_text().to_vec() + )); + assert_eq!( + Balances::free_balance(&get_multi_address_account_id(42).to_account_id_32()), + 200 + ); + assert_eq!(ClaimsPallet::total(), total_claims() - 200); + + let s = sig::( + &dave(), + &Some(get_multi_address_account_id(42)).encode(), + StatementKind::Regular.to_text(), + ); + let r = ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s, + StatementKind::Regular.to_text().to_vec(), + ); + assert_noop!(r, Error::::SignerHasNoClaim); + }); +} + +#[test] +fn cannot_bypass_attest_claiming() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + let s = sig::(&dave(), &Some(get_multi_address_account_id(42)).encode(), &[]); + let r = ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + s.clone(), + ); + assert_noop!(r, Error::::InvalidStatement); + }); +} + +#[test] +fn add_claim_works() { + new_test_ext().execute_with(|| { + assert_noop!( + ClaimsPallet::mint_claim( + RuntimeOrigin::signed(get_multi_address_account_id(42).to_account_id_32()), + eth(&bob()), + 200, + None, + None + ), + sp_runtime::traits::BadOrigin, + ); + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim, + ); + assert_ok!(ClaimsPallet::mint_claim(RuntimeOrigin::root(), eth(&bob()), 200, None, None)); + assert_eq!(ClaimsPallet::total(), total_claims() + 200); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + )); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(69).to_account_id_32()), + 200 + ); + assert_eq!( + VestingPallet::vesting_balance(&get_multi_address_account_id(69).to_account_id_32()), + None + ); + assert_eq!(ClaimsPallet::total(), total_claims()); + }); +} + +#[test] +fn add_claim_with_vesting_works() { + new_test_ext().execute_with(|| { + assert_noop!( + ClaimsPallet::mint_claim( + RuntimeOrigin::signed(get_multi_address_account_id(42).to_account_id_32()), + eth(&bob()), + 200, + Some((50, 10, 1)), + None + ), + sp_runtime::traits::BadOrigin, + ); + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim, + ); + assert_ok!(ClaimsPallet::mint_claim( + RuntimeOrigin::root(), + eth(&bob()), + 200, + Some((50, 10, 1)), + None + )); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + )); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(69).to_account_id_32()), + 200 + ); + assert_eq!( + VestingPallet::vesting_balance(&get_multi_address_account_id(69).to_account_id_32()), + Some(50) + ); + + // Make sure we can not transfer the vested balance. + assert_err!( + >::transfer( + &get_multi_address_account_id(69).to_account_id_32(), + &get_multi_address_account_id(80).to_account_id_32(), + 180, + ExistenceRequirement::AllowDeath + ), + DispatchError::Token(Frozen), + ); + }); +} + +#[test] +fn add_claim_with_statement_works() { + new_test_ext().execute_with(|| { + assert_noop!( + ClaimsPallet::mint_claim( + RuntimeOrigin::signed(get_multi_address_account_id(42).to_account_id_32()), + eth(&bob()), + 200, + None, + Some(StatementKind::Regular) + ), + sp_runtime::traits::BadOrigin, + ); + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + let signature = sig::( + &bob(), + &Some(get_multi_address_account_id(69)).encode(), + StatementKind::Regular.to_text(), + ); + + assert_noop!( + ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + signature.clone(), + StatementKind::Regular.to_text().to_vec() + ), + Error::::SignerHasNoClaim + ); + assert_ok!(ClaimsPallet::mint_claim( + RuntimeOrigin::root(), + eth(&bob()), + 200, + None, + Some(StatementKind::Regular) + )); + assert_noop!( + ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + signature.clone(), + vec![], + ), + Error::::SignerHasNoClaim + ); + assert_ok!(ClaimsPallet::claim_attest( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + signature.clone(), + StatementKind::Regular.to_text().to_vec() + )); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(69).to_account_id_32()), + 200 + ); + }); +} + +#[test] +fn origin_signed_claiming_fail() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_err!( + ClaimsPallet::claim( + RuntimeOrigin::signed(get_multi_address_account_id(42).to_account_id_32()), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + sp_runtime::traits::BadOrigin, + ); + }); +} + +#[test] +fn double_claiming_doesnt_work() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim + ); + }); +} + +#[test] +fn claiming_while_vested_doesnt_work() { + new_test_ext().execute_with(|| { + CurrencyOf::::make_free_balance_be( + &get_multi_address_account_id(69).to_account_id_32(), + total_claims(), + ); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(69).to_account_id_32()), + total_claims() + ); + // A user is already vested + assert_ok!(::VestingSchedule::add_vesting_schedule( + &get_multi_address_account_id(69).to_account_id_32(), + total_claims(), + 100, + 10 + )); + assert_ok!(ClaimsPallet::mint_claim( + RuntimeOrigin::root(), + eth(&bob()), + 200, + Some((50, 10, 1)), + None + )); + // New total + assert_eq!(ClaimsPallet::total(), total_claims() + 200); + + // They should not be able to claim + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(69)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + ), + Error::::VestedBalanceExists, + ); + }); +} + +#[test] +fn non_sender_sig_doesnt_work() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim + ); + }); +} + +#[test] +fn non_claimant_doesnt_work() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), 0); + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&bob(), &Some(get_multi_address_account_id(69)).encode(), &[][..]) + ), + Error::::SignerHasNoClaim + ); + }); +} + +#[test] +fn real_eth_sig_works() { + new_test_ext().execute_with(|| { + // "Pay RUSTs to the TEST account:2a00000000000000" + let sig = hex!["444023e89b67e67c0562ed0305d252a5dd12b2af5ac51d6d3cb69a0b486bc4b3191401802dc29d26d586221f7256cd3329fe82174bdf659baea149a40e1c495d1c"]; + let sig = EcdsaSignature(sig); + let who = 42u64.using_encoded(to_ascii_hex); + let signer = ClaimsPallet::eth_recover(&sig, &who, &[][..]).unwrap(); + assert_eq!(signer.to_ethereum_address().unwrap().0, hex!["6d31165d5d932d571f3b44695653b46dcc327e84"]); + }); +} + +#[test] +fn validate_unsigned_works() { + use sp_runtime::traits::ValidateUnsigned; + let source = sp_runtime::transaction_validity::TransactionSource::External; + + new_test_ext().execute_with(|| { + assert_eq!( + >::validate_unsigned( + source, + &ClaimsCall::claim { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: sig::( + &alice(), + &Some(get_multi_address_account_id(1)).encode(), + &[][..] + ) + } + ), + Ok(ValidTransaction { + priority: 100, + requires: vec![], + provides: vec![("claims", eth(&alice())).encode()], + longevity: TransactionLongevity::max_value(), + propagate: true, + }) + ); + assert_eq!( + >::validate_unsigned( + source, + &ClaimsCall::claim { + dest: Some(get_multi_address_account_id(0)), + signer: None, + signature: MultiAddressSignature::EVM(EcdsaSignature([0; 65])) + } + ), + InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(), + ); + assert_eq!( + >::validate_unsigned( + source, + &ClaimsCall::claim { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: sig::( + &bob(), + &Some(get_multi_address_account_id(1)).encode(), + &[][..] + ) + } + ), + InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), + ); + let s = sig::( + &dave(), + &Some(get_multi_address_account_id(1)).encode(), + StatementKind::Regular.to_text(), + ); + let call = ClaimsCall::claim_attest { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: s, + statement: StatementKind::Regular.to_text().to_vec(), + }; + assert_eq!( + >::validate_unsigned(source, &call), + Ok(ValidTransaction { + priority: 100, + requires: vec![], + provides: vec![("claims", eth(&dave())).encode()], + longevity: TransactionLongevity::max_value(), + propagate: true, + }) + ); + assert_eq!( + >::validate_unsigned( + source, + &ClaimsCall::claim_attest { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: MultiAddressSignature::EVM(EcdsaSignature([0; 65])), + statement: StatementKind::Regular.to_text().to_vec() + } + ), + InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(), + ); + + let s = sig::( + &bob(), + &Some(get_multi_address_account_id(1)).encode(), + StatementKind::Regular.to_text(), + ); + let call = ClaimsCall::claim_attest { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: s, + statement: StatementKind::Regular.to_text().to_vec(), + }; + assert_eq!( + >::validate_unsigned(source, &call), + InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), + ); + + let s = sig::( + &dave(), + &Some(get_multi_address_account_id(1)).encode(), + StatementKind::Safe.to_text(), + ); + let call = ClaimsCall::claim_attest { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: s, + statement: StatementKind::Regular.to_text().to_vec(), + }; + assert_eq!( + >::validate_unsigned(source, &call), + InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), + ); + + let s = sig::( + &dave(), + &Some(get_multi_address_account_id(1)).encode(), + StatementKind::Safe.to_text(), + ); + let call = ClaimsCall::claim_attest { + dest: Some(get_multi_address_account_id(1)), + signer: None, + signature: s, + statement: StatementKind::Safe.to_text().to_vec(), + }; + assert_eq!( + >::validate_unsigned(source, &call), + InvalidTransaction::Custom(ValidityError::InvalidStatement.into()).into(), + ); + }); +} + +#[test] +fn test_unclaimed_returned_to_destination() { + new_test_ext().execute_with(|| { + let original_total_claims = Total::::get(); + let claim_of_alice = 100; + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&alice(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + )); + assert_eq!(Total::::get(), original_total_claims - claim_of_alice); + + // force set the expiry config + assert_ok!(ClaimsPallet::force_set_expiry_config( + RuntimeOrigin::root(), + 5, + get_multi_address_account_id(100) + )); + + // run to after expiry block + run_to_block(7); + assert_eq!(Total::::get(), 0); + // the dest account should receive the remaining pot balance + assert_eq!( + Balances::free_balance(get_multi_address_account_id(100).to_account_id_32()), + original_total_claims - claim_of_alice + ); + + // all further claims should fail with PotUnderflow error since the funds have been + // emptied + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sig::(&frank(), &Some(get_multi_address_account_id(42)).encode(), &[][..]) + ), + Error::::PotUnderflow + ); + }); +} + +#[test] +fn test_claim_from_substrate_address_to_evm() { + new_test_ext().execute_with(|| { + let original_total_claims = Total::::get(); + let claim_of_sub_alice = 500; + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + Some(sr25519_utils::sub(&alice_sr25519())), + sr25519_utils::sig::( + &alice_sr25519(), + &Some(get_multi_address_account_id(42)).encode(), + &[][..] + ) + )); + assert_eq!(Total::::get(), original_total_claims - claim_of_sub_alice); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), + 500 + ); + // Claim bob without providing signer value (needed for sr25519 signatures) + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + None, + sr25519_utils::sig::( + &bob_sr25519(), + &Some(get_multi_address_account_id(42)).encode(), + &[][..] + ) + ), + Error::::InvalidNativeAccount + ); + // force set the expiry config + assert_ok!(ClaimsPallet::force_set_expiry_config( + RuntimeOrigin::root(), + 5, + get_multi_address_account_id(100) + )); + + // run to after expiry block + run_to_block(7); + assert_eq!(Total::::get(), 0); + // the dest account should receive the remaining pot balance + assert_eq!( + Balances::free_balance(get_multi_address_account_id(100).to_account_id_32()), + original_total_claims - claim_of_sub_alice + ); + + // all further claims should fail with PotUnderflow error since the funds have been + // emptied + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + Some(sr25519_utils::sub(&bob_sr25519())), + sr25519_utils::sig::( + &bob_sr25519(), + &Some(get_multi_address_account_id(42)).encode(), + &[][..] + ) + ), + Error::::PotUnderflow + ); + }); +} + +#[test] +fn test_double_claim_fails_for_substrate_account() { + new_test_ext().execute_with(|| { + let original_total_claims = Total::::get(); + let claim_of_sub_alice = 500; + assert_ok!(ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + Some(sr25519_utils::sub(&alice_sr25519())), + sr25519_utils::sig::( + &alice_sr25519(), + &Some(get_multi_address_account_id(42)).encode(), + &[][..] + ) + )); + assert_eq!(Total::::get(), original_total_claims - claim_of_sub_alice); + assert_eq!( + Balances::free_balance(get_multi_address_account_id(42).to_account_id_32()), + 500 + ); + // Claim for Alice again and expect the proper error + assert_noop!( + ClaimsPallet::claim( + RuntimeOrigin::none(), + Some(get_multi_address_account_id(42)), + Some(sr25519_utils::sub(&alice_sr25519())), + sr25519_utils::sig::( + &alice_sr25519(), + &Some(get_multi_address_account_id(42)).encode(), + &[][..] + ) + ), + Error::::SignerHasNoClaim + ); + }); +} diff --git a/pallets/claims/src/utils/ethereum_address.rs b/pallets/claims/src/utils/ethereum_address.rs new file mode 100644 index 000000000..c8e8dfc6c --- /dev/null +++ b/pallets/claims/src/utils/ethereum_address.rs @@ -0,0 +1,63 @@ +use super::*; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account). +/// +/// This gets serialized to the 0x-prefixed hex representation. +#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] +pub struct EthereumAddress(pub [u8; 20]); + +impl Serialize for EthereumAddress { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]); + serializer.serialize_str(&format!("0x{}", hex)) + } +} + +impl<'de> Deserialize<'de> for EthereumAddress { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let base_string = String::deserialize(deserializer)?; + let offset = if base_string.starts_with("0x") { 2 } else { 0 }; + let s = &base_string[offset..]; + if s.len() != 40 { + Err(serde::de::Error::custom( + "Bad length of Ethereum address (should be 42 including '0x')", + ))?; + } + let raw: Vec = rustc_hex::FromHex::from_hex(s) + .map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?; + let mut r = Self::default(); + r.0.copy_from_slice(&raw); + Ok(r) + } +} + +impl From for H160 { + fn from(a: EthereumAddress) -> Self { + let mut r = Self::default(); + r.0.copy_from_slice(&a.0); + r + } +} + +#[derive(Clone, Copy, Eq, Encode, Decode, TypeInfo)] +pub struct EcdsaSignature(pub [u8; 65]); + +impl PartialEq for EcdsaSignature { + fn eq(&self, other: &Self) -> bool { + &self.0[..] == &other.0[..] + } +} + +impl sp_std::fmt::Debug for EcdsaSignature { + fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { + write!(f, "EcdsaSignature({:?})", &self.0[..]) + } +} diff --git a/pallets/claims/src/utils/mod.rs b/pallets/claims/src/utils/mod.rs new file mode 100644 index 000000000..e791612f3 --- /dev/null +++ b/pallets/claims/src/utils/mod.rs @@ -0,0 +1,48 @@ +use pallet_evm::{AddressMapping, HashedAddressMapping}; +use parity_scale_codec::{Decode, Encode}; +use scale_info::{ + prelude::{format, string::String}, + TypeInfo, +}; +use serde::{self, Deserialize, Serialize}; +use sp_core::{sr25519::Signature, H160}; +use sp_runtime::{traits::BlakeTwo256, AccountId32, RuntimeDebug}; +use sp_std::prelude::*; + +pub mod ethereum_address; + +use ethereum_address::{EcdsaSignature, EthereumAddress}; + +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, Serialize, Deserialize)] +pub enum MultiAddress { + /// Claimer is Ethereum address + EVM(EthereumAddress), + /// Claimer is Substrate address + Native(AccountId32), +} + +impl MultiAddress { + pub fn to_account_id_32(&self) -> AccountId32 { + match self { + MultiAddress::EVM(ethereum_address) => + HashedAddressMapping::::into_account_id(H160::from(ethereum_address.0)), + MultiAddress::Native(substrate_address) => substrate_address.clone(), + } + } + + pub fn to_ethereum_address(&self) -> Option { + match self { + MultiAddress::EVM(ethereum_address) => Some(ethereum_address.clone()), + MultiAddress::Native(_) => None, + } + } +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] +pub enum MultiAddressSignature { + EVM(EcdsaSignature), + Native(Sr25519Signature), +} + +#[derive(Clone, Eq, Encode, PartialEq, Decode, TypeInfo, RuntimeDebug)] +pub struct Sr25519Signature(pub Signature); diff --git a/runtime/mainnet/Cargo.toml b/runtime/mainnet/Cargo.toml index 12b9b32cf..19eeb50ad 100644 --- a/runtime/mainnet/Cargo.toml +++ b/runtime/mainnet/Cargo.toml @@ -27,7 +27,7 @@ dkg-runtime-primitives = { workspace = true } pallet-bridge-registry = { workspace = true } # Webb Substrate Dependencies -pallet-ecdsa-claims = { workspace = true } +pallet-airdrop-claims = { workspace = true } # Substrate dependencies sp-api = { workspace = true } @@ -200,7 +200,7 @@ std = [ "pallet-preimage/std", "pallet-nomination-pools/std", "pallet-treasury/std", - "pallet-ecdsa-claims/std", + "pallet-airdrop-claims/std", "pallet-identity/std", "pallet-bridge-registry/std", diff --git a/runtime/mainnet/src/lib.rs b/runtime/mainnet/src/lib.rs index cd5b6abf3..728329f77 100644 --- a/runtime/mainnet/src/lib.rs +++ b/runtime/mainnet/src/lib.rs @@ -102,11 +102,12 @@ pub use tangle_primitives::{ UNSIGNED_PROPOSAL_EXPIRY, }; +use pallet_airdrop_claims::TestWeightInfo; + // Frontier use fp_rpc::TransactionStatus; use pallet_ethereum::{Call::transact, Transaction as EthereumTransaction}; -use pallet_evm::{Account as EVMAccount, FeeCalculator, Runner}; - +use pallet_evm::{Account as EVMAccount, FeeCalculator, HashedAddressMapping, Runner}; pub type Nonce = u32; /// This runtime version. @@ -996,6 +997,20 @@ impl pallet_utility::Config for Runtime { // type Currency = Balances; // } +parameter_types! { + pub Prefix: &'static [u8] = b"Claim TNTs to the account:"; +} + +impl pallet_airdrop_claims::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type VestingSchedule = Vesting; + type ForceOrigin = frame_system::EnsureRoot; + type AddressMapping = HashedAddressMapping; + type Prefix = Prefix; + type MoveClaimOrigin = frame_system::EnsureRoot; + type WeightInfo = TestWeightInfo; +} + pub struct BaseFilter; impl Contains for BaseFilter { fn contains(call: &RuntimeCall) -> bool { @@ -1100,6 +1115,7 @@ construct_runtime!( BaseFee: pallet_base_fee, HotfixSufficients: pallet_hotfix_sufficients, + Claims: pallet_airdrop_claims, //Eth2Client: pallet_eth2_light_client, } ); diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index 86500dd68..0647ce6b0 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -30,7 +30,7 @@ pallet-dkg-proposal-handler = { workspace = true } pallet-dkg-proposals = { workspace = true } # Webb Substrate Dependencies -pallet-ecdsa-claims = { workspace = true } +pallet-airdrop-claims = { workspace = true } # Substrate dependencies sp-api = { workspace = true } @@ -213,7 +213,7 @@ std = [ "pallet-preimage/std", "pallet-nomination-pools/std", "pallet-treasury/std", - "pallet-ecdsa-claims/std", + "pallet-airdrop-claims/std", "pallet-identity/std", "pallet-bridge-registry/std",