Skip to main content

domain_test_service/
lib.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3
4// Cumulus is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Cumulus is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Cumulus.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Crate used for testing with Domain.
18
19pub mod chain_spec;
20pub mod domain;
21pub mod keyring;
22
23pub use domain::*;
24use domain_runtime_primitives::opaque::Block;
25pub use evm_domain_test_runtime;
26use frame_support::dispatch::{DispatchInfo, PostDispatchInfo};
27use frame_system::pallet_prelude::{BlockNumberFor, RuntimeCallFor};
28pub use keyring::Keyring as EcdsaKeyring;
29use sc_network::config::{NonReservedPeerMode, TransportConfig};
30use sc_network::multiaddr;
31use sc_service::config::{
32    DatabaseSource, ExecutorConfiguration, KeystoreConfig, MultiaddrWithPeerId,
33    NetworkConfiguration, OffchainWorkerConfig, PruningMode, RpcBatchRequestConfig,
34    RpcConfiguration, RpcEndpoint, WasmExecutionMethod, WasmtimeInstantiationStrategy,
35};
36use sc_service::{
37    BasePath, BlocksPruning, ChainSpec, Configuration as ServiceConfiguration,
38    Error as ServiceError, Role,
39};
40use serde::de::DeserializeOwned;
41use sp_arithmetic::traits::SaturatedConversion;
42use sp_blockchain::HeaderBackend;
43use sp_core::{Get, H256};
44use sp_domains::DomainId;
45pub use sp_keyring::Sr25519Keyring;
46use sp_runtime::codec::{Decode, Encode};
47use sp_runtime::generic;
48use sp_runtime::generic::SignedPayload;
49use sp_runtime::traits::{AsSystemOriginSigner, Dispatchable};
50use std::fmt::{Debug, Display};
51use std::net::SocketAddr;
52use std::str::FromStr;
53use subspace_runtime_primitives::extension::SmallOrderEd25519CheckExtension;
54
55/// The domain id of the evm domain
56pub const EVM_DOMAIN_ID: DomainId = DomainId::new(0u32);
57
58/// The domain id of the auto-id domain
59pub const AUTO_ID_DOMAIN_ID: DomainId = DomainId::new(1u32);
60
61/// Create a domain node `Configuration`.
62///
63/// By default an in-memory socket will be used, therefore you need to provide nodes if you want the
64/// node to be connected to other nodes. If `nodes_exclusive` is `true`, the node will only connect
65/// to the given `nodes` and not to any other node.
66#[allow(clippy::too_many_arguments)]
67#[expect(clippy::result_large_err, reason = "Comes from Substrate")]
68pub fn node_config(
69    domain_id: DomainId,
70    tokio_handle: tokio::runtime::Handle,
71    key_seed: String,
72    nodes: Vec<MultiaddrWithPeerId>,
73    nodes_exclusive: bool,
74    role: Role,
75    base_path: BasePath,
76    chain_spec: Box<dyn ChainSpec>,
77    rpc_addr: Option<SocketAddr>,
78    rpc_port: Option<u16>,
79) -> Result<ServiceConfiguration, ServiceError> {
80    let root = base_path.path().to_path_buf();
81
82    let domain_name = format!("{domain_id:?}");
83
84    let mut network_config = NetworkConfiguration::new(
85        format!("{key_seed} ({domain_name})"),
86        "network/test/0.1",
87        Default::default(),
88        None,
89    );
90
91    if nodes_exclusive {
92        network_config.default_peers_set.reserved_nodes = nodes;
93        network_config.default_peers_set.non_reserved_mode = NonReservedPeerMode::Deny;
94    } else {
95        network_config.boot_nodes = nodes;
96    }
97
98    network_config.allow_non_globals_in_dht = true;
99
100    network_config
101        .listen_addresses
102        .push(multiaddr::Protocol::Memory(rand::random()).into());
103
104    // NOTE: Block sync is disabled for the domain subnet thus the major sync state may not be accurate,
105    // which will cause transaction not propagate through network properly, setting the `force_synced`
106    // flag can workaround this issue.
107    network_config.force_synced = true;
108
109    network_config.transport = TransportConfig::MemoryOnly;
110
111    let rpc_configuration = match rpc_addr {
112        Some(listen_addr) => {
113            let port = rpc_port.unwrap_or(9945);
114            RpcConfiguration {
115                addr: Some(vec![RpcEndpoint {
116                    batch_config: RpcBatchRequestConfig::Disabled,
117                    max_connections: 100,
118                    listen_addr,
119                    rpc_methods: Default::default(),
120                    rate_limit: None,
121                    rate_limit_trust_proxy_headers: false,
122                    rate_limit_whitelisted_ips: vec![],
123                    max_payload_in_mb: 15,
124                    max_payload_out_mb: 15,
125                    max_subscriptions_per_connection: 100,
126                    max_buffer_capacity_per_connection: 100,
127                    cors: None,
128                    retry_random_port: true,
129                    is_optional: false,
130                }]),
131                max_request_size: 15,
132                max_response_size: 15,
133                id_provider: None,
134                max_subs_per_conn: 1024,
135                port,
136                message_buffer_capacity: 1024,
137                batch_config: RpcBatchRequestConfig::Disabled,
138                max_connections: 1000,
139                cors: None,
140                methods: Default::default(),
141                rate_limit: None,
142                rate_limit_whitelisted_ips: vec![],
143                rate_limit_trust_proxy_headers: false,
144                request_logger_limit: 1024,
145            }
146        }
147        None => RpcConfiguration {
148            addr: None,
149            max_request_size: 0,
150            max_response_size: 0,
151            id_provider: None,
152            max_subs_per_conn: 0,
153            port: 0,
154            message_buffer_capacity: 0,
155            batch_config: RpcBatchRequestConfig::Disabled,
156            max_connections: 0,
157            cors: None,
158            methods: Default::default(),
159            rate_limit: None,
160            rate_limit_whitelisted_ips: vec![],
161            rate_limit_trust_proxy_headers: false,
162            request_logger_limit: 1024,
163        },
164    };
165
166    Ok(ServiceConfiguration {
167        impl_name: "domain-test-node".to_string(),
168        impl_version: "0.1".to_string(),
169        role,
170        tokio_handle,
171        transaction_pool: Default::default(),
172        network: network_config,
173        keystore: KeystoreConfig::InMemory,
174        database: DatabaseSource::ParityDb {
175            path: root.join("paritydb"),
176        },
177        trie_cache_maximum_size: Some(16 * 1024 * 1024),
178        state_pruning: Some(PruningMode::ArchiveAll),
179        blocks_pruning: BlocksPruning::KeepAll,
180        chain_spec,
181        executor: ExecutorConfiguration {
182            wasm_method: WasmExecutionMethod::Compiled {
183                instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite,
184            },
185            max_runtime_instances: 8,
186            default_heap_pages: None,
187            runtime_cache_size: 2,
188        },
189        rpc: rpc_configuration,
190        prometheus_config: None,
191        telemetry_endpoints: None,
192        offchain_worker: OffchainWorkerConfig {
193            enabled: true,
194            indexing_enabled: false,
195        },
196        force_authoring: false,
197        disable_grandpa: false,
198        dev_key_seed: Some(key_seed),
199        tracing_targets: None,
200        tracing_receiver: Default::default(),
201        announce_block: true,
202        data_path: base_path.path().into(),
203        base_path,
204        wasm_runtime_overrides: None,
205        warm_up_trie_cache: None,
206    })
207}
208
209type SignedExtraFor<Runtime> = (
210    frame_system::CheckNonZeroSender<Runtime>,
211    SmallOrderEd25519CheckExtension<Runtime>,
212    frame_system::CheckSpecVersion<Runtime>,
213    frame_system::CheckTxVersion<Runtime>,
214    frame_system::CheckGenesis<Runtime>,
215    frame_system::CheckMortality<Runtime>,
216    frame_system::CheckNonce<Runtime>,
217    domain_check_weight::CheckWeight<Runtime>,
218    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
219);
220
221type UncheckedExtrinsicFor<Runtime> = generic::UncheckedExtrinsic<
222    <Runtime as DomainRuntime>::Address,
223    <Runtime as frame_system::Config>::RuntimeCall,
224    <Runtime as DomainRuntime>::Signature,
225    SignedExtraFor<Runtime>,
226>;
227
228type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
229
230pub fn construct_extrinsic_raw_payload<Runtime, Client>(
231    client: impl AsRef<Client>,
232    function: RuntimeCallFor<Runtime>,
233    immortal: bool,
234    nonce: u32,
235    tip: BalanceOf<Runtime>,
236) -> (
237    SignedPayload<RuntimeCallFor<Runtime>, SignedExtraFor<Runtime>>,
238    SignedExtraFor<Runtime>,
239)
240where
241    Runtime: frame_system::Config<Hash = H256>
242        + pallet_transaction_payment::Config
243        + frame_support::pallet_prelude::TypeInfo
244        + Debug
245        + Send
246        + Sync,
247    RuntimeCallFor<Runtime>:
248        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + Send + Sync,
249    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
250    u64: From<BlockNumberFor<Runtime>>,
251    Client: HeaderBackend<Block>,
252    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
253        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + Clone,
254{
255    let current_block_hash = client.as_ref().info().best_hash;
256    let current_block = client.as_ref().info().best_number.saturated_into();
257    let genesis_block = client.as_ref().hash(0).unwrap().unwrap();
258    let period = u64::from(<Runtime as frame_system::Config>::BlockHashCount::get())
259        .checked_next_power_of_two()
260        .map(|c| c / 2)
261        .unwrap_or(2);
262    let extra: SignedExtraFor<Runtime> = (
263        frame_system::CheckNonZeroSender::<Runtime>::new(),
264        SmallOrderEd25519CheckExtension::<Runtime>::new(),
265        frame_system::CheckSpecVersion::<Runtime>::new(),
266        frame_system::CheckTxVersion::<Runtime>::new(),
267        frame_system::CheckGenesis::<Runtime>::new(),
268        frame_system::CheckMortality::<Runtime>::from(if immortal {
269            generic::Era::Immortal
270        } else {
271            generic::Era::mortal(period, current_block)
272        }),
273        frame_system::CheckNonce::<Runtime>::from(nonce.into()),
274        domain_check_weight::CheckWeight::<Runtime>::new(),
275        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
276    );
277    (
278        generic::SignedPayload::<RuntimeCallFor<Runtime>, SignedExtraFor<Runtime>>::from_raw(
279            function,
280            extra.clone(),
281            ((), (), 1, 0, genesis_block, current_block_hash, (), (), ()),
282        ),
283        extra,
284    )
285}
286
287pub trait DomainRuntime: frame_support::pallet_prelude::TypeInfo + Debug {
288    type Keyring: Copy;
289    type AccountId: DeserializeOwned
290        + Encode
291        + Decode
292        + Clone
293        + Debug
294        + Display
295        + FromStr
296        + Sync
297        + Send
298        + 'static;
299    type Address: Encode + Decode;
300    type Signature: Encode + Decode;
301    fn sign(key: Self::Keyring, payload: &[u8]) -> Self::Signature;
302    fn account_id(key: Self::Keyring) -> Self::AccountId;
303    fn address(key: Self::Keyring) -> Self::Address;
304    fn to_seed(key: Self::Keyring) -> String;
305}
306
307impl DomainRuntime for evm_domain_test_runtime::Runtime {
308    type Keyring = EcdsaKeyring;
309    type AccountId = evm_domain_test_runtime::AccountId;
310    type Address = evm_domain_test_runtime::Address;
311    type Signature = evm_domain_test_runtime::Signature;
312
313    fn sign(key: Self::Keyring, payload: &[u8]) -> Self::Signature {
314        evm_domain_test_runtime::Signature::new(key.sign(payload))
315    }
316
317    fn account_id(key: Self::Keyring) -> Self::AccountId {
318        key.to_account_id()
319    }
320
321    fn address(key: Self::Keyring) -> Self::Address {
322        key.to_account_id()
323    }
324
325    fn to_seed(key: Self::Keyring) -> String {
326        key.to_seed()
327    }
328}
329
330impl DomainRuntime for auto_id_domain_test_runtime::Runtime {
331    type Keyring = Sr25519Keyring;
332    type AccountId = auto_id_domain_test_runtime::AccountId;
333    type Address = auto_id_domain_test_runtime::Address;
334    type Signature = auto_id_domain_test_runtime::Signature;
335
336    fn sign(key: Self::Keyring, payload: &[u8]) -> Self::Signature {
337        key.sign(payload).into()
338    }
339
340    fn account_id(key: Self::Keyring) -> Self::AccountId {
341        key.to_account_id()
342    }
343
344    fn address(key: Self::Keyring) -> Self::Address {
345        sp_runtime::MultiAddress::Id(key.to_account_id())
346    }
347
348    fn to_seed(key: Self::Keyring) -> String {
349        key.to_seed()
350    }
351}
352
353/// Construct an extrinsic that can be applied to the test runtime.
354pub fn construct_extrinsic_generic<Runtime, Client>(
355    client: impl AsRef<Client>,
356    function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
357    caller: Runtime::Keyring,
358    immortal: bool,
359    nonce: u32,
360    tip: BalanceOf<Runtime>,
361) -> UncheckedExtrinsicFor<Runtime>
362where
363    Runtime: frame_system::Config<Hash = H256>
364        + pallet_transaction_payment::Config
365        + DomainRuntime
366        + frame_support::pallet_prelude::TypeInfo
367        + Debug
368        + Send
369        + Sync,
370    Runtime::RuntimeCall:
371        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + Send + Sync,
372    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
373    u64: From<BlockNumberFor<Runtime>>,
374    Client: HeaderBackend<Block>,
375    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
376        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + Clone,
377{
378    let function = function.into();
379    let (raw_payload, extra) =
380        construct_extrinsic_raw_payload(client, function.clone(), immortal, nonce, tip);
381    let signature = raw_payload.using_encoded(|e| Runtime::sign(caller, e));
382    let address = Runtime::address(caller);
383    UncheckedExtrinsicFor::<Runtime>::new_signed(function, address, signature, extra)
384}
385
386/// Construct an unsigned extrinsic that can be applied to the test runtime.
387pub fn construct_unsigned_extrinsic<Runtime>(
388    function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
389) -> UncheckedExtrinsicFor<Runtime>
390where
391    Runtime: frame_system::Config<Hash = H256>
392        + pallet_transaction_payment::Config
393        + DomainRuntime
394        + frame_support::pallet_prelude::TypeInfo
395        + Debug
396        + Send
397        + Sync,
398    Runtime::RuntimeCall:
399        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + Send + Sync,
400    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
401{
402    let function = function.into();
403    UncheckedExtrinsicFor::<Runtime>::new_bare(function)
404}