Network sync refactoring (part 6) (#11940)

* Extract `NetworkKVProvider` trait in `sc-authority-discovery` and remove unnecessary dependency

* Extract `NetworkSyncForkRequest` trait in `sc-finality-grandpa`

* Relax requirements on `SyncOracle` trait, remove extra native methods from `NetworkService` that are already provided by trait impls

* Move `NetworkSigner` trait from `sc-authority-discovery` into `sc-network-common` and de-duplicate methods on `NetworkService`

* Move `NetworkKVProvider` trait from `sc-authority-discovery` into `sc-network-common` and de-duplicate methods on `NetworkService`

* Minimize `sc-authority-discovery` dependency on `sc-network`

* Move `NetworkSyncForkRequest` trait from `sc-finality-grandpa` to `sc-network-common` and de-duplicate methods in `NetworkService`

* Extract `NetworkStatusProvider` trait and de-duplicate methods on `NetworkService`

* Extract `NetworkPeers` trait and de-duplicate methods on `NetworkService`

* Extract `NetworkEventStream` trait and de-duplicate methods on `NetworkService`

* Move more methods from `NetworkService` into `NetworkPeers` trait

* Move `NetworkStateInfo` trait into `sc-network-common`

* Extract `NetworkNotification` trait and de-duplicate methods on `NetworkService`

* Extract `NetworkRequest` trait and de-duplicate methods on `NetworkService`

* Remove `NetworkService::local_peer_id()`, it is already provided by `NetworkStateInfo` impl

* Extract `NetworkTransaction` trait and de-duplicate methods on `NetworkService`

* Extract `NetworkBlock` trait and de-duplicate methods on `NetworkService`

* Remove dependencies on `NetworkService` from most of the methods of `sc-service`

* Address simple review comments
This commit is contained in:
Nazar Mokrynskyi
2022-08-09 21:28:32 +03:00
committed by GitHub
parent 9c56e79c43
commit a685582bfd
49 changed files with 1889 additions and 1029 deletions
@@ -32,19 +32,22 @@ use std::{
use futures::{channel::mpsc, future, stream::Fuse, FutureExt, Stream, StreamExt};
use addr_cache::AddrCache;
use async_trait::async_trait;
use codec::Decode;
use ip_network::IpNetwork;
use libp2p::{
core::multiaddr,
multihash::{Multihash, MultihashDigest},
Multiaddr, PeerId,
};
use log::{debug, error, log_enabled};
use prometheus_endpoint::{register, Counter, CounterVec, Gauge, Opts, U64};
use prost::Message;
use rand::{seq::SliceRandom, thread_rng};
use sc_client_api::blockchain::HeaderBackend;
use sc_network::{DhtEvent, ExHashT, Multiaddr, NetworkStateInfo, PeerId};
use sc_network_common::{
protocol::event::DhtEvent,
service::{KademliaKey, NetworkDHTProvider, NetworkSigner, NetworkStateInfo, Signature},
};
use sp_api::ProvideRuntimeApi;
use sp_authority_discovery::{
AuthorityDiscoveryApi, AuthorityId, AuthorityPair, AuthoritySignature,
@@ -136,7 +139,7 @@ pub struct Worker<Client, Network, Block, DhtEventStream> {
/// Queue of throttled lookups pending to be passed to the network.
pending_lookups: Vec<AuthorityId>,
/// Set of in-flight lookups.
in_flight_lookups: HashMap<sc_network::KademliaKey, AuthorityId>,
in_flight_lookups: HashMap<KademliaKey, AuthorityId>,
addr_cache: addr_cache::AddrCache,
@@ -464,10 +467,7 @@ where
}
}
fn handle_dht_value_found_event(
&mut self,
values: Vec<(sc_network::KademliaKey, Vec<u8>)>,
) -> Result<()> {
fn handle_dht_value_found_event(&mut self, values: Vec<(KademliaKey, Vec<u8>)>) -> Result<()> {
// Ensure `values` is not empty and all its keys equal.
let remote_key = single(values.iter().map(|(key, _)| key.clone()))
.map_err(|_| Error::ReceivingDhtValueFoundEventWithDifferentKeys)?
@@ -523,11 +523,11 @@ where
// properly signed by the owner of the PeerId
if let Some(peer_signature) = peer_signature {
let public_key =
sc_network::PublicKey::from_protobuf_encoding(&peer_signature.public_key)
.map_err(Error::ParsingLibp2pIdentity)?;
let signature =
sc_network::Signature { public_key, bytes: peer_signature.signature };
let public_key = libp2p::identity::PublicKey::from_protobuf_encoding(
&peer_signature.public_key,
)
.map_err(Error::ParsingLibp2pIdentity)?;
let signature = Signature { public_key, bytes: peer_signature.signature };
if !signature.verify(record, &remote_peer_id) {
return Err(Error::VerifyingDhtPayload)
@@ -590,55 +590,15 @@ where
}
}
pub trait NetworkSigner {
/// Sign a message in the name of `self.local_peer_id()`
fn sign_with_local_identity(
&self,
msg: impl AsRef<[u8]>,
) -> std::result::Result<sc_network::Signature, sc_network::SigningError>;
}
/// NetworkProvider provides [`Worker`] with all necessary hooks into the
/// underlying Substrate networking. Using this trait abstraction instead of
/// [`sc_network::NetworkService`] directly is necessary to unit test [`Worker`].
#[async_trait]
pub trait NetworkProvider: NetworkStateInfo + NetworkSigner {
/// Start putting a value in the Dht.
fn put_value(&self, key: sc_network::KademliaKey, value: Vec<u8>);
/// `sc_network::NetworkService` directly is necessary to unit test [`Worker`].
pub trait NetworkProvider: NetworkDHTProvider + NetworkStateInfo + NetworkSigner {}
/// Start getting a value from the Dht.
fn get_value(&self, key: &sc_network::KademliaKey);
}
impl<T> NetworkProvider for T where T: NetworkDHTProvider + NetworkStateInfo + NetworkSigner {}
impl<B, H> NetworkSigner for sc_network::NetworkService<B, H>
where
B: BlockT + 'static,
H: ExHashT,
{
fn sign_with_local_identity(
&self,
msg: impl AsRef<[u8]>,
) -> std::result::Result<sc_network::Signature, sc_network::SigningError> {
self.sign_with_local_identity(msg)
}
}
#[async_trait::async_trait]
impl<B, H> NetworkProvider for sc_network::NetworkService<B, H>
where
B: BlockT + 'static,
H: ExHashT,
{
fn put_value(&self, key: sc_network::KademliaKey, value: Vec<u8>) {
self.put_value(key, value)
}
fn get_value(&self, key: &sc_network::KademliaKey) {
self.get_value(key)
}
}
fn hash_authority_id(id: &[u8]) -> sc_network::KademliaKey {
sc_network::KademliaKey::new(&libp2p::multihash::Code::Sha2_256.digest(id).digest())
fn hash_authority_id(id: &[u8]) -> KademliaKey {
KademliaKey::new(&libp2p::multihash::Code::Sha2_256.digest(id).digest())
}
// Makes sure all values are the same and returns it
@@ -685,7 +645,7 @@ async fn sign_record_with_authority_ids(
peer_signature: Option<schema::PeerSignature>,
key_store: &dyn CryptoStore,
keys: Vec<CryptoTypePublicPair>,
) -> Result<Vec<(sc_network::KademliaKey, Vec<u8>)>> {
) -> Result<Vec<(KademliaKey, Vec<u8>)>> {
let signatures = key_store
.sign_with_all(key_types::AUTHORITY_DISCOVERY, keys.clone(), &serialized_record)
.await