Remove the old API (#565)

* Remove the old API

* Fix integration test
This commit is contained in:
Pierre Krieger
2018-10-15 16:17:55 +01:00
committed by GitHub
parent 2c98d06942
commit 724d0f5d82
18 changed files with 1 additions and 2445 deletions

View File

@ -1,141 +0,0 @@
// Copyright 2017 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.
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate tokio_codec;
extern crate tokio_current_thread;
use futures::sync::oneshot;
use futures::{Future, Sink, Stream};
use std::env;
use libp2p::SimpleProtocol;
use libp2p::core::Transport;
use libp2p::core::{upgrade, either::EitherOutput};
use libp2p::tcp::TcpConfig;
use tokio_codec::{BytesCodec, Framed};
use libp2p::websocket::WsConfig;
fn main() {
env_logger::init();
// Determine which address to dial.
let target_addr = env::args()
.nth(1)
.unwrap_or("/ip4/127.0.0.1/tcp/10333".to_owned());
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new()
// In addition to TCP/IP, we also want to support the Websockets protocol on top of TCP/IP.
// The parameter passed to `WsConfig::new()` must be an implementation of `Transport` to be
// used for the underlying multiaddress.
.or_transport(WsConfig::new(TcpConfig::new()))
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
.with_upgrade({
let plain_text = upgrade::PlainTextConfig;
let secio = {
let private_key = include_bytes!("test-rsa-private-key.pk8");
let public_key = include_bytes!("test-rsa-public-key.der").to_vec();
let keypair = libp2p::secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap();
libp2p::secio::SecioConfig::new(keypair)
};
upgrade::or(
upgrade::map(plain_text, |pt| EitherOutput::First(pt)),
upgrade::map(secio, |out: libp2p::secio::SecioOutput<_>| EitherOutput::Second(out.stream))
)
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MplexConfig::new())
// The object returned by the call to `with_upgrade(MplexConfig::new())` can't be used as a
// `Transport` because the output of the upgrade is not a stream but a controller for
// muxing. We have to explicitly call `into_connection_reuse()` in order to turn this into
// a `Transport`.
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
// Building a struct that represents the protocol that we are going to use for dialing.
let proto = SimpleProtocol::new("/echo/1.0.0", |socket| {
// This closure is called whenever a stream using the "echo" protocol has been
// successfully negotiated. The parameter is the raw socket (implements the AsyncRead
// and AsyncWrite traits), and the closure must return an implementation of
// `IntoFuture` that can yield any type of object.
Ok(Framed::new(socket, BytesCodec::new()))
});
let (finished_tx, finished_rx) = oneshot::channel();
let mut finished_tx = Some(finished_tx);
// Let's put this `transport` into a *swarm*. The swarm will handle all the incoming
// connections for us. The second parameter we pass is the connection upgrade that is accepted
// by the listening part. We don't want to accept anything, so we pass a dummy object that
// represents a connection that is always denied.
let (swarm_controller, swarm_future) = libp2p::core::swarm(
transport.clone().with_upgrade(proto.clone()),
|echo, _client_addr| {
// `echo` is what the closure used when initializing `proto` returns.
// Consequently, please note that the `send` method is available only because the type
// `length_delimited::Framed` has a `send` method.
println!("Sending \"hello world\" to listener");
let finished_tx = finished_tx.take();
echo.send("hello world".into())
// Then listening for one message from the remote.
.and_then(|echo| {
echo.into_future().map_err(|(e, _)| e).map(|(n,_ )| n)
})
.and_then(move |message| {
println!("Received message from listener: {:?}", message.unwrap());
if let Some(finished_tx) = finished_tx {
finished_tx.send(()).unwrap();
}
Ok(())
})
},
);
// We now use the controller to dial to the address.
swarm_controller
.dial(target_addr.parse().expect("invalid multiaddr"), transport.with_upgrade(proto))
// If the multiaddr protocol exists but is not supported, then we get an error containing
// the original multiaddress.
.expect("unsupported multiaddr");
// The address we actually listen on can be different from the address that was passed to
// the `listen_on` function. For example if you pass `/ip4/0.0.0.0/tcp/0`, then the port `0`
// will be replaced with the actual port.
// `swarm_future` is a future that contains all the behaviour that we want, but nothing has
// actually started yet. Because we created the `TcpConfig` with tokio, we need to run the
// future through the tokio core.
let final_future = swarm_future
.for_each(|_| Ok(()))
.select(finished_rx.map_err(|_| unreachable!()))
.map(|_| ())
.map_err(|(err, _)| err);
tokio_current_thread::block_on_all(final_future).unwrap();
}

View File

@ -1,144 +0,0 @@
// Copyright 2017 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.
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate tokio_codec;
extern crate tokio_current_thread;
use futures::future::{loop_fn, Future, IntoFuture, Loop};
use futures::{Sink, Stream};
use std::env;
use libp2p::SimpleProtocol;
use libp2p::core::Transport;
use libp2p::core::{upgrade, either::EitherOutput};
use libp2p::tcp::TcpConfig;
use tokio_codec::{BytesCodec, Framed};
use libp2p::websocket::WsConfig;
fn main() {
env_logger::init();
// Determine which address to listen to.
let listen_addr = env::args()
.nth(1)
.unwrap_or("/ip4/0.0.0.0/tcp/10333".to_owned());
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new()
// In addition to TCP/IP, we also want to support the Websockets protocol on top of TCP/IP.
// The parameter passed to `WsConfig::new()` must be an implementation of `Transport` to be
// used for the underlying multiaddress.
.or_transport(WsConfig::new(TcpConfig::new()))
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
.with_upgrade({
let plain_text = upgrade::PlainTextConfig;
let secio = {
let private_key = include_bytes!("test-rsa-private-key.pk8");
let public_key = include_bytes!("test-rsa-public-key.der").to_vec();
let keypair = libp2p::secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap();
libp2p::secio::SecioConfig::new(keypair)
};
upgrade::or(
upgrade::map(plain_text, |pt| EitherOutput::First(pt)),
upgrade::map(secio, |out: libp2p::secio::SecioOutput<_>| EitherOutput::Second(out.stream))
)
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MplexConfig::new())
// The object returned by the call to `with_upgrade(MplexConfig::new())` can't be used as a
// `Transport` because the output of the upgrade is not a stream but a controller for
// muxing. We have to explicitly call `into_connection_reuse()` in order to turn this into
// a `Transport`.
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
// We now have a `transport` variable that can be used either to dial nodes or listen to
// incoming connections, and that will automatically apply secio and multiplex on top
// of any opened stream.
// We now prepare the protocol that we are going to negotiate with nodes that open a connection
// or substream to our server.
let proto = SimpleProtocol::new("/echo/1.0.0", |socket| {
// This closure is called whenever a stream using the "echo" protocol has been
// successfully negotiated. The parameter is the raw socket (implements the AsyncRead
// and AsyncWrite traits), and the closure must return an implementation of
// `IntoFuture` that can yield any type of object.
Ok(Framed::new(socket, BytesCodec::new()))
});
// Let's put this `transport` into a *swarm*. The swarm will handle all the incoming and
// outgoing connections for us.
let (swarm_controller, swarm_future) = libp2p::core::swarm(
transport.clone().with_upgrade(proto),
|socket, _client_addr| {
println!("Successfully negotiated protocol");
// The type of `socket` is exactly what the closure of `SimpleProtocol` returns.
// We loop forever in order to handle all the messages sent by the client.
loop_fn(socket, move |socket| {
socket
.into_future()
.map_err(|(e, _)| e)
.and_then(move |(msg, rest)| {
if let Some(msg) = msg {
// One message has been received. We send it back to the client.
println!(
"Received a message: {:?}\n => Sending back \
identical message to remote", msg
);
Box::new(rest.send(msg.freeze()).map(|m| Loop::Continue(m)))
as Box<Future<Item = _, Error = _>>
} else {
// End of stream. Connection closed. Breaking the loop.
println!("Received EOF\n => Dropping connection");
Box::new(Ok(Loop::Break(())).into_future())
as Box<Future<Item = _, Error = _>>
}
})
})
},
);
// We now use the controller to listen on the address.
let address = swarm_controller
.listen_on(listen_addr.parse().expect("invalid multiaddr"))
// If the multiaddr protocol exists but is not supported, then we get an error containing
// the original multiaddress.
.expect("unsupported multiaddr");
// The address we actually listen on can be different from the address that was passed to
// the `listen_on` function. For example if you pass `/ip4/0.0.0.0/tcp/0`, then the port `0`
// will be replaced with the actual port.
println!("Now listening on {:?}", address);
// `swarm_future` is a future that contains all the behaviour that we want, but nothing has
// actually started yet. Because we created the `TcpConfig` with tokio, we need to run the
// future through the tokio core.
tokio_current_thread::block_on_all(swarm_future.for_each(|_| Ok(()))).unwrap();
}

View File

@ -1,160 +0,0 @@
// 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.
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate rand;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate tokio_stdin;
use futures::Stream;
use futures::future::Future;
use std::{env, mem};
use libp2p::core::{either::EitherOutput, upgrade};
use libp2p::core::{Multiaddr, Transport, PublicKey};
use libp2p::peerstore::PeerId;
use libp2p::tcp::TcpConfig;
use libp2p::websocket::WsConfig;
fn main() {
env_logger::init();
// Determine which address to listen to.
let listen_addr = env::args()
.nth(1)
.unwrap_or("/ip4/0.0.0.0/tcp/10050".to_owned());
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new()
// In addition to TCP/IP, we also want to support the Websockets protocol on top of TCP/IP.
// The parameter passed to `WsConfig::new()` must be an implementation of `Transport` to be
// used for the underlying multiaddress.
.or_transport(WsConfig::new(TcpConfig::new()))
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
.with_upgrade({
let plain_text = upgrade::PlainTextConfig;
let secio = {
let private_key = include_bytes!("test-rsa-private-key.pk8");
let public_key = include_bytes!("test-rsa-public-key.der").to_vec();
libp2p::secio::SecioConfig::new(
libp2p::secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap()
)
};
upgrade::or(
upgrade::map(plain_text, |pt| EitherOutput::First(pt)),
upgrade::map(secio, |out: libp2p::secio::SecioOutput<_>| EitherOutput::Second(out.stream))
)
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MplexConfig::new())
// The object returned by the call to `with_upgrade(MplexConfig::new())` can't be used as a
// `Transport` because the output of the upgrade is not a stream but a controller for
// muxing. We have to explicitly call `into_connection_reuse()` in order to turn this into
// a `Transport`.
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
// We now have a `transport` variable that can be used either to dial nodes or listen to
// incoming connections, and that will automatically apply secio and multiplex on top
// of any opened stream.
// We now prepare the protocol that we are going to negotiate with nodes that open a connection
// or substream to our server.
let my_id = {
let key = (0..2048).map(|_| rand::random::<u8>()).collect::<Vec<_>>();
PeerId::from_public_key(PublicKey::Rsa(key))
};
let (floodsub_upgrade, floodsub_rx) = libp2p::floodsub::FloodSubUpgrade::new(my_id);
// Let's put this `transport` into a *swarm*. The swarm will handle all the incoming and
// outgoing connections for us.
let (swarm_controller, swarm_future) = libp2p::core::swarm(
transport.clone().with_upgrade(floodsub_upgrade.clone()),
|socket, _| {
println!("Successfully negotiated protocol");
socket
},
);
let address = swarm_controller
.listen_on(listen_addr.parse().expect("invalid multiaddr"))
.expect("unsupported multiaddr");
println!("Now listening on {:?}", address);
let topic = libp2p::floodsub::TopicBuilder::new("chat").build();
let floodsub_ctl = libp2p::floodsub::FloodSubController::new(&floodsub_upgrade);
floodsub_ctl.subscribe(&topic);
let floodsub_rx = floodsub_rx.for_each(|msg| {
if let Ok(msg) = String::from_utf8(msg.data) {
println!("< {}", msg);
}
Ok(())
});
let stdin = {
let mut buffer = Vec::new();
tokio_stdin::spawn_stdin_stream_unbounded().for_each(move |msg| {
if msg != b'\r' && msg != b'\n' {
buffer.push(msg);
return Ok(());
} else if buffer.is_empty() {
return Ok(());
}
let msg = String::from_utf8(mem::replace(&mut buffer, Vec::new())).unwrap();
if msg.starts_with("/dial ") {
let target: Multiaddr = msg[6..].parse().unwrap();
println!("*Dialing {}*", target);
swarm_controller
.dial(
target,
transport.clone().with_upgrade(floodsub_upgrade.clone()),
)
.unwrap();
} else {
floodsub_ctl.publish(&topic, msg.into_bytes());
}
Ok(())
})
};
let final_fut = swarm_future
.for_each(|_| Ok(()))
.select(floodsub_rx)
.map(|_| ())
.map_err(|e| e.0)
.select(stdin.map_err(|_| unreachable!()))
.map(|_| ())
.map_err(|e| e.0);
tokio_current_thread::block_on_all(final_fut).unwrap();
}

View File

@ -1,292 +0,0 @@
// Copyright 2017 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.
// Libp2p's code unfortunately produces very large types. Rust's default length limit for type
// names is not large enough, therefore we need this attribute.
#![type_length_limit = "4194304"]
extern crate bigint;
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate multiaddr;
use bigint::U512;
use futures::{Future, Stream};
use libp2p::peerstore::{PeerAccess, PeerId, Peerstore};
use multiaddr::Multiaddr;
use std::collections::HashMap;
use std::env;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use libp2p::core::{Transport, PublicKey, UniqueConnec};
use libp2p::core::{upgrade, either::EitherOutput};
use libp2p::kad::{KadConnecConfig, KadConnectionType, KadPeer, KadQueryEvent, KadSystem};
use libp2p::kad::{KadSystemConfig, KadIncomingRequest};
use libp2p::tcp::TcpConfig;
fn main() {
env_logger::init();
// Determine which addresses to listen to.
let listen_addrs = {
let mut args = env::args().skip(1).collect::<Vec<_>>();
if args.is_empty() {
args.push("/ip4/0.0.0.0/tcp/0".to_owned());
}
args
};
let peer_store = Arc::new(libp2p::peerstore::memory_peerstore::MemoryPeerstore::empty());
ipfs_bootstrap(&*peer_store);
// We create a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new()
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
.with_upgrade({
let plain_text = upgrade::PlainTextConfig;
let secio = {
let private_key = include_bytes!("test-rsa-private-key.pk8");
let public_key = include_bytes!("test-rsa-public-key.der").to_vec();
libp2p::secio::SecioConfig::new(
libp2p::secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap()
)
};
upgrade::or(
upgrade::map(plain_text, |pt| EitherOutput::First(pt)),
upgrade::map(secio, |out: libp2p::secio::SecioOutput<_>| EitherOutput::Second(out.stream))
)
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MplexConfig::new())
// The object returned by the call to `with_upgrade(MplexConfig::new())` can't be used as a
// `Transport` because the output of the upgrade is not a stream but a controller for
// muxing. We have to explicitly call `into_connection_reuse()` in order to turn this into
// a `Transport`.
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
let addr_resolver = {
let peer_store = peer_store.clone();
move |peer_id| {
peer_store
.peer(&peer_id)
.into_iter()
.flat_map(|peer| peer.addrs())
.collect::<Vec<_>>()
.into_iter()
}
};
let transport = libp2p::identify::PeerIdTransport::new(transport, addr_resolver)
.and_then({
let peer_store = peer_store.clone();
move |id_out, _, remote_addr| {
let socket = id_out.socket;
let original_addr = id_out.original_addr;
id_out.info.map(move |info| {
let peer_id = info.info.public_key.into_peer_id();
peer_store.peer_or_create(&peer_id).add_addr(original_addr, Duration::from_secs(3600));
(socket, remote_addr)
})
}
});
// We now have a `transport` variable that can be used either to dial nodes or listen to
// incoming connections, and that will automatically apply secio and multiplex on top
// of any opened stream.
let my_peer_id = PeerId::from_public_key(PublicKey::Rsa(include_bytes!("test-rsa-public-key.der").to_vec()));
println!("Local peer id is: {:?}", my_peer_id);
let kad_system = Arc::new(KadSystem::without_init(KadSystemConfig {
parallelism: 3,
local_peer_id: my_peer_id.clone(),
kbuckets_timeout: Duration::from_secs(10),
request_timeout: Duration::from_secs(10),
known_initial_peers: peer_store.peers(),
}));
let active_kad_connections = Arc::new(Mutex::new(HashMap::<_, UniqueConnec<_>>::new()));
// Let's put this `transport` into a *swarm*. The swarm will handle all the incoming and
// outgoing connections for us.
let (swarm_controller, swarm_future) = libp2p::core::swarm(
transport.clone().with_upgrade(KadConnecConfig::new()),
{
let peer_store = peer_store.clone();
let kad_system = kad_system.clone();
let active_kad_connections = active_kad_connections.clone();
move |(kad_ctrl, kad_stream), node_addr| {
let peer_store = peer_store.clone();
let kad_system = kad_system.clone();
let active_kad_connections = active_kad_connections.clone();
node_addr.and_then(move |node_addr| {
let node_id = p2p_multiaddr_to_node_id(node_addr);
let node_id2 = node_id.clone();
let fut = kad_stream.for_each(move |req| {
let peer_store = peer_store.clone();
kad_system.update_kbuckets(node_id2.clone());
match req {
KadIncomingRequest::FindNode { searched, responder } => {
let result = kad_system
.known_closest_peers(&searched)
.map(move |peer_id| {
let addrs = peer_store
.peer(&peer_id)
.into_iter()
.flat_map(|p| p.addrs())
.collect::<Vec<_>>();
KadPeer {
node_id: peer_id.clone(),
multiaddrs: addrs,
connection_ty: KadConnectionType::Connected, // meh :-/
}
})
.collect::<Vec<_>>();
responder.respond(result);
},
KadIncomingRequest::GetProviders { .. } => {
},
KadIncomingRequest::AddProvider { .. } => {
},
KadIncomingRequest::PingPong => {
}
};
Ok(())
});
let mut active_kad_connections = active_kad_connections.lock().unwrap();
active_kad_connections
.entry(node_id)
.or_insert_with(Default::default)
.tie_or_passthrough(kad_ctrl, fut)
})
}
}
);
for listen_addr in listen_addrs {
let addr = swarm_controller
.listen_on(listen_addr.parse().expect("invalid multiaddr"))
.expect("unsupported multiaddr");
println!("Now listening on {:?}", addr);
}
let finish_enum = kad_system
.find_node(my_peer_id.clone(), |peer| {
let addr = Multiaddr::from(libp2p::multiaddr::Protocol::P2p(peer.clone().into()));
active_kad_connections.lock().unwrap().entry(peer.clone())
.or_insert_with(Default::default)
.dial(&swarm_controller, &addr, transport.clone().with_upgrade(KadConnecConfig::new()))
})
.filter_map(move |event| {
match event {
KadQueryEvent::PeersReported(peers) => {
for peer in peers {
peer_store.peer_or_create(&peer.node_id)
.add_addrs(peer.multiaddrs, Duration::from_secs(3600));
}
None
},
KadQueryEvent::Finished(out) => Some(out),
}
})
.into_future()
.map_err(|(err, _)| err)
.map(|(out, _)| out.unwrap())
.and_then(|out| {
let local_hash = U512::from(my_peer_id.digest());
println!("Results of peer discovery for {:?}:", my_peer_id);
for n in out {
let other_hash = U512::from(n.digest());
let dist = 512 - (local_hash ^ other_hash).leading_zeros();
println!("* {:?} (distance bits = {:?} (lower is better))", n, dist);
}
Ok(())
});
// `swarm_future` is a future that contains all the behaviour that we want, but nothing has
// actually started yet. Because we created the `TcpConfig` with tokio, we need to run the
// future through the tokio core.
tokio_current_thread::block_on_all(
finish_enum
.select(swarm_future.for_each(|_| Ok(())))
.map(|(n, _)| n)
.map_err(|(err, _)| err),
).unwrap();
}
/// Expects a multiaddr of the format `/p2p/<node_id>` and returns the node ID.
/// Panics if the format is not correct.
fn p2p_multiaddr_to_node_id(client_addr: Multiaddr) -> PeerId {
let (first, second);
{
let mut iter = client_addr.iter();
first = iter.next();
second = iter.next();
}
match (first, second) {
(Some(libp2p::multiaddr::Protocol::P2p(node_id)), None) =>
PeerId::from_multihash(node_id).expect("libp2p always reports a valid node id"),
_ => panic!("Reported multiaddress is in the wrong format ; programmer error")
}
}
/// Stores initial addresses on the given peer store. Uses a very large timeout.
pub fn ipfs_bootstrap<P>(peer_store: P)
where
P: Peerstore + Clone,
{
const ADDRESSES: &[&str] = &[
"/ip4/127.0.0.1/tcp/4001/p2p/QmQRx32wQkw3hB45j4UDw8V9Ju4mGbxMyhs2m8mpFrFkur",
// TODO: add some bootstrap nodes here
];
let ttl = Duration::from_secs(100 * 365 * 24 * 3600);
for address in ADDRESSES.iter() {
let mut multiaddr = address
.parse::<Multiaddr>()
.expect("failed to parse hard-coded multiaddr");
let p2p_component = multiaddr.pop().expect("hard-coded multiaddr is empty");
let peer = match p2p_component {
libp2p::multiaddr::Protocol::P2p(key) => {
PeerId::from_multihash(key).expect("invalid peer id")
}
_ => panic!("hard-coded multiaddr didn't end with /p2p/"),
};
peer_store
.clone()
.peer_or_create(&peer)
.add_addr(multiaddr, ttl.clone());
}
}

View File

@ -1,123 +0,0 @@
// Copyright 2017 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.
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate tokio_current_thread;
extern crate tokio_io;
use futures::{Future, Stream};
use futures::sync::oneshot;
use std::env;
use libp2p::core::Transport;
use libp2p::core::{upgrade, either::EitherOutput};
use libp2p::tcp::TcpConfig;
fn main() {
env_logger::init();
// Determine which address to dial.
let target_addr = env::args()
.nth(1)
.unwrap_or("/ip4/127.0.0.1/tcp/4001".to_owned());
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new()
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
.with_upgrade({
let plain_text = upgrade::PlainTextConfig;
let secio = {
let private_key = include_bytes!("test-rsa-private-key.pk8");
let public_key = include_bytes!("test-rsa-public-key.der").to_vec();
libp2p::secio::SecioConfig::new(
libp2p::secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap()
)
};
upgrade::or(
upgrade::map(plain_text, |pt| EitherOutput::First(pt)),
upgrade::map(secio, |out: libp2p::secio::SecioOutput<_>| EitherOutput::Second(out.stream))
)
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MplexConfig::new())
// The object returned by the call to `with_upgrade(MplexConfig::new())` can't be used as a
// `Transport` because the output of the upgrade is not a stream but a controller for
// muxing. We have to explicitly call `into_connection_reuse()` in order to turn this into
// a `Transport`.
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
// Let's put this `transport` into a *swarm*. The swarm will handle all the incoming
// connections for us. The second parameter we pass is the connection upgrade that is accepted
// by the listening part. We don't want to accept anything, so we pass a dummy object that
// represents a connection that is always denied.
let (tx, rx) = oneshot::channel();
let mut tx = Some(tx);
let (swarm_controller, swarm_future) = libp2p::core::swarm(
transport.clone().with_upgrade(libp2p::ping::Ping::default()),
|out, _client_addr| {
if let libp2p::ping::PingOutput::Pinger(mut pinger) = out {
let tx = tx.take();
pinger.ping(());
pinger
.into_future()
.map(move |_| {
println!("Received pong from the remote");
if let Some(tx) = tx {
let _ = tx.send(());
}
()
})
.map_err(|(e, _)| e)
} else {
unreachable!()
}
},
);
// We now use the controller to dial to the address.
swarm_controller
.dial(target_addr.parse().expect("invalid multiaddr"),
transport.with_upgrade(libp2p::ping::Ping::default()))
// If the multiaddr protocol exists but is not supported, then we get an error containing
// the original multiaddress.
.expect("unsupported multiaddr");
// The address we actually listen on can be different from the address that was passed to
// the `listen_on` function. For example if you pass `/ip4/0.0.0.0/tcp/0`, then the port `0`
// will be replaced with the actual port.
// `swarm_future` is a future that contains all the behaviour that we want, but nothing has
// actually started yet. Because we created the `TcpConfig` with tokio, we need to run the
// future through the tokio core.
tokio_current_thread::block_on_all(
rx.select(swarm_future.for_each(|_| Ok(())).map_err(|_| unreachable!()))
.map_err(|(e, _)| e)
.map(|_| ()),
).unwrap();
}

View File

@ -1,32 +0,0 @@
// 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.
extern crate libp2p;
extern crate rand;
use libp2p::{PeerId, core::PublicKey};
fn main() {
let pid = {
let key = (0..2048).map(|_| rand::random::<u8>()).collect::<Vec<_>>();
PeerId::from_public_key(PublicKey::Rsa(key))
};
println!("{}", pid.to_base58());
}

View File

@ -1,224 +0,0 @@
// 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.
//! Example runs
//! ============
//!
//! As destination
//! --------------
//!
//! relay listen \
//! --self "QmcwnUP8cM2U4EeMW6g6nbFUQRyE6xXh65TPaZD9bqkhdK" \
//! --listen "/ip4/127.0.0.1/tcp/10003" \
//! --peer "QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL=/ip4/127.0.0.1/tcp/10002"
//!
//! As relay
//! --------
//!
//! relay listen \
//! --self "QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL" \
//! --listen "/ip4/127.0.0.1/tcp/10002" \
//! --peer "QmcwnUP8cM2U4EeMW6g6nbFUQRyE6xXh65TPaZD9bqkhdK=/ip4/127.0.0.1/tcp/10003"
//!
//! As source
//! ---------
//!
//! relay dial \
//! --self "QmYJ46WjbwxLkrTGU1JZNEN3HnYbcuES8QahG1PAMCxFY8" \
//! --destination "QmcwnUP8cM2U4EeMW6g6nbFUQRyE6xXh65TPaZD9bqkhdK" \
//! --relay "QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL" \
//! --peer "QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL=/ip4/127.0.0.1/tcp/10002"
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate libp2p;
extern crate libp2p_yamux;
extern crate rand;
#[macro_use]
extern crate structopt;
extern crate tokio_codec;
extern crate tokio_current_thread;
use libp2p::SimpleProtocol;
use libp2p::core::Multiaddr;
use libp2p::core::transport::Transport;
use libp2p::core::upgrade;
use futures::{future::{self, Either, Loop, loop_fn}, prelude::*};
use libp2p::peerstore::{PeerAccess, PeerId, Peerstore, memory_peerstore::MemoryPeerstore};
use libp2p::relay::{RelayConfig, RelayTransport};
use std::{error::Error, iter, str::FromStr, sync::Arc, time::Duration};
use structopt::StructOpt;
use libp2p::tcp::TcpConfig;
use tokio_codec::{BytesCodec, Framed};
fn main() -> Result<(), Box<Error>> {
env_logger::init();
match Options::from_args() {
Options::Dialer(opts) => run_dialer(opts),
Options::Listener(opts) => run_listener(opts)
}
}
#[derive(Debug, StructOpt)]
#[structopt(name = "relay", about = "Usage example for /libp2p/relay/circuit/0.1.0")]
enum Options {
#[structopt(name = "dial")]
/// Run in dial mode.
Dialer(DialerOpts),
#[structopt(name = "listen")]
/// Run in listener mode.
Listener(ListenerOpts)
}
#[derive(Debug, StructOpt)]
struct DialerOpts {
#[structopt(short = "s", long = "self", parse(try_from_str))]
/// The PeerId of this node.
me: PeerId,
#[structopt(short = "d", long = "destination", parse(try_from_str))]
/// The PeerId to dial.
dest: PeerId,
#[structopt(short = "r", long = "relay", parse(try_from_str))]
/// The PeerId of the relay node to use when dialing the destination.
relay: PeerId,
#[structopt(short = "p", long = "peer", parse(try_from_str = "parse_peer_addr"))]
/// A network peer known to this node (format: PeerId=Multiaddr).
/// For example: QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL=/ip4/127.0.0.1/tcp/12345
peers: Vec<(PeerId, Multiaddr)>
}
#[derive(Debug, StructOpt)]
struct ListenerOpts {
#[structopt(short = "s", long = "self", parse(try_from_str))]
/// The PeerId of this node.
me: PeerId,
#[structopt(short = "p", long = "peer", parse(try_from_str = "parse_peer_addr"))]
/// A network peer know to this node (format: PeerId=Multiaddr).
/// For example: QmXnxVaQoP8cPm2J5uN73GPEu3pCkJdYDNDCMZS8dMxTXL=/ip4/127.0.0.1/tcp/12345
peers: Vec<(PeerId, Multiaddr)>,
#[structopt(short = "l", long = "listen", parse(try_from_str))]
/// The multiaddress to listen for incoming connections.
listen: Multiaddr
}
fn run_dialer(opts: DialerOpts) -> Result<(), Box<Error>> {
let store = Arc::new(MemoryPeerstore::empty());
for (p, a) in opts.peers {
store.peer_or_create(&p).add_addr(a, Duration::from_secs(600))
}
let transport = {
let tcp = TcpConfig::new()
.with_upgrade(libp2p_yamux::Config::default())
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
RelayTransport::new(opts.me, tcp, store, iter::once(opts.relay)).with_dummy_muxing()
};
let echo = SimpleProtocol::new("/echo/1.0.0", |socket| {
Ok(Framed::new(socket, BytesCodec::new()))
});
let (control, future) = libp2p::core::swarm(transport.clone().with_upgrade(echo.clone()), |socket, _| {
println!("sending \"hello world\"");
socket.send("hello world".into())
.and_then(|socket| socket.into_future().map_err(|(e, _)| e).map(|(m, _)| m))
.and_then(|message| {
println!("received message: {:?}", message);
Ok(())
})
});
let address = format!("/p2p-circuit/p2p/{}", opts.dest.to_base58()).parse()?;
control.dial(address, transport.with_upgrade(echo)).map_err(|_| "failed to dial")?;
tokio_current_thread::block_on_all(future.for_each(|_| Ok(()))).map_err(From::from)
}
fn run_listener(opts: ListenerOpts) -> Result<(), Box<Error>> {
let store = Arc::new(MemoryPeerstore::empty());
for (p, a) in opts.peers {
store.peer_or_create(&p).add_addr(a, Duration::from_secs(600))
}
let transport = TcpConfig::new()
.with_upgrade(libp2p_yamux::Config::default())
.map(|val, _| ((), val))
.into_connection_reuse()
.map(|((), val), _| val);
let relay = RelayConfig::new(opts.me, transport.clone(), store);
let echo = SimpleProtocol::new("/echo/1.0.0", |socket| {
Ok(Framed::new(socket, BytesCodec::new()))
});
let upgraded = transport.with_upgrade(relay)
.and_then(|out, endpoint, addr| {
match out {
libp2p::relay::Output::Sealed(future) => {
Either::A(future.map(|out| (Either::A(out), Either::A(addr))))
}
libp2p::relay::Output::Stream(socket) => {
Either::B(upgrade::apply(socket, echo, endpoint, addr)
.map(|(out, addr)| (Either::B(out), Either::B(addr))))
}
}
});
let (control, future) = libp2p::core::swarm(upgraded, |out, _| {
match out {
Either::A(()) => Either::A(future::ok(())),
Either::B(socket) => Either::B(loop_fn(socket, move |socket| {
socket.into_future()
.map_err(|(e, _)| e)
.and_then(move |(msg, socket)| {
if let Some(msg) = msg {
println!("received at destination: {:?}", msg);
Either::A(socket.send(msg.freeze()).map(Loop::Continue))
} else {
println!("received EOF at destination");
Either::B(future::ok(Loop::Break(())))
}
})
}))
}
});
control.listen_on(opts.listen).map_err(|_| "failed to listen")?;
tokio_current_thread::block_on_all(future.for_each(|_| Ok(()))).map_err(From::from)
}
// Custom parsers ///////////////////////////////////////////////////////////
fn parse_peer_addr(s: &str) -> Result<(PeerId, Multiaddr), Box<Error>> {
let mut iter = s.splitn(2, '=');
let p = iter.next()
.and_then(|s| PeerId::from_str(s).ok())
.ok_or("missing or invalid PeerId")?;
let m = iter.next()
.and_then(|s| Multiaddr::from_str(s).ok())
.ok_or("missing or invalid Multiaddr")?;
Ok((p, m))
}

Binary file not shown.

Binary file not shown.