Files
nandi ae72b00323
check / check (windows-latest) (push) Failing after 27s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (macos-latest) (push) Failing after 27s
feat: add ratchet, streaming, SU3 reseed, and router floodfill
- 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)
2026-11-27 22:23:46 -08:00

549 lines
16 KiB
MoonBit

///|
/// Errors raised when encoding, decoding, or validating I2NP messages.
#derive(Eq, Debug)
pub suberror I2npError {
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
ChecksumMismatch(Byte, Byte)
InvalidLength(String)
}
///|
/// I2NP message type IDs (per I2P I2NP specification).
#derive(Eq, Debug)
pub(all) enum I2npMessageType {
DatabaseStore // 1
DatabaseLookup // 2
DatabaseSearchReply // 3
DeliveryStatus // 10
Garlic // 11
TunnelData // 18
TunnelGateway // 19
Data // 20
TunnelBuild // 21
TunnelBuildReply // 22
VariableTunnelBuild // 23
VariableTunnelBuildReply // 24
ShortTunnelBuild // 25
ShortTunnelBuildReply // 26
Unknown(Byte)
}
///|
pub fn I2npMessageType::to_byte(self : I2npMessageType) -> Byte {
match self {
DatabaseStore => b'\x01'
DatabaseLookup => b'\x02'
DatabaseSearchReply => b'\x03'
DeliveryStatus => b'\x0a'
Garlic => b'\x0b'
TunnelData => b'\x12'
TunnelGateway => b'\x13'
Data => b'\x14'
TunnelBuild => b'\x15'
TunnelBuildReply => b'\x16'
VariableTunnelBuild => b'\x17'
VariableTunnelBuildReply => b'\x18'
ShortTunnelBuild => b'\x19'
ShortTunnelBuildReply => b'\x1a'
Unknown(b) => b
}
}
///|
pub fn I2npMessageType::from_byte(b : Byte) -> I2npMessageType {
match b.to_int() {
1 => DatabaseStore
2 => DatabaseLookup
3 => DatabaseSearchReply
10 => DeliveryStatus
11 => Garlic
18 => TunnelData
19 => TunnelGateway
20 => Data
21 => TunnelBuild
22 => TunnelBuildReply
23 => VariableTunnelBuild
24 => VariableTunnelBuildReply
25 => ShortTunnelBuild
26 => ShortTunnelBuildReply
_ => Unknown(b)
}
}
///|
/// Standard 16-byte I2NP header:
/// `type (1B) | msg_id (4B) | expiration_ms (8B) | size (2B) | checksum (1B)`.
/// Checksum is the first byte of `SHA-256(payload)`.
#derive(Eq, Debug)
pub(all) struct StandardHeader {
msg_type : I2npMessageType
msg_id : UInt32
expiration_ms : UInt64
size : UInt32
checksum : Byte
}
///|
pub fn StandardHeader::encode(
self : StandardHeader,
w : @encoding.Writer,
) -> Unit {
w.write_u8(self.msg_type.to_byte())
w.write_u32_be(self.msg_id)
w.write_u64_be(self.expiration_ms)
w.write_u16_be(self.size)
w.write_u8(self.checksum)
}
///|
pub fn StandardHeader::decode(
r : @encoding.Reader,
) -> StandardHeader raise I2npError {
let msg_type = I2npMessageType::from_byte(
r.read_u8() catch {
e => raise Encoding(e)
},
)
let msg_id = r.read_u32_be() catch { e => raise Encoding(e) }
let expiration_ms = r.read_u64_be() catch { e => raise Encoding(e) }
let size = r.read_u16_be() catch { e => raise Encoding(e) }
let checksum = r.read_u8() catch { e => raise Encoding(e) }
{ msg_type, msg_id, expiration_ms, size, checksum, }
}
///|
/// Short 9-byte NTCP2/SSU2 I2NP header:
/// `type (1B) | msg_id (4B) | expiration_sec (4B)`.
#derive(Eq, Debug)
pub(all) struct ShortHeader {
msg_type : I2npMessageType
msg_id : UInt32
expiration_sec : UInt32
}
///|
pub fn ShortHeader::encode(self : ShortHeader, w : @encoding.Writer) -> Unit {
w.write_u8(self.msg_type.to_byte())
w.write_u32_be(self.msg_id)
w.write_u32_be(self.expiration_sec)
}
///|
pub fn ShortHeader::decode(r : @encoding.Reader) -> ShortHeader raise I2npError {
let msg_type = I2npMessageType::from_byte(
r.read_u8() catch {
e => raise Encoding(e)
},
)
let msg_id = r.read_u32_be() catch { e => raise Encoding(e) }
let expiration_sec = r.read_u32_be() catch { e => raise Encoding(e) }
{ msg_type, msg_id, expiration_sec, }
}
///|
/// Computes the 1-byte I2NP payload checksum: first byte of SHA-256(payload).
pub fn payload_checksum(payload : Bytes) -> Byte {
@crypto.sha256(payload)[0]
}
///|
/// Core I2NP message payloads.
#derive(Eq, Debug)
pub(all) enum I2npPayload {
/// Type 1: DatabaseStore (stores a RouterInfo or LeaseSet in NetDB).
DatabaseStore(
key~ : @common.Hash,
store_type~ : Byte,
reply_token~ : UInt32,
reply_tunnel_id~ : UInt32,
reply_gateway~ : @common.Hash?,
data~ : Bytes
)
/// Type 2: DatabaseLookup (queries NetDB for a key).
DatabaseLookup(
key~ : @common.Hash,
from~ : @common.Hash,
flags~ : Byte,
reply_tunnel_id~ : UInt32?,
excluded_peers~ : Array[@common.Hash],
reply_key~ : Bytes?,
reply_tags~ : Array[Bytes]
)
/// Type 3: DatabaseSearchReply (floodfill returns closest router hashes).
DatabaseSearchReply(
key~ : @common.Hash,
peer_hashes~ : Array[@common.Hash],
from~ : @common.Hash
)
/// Type 10: DeliveryStatus (confirms delivery of a message or tunnel test).
DeliveryStatus(msg_id~ : UInt32, timestamp_ms~ : UInt64)
/// Type 11: Garlic (length-prefixed encrypted garlic cloves).
Garlic(data~ : Bytes)
/// Type 18: TunnelData (4-byte tunnel ID + 1024-byte encrypted tunnel data).
TunnelData(tunnel_id~ : UInt32, data~ : Bytes)
/// Type 19: TunnelGateway (4-byte tunnel ID + 2-byte length + I2NP message).
TunnelGateway(tunnel_id~ : UInt32, data~ : Bytes)
/// Type 20: Data (4-byte length + opaque payload).
Data(data~ : Bytes)
/// Type 25: ShortTunnelBuild (1-byte record count + N * 218-byte encrypted build records).
ShortTunnelBuild(records~ : Array[Bytes])
/// Type 26: ShortTunnelBuildReply (1-byte record count + N * 218-byte encrypted reply records).
ShortTunnelBuildReply(records~ : Array[Bytes])
/// Fallback for other/custom I2NP message types.
Raw(msg_type~ : I2npMessageType, data~ : Bytes)
}
///|
pub fn I2npPayload::msg_type(self : I2npPayload) -> I2npMessageType {
match self {
DatabaseStore(..) => DatabaseStore
DatabaseLookup(..) => DatabaseLookup
DatabaseSearchReply(..) => DatabaseSearchReply
DeliveryStatus(..) => DeliveryStatus
Garlic(..) => Garlic
TunnelData(..) => TunnelData
TunnelGateway(..) => TunnelGateway
Data(..) => Data
ShortTunnelBuild(..) => ShortTunnelBuild
ShortTunnelBuildReply(..) => ShortTunnelBuildReply
Raw(msg_type~, ..) => msg_type
}
}
///|
pub fn I2npPayload::encode_body(self : I2npPayload) -> Bytes raise I2npError {
let w = @encoding.Writer::new()
match self {
DatabaseStore(
key~,
store_type~,
reply_token~,
reply_tunnel_id~,
reply_gateway~,
data~
) => {
key.encode(w)
w.write_u8(store_type)
w.write_u32_be(reply_token)
if reply_token != 0U {
w.write_u32_be(reply_tunnel_id)
match reply_gateway {
Some(gw) => gw.encode(w)
None =>
raise InvalidLength(
"DatabaseStore with non-zero reply_token requires reply_gateway",
)
}
}
w.write_bytes(data)
}
DatabaseLookup(
key~,
from~,
flags~,
reply_tunnel_id~,
excluded_peers~,
reply_key~,
reply_tags~
) => {
key.encode(w)
from.encode(w)
w.write_u8(flags)
if (flags.to_int() & 0x01) != 0 {
match reply_tunnel_id {
Some(tid) => w.write_u32_be(tid)
None =>
raise InvalidLength(
"DatabaseLookup with tunnel delivery flag requires reply_tunnel_id",
)
}
}
w.write_u16_be(excluded_peers.length().reinterpret_as_uint())
for peer in excluded_peers {
peer.encode(w)
}
let enc_aes = (flags.to_int() & 0x02) != 0
let enc_ecies = (flags.to_int() & 0x10) != 0
if enc_aes || enc_ecies {
match reply_key {
Some(rk) => {
if rk.length() != 32 {
raise InvalidLength(
"DatabaseLookup reply_key must be 32 bytes, got \{rk.length()}",
)
}
w.write_bytes(rk)
}
None =>
raise InvalidLength(
"DatabaseLookup encryption flag requires reply_key",
)
}
let expected_tag_len = if enc_ecies { 8 } else { 32 }
if reply_tags.length() == 0 || reply_tags.length() > 255 {
raise InvalidLength(
"DatabaseLookup encrypted reply requires 1..255 reply_tags",
)
}
w.write_u8(reply_tags.length().to_byte())
for tag in reply_tags {
if tag.length() != expected_tag_len {
raise InvalidLength(
"DatabaseLookup reply_tag must be \{expected_tag_len} bytes, got \{tag.length()}",
)
}
w.write_bytes(tag)
}
}
}
DatabaseSearchReply(key~, peer_hashes~, from~) => {
key.encode(w)
w.write_u8(peer_hashes.length().to_byte())
for peer in peer_hashes {
peer.encode(w)
}
from.encode(w)
}
DeliveryStatus(msg_id~, timestamp_ms~) => {
w.write_u32_be(msg_id)
w.write_u64_be(timestamp_ms)
}
Garlic(data~) => {
w.write_u32_be(data.length().reinterpret_as_uint())
w.write_bytes(data)
}
TunnelData(tunnel_id~, data~) => {
if data.length() != 1024 {
raise InvalidLength(
"TunnelData payload must be 1024 bytes, got \{data.length()}",
)
}
w.write_u32_be(tunnel_id)
w.write_bytes(data)
}
TunnelGateway(tunnel_id~, data~) => {
if data.length() > 65535 {
raise InvalidLength("TunnelGateway payload exceeds 65535 bytes")
}
w.write_u32_be(tunnel_id)
w.write_u16_be(data.length().reinterpret_as_uint())
w.write_bytes(data)
}
Data(data~) => {
w.write_u32_be(data.length().reinterpret_as_uint())
w.write_bytes(data)
}
ShortTunnelBuild(records~) | ShortTunnelBuildReply(records~) => {
w.write_u8(records.length().to_byte())
for rec in records {
if rec.length() != 218 {
raise InvalidLength(
"ShortTunnelBuild record must be 218 bytes, got \{rec.length()}",
)
}
w.write_bytes(rec)
}
}
Raw(data~, ..) => w.write_bytes(data)
}
w.to_bytes()
}
///|
pub fn I2npPayload::decode_body(
msg_type : I2npMessageType,
body : Bytes,
) -> I2npPayload raise I2npError {
let r = @encoding.Reader::new(body)
match msg_type {
DatabaseStore => {
let key = @common.Hash::decode(r) catch { e => raise Common(e) }
let store_type = r.read_u8() catch { e => raise Encoding(e) }
let reply_token = r.read_u32_be() catch { e => raise Encoding(e) }
let (reply_tunnel_id, reply_gateway) = if reply_token != 0U {
let tid = r.read_u32_be() catch { e => raise Encoding(e) }
let gw = @common.Hash::decode(r) catch { e => raise Common(e) }
(tid, Some(gw))
} else {
(0U, None)
}
let data = r.read_remaining()
DatabaseStore(
key~,
store_type~,
reply_token~,
reply_tunnel_id~,
reply_gateway~,
data~,
)
}
DatabaseLookup => {
let key = @common.Hash::decode(r) catch { e => raise Common(e) }
let from = @common.Hash::decode(r) catch { e => raise Common(e) }
let flags = r.read_u8() catch { e => raise Encoding(e) }
let reply_tunnel_id = if (flags.to_int() & 0x01) != 0 {
Some(r.read_u32_be() catch { e => raise Encoding(e) })
} else {
None
}
let excl_count = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let excluded_peers : Array[@common.Hash] = Array(capacity=excl_count)
for _i = 0; _i < excl_count; _i = _i + 1 {
excluded_peers.push(
@common.Hash::decode(r) catch {
e => raise Common(e)
},
)
}
let enc_aes = (flags.to_int() & 0x02) != 0
let enc_ecies = (flags.to_int() & 0x10) != 0
let (reply_key, reply_tags) = if enc_aes || enc_ecies {
let rk = r.read_bytes(32) catch { e => raise Encoding(e) }
let tag_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let tag_len = if enc_ecies { 8 } else { 32 }
let tags : Array[Bytes] = Array(capacity=tag_count)
for _i = 0; _i < tag_count; _i = _i + 1 {
tags.push(r.read_bytes(tag_len) catch { e => raise Encoding(e) })
}
(Some(rk), tags)
} else {
(None, [])
}
DatabaseLookup(
key~,
from~,
flags~,
reply_tunnel_id~,
excluded_peers~,
reply_key~,
reply_tags~,
)
}
DatabaseSearchReply => {
let key = @common.Hash::decode(r) catch { e => raise Common(e) }
let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let peer_hashes : Array[@common.Hash] = Array(capacity=count)
for _i = 0; _i < count; _i = _i + 1 {
peer_hashes.push(@common.Hash::decode(r) catch { e => raise Common(e) })
}
let from = @common.Hash::decode(r) catch { e => raise Common(e) }
DatabaseSearchReply(key~, peer_hashes~, from~)
}
DeliveryStatus => {
let msg_id = r.read_u32_be() catch { e => raise Encoding(e) }
let timestamp_ms = r.read_u64_be() catch { e => raise Encoding(e) }
DeliveryStatus(msg_id~, timestamp_ms~)
}
Garlic => {
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let data = r.read_bytes(len) catch { e => raise Encoding(e) }
Garlic(data~)
}
TunnelData => {
let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let data = r.read_bytes(1024) catch { e => raise Encoding(e) }
TunnelData(tunnel_id~, data~)
}
TunnelGateway => {
let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let data = r.read_bytes(len) catch { e => raise Encoding(e) }
TunnelGateway(tunnel_id~, data~)
}
Data => {
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let data = r.read_bytes(len) catch { e => raise Encoding(e) }
Data(data~)
}
ShortTunnelBuild => {
let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let records : Array[Bytes] = Array(capacity=count)
for _i = 0; _i < count; _i = _i + 1 {
records.push(r.read_bytes(218) catch { e => raise Encoding(e) })
}
ShortTunnelBuild(records~)
}
ShortTunnelBuildReply => {
let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let records : Array[Bytes] = Array(capacity=count)
for _i = 0; _i < count; _i = _i + 1 {
records.push(r.read_bytes(218) catch { e => raise Encoding(e) })
}
ShortTunnelBuildReply(records~)
}
_ => Raw(msg_type~, data=body)
}
}
///|
/// Encodes a complete I2NP message with its 16-byte StandardHeader and SHA-256 checksum.
pub fn encode_standard_message(
msg_id : UInt32,
expiration_ms : UInt64,
payload : I2npPayload,
) -> Bytes raise I2npError {
let body = payload.encode_body()
if body.length() > 65535 {
raise InvalidLength("I2NP message body exceeds 65535 bytes")
}
let hdr : StandardHeader = {
msg_type: payload.msg_type(),
msg_id,
expiration_ms,
size: body.length().reinterpret_as_uint(),
checksum: payload_checksum(body),
}
let w = @encoding.Writer::new(capacity=16 + body.length())
hdr.encode(w)
w.write_bytes(body)
w.to_bytes()
}
///|
/// Decodes and checksum-verifies a standard 16-byte-header I2NP message.
pub fn decode_standard_message(
r : @encoding.Reader,
) -> (StandardHeader, I2npPayload) raise I2npError {
let hdr = StandardHeader::decode(r)
let body = r.read_bytes(hdr.size.reinterpret_as_int()) catch {
e => raise Encoding(e)
}
let actual = payload_checksum(body)
if actual != hdr.checksum {
raise ChecksumMismatch(hdr.checksum, actual)
}
let payload = I2npPayload::decode_body(hdr.msg_type, body)
(hdr, payload)
}
///|
/// Encodes a complete I2NP message with the 9-byte NTCP2/SSU2 ShortHeader.
pub fn encode_short_message(
msg_id : UInt32,
expiration_sec : UInt32,
payload : I2npPayload,
) -> Bytes raise I2npError {
let body = payload.encode_body()
let hdr : ShortHeader = {
msg_type: payload.msg_type(),
msg_id,
expiration_sec,
}
let w = @encoding.Writer::new(capacity=9 + body.length())
hdr.encode(w)
w.write_bytes(body)
w.to_bytes()
}
///|
/// Decodes an NTCP2/SSU2 9-byte-header I2NP message (consuming remaining bytes in `r`).
pub fn decode_short_message(
r : @encoding.Reader,
) -> (ShortHeader, I2npPayload) raise I2npError {
let hdr = ShortHeader::decode(r)
let body = r.read_remaining()
let payload = I2npPayload::decode_body(hdr.msg_type, body)
(hdr, payload)
}