diff --git a/examples/distributed-key-value-store.rs b/examples/distributed-key-value-store.rs index e7b80d00..5be91d29 100644 --- a/examples/distributed-key-value-store.rs +++ b/examples/distributed-key-value-store.rs @@ -28,11 +28,23 @@ //! 3. Type `GET my-key` in terminal two and hit return. //! //! 4. Close with Ctrl-c. +//! +//! 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. use async_std::{io, task}; use futures::prelude::*; use libp2p::kad::record::store::MemoryStore; use libp2p::kad::{ + AddProviderOk, Kademlia, KademliaEvent, PeerRecord, @@ -86,6 +98,18 @@ fn main() -> Result<(), Box> { fn inject_event(&mut self, message: KademliaEvent) { match message { KademliaEvent::QueryResult { result, .. } => match result { + 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); + } QueryResult::GetRecord(Ok(ok)) => { for PeerRecord { record: Record { key, value, .. }, ..} in ok.records { println!( @@ -107,6 +131,14 @@ fn main() -> Result<(), Box> { QueryResult::PutRecord(Err(err)) => { eprintln!("Failed to put record: {:?}", err); } + QueryResult::StartProviding(Ok(AddProviderOk { key })) => { + println!("Successfully put provider record {:?}", + std::str::from_utf8(key.as_ref()).unwrap() + ); + } + QueryResult::StartProviding(Err(err)) => { + eprintln!("Failed to put provider record: {:?}", err); + } _ => {} } _ => {} @@ -175,6 +207,18 @@ fn handle_input_line(kademlia: &mut Kademlia, line: String) { }; kademlia.get_record(&key, Quorum::One); } + Some("GET_PROVIDERS") => { + let key = { + match args.next() { + Some(key) => Key::new(&key), + None => { + eprintln!("Expected key"); + return + } + } + }; + kademlia.get_providers(key); + } Some("PUT") => { let key = { match args.next() { @@ -201,9 +245,22 @@ fn handle_input_line(kademlia: &mut Kademlia, line: String) { expires: None, }; kademlia.put_record(record, Quorum::One).expect("Failed to store record locally."); + }, + Some("PUT_PROVIDER") => { + let key = { + match args.next() { + Some(key) => Key::new(&key), + None => { + eprintln!("Expected key"); + return; + } + } + }; + + kademlia.start_providing(key).expect("Failed to start providing key"); } _ => { - eprintln!("expected GET or PUT"); + eprintln!("expected GET, GET_PROVIDERS, PUT or PUT_PROVIDER"); } } }