feat: add pure-MoonBit NetDB and Floodfill Kademlia DHT

This commit is contained in:
nandi committed 2026-11-27 19:43:47 +00:00
1 parent e6d1c464dd
commit 4993741355
4 files changed
+611

No files matched your search

+400
View File
@@ -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)
}