Skip to content

Commit 39bbaf8

Browse files
authored
Merge pull request #453 from tox-rs/refactor
refactor(binary_io): implement ToBytes/FromBytes for arrays
2 parents db7de02 + d56ecda commit 39bbaf8

File tree

10 files changed

+35
-30
lines changed

10 files changed

+35
-30
lines changed

.github/workflows/rust.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ jobs:
1414
os: [ubuntu-latest, macos-latest, windows-latest]
1515
rust:
1616
- stable
17-
- 1.48.0
17+
- 1.51.0
1818
steps:
1919
- uses: actions/checkout@v2
2020
- uses: actions-rs/toolchain@v1

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ issue / pull request should be filled on the reference repository.
3030
[CONTRIBUTING.md](/CONTRIBUTING.md).
3131

3232
## Building
33-
Fairly simple. First, install [Rust] >= 1.48.0 and a C compiler ([Build Tools
33+
Fairly simple. First, install [Rust] >= 1.51.0 and a C compiler ([Build Tools
3434
for Visual Studio][VSBuild] on Windows, GCC or Clang on other platforms).
3535

3636
Then you can build the debug version with

tox_binary_io/src/lib.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ pub use nom::IResult;
22
pub use cookie_factory::GenError;
33

44
use nom::number::streaming::{le_u8, le_u16};
5-
use nom::{named, map, count};
6-
use cookie_factory::{do_gen, gen_be_u8, gen_le_u16};
5+
use nom::{named, map, map_opt, take, count};
6+
use cookie_factory::{do_gen, gen_be_u8, gen_le_u16, gen_slice};
77

8-
use std::net::{
8+
use std::{convert::TryInto, net::{
99
IpAddr,
1010
Ipv4Addr,
1111
Ipv6Addr,
12-
};
12+
}};
1313

1414
#[cfg(feature = "sodiumoxide")]
1515
pub use sodium::*;
@@ -43,6 +43,16 @@ impl FromBytes for Ipv4Addr {
4343
));
4444
}
4545

46+
impl<const N: usize> ToBytes for [u8; N] {
47+
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
48+
gen_slice!(buf, &self[..])
49+
}
50+
}
51+
52+
impl <const N: usize> FromBytes for [u8; N] {
53+
named!(from_bytes<[u8; N]>, map_opt!(take!(N), |bytes: &[u8]| bytes.try_into().ok()));
54+
}
55+
4656
impl ToBytes for Ipv4Addr {
4757
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
4858
let o = self.octets();

tox_core/src/onion/client/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use tox_packet::ip_port::*;
2727
use crate::onion::client::errors::*;
2828
use crate::onion::client::onion_path::*;
2929
use crate::onion::client::paths_pool::*;
30-
use crate::onion::onion_announce::{PingId, INITIAL_PING_ID};
30+
use crate::onion::onion_announce::INITIAL_PING_ID;
3131
use tox_packet::onion::*;
3232
use tox_packet::packed_node::*;
3333
use crate::relay::client::Connections as TcpConnections;

tox_core/src/onion/onion_announce.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@ use crate::time::*;
1414
use tox_packet::onion::*;
1515
use crate::dht::kbucket::Distance;
1616

17-
/// The type of onion ping ID which is SHA256 hash.
18-
pub type PingId = [u8; <Sha256 as Digest>::OutputSize::USIZE];
19-
2017
/// Number of secret random bytes to make onion ping id unique for each node.
2118
pub const SECRET_BYTES_SIZE: usize = 32;
2219

tox_packet/src/dht/cookie.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
*/
33

44
use super::*;
5-
use nom::{AsBytes, map_opt, number::complete::be_u64};
5+
use nom::number::complete::be_u64;
66
use sha2::{Digest, Sha512};
77
use sha2::digest::generic_array::typenum::marker_traits::Unsigned;
88
use xsalsa20poly1305::{XSalsa20Poly1305, aead::{Aead, Error as AeadError}};
@@ -114,7 +114,7 @@ pub struct EncryptedCookie {
114114

115115
impl FromBytes for EncryptedCookie {
116116
named!(from_bytes<EncryptedCookie>, do_parse!(
117-
nonce: map_opt!(take!(xsalsa20poly1305::NONCE_SIZE), |bytes: &[u8]| bytes.try_into().ok()) >>
117+
nonce: call!(<[u8; xsalsa20poly1305::NONCE_SIZE]>::from_bytes) >>
118118
payload: take!(88) >>
119119
(EncryptedCookie { nonce, payload: payload.to_vec() })
120120
));
@@ -150,7 +150,7 @@ impl EncryptedCookie {
150150
- fails to parse `Cookie`
151151
*/
152152
pub fn get_payload(&self, symmetric_key: &XSalsa20Poly1305) -> Result<Cookie, GetPayloadError> {
153-
let decrypted = symmetric_key.decrypt(&self.nonce.into(), self.payload.as_bytes())
153+
let decrypted = symmetric_key.decrypt(&self.nonce.into(), self.payload.as_slice())
154154
.map_err(|AeadError| {
155155
GetPayloadError::decrypt()
156156
})?;

tox_packet/src/dht/crypto_handshake.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
use super::*;
55

6-
use std::convert::TryInto;
7-
use nom::map_opt;
86
use sha2::{Digest, Sha512};
97
use sha2::digest::generic_array::typenum::marker_traits::Unsigned;
108
use tox_binary_io::*;
@@ -141,7 +139,7 @@ impl FromBytes for CryptoHandshakePayload {
141139
named!(from_bytes<CryptoHandshakePayload>, do_parse!(
142140
base_nonce: call!(Nonce::from_bytes) >>
143141
session_pk: call!(PublicKey::from_bytes) >>
144-
cookie_hash: map_opt!(take!(<Sha512 as Digest>::OutputSize::USIZE), |bytes: &[u8]| bytes.try_into().ok()) >>
142+
cookie_hash: call!(<[u8; <Sha512 as Digest>::OutputSize::USIZE]>::from_bytes) >>
145143
cookie: call!(EncryptedCookie::from_bytes) >>
146144
eof!() >>
147145
(CryptoHandshakePayload {

tox_packet/src/onion/mod.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,14 @@ pub use self::onion_response_2::*;
2929
pub use self::onion_response_3::*;
3030
pub use self::friend_request::*;
3131

32-
use std::convert::TryInto;
3332
use tox_binary_io::*;
3433
use tox_crypto::*;
3534
use xsalsa20poly1305::{XSalsa20Poly1305, aead::{Aead, Error as AeadError}};
3635
use crate::dht::packed_node::PackedNode;
3736
use crate::ip_port::*;
3837

3938
use rand::{Rng, thread_rng};
40-
use nom::{AsBytes, alt, call, cond, do_parse, eof, flat_map, map, map_opt, map_res, named, switch, tag, take, value, verify};
39+
use nom::{alt, call, cond, do_parse, eof, flat_map, map, map_res, named, switch, tag, take, value, verify};
4140

4241
use cookie_factory::{
4342
do_gen,
@@ -107,7 +106,7 @@ pub struct OnionReturn {
107106

108107
impl FromBytes for OnionReturn {
109108
named!(from_bytes<OnionReturn>, do_parse!(
110-
nonce: map_opt!(take!(xsalsa20poly1305::NONCE_SIZE), |bytes: &[u8]| bytes.try_into().ok()) >>
109+
nonce: call!(<[u8; xsalsa20poly1305::NONCE_SIZE]>::from_bytes) >>
111110
payload: rest >>
112111
(OnionReturn { nonce, payload: payload.to_vec() })
113112
));
@@ -162,7 +161,7 @@ impl OnionReturn {
162161
- fails to parse as `IpPort` with possibly inner `OnionReturn`
163162
*/
164163
pub fn get_payload(&self, symmetric_key: &XSalsa20Poly1305) -> Result<(IpPort, Option<OnionReturn>), Error> {
165-
let decrypted = symmetric_key.decrypt(&self.nonce.into(), self.payload.as_bytes())
164+
let decrypted = symmetric_key.decrypt(&self.nonce.into(), self.payload.as_slice())
166165
.map_err(|AeadError| {
167166
Error::new(ErrorKind::Other, "OnionReturn decrypt error.")
168167
})?;

tox_packet/src/onion/onion_announce_request.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@
33

44
use super::*;
55

6-
use std::convert::TryInto;
76
use tox_binary_io::*;
87
use tox_crypto::*;
98
use crate::dht::*;
109

1110
use nom::{
1211
flat_map,
13-
map_opt,
1412
number::complete::le_u64,
1513
combinator::{rest, rest_len},
1614
bytes::complete::take
1715
};
16+
use sha2::{Digest, Sha256};
17+
use sha2::digest::generic_array::typenum::marker_traits::Unsigned;
18+
19+
/// The type of onion ping ID which is SHA256 hash.
20+
pub type PingId = [u8; <Sha256 as Digest>::OutputSize::USIZE];
1821

1922
/** It's used for announcing ourselves to onion node and for looking for other
2023
announced nodes.
@@ -172,7 +175,7 @@ Length | Content
172175
#[derive(Clone, Debug, Eq, PartialEq)]
173176
pub struct OnionAnnounceRequestPayload {
174177
/// Onion ping id
175-
pub ping_id: [u8; 32],
178+
pub ping_id: PingId,
176179
/// `PublicKey` we are searching for
177180
pub search_pk: PublicKey,
178181
/// `PublicKey` that should be used for sending data packets
@@ -183,7 +186,7 @@ pub struct OnionAnnounceRequestPayload {
183186

184187
impl FromBytes for OnionAnnounceRequestPayload {
185188
named!(from_bytes<OnionAnnounceRequestPayload>, do_parse!(
186-
ping_id: map_opt!(take!(32), |bytes: &[u8]| bytes.try_into().ok()) >>
189+
ping_id: call!(PingId::from_bytes) >>
187190
search_pk: call!(PublicKey::from_bytes) >>
188191
data_pk: call!(PublicKey::from_bytes) >>
189192
sendback_data: le_u64 >>
@@ -239,7 +242,7 @@ mod tests {
239242
tox_crypto::crypto_init().unwrap(),
240243
onion_announce_request_payload_encode_decode,
241244
OnionAnnounceRequestPayload {
242-
ping_id: [42; 32],
245+
ping_id: [42; <Sha256 as Digest>::OutputSize::USIZE],
243246
search_pk: gen_keypair().0,
244247
data_pk: gen_keypair().0,
245248
sendback_data: 12345
@@ -253,7 +256,7 @@ mod tests {
253256
let (bob_pk, _bob_sk) = gen_keypair();
254257
let shared_secret = encrypt_precompute(&bob_pk, &alice_sk);
255258
let payload = OnionAnnounceRequestPayload {
256-
ping_id: [42; 32],
259+
ping_id: [42; <Sha256 as Digest>::OutputSize::USIZE],
257260
search_pk: gen_keypair().0,
258261
data_pk: gen_keypair().0,
259262
sendback_data: 12345
@@ -274,7 +277,7 @@ mod tests {
274277
let (_eve_pk, eve_sk) = gen_keypair();
275278
let shared_secret = encrypt_precompute(&bob_pk, &alice_sk);
276279
let payload = OnionAnnounceRequestPayload {
277-
ping_id: [42; 32],
280+
ping_id: [42; <Sha256 as Digest>::OutputSize::USIZE],
278281
search_pk: gen_keypair().0,
279282
data_pk: gen_keypair().0,
280283
sendback_data: 12345

tox_packet/src/onion/onion_announce_response.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@ use tox_binary_io::*;
77
use tox_crypto::*;
88
use crate::dht::*;
99

10-
use std::convert::TryInto;
1110
use nom::{
1211
many0,
13-
map_opt,
1412
number::complete::le_u64,
1513
combinator::{rest, rest_len},
1614
};
@@ -140,7 +138,7 @@ pub struct OnionAnnounceResponsePayload {
140138
impl FromBytes for OnionAnnounceResponsePayload {
141139
named!(from_bytes<OnionAnnounceResponsePayload>, do_parse!(
142140
announce_status: call!(AnnounceStatus::from_bytes) >>
143-
ping_id_or_pk: map_opt!(take!(32), |bytes: &[u8]| bytes.try_into().ok()) >>
141+
ping_id_or_pk: call!(<[u8; 32]>::from_bytes) >>
144142
nodes: many0!(PackedNode::from_bytes) >>
145143
_len: verify!(value!(nodes.len()), |len| *len <= 4_usize) >>
146144
eof!() >>

0 commit comments

Comments
 (0)