Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit beb74f4

Browse files
authored
client/*: Treat protocol name as str and not [u8] (#6967)
* client/*: Treat protocol name as str and not [u8] Notification protocol names are in practice always valid utf8 strings. Instead of treating them as such in the type system, thus far they were casted to a [u8] at creation time. With this commit protocol names are instead treated as valid utf8 strings throughout the codebase and passed as `Cow<'static, str>` instead of `Cow<'static, [u8]>`. Among other things this eliminates the need for string casting when logging. * client/network: Don't allocate when protocol name is borrowed
1 parent 86ae27e commit beb74f4

File tree

16 files changed

+87
-76
lines changed

16 files changed

+87
-76
lines changed

client/finality-grandpa/src/communication/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ mod periodic;
6969
pub(crate) mod tests;
7070

7171
pub use sp_finality_grandpa::GRANDPA_ENGINE_ID;
72-
pub const GRANDPA_PROTOCOL_NAME: &[u8] = b"/paritytech/grandpa/1";
72+
pub const GRANDPA_PROTOCOL_NAME: &'static str = "/paritytech/grandpa/1";
7373

7474
// cost scalars for reporting peers.
7575
mod cost {

client/finality-grandpa/src/communication/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl sc_network_gossip::Network<Block> for TestNetwork {
6161
let _ = self.sender.unbounded_send(Event::WriteNotification(who, message));
6262
}
6363

64-
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, [u8]>) {}
64+
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, str>) {}
6565

6666
fn announce(&self, block: Hash, _associated_data: Vec<u8>) {
6767
let _ = self.sender.unbounded_send(Event::Announce(block));

client/network-gossip/src/bridge.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ impl<B: BlockT> GossipEngine<B> {
6969
pub fn new<N: Network<B> + Send + Clone + 'static>(
7070
network: N,
7171
engine_id: ConsensusEngineId,
72-
protocol_name: impl Into<Cow<'static, [u8]>>,
72+
protocol_name: impl Into<Cow<'static, str>>,
7373
validator: Arc<dyn Validator<B>>,
7474
) -> Self where B: 'static {
7575
// We grab the event stream before registering the notifications protocol, otherwise we
@@ -333,7 +333,7 @@ mod tests {
333333
unimplemented!();
334334
}
335335

336-
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, [u8]>) {}
336+
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, str>) {}
337337

338338
fn announce(&self, _: B::Hash, _: Vec<u8>) {
339339
unimplemented!();
@@ -362,7 +362,7 @@ mod tests {
362362
let mut gossip_engine = GossipEngine::<Block>::new(
363363
network.clone(),
364364
[1, 2, 3, 4],
365-
"my_protocol".as_bytes(),
365+
"my_protocol",
366366
Arc::new(AllowAll{}),
367367
);
368368

@@ -390,7 +390,7 @@ mod tests {
390390
let mut gossip_engine = GossipEngine::<Block>::new(
391391
network.clone(),
392392
engine_id.clone(),
393-
"my_protocol".as_bytes(),
393+
"my_protocol",
394394
Arc::new(AllowAll{}),
395395
);
396396

@@ -525,7 +525,7 @@ mod tests {
525525
let mut gossip_engine = GossipEngine::<Block>::new(
526526
network.clone(),
527527
engine_id.clone(),
528-
"my_protocol".as_bytes(),
528+
"my_protocol",
529529
Arc::new(TestValidator{}),
530530
);
531531

client/network-gossip/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ pub trait Network<B: BlockT> {
8787
fn register_notifications_protocol(
8888
&self,
8989
engine_id: ConsensusEngineId,
90-
protocol_name: Cow<'static, [u8]>,
90+
protocol_name: Cow<'static, str>,
9191
);
9292

9393
/// Notify everyone we're connected to that we have the given block.
@@ -117,7 +117,7 @@ impl<B: BlockT, H: ExHashT> Network<B> for Arc<NetworkService<B, H>> {
117117
fn register_notifications_protocol(
118118
&self,
119119
engine_id: ConsensusEngineId,
120-
protocol_name: Cow<'static, [u8]>,
120+
protocol_name: Cow<'static, str>,
121121
) {
122122
NetworkService::register_notifications_protocol(self, engine_id, protocol_name)
123123
}

client/network-gossip/src/state_machine.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ mod tests {
489489
unimplemented!();
490490
}
491491

492-
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, [u8]>) {}
492+
fn register_notifications_protocol(&self, _: ConsensusEngineId, _: Cow<'static, str>) {}
493493

494494
fn announce(&self, _: B::Hash, _: Vec<u8>) {
495495
unimplemented!();

client/network/src/behaviour.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ impl<B: BlockT, H: ExHashT> Behaviour<B, H> {
255255
pub fn register_notifications_protocol(
256256
&mut self,
257257
engine_id: ConsensusEngineId,
258-
protocol_name: impl Into<Cow<'static, [u8]>>,
258+
protocol_name: impl Into<Cow<'static, str>>,
259259
) {
260260
// This is the message that we will send to the remote as part of the initial handshake.
261261
// At the moment, we force this to be an encoded `Roles`.

client/network/src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ pub struct NetworkConfiguration {
415415
pub node_key: NodeKeyConfig,
416416
/// List of notifications protocols that the node supports. Must also include a
417417
/// `ConsensusEngineId` for backwards-compatibility.
418-
pub notifications_protocols: Vec<(ConsensusEngineId, Cow<'static, [u8]>)>,
418+
pub notifications_protocols: Vec<(ConsensusEngineId, Cow<'static, str>)>,
419419
/// List of request-response protocols that the node supports.
420420
pub request_response_protocols: Vec<RequestResponseConfig>,
421421
/// Maximum allowed number of incoming connections.

client/network/src/gossip/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,14 @@ fn build_nodes_one_proto()
130130
let listen_addr = config::build_multiaddr![Memory(rand::random::<u64>())];
131131

132132
let (node1, events_stream1) = build_test_full_node(config::NetworkConfiguration {
133-
notifications_protocols: vec![(ENGINE_ID, From::from(&b"/foo"[..]))],
133+
notifications_protocols: vec![(ENGINE_ID, From::from("/foo"))],
134134
listen_addresses: vec![listen_addr.clone()],
135135
transport: config::TransportConfig::MemoryOnly,
136136
.. config::NetworkConfiguration::new_local()
137137
});
138138

139139
let (node2, events_stream2) = build_test_full_node(config::NetworkConfiguration {
140-
notifications_protocols: vec![(ENGINE_ID, From::from(&b"/foo"[..]))],
140+
notifications_protocols: vec![(ENGINE_ID, From::from("/foo"))],
141141
listen_addresses: vec![],
142142
reserved_nodes: vec![config::MultiaddrWithPeerId {
143143
multiaddr: listen_addr,

client/network/src/protocol.rs

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -245,13 +245,13 @@ pub struct Protocol<B: BlockT, H: ExHashT> {
245245
/// Handles opening the unique substream and sending and receiving raw messages.
246246
behaviour: GenericProto,
247247
/// For each legacy gossiping engine ID, the corresponding new protocol name.
248-
protocol_name_by_engine: HashMap<ConsensusEngineId, Cow<'static, [u8]>>,
248+
protocol_name_by_engine: HashMap<ConsensusEngineId, Cow<'static, str>>,
249249
/// For each protocol name, the legacy equivalent.
250-
legacy_equiv_by_name: HashMap<Cow<'static, [u8]>, Fallback>,
250+
legacy_equiv_by_name: HashMap<Cow<'static, str>, Fallback>,
251251
/// Name of the protocol used for transactions.
252-
transactions_protocol: Cow<'static, [u8]>,
252+
transactions_protocol: Cow<'static, str>,
253253
/// Name of the protocol used for block announces.
254-
block_announces_protocol: Cow<'static, [u8]>,
254+
block_announces_protocol: Cow<'static, str>,
255255
/// Prometheus metrics.
256256
metrics: Option<Metrics>,
257257
/// The `PeerId`'s of all boot nodes.
@@ -417,19 +417,21 @@ impl<B: BlockT, H: ExHashT> Protocol<B, H> {
417417

418418
let mut legacy_equiv_by_name = HashMap::new();
419419

420-
let transactions_protocol: Cow<'static, [u8]> = Cow::from({
421-
let mut proto = b"/".to_vec();
422-
proto.extend(protocol_id.as_ref().as_bytes());
423-
proto.extend(b"/transactions/1");
420+
let transactions_protocol: Cow<'static, str> = Cow::from({
421+
let mut proto = String::new();
422+
proto.push_str("/");
423+
proto.push_str(protocol_id.as_ref());
424+
proto.push_str("/transactions/1");
424425
proto
425426
});
426427
behaviour.register_notif_protocol(transactions_protocol.clone(), Vec::new());
427428
legacy_equiv_by_name.insert(transactions_protocol.clone(), Fallback::Transactions);
428429

429-
let block_announces_protocol: Cow<'static, [u8]> = Cow::from({
430-
let mut proto = b"/".to_vec();
431-
proto.extend(protocol_id.as_ref().as_bytes());
432-
proto.extend(b"/block-announces/1");
430+
let block_announces_protocol: Cow<'static, str> = Cow::from({
431+
let mut proto = String::new();
432+
proto.push_str("/");
433+
proto.push_str(protocol_id.as_ref());
434+
proto.push_str("/block-announces/1");
433435
proto
434436
});
435437
behaviour.register_notif_protocol(
@@ -679,7 +681,7 @@ impl<B: BlockT, H: ExHashT> Protocol<B, H> {
679681
fn send_message(
680682
&mut self,
681683
who: &PeerId,
682-
message: Option<(Cow<'static, [u8]>, Vec<u8>)>,
684+
message: Option<(Cow<'static, str>, Vec<u8>)>,
683685
legacy: Message<B>,
684686
) {
685687
send_message::<B>(
@@ -1076,7 +1078,7 @@ impl<B: BlockT, H: ExHashT> Protocol<B, H> {
10761078
pub fn register_notifications_protocol<'a>(
10771079
&'a mut self,
10781080
engine_id: ConsensusEngineId,
1079-
protocol_name: impl Into<Cow<'static, [u8]>>,
1081+
protocol_name: impl Into<Cow<'static, str>>,
10801082
handshake_message: Vec<u8>,
10811083
) -> impl Iterator<Item = (&'a PeerId, Roles, &'a NotificationsSink)> + 'a {
10821084
let protocol_name = protocol_name.into();
@@ -1607,7 +1609,7 @@ fn send_message<B: BlockT>(
16071609
behaviour: &mut GenericProto,
16081610
stats: &mut HashMap<&'static str, PacketStats>,
16091611
who: &PeerId,
1610-
message: Option<(Cow<'static, [u8]>, Vec<u8>)>,
1612+
message: Option<(Cow<'static, str>, Vec<u8>)>,
16111613
legacy_message: Message<B>,
16121614
) {
16131615
let encoded = legacy_message.encode();

client/network/src/protocol/generic_proto/behaviour.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ pub struct GenericProto {
120120
/// Notification protocols. Entries are only ever added and not removed.
121121
/// Contains, for each protocol, the protocol name and the message to send as part of the
122122
/// initial handshake.
123-
notif_protocols: Vec<(Cow<'static, [u8]>, Arc<RwLock<Vec<u8>>>)>,
123+
notif_protocols: Vec<(Cow<'static, str>, Arc<RwLock<Vec<u8>>>)>,
124124

125125
/// Receiver for instructions about who to connect to or disconnect from.
126126
peerset: sc_peerset::Peerset,
@@ -322,7 +322,7 @@ pub enum GenericProtoOut {
322322
/// Id of the peer the message came from.
323323
peer_id: PeerId,
324324
/// Engine corresponding to the message.
325-
protocol_name: Cow<'static, [u8]>,
325+
protocol_name: Cow<'static, str>,
326326
/// Message that has been received.
327327
message: BytesMut,
328328
},
@@ -360,7 +360,7 @@ impl GenericProto {
360360
/// will retain the protocols that were registered then, and not any new one.
361361
pub fn register_notif_protocol(
362362
&mut self,
363-
protocol_name: impl Into<Cow<'static, [u8]>>,
363+
protocol_name: impl Into<Cow<'static, str>>,
364364
handshake_msg: impl Into<Vec<u8>>
365365
) {
366366
self.notif_protocols.push((protocol_name.into(), Arc::new(RwLock::new(handshake_msg.into()))));
@@ -371,10 +371,10 @@ impl GenericProto {
371371
/// Has no effect if the protocol is unknown.
372372
pub fn set_notif_protocol_handshake(
373373
&mut self,
374-
protocol_name: &[u8],
374+
protocol_name: &str,
375375
handshake_message: impl Into<Vec<u8>>
376376
) {
377-
if let Some(protocol) = self.notif_protocols.iter_mut().find(|(name, _)| name == &protocol_name) {
377+
if let Some(protocol) = self.notif_protocols.iter_mut().find(|(name, _)| name == protocol_name) {
378378
*protocol.1.write() = handshake_message.into();
379379
}
380380
}
@@ -551,7 +551,7 @@ impl GenericProto {
551551
pub fn write_notification(
552552
&mut self,
553553
target: &PeerId,
554-
protocol_name: Cow<'static, [u8]>,
554+
protocol_name: Cow<'static, str>,
555555
message: impl Into<Vec<u8>>,
556556
encoded_fallback_message: Vec<u8>,
557557
) {
@@ -569,11 +569,11 @@ impl GenericProto {
569569
target: "sub-libp2p",
570570
"External API => Notification({:?}, {:?})",
571571
target,
572-
str::from_utf8(&protocol_name)
572+
protocol_name,
573573
);
574574
trace!(target: "sub-libp2p", "Handler({:?}) <= Packet", target);
575575
notifs_sink.send_sync_notification(
576-
&protocol_name,
576+
protocol_name,
577577
encoded_fallback_message,
578578
message
579579
);
@@ -1374,7 +1374,7 @@ impl NetworkBehaviour for GenericProto {
13741374
target: "sub-libp2p",
13751375
"Handler({:?}) => Notification({:?})",
13761376
source,
1377-
str::from_utf8(&protocol_name)
1377+
protocol_name,
13781378
);
13791379
trace!(target: "sub-libp2p", "External API <= Message({:?}, {:?})", protocol_name, source);
13801380
let event = GenericProtoOut::Notification {

0 commit comments

Comments
 (0)