///| /// Errors raised by the I2P Tunnel subsystem (ShortTunnelBuild, TunnelData framing, layer crypto). #derive(Eq, Debug) pub suberror TunnelError { Crypto(@crypto.CryptoError) Encoding(@encoding.EncodingError) Common(@common.CommonError) Noise(@noise.NoiseError) InvalidLength(String) InvalidFormat(String) ChecksumMismatch RecordNotForUs } ///| /// Proposal 157 ShortTunnelBuild Noise protocol name for ECIES-X25519 record encryption. let stbm_protocol_name : Bytes = b"Noise_N_25519_ChaChaPoly_SHA256" ///| fn t_slice(data : Bytes, start : Int32, len : Int32) -> Bytes { let out = FixedArray::make(len, b'\x00') for i = 0; i < len; i = i + 1 { out[i] = data[start + i] } Bytes::from_array(out) } ///| fn t_concat(a : Bytes, b : Bytes) -> Bytes { let out = FixedArray::make(a.length() + b.length(), b'\x00') for i = 0; i < a.length(); i = i + 1 { out[i] = a[i] } for i = 0; i < b.length(); i = i + 1 { out[a.length() + i] = b[i] } 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 & 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) } ///| /// Cleartext 154-byte Proposal 157 ShortBuildRequestRecord. #derive(Eq, Debug) pub(all) struct ShortBuildRequestRecord { receive_tunnel_id : UInt32 next_tunnel_id : UInt32 next_ident : @common.Hash flag : Byte // bit 7 = IBGW (0x80), bit 6 = OBEP (0x40) layer_enc_type : Byte // 0 = AES-256-CBC request_time_min : UInt32 // minutes since Unix epoch request_expiration_sec : UInt32 // seconds (typically 600) send_message_id : UInt32 options : @common.Mapping } ///| 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) w.write_u32_be(self.next_tunnel_id) self.next_ident.encode(w) w.write_u8(self.flag) w.write_u16_be(0U) // more_flags w.write_u8(self.layer_enc_type) w.write_u32_be(self.request_time_min) w.write_u32_be(self.request_expiration_sec) w.write_u32_be(self.send_message_id) self.options.encode(w) catch { e => raise Common(e) } let prefix = w.to_bytes() if prefix.length() > 154 { raise InvalidLength( "ShortBuildRequestRecord exceeds 154 bytes: \{prefix.length()}", ) } let out = FixedArray::make(154, b'\x00') 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) } ///| pub fn ShortBuildRequestRecord::decode_154( data : Bytes, ) -> ShortBuildRequestRecord raise TunnelError { if data.length() != 154 { raise InvalidLength( "ShortBuildRequestRecord must be 154 bytes, got \{data.length()}", ) } let r = @encoding.Reader::new(data) let receive_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } let next_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } let next_ident = @common.Hash::decode(r) catch { e => raise Common(e) } let flag = r.read_u8() catch { e => raise Encoding(e) } let _ = r.read_u16_be() catch { e => raise Encoding(e) } let layer_enc_type = r.read_u8() catch { e => raise Encoding(e) } let request_time_min = r.read_u32_be() catch { e => raise Encoding(e) } let request_expiration_sec = r.read_u32_be() catch { e => raise Encoding(e) } let send_message_id = r.read_u32_be() catch { e => raise Encoding(e) } let options = @common.Mapping::decode(r) catch { e => raise Common(e) } { receive_tunnel_id, next_tunnel_id, next_ident, flag, layer_enc_type, request_time_min, request_expiration_sec, send_message_id, options, } } ///| /// 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) } 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) if is_obep { 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 kd4 = @crypto.hkdf(ck3, b"", b"RGarlicKeyAndTag", 64) catch { e => raise Crypto(e) } // Canonical i2pd: garlic_tag = kd4[0..8], garlic_key = kd4[32..64] let garlic_tag = Some(t_slice(kd4, 0, 8)) let garlic_key = Some(t_slice(kd4, 32, 32)) { reply_key, layer_key, iv_key, handshake_hash: h, garlic_key, garlic_tag, } } else { // Non-OBEP hops use ck2 directly as iv_key (no TunnelLayerIVKey HKDF step) { reply_key, layer_key, iv_key: ck2, handshake_hash: h, garlic_key: None, garlic_tag: None, } } } ///| fn stbm_init_sym( hop_static_pub : Bytes, ephem_pub : Bytes, dh : Bytes, ) -> @noise.SymmetricState { let sym = @noise.SymmetricState::initialize(stbm_protocol_name) sym.mix_hash(b"") // null prologue sym.mix_hash(hop_static_pub) // <- s sym.mix_hash(ephem_pub) // -> e sym.mix_key(dh) // es sym } ///| /// Encrypts a 154-byte `ShortBuildRequestRecord` into a 218-byte Proposal 157 build record /// targeting `hop_ident_hash` / `hop_static_pub` using `ephemeral` X25519 keypair. /// Returns `(encrypted_218B, derived_hop_keys)`. pub fn encrypt_short_build_record( record : ShortBuildRequestRecord, 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(padding~) let dh = @crypto.x25519(ephemeral.private_key, hop_static_pub) catch { e => raise Crypto(e) } 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) (out, keys) } ///| /// Attempts to decrypt a 218-byte Proposal 157 build record addressed to `local_ident_hash`. /// Raises `RecordNotForUs` if the 16-byte `to_peer` prefix does not match. pub fn decrypt_short_build_record( record_218 : Bytes, local_ident_hash : @common.Hash, local_static : @noise.KeyPair, ) -> (ShortBuildRequestRecord, HopKeys) raise TunnelError { if record_218.length() != 218 { raise InvalidLength( "ShortTunnelBuild record must be 218 bytes, got \{record_218.length()}", ) } let to_peer = t_slice(record_218, 0, 16) let expected_prefix = t_slice(local_ident_hash.as_bytes(), 0, 16) if !@crypto.ct_eq(to_peer, expected_prefix) { raise RecordNotForUs } let ephem_pub = t_slice(record_218, 16, 32) let ct = t_slice(record_218, 48, 170) let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch { e => raise Crypto(e) } 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` 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 = make_slot_nonce(slot_idx) @crypto.aead_chacha20_poly1305_encrypt( keys.reply_key, nonce, keys.handshake_hash, Bytes::from_array(pt), ) catch { e => raise Crypto(e) } } ///| /// 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 { raise InvalidLength( "ShortBuildReplyRecord must be 218 bytes, got \{reply_218.length()}", ) } let nonce = make_slot_nonce(slot_idx) let pt = @crypto.aead_chacha20_poly1305_decrypt( keys.reply_key, nonce, keys.handshake_hash, reply_218, ) catch { e => raise Crypto(e) } 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, 1U, 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, 1U, 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, 1U, 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 }