|
| 1 | +// Copyright 20l9 Parity Technologies (UK) Ltd. |
| 2 | +// |
| 3 | +// Permission is hereby granted, free of charge, to any person obtaining a |
| 4 | +// copy of this software and associated documentation files (the "Software"), |
| 5 | +// to deal in the Software without restriction, including without limitation |
| 6 | +// the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 7 | +// and/or sell copies of the Software, and to permit persons to whom the |
| 8 | +// Software is furnished to do so, subject to the following conditions: |
| 9 | +// |
| 10 | +// The above copyright notice and this permission notice shall be included in |
| 11 | +// all copies or substantial portions of the Software. |
| 12 | +// |
| 13 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
| 14 | +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 18 | +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 19 | +// DEALINGS IN THE SOFTWARE. |
| 20 | + |
| 21 | +//! A basic key value store demonstrating libp2p and the mDNS and Kademlia protocols. |
| 22 | +//! |
| 23 | +//! 1. Using two terminal windows, start two instances. If you local network |
| 24 | +//! allows mDNS, they will automatically connect. |
| 25 | +//! |
| 26 | +//! 2. Type `PUT my-key my-value` in terminal one and hit return. |
| 27 | +//! |
| 28 | +//! 3. Type `GET my-key` in terminal two and hit return. |
| 29 | +//! |
| 30 | +//! 4. Close with Ctrl-c. |
| 31 | +
|
| 32 | +use futures::prelude::*; |
| 33 | +use libp2p::kad::record::store::MemoryStore; |
| 34 | +use libp2p::kad::{record::Key, Kademlia, KademliaEvent, PutRecordOk, Quorum, Record}; |
| 35 | +use libp2p::{ |
| 36 | + build_development_transport, identity, |
| 37 | + mdns::{Mdns, MdnsEvent}, |
| 38 | + swarm::NetworkBehaviourEventProcess, |
| 39 | + tokio_codec::{FramedRead, LinesCodec}, |
| 40 | + tokio_io::{AsyncRead, AsyncWrite}, |
| 41 | + NetworkBehaviour, PeerId, Swarm, |
| 42 | +}; |
| 43 | + |
| 44 | +fn main() { |
| 45 | + env_logger::init(); |
| 46 | + |
| 47 | + // Create a random key for ourselves. |
| 48 | + let local_key = identity::Keypair::generate_ed25519(); |
| 49 | + let local_peer_id = PeerId::from(local_key.public()); |
| 50 | + |
| 51 | + // Set up a an encrypted DNS-enabled TCP Transport over the Mplex protocol. |
| 52 | + let transport = build_development_transport(local_key); |
| 53 | + |
| 54 | + // We create a custom network behaviour that combines Kademlia and mDNS. |
| 55 | + #[derive(NetworkBehaviour)] |
| 56 | + struct MyBehaviour<TSubstream: AsyncRead + AsyncWrite> { |
| 57 | + kademlia: Kademlia<TSubstream, MemoryStore>, |
| 58 | + mdns: Mdns<TSubstream>, |
| 59 | + } |
| 60 | + |
| 61 | + impl<TSubstream: AsyncRead + AsyncWrite> NetworkBehaviourEventProcess<MdnsEvent> |
| 62 | + for MyBehaviour<TSubstream> |
| 63 | + { |
| 64 | + // Called when `mdns` produces an event. |
| 65 | + fn inject_event(&mut self, event: MdnsEvent) { |
| 66 | + if let MdnsEvent::Discovered(list) = event { |
| 67 | + for (peer_id, multiaddr) in list { |
| 68 | + self.kademlia.add_address(&peer_id, multiaddr); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + impl<TSubstream: AsyncRead + AsyncWrite> NetworkBehaviourEventProcess<KademliaEvent> |
| 75 | + for MyBehaviour<TSubstream> |
| 76 | + { |
| 77 | + // Called when `kademlia` produces an event. |
| 78 | + fn inject_event(&mut self, message: KademliaEvent) { |
| 79 | + match message { |
| 80 | + KademliaEvent::GetRecordResult(Ok(result)) => { |
| 81 | + for Record { key, value, .. } in result.records { |
| 82 | + println!( |
| 83 | + "Got record {:?} {:?}", |
| 84 | + std::str::from_utf8(key.as_ref()).unwrap(), |
| 85 | + std::str::from_utf8(&value).unwrap(), |
| 86 | + ); |
| 87 | + } |
| 88 | + } |
| 89 | + KademliaEvent::GetRecordResult(Err(err)) => { |
| 90 | + eprintln!("Failed to get record: {:?}", err); |
| 91 | + } |
| 92 | + KademliaEvent::PutRecordResult(Ok(PutRecordOk { key })) => { |
| 93 | + println!( |
| 94 | + "Successfully put record {:?}", |
| 95 | + std::str::from_utf8(key.as_ref()).unwrap() |
| 96 | + ); |
| 97 | + } |
| 98 | + KademliaEvent::PutRecordResult(Err(err)) => { |
| 99 | + eprintln!("Failed to put record: {:?}", err); |
| 100 | + } |
| 101 | + _ => {} |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + // Create a swarm to manage peers and events. |
| 107 | + let mut swarm = { |
| 108 | + // Create a Kademlia behaviour. |
| 109 | + let store = MemoryStore::new(local_peer_id.clone()); |
| 110 | + let kademlia = Kademlia::new(local_peer_id.clone(), store); |
| 111 | + |
| 112 | + let behaviour = MyBehaviour { |
| 113 | + kademlia, |
| 114 | + mdns: Mdns::new().expect("Failed to create mDNS service"), |
| 115 | + }; |
| 116 | + |
| 117 | + Swarm::new(transport, behaviour, local_peer_id) |
| 118 | + }; |
| 119 | + |
| 120 | + // Read full lines from stdin. |
| 121 | + let stdin = tokio_stdin_stdout::stdin(0); |
| 122 | + let mut framed_stdin = FramedRead::new(stdin, LinesCodec::new()); |
| 123 | + |
| 124 | + // Listen on all interfaces and whatever port the OS assigns. |
| 125 | + Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse().unwrap()).unwrap(); |
| 126 | + |
| 127 | + // Kick it off. |
| 128 | + let mut listening = false; |
| 129 | + tokio::run(futures::future::poll_fn(move || { |
| 130 | + loop { |
| 131 | + match framed_stdin.poll().expect("Error while polling stdin") { |
| 132 | + Async::Ready(Some(line)) => { |
| 133 | + handle_input_line(&mut swarm.kademlia, line); |
| 134 | + } |
| 135 | + Async::Ready(None) => panic!("Stdin closed"), |
| 136 | + Async::NotReady => break, |
| 137 | + }; |
| 138 | + } |
| 139 | + |
| 140 | + loop { |
| 141 | + match swarm.poll().expect("Error while polling swarm") { |
| 142 | + Async::Ready(Some(_)) => {} |
| 143 | + Async::Ready(None) | Async::NotReady => { |
| 144 | + if !listening { |
| 145 | + if let Some(a) = Swarm::listeners(&swarm).next() { |
| 146 | + println!("Listening on {:?}", a); |
| 147 | + listening = true; |
| 148 | + } |
| 149 | + } |
| 150 | + break; |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + Ok(Async::NotReady) |
| 156 | + })); |
| 157 | +} |
| 158 | + |
| 159 | +fn handle_input_line<TSubstream: AsyncRead + AsyncWrite>( |
| 160 | + kademlia: &mut Kademlia<TSubstream, MemoryStore>, |
| 161 | + line: String, |
| 162 | +) { |
| 163 | + let mut args = line.split(" "); |
| 164 | + |
| 165 | + match args.next() { |
| 166 | + Some("GET") => { |
| 167 | + let key = { |
| 168 | + match args.next() { |
| 169 | + Some(key) => Key::new(&key), |
| 170 | + None => { |
| 171 | + eprintln!("Expected key"); |
| 172 | + return; |
| 173 | + } |
| 174 | + } |
| 175 | + }; |
| 176 | + kademlia.get_record(&key, Quorum::One); |
| 177 | + } |
| 178 | + Some("PUT") => { |
| 179 | + let key = { |
| 180 | + match args.next() { |
| 181 | + Some(key) => Key::new(&key), |
| 182 | + None => { |
| 183 | + eprintln!("Expected key"); |
| 184 | + return; |
| 185 | + } |
| 186 | + } |
| 187 | + }; |
| 188 | + let value = { |
| 189 | + match args.next() { |
| 190 | + Some(value) => value.as_bytes().to_vec(), |
| 191 | + None => { |
| 192 | + eprintln!("Expected value"); |
| 193 | + return; |
| 194 | + } |
| 195 | + } |
| 196 | + }; |
| 197 | + let record = Record { |
| 198 | + key, |
| 199 | + value, |
| 200 | + publisher: None, |
| 201 | + expires: None, |
| 202 | + }; |
| 203 | + kademlia.put_record(record, Quorum::One); |
| 204 | + } |
| 205 | + _ => { |
| 206 | + eprintln!("expected GET or PUT"); |
| 207 | + } |
| 208 | + } |
| 209 | +} |
0 commit comments