swap bytes in network code instead of swapping only in little-endian

This commit is contained in:
Riccardo Casatta 2021-06-29 16:01:34 +02:00
parent 8996249f2d
commit 0f4d2cfcaa
No known key found for this signature in database
GPG Key ID: FD986A969E450397
2 changed files with 10 additions and 7 deletions

View File

@ -69,8 +69,11 @@ impl Address {
}
fn addr_to_be(addr: [u16; 8]) -> [u16; 8] {
[addr[0].to_be(), addr[1].to_be(), addr[2].to_be(), addr[3].to_be(),
addr[4].to_be(), addr[5].to_be(), addr[6].to_be(), addr[7].to_be()]
let mut result = addr.clone();
for i in 0..8 {
result[i] = result[i].swap_bytes();
}
result
}
impl Encodable for Address {
@ -81,7 +84,7 @@ impl Encodable for Address {
) -> Result<usize, io::Error> {
let len = self.services.consensus_encode(&mut s)?
+ addr_to_be(self.address).consensus_encode(&mut s)?
+ self.port.to_be().consensus_encode(s)?;
+ self.port.swap_bytes().consensus_encode(s)?;
Ok(len)
}
}
@ -92,7 +95,7 @@ impl Decodable for Address {
Ok(Address {
services: Decodable::consensus_decode(&mut d)?,
address: addr_to_be(Decodable::consensus_decode(&mut d)?),
port: u16::from_be(Decodable::consensus_decode(d)?)
port: u16::swap_bytes(Decodable::consensus_decode(d)?)
})
}
}
@ -267,7 +270,7 @@ impl Encodable for AddrV2Message {
len += self.time.consensus_encode(&mut e)?;
len += VarInt(self.services.as_u64()).consensus_encode(&mut e)?;
len += self.addr.consensus_encode(&mut e)?;
len += self.port.to_be().consensus_encode(e)?;
len += self.port.swap_bytes().consensus_encode(e)?;
Ok(len)
}
}
@ -278,7 +281,7 @@ impl Decodable for AddrV2Message {
time: Decodable::consensus_decode(&mut d)?,
services: ServiceFlags::from(VarInt::consensus_decode(&mut d)?.0),
addr: Decodable::consensus_decode(&mut d)?,
port: u16::from_be(Decodable::consensus_decode(d)?),
port: u16::swap_bytes(Decodable::consensus_decode(d)?),
})
}
}

View File

@ -176,7 +176,7 @@ macro_rules! construct_uint {
fn cmp(&self, other: &$name) -> ::core::cmp::Ordering {
// We need to manually implement ordering because we use little-endian
// and the auto derive is a lexicographic ordering(i.e. memcmp)
// which with numbers is equivilant to big-endian
// which with numbers is equivalent to big-endian
for i in 0..$n_words {
if self[$n_words - 1 - i] < other[$n_words - 1 - i] { return ::core::cmp::Ordering::Less; }
if self[$n_words - 1 - i] > other[$n_words - 1 - i] { return ::core::cmp::Ordering::Greater; }