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
use std::sync::Arc;
use clap::Parser;

/// EVM Tracing CLI flags
#[derive(PartialEq, Clone, Debug)]
pub enum EthApi {
    /// Enable EVM debug RPC methods.
    Debug,
    /// Enable EVM trace RPC methods.
    Trace,
    /// Enable pending transactions RPC methods.
    TxPool,

}

impl std::str::FromStr for EthApi {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "debug" => Ok(EthApi::Debug),
            "trace" => Ok(EthApi::Trace),
            "txpool" => Ok(EthApi::TxPool),
            _ => Err(format!("Invalid EthApi: {}", s))
        }
    }
}

/// Available frontier backends
#[derive(PartialEq, Clone, Debug, Copy, clap::ValueEnum, Default)]
pub enum FrontierBackendType {
    /// RocksDB or ParityDB as inherited from the global settings
    #[default]
    KeyValue,
    /// Sql database with custom log indexing
    Sql
}

/// EVM Tracing CLI config
#[derive(Clone)]
pub struct EvmTracingConfig {
    /// Enabled EVM tracing flags.
    pub ethapi: Vec<EthApi>,
    /// Number of concurrent tracing tasks.
    pub ethapi_max_permits: u32,
    /// The Maximum number of trace entries a single request of `trace_filter` is allowed to return.
    /// A request asking for more or an unbounded one going over this limit will both return an
    /// error.
    pub ethapi_trace_max_count: u32,
    /// Duration (in seconds) after which the cache of `trace_filter` for a given block will be
    /// discarded.
    pub ethapi_trace_cache_duration: u64,
    /// Size in bytes of the LRU cache for block data.
    pub eth_log_block_cache: usize,
    /// Size in bytes of the LRU cache for transaction statuses data.
    pub eth_statuses_cache: usize,
    /// Maximum number of logs in a query.
    pub max_past_logs: u32,
    /// Size in bytes of data a raw tracing request is allowed to use.
    /// Bound the size of memory, stack and storage data.
    pub tracing_raw_max_memory_usage: usize,

    pub fee_history_limit: u64,
    pub frontier_backend_type: FrontierBackendType,
    pub frontier_sql_backend_pool_size: u32,
    pub frontier_sql_backend_num_ops_timeout: u32,
    pub frontier_sql_backend_thread_count: u32,
    pub frontier_sql_backend_cache_size: u64,
}

impl EthApiOptions {
    pub fn build_evm_tracing_config(&self) -> EvmTracingConfig {
        EvmTracingConfig {
            ethapi: self.ethapi.clone(),
            ethapi_max_permits: self.ethapi_max_permits,
            ethapi_trace_max_count: self.ethapi_trace_max_count,
            ethapi_trace_cache_duration: self.ethapi_trace_cache_duration,
            eth_log_block_cache: self.eth_log_block_cache,
            eth_statuses_cache: self.eth_statuses_cache,
            max_past_logs: self.max_past_logs,
            fee_history_limit: self.fee_history_limit,
            tracing_raw_max_memory_usage: self.tracing_raw_max_memory_usage,
            frontier_backend_type: self.frontier_backend_type,
            frontier_sql_backend_pool_size: self.frontier_sql_backend_pool_size,
            frontier_sql_backend_num_ops_timeout: self.frontier_sql_backend_num_ops_timeout,
            frontier_sql_backend_thread_count: self.frontier_sql_backend_thread_count,
            frontier_sql_backend_cache_size: self.frontier_sql_backend_cache_size,
        }
    }
}


#[derive(Debug, Parser)]
pub struct EthApiOptions {
    /// Enable EVM tracing module on a non-authority node.
    #[clap(
    long,
    conflicts_with = "validator",
    value_delimiter = ','
    )]
    pub ethapi: Vec<EthApi>,

    /// Number of concurrent tracing tasks. Meant to be shared by both "debug" and "trace" modules.
    #[clap(long, default_value = "10")]
    pub ethapi_max_permits: u32,

    /// The Maximum number of trace entries a single request of `trace_filter` is allowed to return.
    /// A request asking for more or an unbounded one going over this limit will both return an
    /// error.
    #[clap(long, default_value = "500")]
    pub ethapi_trace_max_count: u32,

    /// Duration (in seconds) after which the cache of `trace_filter` for a given block will be
    /// discarded.
    #[clap(long, default_value = "300")]
    pub ethapi_trace_cache_duration: u64,

    /// Sets the frontierBackend type, either KeyValue of SQL
    #[clap(long, value_enum, ignore_case = true, default_value_t = FrontierBackendType::default())]
    pub frontier_backend_type: FrontierBackendType,

    /// Size in bytes of the LRU cache for block data.
    #[clap(long, default_value = "300000000")]
    pub eth_log_block_cache: usize,

    /// Size in bytes of the LRU cache for transaction statuses data.
    #[clap(long, default_value = "300000000")]
    pub eth_statuses_cache: usize,

    /// Size in bytes of data a raw tracing request is allowed to use.
    /// Bound the size of memory, stack and storage data.
    #[clap(long, default_value = "20000000")]
    pub tracing_raw_max_memory_usage: usize,

    /// Maximum number of logs in a query.
    #[clap(long, default_value = "10000")]
    pub max_past_logs: u32,

    /// Maximum fee history cache size.
    #[arg(long, default_value = "2048")]
    pub fee_history_limit: u64,

    // Sets the SQL backend's pool size.
    #[arg(long, default_value = "100")]
    pub frontier_sql_backend_pool_size: u32,

    /// Sets the SQL backend's query timeout in number of VM ops.
    #[arg(long, default_value = "10000000")]
    pub frontier_sql_backend_num_ops_timeout: u32,

    /// Sets the SQL backend's auxiliary thread limit.
    #[arg(long, default_value = "4")]
    pub frontier_sql_backend_thread_count: u32,

    /// Sets the SQL backend's query timeout in number of VM ops.
    /// Default value is 200MB.
    #[arg(long, default_value = "209715200")]
    pub frontier_sql_backend_cache_size: u64,

}

pub(crate) fn db_config_dir(config: &sc_service::Configuration) -> std::path::PathBuf {
    config.base_path.config_dir(config.chain_spec.id())
}

/// Create a frontier backend
pub(crate) fn frontier_backend<B, C, BE>(
    config: &sc_service::Configuration,
    client: Arc<C>,
    eth_api_options: EvmTracingConfig,
) -> Result<fc_db::Backend<B>, String>
    where
        B: sp_runtime::traits::Block<Hash=sp_core::H256> + 'static,
        BE: sc_client_api::Backend<B> + 'static,
        C: sc_client_api::StorageProvider<B, BE> + Sync + Send + 'static
            + sp_api::ProvideRuntimeApi<B>
            + sc_client_api::HeaderBackend<B>,
        C::Api: fp_rpc::EthereumRuntimeRPCApi<B>,
{
    let db_config_dir = db_config_dir(config);
    let overrides_handle = fc_storage::overrides_handle(client.clone());
    match eth_api_options.frontier_backend_type {
        FrontierBackendType::KeyValue => {
            let db = fc_db::kv::Backend::open(
                client, &config.database, &db_config_dir)?;
            Ok(fc_db::Backend::<B>::KeyValue(db))
        },
        FrontierBackendType::Sql => {
            let db_path = db_config_dir.join("sql");
            std::fs::create_dir_all(&db_path).expect("failed creating sql db directory");
            let backend = futures::executor::block_on(fc_db::sql::Backend::new(
                fc_db::sql::BackendConfig::Sqlite(fc_db::sql::SqliteBackendConfig {
                    path: std::path::Path::new("sqlite:///")
                        .join(db_path)
                        .join("frontier.db3")
                        .to_str()
                        .unwrap(),
                    create_if_missing: true,
                    thread_count: eth_api_options.frontier_sql_backend_thread_count,
                    cache_size: eth_api_options.frontier_sql_backend_cache_size,
                }),
                eth_api_options.frontier_sql_backend_pool_size,
                std::num::NonZeroU32::new(eth_api_options.frontier_sql_backend_num_ops_timeout),
                overrides_handle,
            ))
                .unwrap_or_else(|err| panic!("failed creating sql backend: {:?}", err));
            Ok(fc_db::Backend::<B>::Sql(backend))
        }
    }
}