diff --git a/Cargo.lock b/Cargo.lock index a30d07f9a4e..ad9a1d5f15d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2684,7 +2684,7 @@ dependencies = [ [[package]] name = "libp2p-noise" -version = "0.42.1" +version = "0.42.2" dependencies = [ "async-io", "bytes", diff --git a/core/tests/transport_upgrade.rs b/core/tests/transport_upgrade.rs index e2c44f9f0d4..ac724a64ffa 100644 --- a/core/tests/transport_upgrade.rs +++ b/core/tests/transport_upgrade.rs @@ -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 {}) diff --git a/examples/autonat/src/bin/autonat_client.rs b/examples/autonat/src/bin/autonat_client.rs index 32ecc9aca67..ff3e0805463 100644 --- a/examples/autonat/src/bin/autonat_client.rs +++ b/examples/autonat/src/bin/autonat_client.rs @@ -64,7 +64,7 @@ async fn main() -> Result<(), Box> { 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(); diff --git a/examples/autonat/src/bin/autonat_server.rs b/examples/autonat/src/bin/autonat_server.rs index e3ad9665e30..b6c51ba8b5e 100644 --- a/examples/autonat/src/bin/autonat_server.rs +++ b/examples/autonat/src/bin/autonat_server.rs @@ -53,7 +53,7 @@ async fn main() -> Result<(), Box> { 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(); diff --git a/examples/chat-example/src/main.rs b/examples/chat-example/src/main.rs index 368d270a371..0d1c68a9d3b 100644 --- a/examples/chat-example/src/main.rs +++ b/examples/chat-example/src/main.rs @@ -77,9 +77,7 @@ async fn main() -> Result<(), Box> { // 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(); diff --git a/examples/dcutr/src/main.rs b/examples/dcutr/src/main.rs index 1cafa2411a0..62e28ca9c57 100644 --- a/examples/dcutr/src/main.rs +++ b/examples/dcutr/src/main.rs @@ -98,8 +98,7 @@ fn main() -> Result<(), Box> { ) .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(); diff --git a/examples/distributed-key-value-store/src/main.rs b/examples/distributed-key-value-store/src/main.rs index 404062199cc..83adfa6b43c 100644 --- a/examples/distributed-key-value-store/src/main.rs +++ b/examples/distributed-key-value-store/src/main.rs @@ -65,7 +65,7 @@ async fn main() -> Result<(), Box> { 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(); diff --git a/examples/file-sharing/src/network.rs b/examples/file-sharing/src/network.rs index 62496172e4a..5eedd22d765 100644 --- a/examples/file-sharing/src/network.rs +++ b/examples/file-sharing/src/network.rs @@ -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(); diff --git a/examples/identify/src/main.rs b/examples/identify/src/main.rs index 7159be53b66..1b900043108 100644 --- a/examples/identify/src/main.rs +++ b/examples/identify/src/main.rs @@ -53,7 +53,7 @@ async fn main() -> Result<(), Box> { 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(); diff --git a/examples/ipfs-private/src/main.rs b/examples/ipfs-private/src/main.rs index fadc6cfd06f..1af5bebb4b6 100644 --- a/examples/ipfs-private/src/main.rs +++ b/examples/ipfs-private/src/main.rs @@ -52,7 +52,7 @@ pub fn build_transport( key_pair: identity::Keypair, psk: Option, ) -> 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)); diff --git a/examples/metrics/src/main.rs b/examples/metrics/src/main.rs index 7eda36d9715..7bbb533299c 100644 --- a/examples/metrics/src/main.rs +++ b/examples/metrics/src/main.rs @@ -74,7 +74,7 @@ fn main() -> Result<(), Box> { 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), diff --git a/examples/ping-example/src/main.rs b/examples/ping-example/src/main.rs index 3cb0aa69ae3..34113e1d50d 100644 --- a/examples/ping-example/src/main.rs +++ b/examples/ping-example/src/main.rs @@ -57,7 +57,7 @@ async fn main() -> Result<(), Box> { 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(); diff --git a/examples/relay-server/src/main.rs b/examples/relay-server/src/main.rs index 3484d236986..1a6088b5563 100644 --- a/examples/relay-server/src/main.rs +++ b/examples/relay-server/src/main.rs @@ -51,8 +51,7 @@ fn main() -> Result<(), Box> { 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(); diff --git a/examples/rendezvous/src/bin/rzv-discover.rs b/examples/rendezvous/src/bin/rzv-discover.rs index 2f31dc9d390..b1ac6d7220e 100644 --- a/examples/rendezvous/src/bin/rzv-discover.rs +++ b/examples/rendezvous/src/bin/rzv-discover.rs @@ -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 { diff --git a/examples/rendezvous/src/bin/rzv-identify.rs b/examples/rendezvous/src/bin/rzv-identify.rs index bb5157fba78..7cd28f73441 100644 --- a/examples/rendezvous/src/bin/rzv-identify.rs +++ b/examples/rendezvous/src/bin/rzv-identify.rs @@ -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 { diff --git a/examples/rendezvous/src/bin/rzv-register.rs b/examples/rendezvous/src/bin/rzv-register.rs index 5429fb8efa1..7edd7dc1fdb 100644 --- a/examples/rendezvous/src/bin/rzv-register.rs +++ b/examples/rendezvous/src/bin/rzv-register.rs @@ -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 { diff --git a/examples/rendezvous/src/main.rs b/examples/rendezvous/src/main.rs index 78e48cee7d4..929cdc097e2 100644 --- a/examples/rendezvous/src/main.rs +++ b/examples/rendezvous/src/main.rs @@ -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 { diff --git a/interop-tests/src/bin/ping.rs b/interop-tests/src/bin/ping.rs index 63160f8c8d0..7aacfa82a99 100644 --- a/interop-tests/src/bin/ping.rs +++ b/interop-tests/src/bin/ping.rs @@ -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(), diff --git a/libp2p/Cargo.toml b/libp2p/Cargo.toml index aa35c2b84db..dcdbb00f79d 100644 --- a/libp2p/Cargo.toml +++ b/libp2p/Cargo.toml @@ -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 } diff --git a/libp2p/src/lib.rs b/libp2p/src/lib.rs index 79acd4249b8..f2764e88ef9 100644 --- a/libp2p/src/lib.rs +++ b/libp2p/src/lib.rs @@ -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)] diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index 8ba50e2db4b..ec1c7596de0 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -564,13 +564,10 @@ mod tests { transport::Boxed<(PeerId, StreamMuxerBox)>, ) { let id_keys = identity::Keypair::generate_ed25519(); - let noise_keys = noise::Keypair::::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) diff --git a/protocols/kad/src/behaviour/test.rs b/protocols/kad/src/behaviour/test.rs index 3a76e2f92b2..f361a31f756 100644 --- a/protocols/kad/src/behaviour/test.rs +++ b/protocols/kad/src/behaviour/test.rs @@ -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(); diff --git a/protocols/perf/Cargo.toml b/protocols/perf/Cargo.toml index 03230a8ed13..d76024dfb37 100644 --- a/protocols/perf/Cargo.toml +++ b/protocols/perf/Cargo.toml @@ -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"] } diff --git a/protocols/perf/src/bin/perf-client.rs b/protocols/perf/src/bin/perf-client.rs index c12ab5cbe74..a1d809ac1cb 100644 --- a/protocols/perf/src/bin/perf-client.rs +++ b/protocols/perf/src/bin/perf-client.rs @@ -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()); diff --git a/protocols/perf/src/bin/perf-server.rs b/protocols/perf/src/bin/perf-server.rs index b12972e3c38..8499ccc602b 100644 --- a/protocols/perf/src/bin/perf-server.rs +++ b/protocols/perf/src/bin/perf-server.rs @@ -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()); diff --git a/transports/noise/CHANGELOG.md b/transports/noise/CHANGELOG.md index 2f0698eccef..f9c51382a65 100644 --- a/transports/noise/CHANGELOG.md +++ b/transports/noise/CHANGELOG.md @@ -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]. diff --git a/transports/noise/Cargo.toml b/transports/noise/Cargo.toml index 28a8ceeb0a8..b7da5a31090 100644 --- a/transports/noise/Cargo.toml +++ b/transports/noise/Cargo.toml @@ -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 "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/transports/noise/src/io.rs b/transports/noise/src/io.rs index 314a3b87033..ee184695696 100644 --- a/transports/noise/src/io.rs +++ b/transports/noise/src/io.rs @@ -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 { +pub struct Output { io: NoiseFramed, recv_buffer: Bytes, recv_offset: usize, @@ -45,15 +45,15 @@ pub struct NoiseOutput { send_offset: usize, } -impl fmt::Debug for NoiseOutput { +impl fmt::Debug for Output { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("NoiseOutput").field("io", &self.io).finish() } } -impl NoiseOutput { +impl Output { fn new(io: NoiseFramed) -> Self { - NoiseOutput { + Output { io, recv_buffer: Bytes::new(), recv_offset: 0, @@ -63,7 +63,7 @@ impl NoiseOutput { } } -impl AsyncRead for NoiseOutput { +impl AsyncRead for Output { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -99,7 +99,7 @@ impl AsyncRead for NoiseOutput { } } -impl AsyncWrite for NoiseOutput { +impl AsyncWrite for Output { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, diff --git a/transports/noise/src/io/framed.rs b/transports/noise/src/io/framed.rs index 1e74e46ac9b..01e1f9dbca1 100644 --- a/transports/noise/src/io/framed.rs +++ b/transports/noise/src/io/framed.rs @@ -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 NoiseFramed { /// 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( - self, - ) -> Result<(Option>, NoiseOutput), NoiseError> + pub(crate) fn into_transport(self) -> Result<(Option>, Output), Error> where C: Protocol + AsRef<[u8]>, { @@ -111,7 +109,7 @@ impl NoiseFramed { decrypt_buffer: self.decrypt_buffer, }; - Ok((dh_remote_pubkey, NoiseOutput::new(io))) + Ok((dh_remote_pubkey, Output::new(io))) } } diff --git a/transports/noise/src/io/handshake.rs b/transports/noise/src/io/handshake.rs index d968c481ddd..ea3331d5e68 100644 --- a/transports/noise/src/io/handshake.rs +++ b/transports/noise/src/io/handshake.rs @@ -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 { /// The remote provided no identifying information. /// @@ -79,7 +82,6 @@ pub(crate) struct State { /// The known or received public identity key of the remote, if any. id_remote_pubkey: Option, /// Legacy configuration parameters. - #[allow(deprecated)] legacy: LegacyConfig, } @@ -89,7 +91,7 @@ impl State { /// 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 State { impl State { /// Finish a handshake, yielding the established remote identity and the - /// [`NoiseOutput`] for communicating on the encrypted channel. - pub(crate) fn finish(self) -> Result<(RemoteIdentity, NoiseOutput), NoiseError> + /// [`Output`] for communicating on the encrypted channel. + pub(crate) fn finish(self) -> Result<(RemoteIdentity, Output), Error> where C: Protocol + AsRef<[u8]>, { @@ -122,7 +124,7 @@ impl State { 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 State { // Handshake Message Futures /// A future for receiving a Noise handshake message. -async fn recv(state: &mut State) -> Result +async fn recv(state: &mut State) -> Result 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(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn recv_empty(state: &mut State) -> 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(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_empty(state: &mut State) -> 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(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn recv_identity(state: &mut State) -> 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(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_identity(state: &mut State) -> 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(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_signature_only(state: &mut State) -> 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()); diff --git a/transports/noise/src/lib.rs b/transports/noise/src/lib.rs index c1c120f38a6..1e5b0a437e1 100644 --- a/transports/noise/src/lib.rs +++ b/transports/noise/src/lib.rs @@ -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 = protocol::AuthenticKeypair; + +#[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 = protocol::Keypair; + +#[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 = protocol::PublicKey; + +#[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 = protocol::SecretKey; + +#[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 = Output; 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, +} + +impl Config { + /// Construct a new configuration for the noise handshake using the XX handshake pattern. + + pub fn new(identity: &identity::Keypair) -> Result { + Ok(Config { + inner: NoiseAuthenticated::xx(identity)?, + }) + } + + /// Set the noise prologue. + + pub fn with_prologue(mut self, prologue: Vec) -> Self { + self.inner.config.prologue = prologue; + + self + } +} + +impl UpgradeInfo for Config { + type Info = &'static [u8]; + type InfoIter = std::iter::Once; + + fn protocol_info(&self) -> Self::InfoIter { + std::iter::once(b"/noise") + } +} + +impl InboundUpgrade for Config +where + T: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + type Output = (PeerId, Output); + type Error = Error; + type Future = Pin> + Send>>; + + fn upgrade_inbound(self, socket: T, info: Self::Info) -> Self::Future { + self.inner.upgrade_inbound(socket, info) + } +} + +impl OutboundUpgrade for Config +where + T: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + type Output = (PeerId, Output); + type Error = Error; + type Future = Pin> + 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 { dh_keys: AuthenticKeypair, params: ProtocolParams, - #[allow(deprecated)] + legacy: LegacyConfig, remote: R, _marker: std::marker::PhantomData

, @@ -114,7 +239,7 @@ impl NoiseConfig { 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 NoiseConfig { /// Implement `into_responder` and `into_initiator` for all configs where `R = ()`. /// /// This allows us to ignore the `remote` field. + impl NoiseConfig where C: Zeroize + Protocol + AsRef<[u8]>, { - fn into_responder(self, socket: S) -> Result, NoiseError> { + fn into_responder(self, socket: S) -> Result, 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(self, socket: S) -> Result, NoiseError> { + fn into_initiator(self, socket: S) -> Result, 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(self, socket: S) -> Result, NoiseError> { + fn into_initiator(self, socket: S) -> Result, 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 for DecodeError { } } -impl From for NoiseError { +impl From for Error { fn from(e: quick_protobuf::Error) -> Self { - NoiseError::InvalidPayload(e.into()) + Error::InvalidPayload(e.into()) } } @@ -318,15 +432,16 @@ impl From for NoiseError { /// initiator -{id}-> responder /// initiator <-{id}- responder /// ``` + impl InboundUpgrade for NoiseConfig where NoiseConfig: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 OutboundUpgrade for NoiseConfig where NoiseConfig: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 InboundUpgrade for NoiseConfig where NoiseConfig: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 OutboundUpgrade for NoiseConfig where NoiseConfig: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 InboundUpgrade for NoiseConfig where NoiseConfig: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 OutboundUpgrade for NoiseConfig, identity::PublicKey)> where NoiseConfig, identity::PublicKey)>: UpgradeInfo, T: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Clone + Send + 'static, { - type Output = (RemoteIdentity, NoiseOutput); - type Error = NoiseError; - type Future = BoxFuture<'static, Result<(RemoteIdentity, NoiseOutput), NoiseError>>; + type Output = (RemoteIdentity, Output); + type Error = Error; + type Future = BoxFuture<'static, Result<(RemoteIdentity, Output), 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 { config: NoiseConfig, } @@ -533,7 +656,8 @@ impl NoiseAuthenticated { /// 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 { + #[deprecated(note = "Use `libp2p_noise::Config::new` instead.")] + pub fn xx(id_keys: &identity::Keypair) -> Result { let dh_keys = Keypair::::new(); let noise_keys = dh_keys.into_authentic(id_keys)?; let config = NoiseConfig::xx(noise_keys); @@ -557,14 +681,14 @@ where impl InboundUpgrade for NoiseAuthenticated where NoiseConfig: UpgradeInfo - + InboundUpgrade, NoiseOutput), Error = NoiseError> + + InboundUpgrade, Output), Error = Error> + 'static, as InboundUpgrade>::Future: Send, T: AsyncRead + AsyncWrite + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Send + 'static, { - type Output = (PeerId, NoiseOutput); - type Error = NoiseError; + type Output = (PeerId, Output); + type Error = Error; type Future = Pin> + 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 OutboundUpgrade for NoiseAuthenticated where NoiseConfig: UpgradeInfo - + OutboundUpgrade, NoiseOutput), Error = NoiseError> + + OutboundUpgrade, Output), Error = Error> + 'static, as OutboundUpgrade>::Future: Send, T: AsyncRead + AsyncWrite + Send + 'static, C: Protocol + AsRef<[u8]> + Zeroize + Send + 'static, { - type Output = (PeerId, NoiseOutput); - type Error = NoiseError; + type Output = (PeerId, Output); + type Error = Error; type Future = Pin> + 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), }), ) } diff --git a/transports/noise/src/protocol.rs b/transports/noise/src/protocol.rs index db42b5888b3..c8d9da3ff56 100644 --- a/transports/noise/src/protocol.rs +++ b/transports/noise/src/protocol.rs @@ -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 { /// The protocol parameters for the IK handshake pattern. fn params_ik() -> ProtocolParams; @@ -77,7 +80,7 @@ pub trait Protocol { fn params_xx() -> ProtocolParams; /// Construct a DH public key from a byte slice. - fn public_from_bytes(s: &[u8]) -> Result, NoiseError>; + fn public_from_bytes(s: &[u8]) -> Result, 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 { /// 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, sig: &Option>) -> bool where C: AsRef<[u8]>, @@ -114,7 +117,7 @@ pub trait Protocol { .map_or(false, |s| id_pk.verify(dh_pk.as_ref(), s)) } - fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey) -> Result, NoiseError> + fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey) -> Result, Error> where C: AsRef<[u8]>, { @@ -175,10 +178,7 @@ impl Keypair { /// 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, NoiseError> + pub fn into_authentic(self, id_keys: &identity::Keypair) -> Result, Error> where T: AsRef<[u8]>, T: Protocol, diff --git a/transports/noise/src/protocol/x25519.rs b/transports/noise/src/protocol/x25519.rs index 9dcf5f8d73a..cc1586feb0d 100644 --- a/transports/noise/src/protocol/x25519.rs +++ b/transports/noise/src/protocol/x25519.rs @@ -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 = 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 for X25519 { PARAMS_XX.clone() } - fn public_from_bytes(bytes: &[u8]) -> Result, NoiseError> { + fn public_from_bytes(bytes: &[u8]) -> Result, Error> { if bytes.len() != 32 { - return Err(NoiseError::InvalidLength); + return Err(Error::InvalidLength); } let mut pk = [0u8; 32]; pk.copy_from_slice(bytes); diff --git a/transports/noise/src/protocol/x25519_spec.rs b/transports/noise/src/protocol/x25519_spec.rs index 0924bdd51e4..621532ad52d 100644 --- a/transports/noise/src/protocol/x25519_spec.rs +++ b/transports/noise/src/protocol/x25519_spec.rs @@ -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 { } /// **Note**: This is not currentlyy a standardised upgrade. + impl UpgradeInfo for NoiseConfig { type Info = &'static [u8]; type InfoIter = std::iter::Once; @@ -104,6 +105,7 @@ impl UpgradeInfo for NoiseConfig { } /// **Note**: This is not currently a standardised upgrade. + impl UpgradeInfo for NoiseConfig { type Info = &'static [u8]; type InfoIter = std::iter::Once; @@ -119,23 +121,20 @@ impl UpgradeInfo for NoiseConfig { /// interoperable with other libp2p implementations. impl Protocol 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, NoiseError> { + fn public_from_bytes(bytes: &[u8]) -> Result, 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 for X25519Spec { }) } - fn sign( - id_keys: &identity::Keypair, - dh_pk: &PublicKey, - ) -> Result, NoiseError> { + fn sign(id_keys: &identity::Keypair, dh_pk: &PublicKey) -> Result, Error> { Ok(id_keys.sign(&[STATIC_KEY_DOMAIN.as_bytes(), dh_pk.as_ref()].concat())?) } } diff --git a/transports/noise/tests/smoke.rs b/transports/noise/tests/smoke.rs index 2b71b115b99..9ddbca3eec8 100644 --- a/transports/noise/tests/smoke.rs +++ b/transports/noise/tests/smoke.rs @@ -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,140 +53,36 @@ fn xx() { let server_id_public = server_id.public(); let client_id_public = client_id.public(); - let server_dh = Keypair::::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)) - .boxed(); + .map(move |out, _| { + assert_eq!(out.0, client_id_public.to_peer_id()); - let client_dh = Keypair::::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), - endpoint, - upgrade::Version::V1, - ) + out }) - .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) -> bool) -} - -#[test] -fn ix() { - let _ = env_logger::try_init(); - fn prop(mut messages: Vec) -> bool { - messages.truncate(5); - let server_id = identity::Keypair::generate_ed25519(); - let client_id = identity::Keypair::generate_ed25519(); - - let server_id_public = server_id.public(); - let client_id_public = client_id.public(); - - let server_dh = Keypair::::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::::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), + noise::Config::new(&client_id).unwrap(), 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) -> bool) -} + .map(move |out, _| { + assert_eq!(out.0, server_id_public.to_peer_id()); -#[test] -fn ik_xx() { - let _ = env_logger::try_init(); - fn prop(mut messages: Vec) -> 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::::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, - )) - } + out }) - .and_then(move |out, _| expect_identity(out, &client_id_public)) - .boxed(); - - let client_dh = Keypair::::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); @@ -201,13 +93,10 @@ fn ik_xx() { .quickcheck(prop as fn(Vec) -> bool) } -type Output = (RemoteIdentity, NoiseOutput>>); +type Output = (PeerId, noise::Output>>); -fn run( - mut server: transport::Boxed>, - mut client: transport::Boxed>, - messages: I, -) where +fn run(mut server: transport::Boxed, mut client: transport::Boxed, messages: I) +where I: IntoIterator + Clone, { futures::executor::block_on(async { @@ -274,16 +163,6 @@ fn run( }) } -fn expect_identity( - output: Output, - pk: &identity::PublicKey, -) -> impl Future, 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); diff --git a/transports/pnet/tests/smoke.rs b/transports/pnet/tests/smoke.rs index 7c8f571bb26..66fa01b7222 100644 --- a/transports/pnet/tests/smoke.rs +++ b/transports/pnet/tests/smoke.rs @@ -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( diff --git a/transports/quic/tests/smoke.rs b/transports/quic/tests/smoke.rs index 2e8914140c4..0fe6a65c081 100644 --- a/transports/quic/tests/smoke.rs +++ b/transports/quic/tests/smoke.rs @@ -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::::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) diff --git a/transports/webrtc/Cargo.toml b/transports/webrtc/Cargo.toml index f45d3004531..ae0379b2e03 100644 --- a/transports/webrtc/Cargo.toml +++ b/transports/webrtc/Cargo.toml @@ -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" diff --git a/transports/webrtc/src/tokio/error.rs b/transports/webrtc/src/tokio/error.rs index 4899a077b4b..1b274686ef3 100644 --- a/transports/webrtc/src/tokio/error.rs +++ b/transports/webrtc/src/tokio/error.rs @@ -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})")] diff --git a/transports/webrtc/src/tokio/upgrade/noise.rs b/transports/webrtc/src/tokio/upgrade/noise.rs index fb95a0f4b46..34e3526a2fe 100644 --- a/transports/webrtc/src/tokio/upgrade/noise.rs +++ b/transports/webrtc/src/tokio/upgrade/noise.rs @@ -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( where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, { - let dh_keys = Keypair::::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( where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, { - let dh_keys = Keypair::::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?;