Skip to content

Commit f57e889

Browse files
committed
deprecated pnet, enable tls, quic
change infinity timeout use udp and tcp at the same port check testnet and mainnet add valid peer into kad network
1 parent dcfbc0a commit f57e889

File tree

3 files changed

+46
-60
lines changed

3 files changed

+46
-60
lines changed

.env-template

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
ACCOUNT_SK=""
2-
PRIVITE_NET_ADDRESS="/ip4/0.0.0.0/tcp/8002"
2+
LIBP2P_TCP_LISTEN_ADDRESS="/ip4/0.0.0.0/tcp/8001"
3+
LIBP2P_QUIC_LISTEN_ADDRESS="/ip4/0.0.0.0/udp/8001/quic-v1"
34
NETWORK="testnet"

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "network_bootstrap"
3-
version = "0.1.0"
3+
version = "0.2.0-beta1"
44
edition = "2021"
55

66
[dependencies]
@@ -17,11 +17,12 @@ libp2p = { version = "0.55", features = [
1717
"json",
1818
"kad",
1919
"ping",
20-
"pnet",
20+
"tls",
2121
"request-response",
2222
"secp256k1",
2323
"serde",
2424
"tcp",
25+
"quic",
2526
"yamux",
2627
"noise",
2728
] }

src/mod_libp2p/network.rs

Lines changed: 41 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
use crate::mod_libp2p::behavior::{AgentBehavior, AgentEvent};
22
use alloy::primitives::{keccak256, Address};
3-
use base64::{engine::general_purpose::STANDARD, Engine};
43
use cached::{stores::SizedCache, Cached};
54
use futures_util::StreamExt;
65
use libp2p::{
7-
core::transport::upgrade::Version,
86
dns,
97
identify::{
108
Behaviour as IdentifyBehavior, Config as IdentifyConfig, Event as IdentifyEvent,
@@ -17,9 +15,8 @@ use libp2p::{
1715
},
1816
noise,
1917
ping::{self, Event as PingEvent},
20-
pnet::{PnetConfig, PreSharedKey},
2118
swarm::SwarmEvent,
22-
tcp, yamux, PeerId, StreamProtocol, Swarm, Transport,
19+
tls, yamux, PeerId, StreamProtocol, Swarm,
2320
};
2421
use once_cell::sync::Lazy;
2522
use serde_json::{json, Value};
@@ -39,7 +36,7 @@ pub const PRODUCTION_BOOSTNODE_PEER_ID_LIST: [&str; 3] = [
3936
];
4037

4138
pub const METRICS_PEER_ID: &str = "16Uiu2HAmNa64mzMD6Uq4EhUTdHKoZE7MLiEh7hCK3ACN5F5MgJoL";
42-
const PRIVATE_NETWORK_KEY: &str = "wiwlLGQ8g6zu0mcckkROzeeAU7xN+Adz40ELWSH3f1M=";
39+
pub const TEST_METRICS_PEER_ID: &str = "16Uiu2HAmUGCzsEwPGyuE9HcTzKGY4LUPFpLP3vKpT7buJUAdsKX5";
4340

4441
pub static QUERY_INDEXER_URL: Lazy<&str> = Lazy::new(|| {
4542
if std::env::var("NETWORK").as_deref() == Ok("testnet") {
@@ -50,14 +47,15 @@ pub static QUERY_INDEXER_URL: Lazy<&str> = Lazy::new(|| {
5047
});
5148

5249
static LAZY_BOOTNODE_METRICS_LIST: Lazy<Vec<&str>> = Lazy::new(|| {
53-
let mut list = if std::env::var("NETWORK").as_deref() == Ok("testnet") {
54-
TEST_BOOSTNODE_PEER_ID_LIST.to_vec()
50+
if std::env::var("NETWORK").as_deref() == Ok("testnet") {
51+
let mut temp_list = TEST_BOOSTNODE_PEER_ID_LIST.to_vec();
52+
temp_list.push(TEST_METRICS_PEER_ID);
53+
temp_list
5554
} else {
56-
PRODUCTION_BOOSTNODE_PEER_ID_LIST.to_vec()
57-
};
58-
59-
list.push(METRICS_PEER_ID);
60-
list
55+
let mut temp_list = PRODUCTION_BOOSTNODE_PEER_ID_LIST.to_vec();
56+
temp_list.push(METRICS_PEER_ID);
57+
temp_list
58+
}
6159
});
6260

6361
static GLOBAL_INDEXER_CACHE: Lazy<Mutex<SizedCache<PeerId, ()>>> =
@@ -110,6 +108,7 @@ impl EventLoop {
110108
indexer_cache.cache_remove(&peer_id);
111109
drop(indexer_cache);
112110
self.swarm.behaviour_mut().kad.remove_peer(&peer_id);
111+
_ = self.swarm.disconnect_peer_id(peer_id);
113112
}
114113
}
115114
SwarmEvent::Behaviour(AgentEvent::Identify(sub_event)) => {
@@ -148,15 +147,19 @@ impl EventLoop {
148147
} else if let Ok(controller_address) =
149148
Self::libp2p_publickey_to_eth_address(&public_key).await
150149
{
151-
if Self::is_controller_valid(&controller_address)
152-
.await
153-
.is_err()
154-
{
155-
error!(
156-
"peer_id {:?} is not valid, ethereum address: {} is not registered",
157-
peer_id, controller_address
158-
);
159-
self.swarm.close_connection(connection_id);
150+
match Self::is_controller_valid(&controller_address).await {
151+
Ok(_) => {
152+
for addr in listen_addrs {
153+
self.swarm.behaviour_mut().kad.add_address(&peer_id, addr);
154+
}
155+
}
156+
Err(_) => {
157+
error!(
158+
"peer_id {:?} is not valid, ethereum address: {} is not registered",
159+
peer_id, controller_address
160+
);
161+
self.swarm.close_connection(connection_id);
162+
}
160163
}
161164
} else {
162165
error!(
@@ -179,29 +182,15 @@ impl EventLoop {
179182
let secret_key = identity::secp256k1::SecretKey::try_from_bytes(private_key_bytes)?;
180183
let libp2p_keypair: Keypair = identity::secp256k1::Keypair::from(secret_key).into();
181184

182-
let psk = Self::get_psk();
183-
184-
// info!("using swarm key with fingerprint: {}", psk.fingerprint());
185-
186185
let mut swarm = libp2p::SwarmBuilder::with_existing_identity(libp2p_keypair.clone())
187186
.with_tokio()
188-
.with_other_transport(|key| {
189-
let noise_config = noise::Config::new(key).unwrap();
190-
let mut yamux_config = yamux::Config::default();
191-
yamux_config.set_max_num_streams(1024 * 1024);
192-
let base_transport =
193-
tcp::tokio::Transport::new(tcp::Config::default().nodelay(true));
194-
let base_transport = dns::tokio::Transport::system(base_transport)
195-
.expect("DNS")
196-
.boxed();
197-
let maybe_encrypted = base_transport
198-
.and_then(move |socket, _| PnetConfig::new(psk).handshake(socket));
199-
maybe_encrypted
200-
.upgrade(Version::V1Lazy)
201-
.authenticate(noise_config)
202-
.multiplex(yamux_config)
203-
})?
204-
.with_dns()?
187+
.with_tcp(
188+
Default::default(),
189+
(tls::Config::new, noise::Config::new),
190+
yamux::Config::default,
191+
)?
192+
.with_quic()
193+
.with_dns_config(dns::ResolverConfig::default(), dns::ResolverOpts::default())
205194
.with_behaviour(|key| {
206195
let local_peer_id = PeerId::from(key.clone().public());
207196

@@ -226,26 +215,21 @@ impl EventLoop {
226215

227216
AgentBehavior::new(kad, identify, ping)
228217
})?
229-
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(120)))
218+
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
230219
.build();
231220

232221
swarm.behaviour_mut().kad.set_mode(Some(kad::Mode::Server));
233222

234-
let private_net_address =
235-
std::env::var("PRIVITE_NET_ADDRESS").unwrap_or("/ip4/0.0.0.0/tcp/8000".to_string());
236-
let private_net_address = private_net_address.parse()?;
237-
swarm.listen_on(private_net_address)?;
238-
Ok(swarm)
239-
}
223+
let libp2p_tcp_listen_address = std::env::var("LIBP2P_TCP_LISTEN_ADDRESS")
224+
.unwrap_or("/ip4/0.0.0.0/tcp/8000".to_string());
225+
let libp2p_tcp_listen_address = libp2p_tcp_listen_address.parse()?;
226+
swarm.listen_on(libp2p_tcp_listen_address)?;
240227

241-
/// Read the pre shared key file from the given ipfs directory
242-
fn get_psk() -> PreSharedKey {
243-
let bytes = STANDARD.decode(PRIVATE_NETWORK_KEY).unwrap();
244-
let key: [u8; 32] = bytes
245-
.try_into()
246-
.map_err(|_| "Decoded key must be 32 bytes long")
247-
.unwrap();
248-
PreSharedKey::new(key)
228+
let libp2p_quic_listen_address = std::env::var("LIBP2P_QUIC_LISTEN_ADDRESS")
229+
.unwrap_or("/ip4/0.0.0.0/udp/8001/quic-v1".to_string());
230+
let libp2p_quic_listen_address = libp2p_quic_listen_address.parse()?;
231+
swarm.listen_on(libp2p_quic_listen_address)?;
232+
Ok(swarm)
249233
}
250234

251235
async fn libp2p_publickey_to_eth_address(

0 commit comments

Comments
 (0)