git.delta.rocks / unique-network / refs/commits / fd7a9f1bafd1

difftreelog

source

node/src/service.rs10.5 KiBsourcehistory
1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23use nft_runtime::{self, opaque::Block, RuntimeApi};4use sc_client_api::ExecutorProvider;5use sc_consensus::LongestChain;6use sc_executor::native_executor_instance;7pub use sc_executor::NativeExecutor;8use sc_finality_grandpa::{9    FinalityProofProvider as GrandpaFinalityProofProvider, SharedVoterState,10    StorageAndProofProvider,11};12use sc_service::{error::Error as ServiceError, AbstractService, Configuration, ServiceBuilder};13use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;14use sp_inherents::InherentDataProviders;15use std::sync::Arc;16use std::time::Duration;1718// Our native executor instance.19native_executor_instance!(20    pub Executor,21    nft_runtime::api::dispatch,22    nft_runtime::native_version,23);2425/// Starts a `ServiceBuilder` for a full service.26///27/// Use this macro if you don't actually need the full service, but just the builder in order to28/// be able to perform chain operations.29macro_rules! new_full_start {30    ($config:expr) => {{31        use jsonrpc_core::IoHandler;32        use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;33        use std::sync::Arc;3435        let mut import_setup = None;36        let inherent_data_providers = sp_inherents::InherentDataProviders::new();3738        let builder = sc_service::ServiceBuilder::new_full::<39            nft_runtime::opaque::Block,40            nft_runtime::RuntimeApi,41            crate::service::Executor,42        >($config)?43        .with_select_chain(|_config, backend| Ok(sc_consensus::LongestChain::new(backend.clone())))?44        .with_transaction_pool(|builder| {45            let pool_api = sc_transaction_pool::FullChainApi::new(builder.client().clone());46            Ok(sc_transaction_pool::BasicPool::new(47                builder.config().transaction_pool.clone(),48                std::sync::Arc::new(pool_api),49                builder.prometheus_registry(),50            ))51        })?52        .with_import_queue(53            |_config, client, mut select_chain, _transaction_pool, spawn_task_handle, registry| {54                let select_chain = select_chain55                    .take()56                    .ok_or_else(|| sc_service::Error::SelectChainRequired)?;5758                let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(59                    client.clone(),60                    &(client.clone() as Arc<_>),61                    select_chain,62                )?;6364                let aura_block_import =65                    sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(66                        grandpa_block_import.clone(),67                        client.clone(),68                    );6970                let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(71                    sc_consensus_aura::slot_duration(&*client)?,72                    aura_block_import,73                    Some(Box::new(grandpa_block_import.clone())),74                    None,75                    client,76                    inherent_data_providers.clone(),77                    spawn_task_handle,78                    registry,79                )?;8081                import_setup = Some((grandpa_block_import, grandpa_link));8283                Ok(import_queue)84            },85        )?86        .with_rpc_extensions(|builder| -> Result<IoHandler<sc_rpc::Metadata>, _> {87            let handler = pallet_contracts_rpc::Contracts::new(builder.client().clone());88            let delegate = pallet_contracts_rpc::ContractsApi::to_delegate(handler);8990            let mut io = IoHandler::default();91            io.extend_with(delegate);92            Ok(io)93        })?;9495        (builder, import_setup, inherent_data_providers)96    }};97}9899/// Builds a new service for a full client.100pub fn new_full(config: Configuration) -> Result<impl AbstractService, ServiceError> {101    let role = config.role.clone();102    let force_authoring = config.force_authoring;103    let name = config.network.node_name.clone();104    let disable_grandpa = config.disable_grandpa;105106    let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);107108    let (block_import, grandpa_link) = import_setup.take().expect(109        "Link Half and Block Import are present for Full Services or setup failed before. qed",110    );111112    let service = builder113        .with_finality_proof_provider(|client, backend| {114            // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider115            let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;116            Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)117        })?118        .build()?;119120    if role.is_authority() {121        let proposer = sc_basic_authorship::ProposerFactory::new(122            service.client(),123            service.transaction_pool(),124            service.prometheus_registry().as_ref(),125        );126127        let client = service.client();128        let select_chain = service129            .select_chain()130            .ok_or(ServiceError::SelectChainRequired)?;131132        let can_author_with =133            sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());134135        let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(136            sc_consensus_aura::slot_duration(&*client)?,137            client,138            select_chain,139            block_import,140            proposer,141            service.network(),142            inherent_data_providers.clone(),143            force_authoring,144            service.keystore(),145            can_author_with,146        )?;147148        // the AURA authoring task is considered essential, i.e. if it149        // fails we take down the service with it.150        service.spawn_essential_task("aura", aura);151    }152153    // if the node isn't actively participating in consensus then it doesn't154    // need a keystore, regardless of which protocol we use below.155    let keystore = if role.is_authority() {156        Some(service.keystore())157    } else {158        None159    };160161    let grandpa_config = sc_finality_grandpa::Config {162        // FIXME #1578 make this available through chainspec163        gossip_duration: Duration::from_millis(333),164        justification_period: 512,165        name: Some(name),166        observer_enabled: false,167        keystore,168        is_authority: role.is_network_authority(),169    };170171    let enable_grandpa = !disable_grandpa;172    if enable_grandpa {173        // start the full GRANDPA voter174        // NOTE: non-authorities could run the GRANDPA observer protocol, but at175        // this point the full voter should provide better guarantees of block176        // and vote data availability than the observer. The observer has not177        // been tested extensively yet and having most nodes in a network run it178        // could lead to finality stalls.179        let grandpa_config = sc_finality_grandpa::GrandpaParams {180            config: grandpa_config,181            link: grandpa_link,182            network: service.network(),183            inherent_data_providers: inherent_data_providers.clone(),184            telemetry_on_connect: Some(service.telemetry_on_connect_stream()),185            voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),186            prometheus_registry: service.prometheus_registry(),187            shared_voter_state: SharedVoterState::empty(),188        };189190        // the GRANDPA voter task is considered infallible, i.e.191        // if it fails we take down the service with it.192        service.spawn_essential_task(193            "grandpa-voter",194            sc_finality_grandpa::run_grandpa_voter(grandpa_config)?,195        );196    } else {197        sc_finality_grandpa::setup_disabled_grandpa(198            service.client(),199            &inherent_data_providers,200            service.network(),201        )?;202    }203204    Ok(service)205}206207/// Builds a new service for a light client.208pub fn new_light(config: Configuration) -> Result<impl AbstractService, ServiceError> {209    let inherent_data_providers = InherentDataProviders::new();210211    ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?212        .with_select_chain(|_config, backend| Ok(LongestChain::new(backend.clone())))?213        .with_transaction_pool(|builder| {214            let fetcher = builder215                .fetcher()216                .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;217218            let pool_api =219                sc_transaction_pool::LightChainApi::new(builder.client().clone(), fetcher.clone());220            let pool = sc_transaction_pool::BasicPool::with_revalidation_type(221                builder.config().transaction_pool.clone(),222                Arc::new(pool_api),223                builder.prometheus_registry(),224                sc_transaction_pool::RevalidationType::Light,225            );226            Ok(pool)227        })?228        .with_import_queue_and_fprb(229            |_config,230             client,231             backend,232             fetcher,233             _select_chain,234             _tx_pool,235             spawn_task_handle,236             prometheus_registry| {237                let fetch_checker = fetcher238                    .map(|fetcher| fetcher.checker().clone())239                    .ok_or_else(|| {240                        "Trying to start light import queue without active fetch checker"241                    })?;242                let grandpa_block_import = sc_finality_grandpa::light_block_import(243                    client.clone(),244                    backend,245                    &(client.clone() as Arc<_>),246                    Arc::new(fetch_checker),247                )?;248                let finality_proof_import = grandpa_block_import.clone();249                let finality_proof_request_builder =250                    finality_proof_import.create_finality_proof_request_builder();251252                let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(253                    sc_consensus_aura::slot_duration(&*client)?,254                    grandpa_block_import,255                    None,256                    Some(Box::new(finality_proof_import)),257                    client,258                    inherent_data_providers.clone(),259                    spawn_task_handle,260                    prometheus_registry,261                )?;262263                Ok((import_queue, finality_proof_request_builder))264            },265        )?266        .with_finality_proof_provider(|client, backend| {267            // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider268            let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;269            Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)270        })?271        .build()272}