diff --git a/netdb/moon.pkg b/netdb/moon.pkg new file mode 100644 index 0000000..7a3f50a --- /dev/null +++ b/netdb/moon.pkg @@ -0,0 +1,9 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/common", + "experiments/moon_i2p/i2np", +} + +import { + "experiments/moon_i2p/crypto", +} for "test" diff --git a/netdb/netdb.mbt b/netdb/netdb.mbt new file mode 100644 index 0000000..b90d2a9 --- /dev/null +++ b/netdb/netdb.mbt @@ -0,0 +1,400 @@ +///| +/// Pure-MoonBit I2P Network Database (NetDB) & Floodfill Kademlia DHT. + +///| +#derive(Eq, Debug) +pub suberror NetDbError { + Common(@common.CommonError) + InvalidSignature(String) + InvalidRecord(String) +} + +///| +/// Computes the 32-byte Kademlia XOR distance between two I2P hashes. +pub fn xor_distance(a : @common.Hash, b : @common.Hash) -> Bytes { + let ab = a.as_bytes() + let bb = b.as_bytes() + let out = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + out[i] = (ab[i].to_int() ^ bb[i].to_int()).to_byte() + } + Bytes::from_array(out) +} + +///| +/// Lexicographically compares two 32-byte big-endian XOR distances (`-1`, `0`, or `1`). +pub fn compare_distance(d1 : Bytes, d2 : Bytes) -> Int32 { + let len = if d1.length() < d2.length() { d1.length() } else { d2.length() } + for i = 0; i < len; i = i + 1 { + let a = d1[i].to_int() + let b = d2[i].to_int() + if a < b { + return -1 + } + if a > b { + return 1 + } + } + 0 +} + +///| +fn pad2(n : Int64) -> String { + if n < 10L { + "0\{n}" + } else { + "\{n}" + } +} + +///| +fn pad4(n : Int64) -> String { + if n < 10L { + "000\{n}" + } else if n < 100L { + "00\{n}" + } else if n < 1000L { + "0\{n}" + } else { + "\{n}" + } +} + +///| +/// Formats a Unix timestamp (seconds) as UTC `"YYYYMMDD"` for I2P daily routing keys. +/// Uses Howard Hinnant's civil-from-days algorithm. +pub fn format_utc_date(unix_sec : UInt64) -> String { + let z = (unix_sec / 86400UL).reinterpret_as_int64() + 719468L + let era = if z >= 0L { z / 146097L } else { (z - 146096L) / 146097L } + let doe = z - era * 146097L + let yoe = (doe - doe / 1460L + doe / 36524L - doe / 146096L) / 365L + let y = yoe + era * 400L + let doy = doe - (365L * yoe + yoe / 4L - yoe / 100L) + let mp = (5L * doy + 2L) / 153L + let d = doy - (153L * mp + 2L) / 5L + 1L + let m = mp + (if mp < 10L { 3L } else { -9L }) + let year = y + (if m <= 2L { 1L } else { 0L }) + pad4(year) + pad2(m) + pad2(d) +} + +///| +/// Computes the I2P daily Kademlia routing key: `SHA-256(key || ASCII("YYYYMMDD"))`. +pub fn routing_key(key : @common.Hash, utc_yyyymmdd : String) -> @common.Hash { + let date_bytes = @encoding.string_to_utf8_bytes(utc_yyyymmdd) + let kb = key.as_bytes() + let buf = FixedArray::make(kb.length() + date_bytes.length(), b'\x00') + for i = 0; i < kb.length(); i = i + 1 { + buf[i] = kb[i] + } + for i = 0; i < date_bytes.length(); i = i + 1 { + buf[kb.length() + i] = date_bytes[i] + } + @common.Hash::sha256(Bytes::from_array(buf)) +} + +///| +/// Returns `true` if `ri` advertises floodfill capability (`'f'` in `caps`). +pub fn is_floodfill(ri : @common.RouterInfo) -> Bool { + match ri.options.get("caps") { + Some(caps) => caps.contains("f") + None => false + } +} + +///| +/// In-memory I2P NetDB storing verified `RouterInfo` and `LeaseSet2` entries. +pub struct NetDb { + routers : Array[(@common.Hash, @common.RouterInfo)] + leasesets : Array[(@common.Hash, @common.LeaseSet2)] +} + +///| +pub fn NetDb::new() -> NetDb { + { routers: [], leasesets: [], } +} + +///| +pub fn NetDb::router_count(self : NetDb) -> Int32 { + self.routers.length() +} + +///| +pub fn NetDb::leaseset_count(self : NetDb) -> Int32 { + self.leasesets.length() +} + +///| +/// Stores a `RouterInfo` after verifying its Ed25519 signature. +/// Returns `true` if inserted or updated (newer `published` timestamp), `false` if stale. +pub fn NetDb::store_router_info( + self : NetDb, + ri : @common.RouterInfo, +) -> Bool raise NetDbError { + if !ri.verify_signature() { + raise InvalidSignature("RouterInfo Ed25519 signature verification failed") + } + let h = ri.identity.hash() + for i = 0; i < self.routers.length(); i = i + 1 { + if self.routers[i].0 == h { + if ri.published > self.routers[i].1.published { + self.routers[i] = (h, ri) + return true + } + return false + } + } + self.routers.push((h, ri)) + true +} + +///| +/// Stores a `LeaseSet2` after verifying its Ed25519 signature and checking expiration. +/// Returns `true` if inserted or updated, `false` if stale or already expired. +pub fn NetDb::store_lease_set2( + self : NetDb, + ls2 : @common.LeaseSet2, + now_sec : UInt32, +) -> Bool raise NetDbError { + if !ls2.verify_signature() { + raise InvalidSignature("LeaseSet2 Ed25519 signature verification failed") + } + let expires_at = ls2.published_sec + ls2.expires_offset + if expires_at <= now_sec { + return false + } + let h = ls2.destination.hash() + for i = 0; i < self.leasesets.length(); i = i + 1 { + if self.leasesets[i].0 == h { + if ls2.published_sec > self.leasesets[i].1.published_sec { + self.leasesets[i] = (h, ls2) + return true + } + return false + } + } + self.leasesets.push((h, ls2)) + true +} + +///| +pub fn NetDb::get_router_info( + self : NetDb, + hash : @common.Hash, +) -> @common.RouterInfo? { + for entry in self.routers { + if entry.0 == hash { + return Some(entry.1) + } + } + None +} + +///| +pub fn NetDb::get_lease_set2( + self : NetDb, + hash : @common.Hash, + now_sec : UInt32, +) -> @common.LeaseSet2? { + for entry in self.leasesets { + if entry.0 == hash { + if entry.1.published_sec + entry.1.expires_offset > now_sec { + return Some(entry.1) + } + return None + } + } + None +} + +///| +/// Looks up a stored `LeaseSet2` by its `.b32.i2p` address (case-insensitive). +pub fn NetDb::get_lease_set2_by_b32( + self : NetDb, + b32_addr : String, + now_sec : UInt32, +) -> @common.LeaseSet2? { + let target = b32_addr.to_lower() + for entry in self.leasesets { + if entry.1.destination.b32_address() == target { + if entry.1.published_sec + entry.1.expires_offset > now_sec { + return Some(entry.1) + } + return None + } + } + None +} + +///| +/// Removes expired `LeaseSet2` entries and returns the number pruned. +pub fn NetDb::prune_expired(self : NetDb, now_sec : UInt32) -> Int32 { + let mut pruned = 0 + let kept : Array[(@common.Hash, @common.LeaseSet2)] = [] + for entry in self.leasesets { + if entry.1.published_sec + entry.1.expires_offset > now_sec { + kept.push(entry) + } else { + pruned += 1 + } + } + self.leasesets.clear() + for entry in kept { + self.leasesets.push(entry) + } + pruned +} + +///| +fn is_excluded(h : @common.Hash, excluded : Array[@common.Hash]) -> Bool { + for ex in excluded { + if ex == h { + return true + } + } + false +} + +///| +/// Selects up to `limit` routers closest to `routing_key(target_key, utc_yyyymmdd)` +/// by Kademlia XOR distance. If `floodfills_only` is `true`, only floodfill routers +/// (`caps` contains `'f'`) are considered. +pub fn NetDb::closest_peers( + self : NetDb, + target_key : @common.Hash, + utc_yyyymmdd : String, + limit : Int32, + floodfills_only~ : Bool = false, + excluded~ : Array[@common.Hash] = [], +) -> Array[@common.RouterInfo] { + let rkey = routing_key(target_key, utc_yyyymmdd) + let candidates : Array[(Bytes, @common.RouterInfo)] = [] + for entry in self.routers { + let (h, ri) = entry + if floodfills_only && !is_floodfill(ri) { + continue + } + if is_excluded(h, excluded) { + continue + } + candidates.push((xor_distance(h, rkey), ri)) + } + // Insertion sort ascending by XOR distance + for i = 1; i < candidates.length(); i = i + 1 { + let cur = candidates[i] + let mut j = i - 1 + while j >= 0 && compare_distance(candidates[j].0, cur.0) > 0 { + candidates[j + 1] = candidates[j] + j -= 1 + } + candidates[j + 1] = cur + } + let take = if candidates.length() < limit { + candidates.length() + } else { + limit + } + let out : Array[@common.RouterInfo] = Array(capacity=take) + for i = 0; i < take; i = i + 1 { + out.push(candidates[i].1) + } + out +} + +///| +/// Processes an incoming I2NP `DatabaseStore` payload (type 0 = uncompressed RouterInfo, +/// type 3 = LeaseSet2). Returns `true` if stored/updated. +pub fn NetDb::handle_database_store( + self : NetDb, + store_type : Byte, + key : @common.Hash, + data : Bytes, + now_sec : UInt32, +) -> Bool raise NetDbError { + match store_type.to_int() & 0x0F { + 0 => { + // Uncompressed RouterInfo (if gzipped with 2-byte len prefix, caller decompresses first) + let ri = @common.RouterInfo::decode(@encoding.Reader::new(data)) catch { + e => raise Common(e) + } + if ri.identity.hash() != key { + raise InvalidRecord( + "DatabaseStore key does not match RouterIdentity hash", + ) + } + self.store_router_info(ri) + } + 3 => { + let ls2 = @common.LeaseSet2::decode(@encoding.Reader::new(data)) catch { + e => raise Common(e) + } + if ls2.destination.hash() != key { + raise InvalidRecord("DatabaseStore key does not match Destination hash") + } + self.store_lease_set2(ls2, now_sec) + } + t => raise InvalidRecord("unsupported DatabaseStore type: \{t}") + } +} + +///| +/// Handles an incoming I2NP `DatabaseLookup` request and produces either a +/// `DatabaseStore` (if found locally) or a `DatabaseSearchReply` containing the +/// closest floodfill/router hashes by daily Kademlia XOR routing distance. +pub fn NetDb::handle_database_lookup( + self : NetDb, + local_router_hash : @common.Hash, + key : @common.Hash, + flags : Byte, + excluded_peers : Array[@common.Hash], + now_sec : UInt32, + max_peers~ : Int32 = 3, +) -> @i2np.I2npPayload raise NetDbError { + let lookup_type = (flags.to_int() >> 2) & 0x03 + // 0 = normal (any), 1 = LeaseSet, 2 = RouterInfo, 3 = exploration + if lookup_type == 0 || lookup_type == 1 { + match self.get_lease_set2(key, now_sec) { + Some(ls2) => { + let raw = ls2.to_bytes() catch { e => raise Common(e) } + return DatabaseStore( + key~, + store_type=b'\x03', + reply_token=0U, + reply_tunnel_id=0U, + reply_gateway=None, + data=raw, + ) + } + None => () + } + } + if lookup_type == 0 || lookup_type == 2 { + match self.get_router_info(key) { + Some(ri) => { + let raw = ri.to_bytes() catch { e => raise Common(e) } + return DatabaseStore( + key~, + store_type=b'\x00', + reply_token=0U, + reply_tunnel_id=0U, + reply_gateway=None, + data=raw, + ) + } + None => () + } + } + let utc_date = format_utc_date(now_sec.to_uint64()) + let floodfills_only = lookup_type != 3 + let closest = self.closest_peers( + key, + utc_date, + max_peers, + floodfills_only~, + excluded=excluded_peers, + ) + let hashes : Array[@common.Hash] = Array(capacity=closest.length()) + for ri in closest { + hashes.push(ri.identity.hash()) + } + DatabaseSearchReply(key~, peer_hashes=hashes, from=local_router_hash) +} diff --git a/netdb/netdb_test.mbt b/netdb/netdb_test.mbt new file mode 100644 index 0000000..cb07a94 --- /dev/null +++ b/netdb/netdb_test.mbt @@ -0,0 +1,153 @@ +///| +fn make_signed_router( + seed_byte : Byte, + caps : String, + published : UInt64, +) -> @common.RouterInfo { + let ed_seed = Bytes::make(32, seed_byte) + let ed_pub = try! @crypto.ed25519_public_key(ed_seed) + let x_priv = Bytes::make(32, (seed_byte.to_int() ^ 0x55).to_byte()) + let x_pub = try! @crypto.x25519_public_key(x_priv) + let id = try! @common.RouterIdentity::new_x25519_ed25519(x_pub, ed_pub) + let ri : @common.RouterInfo = { + identity: id, + published, + addresses: [], + options: @common.Mapping::from_entries([ + ("caps", caps), + ("netId", "2"), + ("router.version", "0.9.64"), + ]), + signature: b"", + } + try! ri.sign_ed25519(ed_seed) +} + +///| +test "daily routing key derivation and UTC date formatting" { + assert_eq(@netdb.format_utc_date(0UL), "19700101") + assert_eq(@netdb.format_utc_date(1709164800UL), "20240229") // leap day + assert_eq(@netdb.format_utc_date(1700000000UL), "20231114") + + // Known-answer check: routing_key(key, "20240229") == SHA-256(key || "20240229") + let key = @common.Hash::sha256(b"test-destination-key") + let rk = @netdb.routing_key(key, "20240229") + let expected_in = FixedArray::make(40, b'\x00') + let kb = key.as_bytes() + let db = b"20240229" + for i = 0; i < 32; i = i + 1 { + expected_in[i] = kb[i] + } + for i = 0; i < 8; i = i + 1 { + expected_in[32 + i] = db[i] + } + assert_eq(rk, @common.Hash::sha256(Bytes::from_array(expected_in))) + // Different day produces a different routing key + assert_true(rk != @netdb.routing_key(key, "20240301")) +} + +///| +test "NetDB Kademlia XOR distance, floodfill selection, and DatabaseLookup" { + let db = @netdb.NetDb::new() + let r1 = make_signed_router(b'\x01', "XfR", 1700000000000UL) // floodfill + let r2 = make_signed_router(b'\x02', "LR", 1700000000000UL) // non-floodfill + let r3 = make_signed_router(b'\x03', "OfR", 1700000000000UL) // floodfill + let r4 = make_signed_router(b'\x04', "XfR", 1700000000000UL) // floodfill + + assert_eq(@netdb.is_floodfill(r1), true) + assert_eq(@netdb.is_floodfill(r2), false) + assert_eq(db.store_router_info(r1), true) + assert_eq(db.store_router_info(r2), true) + assert_eq(db.store_router_info(r3), true) + assert_eq(db.store_router_info(r4), true) + assert_eq(db.router_count(), 4) + + // Stale RouterInfo update is rejected (returns false) + assert_eq(db.store_router_info(r1), false) + // Newer RouterInfo update is accepted + let r1_newer = make_signed_router(b'\x01', "XfR", 1700000005000UL) + assert_eq(db.store_router_info(r1_newer), true) + + // Closest floodfills excludes r2 (non-floodfill) and orders ascending by XOR distance + let target = @common.Hash::sha256(b"lookup-target") + let ffs = db.closest_peers(target, "20231114", 3, floodfills_only=true) + assert_eq(ffs.length(), 3) + let rkey = @netdb.routing_key(target, "20231114") + let d0 = @netdb.xor_distance(ffs[0].identity.hash(), rkey) + let d1 = @netdb.xor_distance(ffs[1].identity.hash(), rkey) + let d2 = @netdb.xor_distance(ffs[2].identity.hash(), rkey) + assert_true(@netdb.compare_distance(d0, d1) <= 0) + assert_true(@netdb.compare_distance(d1, d2) <= 0) + + // DatabaseLookup for known RouterInfo returns DatabaseStore + let local_h = r1.identity.hash() + let hit = db.handle_database_lookup( + local_h, + r3.identity.hash(), + b'\x08', + [], + 1700000010U, + ) + match hit { + DatabaseStore(key~, store_type~, ..) => { + assert_eq(key, r3.identity.hash()) + assert_eq(store_type, b'\x00') + } + _ => fail("expected DatabaseStore hit") + } + + // DatabaseLookup for unknown key returns DatabaseSearchReply with closest floodfills + let miss = db.handle_database_lookup( + local_h, + target, + b'\x08', + [ffs[0].identity.hash()], + 1700000010U, + max_peers=2, + ) + match miss { + DatabaseSearchReply(key~, peer_hashes~, from~) => { + assert_eq(key, target) + assert_eq(from, local_h) + assert_eq(peer_hashes.length(), 2) + assert_true(peer_hashes[0] != ffs[0].identity.hash()) + } + _ => fail("expected DatabaseSearchReply") + } +} + +///| +test "NetDB LeaseSet2 store, .b32.i2p lookup, and expiration pruning" { + let db = @netdb.NetDb::new() + let ed_seed = Bytes::make(32, b'\x77') + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let x_pub = @crypto.x25519_public_key(Bytes::make(32, b'\x88')) + let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub) + let ls2 : @common.LeaseSet2 = { + destination: dest, + published_sec: 1700000000U, + expires_offset: 300U, + flags: 0U, + options: @common.Mapping::new(), + encryption_keys: [{ key_type: X25519, key_data: x_pub, }], + leases: [ + { + tunnel_gw: @common.Hash::sha256(b"gw"), + tunnel_id: 101U, + end_date_sec: 1700000300U, + }, + ], + signature: b"", + } + let signed = ls2.sign_ed25519(ed_seed) + assert_eq(db.store_lease_set2(signed, 1700000010U), true) + assert_eq(db.leaseset_count(), 1) + assert_eq( + db.get_lease_set2_by_b32(dest.b32_address(), 1700000100U), + Some(signed), + ) + // After expiration (1700000300), lookup returns None and prune removes it + assert_eq(db.get_lease_set2(dest.hash(), 1700000301U), None) + assert_eq(db.prune_expired(1700000301U), 1) + assert_eq(db.leaseset_count(), 0) +} diff --git a/netdb/pkg.generated.mbti b/netdb/pkg.generated.mbti new file mode 100644 index 0000000..c77d065 --- /dev/null +++ b/netdb/pkg.generated.mbti @@ -0,0 +1,49 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/netdb" + +import { + "experiments/moon_i2p/common", + "experiments/moon_i2p/i2np", + "moonbitlang/core/debug", +} + +// Values +pub fn compare_distance(Bytes, Bytes) -> Int32 + +pub fn format_utc_date(UInt64) -> String + +pub fn is_floodfill(@common.RouterInfo) -> Bool + +pub fn routing_key(@common.Hash, String) -> @common.Hash + +pub fn xor_distance(@common.Hash, @common.Hash) -> Bytes + +// Errors +#derive(Eq, @debug.Debug) +pub suberror NetDbError { + Common(@common.CommonError) + InvalidSignature(String) + InvalidRecord(String) +} + +// Types and methods +pub struct NetDb { + routers : Array[(@common.Hash, @common.RouterInfo)] + leasesets : Array[(@common.Hash, @common.LeaseSet2)] +} +pub fn NetDb::closest_peers(Self, @common.Hash, String, Int32, floodfills_only? : Bool, excluded? : Array[@common.Hash]) -> Array[@common.RouterInfo] +pub fn NetDb::get_lease_set2(Self, @common.Hash, UInt32) -> @common.LeaseSet2? +pub fn NetDb::get_lease_set2_by_b32(Self, String, UInt32) -> @common.LeaseSet2? +pub fn NetDb::get_router_info(Self, @common.Hash) -> @common.RouterInfo? +pub fn NetDb::handle_database_lookup(Self, @common.Hash, @common.Hash, Byte, Array[@common.Hash], UInt32, max_peers? : Int32) -> @i2np.I2npPayload raise NetDbError +pub fn NetDb::handle_database_store(Self, Byte, @common.Hash, Bytes, UInt32) -> Bool raise NetDbError +pub fn NetDb::leaseset_count(Self) -> Int32 +pub fn NetDb::new() -> Self +pub fn NetDb::prune_expired(Self, UInt32) -> Int32 +pub fn NetDb::router_count(Self) -> Int32 +pub fn NetDb::store_lease_set2(Self, @common.LeaseSet2, UInt32) -> Bool raise NetDbError +pub fn NetDb::store_router_info(Self, @common.RouterInfo) -> Bool raise NetDbError + +// Type aliases + +// Traits