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
// The account-mapping pallet is inspired by evm mapping designed by AcalaNetwork

// 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.

//! # Evm Accounts Module
//!
//! ## Overview
//!
//! Evm Accounts module provide a two way mapping between Substrate accounts and
//! EVM accounts so user only have deal with one account / private key.

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]

use circuit_runtime_types::{AccountIndex, EvmAddress};
use frame_support::{
    ensure, log,
    pallet_prelude::*,
    traits::{Currency, ExistenceRequirement, IsType, OnKilledAccount},
    transactional,
};
use frame_system::{ensure_signed, pallet_prelude::*};
use pallet_3vm_evm::AddressMapping as BaseAddressMapping;
use scale_codec::Encode;
use sp_core::crypto::AccountId32;
use sp_io::{
    crypto::secp256k1_ecdsa_recover,
    hashing::{blake2_256, keccak_256},
};
use sp_runtime::{
    traits::{LookupError, Saturating, StaticLookup},
    MultiAddress,
};
use sp_std::{marker::PhantomData, vec::Vec};
use t3rn_primitives::{attesters::ETH_SIGNED_MESSAGE_PREFIX, threevm::AddressMapping};
//pub use weights::WeightInfo;

//#[cfg(feature = "runtime-benchmarks")]
//pub mod benchmarking;
mod tests;
//pub mod weights;
pub use pallet::*;

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

/// 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
}

/// Constructs the message that Ethereum RPC's `personal_sign` and `eth_sign` would sign.
pub fn ethereum_signable_message(what: &[u8], extra: &[u8]) -> Vec<u8> {
    let message_digest = keccak_256([what, extra].concat().as_slice());
    [&ETH_SIGNED_MESSAGE_PREFIX[..], &message_digest[..]].concat()
}

#[frame_support::pallet]
pub mod pallet {
    use super::*;

    pub(crate) type BalanceOf<T> =
        <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

    #[pallet::config]
    pub trait Config: frame_system::Config {
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        /// The Currency for managing Evm account assets.
        type Currency: Currency<Self::AccountId>;

        /// Mapping from address to account id.
        type AddressMapping: AddressMapping<Self::AccountId>;

        /// Chain ID of EVM.
        #[pallet::constant]
        type ChainId: Get<u64>;

        /// The network treasury account
        #[pallet::constant]
        type NetworkTreasuryAccount: Get<Self::AccountId>;

        /// Storage deposit free charged when saving data into the blockchain.
        #[pallet::constant]
        type StorageDepositFee: Get<BalanceOf<Self>>;
    }

    #[pallet::event]
    #[pallet::generate_deposit(fn deposit_event)]
    pub enum Event<T: Config> {
        /// Mapping between Substrate accounts and EVM accounts
        /// claim account.
        ClaimAccount {
            account_id: T::AccountId,
            evm_address: EvmAddress,
        },
    }

    /// Error for evm accounts module.
    #[pallet::error]
    pub enum Error<T> {
        /// AccountId has mapped
        AccountIdHasMapped,
        /// Eth address has mapped
        EthAddressHasMapped,
        /// Bad signature
        BadSignature,
        /// Invalid signature
        InvalidSignature,
        // Pre-image address not matching recovered
        PreImageAddressNotMatchingRecovered,
        /// Account ref count is not zero
        NonZeroRefCount,
    }

    /// The Substrate Account for EvmAddresses
    ///
    /// Accounts: map EvmAddress => Option<AccountId>
    #[pallet::storage]
    #[pallet::getter(fn accounts)]
    pub type Accounts<T: Config> =
        StorageMap<_, Twox64Concat, EvmAddress, T::AccountId, OptionQuery>;

    /// The EvmAddress for Substrate Accounts
    ///
    /// EvmAddresses: map AccountId => Option<EvmAddress>
    #[pallet::storage]
    #[pallet::getter(fn evm_addresses)]
    pub type EvmAddresses<T: Config> =
        StorageMap<_, Twox64Concat, T::AccountId, EvmAddress, OptionQuery>;

    #[pallet::pallet]
    pub struct Pallet<T>(_);

    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Claim account mapping between Substrate accounts and EVM accounts.
        /// Ensure eth_address has not been mapped.
        ///
        /// - `eth_address`: The address to bind to the caller's account
        /// - `eth_signature`: A signature generated by the address to prove ownership
        #[pallet::call_index(0)]
        #[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
        #[transactional]
        pub fn claim_eth_account(
            origin: OriginFor<T>,
            eth_address: EvmAddress,
            eth_signature: EcdsaSignature,
        ) -> DispatchResultWithPostInfo {
            let who = ensure_signed(origin)?;

            // check if user already mapped account
            ensure!(
                !EvmAddresses::<T>::contains_key(&who),
                Error::<T>::AccountIdHasMapped
            );
            ensure!(
                !Accounts::<T>::contains_key(eth_address),
                Error::<T>::EthAddressHasMapped
            );

            let data = eth_address.0.as_slice();

            let address = Self::eth_recover(&eth_signature, &data, &[][..])
                .ok_or(Error::<T>::BadSignature)?;

            ensure!(
                eth_address == address,
                Error::<T>::PreImageAddressNotMatchingRecovered
            );

            // check if the evm padded address already exists
            let account_id = T::AddressMapping::into_account_id(&eth_address);
            if frame_system::Pallet::<T>::account_exists(&account_id) {
                // merge balance from `evm padded address` to `origin`
                <T as Config>::Currency::transfer(
                    &account_id,
                    &who,
                    <T as Config>::Currency::free_balance(&account_id),
                    ExistenceRequirement::AllowDeath,
                )?;
                //T::TransferAll::transfer_all(&account_id, &who)?;
            }

            // Transfer storage deposit fee
            <T as Config>::Currency::transfer(
                &who,
                &T::NetworkTreasuryAccount::get(),
                T::StorageDepositFee::get(),
                ExistenceRequirement::KeepAlive,
            )?;

            Accounts::<T>::insert(eth_address, &who);
            EvmAddresses::<T>::insert(&who, eth_address);

            Self::deposit_event(Event::ClaimAccount {
                account_id: who,
                evm_address: eth_address,
            });

            Ok(Pays::No.into())
        }

        /// Claim account mapping between Substrate accounts and a generated EVM
        /// address based off of those accounts.
        /// Ensure eth_address has not been mapped
        #[pallet::call_index(1)]
        #[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
        #[transactional]
        pub fn claim_default_account(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
            let who = ensure_signed(origin)?;

            // ensure account_id has not been mapped
            ensure!(
                !EvmAddresses::<T>::contains_key(&who),
                Error::<T>::AccountIdHasMapped
            );

            // Transfer storage deposit fee
            <T as Config>::Currency::transfer(
                &who,
                &T::NetworkTreasuryAccount::get(),
                T::StorageDepositFee::get(),
                ExistenceRequirement::KeepAlive,
            )?;

            let eth_address = T::AddressMapping::get_or_create_evm_address(&who);

            Self::deposit_event(Event::ClaimAccount {
                account_id: who,
                evm_address: eth_address,
            });

            Ok(Pays::No.into())
        }

        /// Claim account mapping between Substrate accounts and a generated EVM
        /// address based off of those accounts.
        /// Ensure eth_address has not been mapped
        #[pallet::call_index(2)]
        #[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
        #[transactional]
        pub fn unclaim(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
            let who = ensure_signed(origin)?;

            T::AddressMapping::get_evm_address(&who)
                .map(|eth_address| {
                    Accounts::<T>::remove(eth_address);
                    EvmAddresses::<T>::remove(&who);
                })
                .ok_or(Error::<T>::EthAddressHasMapped)?;

            Ok(Pays::Yes.into())
        }
    }
}

impl<T: Config> Pallet<T> {
    #[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
    // Returns an Etherum public key derived from an Ethereum secret key.
    pub fn eth_public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
        libsecp256k1::PublicKey::from_secret_key(secret)
    }

    #[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
    // Returns an Etherum address derived from an Ethereum secret key.
    // Only for tests
    pub fn eth_address(secret: &libsecp256k1::SecretKey) -> EvmAddress {
        EvmAddress::from_slice(&keccak_256(&Self::eth_public(secret).serialize()[1..65])[12..])
    }

    #[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
    // Constructs a message and signs it.
    pub fn eth_sign(secret: &libsecp256k1::SecretKey, _who: &T::AccountId) -> EcdsaSignature {
        let address = Self::eth_address(secret);

        let what = address.0.as_slice();
        // dbg!("{:?}", what);
        let msg = keccak_256(&Self::ethereum_signable_message(&what, &[][..]));
        let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);
        let mut r = [0u8; 65];
        r[0..64].copy_from_slice(&sig.serialize()[..]);
        r[64] = recovery_id.serialize();
        let signature = EcdsaSignature { 0: r };
        signature
    }

    // 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 message_digest = keccak_256([what, extra].concat().as_slice());
        [&ETH_SIGNED_MESSAGE_PREFIX[..], &message_digest[..]].concat()
    }

    // 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<EvmAddress> {
        let msg = keccak_256(&Self::ethereum_signable_message(what, extra));
        let mut res = EvmAddress::default();
        res.0
            .copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
        Some(res)
    }
}

// Creates a an EvmAddress from an AccountId by appending the bytes "evm:" to
// the account_id and hashing it.
fn account_to_default_evm_address(account_id: &impl Encode) -> EvmAddress {
    EvmAddress::from_slice(&account_id.encode().as_slice()[12..])
}

fn create_default_substrate_address(address: &EvmAddress) -> AccountId32 {
    let mut data: [u8; 32] = [0u8; 32];
    data[0..4].copy_from_slice(b"evm:");
    data[4..24].copy_from_slice(&address[..]);
    AccountId32::from(data)
}

pub struct EvmAddressMapping<T>(sp_std::marker::PhantomData<T>);

impl<T: Config> AddressMapping<T::AccountId> for EvmAddressMapping<T>
where
    T::AccountId: IsType<AccountId32>,
{
    // Returns the AccountId used go generate the given EvmAddress.
    fn into_account_id(address: &EvmAddress) -> T::AccountId {
        if let Some(acc) = Accounts::<T>::get(address) {
            log::info!(
                "AddressMapping::into_account_id - found matching account: {:?}",
                acc
            );
            acc
        } else {
            create_default_substrate_address(address).into()
        }
    }

    // Returns the EvmAddress associated with a given AccountId or the
    // underlying EvmAddress of the AccountId.
    // Returns None if there is no EvmAddress associated with the AccountId
    // and there is no underlying EvmAddress in the AccountId.
    fn get_evm_address(account_id: &T::AccountId) -> Option<EvmAddress> {
        // Return the EvmAddress if a mapping to account_id exists
        EvmAddresses::<T>::get(account_id).or_else(|| {
            let data: &[u8] = account_id.into_ref().as_ref();
            // Return the underlying EVM address if it exists otherwise return None
            if data.starts_with(b"evm:") {
                Some(EvmAddress::from_slice(&data[4..24]))
            } else {
                None
            }
        })
    }

    // Returns the EVM address associated with an account ID and generates an
    // account mapping if no association exists.
    fn get_or_create_evm_address(account_id: &T::AccountId) -> EvmAddress {
        Self::get_evm_address(account_id).unwrap_or_else(|| {
            let addr = account_to_default_evm_address(account_id);

            // create reverse mapping
            Accounts::<T>::insert(&addr, &account_id);
            EvmAddresses::<T>::insert(&account_id, &addr);

            addr
        })
    }

    // Returns the default EVM address associated with an account ID.
    fn get_default_evm_address(account_id: &T::AccountId) -> EvmAddress {
        account_to_default_evm_address(account_id)
    }

    // Returns true if a given AccountId is associated with a given EvmAddress
    // and false if is not.
    fn is_linked(account_id: &T::AccountId, evm: &EvmAddress) -> bool {
        Self::get_evm_address(account_id).as_ref() == Some(evm)
            || &account_to_default_evm_address(account_id.into_ref()) == evm
    }
}

impl<T: Config> BaseAddressMapping<T::AccountId> for EvmAddressMapping<T>
where
    T::AccountId: IsType<AccountId32>,
{
    // Returns the AccountId used go generate the given EvmAddress.
    fn into_account_id(address: EvmAddress) -> T::AccountId {
        if let Some(acc) = Accounts::<T>::get(&address) {
            log::info!("into_account_id - found matching account: {:?}", acc);
            acc
        } else {
            create_default_substrate_address(&address).into()
        }
    }
}
pub struct CallKillAccount<T>(PhantomData<T>);

impl<T: Config> OnKilledAccount<T::AccountId> for CallKillAccount<T> {
    fn on_killed_account(who: &T::AccountId) {
        // remove the reserve mapping that could be created by
        // `get_or_create_evm_address`
        Accounts::<T>::remove(account_to_default_evm_address(who.into_ref()));

        // remove mapping created by `claim_account`
        if let Some(evm_addr) = Pallet::<T>::evm_addresses(who) {
            Accounts::<T>::remove(evm_addr);
            EvmAddresses::<T>::remove(who);
        }
    }
}

impl<T: Config> StaticLookup for Pallet<T> {
    type Source = MultiAddress<T::AccountId, AccountIndex>;
    type Target = T::AccountId;

    fn lookup(a: Self::Source) -> Result<Self::Target, LookupError> {
        match a {
            MultiAddress::Address20(i) => Ok(T::AddressMapping::into_account_id(
                &EvmAddress::from_slice(&i),
            )),
            _ => Err(LookupError),
        }
    }

    fn unlookup(a: Self::Target) -> Self::Source {
        MultiAddress::Id(a)
    }
}