-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnode.rs
174 lines (152 loc) · 5.63 KB
/
node.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! Example bitswap node implementation allowing with basic interaction over cli
//!
//! It shows off example way to setup beetswap behaviour with a libp2p swarm and then either
//! connecting to another node and/or listening for incoming connections. In both cases both
//! the server and the client parts of the bitswap are running.
//!
//! Example invocations:
//!
//! Listen on port `9898` and serve single block with contents "12345"
//! ```sh
//! cargo run --example=node -- -l 9898 --preload-blockstore-string 12345
//! ```
//!
//! Connect to `10.0.0.101` on port `9898` and ask for CID `bafkreic...` (it's a CID of "12345" string above). You can specify multiple CIDs at once.
//! ```sh
//! cargo run --example=node -- -p /ip4/10.0.0.101/tcp/9898 bafkreiczsrdrvoybcevpzqmblh3my5fu6ui3tgag3jm3hsxvvhaxhswpyu
//! ```
//!
//! Listen on port `9898` and requests provided CID from them until it gets correct response with
//! data
//! ```sh
//! cargo run --example=node -- -l 9898 bafkreiczsrdrvoybcevpzqmblh3my5fu6ui3tgag3jm3hsxvvhaxhswpyu
//! ```
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use blockstore::{
block::{Block, CidError},
Blockstore, InMemoryBlockstore,
};
use cid::Cid;
use clap::Parser;
use libp2p::{
futures::StreamExt, identify, noise, swarm::NetworkBehaviour, swarm::SwarmEvent, tcp, yamux,
Multiaddr, SwarmBuilder,
};
use multihash_codetable::{Code, MultihashDigest};
use tracing::{debug, info};
const MAX_MULTIHASH_LENGHT: usize = 64;
const RAW_CODEC: u64 = 0x55;
#[derive(Debug, Parser)]
struct Args {
/// Peers to connect to
#[arg(short, long = "peer")]
pub(crate) peers: Vec<Multiaddr>,
/// CIDs to request
pub(crate) cids: Vec<Cid>,
/// Listen on provided port
#[arg(short, long = "listen")]
pub(crate) listen_port: Option<u16>,
/// Load provided string into blockstore on start
#[arg(long)]
pub(crate) preload_blockstore_string: Vec<String>,
}
#[derive(NetworkBehaviour)]
struct Behaviour {
identify: identify::Behaviour,
bitswap: beetswap::Behaviour<MAX_MULTIHASH_LENGHT, InMemoryBlockstore<MAX_MULTIHASH_LENGHT>>,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let args = Args::parse();
let _guard = init_tracing();
let blockstore = Arc::new(InMemoryBlockstore::new());
for preload_string in args.preload_blockstore_string {
let block = StringBlock(preload_string);
let cid = block.cid()?;
info!("inserted {cid} with content '{}'", block.0);
blockstore.put_keyed(&cid, block.data()).await?;
}
let mut swarm = SwarmBuilder::with_new_identity()
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_behaviour(|key| Behaviour {
identify: identify::Behaviour::new(identify::Config::new(
"/ipfs/id/1.0.0".to_string(),
key.public(),
)),
bitswap: beetswap::Behaviour::new(blockstore),
})?
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
if let Some(port) = args.listen_port {
swarm.listen_on(format!("/ip4/0.0.0.0/tcp/{port}").parse()?)?;
}
for peer in args.peers {
swarm.dial(peer)?;
}
let mut queries = HashMap::new();
for cid in args.cids {
let query_id = swarm.behaviour_mut().bitswap.get(&cid);
queries.insert(query_id, cid);
info!("requested cid {cid}: {query_id:?}");
}
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => debug!("Listening on {address:?}"),
// Prints peer id identify info is being sent to.
SwarmEvent::Behaviour(BehaviourEvent::Identify(identify)) => match identify {
identify::Event::Sent { peer_id, .. } => {
info!("Sent identify info to {peer_id:?}");
}
identify::Event::Received { info, .. } => {
info!("Received {info:?}")
}
_ => (),
},
SwarmEvent::Behaviour(BehaviourEvent::Bitswap(bitswap)) => match bitswap {
beetswap::Event::GetQueryResponse { query_id, data } => {
let cid = queries.get(&query_id).expect("unknown cid received");
info!("received response for {cid:?}: {data:?}");
}
beetswap::Event::GetQueryError { query_id, error } => {
let cid = queries.get(&query_id).expect("unknown cid received");
info!("received error for {cid:?}: {error}");
}
},
_ => (),
}
}
}
struct StringBlock(pub String);
impl Block<64> for StringBlock {
fn cid(&self) -> Result<Cid, CidError> {
let hash = Code::Sha2_256.digest(self.0.as_ref());
Ok(Cid::new_v1(RAW_CODEC, hash))
}
fn data(&self) -> &[u8] {
self.0.as_ref()
}
}
fn init_tracing() -> tracing_appender::non_blocking::WorkerGuard {
let (non_blocking, guard) = tracing_appender::non_blocking(std::io::stdout());
let filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing_subscriber::filter::LevelFilter::INFO.into())
.from_env_lossy();
tracing_subscriber::fmt()
.event_format(
tracing_subscriber::fmt::format()
.with_file(true)
.with_line_number(true),
)
.with_env_filter(filter)
.with_writer(non_blocking)
.init();
guard
}