feat: bootstrap moon-i2p core protocol foundation
check / check (ubuntu-latest) (push) Failing after 30s
check / check (macos-latest) (push) Failing after 33s
check / check (windows-latest) (push) Failing after 32s

This commit is contained in:
Antigravity committed 2026-11-27 15:37:42 +00:00
commit e527b84bc3
47 files changed
+5350

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
///|
test "Mapping canonical sorted encoding and round-trip" {
let m = @common.Mapping::new()
m.set("v", "2")
m.set("host", "127.0.0.1")
m.set("port", "12345")
m.set("caps", "LR")
let w = @encoding.Writer::new()
m.encode(w)
let raw = w.to_bytes()
let decoded = @common.Mapping::decode(@encoding.Reader::new(raw))
assert_eq(decoded.length(), 4)
assert_eq(decoded.get("caps"), Some("LR"))
assert_eq(decoded.get("host"), Some("127.0.0.1"))
assert_eq(decoded.get("port"), Some("12345"))
assert_eq(decoded.get("v"), Some("2"))
// Verify canonical sorted order: caps, host, port, v
assert_eq(decoded.entries[0].0, "caps")
assert_eq(decoded.entries[1].0, "host")
assert_eq(decoded.entries[2].0, "port")
assert_eq(decoded.entries[3].0, "v")
}
///|
test "Destination X25519+Ed25519 key extraction, Base64, and .b32.i2p address" {
let crypto_pub = Bytes::make(32, b'\x11')
let sig_pub = Bytes::make(32, b'\x22')
let dest = @common.Destination::new_x25519_ed25519(crypto_pub, sig_pub)
let raw = dest.to_bytes()
// 384 bytes keys + 1 byte type + 2 bytes len + 4 bytes KeyCert = 391 bytes
assert_eq(raw.length(), 391)
assert_eq(dest.inner.crypto_public_key(), crypto_pub)
assert_eq(dest.inner.signing_public_key(), sig_pub)
assert_eq(dest.inner.crypto_type(), X25519)
assert_eq(dest.inner.signing_type(), EdDsaSha512Ed25519)
// Base64 round-trip
let b64 = dest.to_base64()
let restored = @common.Destination::from_base64(b64)
assert_eq(restored, dest)
// .b32.i2p address is 52 base32 chars + ".b32.i2p" (60 chars total)
let b32 = dest.b32_address()
assert_eq(b32.length(), 60)
assert_true(b32.has_suffix(".b32.i2p"))
}
///|
test "RouterInfo encode and decode round-trip" {
let ri_id = @common.RouterIdentity::new_x25519_ed25519(
Bytes::make(32, b'\x33'),
Bytes::make(32, b'\x44'),
)
let addr_opts = @common.Mapping::from_entries([
("host", "192.0.2.10"),
("port", "9001"),
("v", "2"),
])
let addr = @common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)
let ri_opts = @common.Mapping::from_entries([
("caps", "OR"),
("netId", "2"),
("router.version", "0.9.64"),
])
let ri : @common.RouterInfo = {
identity: ri_id,
published: 1700000000000UL,
addresses: [addr],
options: ri_opts,
signature: Bytes::make(64, b'\x55'),
}
let w = @encoding.Writer::new()
ri.encode(w)
let decoded = @common.RouterInfo::decode(@encoding.Reader::new(w.to_bytes()))
assert_eq(decoded.identity, ri.identity)
assert_eq(decoded.published, ri.published)
assert_eq(decoded.addresses.length(), 1)
assert_eq(decoded.addresses[0].transport_style, "NTCP2")
assert_eq(decoded.options.get("netId"), Some("2"))
assert_eq(decoded.signature, ri.signature)
}
///|
test "LeaseSet2 encode and decode round-trip" {
let dest = @common.Destination::new_x25519_ed25519(
Bytes::make(32, b'\xaa'),
Bytes::make(32, b'\xbb'),
)
let gw = @common.Hash::from_bytes(Bytes::make(32, b'\xcc'))
let lease : @common.Lease2 = {
tunnel_gw: gw,
tunnel_id: 424242U,
end_date_sec: 1700000600U,
}
let ls2 : @common.LeaseSet2 = {
destination: dest,
published_sec: 1700000000U,
expires_offset: 600U,
flags: 0U,
options: @common.Mapping::new(),
encryption_keys: [{ key_type: X25519, key_data: Bytes::make(32, b'\xdd'), }],
leases: [lease],
signature: Bytes::make(64, b'\xee'),
}
let w = @encoding.Writer::new()
ls2.encode(w)
let decoded = @common.LeaseSet2::decode(@encoding.Reader::new(w.to_bytes()))
assert_eq(decoded, ls2)
}
+256
View File
@@ -0,0 +1,256 @@
///|
/// KeysAndCert is the 387+ byte base structure shared by `RouterIdentity` and `Destination`:
/// - 256 bytes: crypto public key (with trailing padding if key < 256 bytes)
/// - 128 bytes: signing public key (right-aligned with leading padding if key < 128 bytes)
/// - 3+ bytes: `Certificate` (typically `Certificate::Key` for modern X25519 + Ed25519).
#derive(Eq, Debug)
pub struct KeysAndCert {
key_data : Bytes // exactly 384 bytes (256 + 128)
certificate : Certificate
}
///|
/// Constructs a modern X25519 + Ed25519 `KeysAndCert` (CryptoType=4, SigType=7).
/// Per I2P spec: X25519 public key (32 bytes) is placed at bytes 0..32,
/// `padding` (320 bytes, or zero-filled if omitted) occupies bytes 32..352,
/// and Ed25519 signing public key (32 bytes) is right-aligned at bytes 352..384.
pub fn KeysAndCert::new_x25519_ed25519(
crypto_pub : Bytes,
signing_pub : Bytes,
padding~ : Bytes = b"",
) -> KeysAndCert raise CommonError {
if crypto_pub.length() != 32 {
raise InvalidLength(
"X25519 public key must be 32 bytes, got \{crypto_pub.length()}",
)
}
if signing_pub.length() != 32 {
raise InvalidLength(
"Ed25519 public key must be 32 bytes, got \{signing_pub.length()}",
)
}
let buf = FixedArray::make(384, b'\x00')
for i = 0; i < 32; i = i + 1 {
buf[i] = crypto_pub[i]
}
let pad_len = if padding.length() < 320 { padding.length() } else { 320 }
for i = 0; i < pad_len; i = i + 1 {
buf[32 + i] = padding[i]
}
for i = 0; i < 32; i = i + 1 {
buf[352 + i] = signing_pub[i]
}
let cert = Certificate::Key(KeyCertificate::new(EdDsaSha512Ed25519, X25519))
{ key_data: Bytes::from_array(buf), certificate: cert, }
}
///|
pub fn KeysAndCert::crypto_type(self : KeysAndCert) -> CryptoPublicKeyType {
match self.certificate {
Key(kc) => kc.crypto_type
_ => ElGamal
}
}
///|
pub fn KeysAndCert::signing_type(self : KeysAndCert) -> SigningPublicKeyType {
match self.certificate {
Key(kc) => kc.sig_type
_ => DsaSha1
}
}
///|
/// Extracts the active cryptography public key from the 384-byte key block.
pub fn KeysAndCert::crypto_public_key(self : KeysAndCert) -> Bytes {
let klen = self.crypto_type().key_length()
let take = if klen <= 256 { klen } else { 256 }
let out = FixedArray::make(take, b'\x00')
for i = 0; i < take; i = i + 1 {
out[i] = self.key_data[i]
}
Bytes::from_array(out)
}
///|
/// Extracts the active signing public key (right-aligned in bytes 256..384, plus any excess in KeyCert).
pub fn KeysAndCert::signing_public_key(self : KeysAndCert) -> Bytes {
let klen = self.signing_type().public_key_length()
if klen <= 128 {
let start = 384 - klen
let out = FixedArray::make(klen, b'\x00')
for i = 0; i < klen; i = i + 1 {
out[i] = self.key_data[start + i]
}
Bytes::from_array(out)
} else {
let excess = match self.certificate {
Key(kc) => kc.excess_signing_key
_ => b""
}
let out = FixedArray::make(128 + excess.length(), b'\x00')
for i = 0; i < 128; i = i + 1 {
out[i] = self.key_data[256 + i]
}
for i = 0; i < excess.length(); i = i + 1 {
out[128 + i] = excess[i]
}
Bytes::from_array(out)
}
}
///|
pub fn KeysAndCert::encode(self : KeysAndCert, w : @encoding.Writer) -> Unit {
w.write_bytes(self.key_data)
self.certificate.encode(w)
}
///|
pub fn KeysAndCert::to_bytes(self : KeysAndCert) -> Bytes {
let w = @encoding.Writer::new(capacity=391)
self.encode(w)
w.to_bytes()
}
///|
pub fn KeysAndCert::decode(
r : @encoding.Reader,
) -> KeysAndCert raise CommonError {
let key_data = r.read_bytes(384) catch { e => raise Encoding(e) }
let certificate = Certificate::decode(r)
{ key_data, certificate, }
}
///|
pub fn KeysAndCert::hash(self : KeysAndCert) -> Hash {
Hash::sha256(self.to_bytes())
}
///|
/// I2P Destination: identifies a client endpoint (service or client tunnel) on the I2P network.
#derive(Eq, Debug)
pub struct Destination {
inner : KeysAndCert
}
///|
pub fn Destination::new(inner : KeysAndCert) -> Destination {
{ inner, }
}
///|
pub fn Destination::new_x25519_ed25519(
crypto_pub : Bytes,
signing_pub : Bytes,
padding~ : Bytes = b"",
) -> Destination raise CommonError {
{ inner: KeysAndCert::new_x25519_ed25519(crypto_pub, signing_pub, padding~), }
}
///|
pub fn Destination::encode(self : Destination, w : @encoding.Writer) -> Unit {
self.inner.encode(w)
}
///|
pub fn Destination::decode(
r : @encoding.Reader,
) -> Destination raise CommonError {
{ inner: KeysAndCert::decode(r), }
}
///|
pub fn Destination::to_bytes(self : Destination) -> Bytes {
self.inner.to_bytes()
}
///|
pub fn Destination::hash(self : Destination) -> Hash {
self.inner.hash()
}
///|
/// Returns the canonical `<52-char-base32>.b32.i2p` address for this Destination.
pub fn Destination::b32_address(self : Destination) -> String {
self.hash().to_b32_address()
}
///|
pub fn Destination::to_base64(self : Destination) -> String {
@encoding.base64_encode(self.to_bytes())
}
///|
pub fn Destination::from_base64(s : String) -> Destination raise CommonError {
let raw = @encoding.base64_decode(s) catch { e => raise Encoding(e) }
let r = @encoding.Reader::new(raw)
Destination::decode(r)
}
///|
/// I2P RouterIdentity: uniquely identifies an I2P router in the NetDB and NTCP2/SSU2 handshakes.
#derive(Eq, Debug)
pub struct RouterIdentity {
inner : KeysAndCert
}
///|
pub fn RouterIdentity::new(inner : KeysAndCert) -> RouterIdentity {
{ inner, }
}
///|
pub fn RouterIdentity::new_x25519_ed25519(
crypto_pub : Bytes,
signing_pub : Bytes,
padding~ : Bytes = b"",
) -> RouterIdentity raise CommonError {
{ inner: KeysAndCert::new_x25519_ed25519(crypto_pub, signing_pub, padding~), }
}
///|
pub fn RouterIdentity::encode(
self : RouterIdentity,
w : @encoding.Writer,
) -> Unit {
self.inner.encode(w)
}
///|
pub fn RouterIdentity::decode(
r : @encoding.Reader,
) -> RouterIdentity raise CommonError {
{ inner: KeysAndCert::decode(r), }
}
///|
pub fn RouterIdentity::to_bytes(self : RouterIdentity) -> Bytes {
self.inner.to_bytes()
}
///|
pub fn RouterIdentity::hash(self : RouterIdentity) -> Hash {
self.inner.hash()
}
///|
pub fn RouterIdentity::b32_address(self : RouterIdentity) -> String {
self.hash().to_b32_address()
}
///|
pub fn RouterIdentity::signing_type(
self : RouterIdentity,
) -> SigningPublicKeyType {
self.inner.signing_type()
}
///|
pub fn RouterIdentity::crypto_public_key(self : RouterIdentity) -> Bytes {
self.inner.crypto_public_key()
}
///|
pub fn RouterIdentity::signing_public_key(self : RouterIdentity) -> Bytes {
self.inner.signing_public_key()
}
+4
View File
@@ -0,0 +1,4 @@
import {
"experiments/moon_i2p/encoding",
"experiments/moon_i2p/crypto",
}
+219
View File
@@ -0,0 +1,219 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moon_i2p/common"
import {
"experiments/moon_i2p/encoding",
"moonbitlang/core/debug",
}
// Values
// Errors
#derive(Eq, @debug.Debug)
pub suberror CommonError {
Encoding(@encoding.EncodingError)
InvalidLength(String)
InvalidFormat(String)
}
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum Certificate {
Null
HashCash(Bytes)
Hidden
Signed(Bytes)
Multiple(Bytes)
Key(KeyCertificate)
Unknown(Byte, Bytes)
}
pub fn Certificate::decode(@encoding.Reader) -> Self raise CommonError
pub fn Certificate::encode(Self, @encoding.Writer) -> Unit
#derive(Eq, @debug.Debug)
pub(all) enum CryptoPublicKeyType {
ElGamal
P256
P384
P521
X25519
Unknown(UInt32)
}
pub fn CryptoPublicKeyType::from_u16(UInt32) -> Self
pub fn CryptoPublicKeyType::key_length(Self) -> Int32
pub fn CryptoPublicKeyType::to_u16(Self) -> UInt32
#derive(Eq, @debug.Debug)
pub struct Destination {
inner : KeysAndCert
}
pub fn Destination::b32_address(Self) -> String
pub fn Destination::decode(@encoding.Reader) -> Self raise CommonError
pub fn Destination::encode(Self, @encoding.Writer) -> Unit
pub fn Destination::from_base64(String) -> Self raise CommonError
pub fn Destination::hash(Self) -> Hash
pub fn Destination::new(KeysAndCert) -> Self
pub fn Destination::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError
pub fn Destination::to_base64(Self) -> String
pub fn Destination::to_bytes(Self) -> Bytes
#derive(Eq, @debug.Debug)
pub struct Hash {
bytes : Bytes
}
pub fn Hash::as_bytes(Self) -> Bytes
pub fn Hash::decode(@encoding.Reader) -> Self raise CommonError
pub fn Hash::encode(Self, @encoding.Writer) -> Unit
pub fn Hash::from_bytes(Bytes) -> Self raise CommonError
pub fn Hash::sha256(Bytes) -> Self
pub fn Hash::to_b32_address(Self) -> String
pub fn Hash::to_base32(Self) -> String
pub fn Hash::to_base64(Self) -> String
pub fn Hash::to_hex(Self) -> String
#derive(Eq, @debug.Debug)
pub(all) struct KeyCertificate {
sig_type : SigningPublicKeyType
crypto_type : CryptoPublicKeyType
excess_signing_key : Bytes
excess_crypto_key : Bytes
}
pub fn KeyCertificate::new(SigningPublicKeyType, CryptoPublicKeyType, excess_signing_key? : Bytes, excess_crypto_key? : Bytes) -> Self
#derive(Eq, @debug.Debug)
pub struct KeysAndCert {
key_data : Bytes
certificate : Certificate
}
pub fn KeysAndCert::crypto_public_key(Self) -> Bytes
pub fn KeysAndCert::crypto_type(Self) -> CryptoPublicKeyType
pub fn KeysAndCert::decode(@encoding.Reader) -> Self raise CommonError
pub fn KeysAndCert::encode(Self, @encoding.Writer) -> Unit
pub fn KeysAndCert::hash(Self) -> Hash
pub fn KeysAndCert::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError
pub fn KeysAndCert::signing_public_key(Self) -> Bytes
pub fn KeysAndCert::signing_type(Self) -> SigningPublicKeyType
pub fn KeysAndCert::to_bytes(Self) -> Bytes
#derive(Eq, @debug.Debug)
pub(all) struct Lease {
tunnel_gw : Hash
tunnel_id : UInt32
end_date_ms : UInt64
}
pub fn Lease::decode(@encoding.Reader) -> Self raise CommonError
pub fn Lease::encode(Self, @encoding.Writer) -> Unit
#derive(Eq, @debug.Debug)
pub(all) struct Lease2 {
tunnel_gw : Hash
tunnel_id : UInt32
end_date_sec : UInt32
}
pub fn Lease2::decode(@encoding.Reader) -> Self raise CommonError
pub fn Lease2::encode(Self, @encoding.Writer) -> Unit
#derive(Eq, @debug.Debug)
pub(all) struct LeaseSet2 {
destination : Destination
published_sec : UInt32
expires_offset : UInt32
flags : UInt32
options : Mapping
encryption_keys : Array[LeaseSet2EncryptionKey]
leases : Array[Lease2]
signature : Bytes
}
pub fn LeaseSet2::decode(@encoding.Reader) -> Self raise CommonError
pub fn LeaseSet2::encode(Self, @encoding.Writer) -> Unit raise CommonError
#derive(Eq, @debug.Debug)
pub(all) struct LeaseSet2EncryptionKey {
key_type : CryptoPublicKeyType
key_data : Bytes
}
#derive(Eq, @debug.Debug)
pub struct Mapping {
entries : Array[(String, String)]
}
pub fn Mapping::decode(@encoding.Reader) -> Self raise CommonError
pub fn Mapping::encode(Self, @encoding.Writer) -> Unit raise CommonError
pub fn Mapping::from_entries(Array[(String, String)]) -> Self
pub fn Mapping::get(Self, String) -> String?
pub fn Mapping::length(Self) -> Int32
pub fn Mapping::new() -> Self
pub fn Mapping::set(Self, String, String) -> Unit
#derive(Eq, @debug.Debug)
pub(all) struct RouterAddress {
cost : Byte
expiration : UInt64
transport_style : String
options : Mapping
}
pub fn RouterAddress::decode(@encoding.Reader) -> Self raise CommonError
pub fn RouterAddress::encode(Self, @encoding.Writer) -> Unit raise CommonError
pub fn RouterAddress::new(Byte, String, Mapping, expiration? : UInt64) -> Self
#derive(Eq, @debug.Debug)
pub struct RouterIdentity {
inner : KeysAndCert
}
pub fn RouterIdentity::b32_address(Self) -> String
pub fn RouterIdentity::crypto_public_key(Self) -> Bytes
pub fn RouterIdentity::decode(@encoding.Reader) -> Self raise CommonError
pub fn RouterIdentity::encode(Self, @encoding.Writer) -> Unit
pub fn RouterIdentity::hash(Self) -> Hash
pub fn RouterIdentity::new(KeysAndCert) -> Self
pub fn RouterIdentity::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError
pub fn RouterIdentity::signing_public_key(Self) -> Bytes
pub fn RouterIdentity::signing_type(Self) -> SigningPublicKeyType
pub fn RouterIdentity::to_bytes(Self) -> Bytes
#derive(Eq, @debug.Debug)
pub(all) struct RouterInfo {
identity : RouterIdentity
published : UInt64
addresses : Array[RouterAddress]
options : Mapping
signature : Bytes
}
pub fn RouterInfo::decode(@encoding.Reader) -> Self raise CommonError
pub fn RouterInfo::encode(Self, @encoding.Writer) -> Unit raise CommonError
pub fn RouterInfo::unsigned_bytes(Self) -> Bytes raise CommonError
#derive(Eq, @debug.Debug)
pub struct SessionKey {
bytes : Bytes
}
pub fn SessionKey::from_bytes(Bytes) -> Self raise CommonError
#derive(Eq, @debug.Debug)
pub struct SessionTag {
bytes : Bytes
}
pub fn SessionTag::from_bytes(Bytes) -> Self raise CommonError
#derive(Eq, @debug.Debug)
pub(all) enum SigningPublicKeyType {
DsaSha1
EcdsaSha256P256
EcdsaSha384P384
EcdsaSha512P521
RsaSha256_2048
RsaSha384_3072
RsaSha512_4096
EdDsaSha512Ed25519
EdDsaSha512Ed25519ph
RedDsaSha512Ed25519
Unknown(UInt32)
}
pub fn SigningPublicKeyType::from_u16(UInt32) -> Self
pub fn SigningPublicKeyType::public_key_length(Self) -> Int32
pub fn SigningPublicKeyType::signature_length(Self) -> Int32
pub fn SigningPublicKeyType::to_u16(Self) -> UInt32
// Type aliases
// Traits
+244
View File
@@ -0,0 +1,244 @@
///|
/// RouterAddress: transport endpoint advertised inside a RouterInfo (e.g., NTCP2, SSU2).
#derive(Eq, Debug)
pub(all) struct RouterAddress {
cost : Byte
expiration : UInt64 // milliseconds since Unix epoch (0 = never)
transport_style : String
options : Mapping
}
///|
pub fn RouterAddress::new(
cost : Byte,
transport_style : String,
options : Mapping,
expiration~ : UInt64 = 0UL,
) -> RouterAddress {
{ cost, expiration, transport_style, options, }
}
///|
pub fn RouterAddress::encode(
self : RouterAddress,
w : @encoding.Writer,
) -> Unit raise CommonError {
w.write_u8(self.cost)
w.write_u64_be(self.expiration)
w.write_i2p_string(self.transport_style) catch {
e => raise Encoding(e)
}
self.options.encode(w)
}
///|
pub fn RouterAddress::decode(
r : @encoding.Reader,
) -> RouterAddress raise CommonError {
let cost = r.read_u8() catch { e => raise Encoding(e) }
let expiration = r.read_u64_be() catch { e => raise Encoding(e) }
let transport_style = r.read_i2p_string() catch { e => raise Encoding(e) }
let options = Mapping::decode(r)
{ cost, expiration, transport_style, options, }
}
///|
/// RouterInfo: NetDB record advertising a router's identity, transport addresses, and capabilities.
#derive(Eq, Debug)
pub(all) struct RouterInfo {
identity : RouterIdentity
published : UInt64 // milliseconds since Unix epoch
addresses : Array[RouterAddress]
options : Mapping
signature : Bytes
}
///|
/// Encodes the unsigned body of RouterInfo (the exact bytes signed by `signature`).
pub fn RouterInfo::unsigned_bytes(self : RouterInfo) -> Bytes raise CommonError {
let w = @encoding.Writer::new(capacity=512)
self.identity.encode(w)
w.write_u64_be(self.published)
w.write_u8(self.addresses.length().to_byte())
for addr in self.addresses {
addr.encode(w)
}
// peer_size is always 0 in I2P spec
w.write_u8(b'\x00')
self.options.encode(w)
w.to_bytes()
}
///|
pub fn RouterInfo::encode(
self : RouterInfo,
w : @encoding.Writer,
) -> Unit raise CommonError {
w.write_bytes(self.unsigned_bytes())
w.write_bytes(self.signature)
}
///|
pub fn RouterInfo::decode(r : @encoding.Reader) -> RouterInfo raise CommonError {
let identity = RouterIdentity::decode(r)
let published = r.read_u64_be() catch { e => raise Encoding(e) }
let addr_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let addresses : Array[RouterAddress] = Array(capacity=addr_count)
for _i = 0; _i < addr_count; _i = _i + 1 {
addresses.push(RouterAddress::decode(r))
}
let peer_size = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
for _i = 0; _i < peer_size; _i = _i + 1 {
let _ = Hash::decode(r)
}
let options = Mapping::decode(r)
let sig_len = identity.signing_type().signature_length()
let signature = if sig_len > 0 {
r.read_bytes(sig_len) catch {
e => raise Encoding(e)
}
} else {
r.read_remaining()
}
{ identity, published, addresses, options, signature, }
}
///|
/// Legacy Lease (44 bytes): 32-byte tunnel gateway hash, 4-byte tunnel ID, 8-byte ms end date.
#derive(Eq, Debug)
pub(all) struct Lease {
tunnel_gw : Hash
tunnel_id : UInt32
end_date_ms : UInt64
}
///|
pub fn Lease::encode(self : Lease, w : @encoding.Writer) -> Unit {
self.tunnel_gw.encode(w)
w.write_u32_be(self.tunnel_id)
w.write_u64_be(self.end_date_ms)
}
///|
pub fn Lease::decode(r : @encoding.Reader) -> Lease raise CommonError {
let tunnel_gw = Hash::decode(r)
let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let end_date_ms = r.read_u64_be() catch { e => raise Encoding(e) }
{ tunnel_gw, tunnel_id, end_date_ms, }
}
///|
/// Modern Lease2 (40 bytes, used in LeaseSet2): 32-byte tunnel gateway hash, 4-byte tunnel ID,
/// 4-byte end date in seconds since Unix epoch.
#derive(Eq, Debug)
pub(all) struct Lease2 {
tunnel_gw : Hash
tunnel_id : UInt32
end_date_sec : UInt32
}
///|
pub fn Lease2::encode(self : Lease2, w : @encoding.Writer) -> Unit {
self.tunnel_gw.encode(w)
w.write_u32_be(self.tunnel_id)
w.write_u32_be(self.end_date_sec)
}
///|
pub fn Lease2::decode(r : @encoding.Reader) -> Lease2 raise CommonError {
let tunnel_gw = Hash::decode(r)
let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let end_date_sec = r.read_u32_be() catch { e => raise Encoding(e) }
{ tunnel_gw, tunnel_id, end_date_sec, }
}
///|
/// Encryption key entry inside a LeaseSet2.
#derive(Eq, Debug)
pub(all) struct LeaseSet2EncryptionKey {
key_type : CryptoPublicKeyType
key_data : Bytes
}
///|
/// Modern LeaseSet2 (I2P Proposal 123, NetDB type 3).
#derive(Eq, Debug)
pub(all) struct LeaseSet2 {
destination : Destination
published_sec : UInt32
expires_offset : UInt32 // uint16 offset in seconds from published_sec
flags : UInt32 // uint16
options : Mapping
encryption_keys : Array[LeaseSet2EncryptionKey]
leases : Array[Lease2]
signature : Bytes
}
///|
pub fn LeaseSet2::encode(
self : LeaseSet2,
w : @encoding.Writer,
) -> Unit raise CommonError {
self.destination.encode(w)
w.write_u32_be(self.published_sec)
w.write_u16_be(self.expires_offset)
w.write_u16_be(self.flags)
self.options.encode(w)
w.write_u8(self.encryption_keys.length().to_byte())
for ek in self.encryption_keys {
w.write_u16_be(ek.key_type.to_u16())
w.write_u16_be(ek.key_data.length().reinterpret_as_uint())
w.write_bytes(ek.key_data)
}
w.write_u8(self.leases.length().to_byte())
for lease in self.leases {
lease.encode(w)
}
w.write_bytes(self.signature)
}
///|
pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError {
let destination = Destination::decode(r)
let published_sec = r.read_u32_be() catch { e => raise Encoding(e) }
let expires_offset = r.read_u16_be() catch { e => raise Encoding(e) }
let flags = r.read_u16_be() catch { e => raise Encoding(e) }
let options = Mapping::decode(r)
let key_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let encryption_keys : Array[LeaseSet2EncryptionKey] = Array(
capacity=key_count,
)
for _i = 0; _i < key_count; _i = _i + 1 {
let kt = CryptoPublicKeyType::from_u16(
r.read_u16_be() catch {
e => raise Encoding(e)
},
)
let klen = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let kd = r.read_bytes(klen) catch { e => raise Encoding(e) }
encryption_keys.push({ key_type: kt, key_data: kd, })
}
let lease_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
let leases : Array[Lease2] = Array(capacity=lease_count)
for _i = 0; _i < lease_count; _i = _i + 1 {
leases.push(Lease2::decode(r))
}
let sig_len = destination.inner.signing_type().signature_length()
let signature = if sig_len > 0 {
r.read_bytes(sig_len) catch {
e => raise Encoding(e)
}
} else {
r.read_remaining()
}
{
destination,
published_sec,
expires_offset,
flags,
options,
encryption_keys,
leases,
signature,
}
}
+488
View File
@@ -0,0 +1,488 @@
///|
/// Errors raised when encoding, decoding, or validating I2P Common Structures.
#derive(Eq, Debug)
pub suberror CommonError {
Encoding(@encoding.EncodingError)
InvalidLength(String)
InvalidFormat(String)
}
///|
/// A 32-byte SHA-256 hash used throughout I2P for RouterIdentities, Destinations, and NetDB keys.
#derive(Eq, Debug)
pub struct Hash {
bytes : Bytes
}
///|
pub fn Hash::from_bytes(bytes : Bytes) -> Hash raise CommonError {
if bytes.length() != 32 {
raise InvalidLength("I2P Hash must be 32 bytes, got \{bytes.length()}")
}
{ bytes, }
}
///|
pub fn Hash::sha256(data : Bytes) -> Hash {
{ bytes: @crypto.sha256(data), }
}
///|
pub fn Hash::as_bytes(self : Hash) -> Bytes {
self.bytes
}
///|
pub fn Hash::to_base32(self : Hash) -> String {
@encoding.base32_encode(self.bytes)
}
///|
pub fn Hash::to_b32_address(self : Hash) -> String {
self.to_base32() + ".b32.i2p"
}
///|
pub fn Hash::to_base64(self : Hash) -> String {
@encoding.base64_encode(self.bytes)
}
///|
pub fn Hash::to_hex(self : Hash) -> String {
@encoding.hex_encode(self.bytes)
}
///|
pub fn Hash::encode(self : Hash, w : @encoding.Writer) -> Unit {
w.write_bytes(self.bytes)
}
///|
pub fn Hash::decode(r : @encoding.Reader) -> Hash raise CommonError {
let bytes = r.read_bytes(32) catch { e => raise Encoding(e) }
{ bytes, }
}
///|
/// 32-byte symmetric session key.
#derive(Eq, Debug)
pub struct SessionKey {
bytes : Bytes
}
///|
pub fn SessionKey::from_bytes(bytes : Bytes) -> SessionKey raise CommonError {
if bytes.length() != 32 {
raise InvalidLength("SessionKey must be 32 bytes, got \{bytes.length()}")
}
{ bytes, }
}
///|
/// Session tag (8 bytes for ECIES-X25519-AEAD-Ratchet, or 32 bytes for legacy ElGamal/AES).
#derive(Eq, Debug)
pub struct SessionTag {
bytes : Bytes
}
///|
pub fn SessionTag::from_bytes(bytes : Bytes) -> SessionTag raise CommonError {
if bytes.length() != 8 && bytes.length() != 32 {
raise InvalidLength(
"SessionTag must be 8 or 32 bytes, got \{bytes.length()}",
)
}
{ bytes, }
}
///|
/// I2P Cryptography Public Key types (per I2P Common Structures specification).
#derive(Eq, Debug)
pub(all) enum CryptoPublicKeyType {
ElGamal // 0 (256 bytes)
P256 // 1 (64 bytes)
P384 // 2 (96 bytes)
P521 // 3 (132 bytes)
X25519 // 4 (32 bytes) - modern default
Unknown(UInt32)
}
///|
pub fn CryptoPublicKeyType::to_u16(self : CryptoPublicKeyType) -> UInt32 {
match self {
ElGamal => 0U
P256 => 1U
P384 => 2U
P521 => 3U
X25519 => 4U
Unknown(v) => v
}
}
///|
pub fn CryptoPublicKeyType::from_u16(v : UInt32) -> CryptoPublicKeyType {
match v {
0U => ElGamal
1U => P256
2U => P384
3U => P521
4U => X25519
_ => Unknown(v)
}
}
///|
pub fn CryptoPublicKeyType::key_length(self : CryptoPublicKeyType) -> Int32 {
match self {
ElGamal => 256
P256 => 64
P384 => 96
P521 => 132
X25519 => 32
Unknown(_) => 0
}
}
///|
/// I2P Signing Public Key types (per I2P Common Structures specification).
#derive(Eq, Debug)
pub(all) enum SigningPublicKeyType {
DsaSha1 // 0 (128B key, 40B sig)
EcdsaSha256P256 // 1 (64B key, 64B sig)
EcdsaSha384P384 // 2 (96B key, 96B sig)
EcdsaSha512P521 // 3 (132B key, 132B sig)
RsaSha256_2048 // 4 (256B key, 256B sig)
RsaSha384_3072 // 5 (384B key, 384B sig)
RsaSha512_4096 // 6 (512B key, 512B sig)
EdDsaSha512Ed25519 // 7 (32B key, 64B sig) - modern default
EdDsaSha512Ed25519ph // 8 (32B key, 64B sig)
RedDsaSha512Ed25519 // 11 (32B key, 64B sig)
Unknown(UInt32)
}
///|
pub fn SigningPublicKeyType::to_u16(self : SigningPublicKeyType) -> UInt32 {
match self {
DsaSha1 => 0U
EcdsaSha256P256 => 1U
EcdsaSha384P384 => 2U
EcdsaSha512P521 => 3U
RsaSha256_2048 => 4U
RsaSha384_3072 => 5U
RsaSha512_4096 => 6U
EdDsaSha512Ed25519 => 7U
EdDsaSha512Ed25519ph => 8U
RedDsaSha512Ed25519 => 11U
Unknown(v) => v
}
}
///|
pub fn SigningPublicKeyType::from_u16(v : UInt32) -> SigningPublicKeyType {
match v {
0U => DsaSha1
1U => EcdsaSha256P256
2U => EcdsaSha384P384
3U => EcdsaSha512P521
4U => RsaSha256_2048
5U => RsaSha384_3072
6U => RsaSha512_4096
7U => EdDsaSha512Ed25519
8U => EdDsaSha512Ed25519ph
11U => RedDsaSha512Ed25519
_ => Unknown(v)
}
}
///|
pub fn SigningPublicKeyType::public_key_length(
self : SigningPublicKeyType,
) -> Int32 {
match self {
DsaSha1 => 128
EcdsaSha256P256 => 64
EcdsaSha384P384 => 96
EcdsaSha512P521 => 132
RsaSha256_2048 => 256
RsaSha384_3072 => 384
RsaSha512_4096 => 512
EdDsaSha512Ed25519 | EdDsaSha512Ed25519ph | RedDsaSha512Ed25519 => 32
Unknown(_) => 0
}
}
///|
pub fn SigningPublicKeyType::signature_length(
self : SigningPublicKeyType,
) -> Int32 {
match self {
DsaSha1 => 40
EcdsaSha256P256 => 64
EcdsaSha384P384 => 96
EcdsaSha512P521 => 132
RsaSha256_2048 => 256
RsaSha384_3072 => 384
RsaSha512_4096 => 512
EdDsaSha512Ed25519 | EdDsaSha512Ed25519ph | RedDsaSha512Ed25519 => 64
Unknown(_) => 0
}
}
///|
/// Key Certificate payload (Certificate type 5).
#derive(Eq, Debug)
pub(all) struct KeyCertificate {
sig_type : SigningPublicKeyType
crypto_type : CryptoPublicKeyType
excess_signing_key : Bytes
excess_crypto_key : Bytes
}
///|
pub fn KeyCertificate::new(
sig_type : SigningPublicKeyType,
crypto_type : CryptoPublicKeyType,
excess_signing_key~ : Bytes = b"",
excess_crypto_key~ : Bytes = b"",
) -> KeyCertificate {
{ sig_type, crypto_type, excess_signing_key, excess_crypto_key, }
}
///|
/// I2P Certificate structure (1-byte type, 2-byte big-endian length, payload).
#derive(Eq, Debug)
pub(all) enum Certificate {
Null // 0
HashCash(Bytes) // 1
Hidden // 2
Signed(Bytes) // 3
Multiple(Bytes) // 4
Key(KeyCertificate) // 5
Unknown(Byte, Bytes)
}
///|
pub fn Certificate::encode(self : Certificate, w : @encoding.Writer) -> Unit {
match self {
Null => {
w.write_u8(b'\x00')
w.write_u16_be(0U)
}
HashCash(p) => {
w.write_u8(b'\x01')
w.write_u16_be(p.length().reinterpret_as_uint())
w.write_bytes(p)
}
Hidden => {
w.write_u8(b'\x02')
w.write_u16_be(0U)
}
Signed(p) => {
w.write_u8(b'\x03')
w.write_u16_be(p.length().reinterpret_as_uint())
w.write_bytes(p)
}
Multiple(p) => {
w.write_u8(b'\x04')
w.write_u16_be(p.length().reinterpret_as_uint())
w.write_bytes(p)
}
Key(kc) => {
let payload_len = 4 +
kc.excess_signing_key.length() +
kc.excess_crypto_key.length()
w.write_u8(b'\x05')
w.write_u16_be(payload_len.reinterpret_as_uint())
w.write_u16_be(kc.sig_type.to_u16())
w.write_u16_be(kc.crypto_type.to_u16())
w.write_bytes(kc.excess_signing_key)
w.write_bytes(kc.excess_crypto_key)
}
Unknown(t, p) => {
w.write_u8(t)
w.write_u16_be(p.length().reinterpret_as_uint())
w.write_bytes(p)
}
}
}
///|
pub fn Certificate::decode(
r : @encoding.Reader,
) -> Certificate raise CommonError {
let cert_type = r.read_u8() catch { e => raise Encoding(e) }
let payload_len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let payload = r.read_bytes(payload_len) catch { e => raise Encoding(e) }
match cert_type.to_int() {
0 => {
if payload_len != 0 {
raise InvalidLength("Null certificate must have 0-byte payload")
}
Null
}
1 => HashCash(payload)
2 => Hidden
3 => Signed(payload)
4 => Multiple(payload)
5 => {
if payload_len < 4 {
raise InvalidLength("Key certificate payload must be at least 4 bytes")
}
let pr = @encoding.Reader::new(payload)
let sig_type = SigningPublicKeyType::from_u16(
pr.read_u16_be() catch {
e => raise Encoding(e)
},
)
let crypto_type = CryptoPublicKeyType::from_u16(
pr.read_u16_be() catch {
e => raise Encoding(e)
},
)
let sig_excess = if sig_type.public_key_length() > 128 {
sig_type.public_key_length() - 128
} else {
0
}
let excess_sig = if sig_excess > 0 && pr.remaining() >= sig_excess {
pr.read_bytes(sig_excess) catch {
e => raise Encoding(e)
}
} else {
b""
}
let excess_crypto = pr.read_remaining()
Key({
sig_type,
crypto_type,
excess_signing_key: excess_sig,
excess_crypto_key: excess_crypto,
})
}
_ => Unknown(cert_type, payload)
}
}
///|
/// I2P Mapping: 2-byte big-endian total byte length followed by `key=value;` pairs
/// where keys and values are I2P Strings. Canonical encoding sorts entries by key.
#derive(Eq, Debug)
pub struct Mapping {
entries : Array[(String, String)]
}
///|
pub fn Mapping::new() -> Mapping {
{ entries: [], }
}
///|
pub fn Mapping::from_entries(entries : Array[(String, String)]) -> Mapping {
let copy : Array[(String, String)] = Array(capacity=entries.length())
for entry in entries {
copy.push(entry)
}
{ entries: copy, }
}
///|
pub fn Mapping::set(self : Mapping, key : String, value : String) -> Unit {
for i = 0; i < self.entries.length(); i = i + 1 {
if self.entries[i].0 == key {
self.entries[i] = (key, value)
return
}
}
self.entries.push((key, value))
}
///|
pub fn Mapping::get(self : Mapping, key : String) -> String? {
for entry in self.entries {
if entry.0 == key {
return Some(entry.1)
}
}
None
}
///|
pub fn Mapping::length(self : Mapping) -> Int32 {
self.entries.length()
}
///|
fn bytes_lex_gt(a : Bytes, b : Bytes) -> Bool {
let min_len = if a.length() < b.length() { a.length() } else { b.length() }
for i = 0; i < min_len; i = i + 1 {
let ai = a[i].to_int()
let bi = b[i].to_int()
if ai != bi {
return ai > bi
}
}
a.length() > b.length()
}
///|
/// Encodes the Mapping in canonical I2P order (sorted ascending by UTF-8 key bytes).
pub fn Mapping::encode(
self : Mapping,
w : @encoding.Writer,
) -> Unit raise CommonError {
let sorted : Array[(String, String)] = Array(capacity=self.entries.length())
for entry in self.entries {
sorted.push(entry)
}
// Insertion sort by UTF-8 key bytes (canonical I2P Mapping sort order)
for i = 1; i < sorted.length(); i = i + 1 {
let cur = sorted[i]
let cur_bytes = @encoding.string_to_utf8_bytes(cur.0)
let mut j = i - 1
while j >= 0 &&
bytes_lex_gt(@encoding.string_to_utf8_bytes(sorted[j].0), cur_bytes) {
sorted[j + 1] = sorted[j]
j -= 1
}
sorted[j + 1] = cur
}
let body = @encoding.Writer::new()
for entry in sorted {
body.write_i2p_string(entry.0) catch {
e => raise Encoding(e)
}
body.write_u8(b'\x3d') // '='
body.write_i2p_string(entry.1) catch {
e => raise Encoding(e)
}
body.write_u8(b'\x3b') // ';'
}
let raw = body.to_bytes()
if raw.length() > 65535 {
raise InvalidLength("Mapping exceeds 65535 bytes: \{raw.length()}")
}
w.write_u16_be(raw.length().reinterpret_as_uint())
w.write_bytes(raw)
}
///|
pub fn Mapping::decode(r : @encoding.Reader) -> Mapping raise CommonError {
let byte_len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let raw = r.read_bytes(byte_len) catch { e => raise Encoding(e) }
let mr = @encoding.Reader::new(raw)
let entries : Array[(String, String)] = []
while !mr.is_eof() {
let k = mr.read_i2p_string() catch { e => raise Encoding(e) }
let eq = mr.read_u8() catch { e => raise Encoding(e) }
if eq != b'\x3d' {
raise InvalidFormat("expected '=' in Mapping, got \{eq}")
}
let v = mr.read_i2p_string() catch { e => raise Encoding(e) }
let semi = mr.read_u8() catch { e => raise Encoding(e) }
if semi != b'\x3b' {
raise InvalidFormat("expected ';' in Mapping, got \{semi}")
}
entries.push((k, v))
}
{ entries, }
}