Re-delete examples (not included in previous commit erroneously)
This commit is contained in:
@@ -1,79 +0,0 @@
|
||||
# rust-libp2p-nym
|
||||
|
||||
This repo contains an example implementation of a libp2p transport using the Nym mixnet. It relies on the ChainSafe's fork of libp2p: https://github.com/ChainSafe/rust-libp2p
|
||||
|
||||
## Requirements
|
||||
|
||||
- Rust 1.68.2
|
||||
- `Protoc` protobuf compiler. On Debian/Ubuntu distributed via `apt` as `protobuf-compiler` & on Arch/Manjaro via AUR as `[python-protobuf-compiler](https://aur.archlinux.org/packages/python-protobuf-compiler)`.
|
||||
|
||||
## Usage
|
||||
|
||||
To instantiate a libp2p swarm using the transport:
|
||||
|
||||
```rust
|
||||
use libp2p::core::{muxing::StreamMuxerBox, transport::Transport};
|
||||
use libp2p::swarm::{keep_alive::Behaviour, SwarmBuilder};
|
||||
use libp2p::{identity, PeerId};
|
||||
use nym_sdk::mixnet::MixnetClient;
|
||||
use rust_libp2p_nym::transport::NymTransport;
|
||||
use rust_libp2p_nym::test_utils::create_nym_client;
|
||||
use std::error::Error;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let local_key = identity::Keypair::generate_ed25519();
|
||||
let local_peer_id = PeerId::from(local_key.public());
|
||||
info!("Local peer id: {local_peer_id:?}");
|
||||
|
||||
let nym_id = rand::random::<u64>().to_string();
|
||||
let nym_client = MixnetClient::connect_new().await.unwrap();
|
||||
let transport = NymTransport::new(nym_client, local_key.clone()).await?;
|
||||
let _swarm = SwarmBuilder::with_tokio_executor(
|
||||
transport
|
||||
.map(|a, _| (a.0, StreamMuxerBox::new(a.1)))
|
||||
.boxed(),
|
||||
Behaviour::default(),
|
||||
local_peer_id,
|
||||
)
|
||||
.build();
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Ping example
|
||||
|
||||
To run the libp2p ping example, run the following in one terminal:
|
||||
```bash
|
||||
cargo run --example libp2p_ping
|
||||
# Local peer id: PeerId("12D3KooWLukBu6q2FerWPFhFFhiYaJkhn2sBmceh9UCaXe6hJf5D")
|
||||
# Listening on "/nym/FhtkzizQg2JbZ19kGkRKXdjV2QnFbT5ww88ZAKaD4nkF.7Remi4UVYzn1yL3qYtEcQBGh6tzTYxMdYB4uqyHVc5Z4@62F81C9GrHDRja9WCqozemRFSzFPMecY85MbGwn6efve"
|
||||
```
|
||||
|
||||
In another terminal, run ping again, passing the Nym multiaddress printed previously:
|
||||
```bash
|
||||
cargo run --example libp2p_ping -- /nym/FhtkzizQg2JbZ19kGkRKXdjV2QnFbT5ww88ZAKaD4nkF.7Remi4UVYzn1yL3qYtEcQBGh6tzTYxMdYB4uqyHVc5Z4@62F81C9GrHDRja9WCqozemRFSzFPMecY85MbGwn6efve
|
||||
# Local peer id: PeerId("12D3KooWNsuRwG6DHnFJCDR8B3zdvja6xLcfnbtKCsQWJ8eppyWC")
|
||||
# Dialed /nym/FhtkzizQg2JbZ19kGkRKXdjV2QnFbT5ww88ZAKaD4nkF.7Remi4UVYzn1yL3qYtEcQBGh6tzTYxMdYB4uqyHVc5Z4@62F81C9GrHDRja9WCqozemRFSzFPMecY85MbGwn6efve
|
||||
# Listening on "/nym/2oiRW5C9ivyF3Bo3Gpm4H9EqSKH7A6GpcrRRwVSDVUQ9.EajgCnhzimsP6KskUwKcEj8VFCmHR78s2J6FHWcZ4etR@Fo4f4SQLdoyoGkFae5TpVhRVoXCF8UiypLVGtGjujVPf"
|
||||
```
|
||||
|
||||
You should see that the nodes connected and pinged each other:
|
||||
```bash
|
||||
# Mar 30 22:56:36.400 INFO ping: BehaviourEvent: Event { peer: PeerId("12D3KooWGf2oYd6U2nrLzfDrN9zxsjSQjPsMh2oDJPUQ9hiHMNtf"), result: Ok(Ping { rtt: 1.06836675s }) }
|
||||
```
|
||||
```bash
|
||||
# Mar 30 22:56:35.595 INFO ping: BehaviourEvent: Event { peer: PeerId("12D3KooWMd5ak31DXuZq7x1JuFSR6toA5RDQrPaHrfXEhy7vqqpC"), result: Ok(Pong) }
|
||||
```
|
||||
|
||||
In order to run the ping example with vanilla libp2p, which uses tcp, pass the
|
||||
`--features libp2p-vanilla` flag to the example and follow the instructions on the
|
||||
rust-libp2p project as usual.
|
||||
|
||||
```bash
|
||||
RUST_LOG=ping=debug cargo run --example ping --features libp2p-vanilla
|
||||
```
|
||||
|
||||
```bash
|
||||
RUST_LOG=ping=debug cargo run --example ping --features libp2p-vanilla -- "/ip4/127.0.0.1/tcp/$PORT"
|
||||
```
|
||||
@@ -1,143 +0,0 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the "Software"),
|
||||
// to deal in the Software without restriction, including without limitation
|
||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
// and/or sell copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
//! Ping example
|
||||
//!
|
||||
//! See ../src/tutorial.rs for a step-by-step guide building the example below.
|
||||
//!
|
||||
//! In the first terminal window, run:
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --example ping --features=full
|
||||
//! ```
|
||||
//!
|
||||
//! It will print the PeerId and the listening addresses, e.g. `Listening on
|
||||
//! "/ip4/0.0.0.0/tcp/24915"`
|
||||
//!
|
||||
//! In the second terminal window, start a new instance of the example with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --example ping --features=full -- /ip4/127.0.0.1/tcp/24915
|
||||
//! ```
|
||||
//!
|
||||
//! The two nodes establish a connection, negotiate the ping protocol
|
||||
//! and begin pinging each other.
|
||||
|
||||
// use libp2p::futures::StreamExt;
|
||||
// use libp2p::ping::Success;
|
||||
// use libp2p::swarm::{keep_alive, NetworkBehaviour, SwarmEvent};
|
||||
// use libp2p::{identity, ping, Multiaddr, PeerId};
|
||||
// use log::{debug, info, LevelFilter};
|
||||
use std::error::Error;
|
||||
// use std::time::Duration;
|
||||
//
|
||||
// #[path = "../libp2p_shared/lib.rs"]
|
||||
// mod rust_libp2p_nym;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
unimplemented!("temporarily disabled")
|
||||
//
|
||||
// pretty_env_logger::formatted_timed_builder()
|
||||
// .filter_level(LevelFilter::Warn)
|
||||
// .filter(Some("libp2p_ping"), LevelFilter::Debug)
|
||||
// .init();
|
||||
//
|
||||
// let local_key = identity::Keypair::generate_ed25519();
|
||||
// let local_peer_id = PeerId::from(local_key.public());
|
||||
// info!("Local peer id: {local_peer_id:?}");
|
||||
//
|
||||
// #[cfg(not(feature = "libp2p-vanilla"))]
|
||||
// let mut swarm = {
|
||||
// debug!("Running `ping` example using NymTransport");
|
||||
// use libp2p::core::{muxing::StreamMuxerBox, transport::Transport};
|
||||
// use libp2p::swarm::SwarmBuilder;
|
||||
// use rust_libp2p_nym::transport::NymTransport;
|
||||
//
|
||||
// let client = nym_sdk::mixnet::MixnetClient::connect_new().await.unwrap();
|
||||
//
|
||||
// let transport = NymTransport::new(client, local_key.clone()).await?;
|
||||
// SwarmBuilder::with_tokio_executor(
|
||||
// transport
|
||||
// .map(|a, _| (a.0, StreamMuxerBox::new(a.1)))
|
||||
// .boxed(),
|
||||
// Behaviour::default(),
|
||||
// local_peer_id,
|
||||
// )
|
||||
// .build()
|
||||
// };
|
||||
//
|
||||
// #[cfg(feature = "libp2p-vanilla")]
|
||||
// let mut swarm = {
|
||||
// debug!("Running `ping` example using the vanilla libp2p tokio_development_transport");
|
||||
// let transport = libp2p::tokio_development_transport(local_key)?;
|
||||
// let mut swarm =
|
||||
// libp2p::Swarm::with_tokio_executor(transport, Behaviour::default(), local_peer_id);
|
||||
// swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
|
||||
// swarm
|
||||
// };
|
||||
//
|
||||
// // Dial the peer identified by the multi-address given as the second
|
||||
// // command-line argument, if any.
|
||||
// if let Some(addr) = std::env::args().nth(1) {
|
||||
// let remote: Multiaddr = addr.parse()?;
|
||||
// swarm.dial(remote)?;
|
||||
// info!("Dialed {addr}")
|
||||
// }
|
||||
//
|
||||
// let mut total_ping_rtt: Duration = Duration::from_micros(0);
|
||||
// let mut counter: u128 = 0;
|
||||
// loop {
|
||||
// match swarm.select_next_some().await {
|
||||
// SwarmEvent::NewListenAddr { address, .. } => info!("Listening on {address:?}"),
|
||||
// SwarmEvent::Behaviour(event) => {
|
||||
// // Get the round-trip duration for the pings.
|
||||
// // This value is already captured in the BehaviourEvent::Ping's `Success::Ping`
|
||||
// // field.
|
||||
// debug!("{event:?}");
|
||||
// if let BehaviourEvent::Ping(ping_event) = event {
|
||||
// let result: Success = ping_event.result?;
|
||||
// match result {
|
||||
// Success::Ping { rtt } => {
|
||||
// counter += 1;
|
||||
// total_ping_rtt += rtt;
|
||||
// let average_ping_rtt = Duration::from_micros(
|
||||
// (total_ping_rtt.as_micros() / counter).try_into().unwrap(),
|
||||
// );
|
||||
// info!("Ping RTT: {rtt:?} AVERAGE RTT: ({counter} pings): {average_ping_rtt:?}");
|
||||
// }
|
||||
// Success::Pong => info!("Pong Event"),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// _ => {}
|
||||
// }
|
||||
// }
|
||||
}
|
||||
//
|
||||
// /// Our network behaviour.
|
||||
// ///
|
||||
// /// For illustrative purposes, this includes the [`KeepAlive`](behaviour::KeepAlive) behaviour so a continuous sequence of
|
||||
// /// pings can be observed.
|
||||
// #[derive(NetworkBehaviour, Default)]
|
||||
// struct Behaviour {
|
||||
// keep_alive: keep_alive::Behaviour,
|
||||
// ping: ping::Behaviour,
|
||||
// }
|
||||
@@ -1,183 +0,0 @@
|
||||
// Copyright 2024-2026 - Nym Technologies SA <contact@nymtech.net>
|
||||
|
||||
//! Multiple DNS lookups + NTP time sync through the Nym mixnet.
|
||||
//!
|
||||
//! Resolves several hostnames and syncs the clock via NTP — all over
|
||||
//! mixnet UDP. Demonstrates timeout handling, socket reuse, and raw
|
||||
//! protocol construction over smolmix's `UdpSocket`.
|
||||
//!
|
||||
//! ```text
|
||||
//! DNS / NTP (application-layer UDP protocols)
|
||||
//! └─ smolmix::UdpSocket (UDP over mixnet)
|
||||
//! └─ smoltcp (userspace IP stack)
|
||||
//! └─ Nym mixnet → IPR exit gateway → internet
|
||||
//! ```
|
||||
//!
|
||||
//! ## What this demonstrates
|
||||
//!
|
||||
//! - Multiple DNS queries over a single `UdpSocket`
|
||||
//! - Timeout handling with `tokio::time::timeout` (essential for UDP)
|
||||
//! - NTP time sync via a raw 48-byte UDP packet
|
||||
//! - Converting NTP epoch (1900) to Unix epoch (1970)
|
||||
//!
|
||||
//! Compare with `udp.rs` which does a single DNS lookup with clearnet comparison.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p smolmix --example udp_multi
|
||||
//! cargo run -p smolmix --example udp_multi -- --ipr <IPR_ADDRESS>
|
||||
//! ```
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use hickory_proto::op::{Message, Query};
|
||||
use hickory_proto::rr::{Name, RData, RecordType};
|
||||
use smolmix::Tunnel;
|
||||
use tracing::info;
|
||||
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
/// Hostnames to resolve via mixnet DNS.
|
||||
const DNS_TARGETS: &[&str] = &["example.com", "cloudflare.com", "nymtech.net"];
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), BoxError> {
|
||||
nym_bin_common::logging::setup_tracing_logger();
|
||||
rustls::crypto::ring::default_provider()
|
||||
.install_default()
|
||||
.expect("Failed to install rustls crypto provider");
|
||||
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let ipr_addr = args
|
||||
.iter()
|
||||
.position(|a| a == "--ipr")
|
||||
.and_then(|i| args.get(i + 1));
|
||||
|
||||
// Create the tunnel
|
||||
let mut builder = Tunnel::builder();
|
||||
if let Some(addr) = ipr_addr {
|
||||
builder = builder.ipr_address(addr.parse().expect("invalid IPR address"));
|
||||
}
|
||||
let tunnel = builder.build().await?;
|
||||
info!(
|
||||
"Tunnel ready — allocated IP: {}",
|
||||
tunnel.allocated_ips().ipv4
|
||||
);
|
||||
|
||||
// Multiple DNS lookups over one UdpSocket
|
||||
// Each query goes to Cloudflare DNS (1.1.1.1:53) through the mixnet.
|
||||
// The DNS server sees the IPR exit gateway's IP, not yours.
|
||||
info!("Private DNS Lookups (via mixnet UDP)");
|
||||
|
||||
let udp = tunnel.udp_socket().await?;
|
||||
|
||||
for host in DNS_TARGETS {
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
let mut query = Message::new();
|
||||
query.set_recursion_desired(true);
|
||||
query.add_query(Query::query(Name::from_ascii(host)?, RecordType::A));
|
||||
let query_bytes = query.to_vec()?;
|
||||
|
||||
udp.send_to(&query_bytes, "1.1.1.1:53".parse()?).await?;
|
||||
|
||||
let mut buf = vec![0u8; 1500];
|
||||
let result =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), udp.recv_from(&mut buf)).await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((n, _))) => {
|
||||
let rtt = start.elapsed();
|
||||
let response = Message::from_vec(&buf[..n])?;
|
||||
let ips: Vec<_> = response
|
||||
.answers()
|
||||
.iter()
|
||||
.filter_map(|r| match r.data() {
|
||||
RData::A(a) => Some(a.0.to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
info!("{host:<16} → {} (rtt: {rtt:.1?})", ips.join(", "));
|
||||
}
|
||||
Ok(Err(e)) => info!("{host:<16} → ERROR: {e}"),
|
||||
Err(_) => info!("{host:<16} → TIMEOUT"),
|
||||
}
|
||||
}
|
||||
|
||||
// NTP time sync via mixnet UDP
|
||||
// NTP uses a simple 48-byte request/response over UDP port 123.
|
||||
// We first resolve pool.ntp.org via the mixnet, then send the NTP request.
|
||||
info!("NTP Time Sync (via mixnet UDP)");
|
||||
|
||||
let ntp_ip = resolve_dns(&tunnel, "pool.ntp.org").await?;
|
||||
info!("Resolved pool.ntp.org → {ntp_ip}");
|
||||
|
||||
// NTP request: 48 bytes, LI=0 Version=4 Mode=3 (client)
|
||||
let mut ntp_req = [0u8; 48];
|
||||
ntp_req[0] = 0x23;
|
||||
|
||||
let ntp_udp = tunnel.udp_socket().await?;
|
||||
let start = std::time::Instant::now();
|
||||
let ntp_dest: std::net::SocketAddr = (ntp_ip, 123).into();
|
||||
ntp_udp.send_to(&ntp_req, ntp_dest).await?;
|
||||
|
||||
let mut buf = [0u8; 48];
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(30),
|
||||
ntp_udp.recv_from(&mut buf),
|
||||
)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Ok((n, _))) if n >= 48 => {
|
||||
let rtt = start.elapsed();
|
||||
|
||||
// Transmit timestamp at bytes 40..48 (seconds since 1900-01-01)
|
||||
let secs = u32::from_be_bytes([buf[40], buf[41], buf[42], buf[43]]);
|
||||
let frac = u32::from_be_bytes([buf[44], buf[45], buf[46], buf[47]]);
|
||||
|
||||
// NTP epoch (1900) → Unix epoch (1970)
|
||||
// Valid for Era 0 (until 2036-02-07); Era 1 wraps secs to 0.
|
||||
const NTP_TO_UNIX: u64 = 2_208_988_800;
|
||||
let unix_secs = secs as u64 - NTP_TO_UNIX;
|
||||
let millis = (frac as u64 * 1000) >> 32;
|
||||
|
||||
let dt =
|
||||
chrono::DateTime::from_timestamp(unix_secs as i64, (millis * 1_000_000) as u32)
|
||||
.expect("valid timestamp");
|
||||
info!("NTP response in {rtt:.1?}");
|
||||
info!("Unix timestamp: {unix_secs}.{millis:03}");
|
||||
info!("UTC: {}", dt.format("%Y-%m-%d %H:%M:%S%.3f UTC"));
|
||||
}
|
||||
Ok(Ok((n, _))) => info!("Short response: {n} bytes (expected 48)"),
|
||||
Ok(Err(e)) => info!("ERROR: {e}"),
|
||||
Err(_) => info!("TIMEOUT (30s)"),
|
||||
}
|
||||
|
||||
tunnel.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve a hostname to an IPv4 address via mixnet UDP DNS.
|
||||
async fn resolve_dns(tunnel: &Tunnel, host: &str) -> Result<Ipv4Addr, BoxError> {
|
||||
let mut query = Message::new();
|
||||
query.set_recursion_desired(true);
|
||||
query.add_query(Query::query(Name::from_ascii(host)?, RecordType::A));
|
||||
let query_bytes = query.to_vec()?;
|
||||
|
||||
let udp = tunnel.udp_socket().await?;
|
||||
udp.send_to(&query_bytes, "1.1.1.1:53".parse()?).await?;
|
||||
|
||||
let mut buf = vec![0u8; 1500];
|
||||
let (n, _) = udp.recv_from(&mut buf).await?;
|
||||
|
||||
let response = Message::from_vec(&buf[..n])?;
|
||||
let ip = response
|
||||
.answers()
|
||||
.iter()
|
||||
.find_map(|r| match r.data() {
|
||||
RData::A(a) => Some(a.0),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or("no A record in DNS response")?;
|
||||
Ok(ip)
|
||||
}
|
||||
Reference in New Issue
Block a user