Move around definitions in sc_network (#5701)

This commit is contained in:
Pierre Krieger
2020-04-20 14:35:17 +02:00
committed by GitHub
parent e1ef69506a
commit ca1c60c2cf
5 changed files with 104 additions and 100 deletions
+57 -2
View File
@@ -21,7 +21,6 @@
pub use crate::chain::{Client, FinalityProofProvider};
pub use crate::on_demand_layer::{AlwaysBadChecker, OnDemand};
pub use crate::service::{TransactionPool, EmptyTransactionPool};
pub use libp2p::{identity, core::PublicKey, wasm_ext::ExtTransport, build_multiaddr};
// Note: this re-export shouldn't be part of the public API of the crate and will be removed in
@@ -29,17 +28,19 @@ pub use libp2p::{identity, core::PublicKey, wasm_ext::ExtTransport, build_multia
#[doc(hidden)]
pub use crate::protocol::ProtocolConfig;
use crate::service::ExHashT;
use crate::{ExHashT, ReportHandle};
use core::{fmt, iter};
use libp2p::identity::{ed25519, Keypair};
use libp2p::wasm_ext;
use libp2p::{multiaddr, Multiaddr, PeerId};
use prometheus_endpoint::Registry;
use sc_peerset::ReputationChange;
use sp_consensus::{block_validation::BlockAnnounceValidator, import_queue::ImportQueue};
use sp_runtime::{traits::Block as BlockT, ConsensusEngineId};
use std::{borrow::Cow, convert::TryFrom, future::Future, pin::Pin, str::FromStr};
use std::{
collections::HashMap,
error::Error,
fs,
io::{self, Write},
@@ -166,6 +167,60 @@ impl<B: BlockT> FinalityProofRequestBuilder<B> for DummyFinalityProofRequestBuil
/// Shared finality proof request builder struct used by the queue.
pub type BoxFinalityProofRequestBuilder<B> = Box<dyn FinalityProofRequestBuilder<B> + Send + Sync>;
/// Transaction pool interface
pub trait TransactionPool<H: ExHashT, B: BlockT>: Send + Sync {
/// Get transactions from the pool that are ready to be propagated.
fn transactions(&self) -> Vec<(H, B::Extrinsic)>;
/// Get hash of transaction.
fn hash_of(&self, transaction: &B::Extrinsic) -> H;
/// Import a transaction into the pool.
///
/// Peer reputation is changed by reputation_change if transaction is accepted by the pool.
fn import(
&self,
report_handle: ReportHandle,
who: PeerId,
reputation_change_good: ReputationChange,
reputation_change_bad: ReputationChange,
transaction: B::Extrinsic,
);
/// Notify the pool about transactions broadcast.
fn on_broadcasted(&self, propagations: HashMap<H, Vec<String>>);
/// Get transaction by hash.
fn transaction(&self, hash: &H) -> Option<B::Extrinsic>;
}
/// Dummy implementation of the [`TransactionPool`] trait for a transaction pool that is always
/// empty and discards all incoming transactions.
///
/// Requires the "hash" type to implement the `Default` trait.
///
/// Useful for testing purposes.
pub struct EmptyTransactionPool;
impl<H: ExHashT + Default, B: BlockT> TransactionPool<H, B> for EmptyTransactionPool {
fn transactions(&self) -> Vec<(H, B::Extrinsic)> {
Vec::new()
}
fn hash_of(&self, _transaction: &B::Extrinsic) -> H {
Default::default()
}
fn import(
&self,
_report_handle: ReportHandle,
_who: PeerId,
_rep_change_good: ReputationChange,
_rep_change_bad: ReputationChange,
_transaction: B::Extrinsic
) {}
fn on_broadcasted(&self, _: HashMap<H, Vec<String>>) {}
fn transaction(&self, _h: &H) -> Option<B::Extrinsic> { None }
}
/// Name of a protocol, transmitted on the wire. Should be unique for each chain.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>);
+36 -1
View File
@@ -246,7 +246,7 @@ pub mod config;
pub mod error;
pub mod network_state;
pub use service::{NetworkService, NetworkStateInfo, NetworkWorker, ExHashT, ReportHandle};
pub use service::{NetworkService, NetworkWorker};
pub use protocol::PeerInfo;
pub use protocol::event::{Event, DhtEvent, ObservedRole};
pub use protocol::sync::SyncState;
@@ -264,3 +264,38 @@ pub use sc_peerset::ReputationChange;
/// case of (possibly repeated) simultaneous dialing attempts between
/// two peers, the per-peer connection limit is not set to 1 but 2.
const MAX_CONNECTIONS_PER_PEER: usize = 2;
/// Minimum Requirements for a Hash within Networking
pub trait ExHashT: std::hash::Hash + Eq + std::fmt::Debug + Clone + Send + Sync + 'static {}
impl<T> ExHashT for T where T: std::hash::Hash + Eq + std::fmt::Debug + Clone + Send + Sync + 'static
{}
/// A cloneable handle for reporting cost/benefits of peers.
#[derive(Clone)]
pub struct ReportHandle {
inner: sc_peerset::PeersetHandle, // wraps it so we don't have to worry about breaking API.
}
impl From<sc_peerset::PeersetHandle> for ReportHandle {
fn from(peerset_handle: sc_peerset::PeersetHandle) -> Self {
ReportHandle { inner: peerset_handle }
}
}
impl ReportHandle {
/// Report a given peer as either beneficial (+) or costly (-) according to the
/// given scalar.
pub fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) {
self.inner.report_peer(who, cost_benefit);
}
}
/// Trait for providing information about the local network state
pub trait NetworkStateInfo {
/// Returns the local external addresses.
fn external_addresses(&self) -> Vec<Multiaddr>;
/// Returns the local Peer ID.
fn local_peer_id(&self) -> PeerId;
}
+8 -6
View File
@@ -14,8 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use crate::config::ProtocolId;
use crate::utils::interval;
use crate::{
ExHashT,
chain::{Client, FinalityProofProvider},
config::{BoxFinalityProofRequestBuilder, ProtocolId, TransactionPool},
error,
utils::interval
};
use bytes::{Bytes, BytesMut};
use futures::prelude::*;
use generic_proto::{GenericProto, GenericProtoOut};
@@ -42,17 +48,13 @@ use message::{BlockAnnounce, Message};
use message::generic::{Message as GenericMessage, ConsensusMessage, Roles};
use prometheus_endpoint::{Registry, Gauge, GaugeVec, HistogramVec, PrometheusError, Opts, register, U64};
use sync::{ChainSync, SyncState};
use crate::service::{TransactionPool, ExHashT};
use crate::config::BoxFinalityProofRequestBuilder;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::sync::Arc;
use std::fmt::Write;
use std::{cmp, io, num::NonZeroUsize, pin::Pin, task::Poll, time};
use log::{log, Level, trace, debug, warn, error};
use crate::chain::{Client, FinalityProofProvider};
use sc_client_api::{ChangesProof, StorageProof};
use crate::error;
use util::LruHashSet;
use wasm_timer::Instant;
+2 -90
View File
@@ -26,6 +26,7 @@
//! which is then processed by [`NetworkWorker::poll`].
use crate::{
ExHashT, NetworkStateInfo,
behaviour::{Behaviour, BehaviourOut},
config::{parse_addr, parse_str_addr, NonReservedPeerMode, Params, Role, TransportConfig},
discovery::DiscoveryConfig,
@@ -57,7 +58,7 @@ use sp_runtime::{
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
collections::HashSet,
fs, io,
marker::PhantomData,
pin::Pin,
@@ -73,86 +74,6 @@ mod out_events;
#[cfg(test)]
mod tests;
/// Minimum Requirements for a Hash within Networking
pub trait ExHashT: std::hash::Hash + Eq + std::fmt::Debug + Clone + Send + Sync + 'static {}
impl<T> ExHashT for T where T: std::hash::Hash + Eq + std::fmt::Debug + Clone + Send + Sync + 'static
{}
/// Transaction pool interface
pub trait TransactionPool<H: ExHashT, B: BlockT>: Send + Sync {
/// Get transactions from the pool that are ready to be propagated.
fn transactions(&self) -> Vec<(H, B::Extrinsic)>;
/// Get hash of transaction.
fn hash_of(&self, transaction: &B::Extrinsic) -> H;
/// Import a transaction into the pool.
///
/// Peer reputation is changed by reputation_change if transaction is accepted by the pool.
fn import(
&self,
report_handle: ReportHandle,
who: PeerId,
reputation_change_good: ReputationChange,
reputation_change_bad: ReputationChange,
transaction: B::Extrinsic,
);
/// Notify the pool about transactions broadcast.
fn on_broadcasted(&self, propagations: HashMap<H, Vec<String>>);
/// Get transaction by hash.
fn transaction(&self, hash: &H) -> Option<B::Extrinsic>;
}
/// Dummy implementation of the [`TransactionPool`] trait for a transaction pool that is always
/// empty and discards all incoming transactions.
///
/// Requires the "hash" type to implement the `Default` trait.
///
/// Useful for testing purposes.
pub struct EmptyTransactionPool;
impl<H: ExHashT + Default, B: BlockT> TransactionPool<H, B> for EmptyTransactionPool {
fn transactions(&self) -> Vec<(H, B::Extrinsic)> {
Vec::new()
}
fn hash_of(&self, _transaction: &B::Extrinsic) -> H {
Default::default()
}
fn import(
&self,
_report_handle: ReportHandle,
_who: PeerId,
_rep_change_good: ReputationChange,
_rep_change_bad: ReputationChange,
_transaction: B::Extrinsic
) {}
fn on_broadcasted(&self, _: HashMap<H, Vec<String>>) {}
fn transaction(&self, _h: &H) -> Option<B::Extrinsic> { None }
}
/// A cloneable handle for reporting cost/benefits of peers.
#[derive(Clone)]
pub struct ReportHandle {
inner: PeersetHandle, // wraps it so we don't have to worry about breaking API.
}
impl From<PeersetHandle> for ReportHandle {
fn from(peerset_handle: PeersetHandle) -> Self {
ReportHandle { inner: peerset_handle }
}
}
impl ReportHandle {
/// Report a given peer as either beneficial (+) or costly (-) according to the
/// given scalar.
pub fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) {
self.inner.report_peer(who, cost_benefit);
}
}
/// Substrate network service. Handles network IO and manages connectivity.
pub struct NetworkService<B: BlockT + 'static, H: ExHashT> {
/// Number of peers we're connected to.
@@ -792,15 +713,6 @@ impl<'a, B: BlockT + 'static, H: ExHashT> sp_consensus::SyncOracle
}
}
/// Trait for providing information about the local network state
pub trait NetworkStateInfo {
/// Returns the local external addresses.
fn external_addresses(&self) -> Vec<Multiaddr>;
/// Returns the local Peer ID.
fn local_peer_id(&self) -> PeerId;
}
impl<B, H> NetworkStateInfo for NetworkService<B, H>
where
B: sp_runtime::traits::Block,
@@ -95,7 +95,7 @@ fn build_test_full_node(config: config::NetworkConfiguration)
finality_proof_provider: None,
finality_proof_request_builder: None,
on_demand: None,
transaction_pool: Arc::new(crate::service::EmptyTransactionPool),
transaction_pool: Arc::new(crate::config::EmptyTransactionPool),
protocol_id: config::ProtocolId::from(&b"/test-protocol-name"[..]),
import_queue,
block_announce_validator: Box::new(