1#[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#[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 Regular,
101 Saft,
103}
104
105impl StatementKind {
106 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#[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 #[pallet::config]
210 pub trait Config: frame_system::Config {
211 #[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 Claimed { who: T::AccountId, ethereum_address: EthereumAddress, amount: BalanceOf<T> },
226 }
227
228 #[pallet::error]
229 pub enum Error<T> {
230 InvalidEthereumSignature,
232 SignerHasNoClaim,
234 SenderHasNoClaim,
236 PotUnderflow,
239 InvalidStatement,
241 VestedBalanceExists,
243 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 #[pallet::storage]
259 pub type Vesting<T: Config> =
260 StorageMap<_, Identity, EthereumAddress, (BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>)>;
261
262 #[pallet::storage]
264 pub type Signing<T> = StorageMap<_, Identity, EthereumAddress, StatementKind>;
265
266 #[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 self.claims.iter().map(|(a, b, _, _)| (*a, *b)).for_each(|(a, b)| {
283 Claims::<T>::insert(a, b);
284 });
285 Total::<T>::put(
287 self.claims
288 .iter()
289 .fold(Zero::zero(), |acc: BalanceOf<T>, &(_, b, _, _)| acc + b),
290 );
291 self.vesting.iter().for_each(|(k, v)| {
293 Vesting::<T>::insert(k, v);
294 });
295 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 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 #[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(ðereum_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 #[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 #[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(ðereum_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 #[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 Call::claim { dest: account, ethereum_signature } => {
514 let data = account.using_encoded(to_ascii_hex);
515 (Self::eth_recover(ðereum_signature, &data, &[][..]), None)
516 },
517 Call::claim_attest { dest: account, ethereum_signature, statement } => {
521 let data = account.using_encoded(to_ascii_hex);
522 (
523 Self::eth_recover(ðereum_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
554fn 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 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 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 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 let _ = CurrencyOf::<T>::deposit_creating(&dest, balance_due);
618
619 if let Some(vs) = vesting {
621 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 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#[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 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;