referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_common/claims/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Pallet to process claims from Ethereum addresses.
18
19#[cfg(not(feature = "std"))]
20use alloc::{format, string::String};
21use alloc::{vec, vec::Vec};
22use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
23use core::fmt::Debug;
24use frame_support::{
25	ensure,
26	traits::{Currency, Get, IsSubType, VestingSchedule},
27	weights::Weight,
28	DefaultNoBound,
29};
30pub use pallet::*;
31use polkadot_primitives::ValidityError;
32use scale_info::TypeInfo;
33use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
34use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
35use sp_runtime::{
36	impl_tx_ext_default,
37	traits::{
38		AsSystemOriginSigner, AsTransactionAuthorizedOrigin, CheckedSub, DispatchInfoOf,
39		Dispatchable, Saturating, TransactionExtension, Zero,
40	},
41	transaction_validity::{
42		InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
43		ValidTransaction,
44	},
45};
46
47type CurrencyOf<T> = <<T as Config>::VestingSchedule as VestingSchedule<
48	<T as frame_system::Config>::AccountId,
49>>::Currency;
50type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
51
52pub trait WeightInfo {
53	fn claim() -> Weight;
54	fn mint_claim() -> Weight;
55	fn claim_attest() -> Weight;
56	fn attest() -> Weight;
57	fn move_claim() -> Weight;
58	fn prevalidate_attests() -> Weight;
59}
60
61pub struct TestWeightInfo;
62impl WeightInfo for TestWeightInfo {
63	fn claim() -> Weight {
64		Weight::zero()
65	}
66	fn mint_claim() -> Weight {
67		Weight::zero()
68	}
69	fn claim_attest() -> Weight {
70		Weight::zero()
71	}
72	fn attest() -> Weight {
73		Weight::zero()
74	}
75	fn move_claim() -> Weight {
76		Weight::zero()
77	}
78	fn prevalidate_attests() -> Weight {
79		Weight::zero()
80	}
81}
82
83/// The kind of statement an account needs to make for a claim to be valid.
84#[derive(
85	Encode,
86	Decode,
87	DecodeWithMemTracking,
88	Clone,
89	Copy,
90	Eq,
91	PartialEq,
92	Debug,
93	TypeInfo,
94	Serialize,
95	Deserialize,
96	MaxEncodedLen,
97)]
98pub enum StatementKind {
99	/// Statement required to be made by non-SAFT holders.
100	Regular,
101	/// Statement required to be made by SAFT holders.
102	Saft,
103}
104
105impl StatementKind {
106	/// Convert this to the (English) statement it represents.
107	fn to_text(self) -> &'static [u8] {
108		match self {
109			StatementKind::Regular => {
110				&b"I hereby agree to the terms of the statement whose SHA-256 multihash is \
111				Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny. (This may be found at the URL: \
112				https://statement.polkadot.network/regular.html)"[..]
113			},
114			StatementKind::Saft => {
115				&b"I hereby agree to the terms of the statement whose SHA-256 multihash is \
116				QmXEkMahfhHJPzT3RjkXiZVFi77ZeVeuxtAjhojGRNYckz. (This may be found at the URL: \
117				https://statement.polkadot.network/saft.html)"[..]
118			},
119		}
120	}
121}
122
123impl Default for StatementKind {
124	fn default() -> Self {
125		StatementKind::Regular
126	}
127}
128
129/// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account).
130///
131/// This gets serialized to the 0x-prefixed hex representation.
132#[derive(
133	Clone,
134	Copy,
135	PartialEq,
136	Eq,
137	Encode,
138	Decode,
139	DecodeWithMemTracking,
140	Default,
141	Debug,
142	TypeInfo,
143	MaxEncodedLen,
144)]
145pub struct EthereumAddress(pub [u8; 20]);
146
147impl Serialize for EthereumAddress {
148	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
149	where
150		S: Serializer,
151	{
152		let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]);
153		serializer.serialize_str(&format!("0x{}", hex))
154	}
155}
156
157impl<'de> Deserialize<'de> for EthereumAddress {
158	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
159	where
160		D: Deserializer<'de>,
161	{
162		let base_string = String::deserialize(deserializer)?;
163		let offset = if base_string.starts_with("0x") { 2 } else { 0 };
164		let s = &base_string[offset..];
165		if s.len() != 40 {
166			Err(serde::de::Error::custom(
167				"Bad length of Ethereum address (should be 42 including '0x')",
168			))?;
169		}
170		let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s)
171			.map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?;
172		let mut r = Self::default();
173		r.0.copy_from_slice(&raw);
174		Ok(r)
175	}
176}
177
178impl AsRef<[u8]> for EthereumAddress {
179	fn as_ref(&self) -> &[u8] {
180		&self.0[..]
181	}
182}
183
184#[derive(Encode, Decode, DecodeWithMemTracking, Clone, TypeInfo, MaxEncodedLen)]
185pub struct EcdsaSignature(pub [u8; 65]);
186
187impl PartialEq for EcdsaSignature {
188	fn eq(&self, other: &Self) -> bool {
189		&self.0[..] == &other.0[..]
190	}
191}
192
193impl core::fmt::Debug for EcdsaSignature {
194	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
195		write!(f, "EcdsaSignature({:?})", &self.0[..])
196	}
197}
198
199#[frame_support::pallet]
200pub mod pallet {
201	use super::*;
202	use frame_support::pallet_prelude::*;
203	use frame_system::pallet_prelude::*;
204
205	#[pallet::pallet]
206	pub struct Pallet<T>(_);
207
208	/// Configuration trait.
209	#[pallet::config]
210	pub trait Config: frame_system::Config {
211		/// The overarching event type.
212		#[allow(deprecated)]
213		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
214		type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>;
215		#[pallet::constant]
216		type Prefix: Get<&'static [u8]>;
217		type MoveClaimOrigin: EnsureOrigin<Self::RuntimeOrigin>;
218		type WeightInfo: WeightInfo;
219	}
220
221	#[pallet::event]
222	#[pallet::generate_deposit(pub(super) fn deposit_event)]
223	pub enum Event<T: Config> {
224		/// Someone claimed some DOTs.
225		Claimed { who: T::AccountId, ethereum_address: EthereumAddress, amount: BalanceOf<T> },
226	}
227
228	#[pallet::error]
229	pub enum Error<T> {
230		/// Invalid Ethereum signature.
231		InvalidEthereumSignature,
232		/// Ethereum address has no claim.
233		SignerHasNoClaim,
234		/// Account ID sending transaction has no claim.
235		SenderHasNoClaim,
236		/// There's not enough in the pot to pay out some unvested amount. Generally implies a
237		/// logic error.
238		PotUnderflow,
239		/// A needed statement was not included.
240		InvalidStatement,
241		/// The account already has a vested balance.
242		VestedBalanceExists,
243		/// The claim has a vesting schedule but its value is below the existential deposit, so the
244		/// destination account could not be kept alive to carry the vesting lock.
245		ClaimBelowExistentialDeposit,
246	}
247
248	#[pallet::storage]
249	pub type Claims<T: Config> = StorageMap<_, Identity, EthereumAddress, BalanceOf<T>>;
250
251	#[pallet::storage]
252	pub type Total<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
253
254	/// Vesting schedule for a claim.
255	/// First balance is the total amount that should be held for vesting.
256	/// Second balance is how much should be unlocked per block.
257	/// The block number is when the vesting should start.
258	#[pallet::storage]
259	pub type Vesting<T: Config> =
260		StorageMap<_, Identity, EthereumAddress, (BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>)>;
261
262	/// The statement kind that must be signed, if any.
263	#[pallet::storage]
264	pub type Signing<T> = StorageMap<_, Identity, EthereumAddress, StatementKind>;
265
266	/// Pre-claimed Ethereum accounts, by the Account ID that they are claimed to.
267	#[pallet::storage]
268	pub type Preclaims<T: Config> = StorageMap<_, Identity, T::AccountId, EthereumAddress>;
269
270	#[pallet::genesis_config]
271	#[derive(DefaultNoBound)]
272	pub struct GenesisConfig<T: Config> {
273		pub claims:
274			Vec<(EthereumAddress, BalanceOf<T>, Option<T::AccountId>, Option<StatementKind>)>,
275		pub vesting: Vec<(EthereumAddress, (BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>))>,
276	}
277
278	#[pallet::genesis_build]
279	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
280		fn build(&self) {
281			// build `Claims`
282			self.claims.iter().map(|(a, b, _, _)| (*a, *b)).for_each(|(a, b)| {
283				Claims::<T>::insert(a, b);
284			});
285			// build `Total`
286			Total::<T>::put(
287				self.claims
288					.iter()
289					.fold(Zero::zero(), |acc: BalanceOf<T>, &(_, b, _, _)| acc + b),
290			);
291			// build `Vesting`
292			self.vesting.iter().for_each(|(k, v)| {
293				Vesting::<T>::insert(k, v);
294			});
295			// build `Signing`
296			self.claims
297				.iter()
298				.filter_map(|(a, _, _, s)| Some((*a, (*s)?)))
299				.for_each(|(a, s)| {
300					Signing::<T>::insert(a, s);
301				});
302			// build `Preclaims`
303			self.claims.iter().filter_map(|(a, _, i, _)| Some((i.clone()?, *a))).for_each(
304				|(i, a)| {
305					Preclaims::<T>::insert(i, a);
306				},
307			);
308		}
309	}
310
311	#[pallet::hooks]
312	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
313
314	#[pallet::call]
315	impl<T: Config> Pallet<T> {
316		/// Make a claim to collect your DOTs.
317		///
318		/// The dispatch origin for this call must be _None_.
319		///
320		/// Unsigned Validation:
321		/// A call to claim is deemed valid if the signature provided matches
322		/// the expected signed message of:
323		///
324		/// > Ethereum Signed Message:
325		/// > (configured prefix string)(address)
326		///
327		/// and `address` matches the `dest` account.
328		///
329		/// Parameters:
330		/// - `dest`: The destination account to payout the claim.
331		/// - `ethereum_signature`: The signature of an ethereum signed message matching the format
332		///   described above.
333		///
334		/// <weight>
335		/// The weight of this call is invariant over the input parameters.
336		/// Weight includes logic to validate unsigned `claim` call.
337		///
338		/// Total Complexity: O(1)
339		/// </weight>
340		#[pallet::call_index(0)]
341		#[pallet::weight(T::WeightInfo::claim())]
342		pub fn claim(
343			origin: OriginFor<T>,
344			dest: T::AccountId,
345			ethereum_signature: EcdsaSignature,
346		) -> DispatchResult {
347			ensure_none(origin)?;
348
349			let data = dest.using_encoded(to_ascii_hex);
350			let signer = Self::eth_recover(&ethereum_signature, &data, &[][..])
351				.ok_or(Error::<T>::InvalidEthereumSignature)?;
352			ensure!(Signing::<T>::get(&signer).is_none(), Error::<T>::InvalidStatement);
353
354			Self::process_claim(signer, dest)?;
355			Ok(())
356		}
357
358		/// Mint a new claim to collect DOTs.
359		///
360		/// The dispatch origin for this call must be _Root_.
361		///
362		/// Parameters:
363		/// - `who`: The Ethereum address allowed to collect this claim.
364		/// - `value`: The number of DOTs that will be claimed.
365		/// - `vesting_schedule`: An optional vesting schedule for these DOTs.
366		///
367		/// <weight>
368		/// The weight of this call is invariant over the input parameters.
369		/// We assume worst case that both vesting and statement is being inserted.
370		///
371		/// Total Complexity: O(1)
372		/// </weight>
373		#[pallet::call_index(1)]
374		#[pallet::weight(T::WeightInfo::mint_claim())]
375		pub fn mint_claim(
376			origin: OriginFor<T>,
377			who: EthereumAddress,
378			value: BalanceOf<T>,
379			vesting_schedule: Option<(BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>)>,
380			statement: Option<StatementKind>,
381		) -> DispatchResult {
382			ensure_root(origin)?;
383			Total::<T>::mutate(|t| *t += value);
384			Claims::<T>::insert(who, value);
385			if let Some(vs) = vesting_schedule {
386				Vesting::<T>::insert(who, vs);
387			}
388			if let Some(s) = statement {
389				Signing::<T>::insert(who, s);
390			}
391			Ok(())
392		}
393
394		/// Make a claim to collect your DOTs by signing a statement.
395		///
396		/// The dispatch origin for this call must be _None_.
397		///
398		/// Unsigned Validation:
399		/// A call to `claim_attest` is deemed valid if the signature provided matches
400		/// the expected signed message of:
401		///
402		/// > Ethereum Signed Message:
403		/// > (configured prefix string)(address)(statement)
404		///
405		/// and `address` matches the `dest` account; the `statement` must match that which is
406		/// expected according to your purchase arrangement.
407		///
408		/// Parameters:
409		/// - `dest`: The destination account to payout the claim.
410		/// - `ethereum_signature`: The signature of an ethereum signed message matching the format
411		///   described above.
412		/// - `statement`: The identity of the statement which is being attested to in the
413		///   signature.
414		///
415		/// <weight>
416		/// The weight of this call is invariant over the input parameters.
417		/// Weight includes logic to validate unsigned `claim_attest` call.
418		///
419		/// Total Complexity: O(1)
420		/// </weight>
421		#[pallet::call_index(2)]
422		#[pallet::weight(T::WeightInfo::claim_attest())]
423		pub fn claim_attest(
424			origin: OriginFor<T>,
425			dest: T::AccountId,
426			ethereum_signature: EcdsaSignature,
427			statement: Vec<u8>,
428		) -> DispatchResult {
429			ensure_none(origin)?;
430
431			let data = dest.using_encoded(to_ascii_hex);
432			let signer = Self::eth_recover(&ethereum_signature, &data, &statement)
433				.ok_or(Error::<T>::InvalidEthereumSignature)?;
434			if let Some(s) = Signing::<T>::get(signer) {
435				ensure!(s.to_text() == &statement[..], Error::<T>::InvalidStatement);
436			}
437			Self::process_claim(signer, dest)?;
438			Ok(())
439		}
440
441		/// Attest to a statement, needed to finalize the claims process.
442		///
443		/// WARNING: Insecure unless your chain includes `PrevalidateAttests` as a
444		/// `TransactionExtension`.
445		///
446		/// Unsigned Validation:
447		/// A call to attest is deemed valid if the sender has a `Preclaim` registered
448		/// and provides a `statement` which is expected for the account.
449		///
450		/// Parameters:
451		/// - `statement`: The identity of the statement which is being attested to in the
452		///   signature.
453		///
454		/// <weight>
455		/// The weight of this call is invariant over the input parameters.
456		/// Weight includes logic to do pre-validation on `attest` call.
457		///
458		/// Total Complexity: O(1)
459		/// </weight>
460		#[pallet::call_index(3)]
461		#[pallet::weight((
462			T::WeightInfo::attest(),
463			DispatchClass::Normal,
464			Pays::No
465		))]
466		pub fn attest(origin: OriginFor<T>, statement: Vec<u8>) -> DispatchResult {
467			let who = ensure_signed(origin)?;
468			let signer = Preclaims::<T>::get(&who).ok_or(Error::<T>::SenderHasNoClaim)?;
469			if let Some(s) = Signing::<T>::get(signer) {
470				ensure!(s.to_text() == &statement[..], Error::<T>::InvalidStatement);
471			}
472			Self::process_claim(signer, who.clone())?;
473			Preclaims::<T>::remove(&who);
474			Ok(())
475		}
476
477		#[pallet::call_index(4)]
478		#[pallet::weight(T::WeightInfo::move_claim())]
479		pub fn move_claim(
480			origin: OriginFor<T>,
481			old: EthereumAddress,
482			new: EthereumAddress,
483			maybe_preclaim: Option<T::AccountId>,
484		) -> DispatchResultWithPostInfo {
485			T::MoveClaimOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?;
486
487			Claims::<T>::take(&old).map(|c| Claims::<T>::insert(&new, c));
488			Vesting::<T>::take(&old).map(|c| Vesting::<T>::insert(&new, c));
489			Signing::<T>::take(&old).map(|c| Signing::<T>::insert(&new, c));
490			maybe_preclaim.map(|preclaim| {
491				Preclaims::<T>::mutate(&preclaim, |maybe_o| {
492					if maybe_o.as_ref().map_or(false, |o| o == &old) {
493						*maybe_o = Some(new)
494					}
495				})
496			});
497			Ok(Pays::No.into())
498		}
499	}
500
501	#[allow(deprecated)]
502	#[pallet::validate_unsigned]
503	impl<T: Config> ValidateUnsigned for Pallet<T> {
504		type Call = Call<T>;
505
506		fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
507			const PRIORITY: u64 = 100;
508
509			let (maybe_signer, maybe_statement) = match call {
510				// <weight>
511				// The weight of this logic is included in the `claim` dispatchable.
512				// </weight>
513				Call::claim { dest: account, ethereum_signature } => {
514					let data = account.using_encoded(to_ascii_hex);
515					(Self::eth_recover(&ethereum_signature, &data, &[][..]), None)
516				},
517				// <weight>
518				// The weight of this logic is included in the `claim_attest` dispatchable.
519				// </weight>
520				Call::claim_attest { dest: account, ethereum_signature, statement } => {
521					let data = account.using_encoded(to_ascii_hex);
522					(
523						Self::eth_recover(&ethereum_signature, &data, &statement),
524						Some(statement.as_slice()),
525					)
526				},
527				_ => return Err(InvalidTransaction::Call.into()),
528			};
529
530			let signer = maybe_signer.ok_or(InvalidTransaction::Custom(
531				ValidityError::InvalidEthereumSignature.into(),
532			))?;
533
534			let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into());
535			ensure!(Claims::<T>::contains_key(&signer), e);
536
537			let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into());
538			match Signing::<T>::get(signer) {
539				None => ensure!(maybe_statement.is_none(), e),
540				Some(s) => ensure!(Some(s.to_text()) == maybe_statement, e),
541			}
542
543			Ok(ValidTransaction {
544				priority: PRIORITY,
545				requires: vec![],
546				provides: vec![("claims", signer).encode()],
547				longevity: TransactionLongevity::max_value(),
548				propagate: true,
549			})
550		}
551	}
552}
553
554/// Converts the given binary data into ASCII-encoded hex. It will be twice the length.
555fn to_ascii_hex(data: &[u8]) -> Vec<u8> {
556	let mut r = Vec::with_capacity(data.len() * 2);
557	let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n });
558	for &b in data.iter() {
559		push_nibble(b / 16);
560		push_nibble(b % 16);
561	}
562	r
563}
564
565impl<T: Config> Pallet<T> {
566	// Constructs the message that Ethereum RPC's `personal_sign` and `eth_sign` would sign.
567	fn ethereum_signable_message(what: &[u8], extra: &[u8]) -> Vec<u8> {
568		let prefix = T::Prefix::get();
569		let mut l = prefix.len() + what.len() + extra.len();
570		let mut rev = Vec::new();
571		while l > 0 {
572			rev.push(b'0' + (l % 10) as u8);
573			l /= 10;
574		}
575		let mut v = b"\x19Ethereum Signed Message:\n".to_vec();
576		v.extend(rev.into_iter().rev());
577		v.extend_from_slice(prefix);
578		v.extend_from_slice(what);
579		v.extend_from_slice(extra);
580		v
581	}
582
583	// Attempts to recover the Ethereum address from a message signature signed by using
584	// the Ethereum RPC's `personal_sign` and `eth_sign`.
585	fn eth_recover(s: &EcdsaSignature, what: &[u8], extra: &[u8]) -> Option<EthereumAddress> {
586		let msg = keccak_256(&Self::ethereum_signable_message(what, extra));
587		let mut res = EthereumAddress::default();
588		res.0
589			.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
590		Some(res)
591	}
592
593	fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> sp_runtime::DispatchResult {
594		let balance_due = Claims::<T>::get(&signer).ok_or(Error::<T>::SignerHasNoClaim)?;
595
596		let new_total =
597			Total::<T>::get().checked_sub(&balance_due).ok_or(Error::<T>::PotUnderflow)?;
598
599		let vesting = Vesting::<T>::get(&signer);
600		if let Some(_) = vesting {
601			if T::VestingSchedule::vesting_balance(&dest).is_some() {
602				return Err(Error::<T>::VestedBalanceExists.into());
603			}
604
605			// A vesting schedule installs a balance lock, which requires the account to stay alive,
606			// otherwise it is dusted and the lock placed on a non-existent account. The `dest` may
607			// already hold funds, so a small claim that tops an existing account over the ED is
608			// valid.
609			let free_after = CurrencyOf::<T>::free_balance(&dest).saturating_add(balance_due);
610			ensure!(
611				free_after >= CurrencyOf::<T>::minimum_balance(),
612				Error::<T>::ClaimBelowExistentialDeposit,
613			);
614		}
615
616		// We first need to deposit the balance to ensure that the account exists.
617		let _ = CurrencyOf::<T>::deposit_creating(&dest, balance_due);
618
619		// Check if this claim should have a vesting schedule.
620		if let Some(vs) = vesting {
621			// This can only fail if the account already has a vesting schedule or its balance is
622			// below the existential deposit, both of which are checked above.
623			T::VestingSchedule::add_vesting_schedule(&dest, vs.0, vs.1, vs.2)
624				.map_err(|_| Error::<T>::VestedBalanceExists)?;
625		}
626
627		Total::<T>::put(new_total);
628		Claims::<T>::remove(&signer);
629		Vesting::<T>::remove(&signer);
630		Signing::<T>::remove(&signer);
631
632		// Let's deposit an event to let the outside world know this happened.
633		Self::deposit_event(Event::<T>::Claimed {
634			who: dest,
635			ethereum_address: signer,
636			amount: balance_due,
637		});
638
639		Ok(())
640	}
641}
642
643/// Validate `attest` calls prior to execution. Needed to avoid a DoS attack since they are
644/// otherwise free to place on chain.
645#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo)]
646#[scale_info(skip_type_params(T))]
647pub struct PrevalidateAttests<T>(core::marker::PhantomData<fn(T)>);
648
649impl<T: Config> Debug for PrevalidateAttests<T>
650where
651	<T as frame_system::Config>::RuntimeCall: IsSubType<Call<T>>,
652{
653	#[cfg(feature = "std")]
654	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
655		write!(f, "PrevalidateAttests")
656	}
657
658	#[cfg(not(feature = "std"))]
659	fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
660		Ok(())
661	}
662}
663
664impl<T: Config> PrevalidateAttests<T>
665where
666	<T as frame_system::Config>::RuntimeCall: IsSubType<Call<T>>,
667{
668	/// Create new `TransactionExtension` to check runtime version.
669	pub fn new() -> Self {
670		Self(core::marker::PhantomData)
671	}
672}
673
674impl<T: Config> TransactionExtension<T::RuntimeCall> for PrevalidateAttests<T>
675where
676	<T as frame_system::Config>::RuntimeCall: IsSubType<Call<T>>,
677	<<T as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
678		AsSystemOriginSigner<T::AccountId> + AsTransactionAuthorizedOrigin + Clone,
679{
680	const IDENTIFIER: &'static str = "PrevalidateAttests";
681	type Implicit = ();
682	type Pre = ();
683	type Val = ();
684
685	fn weight(&self, call: &T::RuntimeCall) -> Weight {
686		if let Some(Call::attest { .. }) = call.is_sub_type() {
687			T::WeightInfo::prevalidate_attests()
688		} else {
689			Weight::zero()
690		}
691	}
692
693	fn validate(
694		&self,
695		origin: <T::RuntimeCall as Dispatchable>::RuntimeOrigin,
696		call: &T::RuntimeCall,
697		_info: &DispatchInfoOf<T::RuntimeCall>,
698		_len: usize,
699		_self_implicit: Self::Implicit,
700		_inherited_implication: &impl Encode,
701		_source: TransactionSource,
702	) -> Result<
703		(ValidTransaction, Self::Val, <T::RuntimeCall as Dispatchable>::RuntimeOrigin),
704		TransactionValidityError,
705	> {
706		if let Some(Call::attest { statement: attested_statement }) = call.is_sub_type() {
707			let who = origin.as_system_origin_signer().ok_or(InvalidTransaction::BadSigner)?;
708			let signer = Preclaims::<T>::get(who)
709				.ok_or(InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()))?;
710			if let Some(s) = Signing::<T>::get(signer) {
711				let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into());
712				ensure!(&attested_statement[..] == s.to_text(), e);
713			}
714		}
715		Ok((ValidTransaction::default(), (), origin))
716	}
717
718	impl_tx_ext_default!(T::RuntimeCall; prepare);
719}
720
721#[cfg(any(test, feature = "runtime-benchmarks"))]
722mod secp_utils {
723	use super::*;
724
725	pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
726		libsecp256k1::PublicKey::from_secret_key(secret)
727	}
728	pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress {
729		let mut res = EthereumAddress::default();
730		res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
731		res
732	}
733	pub fn sig<T: Config>(
734		secret: &libsecp256k1::SecretKey,
735		what: &[u8],
736		extra: &[u8],
737	) -> EcdsaSignature {
738		let msg = keccak_256(&super::Pallet::<T>::ethereum_signable_message(
739			&to_ascii_hex(what)[..],
740			extra,
741		));
742		let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);
743		let mut r = [0u8; 65];
744		r[0..64].copy_from_slice(&sig.serialize()[..]);
745		r[64] = recovery_id.serialize();
746		EcdsaSignature(r)
747	}
748}
749
750#[cfg(test)]
751mod mock;
752
753#[cfg(test)]
754mod tests;
755
756#[cfg(feature = "runtime-benchmarks")]
757mod benchmarking;