feat: add ratchet, streaming, SU3 reseed, and router floodfill
check / check (windows-latest) (push) Failing after 27s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (macos-latest) (push) Failing after 27s

- Add ratchet/ with ECIES-X25519-AEAD-Ratchet (Proposal 144), Garlic cloves, and ECIES DatabaseLookup replies
- Add streaming/ with Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, retransmit, window) and Repliable/Raw Datagrams
- Add common/su3.mbt to parse and verify reseed .su3 bundles
- Add Elligator2 encoding in crypto/ and OfflineSignature support in LeaseSet2 (flags bit 0)
- Router: NTCP2 peer pool, floodfill NetDB crawl, transit tunnel relay, and Garlic/Streaming bridge
- cmd/router: add --peer-dir, --su3, --reseed, --floodfill, --no-clock-skew
- cmd/client: add --dest for persistent destination keys
- Mark Phase 6 complete in README and document the transport scope (NTCP2 only, no SSU2)
This commit is contained in:
nandi committed 2026-11-27 22:23:46 -08:00
1 parent 8eafa11b22
commit ae72b00323
54 files changed
+9607 -704

No files matched your search

+242 -46
View File
@@ -5,6 +5,7 @@ pub suberror TunnelError {
Crypto(@crypto.CryptoError)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
Noise(@noise.NoiseError)
InvalidLength(String)
InvalidFormat(String)
ChecksumMismatch
@@ -36,14 +37,27 @@ fn t_concat(a : Bytes, b : Bytes) -> Bytes {
Bytes::from_array(out)
}
///|
/// Creates a 12-byte ChaCha20/AEAD nonce with 4 zero bytes followed by 64-bit LE `slot_idx`.
pub fn make_slot_nonce(slot_idx : Int32) -> Bytes {
let buf = FixedArray::make(12, b'\x00')
let v = slot_idx.to_uint64()
for i = 0; i < 8; i = i + 1 {
buf[4 + i] = ((v >> (i * 8)) & 0xFFUL).to_byte()
}
Bytes::from_array(buf)
}
///|
/// Hop-derived symmetric keys from a Proposal 157 ShortTunnelBuild record.
#derive(Eq, Debug)
pub(all) struct HopKeys {
reply_key : Bytes // 32-byte ChaCha20-Poly1305 key for ShortBuildReplyRecord
reply_key : Bytes // 32-byte ChaCha20-Poly1305 key for ShortBuildReplyRecord & sibling slots
layer_key : Bytes // 32-byte AES-256 tunnel layer key
iv_key : Bytes // 32-byte AES-256 tunnel IV key
handshake_hash : Bytes // 32-byte AD `h` for reply AEAD
garlic_key : Bytes? // 32-byte OBEP reply Garlic key (when OBEP flag 0x40 set)
garlic_tag : Bytes? // 8-byte OBEP reply Garlic tag (when OBEP flag 0x40 set)
}
///|
@@ -64,6 +78,7 @@ pub(all) struct ShortBuildRequestRecord {
///|
pub fn ShortBuildRequestRecord::encode_154(
self : ShortBuildRequestRecord,
padding~ : Bytes = b"",
) -> Bytes raise TunnelError {
let w = @encoding.Writer::new(capacity=154)
w.write_u32_be(self.receive_tunnel_id)
@@ -88,6 +103,11 @@ pub fn ShortBuildRequestRecord::encode_154(
for i = 0; i < prefix.length(); i = i + 1 {
out[i] = prefix[i]
}
let rem = 154 - prefix.length()
let pad_copy = if padding.length() < rem { padding.length() } else { rem }
for i = 0; i < pad_copy; i = i + 1 {
out[prefix.length() + i] = padding[i]
}
Bytes::from_array(out)
}
@@ -125,41 +145,54 @@ pub fn ShortBuildRequestRecord::decode_154(
}
///|
fn derive_hop_keys(ck : Bytes, h : Bytes) -> HopKeys raise TunnelError {
// Derive 96 bytes = reply_key (32) || layer_key (32) || iv_key (32) via HKDF-SHA256
let okm = @crypto.hkdf(ck, b"", b"SMTunnelReplyKey", 96) catch {
/// Canonical Proposal 157 chained HKDF key derivation:
/// `SMTunnelReplyKey` -> `SMTunnelLayerKey` -> `TunnelLayerIVKey` (-> `RGarlicKeyAndTag` for OBEP).
fn derive_hop_keys(
ck : Bytes,
h : Bytes,
is_obep : Bool,
) -> HopKeys raise TunnelError {
let kd1 = @crypto.hkdf(ck, b"", b"SMTunnelReplyKey", 64) catch {
e => raise Crypto(e)
}
{
reply_key: t_slice(okm, 0, 32),
layer_key: t_slice(okm, 32, 32),
iv_key: t_slice(okm, 64, 32),
handshake_hash: h,
let ck1 = t_slice(kd1, 0, 32)
let reply_key = t_slice(kd1, 32, 32)
let kd2 = @crypto.hkdf(ck1, b"", b"SMTunnelLayerKey", 64) catch {
e => raise Crypto(e)
}
let ck2 = t_slice(kd2, 0, 32)
let layer_key = t_slice(kd2, 32, 32)
let kd3 = @crypto.hkdf(ck2, b"", b"TunnelLayerIVKey", 64) catch {
e => raise Crypto(e)
}
let ck3 = t_slice(kd3, 0, 32)
let iv_key = t_slice(kd3, 32, 32)
let (garlic_key, garlic_tag) = if is_obep {
let kd4 = @crypto.hkdf(ck3, b"", b"RGarlicKeyAndTag", 64) catch {
e => raise Crypto(e)
}
(Some(t_slice(kd4, 0, 32)), Some(t_slice(kd4, 32, 8)))
} else {
(None, None)
}
{ reply_key, layer_key, iv_key, handshake_hash: h, garlic_key, garlic_tag, }
}
///|
fn stbm_init_state(
fn stbm_init_sym(
hop_static_pub : Bytes,
ephem_pub : Bytes,
dh : Bytes,
) -> (Bytes, Bytes, Bytes) {
) -> @noise.SymmetricState {
let sym = @noise.SymmetricState::initialize(stbm_protocol_name)
sym.mix_hash(b"") // prologue
sym.mix_hash(b"") // null prologue
sym.mix_hash(hop_static_pub) // <- s
sym.mix_hash(ephem_pub) // -> e
sym.mix_key(dh) // es
let ck = sym.chaining_key()
let h = sym.handshake_hash()
// Extract the AEAD encryption key from ck/dh via standard Noise HKDF
let temp_k = @crypto.hmac_sha256(
@crypto.hmac_sha256(
@noise.SymmetricState::initialize(stbm_protocol_name).chaining_key(),
dh,
),
t_concat(ck, b"\x02"),
)
(ck, h, temp_k)
sym
}
///|
@@ -171,25 +204,19 @@ pub fn encrypt_short_build_record(
hop_ident_hash : @common.Hash,
hop_static_pub : Bytes,
ephemeral : @noise.KeyPair,
padding~ : Bytes = b"",
) -> (Bytes, HopKeys) raise TunnelError {
if hop_static_pub.length() != 32 {
raise InvalidLength("hop_static_pub must be 32 bytes")
}
let pt = record.encode_154()
let pt = record.encode_154(padding~)
let dh = @crypto.x25519(ephemeral.private_key, hop_static_pub) catch {
e => raise Crypto(e)
}
let (ck, h, enc_key) = stbm_init_state(
hop_static_pub,
ephemeral.public_key,
dh,
)
let nonce = Bytes::make(12, b'\x00')
let ct = @crypto.aead_chacha20_poly1305_encrypt(enc_key, nonce, h, pt) catch {
e => raise Crypto(e)
}
let h_after = @crypto.sha256(t_concat(h, ct))
let keys = derive_hop_keys(ck, h_after)
let sym = stbm_init_sym(hop_static_pub, ephemeral.public_key, dh)
let ct = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) }
let is_obep = (record.flag.to_int() & 0x40) != 0
let keys = derive_hop_keys(sym.chaining_key(), sym.handshake_hash(), is_obep)
// 218 bytes = to_peer[0..16] || ephem_pub (32B) || ciphertext (170B)
let to_peer = t_slice(hop_ident_hash.as_bytes(), 0, 16)
let out = t_concat(t_concat(to_peer, ephemeral.public_key), ct)
@@ -219,27 +246,30 @@ pub fn decrypt_short_build_record(
let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch {
e => raise Crypto(e)
}
let (ck, h, enc_key) = stbm_init_state(local_static.public_key, ephem_pub, dh)
let nonce = Bytes::make(12, b'\x00')
let pt = @crypto.aead_chacha20_poly1305_decrypt(enc_key, nonce, h, ct) catch {
e => raise Crypto(e)
}
let h_after = @crypto.sha256(t_concat(h, ct))
let keys = derive_hop_keys(ck, h_after)
let sym = stbm_init_sym(local_static.public_key, ephem_pub, dh)
let pt = sym.decrypt_and_hash(ct) catch { e => raise Noise(e) }
let rec = ShortBuildRequestRecord::decode_154(pt)
let is_obep = (rec.flag.to_int() & 0x40) != 0
let keys = derive_hop_keys(sym.chaining_key(), sym.handshake_hash(), is_obep)
(rec, keys)
}
///|
/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` (`reply_code`: `0` = accept, `30` = reject).
/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` at `slot_idx` (`reply_code`: `0` = accept, `30` = reject).
pub fn encrypt_short_build_reply(
keys : HopKeys,
slot_idx : Int32,
reply_code : Byte,
padding~ : Bytes = b"",
) -> Bytes raise TunnelError {
let pt = FixedArray::make(202, b'\x00')
// 2-byte empty options mapping (0x00, 0x00) + padding + final reply byte at index 201
let copy_len = if padding.length() < 199 { padding.length() } else { 199 }
for i = 0; i < copy_len; i = i + 1 {
pt[2 + i] = padding[i]
}
pt[201] = reply_code
let nonce = Bytes::make(12, b'\x00')
let nonce = make_slot_nonce(slot_idx)
@crypto.aead_chacha20_poly1305_encrypt(
keys.reply_key,
nonce,
@@ -251,9 +281,10 @@ pub fn encrypt_short_build_reply(
}
///|
/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` and returns its `reply_code` byte (`0` = accept).
/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` at `slot_idx` and returns its `reply_code` byte (`0` = accept).
pub fn decrypt_short_build_reply(
keys : HopKeys,
slot_idx : Int32,
reply_218 : Bytes,
) -> Byte raise TunnelError {
if reply_218.length() != 218 {
@@ -261,7 +292,7 @@ pub fn decrypt_short_build_reply(
"ShortBuildReplyRecord must be 218 bytes, got \{reply_218.length()}",
)
}
let nonce = Bytes::make(12, b'\x00')
let nonce = make_slot_nonce(slot_idx)
let pt = @crypto.aead_chacha20_poly1305_decrypt(
keys.reply_key,
nonce,
@@ -272,3 +303,168 @@ pub fn decrypt_short_build_reply(
}
pt[201]
}
///|
/// Build specification for a single hop inside a multi-hop Proposal 157 `ShortTunnelBuild`.
#derive(Eq, Debug)
pub(all) struct ShortHopBuildSpec {
slot_idx : Int32
hop_ident : @common.Hash
hop_static_pub : Bytes
ephemeral : @noise.KeyPair
record : ShortBuildRequestRecord
padding : Bytes
}
///|
/// Constructs a multi-hop Proposal 157 `ShortTunnelBuild` record array of length `total_slots`,
/// applying ChaCha20 onion pre-encryption for downstream hops so each hop unwraps
/// its record in cleartext as the build message traverses the tunnel.
pub fn build_short_tunnel_request(
total_slots : Int32,
hops : Array[ShortHopBuildSpec],
dummy_records : Array[Bytes],
) -> (Array[Bytes], Array[(Int32, HopKeys)]) raise TunnelError {
if total_slots < hops.length() || total_slots <= 0 {
raise InvalidLength("total_slots must be >= hops.length()")
}
let records : Array[Bytes] = Array(capacity=total_slots)
for i = 0; i < total_slots; i = i + 1 {
if i < dummy_records.length() && dummy_records[i].length() == 218 {
records.push(dummy_records[i])
} else {
records.push(Bytes::make(218, b'\x00'))
}
}
let hop_keys : Array[(Int32, HopKeys)] = Array(capacity=hops.length())
let used_slots : Array[Int32] = []
for spec in hops {
if spec.slot_idx < 0 || spec.slot_idx >= total_slots {
raise InvalidLength("hop slot_idx out of range: \{spec.slot_idx}")
}
for prev in used_slots {
if prev == spec.slot_idx {
raise InvalidFormat("duplicate hop slot_idx: \{spec.slot_idx}")
}
}
used_slots.push(spec.slot_idx)
let (enc, keys) = encrypt_short_build_record(
spec.record,
spec.hop_ident,
spec.hop_static_pub,
spec.ephemeral,
padding=spec.padding,
)
records[spec.slot_idx] = enc
hop_keys.push((spec.slot_idx, keys))
}
// Pre-XOR downstream hop slots with earlier hops' reply keys
for m = 1; m < hops.length(); m = m + 1 {
let slot_m = hops[m].slot_idx
let mut rec = records[slot_m]
for k = 0; k < m; k = k + 1 {
let keys_k = hop_keys[k].1
rec = @crypto.chacha20_xor(
keys_k.reply_key,
0U,
make_slot_nonce(slot_m),
rec,
) catch {
e => raise Crypto(e)
}
}
records[slot_m] = rec
}
(records, hop_keys)
}
///|
/// Participating router handler for a Proposal 157 `ShortTunnelBuild`:
/// finds the slot matching `local_ident[0..16]`, decrypts the record, writes the
/// AEAD-encrypted `ShortBuildReplyRecord` into that slot, and ChaCha20-XORs all other slots.
pub fn process_short_tunnel_build_hop(
records : Array[Bytes],
local_ident : @common.Hash,
local_static : @noise.KeyPair,
reply_code : Byte,
reply_padding~ : Bytes = b"",
) -> (ShortBuildRequestRecord, HopKeys, Int32, Array[Bytes]) raise TunnelError {
let mut matched_slot = -1
let mut matched_rec : ShortBuildRequestRecord? = None
let mut matched_keys : HopKeys? = None
for idx = 0; idx < records.length(); idx = idx + 1 {
let res = Some(
decrypt_short_build_record(records[idx], local_ident, local_static),
) catch {
RecordNotForUs => None
e => raise e
}
match res {
Some((rec, keys)) => {
matched_slot = idx
matched_rec = Some(rec)
matched_keys = Some(keys)
break
}
None => ()
}
}
let rec = match matched_rec {
Some(r) => r
None => raise RecordNotForUs
}
let keys = match matched_keys {
Some(k) => k
None => raise RecordNotForUs
}
let out : Array[Bytes] = Array(capacity=records.length())
for j = 0; j < records.length(); j = j + 1 {
if j == matched_slot {
out.push(
encrypt_short_build_reply(
keys,
matched_slot,
reply_code,
padding=reply_padding,
),
)
} else {
out.push(
@crypto.chacha20_xor(keys.reply_key, 0U, make_slot_nonce(j), records[j]) catch {
e => raise Crypto(e)
},
)
}
}
(rec, keys, matched_slot, out)
}
///|
/// Originator handler for a completed multi-hop Proposal 157 `ShortTunnelBuildReply`:
/// peels outer ChaCha20 layers and AEAD-decrypts each hop's reply status byte (`0` = accept).
pub fn decrypt_short_tunnel_replies(
records : Array[Bytes],
hop_slots_and_keys : Array[(Int32, HopKeys)],
) -> Array[Byte] raise TunnelError {
let reply_codes : Array[Byte] = Array(capacity=hop_slots_and_keys.length())
for m = 0; m < hop_slots_and_keys.length(); m = m + 1 {
let (slot_m, keys_m) = hop_slots_and_keys[m]
if slot_m < 0 || slot_m >= records.length() {
raise InvalidLength("reply slot index out of bounds: \{slot_m}")
}
let mut rec = records[slot_m]
for k = m + 1; k < hop_slots_and_keys.length(); k = k + 1 {
let keys_k = hop_slots_and_keys[k].1
rec = @crypto.chacha20_xor(
keys_k.reply_key,
0U,
make_slot_nonce(slot_m),
rec,
) catch {
e => raise Crypto(e)
}
}
reply_codes.push(decrypt_short_build_reply(keys_m, slot_m, rec))
}
reply_codes
}