2019-10-28 18:04:01 +01:00
|
|
|
// Copyright 20l9 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 key value store demonstrating libp2p and the mDNS and Kademlia protocols.
|
|
|
|
//!
|
|
|
|
//! 1. Using two terminal windows, start two instances. If you local network
|
|
|
|
//! allows mDNS, they will automatically connect.
|
|
|
|
//!
|
|
|
|
//! 2. Type `PUT my-key my-value` in terminal one and hit return.
|
|
|
|
//!
|
|
|
|
//! 3. Type `GET my-key` in terminal two and hit return.
|
|
|
|
//!
|
|
|
|
//! 4. Close with Ctrl-c.
|
2020-08-17 16:30:45 +02:00
|
|
|
//!
|
|
|
|
//! You can also store provider records instead of key value records.
|
|
|
|
//!
|
|
|
|
//! 1. Using two terminal windows, start two instances. If you local network
|
|
|
|
//! allows mDNS, they will automatically connect.
|
|
|
|
//!
|
|
|
|
//! 2. Type `PUT_PROVIDER my-key` in terminal one and hit return.
|
|
|
|
//!
|
|
|
|
//! 3. Type `GET_PROVIDERS my-key` in terminal two and hit return.
|
|
|
|
//!
|
|
|
|
//! 4. Close with Ctrl-c.
|
2019-10-28 18:04:01 +01:00
|
|
|
|
2019-11-25 10:45:04 +01:00
|
|
|
use async_std::{io, task};
|
2019-10-28 18:04:01 +01:00
|
|
|
use futures::prelude::*;
|
|
|
|
use libp2p::kad::record::store::MemoryStore;
|
2020-05-16 10:43:09 +02:00
|
|
|
use libp2p::kad::{
|
2021-08-11 13:12:12 +02:00
|
|
|
record::Key, AddProviderOk, Kademlia, KademliaEvent, PeerRecord, PutRecordOk, QueryResult,
|
|
|
|
Quorum, Record,
|
2020-05-16 10:43:09 +02:00
|
|
|
};
|
2019-10-28 18:04:01 +01:00
|
|
|
use libp2p::{
|
2021-08-11 13:12:12 +02:00
|
|
|
development_transport, identity,
|
2021-03-02 10:18:24 +01:00
|
|
|
mdns::{Mdns, MdnsConfig, MdnsEvent},
|
2021-08-11 13:12:12 +02:00
|
|
|
swarm::{NetworkBehaviourEventProcess, SwarmEvent},
|
|
|
|
NetworkBehaviour, PeerId, Swarm,
|
|
|
|
};
|
|
|
|
use std::{
|
|
|
|
error::Error,
|
|
|
|
task::{Context, Poll},
|
2019-10-28 18:04:01 +01:00
|
|
|
};
|
|
|
|
|
2021-03-16 11:48:48 +01:00
|
|
|
#[async_std::main]
|
|
|
|
async fn main() -> Result<(), Box<dyn Error>> {
|
2019-10-28 18:04:01 +01:00
|
|
|
env_logger::init();
|
|
|
|
|
|
|
|
// Create a random key for ourselves.
|
|
|
|
let local_key = identity::Keypair::generate_ed25519();
|
|
|
|
let local_peer_id = PeerId::from(local_key.public());
|
|
|
|
|
|
|
|
// Set up a an encrypted DNS-enabled TCP Transport over the Mplex protocol.
|
2021-03-16 11:48:48 +01:00
|
|
|
let transport = development_transport(local_key).await?;
|
2019-10-28 18:04:01 +01:00
|
|
|
|
|
|
|
// We create a custom network behaviour that combines Kademlia and mDNS.
|
|
|
|
#[derive(NetworkBehaviour)]
|
2021-09-14 23:28:08 +10:00
|
|
|
#[behaviour(event_process = true)]
|
2020-02-07 16:29:30 +01:00
|
|
|
struct MyBehaviour {
|
|
|
|
kademlia: Kademlia<MemoryStore>,
|
2021-08-11 13:12:12 +02:00
|
|
|
mdns: Mdns,
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
|
2020-02-07 16:29:30 +01:00
|
|
|
impl NetworkBehaviourEventProcess<MdnsEvent> for MyBehaviour {
|
2019-10-28 18:04:01 +01:00
|
|
|
// Called when `mdns` produces an event.
|
|
|
|
fn inject_event(&mut self, event: MdnsEvent) {
|
|
|
|
if let MdnsEvent::Discovered(list) = event {
|
|
|
|
for (peer_id, multiaddr) in list {
|
|
|
|
self.kademlia.add_address(&peer_id, multiaddr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-07 16:29:30 +01:00
|
|
|
impl NetworkBehaviourEventProcess<KademliaEvent> for MyBehaviour {
|
2019-10-28 18:04:01 +01:00
|
|
|
// Called when `kademlia` produces an event.
|
|
|
|
fn inject_event(&mut self, message: KademliaEvent) {
|
|
|
|
match message {
|
2021-06-28 14:14:31 +02:00
|
|
|
KademliaEvent::OutboundQueryCompleted { result, .. } => match result {
|
2020-08-17 16:30:45 +02:00
|
|
|
QueryResult::GetProviders(Ok(ok)) => {
|
|
|
|
for peer in ok.providers {
|
|
|
|
println!(
|
|
|
|
"Peer {:?} provides key {:?}",
|
|
|
|
peer,
|
|
|
|
std::str::from_utf8(ok.key.as_ref()).unwrap()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
QueryResult::GetProviders(Err(err)) => {
|
|
|
|
eprintln!("Failed to get providers: {:?}", err);
|
|
|
|
}
|
2020-05-16 10:43:09 +02:00
|
|
|
QueryResult::GetRecord(Ok(ok)) => {
|
2021-08-11 13:12:12 +02:00
|
|
|
for PeerRecord {
|
|
|
|
record: Record { key, value, .. },
|
|
|
|
..
|
|
|
|
} in ok.records
|
|
|
|
{
|
2020-05-16 10:43:09 +02:00
|
|
|
println!(
|
|
|
|
"Got record {:?} {:?}",
|
|
|
|
std::str::from_utf8(key.as_ref()).unwrap(),
|
|
|
|
std::str::from_utf8(&value).unwrap(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
QueryResult::GetRecord(Err(err)) => {
|
|
|
|
eprintln!("Failed to get record: {:?}", err);
|
|
|
|
}
|
|
|
|
QueryResult::PutRecord(Ok(PutRecordOk { key })) => {
|
2019-10-28 18:04:01 +01:00
|
|
|
println!(
|
2020-05-16 10:43:09 +02:00
|
|
|
"Successfully put record {:?}",
|
|
|
|
std::str::from_utf8(key.as_ref()).unwrap()
|
2019-10-28 18:04:01 +01:00
|
|
|
);
|
|
|
|
}
|
2020-05-16 10:43:09 +02:00
|
|
|
QueryResult::PutRecord(Err(err)) => {
|
|
|
|
eprintln!("Failed to put record: {:?}", err);
|
|
|
|
}
|
2020-08-17 16:30:45 +02:00
|
|
|
QueryResult::StartProviding(Ok(AddProviderOk { key })) => {
|
2021-08-11 13:12:12 +02:00
|
|
|
println!(
|
|
|
|
"Successfully put provider record {:?}",
|
2020-08-17 16:30:45 +02:00
|
|
|
std::str::from_utf8(key.as_ref()).unwrap()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
QueryResult::StartProviding(Err(err)) => {
|
|
|
|
eprintln!("Failed to put provider record: {:?}", err);
|
|
|
|
}
|
2020-05-16 10:43:09 +02:00
|
|
|
_ => {}
|
2021-08-11 13:12:12 +02:00
|
|
|
},
|
2019-10-28 18:04:01 +01:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a swarm to manage peers and events.
|
|
|
|
let mut swarm = {
|
|
|
|
// Create a Kademlia behaviour.
|
2021-06-14 20:41:44 +02:00
|
|
|
let store = MemoryStore::new(local_peer_id);
|
|
|
|
let kademlia = Kademlia::new(local_peer_id, store);
|
2021-03-02 10:18:24 +01:00
|
|
|
let mdns = task::block_on(Mdns::new(MdnsConfig::default()))?;
|
2019-11-25 10:45:04 +01:00
|
|
|
let behaviour = MyBehaviour { kademlia, mdns };
|
2019-10-28 18:04:01 +01:00
|
|
|
Swarm::new(transport, behaviour, local_peer_id)
|
|
|
|
};
|
|
|
|
|
2019-11-25 10:45:04 +01:00
|
|
|
// Read full lines from stdin
|
|
|
|
let mut stdin = io::BufReader::new(io::stdin()).lines();
|
2019-10-28 18:04:01 +01:00
|
|
|
|
|
|
|
// Listen on all interfaces and whatever port the OS assigns.
|
2021-03-18 14:55:33 +01:00
|
|
|
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
|
2019-10-28 18:04:01 +01:00
|
|
|
|
|
|
|
// Kick it off.
|
2020-07-27 20:27:33 +00:00
|
|
|
task::block_on(future::poll_fn(move |cx: &mut Context<'_>| {
|
2019-10-28 18:04:01 +01:00
|
|
|
loop {
|
2019-11-25 10:45:04 +01:00
|
|
|
match stdin.try_poll_next_unpin(cx)? {
|
2021-08-11 13:12:12 +02:00
|
|
|
Poll::Ready(Some(line)) => {
|
|
|
|
handle_input_line(&mut swarm.behaviour_mut().kademlia, line)
|
|
|
|
}
|
2019-11-25 10:45:04 +01:00
|
|
|
Poll::Ready(None) => panic!("Stdin closed"),
|
2021-08-11 13:12:12 +02:00
|
|
|
Poll::Pending => break,
|
2019-11-25 10:45:04 +01:00
|
|
|
}
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
loop {
|
2019-11-25 10:45:04 +01:00
|
|
|
match swarm.poll_next_unpin(cx) {
|
2021-06-14 20:41:44 +02:00
|
|
|
Poll::Ready(Some(event)) => {
|
2021-07-08 11:41:33 +02:00
|
|
|
if let SwarmEvent::NewListenAddr { address, .. } = event {
|
|
|
|
println!("Listening on {:?}", address);
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
}
|
2021-06-14 20:41:44 +02:00
|
|
|
Poll::Ready(None) => return Poll::Ready(Ok(())),
|
|
|
|
Poll::Pending => break,
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
}
|
2019-11-25 10:45:04 +01:00
|
|
|
Poll::Pending
|
|
|
|
}))
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
|
2020-02-07 16:29:30 +01:00
|
|
|
fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
|
2021-06-14 20:41:44 +02:00
|
|
|
let mut args = line.split(' ');
|
2019-10-28 18:04:01 +01:00
|
|
|
|
|
|
|
match args.next() {
|
|
|
|
Some("GET") => {
|
|
|
|
let key = {
|
|
|
|
match args.next() {
|
|
|
|
Some(key) => Key::new(&key),
|
|
|
|
None => {
|
|
|
|
eprintln!("Expected key");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
kademlia.get_record(&key, Quorum::One);
|
|
|
|
}
|
2020-08-17 16:30:45 +02:00
|
|
|
Some("GET_PROVIDERS") => {
|
|
|
|
let key = {
|
|
|
|
match args.next() {
|
|
|
|
Some(key) => Key::new(&key),
|
|
|
|
None => {
|
|
|
|
eprintln!("Expected key");
|
2021-08-11 13:12:12 +02:00
|
|
|
return;
|
2020-08-17 16:30:45 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
kademlia.get_providers(key);
|
|
|
|
}
|
2019-10-28 18:04:01 +01:00
|
|
|
Some("PUT") => {
|
|
|
|
let key = {
|
|
|
|
match args.next() {
|
|
|
|
Some(key) => Key::new(&key),
|
|
|
|
None => {
|
|
|
|
eprintln!("Expected key");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let value = {
|
|
|
|
match args.next() {
|
|
|
|
Some(value) => value.as_bytes().to_vec(),
|
|
|
|
None => {
|
|
|
|
eprintln!("Expected value");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let record = Record {
|
|
|
|
key,
|
|
|
|
value,
|
|
|
|
publisher: None,
|
|
|
|
expires: None,
|
|
|
|
};
|
2021-08-11 13:12:12 +02:00
|
|
|
kademlia
|
|
|
|
.put_record(record, Quorum::One)
|
|
|
|
.expect("Failed to store record locally.");
|
|
|
|
}
|
2020-08-17 16:30:45 +02:00
|
|
|
Some("PUT_PROVIDER") => {
|
|
|
|
let key = {
|
|
|
|
match args.next() {
|
|
|
|
Some(key) => Key::new(&key),
|
|
|
|
None => {
|
|
|
|
eprintln!("Expected key");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-08-11 13:12:12 +02:00
|
|
|
kademlia
|
|
|
|
.start_providing(key)
|
|
|
|
.expect("Failed to start providing key");
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
_ => {
|
2020-08-17 16:30:45 +02:00
|
|
|
eprintln!("expected GET, GET_PROVIDERS, PUT or PUT_PROVIDER");
|
2019-10-28 18:04:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|