1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#![cfg_attr(not(feature = "std"), no_std)]
//! # Equilibrium Claim Pallet
//!
//! Equilibrium's Balances Pallet is a Substrate module that processes claims
//! from Ethereum addresses. It is used in Equilibrium Substrate to payout
//! claims generated during Token Swap event

mod benchmarking;
mod benchmarks;
mod mock;
mod secp_utils;

use codec::{Decode, Encode};
use eq_primitives::AccountGetter;
use eq_utils::log::eq_log;
use eq_utils::{eq_ensure, ok_or_error};
#[allow(unused_imports)]
use frame_support::{
    debug, decl_error, decl_event, decl_module, decl_storage,
    dispatch::IsSubType,
    traits::{Currency, EnsureOrigin, Get, VestingSchedule},
    weights::{DispatchClass, Pays, Weight},
};
use frame_system::{ensure_none, ensure_root, ensure_signed};
#[cfg(feature = "std")]
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
#[cfg(feature = "std")]
use sp_runtime::traits::Zero;
use sp_runtime::{
    traits::{CheckedSub, DispatchInfoOf, Saturating, SignedExtension},
    transaction_validity::{
        InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
        TransactionValidityError, ValidTransaction,
    },
    DispatchResult, RuntimeDebug,
};
use sp_std::{fmt::Debug, prelude::*};

pub trait WeightInfo {
    fn claim(u: u32) -> Weight;
    fn mint_claim(c: u32) -> Weight;
    fn claim_attest(u: u32) -> Weight;
    fn attest(u: u32) -> Weight;
    fn validate_unsigned_claim(c: u32) -> Weight;
    fn validate_unsigned_claim_attest(c: u32) -> Weight;
    fn validate_prevalidate_attests(c: u32) -> Weight;
    fn keccak256(i: u32) -> Weight;
    fn eth_recover(i: u32) -> Weight;
}

type CurrencyOf<T> = <<T as Trait>::VestingSchedule as VestingSchedule<
    <T as frame_system::Trait>::AccountId,
>>::Currency;
type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Trait>::AccountId>>::Balance;

/// Claim validation errors
#[repr(u8)]
pub enum ValidityError {
    /// The Ethereum signature is invalid
    InvalidEthereumSignature = 0,
    /// The signer has no claim
    SignerHasNoClaim = 1,
    /// No permission to execute the call
    NoPermission = 2,
    /// An invalid statement was made for a claim
    InvalidStatement = 3,
}

impl From<ValidityError> for u8 {
    fn from(err: ValidityError) -> Self {
        err as u8
    }
}

/// Substrate pallet configuration trait
pub trait Trait: frame_system::Trait {
    type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
    type WeightInfo: WeightInfo;

    /// Used to schedule vesting part of a claim
    type VestingSchedule: VestingSchedule<Self::AccountId, Moment = Self::BlockNumber>;
    /// TODO
    type Prefix: Get<&'static [u8]>;
    /// ToDO
    type MoveClaimOrigin: EnsureOrigin<Self::Origin>;
    /// Gets vesting account
    type VestingAccountGetter: AccountGetter<Self::AccountId>;
}

/// The kind of a statement an account needs to make for a claim to be valid
#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum StatementKind {
    /// Statement required to be made by non-SAFT holders
    Regular,
    /// Statement required to be made by SAFT holders
    Saft,
}

impl Default for StatementKind {
    fn default() -> Self {
        StatementKind::Regular
    }
}

/// 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, PartialOrd, Ord, Eq, Encode, Decode, Default, RuntimeDebug, Hash,
)]
pub struct EthereumAddress([u8; 20]);

#[cfg(feature = "std")]
impl Serialize for EthereumAddress {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]);
        serializer.serialize_str(&format!("0x{}", hex))
    }
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for EthereumAddress {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    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 {
            debug::error!(
                "{}:{}. Bad length of Ethereum address. Length: {:?}",
                file!(),
                line!(),
                s.len()
            );
            Err(serde::de::Error::custom(
                "Bad length of Ethereum address (should be 42 including '0x')",
            ))?;
        }
        let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s).map_err(|e| {
            debug::error!("{}:{}. Couldn't convert from hex.", file!(), line!());
            serde::de::Error::custom(format!("{:?}", e))
        })?;
        let mut r = Self::default();
        r.0.copy_from_slice(&raw);
        Ok(r)
    }
}

#[derive(Encode, Decode, Clone)]
pub struct EcdsaSignature(pub [u8; 65]);

impl AsRef<[u8; 65]> for EcdsaSignature {
    fn as_ref(&self) -> &[u8; 65] {
        &self.0
    }
}

impl AsRef<[u8]> for EcdsaSignature {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

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[..])
    }
}

decl_event!(
    pub enum Event<T>
    where
        Balance = BalanceOf<T>,
        AccountId = <T as frame_system::Trait>::AccountId,
    {
        /// `AccountId` claimed `Balance` amount of currency reserved for `EthereumAddress`
        Claimed(AccountId, EthereumAddress, Balance),
    }
);

decl_error! {
    /// Pallet's errors
    pub enum Error for Module<T: Trait> {
        /// Invalid Ethereum signature
        InvalidEthereumSignature,
        /// Ethereum address has no claim
        SignerHasNoClaim,
        /// Account sending transaction has no claim
        SenderHasNoClaim,
        /// There's not enough in the pot to pay out some unvested amount. Generally
        /// implies a logic error
        PotUnderflow,
        /// A needed statement was not included.
        InvalidStatement,
        /// The account already has a vested balance
        VestedBalanceExists,
    }
}

decl_storage! {
    trait Store for Module<T: Trait> as Claims {
        /// Pallet storage - stores amount to be claimed by each `EthereumAddress`
        Claims get(fn claims) build(|config: &GenesisConfig<T>| {
            config.claims.iter().map(|(a, b, _, _)| (a.clone(), b.clone())).collect::<Vec<_>>()
        }): map hasher(identity) EthereumAddress => Option<BalanceOf<T>>;

        /// Pallet storage - total `Claims` amount
        Total get(fn total) build(|config: &GenesisConfig<T>| {
            config.claims.iter().fold(Zero::zero(), |acc: BalanceOf<T>, &(_, b, _, _)| acc + b)
        }): BalanceOf<T>;

        /// Pallet storage - vesting schedule for a claim.
        /// First balance is the total amount that should be held for vesting.
        /// Second balance is how much should be unlocked per block.
        /// The block number is when the vesting should start.
        Vesting get(fn vesting) config():
            map hasher(identity) EthereumAddress
            => Option<(BalanceOf<T>, BalanceOf<T>, T::BlockNumber)>;

        /// Pallet storage - the statement kind that must be signed, if any
        Signing build(|config: &GenesisConfig<T>| {
            config.claims.iter()
                .filter_map(|(a, _, _, s)| Some((a.clone(), s.clone())))
                .collect::<Vec<_>>()
        }): map hasher(identity) EthereumAddress => bool;

        /// Pallet storage - pre-claimed Ethereum accounts, by the Account ID that
        /// they are claimed to
        Preclaims build(|config: &GenesisConfig<T>| {
            config.claims.iter()
                .filter_map(|(a, _, i, _)| Some((i.clone()?, a.clone())))
                .collect::<Vec<_>>()
        }): map hasher(identity) T::AccountId => Option<EthereumAddress>;
    }
    add_extra_genesis {
        config(claims): Vec<(EthereumAddress, BalanceOf<T>, Option<T::AccountId>, bool)>;
    }
}

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        fn deposit_event() = default;

        type Error = Error<T>;

        /// The Prefix that is used in signed Ethereum messages for this network
        const Prefix: &[u8] = T::Prefix::get();

        /// Make a claim to collect your currency.
        ///
        /// The dispatch origin for this call must be _None_.
        ///
        /// Unsigned Validation:
        /// A call to claim is deemed valid if the signature provided matches
        /// the expected signed message of:
        ///
        /// > Ethereum Signed Message:
        /// > (configured prefix string)(address)
        ///
        /// and `address` matches the `dest` account.
        ///
        /// Parameters:
        /// - `dest`: The destination account to payout the claim.
        /// - `ethereum_signature`: The signature of an ethereum signed message
        ///    matching the format described above.
        #[weight = T::WeightInfo::claim(1)]
        fn claim(origin, dest: T::AccountId, ethereum_signature: EcdsaSignature) {
            ensure_none(origin)?;

            let data = dest.using_encoded(to_ascii_hex);
            let option_ethereum_address = Self::eth_recover(&ethereum_signature, &data, &[][..]);
            let signer = ok_or_error!(option_ethereum_address, Error::<T>::InvalidEthereumSignature,
            "{}:{}. Invalid ethereum signature while recover. Dest: {:?}, signature: {:?}, data: {:?}.",
            file!(), line!(), dest, ethereum_signature, data)?;

            eq_ensure!(Signing::get(&signer) == false, Error::<T>::InvalidStatement,
            "{}:{}. Cannot get signer. Who: {:?}.", file!(), line!(), signer);

            Self::process_claim(signer, dest)?;
        }

        /// Mint a new claim to collect currency
        ///
        /// The dispatch origin for this call must be _Root_.
        ///
        /// Parameters:
        /// - `who`: The Ethereum address allowed to collect this claim.
        /// - `value`: The balance that will be claimed.
        /// - `vesting_schedule`: An optional vesting schedule for the claim
        #[weight = T::WeightInfo::mint_claim(5_000)]
        fn mint_claim(origin,
            who: EthereumAddress,
            value: BalanceOf<T>,
            vesting_schedule: Option<(BalanceOf<T>, BalanceOf<T>, T::BlockNumber)>,
            statement: bool,
        ) {
            ensure_root(origin)?;

            if vesting_schedule != None && value < vesting_schedule.unwrap().0 {
                eq_log!(
                    "mint_claim error: value {:?} < vesting_schedule.locked {:?}",
                    value,
                    vesting_schedule.unwrap().0
                );
                eq_ensure!(false, Error::<T>::InvalidStatement,
                "{}:{}. Amount to claim is less than vesting_schedule.locked. Amount to claim: {:?}, vesting_schedule: {:?}.",
                file!(), line!(), value, vesting_schedule.unwrap().0);
            }

            <Total<T>>::mutate(|t| *t += value);
            <Claims<T>>::insert(who, value);
            if let Some(vs) = vesting_schedule {
                <Vesting<T>>::insert(who, vs);
            }
            if statement {
                Signing::insert(who, statement);
            }
        }

        /// Make a claim to collect your currency by signing a statement.
        ///
        /// The dispatch origin for this call must be _None_.
        ///
        /// Unsigned Validation:
        /// A call to `claim_attest` is deemed valid if the signature provided matches
        /// the expected signed message of:
        ///
        /// > Ethereum Signed Message:
        /// > (configured prefix string)(address)(statement)
        ///
        /// and `address` matches the `dest` account; the `statement` must match that which is
        /// expected according to your purchase arrangement.
        ///
        /// Parameters:
        /// - `dest`: The destination account to payout the claim.
        /// - `ethereum_signature`: The signature of an ethereum signed message
        ///    matching the format described above.
        /// - `statement`: The identity of the statement which is being attested to in the signature.
        #[weight = T::WeightInfo::claim_attest(1)]
        fn claim_attest(origin,
            dest: T::AccountId,
            ethereum_signature: EcdsaSignature,
            statement: Vec<u8>,
        ) {
            ensure_none(origin)?;

            let data = dest.using_encoded(to_ascii_hex);
            let option_ethereum_address = Self::eth_recover(&ethereum_signature, &data, &statement);
            let signer = ok_or_error!(option_ethereum_address, Error::<T>::InvalidEthereumSignature,
                "{}:{}. Invalid ethereum signature while recover. Dest: {:?}, signature: {:?}, data: {:?}, statement: {:?}.",
                file!(), line!(), dest, ethereum_signature, data, statement)?;
            let s = Signing::get(signer);
            if s {
                eq_ensure!(get_statement_text() == &statement[..], Error::<T>::InvalidStatement,
                "{}:{}. Get_statement_text() not equal to statement from params. Get statement text: {:?}, from params: {:?}.",
                file!(), line!(), get_statement_text(), &statement[..]);
            }
            Self::process_claim(signer, dest)?;
        }

        /// Attest to a statement, needed to finalize the claims process.
        ///
        /// 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.
        #[weight = (T::WeightInfo::attest(1), DispatchClass::Normal, Pays::No)]
        fn attest(origin, statement: Vec<u8>) {
            let who = ensure_signed(origin)?;
            let option_ethereum_address = Preclaims::<T>::get(&who);
            let signer = ok_or_error!(option_ethereum_address, Error::<T>::SenderHasNoClaim,
            "{}:{}. Sender not in Preclaims. Who: {:?}.", file!(), line!(), who)?;
            let s = Signing::get(signer);
            if s {
                eq_ensure!(get_statement_text() == &statement[..], Error::<T>::InvalidStatement,
                "{}:{}. Get_statement_text() not equal to statement from params. Get statement text: {:?}, from params: {:?}.",
                file!(), line!(), get_statement_text(), &statement[..]);
            }
            Self::process_claim(signer, who.clone())?;
            Preclaims::<T>::remove(&who);
        }

        /// Gives claims ownership from `old` to `new`
        #[weight = (
            T::DbWeight::get().reads_writes(4, 4) + 100_000_000_000,
            DispatchClass::Normal,
            Pays::No
        )]
        fn move_claim(origin,
            old: EthereumAddress,
            new: EthereumAddress,
            maybe_preclaim: Option<T::AccountId>,
        ) {
            T::MoveClaimOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?;

            Claims::<T>::take(&old).map(|c| Claims::<T>::insert(&new, c));
            Vesting::<T>::take(&old).map(|c| Vesting::<T>::insert(&new, c));
            let s = Signing::take(&old);
            Signing::insert(&new, s);
            maybe_preclaim.map(|preclaim| Preclaims::<T>::mutate(&preclaim, |maybe_o|
                if maybe_o.as_ref().map_or(false, |o| o == &old) { *maybe_o = Some(new) }
            ));
        }
    }
}

/// Convert this to the (English) statement it represents
pub fn get_statement_text() -> &'static [u8] {
    &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \
            Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny. (This may be found at the URL: \
            https://equilibrium.io/tokenswap/docs/token_swap_t&cs.pdf)"[..]
}

/// Converts the given binary data into ASCII-encoded hex. It will be twice the length
pub fn to_ascii_hex(data: &[u8]) -> Vec<u8> {
    let mut r = Vec::with_capacity(data.len() * 2);
    let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n });
    for &b in data.iter() {
        push_nibble(b / 16);
        push_nibble(b % 16);
    }
    r
}

impl<T: Trait> Module<T> {
    // Constructs the message that Ethereum RPC's `personal_sign` and `eth_sign` would sign
    fn ethereum_signable_message(what: &[u8], extra: &[u8]) -> Vec<u8> {
        let prefix = T::Prefix::get();
        let mut l = prefix.len() + what.len() + extra.len();
        let mut rev = Vec::new();
        while l > 0 {
            rev.push(b'0' + (l % 10) as u8);
            l /= 10;
        }
        let mut v = b"\x19Ethereum Signed Message:\n".to_vec();
        v.extend(rev.into_iter().rev());
        v.extend_from_slice(&prefix[..]);
        v.extend_from_slice(what);
        v.extend_from_slice(extra);
        v
    }

    // 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<EthereumAddress> {
        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)
    }

    fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> DispatchResult {
        let option_balance_of = <Claims<T>>::get(&signer);
        let balance_due = ok_or_error!(
            option_balance_of,
            Error::<T>::SignerHasNoClaim,
            "{}:{}. Signer has no claim. Address: {:?}.",
            file!(),
            line!(),
            signer
        )?;

        let option_checked = Self::total().checked_sub(&balance_due);
        let new_total = ok_or_error!(option_checked, Error::<T>::PotUnderflow,
        "{}:{}. Not enough in the pot to pay out some unvested amount. Total: {:?}, balanceOf: {:?}, address: {:?}", 
        file!(), line!(), Self::total(), balance_due, signer)?;

        let vesting = Vesting::<T>::get(&signer);
        if vesting.is_some() && T::VestingSchedule::vesting_balance(&dest).is_some() {
            return Err({
                debug::error!("{}:{}. The account already has a vested balance. Who ID: {:?}, dest ethereum address: {:?}.", 
            file!(), line!(), dest, signer);
                Error::<T>::VestedBalanceExists.into()
            });
        }

        // Check if this claim should have a vesting schedule.
        if let Some(vs) = vesting {
            let initial_balance = balance_due.saturating_sub(vs.0);
            CurrencyOf::<T>::deposit_creating(&dest, initial_balance);
            let vesting_account_id = T::VestingAccountGetter::get_account_id();

            #[allow(unused_must_use)]
            {
                CurrencyOf::<T>::deposit_creating(&vesting_account_id, vs.0);
            }

            // 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)
                .expect("No other vesting schedule exists, as checked above; qed");
        } else {
            CurrencyOf::<T>::deposit_creating(&dest, balance_due);
        }

        <Total<T>>::put(new_total);
        <Claims<T>>::remove(&signer);
        <Vesting<T>>::remove(&signer);
        Signing::remove(&signer);

        // Let's deposit an event to let the outside world know this happened.
        Self::deposit_event(RawEvent::Claimed(dest, signer, balance_due));

        Ok(())
    }
}

impl<T: Trait> sp_runtime::traits::ValidateUnsigned for Module<T> {
    type Call = Call<T>;

    fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
        const PRIORITY: u64 = 100;

        let (maybe_signer, maybe_statement) = match call {
            // <weight>
            // Base Weight: 188.7 µs (includes the full logic of `validate_unsigned`)
            // DB Weight: 2 Read (Claims, Signing)
            // </weight>
            Call::claim(account, ethereum_signature) => {
                let data = account.using_encoded(to_ascii_hex);
                (Self::eth_recover(&ethereum_signature, &data, &[][..]), None)
            }
            // <weight>
            // Base Weight: 190.1 µs (includes the full logic of `validate_unsigned`)
            // DB Weight: 2 Read (Claims, Signing)
            // </weight>
            Call::claim_attest(account, ethereum_signature, statement) => {
                let data = account.using_encoded(to_ascii_hex);
                (
                    Self::eth_recover(&ethereum_signature, &data, &statement),
                    Some(statement.as_slice()),
                )
            }
            _ => {
                debug::error!("{}:{}. Call didn't match claim options", file!(), line!());
                return Err(InvalidTransaction::Call.into());
            }
        };

        let signer = ok_or_error!(
            maybe_signer,
            InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()),
            "{}:{}. Invalid Ethereum signature. Signature: {:?}.",
            file!(),
            line!(),
            maybe_signer
        )?;

        let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into());
        eq_ensure!(
            <Claims<T>>::contains_key(&signer),
            e,
            "{}:{}. Signer has no claim. Who: {:?}.",
            file!(),
            line!(),
            signer
        );

        let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into());
        let s = Signing::get(signer);
        if s {
            eq_ensure!(Some(get_statement_text()) == maybe_statement, e,
            "{}:{}. Get_statement_text() not equal to statement from params. Get statement text: {:?}, from params: {:?}.",
            file!(), line!(), get_statement_text(), maybe_statement);
        } else {
            eq_ensure!(
                maybe_statement.is_none(),
                e,
                "{}:{}. Statement is none",
                file!(),
                line!()
            );
        }

        Ok(ValidTransaction {
            priority: PRIORITY,
            requires: vec![],
            provides: vec![("claims", signer).encode()],
            longevity: TransactionLongevity::max_value(),
            propagate: true,
        })
    }
}

/// 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)]
pub struct PrevalidateAttests<T: Trait + Send + Sync>(sp_std::marker::PhantomData<T>)
where
    <T as frame_system::Trait>::Call: IsSubType<Call<T>>;

impl<T: Trait + Send + Sync> Debug for PrevalidateAttests<T>
where
    <T as frame_system::Trait>::Call: IsSubType<Call<T>>,
{
    #[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<T: Trait + Send + Sync> PrevalidateAttests<T>
where
    <T as frame_system::Trait>::Call: IsSubType<Call<T>>,
{
    /// Create new `SignedExtension` to check runtime version.
    pub fn new() -> Self {
        Self(sp_std::marker::PhantomData)
    }
}

impl<T: Trait + Send + Sync> SignedExtension for PrevalidateAttests<T>
where
    <T as frame_system::Trait>::Call: IsSubType<Call<T>>,
{
    type AccountId = T::AccountId;
    type Call = <T as frame_system::Trait>::Call;
    type AdditionalSigned = ();
    type Pre = ();
    const IDENTIFIER: &'static str = "PrevalidateAttests";

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

    // <weight>
    // Base Weight: 8.631 µs
    // DB Weight: 2 Read (Preclaims, Signing)
    // </weight>
    fn validate(
        &self,
        who: &Self::AccountId,
        call: &Self::Call,
        _info: &DispatchInfoOf<Self::Call>,
        _len: usize,
    ) -> TransactionValidity {
        if let Some(local_call) = call.is_sub_type() {
            if let Call::attest(attested_statement) = local_call {
                let option_ethereum_address = Preclaims::<T>::get(who);
                let signer = ok_or_error!(
                    option_ethereum_address,
                    InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()),
                    "{}:{}. Signer has no claim. Who: {:?}.",
                    file!(),
                    line!(),
                    who
                )?;
                let s = Signing::get(signer);
                if s {
                    let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into());
                    eq_ensure!(&attested_statement[..] == get_statement_text(), e,
                    "{}:{}. Get_statement_text() not equal to statement from call. Get statement text: {:?}, from call: {:?}.",
                    file!(), line!(), get_statement_text(), &attested_statement[..]);
                }
            }
        }
        Ok(ValidTransaction::default())
    }
}