forked from libp2p/rust-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.rs
187 lines (170 loc) · 6.61 KB
/
chat.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
175
176
177
178
179
180
181
182
183
184
185
186
187
// 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.
//! A basic chat application demonstrating libp2p and the mDNS and floodsub protocols.
//!
//! Using two terminal windows, start two instances. If you local network allows mDNS,
//! they will automatically connect. Type a message in either terminal and hit return: the
//! message is sent and printed in the other terminal. Close with Ctrl-c.
//!
//! You can of course open more terminal windows and add more participants.
//! Dialing any of the other peers will propagate the new participant to all
//! chat members and everyone will receive all messages.
//!
//! # If they don't automatically connect
//!
//! If the nodes don't automatically connect, take note of the listening addresses of the first
//! instance and start the second with one of the addresses as the first argument. In the first
//! terminal window, run:
//!
//! ```sh
//! cargo run --example chat
//! ```
//!
//! 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 chat -- /ip4/127.0.0.1/tcp/24915
//! ```
//!
//! The two nodes then connect.
use async_std::{io, task};
use futures::{
prelude::{stream::StreamExt, *},
select,
};
use libp2p::{
floodsub::{self, Floodsub, FloodsubEvent},
identity,
mdns::{Mdns, MdnsConfig, MdnsEvent},
swarm::SwarmEvent,
Multiaddr, NetworkBehaviour, PeerId, Swarm,
};
use std::error::Error;
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
// Create a random PeerId
let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
println!("Local peer id: {:?}", local_peer_id);
// Set up a an encrypted DNS-enabled TCP Transport over the Mplex and Yamux protocols
let transport = libp2p::development_transport(local_key).await?;
// Create a Floodsub topic
let floodsub_topic = floodsub::Topic::new("chat");
// We create a custom network behaviour that combines floodsub and mDNS.
// In the future, we want to improve libp2p to make this easier to do.
// Use the derive to generate delegating NetworkBehaviour impl and require the
// NetworkBehaviourEventProcess implementations below.
#[derive(NetworkBehaviour)]
#[behaviour(out_event = "OutEvent")]
struct MyBehaviour {
floodsub: Floodsub,
mdns: Mdns,
// Struct fields which do not implement NetworkBehaviour need to be ignored
#[behaviour(ignore)]
#[allow(dead_code)]
ignored_member: bool,
}
#[derive(Debug)]
enum OutEvent {
Floodsub(FloodsubEvent),
Mdns(MdnsEvent),
}
impl From<MdnsEvent> for OutEvent {
fn from(v: MdnsEvent) -> Self {
Self::Mdns(v)
}
}
impl From<FloodsubEvent> for OutEvent {
fn from(v: FloodsubEvent) -> Self {
Self::Floodsub(v)
}
}
// Create a Swarm to manage peers and events
let mut swarm = {
let mdns = task::block_on(Mdns::new(MdnsConfig::default()))?;
let mut behaviour = MyBehaviour {
floodsub: Floodsub::new(local_peer_id),
mdns,
ignored_member: false,
};
behaviour.floodsub.subscribe(floodsub_topic.clone());
Swarm::new(transport, behaviour, local_peer_id)
};
// Reach out to another node if specified
if let Some(to_dial) = std::env::args().nth(1) {
let addr: Multiaddr = to_dial.parse()?;
swarm.dial(addr)?;
println!("Dialed {:?}", to_dial)
}
// Read full lines from stdin
let mut stdin = io::BufReader::new(io::stdin()).lines().fuse();
// Listen on all interfaces and whatever port the OS assigns
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
// Kick it off
loop {
select! {
line = stdin.select_next_some() => swarm
.behaviour_mut()
.floodsub
.publish(floodsub_topic.clone(), line.expect("Stdin not to close").as_bytes()),
event = swarm.select_next_some() => match event {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on {:?}", address);
}
SwarmEvent::Behaviour(OutEvent::Floodsub(
FloodsubEvent::Message(message)
)) => {
println!(
"Received: '{:?}' from {:?}",
String::from_utf8_lossy(&message.data),
message.source
);
}
SwarmEvent::Behaviour(OutEvent::Mdns(
MdnsEvent::Discovered(list)
)) => {
for (peer, _) in list {
swarm
.behaviour_mut()
.floodsub
.add_node_to_partial_view(peer);
}
}
SwarmEvent::Behaviour(OutEvent::Mdns(MdnsEvent::Expired(
list
))) => {
for (peer, _) in list {
if !swarm.behaviour_mut().mdns.has_node(&peer) {
swarm
.behaviour_mut()
.floodsub
.remove_node_from_partial_view(&peer);
}
}
},
_ => {}
}
}
}
}