Struct sc_network::NetworkService [−][src]
Substrate network service. Handles network IO and manages connectivity.
Implementations
impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H>
[src]
pub fn local_peer_id(&self) -> &PeerId
[src]
Returns the local PeerId
.
pub fn set_authorized_peers(&self, peers: HashSet<PeerId>)
[src]
Set authorized peers.
Need a better solution to manage authorized peers, but now just use reserved peers for prototyping.
pub fn set_authorized_only(&self, reserved_only: bool)
[src]
Set authorized_only flag.
Need a better solution to decide authorized_only, but now just use reserved_only flag for prototyping.
pub fn write_notification(
&self,
target: PeerId,
engine_id: ConsensusEngineId,
message: Vec<u8>
)
[src]
&self,
target: PeerId,
engine_id: ConsensusEngineId,
message: Vec<u8>
)
Appends a notification to the buffer of pending outgoing notifications with the given peer. Has no effect if the notifications channel with this protocol name is not open.
If the buffer of pending outgoing notifications with that peer is full, the notification is silently dropped and the connection to the remote will start being shut down. This happens if you call this method at a higher rate than the rate at which the peer processes these notifications, or if the available network bandwidth is too low.
For this reason, this method is considered soft-deprecated. You are encouraged to use
NetworkService::notification_sender
instead.
Note: The reason why this is a no-op in the situation where we have no channel is that we don’t guarantee message delivery anyway. Networking issues can cause connections to drop at any time, and higher-level logic shouldn’t differentiate between the remote voluntarily closing a substream or a network error preventing the message from being delivered.
The protocol must have been registered with register_notifications_protocol
or
NetworkConfiguration::notifications_protocols
.
pub fn notification_sender(
&self,
target: PeerId,
engine_id: ConsensusEngineId
) -> Result<NotificationSender, NotificationSenderError>
[src]
&self,
target: PeerId,
engine_id: ConsensusEngineId
) -> Result<NotificationSender, NotificationSenderError>
Obtains a NotificationSender
for a connected peer, if it exists.
A NotificationSender
is scoped to a particular connection to the peer that holds
a receiver. With a NotificationSender
at hand, sending a notification is done in two steps:
NotificationSender::ready
is used to wait for the sender to become ready for another notification, yielding aNotificationSenderReady
token.NotificationSenderReady::send
enqueues the notification for sending. This operation can only fail if the underlying notification substream or connection has suddenly closed.
An error is returned by NotificationSenderReady::send
if there exists no open
notifications substream with that combination of peer and protocol, or if the remote
has asked to close the notifications substream. If that happens, it is guaranteed that an
Event::NotificationStreamClosed
has been generated on the stream returned by
NetworkService::event_stream
.
If the remote requests to close the notifications substream, all notifications successfully
enqueued using NotificationSenderReady::send
will finish being sent out before the
substream actually gets closed, but attempting to enqueue more notifications will now
return an error. It is however possible for the entire connection to be abruptly closed,
in which case enqueued notifications will be lost.
The protocol must have been registered with register_notifications_protocol
or
NetworkConfiguration::notifications_protocols
.
Usage
This method returns a struct that allows waiting until there is space available in the buffer of messages towards the given peer. If the peer processes notifications at a slower rate than we send them, this buffer will quickly fill up.
As such, you should never do something like this:
// Do NOT do this for peer in peers { if let Ok(n) = network.notification_sender(peer, ...) { if let Ok(s) = n.ready().await { let _ = s.send(...); } } }
Doing so would slow down all peers to the rate of the slowest one. A malicious or malfunctioning peer could intentionally process notifications at a very slow rate.
Instead, you are encouraged to maintain your own buffer of notifications on top of the one
maintained by sc-network
, and use notification_sender
to progressively send out
elements from your buffer. If this additional buffer is full (which will happen at some
point if the peer is too slow to process notifications), appropriate measures can be taken,
such as removing non-critical notifications from the buffer or disconnecting the peer
using NetworkService::disconnect_peer
.
Notifications Per-peer buffer
broadcast +—––> of notifications +–> notification_sender
+–> Internet
^ (not covered by
| sc-network)
+
Notifications should be dropped
if buffer is full
See also the gossip
module for a higher-level way to send
notifications.
pub fn event_stream(&self, name: &'static str) -> impl Stream<Item = Event>
[src]
Returns a stream containing the events that happen on the network.
If this method is called multiple times, the events are duplicated.
The stream never ends (unless the NetworkWorker
gets shut down).
The name passed is used to identify the channel in the Prometheus metrics. Note that the
parameter is a &'static str
, and not a String
, in order to avoid accidentally having
an unbounded set of Prometheus metrics, which would be quite bad in terms of memory
pub async fn request(
&self,
target: PeerId,
protocol: impl Into<Cow<'static, str>>,
request: Vec<u8>
) -> Result<Vec<u8>, RequestFailure>
[src]
&self,
target: PeerId,
protocol: impl Into<Cow<'static, str>>,
request: Vec<u8>
) -> Result<Vec<u8>, RequestFailure>
Sends a single targeted request to a specific peer. On success, returns the response of the peer.
Request-response protocols are a way to complement notifications protocols, but
notifications should remain the default ways of communicating information. For example, a
peer can announce something through a notification, after which the recipient can obtain
more information by performing a request.
As such, this function is meant to be called only with peers we are already connected to.
Calling this method with a target
we are not connected to will not attempt to connect
to said peer.
No limit or throttling of concurrent outbound requests per peer and protocol are enforced. Such restrictions, if desired, need to be enforced at the call site(s).
The protocol must have been registered through
NetworkConfiguration::request_response_protocols
.
pub fn register_notifications_protocol(
&self,
engine_id: ConsensusEngineId,
protocol_name: impl Into<Cow<'static, str>>
)
[src]
&self,
engine_id: ConsensusEngineId,
protocol_name: impl Into<Cow<'static, str>>
)
Registers a new notifications protocol.
After a protocol has been registered, you can call write_notifications
.
Important: This method is a work-around, and you are instead strongly encouraged to
pass the protocol in the NetworkConfiguration::notifications_protocols
list instead.
If you have no other choice but to use this method, you are very strongly encouraged to
call it very early on. Any connection open will retain the protocols that were registered
then, and not any new one.
Please call event_stream
before registering a protocol, otherwise you may miss events
about the protocol that you have registered.
pub fn trigger_repropagate(&self)
[src]
You may call this when new transactons are imported by the transaction pool.
All transactions will be fetched from the TransactionPool
that was passed at
initialization as part of the configuration and propagated to peers.
pub fn propagate_transaction(&self, hash: H)
[src]
You must call when new transaction is imported by the transaction pool.
This transaction will be fetched from the TransactionPool
that was passed at
initialization as part of the configuration and propagated to peers.
pub fn announce_block(&self, hash: B::Hash, data: Vec<u8>)
[src]
Make sure an important block is propagated to peers.
In chain-based consensus, we often need to make sure non-best forks are at least temporarily synced. This function forces such an announcement.
pub fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange)
[src]
Report a given peer as either beneficial (+) or costly (-) according to the given scalar.
pub fn disconnect_peer(&self, who: PeerId)
[src]
Disconnect from a node as soon as possible.
This triggers the same effects as if the connection had closed itself spontaneously.
pub fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>)
[src]
Request a justification for the given block from the network.
On success, the justification will be passed to the import queue that was part at initialization as part of the configuration.
pub fn is_major_syncing(&self) -> bool
[src]
Are we in the process of downloading the chain?
pub fn get_value(&self, key: &Key)
[src]
Start getting a value from the DHT.
This will generate either a ValueFound
or a ValueNotFound
event and pass it as an
item on the NetworkWorker
stream.
pub fn put_value(&self, key: Key, value: Vec<u8>)
[src]
Start putting a value in the DHT.
This will generate either a ValuePut
or a ValuePutFailed
event and pass it as an
item on the NetworkWorker
stream.
pub fn accept_unreserved_peers(&self)
[src]
Connect to unreserved peers and allow unreserved peers to connect.
pub fn deny_unreserved_peers(&self)
[src]
Disconnect from unreserved peers and deny new unreserved peers to connect.
pub fn remove_reserved_peer(&self, peer: PeerId)
[src]
Removes a PeerId
from the list of reserved peers.
pub fn add_reserved_peer(&self, peer: String) -> Result<(), String>
[src]
Adds a PeerId
and its address as reserved. The string should encode the address
and peer ID of the remote node.
Returns an Err
if the given string is not a valid multiaddress
or contains an invalid peer ID (which includes the local peer ID).
pub fn set_sync_fork_request(
&self,
peers: Vec<PeerId>,
hash: B::Hash,
number: NumberFor<B>
)
[src]
&self,
peers: Vec<PeerId>,
hash: B::Hash,
number: NumberFor<B>
)
Configure an explicit fork sync request.
Note that this function should not be used for recent blocks.
Sync should be able to download all the recent forks normally.
set_sync_fork_request
should only be used if external code detects that there’s
a stale fork missing.
Passing empty peers
set effectively removes the sync request.
pub fn set_priority_group(
&self,
group_id: String,
peers: HashSet<Multiaddr>
) -> Result<(), String>
[src]
&self,
group_id: String,
peers: HashSet<Multiaddr>
) -> Result<(), String>
Modify a peerset priority group.
Each Multiaddr
must end with a /p2p/
component containing the PeerId
.
Returns an Err
if one of the given addresses is invalid or contains an
invalid peer ID (which includes the local peer ID).
pub fn num_connected(&self) -> usize
[src]
Returns the number of peers we’re connected to.
pub fn update_chain(&self)
[src]
This function should be called when blocks are added to the chain by something other than the import queue.
Important: This function is a hack and can be removed at any time. Do not use it.
pub fn own_block_imported(&self, hash: B::Hash, number: NumberFor<B>)
[src]
Inform the network service about an own imported block.
Trait Implementations
impl<B, H> NetworkStateInfo for NetworkService<B, H> where
B: Block,
H: ExHashT,
[src]
B: Block,
H: ExHashT,
fn external_addresses(&self) -> Vec<Multiaddr>
[src]
Returns the local external addresses.
fn local_peer_id(&self) -> PeerId
[src]
Returns the local Peer ID.
impl<B: BlockT + 'static, H: ExHashT> SyncOracle for NetworkService<B, H>
[src]
fn is_major_syncing(&mut self) -> bool
[src]
fn is_offline(&mut self) -> bool
[src]
impl<'a, B: BlockT + 'static, H: ExHashT> SyncOracle for &'a NetworkService<B, H>
[src]
fn is_major_syncing(&mut self) -> bool
[src]
fn is_offline(&mut self) -> bool
[src]
Auto Trait Implementations
impl<B, H> !RefUnwindSafe for NetworkService<B, H>
impl<B, H> Send for NetworkService<B, H>
impl<B, H> Sync for NetworkService<B, H>
impl<B, H> Unpin for NetworkService<B, H> where
H: Unpin,
H: Unpin,
impl<B, H> !UnwindSafe for NetworkService<B, H>
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> CheckedConversion for T
[src]
pub fn checked_from<T>(t: T) -> Option<Self> where
Self: TryFrom<T>,
[src]
Self: TryFrom<T>,
pub fn checked_into<T>(self) -> Option<T> where
Self: TryInto<T>,
[src]
Self: TryInto<T>,
impl<T> From<T> for T
[src]
impl<T> Instrument for T
[src]
pub fn instrument(self, span: Span) -> Instrumented<Self>
[src]
pub fn in_current_span(self) -> Instrumented<Self>
[src]
impl<T> Instrument for T
[src]
pub fn instrument(self, span: Span) -> Instrumented<Self>
[src]
pub fn in_current_span(self) -> Instrumented<Self>
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T, Outer> IsWrappedBy<Outer> for T where
T: From<Outer>,
Outer: AsRef<T> + AsMut<T> + From<T>,
[src]
T: From<Outer>,
Outer: AsRef<T> + AsMut<T> + From<T>,
pub fn from_ref(outer: &Outer) -> &T
[src]
Get a reference to the inner from the outer.
pub fn from_mut(outer: &mut Outer) -> &mut T
[src]
Get a mutable reference to the inner from the outer.
impl<T> Pointable for T
[src]
pub const ALIGN: usize
[src]
type Init = T
The type for initializers.
pub unsafe fn init(init: <T as Pointable>::Init) -> usize
[src]
pub unsafe fn deref<'a>(ptr: usize) -> &'a T
[src]
pub unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T
[src]
pub unsafe fn drop(ptr: usize)
[src]
impl<T> Same<T> for T
[src]
type Output = T
Should always be Self
impl<T> SaturatedConversion for T
[src]
pub fn saturated_from<T>(t: T) -> Self where
Self: UniqueSaturatedFrom<T>,
[src]
Self: UniqueSaturatedFrom<T>,
pub fn saturated_into<T>(self) -> T where
Self: UniqueSaturatedInto<T>,
[src]
Self: UniqueSaturatedInto<T>,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<S, T> UncheckedInto<T> for S where
T: UncheckedFrom<S>,
[src]
T: UncheckedFrom<S>,
pub fn unchecked_into(self) -> T
[src]
impl<T, S> UniqueSaturatedInto<T> for S where
T: Bounded,
S: TryInto<T>,
[src]
T: Bounded,
S: TryInto<T>,
pub fn unique_saturated_into(self) -> T
[src]
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
[src]
V: MultiLane<T>,