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

perf(iroh-net): simplify stun::is check #1580

Merged
merged 3 commits into from
Oct 5, 2023
Merged
Changes from all 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
13 changes: 10 additions & 3 deletions iroh-net/src/stun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,15 @@ pub fn response(tx: TransactionId, addr: SocketAddr) -> Vec<u8> {
buffer
}

// Copied from stun_rs
// const MAGIC_COOKIE: Cookie = Cookie(0x2112_A442);
const COOKIE: [u8; 4] = 0x2112_A442u32.to_be_bytes();
Comment on lines +69 to +70
Copy link
Contributor

Choose a reason for hiding this comment

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

why the need to copy the constant?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

because I can't get it out of the library as constant time


/// Reports whether b is a STUN message.
pub fn is(b: &[u8]) -> bool {
let cookie: [u8; 4] = b[4..8].try_into().unwrap();

b.len() >= stun_rs::MESSAGE_HEADER_SIZE &&
b[0]&0b11000000 == 0 && // top two bits must be zero
cookie == stun_rs::MAGIC_COOKIE
b[4..8] == COOKIE
}

/// Parses a STUN binding request.
Expand Down Expand Up @@ -508,6 +510,11 @@ mod tests {
assert_eq!(got_tx, tx);
}

#[test]
fn test_stun_cookie() {
assert_eq!(stun_rs::MAGIC_COOKIE, COOKIE);
}
Comment on lines +514 to +516
Copy link
Contributor

Choose a reason for hiding this comment

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

we can do this in compile time

Copy link
Contributor Author

Choose a reason for hiding this comment

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

the equality check/conversion is not constant time, so not sure how to do that


#[test]
fn test_response() {
let txn = |n| TransactionId::from([n; 12]);
Expand Down