-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathmod.rs
206 lines (184 loc) · 6.5 KB
/
mod.rs
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
extern crate alloc;
use alloc::format;
use core::marker::PhantomData;
use frame_support::dispatch::{GetDispatchInfo, Pays};
use frame_system::RawOrigin;
use pallet_evm::{
ExitError, ExitSucceed, GasWeightMapping, IsPrecompileResult, Precompile, PrecompileFailure,
PrecompileHandle, PrecompileOutput, PrecompileResult, PrecompileSet,
};
use pallet_evm_precompile_modexp::Modexp;
use pallet_evm_precompile_sha3fips::Sha3FIPS256;
use pallet_evm_precompile_simple::{ECRecover, ECRecoverPublicKey, Identity, Ripemd160, Sha256};
use sp_core::{hashing::keccak_256, H160};
use sp_runtime::{traits::Dispatchable, AccountId32};
use crate::{Runtime, RuntimeCall};
// Include custom precompiles
mod balance_transfer;
mod ed25519;
mod metagraph;
mod staking;
use balance_transfer::*;
use ed25519::*;
use metagraph::*;
use staking::*;
pub struct FrontierPrecompiles<R>(PhantomData<R>);
impl<R> Default for FrontierPrecompiles<R>
where
R: pallet_evm::Config,
{
fn default() -> Self {
Self::new()
}
}
impl<R> FrontierPrecompiles<R>
where
R: pallet_evm::Config,
{
pub fn new() -> Self {
Self(Default::default())
}
pub fn used_addresses() -> [H160; 11] {
[
hash(1),
hash(2),
hash(3),
hash(4),
hash(5),
hash(1024),
hash(1025),
hash(EDVERIFY_PRECOMPILE_INDEX),
hash(BALANCE_TRANSFER_INDEX),
hash(STAKING_PRECOMPILE_INDEX),
hash(METAGRAPH_PRECOMPILE_INDEX),
]
}
}
impl<R> PrecompileSet for FrontierPrecompiles<R>
where
R: pallet_evm::Config,
{
fn execute(&self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
match handle.code_address() {
// Ethereum precompiles :
a if a == hash(1) => Some(ECRecover::execute(handle)),
a if a == hash(2) => Some(Sha256::execute(handle)),
a if a == hash(3) => Some(Ripemd160::execute(handle)),
a if a == hash(4) => Some(Identity::execute(handle)),
a if a == hash(5) => Some(Modexp::execute(handle)),
// Non-Frontier specific nor Ethereum precompiles :
a if a == hash(1024) => Some(Sha3FIPS256::execute(handle)),
a if a == hash(1025) => Some(ECRecoverPublicKey::execute(handle)),
a if a == hash(EDVERIFY_PRECOMPILE_INDEX) => Some(Ed25519Verify::execute(handle)),
// Subtensor specific precompiles :
a if a == hash(BALANCE_TRANSFER_INDEX) => {
Some(BalanceTransferPrecompile::execute(handle))
}
a if a == hash(STAKING_PRECOMPILE_INDEX) => Some(StakingPrecompile::execute(handle)),
a if a == hash(METAGRAPH_PRECOMPILE_INDEX) => {
Some(MetagraphPrecompile::execute(handle))
}
_ => None,
}
}
fn is_precompile(&self, address: H160, _gas: u64) -> IsPrecompileResult {
IsPrecompileResult::Answer {
is_precompile: Self::used_addresses().contains(&address),
extra_cost: 0,
}
}
}
fn hash(a: u64) -> H160 {
H160::from_low_u64_be(a)
}
/// Returns Ethereum method ID from an str method signature
///
pub fn get_method_id(method_signature: &str) -> [u8; 4] {
// Calculate the full Keccak-256 hash of the method signature
let hash = keccak_256(method_signature.as_bytes());
// Extract the first 4 bytes to get the method ID
[hash[0], hash[1], hash[2], hash[3]]
}
/// Convert bytes to AccountId32 with PrecompileFailure as Error
/// which consumes all gas
///
pub fn bytes_to_account_id(account_id_bytes: &[u8]) -> Result<AccountId32, PrecompileFailure> {
AccountId32::try_from(account_id_bytes).map_err(|_| {
log::info!("Error parsing account id bytes {:?}", account_id_bytes);
PrecompileFailure::Error {
exit_status: ExitError::InvalidRange,
}
})
}
/// Takes a slice from bytes with PrecompileFailure as Error
///
pub fn get_slice(data: &[u8], from: usize, to: usize) -> Result<&[u8], PrecompileFailure> {
let maybe_slice = data.get(from..to);
if let Some(slice) = maybe_slice {
Ok(slice)
} else {
Err(PrecompileFailure::Error {
exit_status: ExitError::InvalidRange,
})
}
}
/// Dispatches a runtime call, but also checks and records the gas costs.
fn try_dispatch_runtime_call(
handle: &mut impl PrecompileHandle,
call: impl Into<RuntimeCall>,
origin: RawOrigin<AccountId32>,
) -> PrecompileResult {
let call = Into::<RuntimeCall>::into(call);
let info = call.get_dispatch_info();
let target_gas = handle.gas_limit();
if let Some(gas) = target_gas {
let valid_weight =
<Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(gas, false).ref_time();
if info.weight.ref_time() > valid_weight {
return Err(PrecompileFailure::Error {
exit_status: ExitError::OutOfGas,
});
}
}
handle.record_external_cost(
Some(info.weight.ref_time()),
Some(info.weight.proof_size()),
None,
)?;
match call.dispatch(origin.into()) {
Ok(post_info) => {
if post_info.pays_fee(&info) == Pays::Yes {
let actual_weight = post_info.actual_weight.unwrap_or(info.weight);
let cost =
<Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(actual_weight);
handle.record_cost(cost)?;
handle.refund_external_cost(
Some(
info.weight
.ref_time()
.saturating_sub(actual_weight.ref_time()),
),
Some(
info.weight
.proof_size()
.saturating_sub(actual_weight.proof_size()),
),
);
}
log::info!("Dispatch succeeded. Post info: {:?}", post_info);
Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
output: Default::default(),
})
}
Err(e) => {
log::error!("Dispatch failed. Error: {:?}", e);
log::warn!("Returning error PrecompileFailure::Error");
Err(PrecompileFailure::Error {
exit_status: ExitError::Other(
format!("dispatch execution failed: {}", <&'static str>::from(e)).into(),
),
})
}
}
}