Skip to content

Commit

Permalink
fix code style
Browse files Browse the repository at this point in the history
  • Loading branch information
navichok26 committed Feb 14, 2024
1 parent 2276948 commit 694b4e6
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 39 deletions.
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ Minimal ADNL implementation in Rust (client-server only, without p2p for now). S
Run this example: `cargo run --example time`

```rust
use std::net::SocketAddrV4;
use adnl::AdnlClient;
use anyhow::{anyhow, Context, Result};
use std::net::SocketAddrV4;


#[tokio::main]
async fn main() -> Result<()> {
Expand All @@ -28,10 +29,8 @@ async fn main() -> Result<()> {
let ls_ip = "65.21.74.140";
let ls_port = 46427;
// create AdnlClient
let mut client = AdnlClient::connect(
remote_public,
SocketAddrV4::new(ls_ip.parse()?, ls_port)
).await?;
let mut client =
AdnlClient::connect(remote_public, SocketAddrV4::new(ls_ip.parse()?, ls_port)).await?;

// already serialized TL with gettime query
let mut query = hex::decode("7af98bb435263e6c95d6fecb497dfd0aa5f031e7d412986b5ce720496db512052e8f2d100cdf068c7904345aad16000000000000")?;
Expand All @@ -50,5 +49,4 @@ async fn main() -> Result<()> {
);
Ok(())
}

```
9 changes: 4 additions & 5 deletions examples/time.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::net::SocketAddrV4;
use adnl::AdnlClient;
use anyhow::{anyhow, Context, Result};
use std::net::SocketAddrV4;


#[tokio::main]
async fn main() -> Result<()> {
Expand All @@ -12,10 +13,8 @@ async fn main() -> Result<()> {
let ls_ip = "65.21.74.140";
let ls_port = 46427;
// create AdnlClient
let mut client = AdnlClient::connect(
remote_public,
SocketAddrV4::new(ls_ip.parse()?, ls_port)
).await?;
let mut client =
AdnlClient::connect(remote_public, SocketAddrV4::new(ls_ip.parse()?, ls_port)).await?;

// already serialized TL with gettime query
let mut query = hex::decode("7af98bb435263e6c95d6fecb497dfd0aa5f031e7d412986b5ce720496db512052e8f2d100cdf068c7904345aad16000000000000")?;
Expand Down
6 changes: 3 additions & 3 deletions src/helper_types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use sha2::{Digest, Sha256};
use std::io::Error;
use std::net::AddrParseError;
use sha2::{Digest, Sha256};
use thiserror::Error;

pub trait CryptoRandom: rand_core::RngCore + rand_core::CryptoRng {}
Expand All @@ -12,7 +12,7 @@ pub trait AdnlPublicKey {
let mut hasher = Sha256::new();
hasher.update([0xc6, 0xb4, 0x13, 0x48]); // type id - always ed25519
hasher.update(self.to_bytes());
AdnlAddress(hasher.finalize().try_into().unwrap())
AdnlAddress(hasher.finalize().into())
}

fn to_bytes(&self) -> [u8; 32];
Expand Down Expand Up @@ -162,5 +162,5 @@ pub enum AdnlError {
#[error("Incorrect ip address")]
IncorrectAddr(AddrParseError),
#[error(transparent)]
OtherError(#[from] Error)
OtherError(#[from] Error),
}
2 changes: 1 addition & 1 deletion src/primitives/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl<P: AdnlPublicKey> AdnlHandshake<P> {
let mut raw_params = self.aes_params.to_bytes();
let mut hasher = Sha256::new();
hasher.update(raw_params);
let hash: [u8; 32] = hasher.finalize().try_into().unwrap();
let hash: [u8; 32] = hasher.finalize().into();

let mut key = [0u8; 32];
key[..16].copy_from_slice(&self.secret.as_bytes()[..16]);
Expand Down
21 changes: 14 additions & 7 deletions src/primitives/receive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ impl AdnlReceiver {
let mut length = [0u8; 4];
log::debug!("reading length");
transport
.read_exact(&mut length).await
.read_exact(&mut length)
.await
.map_err(AdnlError::ReadError)?;
self.aes.apply_keystream(&mut length);
let length = u32::from_le_bytes(length);
Expand All @@ -49,7 +50,8 @@ impl AdnlReceiver {
let mut nonce = [0u8; 32];
log::debug!("reading nonce");
transport
.read_exact(&mut nonce).await
.read_exact(&mut nonce)
.await
.map_err(AdnlError::ReadError)?;
self.aes.apply_keystream(&mut nonce);
hasher.update(nonce);
Expand All @@ -65,12 +67,14 @@ impl AdnlReceiver {
bytes_to_read
);
transport
.read_exact(&mut buffer).await
.read_exact(&mut buffer)
.await
.map_err(AdnlError::ReadError)?;
self.aes.apply_keystream(&mut buffer);
hasher.update(buffer);
consumer
.write_all(&buffer).await
.write_all(&buffer)
.await
.map_err(AdnlError::WriteError)?;
bytes_to_read -= BUFFER;
}
Expand All @@ -80,20 +84,23 @@ impl AdnlReceiver {
log::debug!("last chunk, {} bytes remaining", bytes_to_read);
let buffer = &mut buffer[..bytes_to_read];
transport
.read_exact(buffer).await
.read_exact(buffer)
.await
.map_err(AdnlError::ReadError)?;
self.aes.apply_keystream(buffer);
hasher.update(&buffer);
consumer
.write_all(buffer).await
.write_all(buffer)
.await
.map_err(AdnlError::WriteError)?;
}
}

let mut given_hash = [0u8; 32];
log::debug!("reading hash");
transport
.read_exact(&mut given_hash).await
.read_exact(&mut given_hash)
.await
.map_err(AdnlError::ReadError)?;
self.aes.apply_keystream(&mut given_hash);

Expand Down
14 changes: 9 additions & 5 deletions src/primitives/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl AdnlSender {
let mut hasher = Sha256::new();
hasher.update(*nonce);
hasher.update(&*buffer);
let mut hash: [u8; 32] = hasher.finalize().try_into().unwrap();
let mut hash: [u8; 32] = hasher.finalize().into();

// encrypt packet
self.aes.apply_keystream(&mut length);
Expand All @@ -49,16 +49,20 @@ impl AdnlSender {

// write to transport
transport
.write_all(&length).await
.write_all(&length)
.await
.map_err(AdnlError::WriteError)?;
transport
.write_all(nonce).await
.write_all(nonce)
.await
.map_err(AdnlError::WriteError)?;
transport
.write_all(buffer).await
.write_all(buffer)
.await
.map_err(AdnlError::WriteError)?;
transport
.write_all(&hash).await
.write_all(&hash)
.await
.map_err(AdnlError::WriteError)?;
transport.flush().await.map_err(AdnlError::WriteError)?;

Expand Down
4 changes: 3 additions & 1 deletion src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ async fn test_send(aes_params: Vec<u8>, nonce: Vec<u8>, buffer: Vec<u8>, expecte
let aes_params = AdnlAesParams::from(aes_params);
let mut protocol_client = AdnlSender::new(&aes_params);
let mut packet = Vec::<u8>::new();
let _result = protocol_client.send(&mut packet, &mut nonce, &mut buffer).await;
let _result = protocol_client
.send(&mut packet, &mut nonce, &mut buffer)
.await;
assert_eq!(
packet.as_slice(),
&expected_packet,
Expand Down
29 changes: 18 additions & 11 deletions src/wrappers/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{AdnlBuilder, AdnlError, AdnlHandshake, AdnlPublicKey, AdnlReceiver, AdnlSender};
use tokio::io::{AsyncReadExt, AsyncWriteExt, empty};
use tokio::io::{empty, AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, ToSocketAddrs};
use x25519_dalek::StaticSecret;

Expand Down Expand Up @@ -27,21 +27,22 @@ impl AdnlClient<TcpStream> {
// then perform handshake over our TcpStream
let client = AdnlBuilder::with_random_aes_params(&mut rand::rngs::OsRng)
.perform_ecdh(local_secret, ls_public)
.perform_handshake(transport).await?;
.perform_handshake(transport)
.await?;
Ok(client)
}
}

impl<T: AsyncReadExt + AsyncWriteExt + Unpin> AdnlClient<T> {

/// Send `handshake` over `transport` and check that handshake was successful
pub async fn perform_handshake<P: AdnlPublicKey>(
mut transport: T,
handshake: &AdnlHandshake<P>,
) -> Result<Self, AdnlError> {
// send handshake
transport
.write_all(&handshake.to_bytes()).await
.write_all(&handshake.to_bytes())
.await
.map_err(AdnlError::WriteError)?;

// receive empty message to ensure that server knows our AES keys
Expand All @@ -51,16 +52,21 @@ impl<T: AsyncReadExt + AsyncWriteExt + Unpin> AdnlClient<T> {
transport,
};
let mut empty = empty();
client.receiver.receive::<_, _, 0>(&mut client.transport, &mut empty).await?;
client
.receiver
.receive::<_, _, 0>(&mut client.transport, &mut empty)
.await?;
Ok(client)
}

/// Send `data` to another peer with random nonce
pub async fn send(
&mut self,
data: &mut [u8],
) -> Result<(), AdnlError> {
self.sender.send(&mut self.transport, &mut rand::random(), data).await
self.sender
.send(&mut self.transport, &mut rand::random(), data)
.await
}

/// Send `data` to another peer. Random `nonce` must be provided to eliminate bit-flipping attacks.
Expand All @@ -71,16 +77,16 @@ impl<T: AsyncReadExt + AsyncWriteExt + Unpin> AdnlClient<T> {
) -> Result<(), AdnlError> {
self.sender.send(&mut self.transport, nonce, data).await
}



/// Receive data from another peer into `consumer` which will process the data with
/// a `BUFFER` size of 8192 bytes.
pub async fn receive<C: AsyncWriteExt + Unpin>(
&mut self,
consumer: &mut C,
) -> Result<(), AdnlError> {
self.receiver
.receive::<_, _, 8192>(&mut self.transport, consumer).await
.receive::<_, _, 8192>(&mut self.transport, consumer)
.await
}

/// Receive data from another peer into `consumer` which will process the data. Set `BUFFER`
Expand All @@ -90,6 +96,7 @@ impl<T: AsyncReadExt + AsyncWriteExt + Unpin> AdnlClient<T> {
consumer: &mut C,
) -> Result<(), AdnlError> {
self.receiver
.receive::<_, _, BUFFER>(&mut self.transport, consumer).await
.receive::<_, _, BUFFER>(&mut self.transport, consumer)
.await
}
}

0 comments on commit 694b4e6

Please sign in to comment.