Skip to content

Commit d203401

Browse files
Custom protocol id (#163)
* Revert "Custom protocol (#158)" This reverts commit 8f2716e. * trait threading via functions * clippy * make it easier to use the default protocol id * fix tests
1 parent 07881d8 commit d203401

File tree

19 files changed

+168
-200
lines changed

19 files changed

+168
-200
lines changed

Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ tokio-util = { version = "0.6.9", features = ["time"] }
1919
libp2p-core = { version = "0.36.0", optional = true }
2020
zeroize = { version = "1.4.3", features = ["zeroize_derive"] }
2121
futures = "0.3.19"
22-
uint = { version = "0.9.5", default-features = false }
22+
uint = { version = "0.9.1", default-features = false }
2323
rlp = "0.5.1"
2424
# This version must be kept up to date do it uses the same dependencies as ENR
2525
hkdf = "0.12.3"
@@ -39,7 +39,6 @@ lru = "0.7.1"
3939
hashlink = "0.7.0"
4040
delay_map = "0.1.1"
4141
more-asserts = "0.2.2"
42-
once_cell = "1.17.0"
4342

4443
[dev-dependencies]
4544
rand_07 = { package = "rand", version = "0.7" }

examples/custom_executor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ fn main() {
3939
let config = Discv5ConfigBuilder::new().build();
4040

4141
// construct the discv5 server
42-
let mut discv5 = Discv5::new(enr, enr_key, config).unwrap();
42+
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
4343

4444
// if we know of another peer's ENR, add it known peers
4545
if let Some(base64_enr) = std::env::args().nth(1) {

examples/find_nodes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ async fn main() {
135135
let socket_addr = SocketAddr::new(bind_addr, port);
136136

137137
// construct the discv5 server
138-
let mut discv5 = Discv5::new(enr, enr_key, config).unwrap();
138+
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
139139

140140
// if we know of another peer's ENR, add it known peers
141141
for enr in args.remote_peer {

examples/simple_server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ async fn main() {
7272
let config = Discv5Config::default();
7373

7474
// construct the discv5 server
75-
let mut discv5 = Discv5::new(enr, enr_key, config).unwrap();
75+
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
7676

7777
// if we know of another peer's ENR, add it known peers
7878
if let Some(base64_enr) = std::env::args().nth(3) {

src/config.rs

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
11
use crate::{
2-
ipmode::IpMode,
3-
kbucket::MAX_NODES_PER_BUCKET,
4-
packet::{PROTOCOL_ID_LENGTH, PROTOCOL_VERSION_LENGTH},
5-
Enr, Executor, PermitBanList, RateLimiter, RateLimiterBuilder,
2+
ipmode::IpMode, kbucket::MAX_NODES_PER_BUCKET, Enr, Executor, PermitBanList, RateLimiter,
3+
RateLimiterBuilder,
64
};
75
///! A set of configuration parameters to tune the discovery protocol.
86
use std::time::Duration;
9-
use std::{convert::TryInto, num::NonZeroU16};
10-
11-
/// Protocol ID sent with each message.
12-
pub(crate) const DEFAULT_PROTOCOL_ID: [u8; PROTOCOL_ID_LENGTH] = *b"discv5";
13-
/// The version sent with each handshake.
14-
pub(crate) const DEFAULT_PROTOCOL_VERSION: [u8; PROTOCOL_VERSION_LENGTH] = 0x0001_u16.to_be_bytes();
157

168
/// Configuration parameters that define the performance of the discovery network.
179
#[derive(Clone)]
@@ -107,9 +99,6 @@ pub struct Discv5Config {
10799
/// A custom executor which can spawn the discv5 tasks. This must be a tokio runtime, with
108100
/// timing support. By default, the executor that created the discv5 struct will be used.
109101
pub executor: Option<Box<dyn Executor + Send + Sync>>,
110-
111-
/// The Discv5 protocol id and version, in bytes.
112-
pub protocol: ([u8; PROTOCOL_ID_LENGTH], [u8; PROTOCOL_VERSION_LENGTH]),
113102
}
114103

115104
impl Default for Discv5Config {
@@ -149,7 +138,6 @@ impl Default for Discv5Config {
149138
ban_duration: Some(Duration::from_secs(3600)), // 1 hour
150139
ip_mode: IpMode::default(),
151140
executor: None,
152-
protocol: (DEFAULT_PROTOCOL_ID, DEFAULT_PROTOCOL_VERSION),
153141
}
154142
}
155143
}
@@ -326,30 +314,6 @@ impl Discv5ConfigBuilder {
326314
self
327315
}
328316

329-
/// Set the discv5 wire protocol id.
330-
pub fn protocol_id(&mut self, protocol_id: &'static str) -> &mut Self {
331-
let protocol_id: [u8; PROTOCOL_ID_LENGTH] =
332-
protocol_id.as_bytes().try_into().unwrap_or_else(|_| {
333-
panic!("The protocol id must be {} bytes long", PROTOCOL_ID_LENGTH)
334-
});
335-
336-
self.config.protocol = (protocol_id, DEFAULT_PROTOCOL_VERSION);
337-
self
338-
}
339-
340-
/// Set the discv5 wire protocol id and the version.
341-
pub fn protocol(
342-
&mut self,
343-
protocol_id: &'static str,
344-
protocol_version: NonZeroU16,
345-
) -> &mut Self {
346-
self.protocol_id(protocol_id);
347-
let protocol_version = protocol_version.get().to_be_bytes();
348-
349-
self.config.protocol.1 = protocol_version;
350-
self
351-
}
352-
353317
pub fn build(&mut self) -> Discv5Config {
354318
// If an executor is not provided, assume a current tokio runtime is running.
355319
if self.config.executor.is_none() {
@@ -383,7 +347,6 @@ impl std::fmt::Debug for Discv5Config {
383347
.field("incoming_bucket_limit", &self.incoming_bucket_limit)
384348
.field("ping_interval", &self.ping_interval)
385349
.field("ban_duration", &self.ban_duration)
386-
.field("protocol", &self.protocol)
387350
.finish()
388351
}
389352
}

src/discv5.rs

Lines changed: 13 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@ use crate::{
1919
NodeStatus, UpdateResult,
2020
},
2121
node_info::NodeContact,
22+
packet::ProtocolIdentity,
2223
service::{QueryKind, Service, ServiceRequest, TalkRequest},
23-
Discv5Config, Enr,
24+
DefaultProtocolId, Discv5Config, Enr,
2425
};
2526
use enr::{CombinedKey, EnrError, EnrKey, NodeId};
2627
use parking_lot::RwLock;
2728
use std::{
2829
future::Future,
30+
marker::PhantomData,
2931
net::SocketAddr,
3032
sync::Arc,
3133
time::{Duration, Instant},
@@ -71,7 +73,10 @@ pub enum Discv5Event {
7173

7274
/// The main Discv5 Service struct. This provides the user-level API for performing queries and
7375
/// interacting with the underlying service.
74-
pub struct Discv5 {
76+
pub struct Discv5<P = DefaultProtocolId>
77+
where
78+
P: ProtocolIdentity,
79+
{
7580
config: Discv5Config,
7681
/// The channel to make requests from the main service.
7782
service_channel: Option<mpsc::Sender<ServiceRequest>>,
@@ -83,47 +88,16 @@ pub struct Discv5 {
8388
local_enr: Arc<RwLock<Enr>>,
8489
/// The key associated with the local ENR, required for updating the local ENR.
8590
enr_key: Arc<RwLock<CombinedKey>>,
91+
/// Phantom for the protocol id.
92+
_phantom: PhantomData<P>,
8693
}
8794

88-
impl Discv5 {
95+
impl<P: ProtocolIdentity> Discv5<P> {
8996
pub fn new(
9097
local_enr: Enr,
9198
enr_key: CombinedKey,
9299
mut config: Discv5Config,
93100
) -> Result<Self, &'static str> {
94-
// tests use the default value, so we ignore initializing the protocol.
95-
#[cfg(not(test))]
96-
{
97-
use crate::{
98-
config::{DEFAULT_PROTOCOL_ID, DEFAULT_PROTOCOL_VERSION},
99-
packet::{PROTOCOL_ID, VERSION},
100-
};
101-
// initialize the protocol id and version
102-
let (protocol_id_bytes, protocol_version_bytes) = config.protocol;
103-
PROTOCOL_ID
104-
.set(protocol_id_bytes)
105-
.map_err(|_old_val| "PROTOCOL_ID has already been initialized")?;
106-
VERSION
107-
.set(protocol_version_bytes)
108-
.map_err(|_old_val| "protocol's VERSION has already been initialized")?;
109-
110-
if protocol_id_bytes != DEFAULT_PROTOCOL_ID
111-
|| protocol_version_bytes != DEFAULT_PROTOCOL_VERSION
112-
{
113-
let protocol_version = u16::from_be_bytes(protocol_version_bytes);
114-
match std::str::from_utf8(&protocol_id_bytes) {
115-
Ok(pretty_protocol_id) => tracing::info!(
116-
"Discv5 using custom protocol id and version. Id: {} Version: {}",
117-
pretty_protocol_id, protocol_version
118-
),
119-
Err(_) => tracing::info!(
120-
"Discv5 using custom protocol id and version, with non utf8 protocol id. Id: {:?} Version: {}",
121-
protocol_id_bytes, protocol_version
122-
),
123-
}
124-
}
125-
}
126-
127101
// ensure the keypair matches the one that signed the enr.
128102
if local_enr.public_key() != enr_key.public() {
129103
return Err("Provided keypair does not match the provided ENR");
@@ -166,6 +140,7 @@ impl Discv5 {
166140
kbuckets,
167141
local_enr,
168142
enr_key,
143+
_phantom: Default::default(),
169144
})
170145
}
171146

@@ -177,7 +152,7 @@ impl Discv5 {
177152
}
178153

179154
// create the main service
180-
let (service_exit, service_channel) = Service::spawn(
155+
let (service_exit, service_channel) = Service::spawn::<P>(
181156
self.local_enr.clone(),
182157
self.enr_key.clone(),
183158
self.kbuckets.clone(),
@@ -638,7 +613,7 @@ impl Discv5 {
638613
}
639614
}
640615

641-
impl Drop for Discv5 {
616+
impl<P: ProtocolIdentity> Drop for Discv5<P> {
642617
fn drop(&mut self) {
643618
self.shutdown();
644619
}

src/discv5/test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ async fn test_bucket_limits() {
615615
.collect();
616616

617617
let config = Discv5ConfigBuilder::new().ip_limit().build();
618-
let discv5 = Discv5::new(enr, enr_key, config).unwrap();
618+
let discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
619619
for enr in enrs {
620620
let _ = discv5.add_enr(enr.clone()); // we expect some of these to fail based on the filter.
621621
}

src/handler/crypto/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,8 @@ pub(crate) fn encrypt_message(
223223

224224
#[cfg(test)]
225225
mod tests {
226+
use crate::packet::DefaultProtocolId;
227+
226228
use super::*;
227229
use enr::{CombinedKey, EnrBuilder, EnrKey};
228230
use std::convert::TryInto;
@@ -394,7 +396,8 @@ mod tests {
394396
let dst_id: NodeId = node_key_2().public().into();
395397
let encoded_ref_packet = hex::decode("00000000000000000000000000000000088b3d4342774649325f313964a39e55ea96c005ad52be8c7560413a7008f16c9e6d2f43bbea8814a546b7409ce783d34c4f53245d08dab84102ed931f66d1492acb308fa1c6715b9d139b81acbdcc").unwrap();
396398
let (_packet, auth_data) =
397-
crate::packet::Packet::decode(&dst_id, &encoded_ref_packet).unwrap();
399+
crate::packet::Packet::decode::<DefaultProtocolId>(&dst_id, &encoded_ref_packet)
400+
.unwrap();
398401

399402
let ciphertext = hex::decode("b84102ed931f66d1492acb308fa1c6715b9d139b81acbdcc").unwrap();
400403
let read_key = hex::decode("00000000000000000000000000000000").unwrap();

0 commit comments

Comments
 (0)