diff --git a/Cargo.toml b/Cargo.toml index bcc44cd6..e102e32e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +resolver = "2" members = [ "yamux", "secio", diff --git a/Makefile b/Makefile index 1b13a58e..bc3a80ce 100644 --- a/Makefile +++ b/Makefile @@ -13,10 +13,10 @@ fmt: cargo fmt --all -- --check clippy: - $(Change_Work_Path) && RUSTFLAGS='-F warnings' cargo clippy --all --tests --features ws,unstable -- -D clippy::let_underscore_must_use + $(Change_Work_Path) && RUSTFLAGS='-W warnings' cargo clippy --all --tests --features ws,unstable -- -D clippy::let_underscore_must_use test: - $(Change_Work_Path) && RUSTFLAGS='-F warnings' RUST_BACKTRACE=full cargo test --all --features ws,unstable + $(Change_Work_Path) && RUSTFLAGS='-W warnings' RUST_BACKTRACE=full cargo test --all --features ws,unstable fuzz: cargo +nightly fuzz run secio_crypto_decrypt_cipher -- -max_total_time=60 @@ -32,14 +32,12 @@ examples: features-check: # remove yamux default features - sed -i 's/"tokio-timer"//g' yamux/Cargo.toml $(Change_Work_Path) && cargo build --features unstable $(Change_Work_Path) && cargo build --features tokio-runtime,generic-timer,unstable --no-default-features $(Change_Work_Path) && cargo build --features async-runtime,generic-timer,unstable --no-default-features $(Change_Work_Path) && cargo build --features async-runtime,async-timer,unstable --no-default-features # required wasm32-unknown-unknown target $(Change_Work_Path) && cargo build --features wasm-timer,unstable --no-default-features --target=wasm32-unknown-unknown - git checkout . bench_p2p: cd bench && cargo run --release diff --git a/multiaddr/src/lib.rs b/multiaddr/src/lib.rs index 9f35e646..78ec6ae8 100644 --- a/multiaddr/src/lib.rs +++ b/multiaddr/src/lib.rs @@ -50,7 +50,7 @@ impl Multiaddr { /// use tentacle_multiaddr::{Multiaddr, Protocol}; /// /// let mut address: Multiaddr = "/ip4/127.0.0.1".parse().unwrap(); - /// address.push(Protocol::TCP(10000)); + /// address.push(Protocol::Tcp(10000)); /// println!("{}", address); /// assert_eq!(address, "/ip4/127.0.0.1/tcp/10000".parse().unwrap()); /// ``` @@ -70,8 +70,8 @@ impl Multiaddr { /// /// let mut address: Multiaddr = "/ip4/127.0.0.1/tcp/5678".parse().unwrap(); /// - /// assert_eq!(address.pop().unwrap(), Protocol::TCP(5678)); - /// assert_eq!(address.pop().unwrap(), Protocol::IP4(Ipv4Addr::new(127, 0, 0, 1))); + /// assert_eq!(address.pop().unwrap(), Protocol::Tcp(5678)); + /// assert_eq!(address.pop().unwrap(), Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1))); /// ``` /// pub fn pop<'a>(&mut self) -> Option> { @@ -100,8 +100,8 @@ impl Multiaddr { /// let address: Multiaddr = "/ip4/127.0.0.1/tcp/5678".parse().unwrap(); /// /// let components = address.iter().collect::>(); - /// assert_eq!(components[0], Protocol::IP4(Ipv4Addr::new(127, 0, 0, 1))); - /// assert_eq!(components[1], Protocol::TCP(5678)); + /// assert_eq!(components[0], Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1))); + /// assert_eq!(components[1], Protocol::Tcp(5678)); /// ``` /// pub fn iter(&self) -> Iter<'_> { @@ -264,13 +264,13 @@ impl From for Multiaddr { impl From for Multiaddr { fn from(v: Ipv4Addr) -> Multiaddr { - Protocol::IP4(v).into() + Protocol::Ip4(v).into() } } impl From for Multiaddr { fn from(v: Ipv6Addr) -> Multiaddr { - Protocol::IP6(v).into() + Protocol::Ip6(v).into() } } @@ -340,7 +340,7 @@ impl<'de> Deserialize<'de> for Multiaddr { { struct Visitor { is_human_readable: bool, - }; + } impl<'de> de::Visitor<'de> for Visitor { type Value = Multiaddr; @@ -401,7 +401,7 @@ impl<'de> Deserialize<'de> for Multiaddr { /// /// ```rust /// # use tentacle_multiaddr::multiaddr; -/// let addr = multiaddr!(IP4([127, 0, 0, 1]), TCP(10500u16)); +/// let addr = multiaddr!(Ip4([127, 0, 0, 1]), Tcp(10500u16)); /// ``` /// /// Each element passed to `multiaddr!` should be a variant of the `Protocol` enum. The @@ -433,7 +433,7 @@ mod test { #[test] fn compatibility_test() { let mut address: Multiaddr = "/ip4/127.0.0.1".parse().unwrap(); - address.push(Protocol::TCP(10000)); + address.push(Protocol::Tcp(10000)); assert_eq!(address, "/ip4/127.0.0.1/tcp/10000".parse().unwrap()); let _address: Multiaddr = "/ip4/127.0.0.1/tcp/20/tls/main".parse().unwrap(); diff --git a/multiaddr/src/protocol.rs b/multiaddr/src/protocol.rs index 9a4ed59b..f72e1b5e 100644 --- a/multiaddr/src/protocol.rs +++ b/multiaddr/src/protocol.rs @@ -25,13 +25,13 @@ const SHA256_SIZE: u8 = 32; /// `Protocol` describes all possible multiaddress protocols. #[derive(PartialEq, Eq, Clone, Debug)] pub enum Protocol<'a> { - DNS4(Cow<'a, str>), - DNS6(Cow<'a, str>), - IP4(Ipv4Addr), - IP6(Ipv6Addr), + Dns4(Cow<'a, str>), + Dns6(Cow<'a, str>), + Ip4(Ipv4Addr), + Ip6(Ipv6Addr), P2P(Cow<'a, [u8]>), - TCP(u16), - TLS(Cow<'a, str>), + Tcp(u16), + Tls(Cow<'a, str>), Ws, Wss, } @@ -50,23 +50,23 @@ impl<'a> Protocol<'a> { match iter.next().ok_or(Error::InvalidProtocolString)? { "dns4" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::DNS4(Cow::Borrowed(s))) + Ok(Protocol::Dns4(Cow::Borrowed(s))) } "dns6" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::DNS6(Cow::Borrowed(s))) + Ok(Protocol::Dns6(Cow::Borrowed(s))) } "ip4" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::IP4(Ipv4Addr::from_str(s)?)) + Ok(Protocol::Ip4(Ipv4Addr::from_str(s)?)) } "ip6" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::IP6(Ipv6Addr::from_str(s)?)) + Ok(Protocol::Ip6(Ipv6Addr::from_str(s)?)) } "tls" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::TLS(Cow::Borrowed(s))) + Ok(Protocol::Tls(Cow::Borrowed(s))) } "p2p" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; @@ -76,7 +76,7 @@ impl<'a> Protocol<'a> { } "tcp" => { let s = iter.next().ok_or(Error::InvalidProtocolString)?; - Ok(Protocol::TCP(s.parse()?)) + Ok(Protocol::Tcp(s.parse()?)) } "ws" => Ok(Protocol::Ws), "wss" => Ok(Protocol::Wss), @@ -99,17 +99,17 @@ impl<'a> Protocol<'a> { DNS4 => { let (n, input) = decode::usize(input)?; let (data, rest) = split_header(n, input)?; - Ok((Protocol::DNS4(Cow::Borrowed(str::from_utf8(data)?)), rest)) + Ok((Protocol::Dns4(Cow::Borrowed(str::from_utf8(data)?)), rest)) } DNS6 => { let (n, input) = decode::usize(input)?; let (data, rest) = split_header(n, input)?; - Ok((Protocol::DNS6(Cow::Borrowed(str::from_utf8(data)?)), rest)) + Ok((Protocol::Dns6(Cow::Borrowed(str::from_utf8(data)?)), rest)) } IP4 => { let (data, rest) = split_header(4, input)?; Ok(( - Protocol::IP4(Ipv4Addr::new(data[0], data[1], data[2], data[3])), + Protocol::Ip4(Ipv4Addr::new(data[0], data[1], data[2], data[3])), rest, )) } @@ -126,12 +126,12 @@ impl<'a> Protocol<'a> { seg[0], seg[1], seg[2], seg[3], seg[4], seg[5], seg[6], seg[7], ); - Ok((Protocol::IP6(addr), rest)) + Ok((Protocol::Ip6(addr), rest)) } TLS => { let (n, input) = decode::usize(input)?; let (data, rest) = split_header(n, input)?; - Ok((Protocol::TLS(Cow::Borrowed(str::from_utf8(data)?)), rest)) + Ok((Protocol::Tls(Cow::Borrowed(str::from_utf8(data)?)), rest)) } P2P => { let (n, input) = decode::usize(input)?; @@ -143,7 +143,7 @@ impl<'a> Protocol<'a> { let (data, rest) = split_header(2, input)?; let mut rdr = Cursor::new(data); let num = rdr.get_u16(); - Ok((Protocol::TCP(num), rest)) + Ok((Protocol::Tcp(num), rest)) } WS => Ok((Protocol::Ws, input)), WSS => Ok((Protocol::Wss, input)), @@ -157,33 +157,33 @@ impl<'a> Protocol<'a> { use unsigned_varint::encode; let mut buf = encode::u32_buffer(); match self { - Protocol::DNS4(s) => { + Protocol::Dns4(s) => { w.put(encode::u32(DNS4, &mut buf)); let bytes = s.as_bytes(); w.put(encode::usize(bytes.len(), &mut encode::usize_buffer())); w.put(bytes) } - Protocol::DNS6(s) => { + Protocol::Dns6(s) => { w.put(encode::u32(DNS6, &mut buf)); let bytes = s.as_bytes(); w.put(encode::usize(bytes.len(), &mut encode::usize_buffer())); w.put(bytes) } - Protocol::IP4(addr) => { + Protocol::Ip4(addr) => { w.put(encode::u32(IP4, &mut buf)); w.put(&addr.octets()[..]) } - Protocol::IP6(addr) => { + Protocol::Ip6(addr) => { w.put(encode::u32(IP6, &mut buf)); for &segment in &addr.segments() { w.put_u16(segment) } } - Protocol::TCP(port) => { + Protocol::Tcp(port) => { w.put(encode::u32(TCP, &mut buf)); w.put_u16(*port) } - Protocol::TLS(s) => { + Protocol::Tls(s) => { w.put(encode::u32(TLS, &mut buf)); let bytes = s.as_bytes(); w.put(encode::usize(bytes.len(), &mut encode::usize_buffer())); @@ -202,12 +202,12 @@ impl<'a> Protocol<'a> { /// Turn this `Protocol` into one that owns its data, thus being valid for any lifetime. pub fn acquire<'b>(self) -> Protocol<'b> { match self { - Protocol::DNS4(s) => Protocol::DNS4(Cow::Owned(s.into_owned())), - Protocol::DNS6(s) => Protocol::DNS6(Cow::Owned(s.into_owned())), - Protocol::IP4(addr) => Protocol::IP4(addr), - Protocol::IP6(addr) => Protocol::IP6(addr), - Protocol::TCP(port) => Protocol::TCP(port), - Protocol::TLS(s) => Protocol::TLS(Cow::Owned(s.into_owned())), + Protocol::Dns4(s) => Protocol::Dns4(Cow::Owned(s.into_owned())), + Protocol::Dns6(s) => Protocol::Dns6(Cow::Owned(s.into_owned())), + Protocol::Ip4(addr) => Protocol::Ip4(addr), + Protocol::Ip6(addr) => Protocol::Ip6(addr), + Protocol::Tcp(port) => Protocol::Tcp(port), + Protocol::Tls(s) => Protocol::Tls(Cow::Owned(s.into_owned())), Protocol::P2P(s) => Protocol::P2P(Cow::Owned(s.into_owned())), Protocol::Ws => Protocol::Ws, Protocol::Wss => Protocol::Wss, @@ -219,13 +219,13 @@ impl<'a> fmt::Display for Protocol<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Protocol::*; match self { - DNS4(s) => write!(f, "/dns4/{}", s), - DNS6(s) => write!(f, "/dns6/{}", s), - IP4(addr) => write!(f, "/ip4/{}", addr), - IP6(addr) => write!(f, "/ip6/{}", addr), + Dns4(s) => write!(f, "/dns4/{}", s), + Dns6(s) => write!(f, "/dns6/{}", s), + Ip4(addr) => write!(f, "/ip4/{}", addr), + Ip6(addr) => write!(f, "/ip6/{}", addr), P2P(c) => write!(f, "/p2p/{}", bs58::encode(c).into_string()), - TCP(port) => write!(f, "/tcp/{}", port), - TLS(s) => write!(f, "/tls/{}", s), + Tcp(port) => write!(f, "/tcp/{}", port), + Tls(s) => write!(f, "/tls/{}", s), Ws => write!(f, "/ws"), Wss => write!(f, "/wss"), } @@ -236,8 +236,8 @@ impl<'a> From for Protocol<'a> { #[inline] fn from(addr: IpAddr) -> Self { match addr { - IpAddr::V4(addr) => Protocol::IP4(addr), - IpAddr::V6(addr) => Protocol::IP6(addr), + IpAddr::V4(addr) => Protocol::Ip4(addr), + IpAddr::V6(addr) => Protocol::Ip6(addr), } } } @@ -245,14 +245,14 @@ impl<'a> From for Protocol<'a> { impl<'a> From for Protocol<'a> { #[inline] fn from(addr: Ipv4Addr) -> Self { - Protocol::IP4(addr) + Protocol::Ip4(addr) } } impl<'a> From for Protocol<'a> { #[inline] fn from(addr: Ipv6Addr) -> Self { - Protocol::IP6(addr) + Protocol::Ip6(addr) } } diff --git a/rust-toolchain b/rust-toolchain index 0a3db35b..ba0a7191 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -1.46.0 +1.51.0 diff --git a/secio/build.rs b/secio/build.rs index c5995724..a51b136a 100644 --- a/secio/build.rs +++ b/secio/build.rs @@ -1,11 +1,10 @@ use std::env; -#[allow(clippy::inconsistent_digit_grouping)] fn main() { if let Ok(v) = env::var("DEP_OPENSSL_VERSION_NUMBER") { let version = u64::from_str_radix(&v, 16).unwrap(); - if version >= 0x1_01_00_00_0 { + if version >= 0x1010_0000 { println!("cargo:rustc-cfg=ossl110"); } } diff --git a/secio/src/crypto/mod.rs b/secio/src/crypto/mod.rs index 418ab9f4..ed9ae4f7 100644 --- a/secio/src/crypto/mod.rs +++ b/secio/src/crypto/mod.rs @@ -49,7 +49,7 @@ pub enum CryptoMode { #[doc(hidden)] #[cfg(all(ossl110, unix))] pub fn new_stream(t: cipher::CipherType, key: &[u8], _mode: CryptoMode) -> BoxStreamCipher { - Box::new(openssl_impl::OpenSSLCrypt::new(t, key)) + Box::new(openssl_impl::OpenSsLCrypt::new(t, key)) } /// Generate a specific Cipher with key and initialize vector @@ -59,7 +59,7 @@ pub fn new_stream(t: cipher::CipherType, key: &[u8], mode: CryptoMode) -> BoxStr use cipher::CipherType::*; match t { - Aes128Gcm | Aes256Gcm => Box::new(openssl_impl::OpenSSLCrypt::new(t, key)), + Aes128Gcm | Aes256Gcm => Box::new(openssl_impl::OpenSsLCrypt::new(t, key)), ChaCha20Poly1305 => Box::new(ring_impl::RingAeadCipher::new(t, key, mode)), } } @@ -100,7 +100,7 @@ fn nonce_advance(nonce: &mut [u8]) { #[cfg(all(test, unix))] mod test { use super::{ - cipher::CipherType, openssl_impl::OpenSSLCrypt, ring_impl::RingAeadCipher, + cipher::CipherType, openssl_impl::OpenSsLCrypt, ring_impl::RingAeadCipher, wasm_compat::WasmCrypt, CryptoMode, }; @@ -109,7 +109,7 @@ mod test { .map(|_| rand::random::()) .collect::>(); - let mut openssl_encrypt = OpenSSLCrypt::new(cipher, &key); + let mut openssl_encrypt = OpenSsLCrypt::new(cipher, &key); let mut ring_decrypt = RingAeadCipher::new(cipher, &key, CryptoMode::Decrypt); // first time @@ -135,7 +135,7 @@ mod test { .collect::>(); let mut ring_encrypt = RingAeadCipher::new(cipher, &key, CryptoMode::Encrypt); - let mut openssl_decrypt = OpenSSLCrypt::new(cipher, &key); + let mut openssl_decrypt = OpenSsLCrypt::new(cipher, &key); // first time let message = b"HELLO WORLD"; @@ -185,7 +185,7 @@ mod test { .collect::>(); let mut wasm_encrypt = WasmCrypt::new(cipher, &key); - let mut openssl_decrypt = OpenSSLCrypt::new(cipher, &key); + let mut openssl_decrypt = OpenSsLCrypt::new(cipher, &key); // first time let message = b"HELLO WORLD"; diff --git a/secio/src/crypto/openssl_impl.rs b/secio/src/crypto/openssl_impl.rs index 980b8472..337528dc 100644 --- a/secio/src/crypto/openssl_impl.rs +++ b/secio/src/crypto/openssl_impl.rs @@ -6,14 +6,14 @@ use crate::{ error::SecioError, }; -pub(crate) struct OpenSSLCrypt { +pub(crate) struct OpenSsLCrypt { cipher: symm::Cipher, cipher_type: CipherType, key: Bytes, iv: BytesMut, } -impl OpenSSLCrypt { +impl OpenSsLCrypt { pub fn new(cipher_type: CipherType, key: &[u8]) -> Self { let cipher = match cipher_type { CipherType::Aes128Gcm => symm::Cipher::aes_128_gcm(), @@ -22,7 +22,7 @@ impl OpenSSLCrypt { CipherType::ChaCha20Poly1305 => symm::Cipher::chacha20_poly1305(), #[cfg(not(ossl110))] _ => panic!( - "Cipher type {:?} does not supported by OpenSSLCrypt yet", + "Cipher type {:?} does not supported by OpenSsLCrypt yet", cipher_type ), }; @@ -35,7 +35,7 @@ impl OpenSSLCrypt { ::std::ptr::write_bytes(nonce.as_mut_ptr(), 0, nonce_size); } - OpenSSLCrypt { + OpenSsLCrypt { cipher, cipher_type, key: Bytes::from(key.to_owned()), @@ -86,7 +86,7 @@ impl OpenSSLCrypt { } } -impl StreamCipher for OpenSSLCrypt { +impl StreamCipher for OpenSsLCrypt { fn encrypt(&mut self, input: &[u8]) -> Result, SecioError> { self.encrypt(input) } @@ -98,15 +98,15 @@ impl StreamCipher for OpenSSLCrypt { #[cfg(test)] mod test { - use super::{CipherType, OpenSSLCrypt}; + use super::{CipherType, OpenSsLCrypt}; fn test_openssl(mode: CipherType) { let key = (0..mode.key_size()) .map(|_| rand::random::()) .collect::>(); - let mut encryptor = OpenSSLCrypt::new(mode, &key[0..]); - let mut decryptor = OpenSSLCrypt::new(mode, &key[0..]); + let mut encryptor = OpenSsLCrypt::new(mode, &key[0..]); + let mut decryptor = OpenSsLCrypt::new(mode, &key[0..]); // first time let message = b"HELLO WORLD"; diff --git a/secio/src/dh_compat/native.rs b/secio/src/dh_compat/native.rs index 5aa56ea3..49776704 100644 --- a/secio/src/dh_compat/native.rs +++ b/secio/src/dh_compat/native.rs @@ -8,10 +8,10 @@ use super::KeyAgreement; use crate::error::SecioError; pub use ring::agreement::EphemeralPrivateKey; -impl Into<&'static agreement::Algorithm> for KeyAgreement { +impl From for &'static agreement::Algorithm { #[inline] - fn into(self) -> &'static agreement::Algorithm { - match self { + fn from(a: KeyAgreement) -> &'static agreement::Algorithm { + match a { KeyAgreement::EcdhP256 => &agreement::ECDH_P256, KeyAgreement::EcdhP384 => &agreement::ECDH_P384, KeyAgreement::X25519 => &agreement::X25519, diff --git a/secio/src/error.rs b/secio/src/error.rs index 04709806..86eeead9 100644 --- a/secio/src/error.rs +++ b/secio/src/error.rs @@ -75,9 +75,10 @@ impl From for SecioError { } } -impl Into for SecioError { - fn into(self) -> io::Error { - match self { +impl From for io::Error { + #[inline] + fn from(err: SecioError) -> io::Error { + match err { SecioError::IoError(e) => e, e => io::Error::new(io::ErrorKind::BrokenPipe, e.to_string()), } diff --git a/secio/src/peer_id.rs b/secio/src/peer_id.rs index 48ddc2e6..c07c4ac1 100644 --- a/secio/src/peer_id.rs +++ b/secio/src/peer_id.rs @@ -26,23 +26,23 @@ impl PeerId { } /// If data is a valid `PeerId`, return `PeerId`, else return error - pub fn from_bytes(data: Vec) -> Result { + pub fn from_bytes(data: Vec) -> Result { if data.is_empty() { - return Err(()); + return Err(Error::Empty); } - let (code, bytes) = decode::u16(&data).map_err(|_| ())?; + let (code, bytes) = decode::u16(&data).map_err(|_| Error::InvalidData)?; if code != SHA256_CODE { - return Err(()); + return Err(Error::NotSupportHashCode); } if bytes.len() != SHA256_SIZE as usize + 1 { - return Err(()); + return Err(Error::WrongLength); } if bytes[0] != SHA256_SIZE { - return Err(()); + return Err(Error::InvalidData); } Ok(PeerId { inner: data }) @@ -119,15 +119,41 @@ impl From for PeerId { } impl ::std::str::FromStr for PeerId { - type Err = (); + type Err = Error; #[inline] fn from_str(s: &str) -> Result { - let bytes = bs58::decode(s).into_vec().map_err(|_| ())?; + let bytes = bs58::decode(s).into_vec().map_err(|_| Error::InvalidData)?; PeerId::from_bytes(bytes) } } +/// Error code from generate peer id +#[derive(Debug)] +pub enum Error { + /// invalid data + InvalidData, + /// data has wrong length + WrongLength, + /// not support hash code + NotSupportHashCode, + /// empty data + Empty, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Empty => write!(f, "data is empty"), + Error::InvalidData => write!(f, "invalid data"), + Error::WrongLength => write!(f, "wrong length"), + Error::NotSupportHashCode => write!(f, "not support hash code"), + } + } +} + +impl ::std::error::Error for Error {} + #[cfg(test)] mod tests { use crate::{peer_id::PeerId, SecioKeyPair}; diff --git a/tentacle/src/buffer.rs b/tentacle/src/buffer.rs index 93589ad3..13893ab6 100644 --- a/tentacle/src/buffer.rs +++ b/tentacle/src/buffer.rs @@ -234,10 +234,9 @@ mod test { assert_eq!(buffer.normal_buffer, VecDeque::from(vec![5, 6])); let res: Vec<_> = block_on(async { - let mut a = Vec::new(); - a.push(rx.next().await.unwrap().1); - a.push(rx.next().await.unwrap().1); - a + let v1 = rx.next().await.unwrap().1; + let v2 = rx.next().await.unwrap().1; + vec![v1, v2] }); assert_eq!(res, vec![1, 2]); @@ -252,10 +251,9 @@ mod test { assert_eq!(buffer.normal_buffer, VecDeque::from(vec![5, 6])); let res: Vec<_> = block_on(async { - let mut a = Vec::new(); - a.push(rx.next().await.unwrap().1); - a.push(rx.next().await.unwrap().1); - a + let v1 = rx.next().await.unwrap().1; + let v2 = rx.next().await.unwrap().1; + vec![v1, v2] }); assert_eq!(res, vec![3, 4]); @@ -290,10 +288,9 @@ mod test { assert_eq!(buffer.buffer, VecDeque::from(vec![3, 4, 5])); let res: Vec<_> = block_on(async { - let mut a = Vec::new(); - a.push(rx.next().await.unwrap()); - a.push(rx.next().await.unwrap()); - a + let v1 = rx.next().await.unwrap(); + let v2 = rx.next().await.unwrap(); + vec![v1, v2] }); assert_eq!(res, vec![1, 2]); diff --git a/tentacle/src/channel/bound.rs b/tentacle/src/channel/bound.rs index 39211f9d..05293d68 100644 --- a/tentacle/src/channel/bound.rs +++ b/tentacle/src/channel/bound.rs @@ -364,19 +364,24 @@ impl Clone for BoundedSenderInner { debug_assert!(curr < self.inner.max_senders()); let next = curr + 1; - let actual = self.inner.num_senders.compare_and_swap(curr, next, SeqCst); - - // The ABA problem doesn't matter here. We only care that the - // number of senders never exceeds the maximum. - if actual == curr { - return BoundedSenderInner { - inner: self.inner.clone(), - sender_task: Arc::new(Mutex::new(SenderTask::new())), - maybe_parked: AtomicBool::new(false), - }; + match self + .inner + .num_senders + .compare_exchange(curr, next, SeqCst, SeqCst) + { + Ok(actual) => { + // The ABA problem doesn't matter here. We only care that the + // number of senders never exceeds the maximum. + if actual == curr { + return BoundedSenderInner { + inner: self.inner.clone(), + sender_task: Arc::new(Mutex::new(SenderTask::new())), + maybe_parked: AtomicBool::new(false), + }; + } + } + Err(actual) => curr = actual, } - - curr = actual; } } } diff --git a/tentacle/src/channel/unbound.rs b/tentacle/src/channel/unbound.rs index 0b604365..7a7b025f 100644 --- a/tentacle/src/channel/unbound.rs +++ b/tentacle/src/channel/unbound.rs @@ -190,17 +190,22 @@ impl Clone for UnboundedSenderInner { debug_assert!(curr < MAX_BUFFER); let next = curr + 1; - let actual = self.inner.num_senders.compare_and_swap(curr, next, SeqCst); - - // The ABA problem doesn't matter here. We only care that the - // number of senders never exceeds the maximum. - if actual == curr { - return UnboundedSenderInner { - inner: self.inner.clone(), - }; + match self + .inner + .num_senders + .compare_exchange(curr, next, SeqCst, SeqCst) + { + Ok(actual) => { + // The ABA problem doesn't matter here. We only care that the + // number of senders never exceeds the maximum. + if actual == curr { + return UnboundedSenderInner { + inner: self.inner.clone(), + }; + } + } + Err(actual) => curr = actual, } - - curr = actual; } } } diff --git a/tentacle/src/error.rs b/tentacle/src/error.rs index 2b7e7e90..95f7de7a 100644 --- a/tentacle/src/error.rs +++ b/tentacle/src/error.rs @@ -14,7 +14,7 @@ pub enum TransportErrorKind { NotSupported(Multiaddr), /// Dns resolver error #[error("can not resolve `{0:?}`, io error: `{1:?}`")] - DNSResolverError(Multiaddr, IOError), + DnsResolverError(Multiaddr, IOError), } #[derive(Error, Debug)] diff --git a/tentacle/src/service.rs b/tentacle/src/service.rs index a4555417..8d24831f 100644 --- a/tentacle/src/service.rs +++ b/tentacle/src/service.rs @@ -77,7 +77,7 @@ pub struct Service { listens: HashSet, #[cfg(all(not(target_arch = "wasm32"), feature = "upnp"))] - igd_client: Option, + igd_client: Option, dial_protocols: HashMap, config: ServiceConfig, @@ -143,7 +143,7 @@ where let shutdown = Arc::new(AtomicBool::new(false)); #[cfg(all(not(target_arch = "wasm32"), feature = "upnp"))] let igd_client = if config.upnp { - crate::upnp::IGDClient::new() + crate::upnp::IgdClient::new() } else { None }; diff --git a/tentacle/src/service/helper.rs b/tentacle/src/service/helper.rs index 0ce6e2eb..504092fb 100644 --- a/tentacle/src/service/helper.rs +++ b/tentacle/src/service/helper.rs @@ -62,10 +62,10 @@ impl From for SessionType { } } -impl Into for SessionType { +impl From for YamuxType { #[inline] - fn into(self) -> YamuxType { - match self { + fn from(ty: SessionType) -> YamuxType { + match ty { SessionType::Outbound => YamuxType::Client, SessionType::Inbound => YamuxType::Server, } diff --git a/tentacle/src/session.rs b/tentacle/src/session.rs index 24a0bdc1..807c51bf 100644 --- a/tentacle/src/session.rs +++ b/tentacle/src/session.rs @@ -31,9 +31,9 @@ use crate::{ ProtocolId, SessionId, StreamId, SubstreamReadPart, }; -pub trait AsyncRW: AsyncWrite + AsyncRead {} +pub trait AsyncRw: AsyncWrite + AsyncRead {} -impl AsyncRW for T {} +impl AsyncRw for T {} /// Event generated/received by the Session pub(crate) enum SessionEvent { @@ -49,7 +49,7 @@ pub(crate) enum SessionEvent { HandshakeSuccess { /// In order to be compatible with multiple underlying connection abstractions, /// the dyn trait needs to be used here - handle: Box, + handle: Box, /// Remote Public key public_key: Option, /// Remote address diff --git a/tentacle/src/transports/browser.rs b/tentacle/src/transports/browser.rs index a2189fa6..7920a6a6 100644 --- a/tentacle/src/transports/browser.rs +++ b/tentacle/src/transports/browser.rs @@ -53,7 +53,7 @@ async fn connect(addr: Multiaddr, timeout: Duration) -> Result<(Multiaddr, Brows return Err(TransportErrorKind::NotSupported(addr.clone())); } match iter.peek() { - Some(Protocol::DNS4(_)) | Some(Protocol::DNS6(_)) => (), + Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => (), _ => { // this ignore is true let _ignore = iter.next(); @@ -69,10 +69,10 @@ async fn connect(addr: Multiaddr, timeout: Duration) -> Result<(Multiaddr, Brows .ok_or(TransportErrorKind::NotSupported(addr.clone()))?; match (proto1, proto2) { - (Protocol::DNS4(domain), Protocol::TCP(port)) => { + (Protocol::Dns4(domain), Protocol::Tcp(port)) => { break format!("ws://{}:{}", domain, port) } - (Protocol::DNS6(domain), Protocol::TCP(port)) => { + (Protocol::Dns6(domain), Protocol::Tcp(port)) => { break format!("ws://{}:{}", domain, port) } _ => return Err(TransportErrorKind::NotSupported(addr.clone())), diff --git a/tentacle/src/transports/mod.rs b/tentacle/src/transports/mod.rs index 8e06d438..3cc89660 100644 --- a/tentacle/src/transports/mod.rs +++ b/tentacle/src/transports/mod.rs @@ -33,7 +33,7 @@ pub enum TransportType { Ws, Wss, Tcp, - TLS, + Tls, } pub fn find_type(addr: &Multiaddr) -> TransportType { @@ -44,8 +44,8 @@ pub fn find_type(addr: &Multiaddr) -> TransportType { Some(TransportType::Ws) } else if let Protocol::Wss = proto { Some(TransportType::Wss) - } else if let Protocol::TLS(_) = proto { - Some(TransportType::TLS) + } else if let Protocol::Tls(_) = proto { + Some(TransportType::Tls) } else { None } @@ -133,7 +133,7 @@ mod os { #[cfg(not(feature = "ws"))] TransportType::Ws => Err(TransportErrorKind::NotSupported(address)), TransportType::Wss => Err(TransportErrorKind::NotSupported(address)), - TransportType::TLS => Err(TransportErrorKind::NotSupported(address)), + TransportType::Tls => Err(TransportErrorKind::NotSupported(address)), } } @@ -155,7 +155,7 @@ mod os { #[cfg(not(feature = "ws"))] TransportType::Ws => Err(TransportErrorKind::NotSupported(address)), TransportType::Wss => Err(TransportErrorKind::NotSupported(address)), - TransportType::TLS => Err(TransportErrorKind::NotSupported(address)), + TransportType::Tls => Err(TransportErrorKind::NotSupported(address)), } } } @@ -369,8 +369,8 @@ mod test { assert_eq!(find_type(&a), TransportType::Tcp); - a.push(Protocol::TLS(Cow::Owned("/".to_string()))); + a.push(Protocol::Tls(Cow::Owned("/".to_string()))); - assert_eq!(find_type(&a), TransportType::TLS); + assert_eq!(find_type(&a), TransportType::Tls); } } diff --git a/tentacle/src/transports/tcp.rs b/tentacle/src/transports/tcp.rs index 1ebb5ea4..54252f9d 100644 --- a/tentacle/src/transports/tcp.rs +++ b/tentacle/src/transports/tcp.rs @@ -13,7 +13,7 @@ use crate::{ multiaddr::Multiaddr, runtime::{TcpListener, TcpStream}, transports::{tcp_dial, tcp_listen, Transport}, - utils::{dns::DNSResolver, multiaddr_to_socketaddr, socketaddr_to_multiaddr}, + utils::{dns::DnsResolver, multiaddr_to_socketaddr, socketaddr_to_multiaddr}, }; /// Tcp listen bind @@ -69,11 +69,11 @@ impl Transport for TcpTransport { type DialFuture = TcpDialFuture; fn listen(self, address: Multiaddr) -> Result { - match DNSResolver::new(address.clone()) { + match DnsResolver::new(address.clone()) { Some(dns) => { let task = bind( dns.map_err(|(multiaddr, io_error)| { - TransportErrorKind::DNSResolverError(multiaddr, io_error) + TransportErrorKind::DnsResolverError(multiaddr, io_error) }), self.bind_addr.is_some(), ); @@ -87,13 +87,13 @@ impl Transport for TcpTransport { } fn dial(self, address: Multiaddr) -> Result { - match DNSResolver::new(address.clone()) { + match DnsResolver::new(address.clone()) { Some(dns) => { // Why do this? // Because here need to save the original address as an index to open the specified protocol. let task = connect( dns.map_err(|(multiaddr, io_error)| { - TransportErrorKind::DNSResolverError(multiaddr, io_error) + TransportErrorKind::DnsResolverError(multiaddr, io_error) }), self.timeout, Some(address), diff --git a/tentacle/src/transports/ws.rs b/tentacle/src/transports/ws.rs index b14fb0b6..0f73f578 100644 --- a/tentacle/src/transports/ws.rs +++ b/tentacle/src/transports/ws.rs @@ -24,7 +24,7 @@ use crate::{ multiaddr::{Multiaddr, Protocol}, runtime::{TcpListener, TcpStream}, transports::{tcp_dial, tcp_listen, Result, Transport}, - utils::{dns::DNSResolver, multiaddr_to_socketaddr, socketaddr_to_multiaddr}, + utils::{dns::DnsResolver, multiaddr_to_socketaddr, socketaddr_to_multiaddr}, }; /// websocket listen bind @@ -93,11 +93,11 @@ impl Transport for WsTransport { type DialFuture = WsDialFuture; fn listen(self, address: Multiaddr) -> Result { - match DNSResolver::new(address.clone()) { + match DnsResolver::new(address.clone()) { Some(dns) => { let task = bind( dns.map_err(|(multiaddr, io_error)| { - TransportErrorKind::DNSResolverError(multiaddr, io_error) + TransportErrorKind::DnsResolverError(multiaddr, io_error) }), self.timeout, self.bind_addr.is_some(), @@ -112,13 +112,13 @@ impl Transport for WsTransport { } fn dial(self, address: Multiaddr) -> Result { - match DNSResolver::new(address.clone()) { + match DnsResolver::new(address.clone()) { Some(dns) => { // Why do this? // Because here need to save the original address as an index to open the specified protocol. let task = connect( dns.map_err(|(multiaddr, io_error)| { - TransportErrorKind::DNSResolverError(multiaddr, io_error) + TransportErrorKind::DnsResolverError(multiaddr, io_error) }), self.timeout, Some(address), diff --git a/tentacle/src/upnp/mod.rs b/tentacle/src/upnp/mod.rs index 4ac11f3a..041ae887 100644 --- a/tentacle/src/upnp/mod.rs +++ b/tentacle/src/upnp/mod.rs @@ -30,7 +30,7 @@ pub struct Network { net_mask: Ipv4Addr, } -pub struct IGDClient { +pub struct IgdClient { gateway: igd::Gateway, state: Network, only_leases_support: bool, @@ -38,7 +38,7 @@ pub struct IGDClient { leases: HashMap>, } -impl IGDClient { +impl IgdClient { /// init pub fn new() -> Option { let gateway = match igd::search_gateway(Default::default()) { @@ -77,7 +77,7 @@ impl IGDClient { }) })?; - Some(IGDClient { + Some(IgdClient { gateway, state, only_leases_support: false, @@ -174,7 +174,7 @@ impl IGDClient { } } -impl Drop for IGDClient { +impl Drop for IgdClient { fn drop(&mut self) { self.clear(); } diff --git a/tentacle/src/utils.rs b/tentacle/src/utils.rs index ec92b997..f6dfc30f 100644 --- a/tentacle/src/utils.rs +++ b/tentacle/src/utils.rs @@ -7,7 +7,7 @@ use std::{ net::{IpAddr, SocketAddr}, }; -/// This module create a `DNSResolver` future task to DNS resolver +/// This module create a `DnsResolver` future task to DNS resolver #[cfg(not(target_arch = "wasm32"))] pub mod dns; @@ -65,7 +65,7 @@ pub fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Option { while iter.peek().is_some() { match iter.peek() { - Some(Protocol::IP4(_)) | Some(Protocol::IP6(_)) => (), + Some(Protocol::Ip4(_)) | Some(Protocol::Ip6(_)) => (), _ => { // ignore is true let _ignore = iter.next(); @@ -77,10 +77,10 @@ pub fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Option { let proto2 = iter.next()?; match (proto1, proto2) { - (Protocol::IP4(ip), Protocol::TCP(port)) => { + (Protocol::Ip4(ip), Protocol::Tcp(port)) => { return Some(SocketAddr::new(ip.into(), port)); } - (Protocol::IP6(ip), Protocol::TCP(port)) => { + (Protocol::Ip6(ip), Protocol::Tcp(port)) => { return Some(SocketAddr::new(ip.into(), port)); } _ => (), @@ -93,11 +93,11 @@ pub fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Option { /// convert socket address to multiaddr pub fn socketaddr_to_multiaddr(address: SocketAddr) -> Multiaddr { let proto = match address.ip() { - IpAddr::V4(ip) => Protocol::IP4(ip), - IpAddr::V6(ip) => Protocol::IP6(ip), + IpAddr::V4(ip) => Protocol::Ip4(ip), + IpAddr::V6(ip) => Protocol::Ip6(ip), }; iter::once(proto) - .chain(iter::once(Protocol::TCP(address.port()))) + .chain(iter::once(Protocol::Tcp(address.port()))) .collect() } diff --git a/tentacle/src/utils/dns.rs b/tentacle/src/utils/dns.rs index 702be363..a884caed 100644 --- a/tentacle/src/utils/dns.rs +++ b/tentacle/src/utils/dns.rs @@ -17,7 +17,7 @@ use crate::{ }; /// DNS resolver, use on multi-thread tokio runtime -pub struct DNSResolver { +pub struct DnsResolver { source_address: Multiaddr, ty: TransportType, peer_id: Option, @@ -26,7 +26,7 @@ pub struct DNSResolver { join_handle: Option>>>, } -impl DNSResolver { +impl DnsResolver { /// If address like `/dns4/localhost/tcp/80` or `"/dns6/localhost/tcp/80"`, /// it will be return Some, else None pub fn new(source_address: Multiaddr) -> Option { @@ -37,7 +37,7 @@ impl DNSResolver { break (None, None); } match iter.peek() { - Some(Protocol::DNS4(_)) | Some(Protocol::DNS6(_)) => (), + Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => (), _ => { // this ignore is true let _ignore = iter.next(); @@ -49,14 +49,14 @@ impl DNSResolver { let proto2 = iter.next()?; match (proto1, proto2) { - (Protocol::DNS4(domain), Protocol::TCP(port)) => break (Some(domain), Some(port)), - (Protocol::DNS6(domain), Protocol::TCP(port)) => break (Some(domain), Some(port)), + (Protocol::Dns4(domain), Protocol::Tcp(port)) => break (Some(domain), Some(port)), + (Protocol::Dns6(domain), Protocol::Tcp(port)) => break (Some(domain), Some(port)), _ => (), } }; match (domain, port) { - (Some(domain), Some(port)) => Some(DNSResolver { + (Some(domain), Some(port)) => Some(DnsResolver { ty: find_type(&source_address), peer_id: extract_peer_id(&source_address), domain: domain.to_string(), @@ -76,7 +76,7 @@ impl DNSResolver { Some(address) => { let mut address = socketaddr_to_multiaddr(address); match self.ty { - TransportType::Tcp | TransportType::TLS => (), + TransportType::Tcp | TransportType::Tls => (), TransportType::Ws => address.push(Protocol::Ws), TransportType::Wss => address.push(Protocol::Wss), } @@ -94,7 +94,7 @@ impl DNSResolver { } } -impl Future for DNSResolver { +impl Future for DnsResolver { type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { @@ -140,20 +140,20 @@ impl Future for DNSResolver { mod test { use crate::{ multiaddr::{Multiaddr, Protocol}, - utils::dns::DNSResolver, + utils::dns::DnsResolver, }; #[test] fn dns_parser() { - let future: DNSResolver = - DNSResolver::new("/dns4/localhost/tcp/80".parse().unwrap()).unwrap(); + let future: DnsResolver = + DnsResolver::new("/dns4/localhost/tcp/80".parse().unwrap()).unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); let addr = rt.block_on(future).unwrap(); match addr.iter().next().unwrap() { - Protocol::IP4(_) => { + Protocol::Ip4(_) => { assert_eq!("/ip4/127.0.0.1/tcp/80".parse::().unwrap(), addr) } - Protocol::IP6(_) => assert_eq!("/ip6/::1/tcp/80".parse::().unwrap(), addr), + Protocol::Ip6(_) => assert_eq!("/ip6/::1/tcp/80".parse::().unwrap(), addr), _ => panic!("Dns resolver fail"), } } diff --git a/yamux/src/session.rs b/yamux/src/session.rs index 5682ee68..89f56a45 100644 --- a/yamux/src/session.rs +++ b/yamux/src/session.rs @@ -1097,9 +1097,11 @@ mod test { rt.block_on(async { let (remote, local) = MockSocket::new(); - let mut config = Config::default(); - config.enable_keepalive = false; - config.max_stream_count = 1; + let config = Config { + enable_keepalive: false, + max_stream_count: 1, + ..Default::default() + }; let mut session = Session::new_server(local, config); @@ -1147,9 +1149,11 @@ mod test { rt.block_on(async { let (_remote, local) = MockSocket::new(); - let mut config = Config::default(); - config.enable_keepalive = false; - config.connection_write_timeout = Duration::from_secs(1); + let config = Config { + enable_keepalive: false, + connection_write_timeout: Duration::from_secs(1), + ..Default::default() + }; let mut session = Session::new_server(local, config);