hypercore_protocol/lib.rs
1//! ## Introduction
2//!
3//! Hypercore protocol is a streaming, message based protocol. This is a rust port of the wire
4//! protocol implementation in [the original Javascript version][holepunch-hypercore] aiming
5//! for interoperability with LTS version.
6//!
7//! This crate is built on top of the [hypercore] crate, which defines some structs used here.
8//!
9//! ## Design
10//!
11//! This crate does not include any IO related code, it is up to the user to supply a streaming IO
12//! handler that implements the [AsyncRead] and [AsyncWrite] traits.
13//!
14//! When opening a Hypercore protocol stream on an IO handler, the protocol will perform a Noise
15//! handshake followed by libsodium's [crypto_secretstream] to setup a secure and authenticated
16//! connection. After that, each side can request any number of channels on the protocol. A
17//! channel is opened with a [Key], a 32 byte buffer. Channels are only opened if both peers
18//! opened a channel for the same key. It is automatically verified that both parties know the
19//! key without transmitting the key itself.
20//!
21//! On a channel, the predefined messages, including a custom Extension message, of the Hypercore
22//! protocol can be sent and received.
23//!
24//! ## Features
25//!
26//! ### `sparse` (default)
27//!
28//! When using disk storage for hypercore, clearing values may create sparse files. On by default.
29//!
30//! ### `async-std` (default)
31//!
32//! Use the async-std runtime, on by default. Either this or `tokio` is mandatory.
33//!
34//! ### `tokio`
35//!
36//! Use the tokio runtime. Either this or `async_std` is mandatory.
37//!
38//! ### `wasm-bindgen`
39//!
40//! Enable for WASM runtime support.
41//!
42//! ### `cache`
43//!
44//! Use a moka cache for hypercore's merkle tree nodes to speed-up reading.
45//!
46//! ## Example
47//!
48//! The following example opens a TCP server on localhost and connects to that server. Both ends
49//! then open a channel with the same key and exchange a message.
50//!
51//! ```no_run
52//! # async_std::task::block_on(async {
53//! use hypercore_protocol::{ProtocolBuilder, Event, Message};
54//! use hypercore_protocol::schema::*;
55//! use async_std::prelude::*;
56//! // Start a tcp server.
57//! let listener = async_std::net::TcpListener::bind("localhost:8000").await.unwrap();
58//! async_std::task::spawn(async move {
59//! let mut incoming = listener.incoming();
60//! while let Some(Ok(stream)) = incoming.next().await {
61//! async_std::task::spawn(async move {
62//! onconnection(stream, false).await
63//! });
64//! }
65//! });
66//!
67//! // Connect a client.
68//! let stream = async_std::net::TcpStream::connect("localhost:8000").await.unwrap();
69//! onconnection(stream, true).await;
70//!
71//! /// Start Hypercore protocol on a TcpStream.
72//! async fn onconnection (stream: async_std::net::TcpStream, is_initiator: bool) {
73//! // A peer either is the initiator or a connection or is being connected to.
74//! let name = if is_initiator { "dialer" } else { "listener" };
75//! // A key for the channel we want to open. Usually, this is a pre-shared key that both peers
76//! // know about.
77//! let key = [3u8; 32];
78//! // Create the protocol.
79//! let mut protocol = ProtocolBuilder::new(is_initiator).connect(stream);
80//!
81//! // Iterate over the protocol events. This is required to "drive" the protocol.
82//!
83//! while let Some(Ok(event)) = protocol.next().await {
84//! eprintln!("{} received event {:?}", name, event);
85//! match event {
86//! // The handshake event is emitted after the protocol is fully established.
87//! Event::Handshake(_remote_key) => {
88//! protocol.open(key.clone()).await;
89//! },
90//! // A Channel event is emitted for each established channel.
91//! Event::Channel(mut channel) => {
92//! // A Channel can be sent to other tasks.
93//! async_std::task::spawn(async move {
94//! // A Channel can both send messages and is a stream of incoming messages.
95//! channel.send(Message::Want(Want { start: 0, length: 1 })).await;
96//! while let Some(message) = channel.next().await {
97//! eprintln!("{} received message: {:?}", name, message);
98//! }
99//! });
100//! },
101//! _ => {}
102//! }
103//! }
104//! }
105//! # })
106//! ```
107//!
108//! Find more examples in the [Github repository][examples].
109//!
110//! [holepunch-hypercore]: https://github.com/holepunchto/hypercore
111//! [datrs-hypercore]: https://github.com/datrs/hypercore
112//! [AsyncRead]: futures_lite::AsyncRead
113//! [AsyncWrite]: futures_lite::AsyncWrite
114//! [examples]: https://github.com/datrs/hypercore-protocol-rs#examples
115
116#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
117#![deny(missing_debug_implementations, nonstandard_style)]
118#![warn(missing_docs, unreachable_pub)]
119
120mod builder;
121mod channels;
122mod constants;
123mod crypto;
124mod duplex;
125mod message;
126mod protocol;
127mod reader;
128mod util;
129mod writer;
130
131/// The wire messages used by the protocol.
132pub mod schema;
133
134pub use builder::Builder as ProtocolBuilder;
135pub use channels::Channel;
136// Export the needed types for Channel::take_receiver, and Channel::local_sender()
137pub use async_channel::{
138 Receiver as ChannelReceiver, SendError as ChannelSendError, Sender as ChannelSender,
139};
140pub use duplex::Duplex;
141pub use hypercore; // Re-export hypercore
142pub use message::Message;
143pub use protocol::{Command, CommandTx, DiscoveryKey, Event, Key, Protocol};
144pub use util::discovery_key;