Skip to main content

subspace_test_service/
lib.rs

1// Copyright (C) 2021 Subspace Labs, Inc.
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4// This program 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// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
16
17//! Subspace test service only.
18
19#![warn(missing_docs, unused_crate_dependencies)]
20
21use cross_domain_message_gossip::{GossipWorkerBuilder, xdm_gossip_peers_set_config};
22use domain_runtime_primitives::opaque::{Block as DomainBlock, Header as DomainHeader};
23use frame_system::pallet_prelude::BlockNumberFor;
24use futures::channel::mpsc;
25use futures::{Future, StreamExt};
26use jsonrpsee::RpcModule;
27use pallet_domains::staking::StakingSummary;
28use parity_scale_codec::{Decode, Encode};
29use parking_lot::Mutex;
30use sc_block_builder::BlockBuilderBuilder;
31use sc_client_api::execution_extensions::ExtensionsFactory;
32use sc_client_api::{Backend as BackendT, BlockBackend, ExecutorProvider, Finalizer};
33use sc_consensus::block_import::{
34    BlockCheckParams, BlockImportParams, ForkChoiceStrategy, ImportResult,
35};
36use sc_consensus::{BasicQueue, BlockImport, StateAction, Verifier as VerifierT};
37use sc_domains::ExtensionsFactory as DomainsExtensionFactory;
38use sc_network::config::{NetworkConfiguration, TransportConfig};
39use sc_network::service::traits::NetworkService;
40use sc_network::{
41    NetworkWorker, NotificationMetrics, NotificationService, ReputationChange, multiaddr,
42};
43use sc_service::config::{
44    DatabaseSource, ExecutorConfiguration, KeystoreConfig, MultiaddrWithPeerId,
45    OffchainWorkerConfig, RpcBatchRequestConfig, RpcConfiguration, RpcEndpoint,
46    WasmExecutionMethod, WasmtimeInstantiationStrategy,
47};
48use sc_service::{BasePath, BlocksPruning, Configuration, Role, SpawnTasksParams, TaskManager};
49use sc_transaction_pool::{BasicPool, FullChainApi, Options};
50use sc_transaction_pool_api::error::{Error as TxPoolError, IntoPoolError};
51use sc_transaction_pool_api::{InPoolTransaction, TransactionPool, TransactionSource};
52use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender, tracing_unbounded};
53use sp_api::{ApiExt, ProvideRuntimeApi};
54use sp_blockchain::{HashAndNumber, HeaderBackend};
55use sp_consensus::{BlockOrigin, Error as ConsensusError};
56use sp_consensus_slots::Slot;
57use sp_consensus_subspace::digests::{
58    CompatibleDigestItem, PreDigest, PreDigestPotInfo, extract_pre_digest,
59};
60use sp_consensus_subspace::{PotExtension, SubspaceApi};
61use sp_core::H256;
62use sp_core::offchain::OffchainDbExt;
63use sp_core::offchain::storage::OffchainDb;
64use sp_core::traits::{CodeExecutor, SpawnEssentialNamed};
65use sp_domains::bundle::OpaqueBundle;
66use sp_domains::{BundleProducerElectionApi, ChainId, DomainId, DomainsApi, OperatorId};
67use sp_domains_fraud_proof::fraud_proof::FraudProof;
68use sp_domains_fraud_proof::{FraudProofExtension, FraudProofHostFunctionsImpl};
69use sp_externalities::Extensions;
70use sp_inherents::{InherentData, InherentDataProvider};
71use sp_keyring::Sr25519Keyring;
72use sp_messenger::MessengerApi;
73use sp_messenger_host_functions::{MessengerExtension, MessengerHostFunctionsImpl};
74use sp_mmr_primitives::MmrApi;
75use sp_runtime::generic::{Digest, SignedPayload};
76use sp_runtime::traits::{
77    BlakeTwo256, Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor,
78};
79use sp_runtime::{DigestItem, MultiAddress, OpaqueExtrinsic, SaturatedConversion, generic};
80use sp_subspace_mmr::host_functions::{SubspaceMmrExtension, SubspaceMmrHostFunctionsImpl};
81use sp_timestamp::Timestamp;
82use std::collections::HashMap;
83use std::error::Error;
84use std::marker::PhantomData;
85use std::net::SocketAddr;
86use std::pin::Pin;
87use std::sync::Arc;
88use std::time;
89use std::time::Duration;
90use subspace_core_primitives::pot::PotOutput;
91use subspace_core_primitives::solutions::Solution;
92use subspace_core_primitives::{BlockNumber, PublicKey};
93use subspace_runtime_primitives::extension::{
94    BalanceTransferCheckExtension, SmallOrderEd25519CheckExtension,
95};
96use subspace_runtime_primitives::opaque::Block;
97use subspace_runtime_primitives::{
98    AccountId, Balance, BlockHashFor, ExtrinsicFor, Hash, HeaderFor, Signature,
99};
100use subspace_service::{FullSelectChain, RuntimeExecutor};
101use subspace_test_client::{Backend, Client, chain_spec};
102use subspace_test_primitives::OnchainStateApi;
103use subspace_test_runtime::{
104    Runtime, RuntimeApi, RuntimeCall, SLOT_DURATION, SignedExtra, UncheckedExtrinsic,
105};
106use substrate_frame_rpc_system::AccountNonceApi;
107use substrate_test_client::{RpcHandlersExt, RpcTransactionError, RpcTransactionOutput};
108use tokio::time::sleep;
109
110/// Helper type alias
111pub type FraudProofFor<Block, DomainBlock> =
112    FraudProof<NumberFor<Block>, BlockHashFor<Block>, HeaderFor<DomainBlock>, H256>;
113
114const MAX_PRODUCE_BUNDLE_TRY: usize = 10;
115
116/// Create a Subspace `Configuration`.
117///
118/// By default an in-memory socket will be used, therefore you need to provide boot
119/// nodes if you want the future node to be connected to other nodes.
120#[expect(clippy::too_many_arguments)]
121pub fn node_config(
122    tokio_handle: tokio::runtime::Handle,
123    key: Sr25519Keyring,
124    boot_nodes: Vec<MultiaddrWithPeerId>,
125    run_farmer: bool,
126    force_authoring: bool,
127    force_synced: bool,
128    private_evm: bool,
129    evm_owner_account: Option<AccountId>,
130    base_path: BasePath,
131    rpc_addr: Option<SocketAddr>,
132    rpc_port: Option<u16>,
133) -> Configuration {
134    let root = base_path.path();
135    let role = if run_farmer {
136        Role::Authority
137    } else {
138        Role::Full
139    };
140    let key_seed = key.to_seed();
141    let spec = chain_spec::subspace_local_testnet_config(private_evm, evm_owner_account).unwrap();
142
143    let mut network_config = NetworkConfiguration::new(
144        key_seed.to_string(),
145        "network/test/0.1",
146        Default::default(),
147        None,
148    );
149
150    network_config.boot_nodes = boot_nodes;
151
152    network_config.allow_non_globals_in_dht = true;
153
154    let addr: multiaddr::Multiaddr = multiaddr::Protocol::Memory(rand::random()).into();
155    network_config.listen_addresses.push(addr.clone());
156
157    network_config.public_addresses.push(addr);
158
159    network_config.transport = TransportConfig::MemoryOnly;
160
161    network_config.force_synced = force_synced;
162
163    let rpc_configuration = match rpc_addr {
164        Some(listen_addr) => {
165            let port = rpc_port.unwrap_or(9944);
166            RpcConfiguration {
167                addr: Some(vec![RpcEndpoint {
168                    batch_config: RpcBatchRequestConfig::Disabled,
169                    max_connections: 100,
170                    listen_addr,
171                    rpc_methods: Default::default(),
172                    rate_limit: None,
173                    rate_limit_trust_proxy_headers: false,
174                    rate_limit_whitelisted_ips: vec![],
175                    max_payload_in_mb: 15,
176                    max_payload_out_mb: 15,
177                    max_subscriptions_per_connection: 100,
178                    max_buffer_capacity_per_connection: 100,
179                    cors: None,
180                    retry_random_port: true,
181                    is_optional: false,
182                }]),
183                max_request_size: 15,
184                max_response_size: 15,
185                id_provider: None,
186                max_subs_per_conn: 1024,
187                port,
188                message_buffer_capacity: 1024,
189                batch_config: RpcBatchRequestConfig::Disabled,
190                max_connections: 1000,
191                cors: None,
192                methods: Default::default(),
193                rate_limit: None,
194                rate_limit_whitelisted_ips: vec![],
195                rate_limit_trust_proxy_headers: false,
196                request_logger_limit: 1024,
197            }
198        }
199        None => RpcConfiguration {
200            addr: None,
201            max_request_size: 0,
202            max_response_size: 0,
203            id_provider: None,
204            max_subs_per_conn: 0,
205            port: 0,
206            message_buffer_capacity: 0,
207            batch_config: RpcBatchRequestConfig::Disabled,
208            max_connections: 0,
209            cors: None,
210            methods: Default::default(),
211            rate_limit: None,
212            rate_limit_whitelisted_ips: vec![],
213            rate_limit_trust_proxy_headers: false,
214            request_logger_limit: 1024,
215        },
216    };
217
218    Configuration {
219        impl_name: "subspace-test-node".to_string(),
220        impl_version: "0.1".to_string(),
221        role,
222        tokio_handle,
223        transaction_pool: Default::default(),
224        network: network_config,
225        keystore: KeystoreConfig::InMemory,
226        database: DatabaseSource::ParityDb {
227            path: root.join("paritydb"),
228        },
229        trie_cache_maximum_size: Some(64 * 1024 * 1024),
230        state_pruning: Default::default(),
231        blocks_pruning: BlocksPruning::KeepAll,
232        chain_spec: Box::new(spec),
233        executor: ExecutorConfiguration {
234            wasm_method: WasmExecutionMethod::Compiled {
235                instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite,
236            },
237            max_runtime_instances: 8,
238            default_heap_pages: None,
239            runtime_cache_size: 2,
240        },
241        wasm_runtime_overrides: Default::default(),
242        rpc: rpc_configuration,
243        prometheus_config: None,
244        telemetry_endpoints: None,
245        offchain_worker: OffchainWorkerConfig {
246            enabled: false,
247            indexing_enabled: true,
248        },
249        force_authoring,
250        disable_grandpa: false,
251        dev_key_seed: Some(key_seed),
252        tracing_targets: None,
253        tracing_receiver: Default::default(),
254        announce_block: true,
255        data_path: base_path.path().into(),
256        base_path,
257        warm_up_trie_cache: None,
258    }
259}
260
261type StorageChanges = sp_api::StorageChanges<Block>;
262
263struct MockExtensionsFactory<Client, DomainBlock, Executor, CBackend> {
264    consensus_client: Arc<Client>,
265    consensus_backend: Arc<CBackend>,
266    executor: Arc<Executor>,
267    mock_pot_verifier: Arc<MockPotVerfier>,
268    confirmation_depth_k: BlockNumber,
269    _phantom: PhantomData<DomainBlock>,
270}
271
272impl<Client, DomainBlock, Executor, CBackend>
273    MockExtensionsFactory<Client, DomainBlock, Executor, CBackend>
274{
275    fn new(
276        consensus_client: Arc<Client>,
277        executor: Arc<Executor>,
278        mock_pot_verifier: Arc<MockPotVerfier>,
279        consensus_backend: Arc<CBackend>,
280        confirmation_depth_k: BlockNumber,
281    ) -> Self {
282        Self {
283            consensus_client,
284            consensus_backend,
285            executor,
286            mock_pot_verifier,
287            confirmation_depth_k,
288            _phantom: Default::default(),
289        }
290    }
291}
292
293#[derive(Default)]
294struct MockPotVerfier(Mutex<HashMap<u64, PotOutput>>);
295
296impl MockPotVerfier {
297    fn is_valid(&self, slot: u64, pot: PotOutput) -> bool {
298        self.0.lock().get(&slot).map(|p| *p == pot).unwrap_or(false)
299    }
300
301    fn inject_pot(&self, slot: u64, pot: PotOutput) {
302        self.0.lock().insert(slot, pot);
303    }
304}
305
306impl<Block, Client, DomainBlock, Executor, CBackend> ExtensionsFactory<Block>
307    for MockExtensionsFactory<Client, DomainBlock, Executor, CBackend>
308where
309    Block: BlockT,
310    Block::Hash: From<H256> + Into<H256>,
311    DomainBlock: BlockT,
312    DomainBlock::Hash: Into<H256> + From<H256>,
313    Client: BlockBackend<Block> + HeaderBackend<Block> + ProvideRuntimeApi<Block> + 'static,
314    Client::Api: DomainsApi<Block, DomainBlock::Header>
315        + BundleProducerElectionApi<Block, Balance>
316        + MessengerApi<Block, NumberFor<Block>, Block::Hash>
317        + MmrApi<Block, H256, NumberFor<Block>>,
318    Executor: CodeExecutor + sc_executor::RuntimeVersionOf,
319    CBackend: BackendT<Block> + 'static,
320{
321    fn extensions_for(
322        &self,
323        _block_hash: Block::Hash,
324        _block_number: NumberFor<Block>,
325    ) -> Extensions {
326        let confirmation_depth_k = self.confirmation_depth_k;
327        let mut exts = Extensions::new();
328        exts.register(FraudProofExtension::new(Arc::new(
329            FraudProofHostFunctionsImpl::<_, _, DomainBlock, Executor, _>::new(
330                self.consensus_client.clone(),
331                self.executor.clone(),
332                move |client, executor| {
333                    let extension_factory =
334                        DomainsExtensionFactory::<_, Block, DomainBlock, _>::new(
335                            client,
336                            executor,
337                            confirmation_depth_k,
338                        );
339                    Box::new(extension_factory) as Box<dyn ExtensionsFactory<DomainBlock>>
340                },
341            ),
342        )));
343        exts.register(SubspaceMmrExtension::new(Arc::new(
344            SubspaceMmrHostFunctionsImpl::<Block, _>::new(
345                self.consensus_client.clone(),
346                confirmation_depth_k,
347            ),
348        )));
349        exts.register(MessengerExtension::new(Arc::new(
350            MessengerHostFunctionsImpl::<Block, _, DomainBlock, _>::new(
351                self.consensus_client.clone(),
352                self.executor.clone(),
353            ),
354        )));
355
356        if let Some(offchain_storage) = self.consensus_backend.offchain_storage() {
357            let offchain_db = OffchainDb::new(offchain_storage);
358            exts.register(OffchainDbExt::new(offchain_db));
359        }
360        exts.register(PotExtension::new({
361            let client = Arc::clone(&self.consensus_client);
362            let mock_pot_verifier = Arc::clone(&self.mock_pot_verifier);
363            Box::new(
364                move |parent_hash, slot, proof_of_time, _quick_verification| {
365                    let parent_hash = {
366                        let mut converted_parent_hash = Block::Hash::default();
367                        converted_parent_hash.as_mut().copy_from_slice(&parent_hash);
368                        converted_parent_hash
369                    };
370
371                    let parent_header = match client.header(parent_hash) {
372                        Ok(Some(parent_header)) => parent_header,
373                        _ => return false,
374                    };
375                    let parent_pre_digest = match extract_pre_digest(&parent_header) {
376                        Ok(parent_pre_digest) => parent_pre_digest,
377                        _ => return false,
378                    };
379
380                    let parent_slot = parent_pre_digest.slot();
381                    if slot <= *parent_slot {
382                        return false;
383                    }
384
385                    mock_pot_verifier.is_valid(slot, proof_of_time)
386                },
387            )
388        }));
389        exts
390    }
391}
392
393type NewSlot = (Slot, PotOutput);
394
395/// A mock Subspace consensus node instance used for testing.
396pub struct MockConsensusNode {
397    /// `TaskManager`'s instance.
398    pub task_manager: TaskManager,
399    /// Client's instance.
400    pub client: Arc<Client>,
401    /// Backend.
402    pub backend: Arc<Backend>,
403    /// Code executor.
404    pub executor: RuntimeExecutor,
405    /// Transaction pool.
406    pub transaction_pool: Arc<BasicPool<FullChainApi<Client, Block>, Block>>,
407    /// The SelectChain Strategy
408    pub select_chain: FullSelectChain,
409    /// Network service.
410    pub network_service: Arc<dyn NetworkService + Send + Sync>,
411    /// Cross-domain gossip notification service.
412    pub xdm_gossip_notification_service: Option<Box<dyn NotificationService>>,
413    /// Sync service.
414    pub sync_service: Arc<sc_network_sync::SyncingService<Block>>,
415    /// RPC handlers.
416    pub rpc_handlers: sc_service::RpcHandlers,
417    /// The next slot number
418    next_slot: u64,
419    /// The mock pot verifier
420    mock_pot_verifier: Arc<MockPotVerfier>,
421    /// The slot notification subscribers
422    new_slot_notification_subscribers: Vec<mpsc::UnboundedSender<(Slot, PotOutput)>>,
423    /// The acknowledgement sender subscribers
424    acknowledgement_sender_subscribers: Vec<TracingUnboundedSender<mpsc::Sender<()>>>,
425    /// Block import pipeline
426    block_import: MockBlockImport<Client, Block>,
427    xdm_gossip_worker_builder: Option<GossipWorkerBuilder>,
428    /// Mock subspace solution used to mock the subspace `PreDigest`
429    mock_solution: Solution<AccountId>,
430    log_prefix: &'static str,
431    /// Ferdie key
432    pub key: Sr25519Keyring,
433    finalize_block_depth: Option<NumberFor<Block>>,
434    /// The node's base path
435    base_path: BasePath,
436}
437
438/// Configuration values required to run a mock consensus node with custom RPC options.
439pub struct MockConsensusNodeRpcConfig {
440    /// The node's base path.
441    pub base_path: BasePath,
442    /// Optional block finalization depth override.
443    pub finalize_block_depth: Option<NumberFor<Block>>,
444    /// Whether to enable the private EVM domain.
445    pub private_evm: bool,
446    /// Optional EVM owner key.
447    pub evm_owner: Option<Sr25519Keyring>,
448    /// Optional RPC listen address override.
449    pub rpc_addr: Option<SocketAddr>,
450    /// Optional RPC listen port override.
451    pub rpc_port: Option<u16>,
452}
453
454impl MockConsensusNode {
455    #[expect(clippy::result_large_err, reason = "Comes from Substrate")]
456    fn run_with_configuration(
457        mut config: Configuration,
458        key: Sr25519Keyring,
459        base_path: BasePath,
460        finalize_block_depth: Option<NumberFor<Block>>,
461        rpc_builder: Box<
462            dyn Fn() -> Result<RpcModule<()>, sc_service::Error> + Send + Sync + 'static,
463        >,
464    ) -> MockConsensusNode {
465        let log_prefix = key.into();
466
467        let tx_pool_options = Options {
468            ban_time: Duration::from_millis(0),
469            ..Default::default()
470        };
471
472        config.network.node_name = format!("{} (Consensus)", config.network.node_name);
473        let span = sc_tracing::tracing::info_span!(
474            sc_tracing::logging::PREFIX_LOG_SPAN,
475            name = config.network.node_name.as_str()
476        );
477        let _enter = span.enter();
478
479        let executor = sc_service::new_wasm_executor(&config.executor);
480
481        let (client, backend, keystore_container, mut task_manager) =
482            sc_service::new_full_parts::<Block, RuntimeApi, _>(
483                &config,
484                None,
485                executor.clone(),
486                Vec::new(),
487            )
488            .expect("Fail to new full parts");
489
490        let domain_executor = Arc::new(sc_service::new_wasm_executor(&config.executor));
491        let client = Arc::new(client);
492        let mock_pot_verifier = Arc::new(MockPotVerfier::default());
493        let chain_constants = client
494            .runtime_api()
495            .chain_constants(client.info().best_hash)
496            .expect("Fail to get chain constants");
497        client
498            .execution_extensions()
499            .set_extensions_factory(MockExtensionsFactory::<
500                _,
501                DomainBlock,
502                sc_domains::RuntimeExecutor,
503                _,
504            >::new(
505                client.clone(),
506                domain_executor.clone(),
507                Arc::clone(&mock_pot_verifier),
508                backend.clone(),
509                chain_constants.confirmation_depth_k(),
510            ));
511
512        let select_chain = sc_consensus::LongestChain::new(backend.clone());
513        let transaction_pool = Arc::from(BasicPool::new_full(
514            tx_pool_options,
515            config.role.is_authority().into(),
516            config.prometheus_registry(),
517            task_manager.spawn_essential_handle(),
518            client.clone(),
519        ));
520
521        let block_import = MockBlockImport::<_, _>::new(client.clone());
522
523        let mut net_config = sc_network::config::FullNetworkConfiguration::<
524            _,
525            _,
526            NetworkWorker<_, _>,
527        >::new(&config.network, None);
528        let (xdm_gossip_notification_config, xdm_gossip_notification_service) =
529            xdm_gossip_peers_set_config();
530        net_config.add_notification_protocol(xdm_gossip_notification_config);
531
532        let (network_service, system_rpc_tx, tx_handler_controller, sync_service, _) =
533            sc_service::build_network(sc_service::BuildNetworkParams {
534                config: &config,
535                net_config,
536                client: client.clone(),
537                transaction_pool: transaction_pool.clone(),
538                spawn_handle: task_manager.spawn_handle(),
539                spawn_essential_handle: task_manager.spawn_essential_handle(),
540                import_queue: mock_import_queue(
541                    block_import.clone(),
542                    &task_manager.spawn_essential_handle(),
543                ),
544                block_announce_validator_builder: None,
545                warp_sync_config: None,
546                block_relay: None,
547                metrics: NotificationMetrics::new(None),
548                gap_sync_body_policy: None,
549            })
550            .expect("Should be able to build network");
551
552        let rpc_handlers = sc_service::spawn_tasks(SpawnTasksParams {
553            network: network_service.clone(),
554            client: client.clone(),
555            keystore: keystore_container.keystore(),
556            task_manager: &mut task_manager,
557            transaction_pool: transaction_pool.clone(),
558            rpc_builder: Box::new(move |_| rpc_builder()),
559            backend: backend.clone(),
560            system_rpc_tx,
561            config,
562            telemetry: None,
563            tx_handler_controller,
564            sync_service: sync_service.clone(),
565            tracing_execute_block: None,
566        })
567        .expect("Should be able to spawn tasks");
568
569        let mock_solution =
570            Solution::genesis_solution(PublicKey::from(key.public().0), key.to_account_id());
571
572        let mut gossip_builder = GossipWorkerBuilder::new();
573
574        task_manager
575            .spawn_essential_handle()
576            .spawn_essential_blocking(
577                "consensus-chain-channel-update-worker",
578                None,
579                Box::pin(
580                    domain_client_message_relayer::worker::gossip_channel_updates::<_, _, Block, _>(
581                        ChainId::Consensus,
582                        client.clone(),
583                        sync_service.clone(),
584                        gossip_builder.gossip_msg_sink(),
585                    ),
586                ),
587            );
588
589        let (consensus_msg_sink, consensus_msg_receiver) =
590            tracing_unbounded("consensus_message_channel", 100);
591
592        let consensus_listener =
593            cross_domain_message_gossip::start_cross_chain_message_listener::<_, _, _, _, _, _, _>(
594                ChainId::Consensus,
595                client.clone(),
596                client.clone(),
597                transaction_pool.clone(),
598                network_service.clone(),
599                consensus_msg_receiver,
600                domain_executor,
601                sync_service.clone(),
602            );
603
604        task_manager
605            .spawn_essential_handle()
606            .spawn_essential_blocking(
607                "consensus-message-listener",
608                None,
609                Box::pin(consensus_listener),
610            );
611
612        gossip_builder.push_chain_sink(ChainId::Consensus, consensus_msg_sink);
613
614        task_manager.spawn_essential_handle().spawn_blocking(
615            "mmr-gadget",
616            None,
617            mmr_gadget::MmrGadget::start(
618                client.clone(),
619                backend.clone(),
620                sp_mmr_primitives::INDEXING_PREFIX.to_vec(),
621            ),
622        );
623
624        MockConsensusNode {
625            task_manager,
626            client,
627            backend,
628            executor,
629            transaction_pool,
630            select_chain,
631            network_service,
632            xdm_gossip_notification_service: Some(xdm_gossip_notification_service),
633            sync_service,
634            rpc_handlers,
635            next_slot: 1,
636            mock_pot_verifier,
637            new_slot_notification_subscribers: Vec::new(),
638            acknowledgement_sender_subscribers: Vec::new(),
639            block_import,
640            xdm_gossip_worker_builder: Some(gossip_builder),
641            mock_solution,
642            log_prefix,
643            key,
644            finalize_block_depth,
645            base_path,
646        }
647    }
648
649    /// Run a mock consensus node
650    pub fn run(
651        tokio_handle: tokio::runtime::Handle,
652        key: Sr25519Keyring,
653        base_path: BasePath,
654    ) -> MockConsensusNode {
655        Self::run_with_finalization_depth(tokio_handle, key, base_path, None, false, None)
656    }
657
658    /// Run a mock consensus node with a private EVM domain
659    pub fn run_with_private_evm(
660        tokio_handle: tokio::runtime::Handle,
661        key: Sr25519Keyring,
662        evm_owner: Option<Sr25519Keyring>,
663        base_path: BasePath,
664    ) -> MockConsensusNode {
665        Self::run_with_finalization_depth(tokio_handle, key, base_path, None, true, evm_owner)
666    }
667
668    /// Run a mock consensus node with finalization depth
669    #[expect(clippy::result_large_err, reason = "Comes from Substrate")]
670    pub fn run_with_finalization_depth(
671        tokio_handle: tokio::runtime::Handle,
672        key: Sr25519Keyring,
673        base_path: BasePath,
674        finalize_block_depth: Option<NumberFor<Block>>,
675        private_evm: bool,
676        evm_owner: Option<Sr25519Keyring>,
677    ) -> MockConsensusNode {
678        let rpc_config = MockConsensusNodeRpcConfig {
679            base_path,
680            finalize_block_depth,
681            private_evm,
682            evm_owner,
683            rpc_addr: None,
684            rpc_port: None,
685        };
686
687        Self::run_with_rpc_builder(
688            tokio_handle,
689            key,
690            rpc_config,
691            Box::new(|| Ok(RpcModule::new(()))),
692        )
693    }
694
695    /// Run a mock consensus node with a custom RPC builder and RPC address/port options.
696    pub fn run_with_rpc_builder(
697        tokio_handle: tokio::runtime::Handle,
698        key: Sr25519Keyring,
699        rpc_config: MockConsensusNodeRpcConfig,
700        rpc_builder: Box<
701            dyn Fn() -> Result<RpcModule<()>, sc_service::Error> + Send + Sync + 'static,
702        >,
703    ) -> MockConsensusNode {
704        let MockConsensusNodeRpcConfig {
705            base_path,
706            finalize_block_depth,
707            private_evm,
708            evm_owner,
709            rpc_addr,
710            rpc_port,
711        } = rpc_config;
712
713        let config = node_config(
714            tokio_handle,
715            key,
716            vec![],
717            false,
718            false,
719            false,
720            private_evm,
721            evm_owner.map(|key| key.to_account_id()),
722            base_path.clone(),
723            rpc_addr,
724            rpc_port,
725        );
726
727        Self::run_with_configuration(config, key, base_path, finalize_block_depth, rpc_builder)
728    }
729
730    /// Run a mock consensus node with RPC options using the default empty RPC module.
731    #[expect(clippy::result_large_err, reason = "Comes from Substrate")]
732    pub fn run_with_rpc_options(
733        tokio_handle: tokio::runtime::Handle,
734        key: Sr25519Keyring,
735        rpc_config: MockConsensusNodeRpcConfig,
736    ) -> MockConsensusNode {
737        Self::run_with_rpc_builder(
738            tokio_handle,
739            key,
740            rpc_config,
741            Box::new(|| Ok(RpcModule::new(()))),
742        )
743    }
744
745    /// Get the cross domain gossip message worker builder
746    pub fn xdm_gossip_worker_builder(&mut self) -> &mut GossipWorkerBuilder {
747        self.xdm_gossip_worker_builder
748            .as_mut()
749            .expect("gossip message worker have not started yet")
750    }
751
752    /// Start the cross domain gossip message worker.
753    pub fn start_cross_domain_gossip_message_worker(&mut self) {
754        let xdm_gossip_worker_builder = self
755            .xdm_gossip_worker_builder
756            .take()
757            .expect("gossip message worker have not started yet");
758        let cross_domain_message_gossip_worker = xdm_gossip_worker_builder.build::<Block, _, _>(
759            self.network_service.clone(),
760            self.xdm_gossip_notification_service
761                .take()
762                .expect("XDM gossip notification service must be used only once"),
763            self.sync_service.clone(),
764        );
765        self.task_manager
766            .spawn_essential_handle()
767            .spawn_essential_blocking(
768                "cross-domain-gossip-message-worker",
769                None,
770                Box::pin(cross_domain_message_gossip_worker.run()),
771            );
772    }
773
774    /// Return the next slot number
775    pub fn next_slot(&self) -> u64 {
776        self.next_slot
777    }
778
779    /// Set the next slot number
780    pub fn set_next_slot(&mut self, next_slot: u64) {
781        self.next_slot = next_slot;
782    }
783
784    /// Produce a slot only, without waiting for the potential slot handlers.
785    pub fn produce_slot(&mut self) -> NewSlot {
786        let slot = Slot::from(self.next_slot);
787        let proof_of_time = PotOutput::from(
788            <&[u8] as TryInto<[u8; 16]>>::try_into(&Hash::random().to_fixed_bytes()[..16])
789                .expect("slice with length of 16 must able convert into [u8; 16]; qed"),
790        );
791        self.mock_pot_verifier.inject_pot(*slot, proof_of_time);
792        self.next_slot += 1;
793
794        (slot, proof_of_time)
795    }
796
797    /// Notify the executor about the new slot and wait for the bundle produced at this slot.
798    pub async fn notify_new_slot_and_wait_for_bundle(
799        &mut self,
800        new_slot: NewSlot,
801    ) -> Option<OpaqueBundle<NumberFor<Block>, Hash, DomainHeader, Balance>> {
802        self.new_slot_notification_subscribers
803            .retain(|subscriber| subscriber.unbounded_send(new_slot).is_ok());
804
805        self.confirm_acknowledgement().await;
806        self.get_bundle_from_tx_pool(new_slot)
807    }
808
809    /// Produce a new slot and wait for a bundle produced at this slot.
810    pub async fn produce_slot_and_wait_for_bundle_submission(
811        &mut self,
812    ) -> (
813        NewSlot,
814        OpaqueBundle<NumberFor<Block>, Hash, DomainHeader, Balance>,
815    ) {
816        let slot = self.produce_slot();
817        for _ in 0..MAX_PRODUCE_BUNDLE_TRY {
818            if let Some(bundle) = self.notify_new_slot_and_wait_for_bundle(slot).await {
819                return (slot, bundle);
820            }
821        }
822        panic!(
823            "Failed to produce bundle after {MAX_PRODUCE_BUNDLE_TRY:?} tries, something must be wrong"
824        );
825    }
826
827    /// Produce a slot and wait for bundle submission from specific operator.
828    pub async fn produce_slot_and_wait_for_bundle_submission_from_operator(
829        &mut self,
830        operator_id: OperatorId,
831    ) -> (
832        NewSlot,
833        OpaqueBundle<NumberFor<Block>, Hash, DomainHeader, Balance>,
834    ) {
835        loop {
836            let slot = self.produce_slot();
837            if let Some(bundle) = self.notify_new_slot_and_wait_for_bundle(slot).await
838                && bundle.sealed_header().proof_of_election().operator_id == operator_id
839            {
840                return (slot, bundle);
841            }
842        }
843    }
844
845    /// Subscribe the new slot notification
846    pub fn new_slot_notification_stream(&mut self) -> mpsc::UnboundedReceiver<(Slot, PotOutput)> {
847        let (tx, rx) = mpsc::unbounded();
848        self.new_slot_notification_subscribers.push(tx);
849        rx
850    }
851
852    /// Subscribe the acknowledgement sender stream
853    pub fn new_acknowledgement_sender_stream(
854        &mut self,
855    ) -> TracingUnboundedReceiver<mpsc::Sender<()>> {
856        let (tx, rx) = tracing_unbounded("subspace_acknowledgement_sender_stream", 100);
857        self.acknowledgement_sender_subscribers.push(tx);
858        rx
859    }
860
861    /// Wait for all the acknowledgements before return
862    ///
863    /// It is used to wait for the acknowledgement of the domain worker to ensure it have
864    /// finish all the previous tasks before return
865    pub async fn confirm_acknowledgement(&mut self) {
866        let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(0);
867
868        // Must drop `acknowledgement_sender` after the notification otherwise the receiver
869        // will block forever as there is still a sender not closed.
870        {
871            self.acknowledgement_sender_subscribers
872                .retain(|subscriber| {
873                    subscriber
874                        .unbounded_send(acknowledgement_sender.clone())
875                        .is_ok()
876                });
877            drop(acknowledgement_sender);
878        }
879
880        // Wait for all the acknowledgements to progress and proactively drop closed subscribers.
881        while acknowledgement_receiver.next().await.is_some() {
882            // Wait for all the acknowledgements to finish.
883        }
884    }
885
886    /// Wait for the operator finish processing the consensus block before return
887    pub async fn confirm_block_import_processed(&mut self) {
888        // Send one more notification to ensure the previous consensus block import notification
889        // have been received by the operator
890        let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(0);
891        {
892            // Must drop `block_import_acknowledgement_sender` after the notification otherwise
893            // the receiver will block forever as there is still a sender not closed.
894            // NOTE: it is okay to use the default block number since it is ignored in the consumer side.
895            let value = (NumberFor::<Block>::default(), acknowledgement_sender);
896            self.block_import
897                .block_importing_notification_subscribers
898                .lock()
899                .retain(|subscriber| subscriber.unbounded_send(value.clone()).is_ok());
900        }
901        while acknowledgement_receiver.next().await.is_some() {
902            // Wait for all the acknowledgements to finish.
903        }
904
905        // Ensure the operator finish processing the consensus block
906        self.confirm_acknowledgement().await;
907    }
908
909    /// Subscribe the block importing notification
910    pub fn block_importing_notification_stream(
911        &self,
912    ) -> TracingUnboundedReceiver<(NumberFor<Block>, mpsc::Sender<()>)> {
913        self.block_import.block_importing_notification_stream()
914    }
915
916    /// Get the bundle that created at `slot` from the transaction pool
917    pub fn get_bundle_from_tx_pool(
918        &self,
919        new_slot: NewSlot,
920    ) -> Option<OpaqueBundle<NumberFor<Block>, Hash, DomainHeader, Balance>> {
921        for ready_tx in self.transaction_pool.ready() {
922            let ext = UncheckedExtrinsic::decode(&mut ready_tx.data.encode().as_slice())
923                .expect("should be able to decode");
924            if let RuntimeCall::Domains(pallet_domains::Call::submit_bundle { opaque_bundle }) =
925                ext.function
926                && opaque_bundle.sealed_header().slot_number() == *new_slot.0
927            {
928                return Some(opaque_bundle);
929            }
930        }
931        None
932    }
933
934    /// Submit a tx to the tx pool
935    pub async fn submit_transaction(&self, tx: OpaqueExtrinsic) -> Result<H256, TxPoolError> {
936        self.transaction_pool
937            .submit_one(
938                self.client.info().best_hash,
939                TransactionSource::External,
940                tx,
941            )
942            .await
943            .map_err(|err| {
944                err.into_pool_error()
945                    .expect("should always be a pool error")
946            })
947    }
948
949    /// Remove all tx from the tx pool
950    pub async fn clear_tx_pool(&self) -> Result<(), Box<dyn Error>> {
951        let txs: Vec<_> = self
952            .transaction_pool
953            .ready()
954            .map(|t| self.transaction_pool.hash_of(&t.data))
955            .collect();
956        self.prune_txs_from_pool(txs.as_slice()).await
957    }
958
959    /// Remove a ready transaction from transaction pool.
960    pub async fn prune_tx_from_pool(&self, tx: &OpaqueExtrinsic) -> Result<(), Box<dyn Error>> {
961        self.prune_txs_from_pool(&[self.transaction_pool.hash_of(tx)])
962            .await
963    }
964
965    async fn prune_txs_from_pool(
966        &self,
967        tx_hashes: &[BlockHashFor<Block>],
968    ) -> Result<(), Box<dyn Error>> {
969        let hash_and_number = HashAndNumber {
970            number: self.client.info().best_number,
971            hash: self.client.info().best_hash,
972        };
973        self.transaction_pool
974            .pool()
975            .prune_known(&hash_and_number, tx_hashes);
976        // `ban_time` have set to 0, explicitly wait 1ms here to ensure `clear_stale` will remove
977        // all the bans as the ban time must be passed.
978        tokio::time::sleep(time::Duration::from_millis(1)).await;
979        self.transaction_pool
980            .pool()
981            .validated_pool()
982            .clear_stale(&hash_and_number);
983        Ok(())
984    }
985
986    /// Return if the given ER exist in the consensus state
987    pub fn does_receipt_exist(
988        &self,
989        er_hash: BlockHashFor<DomainBlock>,
990    ) -> Result<bool, Box<dyn Error>> {
991        Ok(self
992            .client
993            .runtime_api()
994            .execution_receipt(self.client.info().best_hash, er_hash)?
995            .is_some())
996    }
997
998    /// Wait for a specific execution receipt to appear in the consensus state.
999    ///
1000    /// Polls by producing blocks with bundles (the same primitive that
1001    /// `produce_blocks_until!` uses internally) until
1002    /// `does_receipt_exist(receipt_hash)` returns `Ok(true)`, or the timeout
1003    /// expires. On timeout, returns `Err`. Tests expecting deterministic
1004    /// receipt arrival should use this in place of a bare
1005    /// `assert!(ferdie.does_receipt_exist(...).unwrap())`, which races with
1006    /// the underlying block-production pipeline.
1007    pub async fn wait_for_receipt(
1008        &mut self,
1009        receipt_hash: BlockHashFor<DomainBlock>,
1010        timeout: Duration,
1011    ) -> Result<(), Box<dyn Error>> {
1012        let deadline = std::time::Instant::now() + timeout;
1013        while std::time::Instant::now() < deadline {
1014            if self.does_receipt_exist(receipt_hash)? {
1015                return Ok(());
1016            }
1017            // Advance the consensus chain by producing one block with bundles,
1018            // then re-check. This mirrors what `produce_blocks_until!` does:
1019            // the receipt lands in consensus state via a bundle carried in a
1020            // consensus block.
1021            self.produce_blocks_with_bundles(1).await?;
1022        }
1023        Err(
1024            format!("wait_for_receipt timed out after {timeout:?} for receipt {receipt_hash:?}")
1025                .into(),
1026        )
1027    }
1028
1029    /// Returns the stake summary of the Domain.
1030    pub fn get_domain_staking_summary(
1031        &self,
1032        domain_id: DomainId,
1033    ) -> Result<Option<StakingSummary<OperatorId, Balance>>, Box<dyn Error>> {
1034        Ok(self
1035            .client
1036            .runtime_api()
1037            .domain_stake_summary(self.client.info().best_hash, domain_id)?)
1038    }
1039
1040    /// Returns the domain block pruning depth.
1041    pub fn get_domain_block_pruning_depth(&self) -> Result<BlockNumber, Box<dyn Error>> {
1042        Ok(self
1043            .client
1044            .runtime_api()
1045            .block_pruning_depth(self.client.info().best_hash)?)
1046    }
1047
1048    /// Return a future that only resolve if a fraud proof that the given `fraud_proof_predicate`
1049    /// return true is submitted to the consensus tx pool
1050    pub fn wait_for_fraud_proof<FP>(
1051        &self,
1052        fraud_proof_predicate: FP,
1053    ) -> Pin<Box<dyn Future<Output = FraudProofFor<Block, DomainBlock>> + Send>>
1054    where
1055        FP: Fn(&FraudProofFor<Block, DomainBlock>) -> bool + Send + 'static,
1056    {
1057        let tx_pool = self.transaction_pool.clone();
1058        let mut import_tx_stream = self.transaction_pool.import_notification_stream();
1059        Box::pin(async move {
1060            while let Some(ready_tx_hash) = import_tx_stream.next().await {
1061                let ready_tx = tx_pool
1062                    .ready_transaction(&ready_tx_hash)
1063                    .expect("Just get the ready tx hash from import stream; qed");
1064                let ext = subspace_test_runtime::UncheckedExtrinsic::decode(
1065                    &mut ready_tx.data.encode().as_slice(),
1066                )
1067                .expect("Decode tx must success");
1068                if let subspace_test_runtime::RuntimeCall::Domains(
1069                    pallet_domains::Call::submit_fraud_proof { fraud_proof },
1070                ) = ext.function
1071                    && fraud_proof_predicate(&fraud_proof)
1072                {
1073                    return *fraud_proof;
1074                }
1075            }
1076            unreachable!()
1077        })
1078    }
1079
1080    /// Get the free balance of the given account
1081    pub fn free_balance(&self, account_id: AccountId) -> subspace_runtime_primitives::Balance {
1082        self.client
1083            .runtime_api()
1084            .free_balance(self.client.info().best_hash, account_id)
1085            .expect("Fail to get account free balance")
1086    }
1087
1088    /// Give the peer at `addr` the minimum reputation, which will ban it.
1089    // TODO: also ban/unban in the DSN
1090    pub fn ban_peer(&self, addr: MultiaddrWithPeerId) {
1091        // If unban_peer() has been called on the peer, we need to bump it twice
1092        // to give it the minimal reputation.
1093        self.network_service.report_peer(
1094            addr.peer_id,
1095            ReputationChange::new_fatal("Peer banned by test (1)"),
1096        );
1097        self.network_service.report_peer(
1098            addr.peer_id,
1099            ReputationChange::new_fatal("Peer banned by test (2)"),
1100        );
1101    }
1102
1103    /// Give the peer at `addr` a high reputation, which guarantees it is un-banned it.
1104    pub fn unban_peer(&self, addr: MultiaddrWithPeerId) {
1105        // If ReputationChange::new_fatal() has been called on the peer, we need to bump it twice
1106        // to give it a positive reputation.
1107        self.network_service.report_peer(
1108            addr.peer_id,
1109            ReputationChange::new(i32::MAX, "Peer unbanned by test (1)"),
1110        );
1111        self.network_service.report_peer(
1112            addr.peer_id,
1113            ReputationChange::new(i32::MAX, "Peer unbanned by test (2)"),
1114        );
1115    }
1116
1117    /// Take and stop the `MockConsensusNode` and delete its database lock file.
1118    ///
1119    /// Stopping and restarting a node can cause weird race conditions, with errors like:
1120    /// "The system cannot find the path specified".
1121    /// If this happens, try increasing the wait time in this method.
1122    pub async fn stop(self) -> Result<(), std::io::Error> {
1123        let lock_file_path = self.base_path.path().join("paritydb").join("lock");
1124        // On Windows, sometimes open files can’t be deleted so `drop` first then delete
1125        std::mem::drop(self);
1126
1127        // Give the node time to cleanup, exit, and release the lock file.
1128        // TODO: fix the underlying issue or wait for the actual shutdown instead
1129        sleep(Duration::from_secs(2)).await;
1130
1131        // The lock file already being deleted is not a fatal test error, so just log it
1132        if let Err(err) = std::fs::remove_file(lock_file_path) {
1133            tracing::error!("deleting paritydb lock file failed: {err:?}");
1134        }
1135        Ok(())
1136    }
1137}
1138
1139impl MockConsensusNode {
1140    async fn collect_txn_from_pool(&self, parent_hash: Hash) -> Vec<ExtrinsicFor<Block>> {
1141        self.transaction_pool
1142            .ready_at(parent_hash)
1143            .await
1144            .map(|pending_tx| pending_tx.data().as_ref().clone())
1145            .collect()
1146    }
1147
1148    async fn mock_inherent_data(slot: Slot) -> Result<InherentData, Box<dyn Error>> {
1149        let timestamp = sp_timestamp::InherentDataProvider::new(Timestamp::new(
1150            <Slot as Into<u64>>::into(slot) * SLOT_DURATION,
1151        ));
1152        let subspace_inherents =
1153            sp_consensus_subspace::inherents::InherentDataProvider::new(vec![]);
1154
1155        let inherent_data = (subspace_inherents, timestamp)
1156            .create_inherent_data()
1157            .await?;
1158
1159        Ok(inherent_data)
1160    }
1161
1162    fn mock_subspace_digest(&self, slot: Slot) -> Digest {
1163        let pre_digest: PreDigest<AccountId> = PreDigest::V0 {
1164            slot,
1165            solution: self.mock_solution.clone(),
1166            pot_info: PreDigestPotInfo::V0 {
1167                proof_of_time: Default::default(),
1168                future_proof_of_time: Default::default(),
1169            },
1170        };
1171        let mut digest = Digest::default();
1172        digest.push(DigestItem::subspace_pre_digest(&pre_digest));
1173        digest
1174    }
1175
1176    /// Build block
1177    async fn build_block(
1178        &self,
1179        slot: Slot,
1180        parent_hash: BlockHashFor<Block>,
1181        extrinsics: Vec<ExtrinsicFor<Block>>,
1182    ) -> Result<(Block, StorageChanges), Box<dyn Error>> {
1183        let inherent_digest = self.mock_subspace_digest(slot);
1184
1185        let inherent_data = Self::mock_inherent_data(slot).await?;
1186
1187        let mut block_builder = BlockBuilderBuilder::new(self.client.as_ref())
1188            .on_parent_block(parent_hash)
1189            .fetch_parent_block_number(self.client.as_ref())?
1190            .with_inherent_digests(inherent_digest)
1191            .build()
1192            .expect("Creates new block builder");
1193
1194        let inherent_txns = block_builder.create_inherents(inherent_data)?;
1195
1196        for tx in inherent_txns.into_iter().chain(extrinsics) {
1197            if let Err(err) = sc_block_builder::BlockBuilder::push(&mut block_builder, tx) {
1198                tracing::error!("Invalid transaction while building block: {}", err);
1199            }
1200        }
1201
1202        let (block, storage_changes) = block_builder.build()?.into_inner();
1203        Ok((block, storage_changes))
1204    }
1205
1206    /// Import block
1207    async fn import_block(
1208        &self,
1209        block: Block,
1210        storage_changes: Option<StorageChanges>,
1211    ) -> Result<BlockHashFor<Block>, Box<dyn Error>> {
1212        let (header, body) = block.deconstruct();
1213
1214        let header_hash = header.hash();
1215        let header_number = header.number;
1216
1217        let block_import_params = {
1218            let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
1219            import_block.body = Some(body);
1220            import_block.state_action = match storage_changes {
1221                Some(changes) => {
1222                    StateAction::ApplyChanges(sc_consensus::StorageChanges::Changes(changes))
1223                }
1224                None => StateAction::Execute,
1225            };
1226            import_block
1227        };
1228
1229        let import_result = self.block_import.import_block(block_import_params).await?;
1230
1231        if let Some(finalized_block_hash) = self
1232            .finalize_block_depth
1233            .and_then(|depth| header_number.checked_sub(depth))
1234            .and_then(|block_to_finalize| {
1235                self.client
1236                    .hash(block_to_finalize)
1237                    .expect("Block hash not found for number: {block_to_finalize:?}")
1238            })
1239        {
1240            self.client
1241                .finalize_block(finalized_block_hash, None, true)
1242                .unwrap();
1243        }
1244
1245        match import_result {
1246            ImportResult::Imported(_) | ImportResult::AlreadyInChain => Ok(header_hash),
1247            bad_res => Err(format!("Fail to import block due to {bad_res:?}").into()),
1248        }
1249    }
1250
1251    /// Produce a new block with the slot on top of `parent_hash`, with optional
1252    /// specified extrinsic list.
1253    #[sc_tracing::logging::prefix_logs_with(self.log_prefix)]
1254    pub async fn produce_block_with_slot_at(
1255        &mut self,
1256        new_slot: NewSlot,
1257        parent_hash: BlockHashFor<Block>,
1258        maybe_extrinsics: Option<Vec<ExtrinsicFor<Block>>>,
1259    ) -> Result<BlockHashFor<Block>, Box<dyn Error>> {
1260        let block_timer = time::Instant::now();
1261
1262        let extrinsics = match maybe_extrinsics {
1263            Some(extrinsics) => extrinsics,
1264            None => self.collect_txn_from_pool(parent_hash).await,
1265        };
1266        let tx_hashes: Vec<_> = extrinsics
1267            .iter()
1268            .map(|t| self.transaction_pool.hash_of(t))
1269            .collect();
1270
1271        let (block, storage_changes) = self
1272            .build_block(new_slot.0, parent_hash, extrinsics)
1273            .await?;
1274
1275        log_new_block(&block, block_timer.elapsed().as_millis());
1276
1277        let res = match self.import_block(block, Some(storage_changes)).await {
1278            Ok(hash) => {
1279                // Remove the tx of the imported block from the tx pool, so we don't re-include
1280                // them in future blocks by accident.
1281                self.prune_txs_from_pool(tx_hashes.as_slice()).await?;
1282                Ok(hash)
1283            }
1284            err => err,
1285        };
1286        self.confirm_block_import_processed().await;
1287        res
1288    }
1289
1290    /// Produce a new block on top of the current best block, with the extrinsics collected from
1291    /// the transaction pool.
1292    #[sc_tracing::logging::prefix_logs_with(self.log_prefix)]
1293    pub async fn produce_block_with_slot(&mut self, slot: NewSlot) -> Result<(), Box<dyn Error>> {
1294        self.produce_block_with_slot_at(slot, self.client.info().best_hash, None)
1295            .await?;
1296        Ok(())
1297    }
1298
1299    /// Produce a new block on top of the current best block, with the specified extrinsics.
1300    #[sc_tracing::logging::prefix_logs_with(self.log_prefix)]
1301    pub async fn produce_block_with_extrinsics(
1302        &mut self,
1303        extrinsics: Vec<ExtrinsicFor<Block>>,
1304    ) -> Result<(), Box<dyn Error>> {
1305        let slot = self.produce_slot();
1306        self.produce_block_with_slot_at(slot, self.client.info().best_hash, Some(extrinsics))
1307            .await?;
1308        Ok(())
1309    }
1310
1311    /// Produce `n` number of blocks.
1312    #[sc_tracing::logging::prefix_logs_with(self.log_prefix)]
1313    pub async fn produce_blocks(&mut self, n: u64) -> Result<(), Box<dyn Error>> {
1314        for _ in 0..n {
1315            let slot = self.produce_slot();
1316            self.produce_block_with_slot(slot).await?;
1317        }
1318        Ok(())
1319    }
1320
1321    /// Produce `n` number of blocks and wait for bundle submitted to the block.
1322    #[sc_tracing::logging::prefix_logs_with(self.log_prefix)]
1323    pub async fn produce_blocks_with_bundles(&mut self, n: u64) -> Result<(), Box<dyn Error>> {
1324        for _ in 0..n {
1325            let (slot, _) = self.produce_slot_and_wait_for_bundle_submission().await;
1326            self.produce_block_with_slot(slot).await?;
1327        }
1328        Ok(())
1329    }
1330
1331    /// Get the nonce of the node account
1332    pub fn account_nonce(&self) -> u32 {
1333        self.client
1334            .runtime_api()
1335            .account_nonce(self.client.info().best_hash, self.key.to_account_id())
1336            .expect("Fail to get account nonce")
1337    }
1338
1339    /// Get the nonce of the given account
1340    pub fn account_nonce_of(&self, account_id: AccountId) -> u32 {
1341        self.client
1342            .runtime_api()
1343            .account_nonce(self.client.info().best_hash, account_id)
1344            .expect("Fail to get account nonce")
1345    }
1346
1347    /// Construct an extrinsic.
1348    pub fn construct_extrinsic(
1349        &self,
1350        nonce: u32,
1351        function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
1352    ) -> UncheckedExtrinsic {
1353        construct_extrinsic_generic(&self.client, function, self.key, false, nonce, 0)
1354    }
1355
1356    /// Construct an unsigned general extrinsic.
1357    pub fn construct_unsigned_extrinsic(
1358        &self,
1359        function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
1360    ) -> UncheckedExtrinsic {
1361        construct_unsigned_extrinsic(&self.client, function)
1362    }
1363
1364    /// Construct and send extrinsic through rpc
1365    pub async fn construct_and_send_extrinsic_with(
1366        &self,
1367        function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
1368    ) -> Result<RpcTransactionOutput, RpcTransactionError> {
1369        let nonce = self.account_nonce();
1370        let extrinsic = self.construct_extrinsic(nonce, function);
1371        self.rpc_handlers.send_transaction(extrinsic.into()).await
1372    }
1373
1374    /// Get the nonce of the given account
1375    pub async fn send_extrinsic(
1376        &self,
1377        extrinsic: impl Into<OpaqueExtrinsic>,
1378    ) -> Result<RpcTransactionOutput, RpcTransactionError> {
1379        self.rpc_handlers.send_transaction(extrinsic.into()).await
1380    }
1381}
1382
1383fn log_new_block(block: &Block, used_time_ms: u128) {
1384    tracing::info!(
1385        "🎁 Prepared block for proposing at {} ({} ms) [hash: {:?}; parent_hash: {}; extrinsics ({}): [{}]]",
1386        block.header().number(),
1387        used_time_ms,
1388        block.header().hash(),
1389        block.header().parent_hash(),
1390        block.extrinsics().len(),
1391        block
1392            .extrinsics()
1393            .iter()
1394            .map(|xt| BlakeTwo256::hash_of(xt).to_string())
1395            .collect::<Vec<_>>()
1396            .join(", ")
1397    );
1398}
1399
1400fn mock_import_queue<Block: BlockT, I>(
1401    block_import: I,
1402    spawner: &impl SpawnEssentialNamed,
1403) -> BasicQueue<Block>
1404where
1405    I: BlockImport<Block, Error = ConsensusError> + Send + Sync + 'static,
1406{
1407    BasicQueue::new(
1408        MockVerifier::default(),
1409        Box::new(block_import),
1410        None,
1411        spawner,
1412        None,
1413    )
1414}
1415
1416struct MockVerifier<Block> {
1417    _marker: PhantomData<Block>,
1418}
1419
1420impl<Block> Default for MockVerifier<Block> {
1421    fn default() -> Self {
1422        Self {
1423            _marker: PhantomData,
1424        }
1425    }
1426}
1427
1428#[async_trait::async_trait]
1429impl<Block> VerifierT<Block> for MockVerifier<Block>
1430where
1431    Block: BlockT,
1432{
1433    async fn verify(
1434        &self,
1435        block_params: BlockImportParams<Block>,
1436    ) -> Result<BlockImportParams<Block>, String> {
1437        Ok(block_params)
1438    }
1439}
1440
1441// `MockBlockImport` is mostly port from `sc-consensus-subspace::SubspaceBlockImport` with all
1442// the consensus related logic removed.
1443#[allow(clippy::type_complexity)]
1444struct MockBlockImport<Client, Block: BlockT> {
1445    inner: Arc<Client>,
1446    block_importing_notification_subscribers:
1447        Arc<Mutex<Vec<TracingUnboundedSender<(NumberFor<Block>, mpsc::Sender<()>)>>>>,
1448}
1449
1450impl<Client, Block: BlockT> MockBlockImport<Client, Block> {
1451    fn new(inner: Arc<Client>) -> Self {
1452        MockBlockImport {
1453            inner,
1454            block_importing_notification_subscribers: Arc::new(Mutex::new(Vec::new())),
1455        }
1456    }
1457
1458    // Subscribe the block importing notification
1459    fn block_importing_notification_stream(
1460        &self,
1461    ) -> TracingUnboundedReceiver<(NumberFor<Block>, mpsc::Sender<()>)> {
1462        let (tx, rx) = tracing_unbounded("subspace_new_slot_notification_stream", 100);
1463        self.block_importing_notification_subscribers
1464            .lock()
1465            .push(tx);
1466        rx
1467    }
1468}
1469
1470impl<Client, Block: BlockT> MockBlockImport<Client, Block> {
1471    fn clone(&self) -> Self {
1472        MockBlockImport {
1473            inner: self.inner.clone(),
1474            block_importing_notification_subscribers: self
1475                .block_importing_notification_subscribers
1476                .clone(),
1477        }
1478    }
1479}
1480
1481#[async_trait::async_trait]
1482impl<Client, Block> BlockImport<Block> for MockBlockImport<Client, Block>
1483where
1484    Block: BlockT,
1485    for<'r> &'r Client: BlockImport<Block, Error = ConsensusError> + Send + Sync,
1486    Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
1487    Client::Api: ApiExt<Block>,
1488{
1489    type Error = ConsensusError;
1490
1491    async fn import_block(
1492        &self,
1493        mut block: BlockImportParams<Block>,
1494    ) -> Result<ImportResult, Self::Error> {
1495        let block_number = *block.header.number();
1496        block.fork_choice = Some(ForkChoiceStrategy::LongestChain);
1497
1498        let (acknowledgement_sender, mut acknowledgement_receiver) = mpsc::channel(0);
1499
1500        // Must drop `block_import_acknowledgement_sender` after the notification otherwise the receiver
1501        // will block forever as there is still a sender not closed.
1502        {
1503            let value = (block_number, acknowledgement_sender);
1504            self.block_importing_notification_subscribers
1505                .lock()
1506                .retain(|subscriber| subscriber.unbounded_send(value.clone()).is_ok());
1507        }
1508
1509        while acknowledgement_receiver.next().await.is_some() {
1510            // Wait for all the acknowledgements to finish.
1511        }
1512
1513        self.inner.import_block(block).await
1514    }
1515
1516    async fn check_block(
1517        &self,
1518        block: BlockCheckParams<Block>,
1519    ) -> Result<ImportResult, Self::Error> {
1520        self.inner.check_block(block).await
1521    }
1522}
1523
1524/// Produce the given number of blocks for both the primary node and the domain nodes
1525#[macro_export]
1526macro_rules! produce_blocks {
1527    ($primary_node:ident, $operator_node:ident, $count: literal $(, $domain_node:ident)*) => {
1528        {
1529            async {
1530                let domain_fut = {
1531                    let mut futs: Vec<std::pin::Pin<Box<dyn futures::Future<Output = ()>>>> = Vec::new();
1532                    futs.push(Box::pin($operator_node.wait_for_blocks($count)));
1533                    $( futs.push( Box::pin( $domain_node.wait_for_blocks($count) ) ); )*
1534                    futures::future::join_all(futs)
1535                };
1536                $primary_node.produce_blocks_with_bundles($count).await?;
1537                domain_fut.await;
1538                Ok::<(), Box<dyn std::error::Error>>(())
1539            }
1540        }
1541    };
1542}
1543
1544/// Producing one block for both the primary node and the domain nodes, where the primary node can
1545/// use the `produce_block_with_xxx` function (i.e. `produce_block_with_slot`) to produce block
1546#[macro_export]
1547macro_rules! produce_block_with {
1548    ($primary_node_produce_block:expr, $operator_node:ident $(, $domain_node:ident)*) => {
1549        {
1550            async {
1551                let domain_fut = {
1552                    let mut futs: Vec<std::pin::Pin<Box<dyn futures::Future<Output = ()>>>> = Vec::new();
1553                    futs.push(Box::pin($operator_node.wait_for_blocks(1)));
1554                    $( futs.push( Box::pin( $domain_node.wait_for_blocks(1) ) ); )*
1555                    futures::future::join_all(futs)
1556                };
1557                $primary_node_produce_block.await?;
1558                domain_fut.await;
1559                Ok::<(), Box<dyn std::error::Error>>(())
1560            }
1561        }
1562    };
1563}
1564
1565/// Keep producing block with a fixed interval until the given condition become `true`
1566#[macro_export]
1567macro_rules! produce_blocks_until {
1568    ($primary_node:ident, $operator_node:ident, $condition: block $(, $domain_node:ident)*) => {
1569        async {
1570            while !$condition {
1571                produce_blocks!($primary_node, $operator_node, 1 $(, $domain_node),*).await?;
1572                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1573            }
1574            Ok::<(), Box<dyn std::error::Error>>(())
1575        }
1576    };
1577}
1578
1579type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
1580
1581fn get_signed_extra(
1582    current_block: u64,
1583    immortal: bool,
1584    nonce: u32,
1585    tip: BalanceOf<Runtime>,
1586) -> SignedExtra {
1587    let period = u64::from(<<Runtime as frame_system::Config>::BlockHashCount>::get())
1588        .checked_next_power_of_two()
1589        .map(|c| c / 2)
1590        .unwrap_or(2);
1591    (
1592        (
1593            frame_system::CheckNonZeroSender::<Runtime>::new(),
1594            SmallOrderEd25519CheckExtension::<Runtime>::new(),
1595        ),
1596        frame_system::CheckSpecVersion::<Runtime>::new(),
1597        frame_system::CheckTxVersion::<Runtime>::new(),
1598        frame_system::CheckGenesis::<Runtime>::new(),
1599        frame_system::CheckMortality::<Runtime>::from(if immortal {
1600            generic::Era::Immortal
1601        } else {
1602            generic::Era::mortal(period, current_block)
1603        }),
1604        frame_system::CheckNonce::<Runtime>::from(nonce.into()),
1605        frame_system::CheckWeight::<Runtime>::new(),
1606        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
1607        BalanceTransferCheckExtension::<Runtime>::default(),
1608        pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
1609        pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
1610        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1611    )
1612}
1613
1614fn construct_extrinsic_raw_payload<Client>(
1615    client: impl AsRef<Client>,
1616    function: <Runtime as frame_system::Config>::RuntimeCall,
1617    immortal: bool,
1618    nonce: u32,
1619    tip: BalanceOf<Runtime>,
1620) -> (
1621    SignedPayload<<Runtime as frame_system::Config>::RuntimeCall, SignedExtra>,
1622    SignedExtra,
1623)
1624where
1625    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
1626    u64: From<BlockNumberFor<Runtime>>,
1627    Client: HeaderBackend<subspace_runtime_primitives::opaque::Block>,
1628{
1629    let current_block_hash = client.as_ref().info().best_hash;
1630    let current_block = client.as_ref().info().best_number.saturated_into();
1631    let genesis_block = client.as_ref().hash(0).unwrap().unwrap();
1632    let extra = get_signed_extra(current_block, immortal, nonce, tip);
1633    (
1634        generic::SignedPayload::<
1635            <Runtime as frame_system::Config>::RuntimeCall,
1636            SignedExtra,
1637        >::from_raw(
1638            function,
1639            extra.clone(),
1640            (
1641                ((), ()),
1642                100,
1643                1,
1644                genesis_block,
1645                current_block_hash,
1646                (),
1647                (),
1648                (),
1649                (),
1650                (),
1651                (),
1652                (),
1653            ),
1654        ),
1655        extra,
1656    )
1657}
1658
1659/// Construct an extrinsic that can be applied to the test runtime.
1660pub fn construct_extrinsic_generic<Client>(
1661    client: impl AsRef<Client>,
1662    function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
1663    caller: Sr25519Keyring,
1664    immortal: bool,
1665    nonce: u32,
1666    tip: BalanceOf<Runtime>,
1667) -> UncheckedExtrinsic
1668where
1669    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
1670    u64: From<BlockNumberFor<Runtime>>,
1671    Client: HeaderBackend<subspace_runtime_primitives::opaque::Block>,
1672{
1673    let function = function.into();
1674    let (raw_payload, extra) =
1675        construct_extrinsic_raw_payload(client, function.clone(), immortal, nonce, tip);
1676    let signature = raw_payload.using_encoded(|e| caller.sign(e));
1677    UncheckedExtrinsic::new_signed(
1678        function,
1679        MultiAddress::Id(caller.to_account_id()),
1680        Signature::Sr25519(signature),
1681        extra,
1682    )
1683}
1684
1685/// Construct a general unsigned extrinsic that can be applied to the test runtime.
1686fn construct_unsigned_extrinsic<Client>(
1687    client: impl AsRef<Client>,
1688    function: impl Into<<Runtime as frame_system::Config>::RuntimeCall>,
1689) -> UncheckedExtrinsic
1690where
1691    BalanceOf<Runtime>: Send + Sync + From<u64> + sp_runtime::FixedPointOperand,
1692    u64: From<BlockNumberFor<Runtime>>,
1693    Client: HeaderBackend<subspace_runtime_primitives::opaque::Block>,
1694{
1695    let function = function.into();
1696    let current_block = client.as_ref().info().best_number.saturated_into();
1697    let extra = get_signed_extra(current_block, true, 0, 0);
1698    UncheckedExtrinsic::new_transaction(function, extra)
1699}