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
}
+119 -41
View File
@@ -119,10 +119,12 @@ fn encode_fragment(frag : TunnelFragment) -> Bytes {
///|
/// Packs one or more `TunnelFragment`s into a cleartext 1024-byte `TunnelData` cell
/// with its 16-byte `iv`, 4-byte SHA-256 checksum, non-zero padding, and `0x00` delimiter.
/// with its 16-byte `iv`, 4-byte SHA-256 checksum, non-zero padding (using caller-provided
/// random `padding` with any `0x00` replaced by `0x01`, or deterministic fallback), and `0x00` delimiter.
pub fn pack_tunnel_cell(
iv : Bytes,
fragments : Array[TunnelFragment],
padding~ : Bytes = b"",
) -> Bytes raise TunnelError {
if iv.length() != 16 {
raise InvalidLength("TunnelData IV must be 16 bytes, got \{iv.length()}")
@@ -147,9 +149,18 @@ pub fn pack_tunnel_cell(
for i = 0; i < 4; i = i + 1 {
cell[16 + i] = checksum[i]
}
// Non-zero deterministic padding bytes
// Strictly non-zero padding bytes
for i = 0; i < pad_len; i = i + 1 {
cell[20 + i] = (i % 254 + 1).to_byte()
let b = if i < padding.length() {
if padding[i] == b'\x00' {
b'\x01'
} else {
padding[i]
}
} else {
(i % 254 + 1).to_byte()
}
cell[20 + i] = b
}
// Zero delimiter at 20 + pad_len
cell[20 + pad_len] = b'\x00'
@@ -238,6 +249,7 @@ pub fn fragment_message_to_cells(
msg_id : UInt32,
payload : Bytes,
base_iv : Bytes,
padding~ : Bytes = b"",
) -> Array[Bytes] raise TunnelError {
if base_iv.length() != 16 {
raise InvalidLength("base_iv must be 16 bytes")
@@ -249,18 +261,22 @@ pub fn fragment_message_to_cells(
}
let single_max = 1003 - (3 + target_overhead)
if payload.length() <= single_max {
let cell = pack_tunnel_cell(base_iv, [
First(target~, fragmented=false, msg_id=0U, data=payload),
])
let cell = pack_tunnel_cell(
base_iv,
[First(target~, fragmented=false, msg_id=0U, data=payload)],
padding~,
)
return [cell]
}
let cells : Array[Bytes] = []
let first_max = 1003 - (7 + target_overhead)
let first_chunk = t_slice(payload, 0, first_max)
cells.push(
pack_tunnel_cell(base_iv, [
First(target~, fragmented=true, msg_id~, data=first_chunk),
]),
pack_tunnel_cell(
base_iv,
[First(target~, fragmented=true, msg_id~, data=first_chunk)],
padding~,
),
)
let mut off = first_max
let mut frag_num = 1
@@ -276,9 +292,11 @@ pub fn fragment_message_to_cells(
cell_iv[i] = (base_iv[i].to_int() ^ frag_num).to_byte()
}
cells.push(
pack_tunnel_cell(Bytes::from_array(cell_iv), [
FollowOn(frag_num~, is_last~, msg_id~, data=chunk),
]),
pack_tunnel_cell(
Bytes::from_array(cell_iv),
[FollowOn(frag_num~, is_last~, msg_id~, data=chunk)],
padding~,
),
)
off += take
frag_num += 1
@@ -289,13 +307,13 @@ pub fn fragment_message_to_cells(
///|
priv struct PendingReassembly {
msg_id : UInt32
target : DeliveryTarget
mut target : DeliveryTarget?
chunks : Array[(Int32, Bytes)]
mut last_num : Int32
}
///|
/// Stateful reassembler for fragmented `TunnelData` messages.
/// Stateful reassembler for fragmented `TunnelData` messages (supports out-of-order fragments).
pub struct FragmentReassembler {
priv pending : Array[PendingReassembly]
}
@@ -305,6 +323,65 @@ pub fn FragmentReassembler::new() -> FragmentReassembler {
{ pending: [], }
}
///|
fn FragmentReassembler::find_or_insert(
self : FragmentReassembler,
msg_id : UInt32,
) -> PendingReassembly {
for p in self.pending {
if p.msg_id == msg_id {
return p
}
}
if self.pending.length() >= 64 {
let _ = self.pending.remove(0)
}
let created : PendingReassembly = {
msg_id,
target: None,
chunks: [],
last_num: -1,
}
self.pending.push(created)
created
}
///|
fn FragmentReassembler::try_finish(
self : FragmentReassembler,
msg_id : UInt32,
) -> (DeliveryTarget, Bytes)? {
for idx = 0; idx < self.pending.length(); idx = idx + 1 {
let p = self.pending[idx]
if p.msg_id == msg_id {
match p.target {
None => return None
Some(target) =>
if p.last_num > 0 && p.chunks.length() == p.last_num + 1 {
let w = @encoding.Writer::new()
for n = 0; n <= p.last_num; n = n + 1 {
let mut found = false
for ch in p.chunks {
if ch.0 == n {
w.write_bytes(ch.1)
found = true
break
}
}
if !found {
return None
}
}
let _ = self.pending.remove(idx)
return Some((target, w.to_bytes()))
}
}
return None
}
}
None
}
///|
/// Feeds a decoded `TunnelFragment` into the reassembler.
/// Returns `Some((target, full_payload))` once all fragments of a message have arrived.
@@ -317,35 +394,36 @@ pub fn FragmentReassembler::push(
if !fragmented {
return Some((target, data))
}
self.pending.push({ msg_id, target, chunks: [(0, data)], last_num: -1, })
None
}
FollowOn(frag_num~, is_last~, msg_id~, data~) => {
for idx = 0; idx < self.pending.length(); idx = idx + 1 {
let p = self.pending[idx]
if p.msg_id == msg_id {
p.chunks.push((frag_num, data))
if is_last {
p.last_num = frag_num
}
if p.last_num > 0 && p.chunks.length() == p.last_num + 1 {
let w = @encoding.Writer::new()
for n = 0; n <= p.last_num; n = n + 1 {
for ch in p.chunks {
if ch.0 == n {
w.write_bytes(ch.1)
break
}
}
}
let target = p.target
let _ = self.pending.remove(idx)
return Some((target, w.to_bytes()))
}
return None
let p = self.find_or_insert(msg_id)
p.target = Some(target)
let mut dup = false
for ch in p.chunks {
if ch.0 == 0 {
dup = true
break
}
}
None
if !dup {
p.chunks.push((0, data))
}
self.try_finish(msg_id)
}
FollowOn(frag_num~, is_last~, msg_id~, data~) => {
let p = self.find_or_insert(msg_id)
let mut dup = false
for ch in p.chunks {
if ch.0 == frag_num {
dup = true
break
}
}
if !dup {
p.chunks.push((frag_num, data))
}
if is_last {
p.last_num = frag_num
}
self.try_finish(msg_id)
}
}
}
+27 -6
View File
@@ -10,17 +10,25 @@ import {
}
// Values
pub fn build_short_tunnel_request(Int32, Array[ShortHopBuildSpec], Array[Bytes]) -> (Array[Bytes], Array[(Int32, HopKeys)]) raise TunnelError
pub fn decrypt_short_build_record(Bytes, @common.Hash, @noise.KeyPair) -> (ShortBuildRequestRecord, HopKeys) raise TunnelError
pub fn decrypt_short_build_reply(HopKeys, Bytes) -> Byte raise TunnelError
pub fn decrypt_short_build_reply(HopKeys, Int32, Bytes) -> Byte raise TunnelError
pub fn encrypt_short_build_record(ShortBuildRequestRecord, @common.Hash, Bytes, @noise.KeyPair) -> (Bytes, HopKeys) raise TunnelError
pub fn decrypt_short_tunnel_replies(Array[Bytes], Array[(Int32, HopKeys)]) -> Array[Byte] raise TunnelError
pub fn encrypt_short_build_reply(HopKeys, Byte) -> Bytes raise TunnelError
pub fn encrypt_short_build_record(ShortBuildRequestRecord, @common.Hash, Bytes, @noise.KeyPair, padding? : Bytes) -> (Bytes, HopKeys) raise TunnelError
pub fn fragment_message_to_cells(DeliveryTarget, UInt32, Bytes, Bytes) -> Array[Bytes] raise TunnelError
pub fn encrypt_short_build_reply(HopKeys, Int32, Byte, padding? : Bytes) -> Bytes raise TunnelError
pub fn pack_tunnel_cell(Bytes, Array[TunnelFragment]) -> Bytes raise TunnelError
pub fn fragment_message_to_cells(DeliveryTarget, UInt32, Bytes, Bytes, padding? : Bytes) -> Array[Bytes] raise TunnelError
pub fn make_slot_nonce(Int32) -> Bytes
pub fn pack_tunnel_cell(Bytes, Array[TunnelFragment], padding? : Bytes) -> Bytes raise TunnelError
pub fn process_short_tunnel_build_hop(Array[Bytes], @common.Hash, @noise.KeyPair, Byte, reply_padding? : Bytes) -> (ShortBuildRequestRecord, HopKeys, Int32, Array[Bytes]) raise TunnelError
pub fn tunnel_layer_decrypt(Bytes, Bytes, Bytes) -> Bytes raise TunnelError
@@ -34,6 +42,7 @@ pub suberror TunnelError {
Crypto(@crypto.CryptoError)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
Noise(@noise.NoiseError)
InvalidLength(String)
InvalidFormat(String)
ChecksumMismatch
@@ -60,6 +69,8 @@ pub(all) struct HopKeys {
layer_key : Bytes
iv_key : Bytes
handshake_hash : Bytes
garlic_key : Bytes?
garlic_tag : Bytes?
}
#derive(Eq, @debug.Debug)
@@ -75,7 +86,17 @@ pub(all) struct ShortBuildRequestRecord {
options : @common.Mapping
}
pub fn ShortBuildRequestRecord::decode_154(Bytes) -> Self raise TunnelError
pub fn ShortBuildRequestRecord::encode_154(Self) -> Bytes raise TunnelError
pub fn ShortBuildRequestRecord::encode_154(Self, padding? : Bytes) -> Bytes raise TunnelError
#derive(Eq, @debug.Debug)
pub(all) struct ShortHopBuildSpec {
slot_idx : Int32
hop_ident : @common.Hash
hop_static_pub : Bytes
ephemeral : @noise.KeyPair
record : ShortBuildRequestRecord
padding : Bytes
}
#derive(Eq, @debug.Debug)
pub(all) struct TransitHop {
+96 -3
View File
@@ -42,10 +42,103 @@ test "Proposal 157 ShortTunnelBuild 218-byte record & reply round-trip" {
assert_eq(dec_rec, req)
assert_eq(hop_keys, creator_keys)
// Hop encrypts 218-byte accept reply (code 0); creator decrypts it
let reply = @tunnel.encrypt_short_build_reply(hop_keys, b'\x00')
// Hop encrypts 218-byte accept reply (code 0) at slot 0; creator decrypts it
let reply = @tunnel.encrypt_short_build_reply(hop_keys, 0, b'\x00')
assert_eq(reply.length(), 218)
assert_eq(@tunnel.decrypt_short_build_reply(creator_keys, reply), b'\x00')
assert_eq(@tunnel.decrypt_short_build_reply(creator_keys, 0, reply), b'\x00')
}
///|
test "Proposal 157 multi-hop ShortTunnelBuild onion build, hop relay, OBEP garlic keys, and reply decrypt" {
let hops : Array[@tunnel.ShortHopBuildSpec] = []
let hop_statics : Array[@noise.KeyPair] = []
let hop_idents : Array[@common.Hash] = []
for i = 0; i < 3; i = i + 1 {
let sp = Bytes::make(32, (0x10 + i).to_byte())
let skp = @noise.KeyPair::from_private(sp)
let ep = Bytes::make(32, (0x20 + i).to_byte())
let ekp = @noise.KeyPair::from_private(ep)
let ident = @common.Hash::sha256(Bytes::make(4, (0x30 + i).to_byte()))
let next_ident = @common.Hash::sha256(Bytes::make(4, (0x31 + i).to_byte()))
let flag = if i == 0 {
b'\x80' // IBGW
} else if i == 2 {
b'\x40' // OBEP
} else {
b'\x00'
}
let rec : @tunnel.ShortBuildRequestRecord = {
receive_tunnel_id: (100 + i).reinterpret_as_uint(),
next_tunnel_id: (200 + i).reinterpret_as_uint(),
next_ident,
flag,
layer_enc_type: b'\x00',
request_time_min: 28333333U,
request_expiration_sec: 600U,
send_message_id: (500 + i).reinterpret_as_uint(),
options: @common.Mapping::new(),
}
hop_statics.push(skp)
hop_idents.push(ident)
hops.push({
slot_idx: (i + 1) % 4, // scrambled slot positions (1, 2, 3) with slot 0 dummy
hop_ident: ident,
hop_static_pub: skp.public_key,
ephemeral: ekp,
record: rec,
padding: Bytes::make(16, (0x40 + i).to_byte()),
})
}
let (req_records, creator_hop_keys) = @tunnel.build_short_tunnel_request(
4,
hops,
[Bytes::make(218, b'\xde')],
)
assert_eq(req_records.length(), 4)
assert_true(creator_hop_keys[0].1.garlic_key is None)
assert_true(creator_hop_keys[2].1.garlic_key is Some(_))
assert_true(creator_hop_keys[2].1.garlic_tag is Some(_))
let mut wire_records = req_records
for i = 0; i < 3; i = i + 1 {
let (rec, keys, slot, next_records) = @tunnel.process_short_tunnel_build_hop(
wire_records,
hop_idents[i],
hop_statics[i],
b'\x00',
reply_padding=Bytes::make(16, b'\x77'),
)
assert_eq(slot, hops[i].slot_idx)
assert_eq(rec, hops[i].record)
assert_eq(keys, creator_hop_keys[i].1)
wire_records = next_records
}
let codes = @tunnel.decrypt_short_tunnel_replies(
wire_records, creator_hop_keys,
)
assert_eq(codes, [b'\x00', b'\x00', b'\x00'])
}
///|
test "TunnelData FragmentReassembler handles out-of-order FollowOn before First" {
let iv = Bytes::make(16, b'\x33')
let payload = Bytes::make(2200, b'\xab')
let cells = @tunnel.fragment_message_to_cells(
Local,
777U,
payload,
iv,
padding=Bytes::make(64, b'\x00'), // zeros sanitized to 0x01
)
assert_eq(cells.length(), 3)
let r = @tunnel.FragmentReassembler::new()
// Deliver cell 2, then cell 1, then cell 0
assert_eq(r.push(@tunnel.unpack_tunnel_cell(cells[2])[0]), None)
assert_eq(r.push(@tunnel.unpack_tunnel_cell(cells[1])[0]), None)
assert_eq(
r.push(@tunnel.unpack_tunnel_cell(cells[0])[0]),
Some((Local, payload)),
)
}
///|