Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow empty IP when decoding Ping's from field #9953

Merged
merged 10 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/net/discv4/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ secp256k1 = { workspace = true, features = [
enr.workspace = true

# async/futures
tokio = { workspace = true, features = ["io-util", "net", "time"] }
tokio = { workspace = true, features = ["io-util", "net", "time", "rt-multi-thread"] }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably not, left over from something being messed up with my setup, for some reason I can't test discv4 without it

tokio-stream.workspace = true

# misc
Expand Down
99 changes: 91 additions & 8 deletions crates/net/discv4/src/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ use alloy_primitives::{
bytes::{Buf, BufMut, Bytes, BytesMut},
keccak256, B256,
};
use alloy_rlp::{Decodable, Encodable, Error as RlpError, Header, RlpDecodable, RlpEncodable};
use alloy_rlp::{
Decodable, Encodable, Error as RlpError, Header, RlpDecodable, RlpEncodable,
RlpEncodableWrapper,
};
use enr::Enr;
use reth_ethereum_forks::{EnrForkIdEntry, ForkId};
use reth_network_peers::{pk2id, NodeRecord, PeerId};
use secp256k1::{
ecdsa::{RecoverableSignature, RecoveryId},
SecretKey, SECP256K1,
};
use std::net::IpAddr;
use std::net::{IpAddr, Ipv4Addr};

// Note: this is adapted from https://github.com/vorot93/discv4

Expand Down Expand Up @@ -191,6 +194,72 @@ pub struct Packet {
pub hash: B256,
}

/// Represents the `from` field in the `Ping` packet
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, RlpEncodableWrapper)]
pub struct PingNodeEndpoint(pub NodeEndpoint);
Rjected marked this conversation as resolved.
Show resolved Hide resolved

impl alloy_rlp::Decodable for PingNodeEndpoint {
#[inline]
fn decode(b: &mut &[u8]) -> alloy_rlp::Result<Self> {
let alloy_rlp::Header { list, payload_length } = alloy_rlp::Header::decode(b)?;
if !list {
return Err(alloy_rlp::Error::UnexpectedString);
}
let started_len = b.len();
if started_len < payload_length {
return Err(alloy_rlp::Error::InputTooShort);
}

// Geth allows the ipaddr to be possibly empty:
// <https://github.com/ethereum/go-ethereum/blob/380688c636a654becc8f114438c2a5d93d2db032/p2p/discover/v4_udp.go#L206-L209>
// <https://github.com/ethereum/go-ethereum/blob/380688c636a654becc8f114438c2a5d93d2db032/p2p/enode/node.go#L189-L189>
//
// Therefore, if we see an empty list instead of a properly formed `IpAddr`, we will
// instead use `IpV4Addr::UNSPECIFIED`
let address =
if *b.first().ok_or(alloy_rlp::Error::InputTooShort)? == alloy_rlp::EMPTY_STRING_CODE {
let addr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
b.advance(1);
addr
} else {
alloy_rlp::Decodable::decode(b)?
};

let this = NodeEndpoint {
address,
udp_port: alloy_rlp::Decodable::decode(b)?,
tcp_port: alloy_rlp::Decodable::decode(b)?,
};
let consumed = started_len - b.len();
if consumed != payload_length {
return Err(alloy_rlp::Error::ListLengthMismatch {
expected: payload_length,
got: consumed,
});
}
Ok(Self(this))
}
}

impl From<NodeRecord> for PingNodeEndpoint {
fn from(NodeRecord { address, tcp_port, udp_port, .. }: NodeRecord) -> Self {
Self(NodeEndpoint { address, tcp_port, udp_port })
}
}

impl From<NodeEndpoint> for PingNodeEndpoint {
fn from(value: NodeEndpoint) -> Self {
Self(value)
}
}

impl PingNodeEndpoint {
/// Creates a new [`PingNodeEndpoint`] from a given UDP address and TCP port.
pub const fn from_udp_address(udp_address: &std::net::SocketAddr, tcp_port: u16) -> Self {
Self(NodeEndpoint { address: udp_address.ip(), udp_port: udp_address.port(), tcp_port })
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need these?

we only need the .0?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need these


/// Represents the `from`, `to` fields in the packets
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, RlpEncodable, RlpDecodable)]
pub struct NodeEndpoint {
Expand Down Expand Up @@ -433,12 +502,11 @@ impl Decodable for Ping {
// <https://github.com/ethereum/devp2p/blob/master/discv4.md#ping-packet-0x01>
let _version = u32::decode(b)?;

let mut this = Self {
from: Decodable::decode(b)?,
to: Decodable::decode(b)?,
expire: Decodable::decode(b)?,
enr_sq: None,
};
// see `Decodable` implementation in `PingNodeEndpoint` for why this is needed
let from = PingNodeEndpoint::decode(b)?.0;

let mut this =
Self { from, to: Decodable::decode(b)?, expire: Decodable::decode(b)?, enr_sq: None };

// only decode the ENR sequence if there's more data in the datagram to decode else skip
if b.has_remaining() {
Expand Down Expand Up @@ -837,6 +905,21 @@ mod tests {
assert!(enr.verify());
}

// test for failing message decode
#[test]
fn decode_failing_packet() {
let packet = hex!("2467ab56952aedf4cfb8bb7830ddc8922d0f992185229919dad9de3841fe95d9b3a7b52459398235f6d3805644666d908b45edb3670414ed97f357afba51f71f7d35c1f45878ba732c3868b04ca42ff0ed347c99efcf3a5768afed68eb21ef960001db04c3808080c9840a480e8f82765f808466a9a06386019106833efe");

let _message = Message::decode(&packet[..]).unwrap();
}

// test for failing message decode
#[test]
fn decode_node() {
let packet = hex!("cb840000000082115c82115d");
let _message = NodeEndpoint::decode(&mut &packet[..]).unwrap();
}

// test vector from the enr library rlp encoding tests
// <https://github.com/sigp/enr/blob/e59dcb45ea07e423a7091d2a6ede4ad6d8ef2840/src/lib.rs#LL1206C35-L1206C35>
#[test]
Expand Down
Loading