|
| 1 | +use clap::Parser; |
| 2 | +use libp2p::pnet::PreSharedKey; |
| 3 | +use rand::Rng; |
| 4 | +use rust_ipfs::Ipfs; |
| 5 | +use rust_ipfs::Keypair; |
| 6 | +use rust_ipfs::UninitializedIpfs; |
| 7 | +use std::str::FromStr; |
| 8 | + |
| 9 | +#[derive(Debug, Parser)] |
| 10 | +#[clap(name = "ipfs-pnet")] |
| 11 | +struct Opt { |
| 12 | + #[clap(required = false)] |
| 13 | + psk: Option<String>, |
| 14 | +} |
| 15 | +fn generate_psk() -> PreSharedKey { |
| 16 | + let mut key_bytes = [0u8; 32]; |
| 17 | + rand::thread_rng().fill(&mut key_bytes); |
| 18 | + PreSharedKey::new(key_bytes) |
| 19 | +} |
| 20 | + |
| 21 | +/// you can provide a PSK as an argument |
| 22 | +/// example: cargo run --example 8ab6e6aeb73353791b88c3c73e3d9a5111273e6d89edcbfb8be783f1e595617b |
| 23 | +/// |
| 24 | +/// or create a random one without providing any argument |
| 25 | +/// example: cargo run --example ipfs-pnet |
| 26 | +#[tokio::main] |
| 27 | +async fn main() -> anyhow::Result<()> { |
| 28 | + tracing_subscriber::fmt::init(); |
| 29 | + |
| 30 | + let keypair = Keypair::generate_ed25519(); |
| 31 | + let local_peer_id = keypair.public().to_peer_id(); |
| 32 | + |
| 33 | + let opt = Opt::parse(); |
| 34 | + let psk = { |
| 35 | + match opt.psk { |
| 36 | + Some(psk) => { |
| 37 | + let formatted_psk = format!("/key/swarm/psk/1.0.0/\n/base16/\n{}", psk); |
| 38 | + match PreSharedKey::from_str(&formatted_psk) { |
| 39 | + Ok(psk) => psk, |
| 40 | + Err(_) => { |
| 41 | + println!("Invalid PSK , generating a random PSK"); |
| 42 | + generate_psk() |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + None => generate_psk(), |
| 47 | + } |
| 48 | + }; |
| 49 | + println!("PSK: {:?}", psk); |
| 50 | + |
| 51 | + // Initialize the repo and start a daemon |
| 52 | + let ipfs: Ipfs = UninitializedIpfs::new() |
| 53 | + .with_default() |
| 54 | + .set_keypair(&keypair) |
| 55 | + .add_listening_addr("/ip4/0.0.0.0/tcp/0".parse()?) |
| 56 | + .with_mdns() |
| 57 | + .with_pnet(psk) |
| 58 | + .with_custom_behaviour(ext_behaviour::Behaviour::new(local_peer_id)) |
| 59 | + .start() |
| 60 | + .await?; |
| 61 | + |
| 62 | + ipfs.default_bootstrap().await?; |
| 63 | + ipfs.bootstrap().await?; |
| 64 | + |
| 65 | + // Used to wait until the process is terminated instead of creating a loop |
| 66 | + tokio::signal::ctrl_c().await?; |
| 67 | + ipfs.exit_daemon().await; |
| 68 | + Ok(()) |
| 69 | +} |
| 70 | + |
| 71 | +mod ext_behaviour { |
| 72 | + use libp2p::swarm::derive_prelude::PortUse; |
| 73 | + use libp2p::{ |
| 74 | + core::Endpoint, |
| 75 | + swarm::{ |
| 76 | + ConnectionDenied, ConnectionId, FromSwarm, NewListenAddr, THandler, THandlerInEvent, |
| 77 | + THandlerOutEvent, ToSwarm, |
| 78 | + }, |
| 79 | + Multiaddr, PeerId, |
| 80 | + }; |
| 81 | + use rust_ipfs::NetworkBehaviour; |
| 82 | + use std::convert::Infallible; |
| 83 | + use std::{ |
| 84 | + collections::HashSet, |
| 85 | + task::{Context, Poll}, |
| 86 | + }; |
| 87 | + |
| 88 | + #[derive(Default, Debug)] |
| 89 | + pub struct Behaviour { |
| 90 | + addrs: HashSet<Multiaddr>, |
| 91 | + } |
| 92 | + |
| 93 | + impl Behaviour { |
| 94 | + pub fn new(local_peer_id: PeerId) -> Self { |
| 95 | + println!("PeerID: {}", local_peer_id); |
| 96 | + Self { |
| 97 | + addrs: Default::default(), |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + impl NetworkBehaviour for Behaviour { |
| 103 | + type ConnectionHandler = rust_ipfs::libp2p::swarm::dummy::ConnectionHandler; |
| 104 | + type ToSwarm = Infallible; |
| 105 | + |
| 106 | + fn handle_pending_inbound_connection( |
| 107 | + &mut self, |
| 108 | + _: ConnectionId, |
| 109 | + _: &Multiaddr, |
| 110 | + _: &Multiaddr, |
| 111 | + ) -> Result<(), ConnectionDenied> { |
| 112 | + Ok(()) |
| 113 | + } |
| 114 | + |
| 115 | + fn handle_pending_outbound_connection( |
| 116 | + &mut self, |
| 117 | + _: ConnectionId, |
| 118 | + _: Option<PeerId>, |
| 119 | + _: &[Multiaddr], |
| 120 | + _: Endpoint, |
| 121 | + ) -> Result<Vec<Multiaddr>, ConnectionDenied> { |
| 122 | + Ok(vec![]) |
| 123 | + } |
| 124 | + |
| 125 | + fn handle_established_inbound_connection( |
| 126 | + &mut self, |
| 127 | + _: ConnectionId, |
| 128 | + _: PeerId, |
| 129 | + _: &Multiaddr, |
| 130 | + _: &Multiaddr, |
| 131 | + ) -> Result<THandler<Self>, ConnectionDenied> { |
| 132 | + Ok(rust_ipfs::libp2p::swarm::dummy::ConnectionHandler) |
| 133 | + } |
| 134 | + |
| 135 | + fn handle_established_outbound_connection( |
| 136 | + &mut self, |
| 137 | + _: ConnectionId, |
| 138 | + _: PeerId, |
| 139 | + _: &Multiaddr, |
| 140 | + _: Endpoint, |
| 141 | + _: PortUse, |
| 142 | + ) -> Result<THandler<Self>, ConnectionDenied> { |
| 143 | + Ok(rust_ipfs::libp2p::swarm::dummy::ConnectionHandler) |
| 144 | + } |
| 145 | + |
| 146 | + fn on_connection_handler_event( |
| 147 | + &mut self, |
| 148 | + peerid: PeerId, |
| 149 | + _: ConnectionId, |
| 150 | + _: THandlerOutEvent<Self>, |
| 151 | + ) { |
| 152 | + println!("Connection established with {peerid}"); |
| 153 | + } |
| 154 | + |
| 155 | + fn on_swarm_event(&mut self, event: FromSwarm) { |
| 156 | + match event { |
| 157 | + FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { |
| 158 | + if self.addrs.insert(addr.clone()) { |
| 159 | + println!("Listening on {addr}"); |
| 160 | + } |
| 161 | + } |
| 162 | + FromSwarm::ExternalAddrConfirmed(ev) => { |
| 163 | + if self.addrs.insert(ev.addr.clone()) { |
| 164 | + println!("Listening on {}", ev.addr); |
| 165 | + } |
| 166 | + } |
| 167 | + _ => {} |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + fn poll(&mut self, _: &mut Context) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> { |
| 172 | + Poll::Pending |
| 173 | + } |
| 174 | + } |
| 175 | +} |
0 commit comments