pass local key

This commit is contained in:
folex
2020-03-16 19:13:00 +03:00
parent 0343c129a5
commit 3ed32a6a1b
4 changed files with 326 additions and 315 deletions

View File

@ -1,197 +1,201 @@
// Copyright 20l9 Parity Technologies (UK) Ltd.
// // 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.
//
// 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:
// //! 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.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// use async_std::{io, task};
// use futures::prelude::*;
// use libp2p::identity::Keypair;
// use libp2p::kad::record::store::MemoryStore;
// use libp2p::kad::{record::Key, Kademlia, KademliaEvent, PutRecordOk, Quorum, Record};
// use libp2p::{
// build_development_transport, identity,
// mdns::{Mdns, MdnsEvent},
// swarm::NetworkBehaviourEventProcess,
// NetworkBehaviour, PeerId, Swarm,
// };
// use std::{
// error::Error,
// task::{Context, Poll},
// };
//
// 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.
// fn main() -> Result<(), Box<dyn Error>> {
// 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.
// let transport = build_development_transport(local_key.clone())?;
//
// // We create a custom network behaviour that combines Kademlia and mDNS.
// #[derive(NetworkBehaviour)]
// struct MyBehaviour {
// kademlia: Kademlia<MemoryStore>,
// mdns: Mdns,
// }
//
// impl NetworkBehaviourEventProcess<MdnsEvent> for MyBehaviour {
// // 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);
// }
// }
// }
// }
//
// impl NetworkBehaviourEventProcess<KademliaEvent> for MyBehaviour {
// // Called when `kademlia` produces an event.
// fn inject_event(&mut self, message: KademliaEvent) {
// match message {
// KademliaEvent::GetRecordResult(Ok(result)) => {
// for Record { key, value, .. } in result.records {
// println!(
// "Got record {:?} {:?}",
// std::str::from_utf8(key.as_ref()).unwrap(),
// std::str::from_utf8(&value).unwrap(),
// );
// }
// }
// KademliaEvent::GetRecordResult(Err(err)) => {
// eprintln!("Failed to get record: {:?}", err);
// }
// KademliaEvent::PutRecordResult(Ok(PutRecordOk { key })) => {
// println!(
// "Successfully put record {:?}",
// std::str::from_utf8(key.as_ref()).unwrap()
// );
// }
// KademliaEvent::PutRecordResult(Err(err)) => {
// eprintln!("Failed to put record: {:?}", err);
// }
// _ => {}
// }
// }
// }
//
// // Create a swarm to manage peers and events.
// let mut swarm = {
// // Create a Kademlia behaviour.
// let store = MemoryStore::new(local_peer_id.clone());
// let Keypair::Ed25519(local_key) = local_key;
// let kademlia = Kademlia::new(local_key, local_peer_id.clone(), store);
// let mdns = Mdns::new()?;
// let behaviour = MyBehaviour { kademlia, mdns };
// Swarm::new(transport, behaviour, local_peer_id)
// };
//
// // Read full lines from stdin
// let mut stdin = io::BufReader::new(io::stdin()).lines();
//
// // Listen on all interfaces and whatever port the OS assigns.
// Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse()?)?;
//
// // Kick it off.
// let mut listening = false;
// task::block_on(future::poll_fn(move |cx: &mut Context| {
// loop {
// match stdin.try_poll_next_unpin(cx)? {
// Poll::Ready(Some(line)) => handle_input_line(&mut swarm.kademlia, line),
// Poll::Ready(None) => panic!("Stdin closed"),
// Poll::Pending => break,
// }
// }
// loop {
// match swarm.poll_next_unpin(cx) {
// Poll::Ready(Some(event)) => println!("{:?}", event),
// Poll::Ready(None) => return Poll::Ready(Ok(())),
// Poll::Pending => {
// if !listening {
// if let Some(a) = Swarm::listeners(&swarm).next() {
// println!("Listening on {:?}", a);
// listening = true;
// }
// }
// break;
// }
// }
// }
// Poll::Pending
// }))
// }
//
// fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
// let mut args = line.split(" ");
//
// 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);
// }
// 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,
// };
// kademlia.put_record(record, Quorum::One);
// }
// _ => {
// eprintln!("expected GET or PUT");
// }
// }
// }
//! 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.
use async_std::{io, task};
use futures::prelude::*;
use libp2p::kad::record::store::MemoryStore;
use libp2p::kad::{record::Key, Kademlia, KademliaEvent, PutRecordOk, Quorum, Record};
use libp2p::{
NetworkBehaviour,
PeerId,
Swarm,
build_development_transport,
identity,
mdns::{Mdns, MdnsEvent},
swarm::NetworkBehaviourEventProcess
};
use std::{error::Error, task::{Context, Poll}};
fn main() -> Result<(), Box<dyn Error>> {
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.
let transport = build_development_transport(local_key)?;
// We create a custom network behaviour that combines Kademlia and mDNS.
#[derive(NetworkBehaviour)]
struct MyBehaviour {
kademlia: Kademlia<MemoryStore>,
mdns: Mdns
}
impl NetworkBehaviourEventProcess<MdnsEvent> for MyBehaviour {
// 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);
}
}
}
}
impl NetworkBehaviourEventProcess<KademliaEvent> for MyBehaviour {
// Called when `kademlia` produces an event.
fn inject_event(&mut self, message: KademliaEvent) {
match message {
KademliaEvent::GetRecordResult(Ok(result)) => {
for Record { key, value, .. } in result.records {
println!(
"Got record {:?} {:?}",
std::str::from_utf8(key.as_ref()).unwrap(),
std::str::from_utf8(&value).unwrap(),
);
}
}
KademliaEvent::GetRecordResult(Err(err)) => {
eprintln!("Failed to get record: {:?}", err);
}
KademliaEvent::PutRecordResult(Ok(PutRecordOk { key })) => {
println!(
"Successfully put record {:?}",
std::str::from_utf8(key.as_ref()).unwrap()
);
}
KademliaEvent::PutRecordResult(Err(err)) => {
eprintln!("Failed to put record: {:?}", err);
}
_ => {}
}
}
}
// Create a swarm to manage peers and events.
let mut swarm = {
// Create a Kademlia behaviour.
let store = MemoryStore::new(local_peer_id.clone());
let kademlia = Kademlia::new(local_peer_id.clone(), store);
let mdns = Mdns::new()?;
let behaviour = MyBehaviour { kademlia, mdns };
Swarm::new(transport, behaviour, local_peer_id)
};
// Read full lines from stdin
let mut stdin = io::BufReader::new(io::stdin()).lines();
// Listen on all interfaces and whatever port the OS assigns.
Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse()?)?;
// Kick it off.
let mut listening = false;
task::block_on(future::poll_fn(move |cx: &mut Context| {
loop {
match stdin.try_poll_next_unpin(cx)? {
Poll::Ready(Some(line)) => handle_input_line(&mut swarm.kademlia, line),
Poll::Ready(None) => panic!("Stdin closed"),
Poll::Pending => break
}
}
loop {
match swarm.poll_next_unpin(cx) {
Poll::Ready(Some(event)) => println!("{:?}", event),
Poll::Ready(None) => return Poll::Ready(Ok(())),
Poll::Pending => {
if !listening {
if let Some(a) = Swarm::listeners(&swarm).next() {
println!("Listening on {:?}", a);
listening = true;
}
}
break
}
}
}
Poll::Pending
}))
}
fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
let mut args = line.split(" ");
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);
}
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,
};
kademlia.put_record(record, Quorum::One);
}
_ => {
eprintln!("expected GET or PUT");
}
}
}
fn main() {}

View File

@ -1,120 +1,123 @@
// Copyright 2018 Parity Technologies (UK) Ltd.
// // 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.
//
// 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:
// //! Demonstrates how to perform Kademlia queries on the IPFS network.
// //!
// //! You can pass as parameter a base58 peer ID to search for. If you don't pass any parameter, a
// //! peer ID will be generated randomly.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// use async_std::task;
// use libp2p::identity::Keypair;
// use libp2p::kad::record::store::MemoryStore;
// use libp2p::kad::{GetClosestPeersError, Kademlia, KademliaConfig, KademliaEvent};
// use libp2p::{build_development_transport, identity, PeerId, Swarm};
// use std::{env, error::Error, time::Duration};
//
// 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.
// fn main() -> Result<(), Box<dyn Error>> {
// 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
// let transport = build_development_transport(local_key.clone())?;
//
// // Create a swarm to manage peers and events.
// let mut swarm = {
// // Create a Kademlia behaviour.
// let mut cfg = KademliaConfig::default();
// cfg.set_query_timeout(Duration::from_secs(5 * 60));
// let store = MemoryStore::new(local_peer_id.clone());
// let mut behaviour = Kademlia::with_config(local_key, local_peer_id.clone(), store, cfg);
//
// // TODO: the /dnsaddr/ scheme is not supported (https://github.com/libp2p/rust-libp2p/issues/967)
// /*behaviour.add_address(&"QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
// behaviour.add_address(&"QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
// behaviour.add_address(&"QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
// behaviour.add_address(&"QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());*/
//
// // The only address that currently works.
// behaviour.add_address(
// &"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ".parse()?,
// "/ip4/104.131.131.82/tcp/4001".parse()?,
// );
//
// // The following addresses always fail signature verification, possibly due to
// // RSA keys with < 2048 bits.
// // behaviour.add_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip4/104.236.179.241/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip4/128.199.219.111/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip4/104.236.76.40/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip4/178.62.158.247/tcp/4001".parse().unwrap());
//
// // The following addresses are permanently unreachable:
// // Other(Other(A(Transport(A(Underlying(Os { code: 101, kind: Other, message: "Network is unreachable" }))))))
// // behaviour.add_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip6/2604:a880:1:20::203:d001/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip6/2400:6180:0:d0::151:6001/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip6/2604:a880:800:10::4a:5001/tcp/4001".parse().unwrap());
// // behaviour.add_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001".parse().unwrap());
// Swarm::new(transport, behaviour, local_peer_id)
// };
//
// // Order Kademlia to search for a peer.
// let to_search: PeerId = if let Some(peer_id) = env::args().nth(1) {
// peer_id.parse()?
// } else {
// identity::Keypair::generate_ed25519().public().into()
// };
//
// println!("Searching for the closest peers to {:?}", to_search);
// swarm.get_closest_peers(to_search);
//
// // Kick it off!
// task::block_on(async move {
// loop {
// let event = swarm.next().await;
// if let KademliaEvent::GetClosestPeersResult(result) = event {
// match result {
// Ok(ok) => {
// if !ok.peers.is_empty() {
// println!("Query finished with closest peers: {:#?}", ok.peers)
// } else {
// // The example is considered failed as there
// // should always be at least 1 reachable peer.
// println!("Query finished with no closest peers.")
// }
// }
// Err(GetClosestPeersError::Timeout { peers, .. }) => {
// if !peers.is_empty() {
// println!("Query timed out with closest peers: {:#?}", peers)
// } else {
// // The example is considered failed as there
// // should always be at least 1 reachable peer.
// println!("Query timed out with no closest peers.");
// }
// }
// };
//
// break;
// }
// }
//
// Ok(())
// })
// }
//! Demonstrates how to perform Kademlia queries on the IPFS network.
//!
//! You can pass as parameter a base58 peer ID to search for. If you don't pass any parameter, a
//! peer ID will be generated randomly.
use async_std::task;
use libp2p::{
Swarm,
PeerId,
identity,
build_development_transport
};
use libp2p::kad::{Kademlia, KademliaConfig, KademliaEvent, GetClosestPeersError};
use libp2p::kad::record::store::MemoryStore;
use std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> {
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
let transport = build_development_transport(local_key)?;
// Create a swarm to manage peers and events.
let mut swarm = {
// Create a Kademlia behaviour.
let mut cfg = KademliaConfig::default();
cfg.set_query_timeout(Duration::from_secs(5 * 60));
let store = MemoryStore::new(local_peer_id.clone());
let mut behaviour = Kademlia::with_config(local_peer_id.clone(), store, cfg);
// TODO: the /dnsaddr/ scheme is not supported (https://github.com/libp2p/rust-libp2p/issues/967)
/*behaviour.add_address(&"QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
behaviour.add_address(&"QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
behaviour.add_address(&"QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());
behaviour.add_address(&"QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt".parse().unwrap(), "/dnsaddr/bootstrap.libp2p.io".parse().unwrap());*/
// The only address that currently works.
behaviour.add_address(&"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ".parse()?, "/ip4/104.131.131.82/tcp/4001".parse()?);
// The following addresses always fail signature verification, possibly due to
// RSA keys with < 2048 bits.
// behaviour.add_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip4/104.236.179.241/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip4/128.199.219.111/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip4/104.236.76.40/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip4/178.62.158.247/tcp/4001".parse().unwrap());
// The following addresses are permanently unreachable:
// Other(Other(A(Transport(A(Underlying(Os { code: 101, kind: Other, message: "Network is unreachable" }))))))
// behaviour.add_address(&"QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM".parse().unwrap(), "/ip6/2604:a880:1:20::203:d001/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu".parse().unwrap(), "/ip6/2400:6180:0:d0::151:6001/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64".parse().unwrap(), "/ip6/2604:a880:800:10::4a:5001/tcp/4001".parse().unwrap());
// behaviour.add_address(&"QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd".parse().unwrap(), "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001".parse().unwrap());
Swarm::new(transport, behaviour, local_peer_id)
};
// Order Kademlia to search for a peer.
let to_search: PeerId = if let Some(peer_id) = env::args().nth(1) {
peer_id.parse()?
} else {
identity::Keypair::generate_ed25519().public().into()
};
println!("Searching for the closest peers to {:?}", to_search);
swarm.get_closest_peers(to_search);
// Kick it off!
task::block_on(async move {
loop {
let event = swarm.next().await;
if let KademliaEvent::GetClosestPeersResult(result) = event {
match result {
Ok(ok) =>
if !ok.peers.is_empty() {
println!("Query finished with closest peers: {:#?}", ok.peers)
} else {
// The example is considered failed as there
// should always be at least 1 reachable peer.
println!("Query finished with no closest peers.")
}
Err(GetClosestPeersError::Timeout { peers, .. }) =>
if !peers.is_empty() {
println!("Query timed out with closest peers: {:#?}", peers)
} else {
// The example is considered failed as there
// should always be at least 1 reachable peer.
println!("Query timed out with no closest peers.");
}
};
break;
}
}
Ok(())
})
}
fn main() {}

View File

@ -47,8 +47,9 @@ use std::collections::VecDeque;
use std::num::NonZeroUsize;
use std::task::{Context, Poll};
use wasm_timer::Instant;
use libp2p_core::identity::ed25519::Keypair;
// TODO: how Kademlia knows hers PeerId? By distance, but how?
// TODO: how Kademlia knows hers PeerId? It's stored in KBucketsTable
// TODO: add there hers PublicKey, and exchange it on the network
/// Network behaviour that handles Kademlia.
@ -228,8 +229,8 @@ where
for<'a> TStore: RecordStore<'a>
{
/// Creates a new `Kademlia` network behaviour with the given configuration.
pub fn new(id: PeerId, store: TStore) -> Self {
Self::with_config(id, store, Default::default())
pub fn new(kp: Keypair, id: PeerId, store: TStore) -> Self {
Self::with_config(kp, id, store, Default::default())
}
/// Get the protocol name of this kademlia instance.
@ -240,7 +241,7 @@ where
}
/// Creates a new `Kademlia` network behaviour with the given configuration.
pub fn with_config(id: PeerId, store: TStore, config: KademliaConfig) -> Self {
pub fn with_config(kp: Keypair, id: PeerId, store: TStore, config: KademliaConfig) -> Self {
let local_key = kbucket::Key::new(id.clone());
let put_record_job = config
@ -259,7 +260,7 @@ where
Kademlia {
store,
kbuckets: KBucketsTable::new(local_key, config.kbucket_pending_timeout),
kbuckets: KBucketsTable::new(kp, local_key, config.kbucket_pending_timeout),
protocol_name_override: config.protocol_name_override,
queued_events: VecDeque::with_capacity(config.query_config.replication_factor.get()),
queries: QueryPool::new(config.query_config),

View File

@ -76,6 +76,7 @@ use arrayvec::{self, ArrayVec};
use bucket::KBucket;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use libp2p_core::identity::ed25519::Keypair;
/// Maximum number of k-buckets.
const NUM_BUCKETS: usize = 256;
@ -83,6 +84,7 @@ const NUM_BUCKETS: usize = 256;
/// A `KBucketsTable` represents a Kademlia routing table.
#[derive(Debug, Clone)]
pub struct KBucketsTable<TKey, TVal> {
local_kp: Keypair,
/// The key identifying the local peer that owns the routing table.
local_key: TKey,
/// The buckets comprising the routing table.
@ -142,8 +144,9 @@ where
/// The given `pending_timeout` specifies the duration after creation of
/// a [`PendingEntry`] after which it becomes eligible for insertion into
/// a full bucket, replacing the least-recently (dis)connected node.
pub fn new(local_key: TKey, pending_timeout: Duration) -> Self {
pub fn new(local_kp: Keypair, local_key: TKey, pending_timeout: Duration) -> Self {
KBucketsTable {
local_kp,
local_key,
buckets: (0 .. NUM_BUCKETS).map(|_| KBucket::new(pending_timeout)).collect(),
applied_pending: VecDeque::new()