rust-libp2p/libp2p/examples/echo-dialer.rs

139 lines
6.4 KiB
Rust
Raw Normal View History

2017-11-02 11:58:02 +01:00
// 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
2017-11-02 11:58:02 +01:00
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
2017-11-02 11:58:02 +01:00
// 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
2017-11-02 11:58:02 +01:00
// DEALINGS IN THE SOFTWARE.
extern crate bytes;
2018-03-15 16:56:55 +01:00
extern crate env_logger;
2017-11-02 11:58:02 +01:00
extern crate futures;
extern crate libp2p;
2018-06-22 16:12:23 +02:00
extern crate tokio_codec;
2018-07-16 12:15:27 +02:00
extern crate tokio_current_thread;
2017-11-02 11:58:02 +01:00
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;
2018-06-22 16:12:23 +02:00
use tokio_codec::{BytesCodec, Framed};
use libp2p::websocket::WsConfig;
2017-11-02 11:58:02 +01:00
fn main() {
2018-03-15 16:56:55 +01:00
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());
2017-12-07 18:06:38 +01:00
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
2018-07-16 12:15:27 +02:00
let transport = TcpConfig::new()
2018-01-02 15:22:55 +01:00
// 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.
2018-07-16 12:15:27 +02:00
.or_transport(WsConfig::new(TcpConfig::new()))
2018-01-02 15:22:55 +01:00
2017-12-07 18:06:38 +01:00
// 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 {
key: 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))
)
2017-12-07 18:06:38 +01:00
})
// On top of plaintext or secio, we will use the multiplex protocol.
.with_upgrade(libp2p::mplex::MultiplexConfig::new())
// The object returned by the call to `with_upgrade(MultiplexConfig::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`.
2017-12-18 12:29:21 +01:00
.into_connection_reuse();
2018-01-04 17:18:49 +01:00
// 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.
2018-06-22 16:12:23 +02:00
Ok(Framed::new(socket, BytesCodec::new()))
2018-01-04 17:18:49 +01:00
});
2017-12-18 15:55:49 +01:00
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| {
2018-01-04 17:18:49 +01:00
// `echo` is what the closure used when initializing `proto` returns.
2017-12-07 18:06:38 +01:00
// 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();
2017-12-18 12:29:21 +01:00
echo.send("hello world".into())
2018-01-04 17:18:49 +01:00
// Then listening for one message from the remote.
.and_then(|echo| {
echo.into_future().map_err(|(e, _)| e).map(|(n,_ )| n)
2017-11-02 11:58:02 +01:00
})
.and_then(move |message| {
2018-01-04 17:18:49 +01:00
println!("Received message from listener: {:?}", message.unwrap());
if let Some(finished_tx) = finished_tx {
finished_tx.send(()).unwrap();
}
2018-01-04 17:18:49 +01:00
Ok(())
})
},
);
// We now use the controller to dial to the address.
swarm_controller
.dial(target_addr.parse().expect("invalid multiaddr"), transport.with_upgrade(proto))
2018-01-04 17:18:49 +01:00
// 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.
2017-11-02 11:58:02 +01:00
2018-01-04 17:18:49 +01:00
// `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
.select(finished_rx.map_err(|_| unreachable!()))
.map(|_| ())
.map_err(|(err, _)| err);
2018-07-16 12:15:27 +02:00
tokio_current_thread::block_on_all(final_future).unwrap();
2017-11-02 11:58:02 +01:00
}