feat(noise): deprecate all handshake patterns apart from XX

In the libp2p specs, the only handshake pattern that is specified is the XX handshake. Support for other handshake patterns can be added through external modules. While we are at it, we rename the remaining types to following the laid out naming convention.

The tests for handshakes other than XX are removed. The handshakes still work as we don't touch them in this patch.

Related #2217.

Pull-Request: #3768.
This commit is contained in:
Thomas Eizinger
2023-04-28 15:50:31 +02:00
committed by GitHub
parent 99ad3b6eaf
commit 2f5270ba76
40 changed files with 299 additions and 329 deletions

2
Cargo.lock generated
View File

@ -2684,7 +2684,7 @@ dependencies = [
[[package]]
name = "libp2p-noise"
version = "0.42.1"
version = "0.42.2"
dependencies = [
"async-io",
"bytes",

View File

@ -81,7 +81,7 @@ fn upgrade_pipeline() {
let listener_id = listener_keys.public().to_peer_id();
let mut listener_transport = MemoryTransport::default()
.upgrade(upgrade::Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&listener_keys).unwrap())
.authenticate(noise::Config::new(&listener_keys).unwrap())
.apply(HelloUpgrade {})
.apply(HelloUpgrade {})
.apply(HelloUpgrade {})
@ -92,7 +92,7 @@ fn upgrade_pipeline() {
let dialer_id = dialer_keys.public().to_peer_id();
let mut dialer_transport = MemoryTransport::default()
.upgrade(upgrade::Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&dialer_keys).unwrap())
.authenticate(noise::Config::new(&dialer_keys).unwrap())
.apply(HelloUpgrade {})
.apply(HelloUpgrade {})
.apply(HelloUpgrade {})

View File

@ -64,7 +64,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key)?)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -53,7 +53,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key)?)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -77,9 +77,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Set up an encrypted DNS-enabled TCP Transport over the Mplex protocol.
let tcp_transport = tcp::async_io::Transport::new(tcp::Config::default().nodelay(true))
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::NoiseAuthenticated::xx(&id_keys).expect("signing libp2p-noise static keypair"),
)
.authenticate(noise::Config::new(&id_keys).expect("signing libp2p-noise static keypair"))
.multiplex(yamux::YamuxConfig::default())
.timeout(std::time::Duration::from_secs(20))
.boxed();

View File

@ -98,8 +98,7 @@ fn main() -> Result<(), Box<dyn Error>> {
)
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
noise::Config::new(&local_key).expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -65,7 +65,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key)?)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -49,7 +49,7 @@ pub(crate) async fn new(
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&id_keys)?)
.authenticate(noise::Config::new(&id_keys)?)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -53,7 +53,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key).unwrap())
.authenticate(noise::Config::new(&local_key).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -52,7 +52,7 @@ pub fn build_transport(
key_pair: identity::Keypair,
psk: Option<PreSharedKey>,
) -> transport::Boxed<(PeerId, StreamMuxerBox)> {
let noise_config = noise::NoiseAuthenticated::xx(&key_pair).unwrap();
let noise_config = noise::Config::new(&key_pair).unwrap();
let yamux_config = YamuxConfig::default();
let base_transport = tcp::async_io::Transport::new(tcp::Config::default().nodelay(true));

View File

@ -74,7 +74,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut swarm = SwarmBuilder::without_executor(
tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key)?)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::YamuxConfig::default())
.boxed(),
Behaviour::new(local_pub_key),

View File

@ -57,7 +57,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&local_key)?)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -51,8 +51,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let transport = tcp_transport
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
noise::Config::new(&local_key).expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(libp2p::yamux::YamuxConfig::default())
.boxed();

View File

@ -44,7 +44,7 @@ async fn main() {
let mut swarm = SwarmBuilder::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.authenticate(noise::Config::new(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {

View File

@ -40,7 +40,7 @@ async fn main() {
let mut swarm = SwarmBuilder::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.authenticate(noise::Config::new(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {

View File

@ -40,7 +40,7 @@ async fn main() {
let mut swarm = SwarmBuilder::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.authenticate(noise::Config::new(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {

View File

@ -54,7 +54,7 @@ async fn main() {
let mut swarm = SwarmBuilder::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.authenticate(noise::Config::new(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {

View File

@ -61,10 +61,7 @@ async fn main() -> Result<()> {
(Transport::Tcp, Ok(SecProtocol::Noise)) => (
tcp::tokio::Transport::new(tcp::Config::new())
.upgrade(Version::V1Lazy)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.context("failed to intialise noise")?,
)
.authenticate(noise::Config::new(&local_key).context("failed to intialise noise")?)
.multiplex(muxer_protocol_from_env()?)
.timeout(Duration::from_secs(5))
.boxed(),
@ -82,10 +79,7 @@ async fn main() -> Result<()> {
(Transport::Ws, Ok(SecProtocol::Noise)) => (
WsConfig::new(tcp::tokio::Transport::new(tcp::Config::new()))
.upgrade(Version::V1Lazy)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.context("failed to intialise noise")?,
)
.authenticate(noise::Config::new(&local_key).context("failed to intialise noise")?)
.multiplex(muxer_protocol_from_env()?)
.timeout(Duration::from_secs(5))
.boxed(),

View File

@ -107,7 +107,7 @@ libp2p-identity = { version = "0.1.0", path = "../identity" }
libp2p-kad = { version = "0.43.0", path = "../protocols/kad", optional = true }
libp2p-metrics = { version = "0.12.0", path = "../misc/metrics", optional = true }
libp2p-mplex = { version = "0.39.0", path = "../muxers/mplex", optional = true }
libp2p-noise = { version = "0.42.0", path = "../transports/noise", optional = true }
libp2p-noise = { version = "0.42.2", path = "../transports/noise", optional = true }
libp2p-ping = { version = "0.42.0", path = "../protocols/ping", optional = true }
libp2p-plaintext = { version = "0.39.0", path = "../transports/plaintext", optional = true }
libp2p-pnet = { version = "0.22.2", path = "../transports/pnet", optional = true }

View File

@ -231,7 +231,7 @@ pub async fn development_transport(
Ok(transport
.upgrade(core::upgrade::Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&keypair).unwrap())
.authenticate(noise::Config::new(&keypair).unwrap())
.multiplex(core::upgrade::SelectUpgrade::new(
yamux::YamuxConfig::default(),
#[allow(deprecated)]
@ -288,7 +288,7 @@ pub fn tokio_development_transport(
Ok(transport
.upgrade(core::upgrade::Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&keypair).unwrap())
.authenticate(noise::Config::new(&keypair).unwrap())
.multiplex(core::upgrade::SelectUpgrade::new(
yamux::YamuxConfig::default(),
#[allow(deprecated)]

View File

@ -564,13 +564,10 @@ mod tests {
transport::Boxed<(PeerId, StreamMuxerBox)>,
) {
let id_keys = identity::Keypair::generate_ed25519();
let noise_keys = noise::Keypair::<noise::X25519Spec>::new()
.into_authentic(&id_keys)
.unwrap();
let pubkey = id_keys.public();
let transport = tcp::async_io::Transport::new(tcp::Config::default().nodelay(true))
.upgrade(upgrade::Version::V1)
.authenticate(noise::NoiseConfig::xx(noise_keys).into_authenticated())
.authenticate(noise::Config::new(&id_keys).unwrap())
.multiplex(MplexConfig::new())
.boxed();
(pubkey, transport)

View File

@ -59,7 +59,7 @@ fn build_node_with_config(cfg: KademliaConfig) -> (Multiaddr, TestSwarm) {
let local_public_key = local_key.public();
let transport = MemoryTransport::default()
.upgrade(upgrade::Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&local_key).unwrap())
.authenticate(noise::Config::new(&local_key).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed();

View File

@ -20,7 +20,7 @@ instant = "0.1.11"
libp2p-core = { version = "0.39.0", path = "../../core" }
libp2p-dns = { version = "0.39.0", path = "../../transports/dns", features = ["async-std"] }
libp2p-identity = { version = "0.1.0", path = "../../identity" }
libp2p-noise = { version = "0.42.0", path = "../../transports/noise" }
libp2p-noise = { version = "0.42.2", path = "../../transports/noise" }
libp2p-quic = { version = "0.7.0-alpha.2", path = "../../transports/quic", features = ["async-std"] }
libp2p-swarm = { version = "0.42.1", path = "../../swarm", features = ["macros", "async-std"] }
libp2p-tcp = { version = "0.39.0", path = "../../transports/tcp", features = ["async-io"] }

View File

@ -52,7 +52,7 @@ async fn main() -> Result<()> {
libp2p_tcp::async_io::Transport::new(libp2p_tcp::Config::default().port_reuse(true))
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
libp2p_noise::NoiseAuthenticated::xx(&local_key)
libp2p_noise::Config::new(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(libp2p_yamux::YamuxConfig::default());

View File

@ -46,7 +46,7 @@ async fn main() {
libp2p_tcp::async_io::Transport::new(libp2p_tcp::Config::default().port_reuse(true))
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
libp2p_noise::NoiseAuthenticated::xx(&local_key)
libp2p_noise::Config::new(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(libp2p_yamux::YamuxConfig::default());

View File

@ -1,3 +1,13 @@
## 0.42.2 - unreleased
- Deprecate all noise handshakes apart from XX.
This deprecates `NoiseConfig` and `NoiseAuthenticated` in favor of a new `libp2p_noise::Config` struct.
In addition, we deprecate all types with a `Noise` prefix.
Users are encouraged to import the `noise` module and refer to types as `noise::Error` etc.
See [PR 3768].
[PR 3768]: https://github.com/libp2p/rust-libp2p/pull/3768
## 0.42.1
- Migrate from `prost` to `quick-protobuf`. This removes `protoc` dependency. See [PR 3312].

View File

@ -3,7 +3,7 @@ name = "libp2p-noise"
edition = "2021"
rust-version = "1.60.0"
description = "Cryptographic handshake protocol using the noise framework."
version = "0.42.1"
version = "0.42.2"
authors = ["Parity Technologies <admin@parity.io>"]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"

View File

@ -37,7 +37,7 @@ use std::{
/// A noise session to a remote.
///
/// `T` is the type of the underlying I/O resource.
pub struct NoiseOutput<T> {
pub struct Output<T> {
io: NoiseFramed<T, snow::TransportState>,
recv_buffer: Bytes,
recv_offset: usize,
@ -45,15 +45,15 @@ pub struct NoiseOutput<T> {
send_offset: usize,
}
impl<T> fmt::Debug for NoiseOutput<T> {
impl<T> fmt::Debug for Output<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NoiseOutput").field("io", &self.io).finish()
}
}
impl<T> NoiseOutput<T> {
impl<T> Output<T> {
fn new(io: NoiseFramed<T, snow::TransportState>) -> Self {
NoiseOutput {
Output {
io,
recv_buffer: Bytes::new(),
recv_offset: 0,
@ -63,7 +63,7 @@ impl<T> NoiseOutput<T> {
}
}
impl<T: AsyncRead + Unpin> AsyncRead for NoiseOutput<T> {
impl<T: AsyncRead + Unpin> AsyncRead for Output<T> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
@ -99,7 +99,7 @@ impl<T: AsyncRead + Unpin> AsyncRead for NoiseOutput<T> {
}
}
impl<T: AsyncWrite + Unpin> AsyncWrite for NoiseOutput<T> {
impl<T: AsyncWrite + Unpin> AsyncWrite for Output<T> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,

View File

@ -21,8 +21,8 @@
//! This module provides a `Sink` and `Stream` for length-delimited
//! Noise protocol messages in form of [`NoiseFramed`].
use crate::io::NoiseOutput;
use crate::{NoiseError, Protocol, PublicKey};
use crate::io::Output;
use crate::{Error, Protocol, PublicKey};
use bytes::{Bytes, BytesMut};
use futures::prelude::*;
use futures::ready;
@ -89,9 +89,7 @@ impl<T> NoiseFramed<T, snow::HandshakeState> {
/// transitioning to transport mode because the handshake is incomplete,
/// an error is returned. Similarly if the remote's static DH key, if
/// present, cannot be parsed.
pub(crate) fn into_transport<C>(
self,
) -> Result<(Option<PublicKey<C>>, NoiseOutput<T>), NoiseError>
pub(crate) fn into_transport<C>(self) -> Result<(Option<PublicKey<C>>, Output<T>), Error>
where
C: Protocol<C> + AsRef<[u8]>,
{
@ -111,7 +109,7 @@ impl<T> NoiseFramed<T, snow::HandshakeState> {
decrypt_buffer: self.decrypt_buffer,
};
Ok((dh_remote_pubkey, NoiseOutput::new(io)))
Ok((dh_remote_pubkey, Output::new(io)))
}
}

View File

@ -26,11 +26,11 @@ mod proto {
pub use self::payload::proto::NoiseHandshakePayload;
}
use crate::io::{framed::NoiseFramed, NoiseOutput};
use crate::io::{framed::NoiseFramed, Output};
use crate::protocol::{KeypairIdentity, Protocol, PublicKey};
#[allow(deprecated)]
use crate::Error;
use crate::LegacyConfig;
use crate::NoiseError;
use bytes::Bytes;
use futures::prelude::*;
use libp2p_identity as identity;
@ -38,6 +38,9 @@ use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
use std::io;
/// The identity of the remote established during a handshake.
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub enum RemoteIdentity<C> {
/// The remote provided no identifying information.
///
@ -79,7 +82,6 @@ pub(crate) struct State<T> {
/// The known or received public identity key of the remote, if any.
id_remote_pubkey: Option<identity::PublicKey>,
/// Legacy configuration parameters.
#[allow(deprecated)]
legacy: LegacyConfig,
}
@ -89,7 +91,7 @@ impl<T> State<T> {
/// will be sent and received on the given I/O resource and using the
/// provided session for cryptographic operations according to the chosen
/// Noise handshake pattern.
#[allow(deprecated)]
pub(crate) fn new(
io: T,
session: snow::HandshakeState,
@ -109,8 +111,8 @@ impl<T> State<T> {
impl<T> State<T> {
/// Finish a handshake, yielding the established remote identity and the
/// [`NoiseOutput`] for communicating on the encrypted channel.
pub(crate) fn finish<C>(self) -> Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>
/// [`Output`] for communicating on the encrypted channel.
pub(crate) fn finish<C>(self) -> Result<(RemoteIdentity<C>, Output<T>), Error>
where
C: Protocol<C> + AsRef<[u8]>,
{
@ -122,7 +124,7 @@ impl<T> State<T> {
if C::verify(&id_pk, &dh_pk, &self.dh_remote_pubkey_sig) {
RemoteIdentity::IdentityKey(id_pk)
} else {
return Err(NoiseError::BadSignature);
return Err(Error::BadSignature);
}
}
};
@ -134,7 +136,7 @@ impl<T> State<T> {
// Handshake Message Futures
/// A future for receiving a Noise handshake message.
async fn recv<T>(state: &mut State<T>) -> Result<Bytes, NoiseError>
async fn recv<T>(state: &mut State<T>) -> Result<Bytes, Error>
where
T: AsyncRead + Unpin,
{
@ -146,7 +148,7 @@ where
}
/// A future for receiving a Noise handshake message with an empty payload.
pub(crate) async fn recv_empty<T>(state: &mut State<T>) -> Result<(), NoiseError>
pub(crate) async fn recv_empty<T>(state: &mut State<T>) -> Result<(), Error>
where
T: AsyncRead + Unpin,
{
@ -160,7 +162,7 @@ where
}
/// A future for sending a Noise handshake message with an empty payload.
pub(crate) async fn send_empty<T>(state: &mut State<T>) -> Result<(), NoiseError>
pub(crate) async fn send_empty<T>(state: &mut State<T>) -> Result<(), Error>
where
T: AsyncWrite + Unpin,
{
@ -173,7 +175,7 @@ where
///
/// In case `expected_key` is passed, this function will fail if the received key does not match the expected key.
/// In case the remote does not send us a key, the expected key is assumed to be the remote's key.
pub(crate) async fn recv_identity<T>(state: &mut State<T>) -> Result<(), NoiseError>
pub(crate) async fn recv_identity<T>(state: &mut State<T>) -> Result<(), Error>
where
T: AsyncRead + Unpin,
{
@ -182,7 +184,6 @@ where
let mut reader = BytesReader::from_bytes(&msg[..]);
let mut pb_result = proto::NoiseHandshakePayload::from_reader(&mut reader, &msg[..]);
#[allow(deprecated)]
if pb_result.is_err() && state.legacy.recv_legacy_handshake {
// NOTE: This is support for legacy handshake payloads. As long as
// the frame length is less than 256 bytes, which is the case for
@ -218,7 +219,7 @@ where
let pk = identity::PublicKey::try_decode_protobuf(&pb.identity_key)?;
if let Some(ref k) = state.id_remote_pubkey {
if k != &pk {
return Err(NoiseError::UnexpectedKey);
return Err(Error::UnexpectedKey);
}
}
state.id_remote_pubkey = Some(pk);
@ -232,7 +233,7 @@ where
}
/// Send a Noise handshake message with a payload identifying the local node to the remote.
pub(crate) async fn send_identity<T>(state: &mut State<T>) -> Result<(), NoiseError>
pub(crate) async fn send_identity<T>(state: &mut State<T>) -> Result<(), Error>
where
T: AsyncWrite + Unpin,
{
@ -245,7 +246,6 @@ where
pb.identity_sig = sig.clone()
}
#[allow(deprecated)]
let mut msg = if state.legacy.send_legacy_handshake {
let mut msg = Vec::with_capacity(2 + pb.get_size());
msg.extend_from_slice(&(pb.get_size() as u16).to_be_bytes());
@ -262,7 +262,7 @@ where
}
/// Send a Noise handshake message with a payload identifying the local node to the remote.
pub(crate) async fn send_signature_only<T>(state: &mut State<T>) -> Result<(), NoiseError>
pub(crate) async fn send_signature_only<T>(state: &mut State<T>) -> Result<(), Error>
where
T: AsyncWrite + Unpin,
{
@ -272,7 +272,6 @@ where
pb.identity_sig = sig.clone()
}
#[allow(deprecated)]
let mut msg = if state.legacy.send_legacy_handshake {
let mut msg = Vec::with_capacity(2 + pb.get_size());
msg.extend_from_slice(&(pb.get_size() as u16).to_be_bytes());

View File

@ -41,11 +41,11 @@
//! ```
//! use libp2p_core::{identity, Transport, upgrade};
//! use libp2p_tcp::TcpTransport;
//! use libp2p_noise::{Keypair, X25519Spec, NoiseAuthenticated};
//! use libp2p_noise as noise;
//!
//! # fn main() {
//! let id_keys = identity::Keypair::generate_ed25519();
//! let noise = NoiseAuthenticated::xx(&id_keys).unwrap();
//! let noise = noise::Config::new(&id_keys).unwrap();
//! let builder = TcpTransport::default().upgrade(upgrade::Version::V1).authenticate(noise);
//! // let transport = builder.multiplex(...);
//! # }
@ -54,19 +54,80 @@
//! [noise]: http://noiseprotocol.org/
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![allow(deprecated)] // Temporarily until we remove deprecated items.
mod io;
mod protocol;
pub use io::handshake::RemoteIdentity;
pub use io::NoiseOutput;
#[allow(deprecated)]
pub use protocol::x25519::X25519;
pub use protocol::x25519_spec::X25519Spec;
pub use protocol::{AuthenticKeypair, Keypair, KeypairIdentity, PublicKey, SecretKey};
pub use protocol::{Protocol, ProtocolParams, IK, IX, XX};
use std::fmt;
use std::fmt::Formatter;
pub use io::Output;
pub use protocol::Protocol;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type X25519Spec = protocol::x25519_spec::X25519Spec;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type X25519 = protocol::x25519::X25519;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type AuthenticKeypair<T> = protocol::AuthenticKeypair<T>;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type Keypair<T> = protocol::Keypair<T>;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type KeypairIdentity = protocol::KeypairIdentity;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type PublicKey<T> = protocol::PublicKey<T>;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type SecretKey<T> = protocol::SecretKey<T>;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type ProtocolParams = protocol::ProtocolParams;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type IK = protocol::IK;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type IX = protocol::IX;
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub type XX = protocol::XX;
#[deprecated(
note = "This type has been renamed to drop the `Noise` prefix, refer to it as `noise::Error` instead."
)]
pub type NoiseError = Error;
#[deprecated(
note = "This type has been renamed to drop the `Noise` prefix, refer to it as `noise::Output` instead."
)]
pub type NoiseOutput<T> = Output<T>;
use crate::handshake::State;
use crate::io::handshake;
@ -75,15 +136,79 @@ use futures::prelude::*;
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p_identity as identity;
use libp2p_identity::PeerId;
use std::fmt;
use std::fmt::Formatter;
use std::pin::Pin;
use zeroize::Zeroize;
/// The configuration for the noise handshake.
#[derive(Clone)]
pub struct Config {
inner: NoiseAuthenticated<XX, X25519Spec, ()>,
}
impl Config {
/// Construct a new configuration for the noise handshake using the XX handshake pattern.
pub fn new(identity: &identity::Keypair) -> Result<Self, Error> {
Ok(Config {
inner: NoiseAuthenticated::xx(identity)?,
})
}
/// Set the noise prologue.
pub fn with_prologue(mut self, prologue: Vec<u8>) -> Self {
self.inner.config.prologue = prologue;
self
}
}
impl UpgradeInfo for Config {
type Info = &'static [u8];
type InfoIter = std::iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
std::iter::once(b"/noise")
}
}
impl<T> InboundUpgrade<T> for Config
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = (PeerId, Output<T>);
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_inbound(self, socket: T, info: Self::Info) -> Self::Future {
self.inner.upgrade_inbound(socket, info)
}
}
impl<T> OutboundUpgrade<T> for Config
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = (PeerId, Output<T>);
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_outbound(self, socket: T, info: Self::Info) -> Self::Future {
self.inner.upgrade_outbound(socket, info)
}
}
/// The protocol upgrade configuration.
#[deprecated(
note = "Use `libp2p_noise::Config` instead. All other handshake patterns are deprecated and will be removed."
)]
#[derive(Clone)]
pub struct NoiseConfig<P, C: Zeroize, R = ()> {
dh_keys: AuthenticKeypair<C>,
params: ProtocolParams,
#[allow(deprecated)]
legacy: LegacyConfig,
remote: R,
_marker: std::marker::PhantomData<P>,
@ -114,7 +239,7 @@ impl<H, C: Zeroize, R> NoiseConfig<H, C, R> {
since = "0.42.0",
note = "`LegacyConfig` will be removed without replacement."
)]
#[allow(deprecated)]
pub fn set_legacy_config(&mut self, cfg: LegacyConfig) -> &mut Self {
self.legacy = cfg;
self
@ -124,11 +249,12 @@ impl<H, C: Zeroize, R> NoiseConfig<H, C, R> {
/// Implement `into_responder` and `into_initiator` for all configs where `R = ()`.
///
/// This allows us to ignore the `remote` field.
impl<H, C> NoiseConfig<H, C, ()>
where
C: Zeroize + Protocol<C> + AsRef<[u8]>,
{
fn into_responder<S>(self, socket: S) -> Result<State<S>, NoiseError> {
fn into_responder<S>(self, socket: S) -> Result<State<S>, Error> {
let session = self
.params
.into_builder(&self.prologue, self.dh_keys.keypair.secret(), None)
@ -139,7 +265,7 @@ where
Ok(state)
}
fn into_initiator<S>(self, socket: S) -> Result<State<S>, NoiseError> {
fn into_initiator<S>(self, socket: S) -> Result<State<S>, Error> {
let session = self
.params
.into_builder(&self.prologue, self.dh_keys.keypair.secret(), None)
@ -160,10 +286,7 @@ where
NoiseConfig {
dh_keys,
params: C::params_ix(),
legacy: {
#[allow(deprecated)]
LegacyConfig::default()
},
legacy: { LegacyConfig::default() },
remote: (),
_marker: std::marker::PhantomData,
prologue: Vec::default(),
@ -180,10 +303,7 @@ where
NoiseConfig {
dh_keys,
params: C::params_xx(),
legacy: {
#[allow(deprecated)]
LegacyConfig::default()
},
legacy: { LegacyConfig::default() },
remote: (),
_marker: std::marker::PhantomData,
prologue: Vec::default(),
@ -203,10 +323,7 @@ where
NoiseConfig {
dh_keys,
params: C::params_ik(),
legacy: {
#[allow(deprecated)]
LegacyConfig::default()
},
legacy: { LegacyConfig::default() },
remote: (),
_marker: std::marker::PhantomData,
prologue: Vec::default(),
@ -230,10 +347,7 @@ where
NoiseConfig {
dh_keys,
params: C::params_ik(),
legacy: {
#[allow(deprecated)]
LegacyConfig::default()
},
legacy: { LegacyConfig::default() },
remote: (remote_dh, remote_id),
_marker: std::marker::PhantomData,
prologue: Vec::default(),
@ -241,7 +355,7 @@ where
}
/// Specialised implementation of `into_initiator` for the `IK` handshake where `R != ()`.
fn into_initiator<S>(self, socket: S) -> Result<State<S>, NoiseError> {
fn into_initiator<S>(self, socket: S) -> Result<State<S>, Error> {
let session = self
.params
.into_builder(
@ -266,7 +380,7 @@ where
/// libp2p_noise error type.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NoiseError {
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
@ -302,9 +416,9 @@ impl From<quick_protobuf::Error> for DecodeError {
}
}
impl From<quick_protobuf::Error> for NoiseError {
impl From<quick_protobuf::Error> for Error {
fn from(e: quick_protobuf::Error) -> Self {
NoiseError::InvalidPayload(e.into())
Error::InvalidPayload(e.into())
}
}
@ -318,15 +432,16 @@ impl From<quick_protobuf::Error> for NoiseError {
/// initiator -{id}-> responder
/// initiator <-{id}- responder
/// ```
impl<T, C> InboundUpgrade<T> for NoiseConfig<IX, C>
where
NoiseConfig<IX, C>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_inbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -349,15 +464,16 @@ where
/// initiator -{id}-> responder
/// initiator <-{id}- responder
/// ```
impl<T, C> OutboundUpgrade<T> for NoiseConfig<IX, C>
where
NoiseConfig<IX, C>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_outbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -384,15 +500,16 @@ where
/// initiator <-{id}- responder
/// initiator -{id}-> responder
/// ```
impl<T, C> InboundUpgrade<T> for NoiseConfig<XX, C>
where
NoiseConfig<XX, C>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_inbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -420,15 +537,16 @@ where
/// initiator <-{id}- responder
/// initiator -{id}-> responder
/// ```
impl<T, C> OutboundUpgrade<T> for NoiseConfig<XX, C>
where
NoiseConfig<XX, C>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_outbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -455,15 +573,16 @@ where
/// initiator -{id}-> responder
/// initiator <-{id}- responder
/// ```
impl<T, C> InboundUpgrade<T> for NoiseConfig<IK, C>
where
NoiseConfig<IK, C>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_inbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -489,15 +608,16 @@ where
/// initiator -{id}-> responder
/// initiator <-{id}- responder
/// ```
impl<T, C> OutboundUpgrade<T> for NoiseConfig<IK, C, (PublicKey<C>, identity::PublicKey)>
where
NoiseConfig<IK, C, (PublicKey<C>, identity::PublicKey)>: UpgradeInfo,
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Clone + Send + 'static,
{
type Output = (RemoteIdentity<C>, NoiseOutput<T>);
type Error = NoiseError;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>>;
type Output = (RemoteIdentity<C>, Output<T>);
type Error = Error;
type Future = BoxFuture<'static, Result<(RemoteIdentity<C>, Output<T>), Error>>;
fn upgrade_outbound(self, socket: T, _: Self::Info) -> Self::Future {
async move {
@ -525,6 +645,9 @@ where
/// for creating an [`authenticated`](libp2p_core::transport::upgrade::Authenticate)
/// transport for use with a `Swarm`.
#[derive(Clone)]
#[deprecated(
note = "Use `libp2p_noise::Config` instead. All other handshake patterns are deprecated and will be removed."
)]
pub struct NoiseAuthenticated<P, C: Zeroize, R> {
config: NoiseConfig<P, C, R>,
}
@ -533,7 +656,8 @@ impl NoiseAuthenticated<XX, X25519Spec, ()> {
/// Create a new [`NoiseAuthenticated`] for the `XX` handshake pattern using X25519 DH keys.
///
/// For now, this is the only combination that is guaranteed to be compatible with other libp2p implementations.
pub fn xx(id_keys: &identity::Keypair) -> Result<Self, NoiseError> {
#[deprecated(note = "Use `libp2p_noise::Config::new` instead.")]
pub fn xx(id_keys: &identity::Keypair) -> Result<Self, Error> {
let dh_keys = Keypair::<X25519Spec>::new();
let noise_keys = dh_keys.into_authentic(id_keys)?;
let config = NoiseConfig::xx(noise_keys);
@ -557,14 +681,14 @@ where
impl<T, P, C, R> InboundUpgrade<T> for NoiseAuthenticated<P, C, R>
where
NoiseConfig<P, C, R>: UpgradeInfo
+ InboundUpgrade<T, Output = (RemoteIdentity<C>, NoiseOutput<T>), Error = NoiseError>
+ InboundUpgrade<T, Output = (RemoteIdentity<C>, Output<T>), Error = Error>
+ 'static,
<NoiseConfig<P, C, R> as InboundUpgrade<T>>::Future: Send,
T: AsyncRead + AsyncWrite + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Send + 'static,
{
type Output = (PeerId, NoiseOutput<T>);
type Error = NoiseError;
type Output = (PeerId, Output<T>);
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_inbound(self, socket: T, info: Self::Info) -> Self::Future {
@ -573,7 +697,7 @@ where
.upgrade_inbound(socket, info)
.and_then(|(remote, io)| match remote {
RemoteIdentity::IdentityKey(pk) => future::ok((pk.to_peer_id(), io)),
_ => future::err(NoiseError::AuthenticationFailed),
_ => future::err(Error::AuthenticationFailed),
}),
)
}
@ -582,14 +706,14 @@ where
impl<T, P, C, R> OutboundUpgrade<T> for NoiseAuthenticated<P, C, R>
where
NoiseConfig<P, C, R>: UpgradeInfo
+ OutboundUpgrade<T, Output = (RemoteIdentity<C>, NoiseOutput<T>), Error = NoiseError>
+ OutboundUpgrade<T, Output = (RemoteIdentity<C>, Output<T>), Error = Error>
+ 'static,
<NoiseConfig<P, C, R> as OutboundUpgrade<T>>::Future: Send,
T: AsyncRead + AsyncWrite + Send + 'static,
C: Protocol<C> + AsRef<[u8]> + Zeroize + Send + 'static,
{
type Output = (PeerId, NoiseOutput<T>);
type Error = NoiseError;
type Output = (PeerId, Output<T>);
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_outbound(self, socket: T, info: Self::Info) -> Self::Future {
@ -598,7 +722,7 @@ where
.upgrade_outbound(socket, info)
.and_then(|(remote, io)| match remote {
RemoteIdentity::IdentityKey(pk) => future::ok((pk.to_peer_id(), io)),
_ => future::err(NoiseError::AuthenticationFailed),
_ => future::err(Error::AuthenticationFailed),
}),
)
}

View File

@ -22,7 +22,7 @@
pub(crate) mod x25519;
pub(crate) mod x25519_spec;
use crate::NoiseError;
use crate::Error;
use libp2p_identity as identity;
use rand::SeedableRng;
use zeroize::Zeroize;
@ -68,6 +68,9 @@ pub enum XX {}
/// A Noise protocol over DH keys of type `C`. The choice of `C` determines the
/// protocol parameters for each handshake pattern.
#[deprecated(
note = "This type will be made private in the future. Use `libp2p_noise::Config::new` instead to use the noise protocol."
)]
pub trait Protocol<C> {
/// The protocol parameters for the IK handshake pattern.
fn params_ik() -> ProtocolParams;
@ -77,7 +80,7 @@ pub trait Protocol<C> {
fn params_xx() -> ProtocolParams;
/// Construct a DH public key from a byte slice.
fn public_from_bytes(s: &[u8]) -> Result<PublicKey<C>, NoiseError>;
fn public_from_bytes(s: &[u8]) -> Result<PublicKey<C>, Error>;
/// Determines whether the authenticity of the given DH static public key
/// and public identity key is linked, i.e. that proof of ownership of a
@ -103,7 +106,7 @@ pub trait Protocol<C> {
/// without a signature, otherwise a signature over the static DH public key
/// must be given and is verified with the public identity key, establishing
/// the authenticity of the static DH public key w.r.t. the public identity key.
#[allow(deprecated)]
fn verify(id_pk: &identity::PublicKey, dh_pk: &PublicKey<C>, sig: &Option<Vec<u8>>) -> bool
where
C: AsRef<[u8]>,
@ -114,7 +117,7 @@ pub trait Protocol<C> {
.map_or(false, |s| id_pk.verify(dh_pk.as_ref(), s))
}
fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey<C>) -> Result<Vec<u8>, NoiseError>
fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey<C>) -> Result<Vec<u8>, Error>
where
C: AsRef<[u8]>,
{
@ -175,10 +178,7 @@ impl<T: Zeroize> Keypair<T> {
/// Turn this DH keypair into a [`AuthenticKeypair`], i.e. a DH keypair that
/// is authentic w.r.t. the given identity keypair, by signing the DH public key.
pub fn into_authentic(
self,
id_keys: &identity::Keypair,
) -> Result<AuthenticKeypair<T>, NoiseError>
pub fn into_authentic(self, id_keys: &identity::Keypair) -> Result<AuthenticKeypair<T>, Error>
where
T: AsRef<[u8]>,
T: Protocol<T>,

View File

@ -23,9 +23,7 @@
//! **Note**: This set of protocols is not interoperable with other
//! libp2p implementations.
#![allow(deprecated)]
use crate::{NoiseConfig, NoiseError, Protocol, ProtocolParams};
use crate::{Error, NoiseConfig, Protocol, ProtocolParams};
use curve25519_dalek::edwards::CompressedEdwardsY;
use libp2p_core::UpgradeInfo;
use libp2p_identity as identity;
@ -59,10 +57,6 @@ static PARAMS_XX: Lazy<ProtocolParams> = Lazy::new(|| {
/// A X25519 key.
#[derive(Clone)]
#[deprecated(
since = "0.42.0",
note = "Will be removed because it is not compliant with the official libp2p specification. Use `X25519Spec` instead."
)]
pub struct X25519([u8; 32]);
impl AsRef<[u8]> for X25519 {
@ -122,9 +116,9 @@ impl Protocol<X25519> for X25519 {
PARAMS_XX.clone()
}
fn public_from_bytes(bytes: &[u8]) -> Result<PublicKey<X25519>, NoiseError> {
fn public_from_bytes(bytes: &[u8]) -> Result<PublicKey<X25519>, Error> {
if bytes.len() != 32 {
return Err(NoiseError::InvalidLength);
return Err(Error::InvalidLength);
}
let mut pk = [0u8; 32];
pk.copy_from_slice(bytes);

View File

@ -22,7 +22,7 @@
//!
//! [libp2p-noise-spec]: https://github.com/libp2p/specs/tree/master/noise
use crate::{NoiseConfig, NoiseError, Protocol, ProtocolParams};
use crate::{Error, NoiseConfig, Protocol, ProtocolParams};
use libp2p_core::UpgradeInfo;
use libp2p_identity as identity;
use rand::Rng;
@ -94,6 +94,7 @@ impl UpgradeInfo for NoiseConfig<XX, X25519Spec> {
}
/// **Note**: This is not currentlyy a standardised upgrade.
impl UpgradeInfo for NoiseConfig<IX, X25519Spec> {
type Info = &'static [u8];
type InfoIter = std::iter::Once<Self::Info>;
@ -104,6 +105,7 @@ impl UpgradeInfo for NoiseConfig<IX, X25519Spec> {
}
/// **Note**: This is not currently a standardised upgrade.
impl<R> UpgradeInfo for NoiseConfig<IK, X25519Spec, R> {
type Info = &'static [u8];
type InfoIter = std::iter::Once<Self::Info>;
@ -119,23 +121,20 @@ impl<R> UpgradeInfo for NoiseConfig<IK, X25519Spec, R> {
/// interoperable with other libp2p implementations.
impl Protocol<X25519Spec> for X25519Spec {
fn params_ik() -> ProtocolParams {
#[allow(deprecated)]
x25519::X25519::params_ik()
}
fn params_ix() -> ProtocolParams {
#[allow(deprecated)]
x25519::X25519::params_ix()
}
fn params_xx() -> ProtocolParams {
#[allow(deprecated)]
x25519::X25519::params_xx()
}
fn public_from_bytes(bytes: &[u8]) -> Result<PublicKey<X25519Spec>, NoiseError> {
fn public_from_bytes(bytes: &[u8]) -> Result<PublicKey<X25519Spec>, Error> {
if bytes.len() != 32 {
return Err(NoiseError::InvalidLength);
return Err(Error::InvalidLength);
}
let mut pk = [0u8; 32];
pk.copy_from_slice(bytes);
@ -152,10 +151,7 @@ impl Protocol<X25519Spec> for X25519Spec {
})
}
fn sign(
id_keys: &identity::Keypair,
dh_pk: &PublicKey<X25519Spec>,
) -> Result<Vec<u8>, NoiseError> {
fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey<X25519Spec>) -> Result<Vec<u8>, Error> {
Ok(id_keys.sign(&[STATIC_KEY_DOMAIN.as_bytes(), dh_pk.as_ref()].concat())?)
}
}

View File

@ -19,17 +19,13 @@
// DEALINGS IN THE SOFTWARE.
use async_io::Async;
use futures::{
future::{self, Either},
prelude::*,
};
use futures::prelude::*;
use libp2p_core::transport::Transport;
use libp2p_core::upgrade::{apply_inbound, apply_outbound, Negotiated};
use libp2p_core::upgrade::Negotiated;
use libp2p_core::{transport, upgrade};
use libp2p_identity as identity;
use libp2p_noise::{
Keypair, NoiseAuthenticated, NoiseConfig, NoiseError, NoiseOutput, RemoteIdentity, X25519Spec,
};
use libp2p_identity::PeerId;
use libp2p_noise as noise;
use libp2p_tcp as tcp;
use log::info;
use quickcheck::*;
@ -40,7 +36,7 @@ fn core_upgrade_compat() {
// Tests API compaibility with the libp2p-core upgrade API,
// i.e. if it compiles, the "test" is considered a success.
let id_keys = identity::Keypair::generate_ed25519();
let noise = NoiseAuthenticated::xx(&id_keys).unwrap();
let noise = noise::Config::new(&id_keys).unwrap();
let _ = tcp::async_io::Transport::default()
.upgrade(upgrade::Version::V1)
.authenticate(noise);
@ -57,34 +53,36 @@ fn xx() {
let server_id_public = server_id.public();
let client_id_public = client_id.public();
let server_dh = Keypair::<X25519Spec>::new()
.into_authentic(&server_id)
.unwrap();
let server_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
upgrade::apply(
output,
NoiseConfig::xx(server_dh),
noise::Config::new(&server_id).unwrap(),
endpoint,
upgrade::Version::V1,
)
})
.and_then(move |out, _| expect_identity(out, &client_id_public))
.map(move |out, _| {
assert_eq!(out.0, client_id_public.to_peer_id());
out
})
.boxed();
let client_dh = Keypair::<X25519Spec>::new()
.into_authentic(&client_id)
.unwrap();
let client_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
upgrade::apply(
output,
NoiseConfig::xx(client_dh),
noise::Config::new(&client_id).unwrap(),
endpoint,
upgrade::Version::V1,
)
})
.and_then(move |out, _| expect_identity(out, &server_id_public))
.map(move |out, _| {
assert_eq!(out.0, server_id_public.to_peer_id());
out
})
.boxed();
run(server_transport, client_transport, messages);
@ -95,119 +93,10 @@ fn xx() {
.quickcheck(prop as fn(Vec<Message>) -> bool)
}
#[test]
fn ix() {
let _ = env_logger::try_init();
fn prop(mut messages: Vec<Message>) -> bool {
messages.truncate(5);
let server_id = identity::Keypair::generate_ed25519();
let client_id = identity::Keypair::generate_ed25519();
type Output = (PeerId, noise::Output<Negotiated<Async<TcpStream>>>);
let server_id_public = server_id.public();
let client_id_public = client_id.public();
let server_dh = Keypair::<X25519Spec>::new()
.into_authentic(&server_id)
.unwrap();
let server_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
upgrade::apply(
output,
NoiseConfig::ix(server_dh),
endpoint,
upgrade::Version::V1,
)
})
.and_then(move |out, _| expect_identity(out, &client_id_public))
.boxed();
let client_dh = Keypair::<X25519Spec>::new()
.into_authentic(&client_id)
.unwrap();
let client_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
upgrade::apply(
output,
NoiseConfig::ix(client_dh),
endpoint,
upgrade::Version::V1,
)
})
.and_then(move |out, _| expect_identity(out, &server_id_public))
.boxed();
run(server_transport, client_transport, messages);
true
}
QuickCheck::new()
.max_tests(30)
.quickcheck(prop as fn(Vec<Message>) -> bool)
}
#[test]
fn ik_xx() {
let _ = env_logger::try_init();
fn prop(mut messages: Vec<Message>) -> bool {
messages.truncate(5);
let server_id = identity::Keypair::generate_ed25519();
let server_id_public = server_id.public();
let client_id = identity::Keypair::generate_ed25519();
let client_id_public = client_id.public();
let server_dh = Keypair::<X25519Spec>::new()
.into_authentic(&server_id)
.unwrap();
let server_dh_public = server_dh.public_dh_key().clone();
let server_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
if endpoint.is_listener() {
Either::Left(apply_inbound(output, NoiseConfig::ik_listener(server_dh)))
} else {
Either::Right(apply_outbound(
output,
NoiseConfig::xx(server_dh),
upgrade::Version::V1,
))
}
})
.and_then(move |out, _| expect_identity(out, &client_id_public))
.boxed();
let client_dh = Keypair::<X25519Spec>::new()
.into_authentic(&client_id)
.unwrap();
let server_id_public2 = server_id_public.clone();
let client_transport = tcp::async_io::Transport::default()
.and_then(move |output, endpoint| {
if endpoint.is_dialer() {
Either::Left(apply_outbound(
output,
NoiseConfig::ik_dialer(client_dh, server_id_public, server_dh_public),
upgrade::Version::V1,
))
} else {
Either::Right(apply_inbound(output, NoiseConfig::xx(client_dh)))
}
})
.and_then(move |out, _| expect_identity(out, &server_id_public2))
.boxed();
run(server_transport, client_transport, messages);
true
}
QuickCheck::new()
.max_tests(30)
.quickcheck(prop as fn(Vec<Message>) -> bool)
}
type Output<C> = (RemoteIdentity<C>, NoiseOutput<Negotiated<Async<TcpStream>>>);
fn run<I, C>(
mut server: transport::Boxed<Output<C>>,
mut client: transport::Boxed<Output<C>>,
messages: I,
) where
fn run<I>(mut server: transport::Boxed<Output>, mut client: transport::Boxed<Output>, messages: I)
where
I: IntoIterator<Item = Message> + Clone,
{
futures::executor::block_on(async {
@ -274,16 +163,6 @@ fn run<I, C>(
})
}
fn expect_identity<C>(
output: Output<C>,
pk: &identity::PublicKey,
) -> impl Future<Output = Result<Output<C>, NoiseError>> {
match output.0 {
RemoteIdentity::IdentityKey(ref k) if k == pk => future::ok(output),
_ => panic!("Unexpected remote identity"),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Message(Vec<u8>);

View File

@ -110,7 +110,7 @@ where
let transport = transport
.and_then(move |socket, _| pnet.handshake(socket))
.upgrade(Version::V1)
.authenticate(libp2p_noise::NoiseAuthenticated::xx(&identity).unwrap())
.authenticate(libp2p_noise::Config::new(&identity).unwrap())
.multiplex(libp2p_yamux::YamuxConfig::default())
.boxed();
SwarmBuilder::with_tokio_executor(

View File

@ -233,14 +233,7 @@ fn new_tcp_quic_transport() -> (PeerId, Boxed<(PeerId, StreamMuxerBox)>) {
let quic_transport = quic::async_std::Transport::new(config);
let tcp_transport = tcp::async_io::Transport::new(tcp::Config::default())
.upgrade(upgrade::Version::V1)
.authenticate(
noise::NoiseConfig::xx(
noise::Keypair::<noise::X25519Spec>::new()
.into_authentic(&keypair)
.unwrap(),
)
.into_authenticated(),
)
.authenticate(noise::Config::new(&keypair).unwrap())
.multiplex(yamux::YamuxConfig::default());
let transport = OrTransport::new(quic_transport, tcp_transport)

View File

@ -19,7 +19,7 @@ futures-timer = "3"
hex = "0.4"
if-watch = "3.0"
libp2p-core = { version = "0.39.0", path = "../../core" }
libp2p-noise = { version = "0.42.0", path = "../../transports/noise" }
libp2p-noise = { version = "0.42.2", path = "../../transports/noise" }
libp2p-identity = { version = "0.1.0", path = "../../identity" }
log = "0.4"
sha2 = "0.10.6"

View File

@ -29,7 +29,7 @@ pub enum Error {
#[error("IO error")]
Io(#[from] std::io::Error),
#[error("failed to authenticate peer")]
Authentication(#[from] libp2p_noise::NoiseError),
Authentication(#[from] libp2p_noise::Error),
// Authentication errors.
#[error("invalid peer ID (expected {expected}, got {got})")]

View File

@ -22,7 +22,7 @@ use futures::{AsyncRead, AsyncWrite, AsyncWriteExt};
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p_identity as identity;
use libp2p_identity::PeerId;
use libp2p_noise::{Keypair, NoiseConfig, X25519Spec};
use libp2p_noise as noise;
use crate::tokio::fingerprint::Fingerprint;
use crate::tokio::Error;
@ -36,18 +36,13 @@ pub(crate) async fn inbound<T>(
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
let dh_keys = Keypair::<X25519Spec>::new()
.into_authentic(&id_keys)
.unwrap();
let noise = NoiseConfig::xx(dh_keys)
let noise = noise::Config::new(&id_keys)
.unwrap()
.with_prologue(noise_prologue(client_fingerprint, server_fingerprint));
let info = noise.protocol_info().next().unwrap();
// Note the roles are reversed because it allows the server (webrtc connection responder) to
// send application data 0.5 RTT earlier.
let (peer_id, mut channel) = noise
.into_authenticated()
.upgrade_outbound(stream, info)
.await?;
let (peer_id, mut channel) = noise.upgrade_outbound(stream, info).await?;
channel.close().await?;
@ -63,18 +58,13 @@ pub(crate) async fn outbound<T>(
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
let dh_keys = Keypair::<X25519Spec>::new()
.into_authentic(&id_keys)
.unwrap();
let noise = NoiseConfig::xx(dh_keys)
let noise = noise::Config::new(&id_keys)
.unwrap()
.with_prologue(noise_prologue(client_fingerprint, server_fingerprint));
let info = noise.protocol_info().next().unwrap();
// Note the roles are reversed because it allows the server (webrtc connection responder) to
// send application data 0.5 RTT earlier.
let (peer_id, mut channel) = noise
.into_authenticated()
.upgrade_inbound(stream, info)
.await?;
let (peer_id, mut channel) = noise.upgrade_inbound(stream, info).await?;
channel.close().await?;