///| /// Canonical Pure-MoonBit I2P BitTorrent DHT (BEP 5 adapted per I2P DHT specification): /// - Secure Node IDs: first 4B = dest_hash[0..4], next 2B = dest_hash[4..6] ^ port_be16 /// - 54-byte compact nodes: 20B node_id || 32B dest_hash || 2B port_be16 /// - KRPC query/response/error codec & routing table with Kademlia XOR distance ///| /// Builds a Secure I2P DHT 20-byte Node ID bound to `dest_hash` and `query_port`. pub fn make_i2p_dht_node_id( dest_hash : @common.Hash, query_port : UInt32, rand14 : Bytes, ) -> Bytes raise BtError { if rand14.length() < 14 { raise InvalidKrpc("rand14 must be at least 14 bytes") } let hb = dest_hash.as_bytes() let out = FixedArray::make(20, b'\x00') out[0] = hb[0] out[1] = hb[1] out[2] = hb[2] out[3] = hb[3] out[4] = (hb[4].to_int() ^ ((query_port.reinterpret_as_int() >> 8) & 0xFF)).to_byte() out[5] = (hb[5].to_int() ^ (query_port.reinterpret_as_int() & 0xFF)).to_byte() for i = 0; i < 14; i = i + 1 { out[6 + i] = rand14[i] } Bytes::from_array(out) } ///| /// Verifies that `node_id` (20B) satisfies I2P DHT Secure Node ID rules for `(dest_hash, query_port)`. pub fn verify_i2p_dht_node_id( node_id : Bytes, dest_hash : @common.Hash, query_port : UInt32, ) -> Bool { if node_id.length() != 20 { return false } let hb = dest_hash.as_bytes() let p_hi = (query_port.reinterpret_as_int() >> 8) & 0xFF let p_lo = query_port.reinterpret_as_int() & 0xFF node_id[0] == hb[0] && node_id[1] == hb[1] && node_id[2] == hb[2] && node_id[3] == hb[3] && node_id[4] == (hb[4].to_int() ^ p_hi).to_byte() && node_id[5] == (hb[5].to_int() ^ p_lo).to_byte() } ///| #derive(Eq, Debug) pub(all) struct DhtNode { node_id : Bytes // 20B dest_hash : @common.Hash port : UInt32 last_seen_ms : UInt64 } ///| /// Encodes DHT nodes in canonical 54-byte I2P compact format (`20B id || 32B dest_hash || 2B port_be16`). pub fn encode_compact_nodes(nodes : Array[DhtNode]) -> Bytes { let w = @encoding.Writer::new(capacity=nodes.length() * 54) for n in nodes { if n.node_id.length() == 20 { w.write_bytes(n.node_id) w.write_bytes(n.dest_hash.as_bytes()) w.write_u16_be(n.port) } } w.to_bytes() } ///| /// Decodes canonical 54-byte compact I2P DHT nodes (`nodes` dictionary field). pub fn decode_compact_nodes( blob : Bytes, now_ms~ : UInt64 = 0UL, ) -> Array[DhtNode] raise BtError { if blob.length() % 54 != 0 { raise InvalidKrpc( "compact I2P DHT nodes length must be a multiple of 54, got \{blob.length()}", ) } let count = blob.length() / 54 let out : Array[DhtNode] = Array(capacity=count) for i = 0; i < count; i = i + 1 { let off = i * 54 let node_id = blob[off:off + 20].to_owned() let dh = @common.Hash::from_bytes(blob[off + 20:off + 52].to_owned()) catch { e => raise Common(e) } let port = ((blob[off + 52].to_int() << 8) | blob[off + 53].to_int()).reinterpret_as_uint() if port > 0U { out.push({ node_id, dest_hash: dh, port, last_seen_ms: now_ms, }) } } out } ///| /// Computes 20-byte Kademlia XOR distance between `a` and `b`. pub fn xor_distance_20(a : Bytes, b : Bytes) -> Bytes { let out = FixedArray::make(20, b'\x00') let n = if a.length() < b.length() { a.length() } else { b.length() } let len = if n < 20 { n } else { 20 } for i = 0; i < len; i = i + 1 { out[i] = (a[i].to_int() ^ b[i].to_int()).to_byte() } Bytes::from_array(out) } ///| pub fn cmp_distance_20(a : Bytes, b : Bytes) -> Int32 { cmp_bytes_lex(a, b) } ///| #derive(Eq, Debug) pub(all) enum KrpcQueryKind { Ping FindNode(target~ : Bytes) GetPeers(info_hash~ : Bytes) AnnouncePeer( info_hash~ : Bytes, port~ : UInt32, token~ : Bytes, implied_port~ : Bool ) } ///| #derive(Eq, Debug) pub(all) enum KrpcMessage { Query(tx_id~ : Bytes, sender_id~ : Bytes, kind~ : KrpcQueryKind) Response( tx_id~ : Bytes, sender_id~ : Bytes, nodes~ : Bytes, values~ : Array[Bytes], token~ : Bytes? ) ErrorMsg(tx_id~ : Bytes, code~ : Int64, msg~ : String) } ///| /// Encodes a KRPC message into Bencode bytes. pub fn encode_krpc(msg : KrpcMessage) -> Bytes { match msg { Query(tx_id~, sender_id~, kind~) => match kind { Ping => bencode_encode( BDict([ (b"a", BDict([(b"id", BBytes(sender_id))])), (b"q", BBytes(b"ping")), (b"t", BBytes(tx_id)), (b"y", BBytes(b"q")), ]), ) FindNode(target~) => bencode_encode( BDict([ ( b"a", BDict([(b"id", BBytes(sender_id)), (b"target", BBytes(target))]), ), (b"q", BBytes(b"find_node")), (b"t", BBytes(tx_id)), (b"y", BBytes(b"q")), ]), ) GetPeers(info_hash~) => bencode_encode( BDict([ ( b"a", BDict([ (b"id", BBytes(sender_id)), (b"info_hash", BBytes(info_hash)), ]), ), (b"q", BBytes(b"get_peers")), (b"t", BBytes(tx_id)), (b"y", BBytes(b"q")), ]), ) AnnouncePeer(info_hash~, port~, token~, implied_port~) => { let args : Array[(Bytes, BVal)] = [ (b"id", BBytes(sender_id)), (b"info_hash", BBytes(info_hash)), (b"port", BInt(port.to_int64())), (b"token", BBytes(token)), ] if implied_port { args.push((b"implied_port", BInt(1L))) } bencode_encode( BDict([ (b"a", BDict(args)), (b"q", BBytes(b"announce_peer")), (b"t", BBytes(tx_id)), (b"y", BBytes(b"q")), ]), ) } } Response(tx_id~, sender_id~, nodes~, values~, token~) => { let r_entries : Array[(Bytes, BVal)] = [(b"id", BBytes(sender_id))] if nodes.length() > 0 { r_entries.push((b"nodes", BBytes(nodes))) } if values.length() > 0 { let vlist : Array[BVal] = Array(capacity=values.length()) for v in values { vlist.push(BBytes(v)) } r_entries.push((b"values", BList(vlist))) } match token { Some(tk) => r_entries.push((b"token", BBytes(tk))) None => () } bencode_encode( BDict([ (b"r", BDict(r_entries)), (b"t", BBytes(tx_id)), (b"y", BBytes(b"r")), ]), ) } ErrorMsg(tx_id~, code~, msg~) => bencode_encode( BDict([ ( b"e", BList([BInt(code), BBytes(@encoding.string_to_utf8_bytes(msg))]), ), (b"t", BBytes(tx_id)), (b"y", BBytes(b"e")), ]), ) } } ///| /// Decodes a Bencoded KRPC packet. pub fn decode_krpc(data : Bytes) -> KrpcMessage raise BtError { let root = bencode_decode(data) let tx_id = match bdict_get_bytes(root, "t") { Some(t) => t None => raise InvalidKrpc("KRPC packet missing 't' transaction id") } let y = match bdict_get_string(root, "y") { Some(yv) => yv None => raise InvalidKrpc("KRPC packet missing 'y' message type") } if y == "q" { let q = match bdict_get_string(root, "q") { Some(qv) => qv None => raise InvalidKrpc("KRPC query missing 'q'") } let a = match bdict_get(root, "a") { Some(av) => av None => raise InvalidKrpc("KRPC query missing 'a'") } let sender_id = match bdict_get_bytes(a, "id") { Some(id) if id.length() == 20 => id _ => raise InvalidKrpc("KRPC query missing valid 20B 'id'") } if q == "ping" { return Query(tx_id~, sender_id~, kind=Ping) } if q == "find_node" { let target = match bdict_get_bytes(a, "target") { Some(t) if t.length() == 20 => t _ => raise InvalidKrpc("find_node missing valid 20B 'target'") } return Query(tx_id~, sender_id~, kind=FindNode(target~)) } if q == "get_peers" { let info_hash = match bdict_get_bytes(a, "info_hash") { Some(ih) if ih.length() == 20 => ih _ => raise InvalidKrpc("get_peers missing valid 20B 'info_hash'") } return Query(tx_id~, sender_id~, kind=GetPeers(info_hash~)) } if q == "announce_peer" { let info_hash = match bdict_get_bytes(a, "info_hash") { Some(ih) if ih.length() == 20 => ih _ => raise InvalidKrpc("announce_peer missing valid 20B 'info_hash'") } let port = match bdict_get_int(a, "port") { Some(p) if p > 0L && p <= 65535L => p.to_int().reinterpret_as_uint() _ => 6881U } let implied = match bdict_get_int(a, "implied_port") { Some(v) => v != 0L None => false } let token = match bdict_get_bytes(a, "token") { Some(tk) => tk None => raise InvalidKrpc("announce_peer missing 'token'") } return Query( tx_id~, sender_id~, kind=AnnouncePeer(info_hash~, port~, token~, implied_port=implied), ) } raise InvalidKrpc("unsupported KRPC query '\{q}'") } if y == "r" { let r = match bdict_get(root, "r") { Some(rv) => rv None => raise InvalidKrpc("KRPC response missing 'r'") } let sender_id = match bdict_get_bytes(r, "id") { Some(id) if id.length() == 20 => id _ => raise InvalidKrpc("KRPC response missing valid 20B 'id'") } let nodes = match bdict_get_bytes(r, "nodes") { Some(n) => n None => b"" } let values : Array[Bytes] = [] match bdict_get(r, "values") { Some(BList(vlist)) => for item in vlist { match item { BBytes(vb) => values.push(vb) _ => () } } _ => () } let token = bdict_get_bytes(r, "token") return Response(tx_id~, sender_id~, nodes~, values~, token~) } if y == "e" { match bdict_get(root, "e") { Some(BList(elist)) if elist.length() >= 2 => { let code = match elist[0] { BInt(c) => c _ => 201L } let msg = match elist[1] { BBytes(mb) => @encoding.utf8_bytes_to_string(mb) catch { _ => "krpc error" } _ => "krpc error" } return ErrorMsg(tx_id~, code~, msg~) } _ => return ErrorMsg(tx_id~, code=201L, msg="malformed krpc error") } } raise InvalidKrpc("unknown KRPC message type '\{y}'") } ///| #derive(Eq, Debug) pub(all) struct DhtPendingTx { tx_id : Bytes kind : String // "ping" | "find_node" | "get_peers" | "announce_peer" info_hash : Bytes? dest_hash : @common.Hash port : UInt32 sent_ms : UInt64 } ///| priv struct DhtPeerEntry { peer_hash : @common.Hash expires_ms : UInt64 } ///| /// Pure-MoonBit I2P Kademlia DHT state machine (routing table, token secret, peer store). pub struct I2pDht { local_id : Bytes // 20B Secure I2P Node ID local_dest_hash : @common.Hash query_port : UInt32 reply_port : UInt32 priv secret : Bytes nodes : Array[DhtNode] pending_txs : Array[DhtPendingTx] priv peer_store : Array[(Bytes, Array[DhtPeerEntry])] // (info_hash_20B, peers) mut next_tx_seq : UInt32 mut queries_sent : UInt64 mut responses_recv : UInt64 mut queries_recv : UInt64 mut peers_discovered : UInt64 } ///| pub fn I2pDht::new( local_dest_hash : @common.Hash, rand14 : Bytes, secret : Bytes, query_port~ : UInt32 = 6881U, reply_port~ : UInt32 = 6882U, ) -> I2pDht raise BtError { let local_id = make_i2p_dht_node_id(local_dest_hash, query_port, rand14) { local_id, local_dest_hash, query_port, reply_port, secret, nodes: [], pending_txs: [], peer_store: [], next_tx_seq: 1U, queries_sent: 0UL, responses_recv: 0UL, queries_recv: 0UL, peers_discovered: 0UL, } } ///| pub fn I2pDht::alloc_tx_id(self : I2pDht) -> Bytes { let id = self.next_tx_seq self.next_tx_seq = id + 1U let w = @encoding.Writer::new(capacity=4) w.write_u32_be(id) w.to_bytes() } ///| pub fn I2pDht::register_pending_tx( self : I2pDht, tx_id : Bytes, kind : String, dest_hash : @common.Hash, port : UInt32, sent_ms : UInt64, info_hash~ : Bytes? = None, ) -> Unit { while self.pending_txs.length() >= 256 { let _ = self.pending_txs.remove(0) } self.pending_txs.push({ tx_id, kind, info_hash, dest_hash, port, sent_ms, }) self.queries_sent += 1UL } ///| pub fn I2pDht::take_pending_tx(self : I2pDht, tx_id : Bytes) -> DhtPendingTx? { for i = 0; i < self.pending_txs.length(); i = i + 1 { if @crypto.ct_eq(self.pending_txs[i].tx_id, tx_id) { self.responses_recv += 1UL return Some(self.pending_txs.remove(i)) } } None } ///| pub fn I2pDht::record_query_recv(self : I2pDht) -> Unit { self.queries_recv += 1UL } ///| pub fn I2pDht::record_peers_discovered(self : I2pDht, count : UInt64) -> Unit { self.peers_discovered += count } ///| pub fn I2pDht::prune_expired_txs(self : I2pDht, now_ms : UInt64) -> Unit { let mut i = 0 while i < self.pending_txs.length() { if now_ms > self.pending_txs[i].sent_ms + 30000UL { let _ = self.pending_txs.remove(i) } else { i += 1 } } } ///| /// Inserts or refreshes a remote DHT node, enforcing Secure I2P Node ID verification by default. pub fn I2pDht::upsert_node( self : I2pDht, node_id : Bytes, dest_hash : @common.Hash, port : UInt32, now_ms : UInt64, verify_secure_id~ : Bool = true, ) -> Bool { if node_id.length() != 20 || port == 0U { return false } if dest_hash == self.local_dest_hash { return false } if verify_secure_id && !verify_i2p_dht_node_id(node_id, dest_hash, port) { return false } for i = 0; i < self.nodes.length(); i = i + 1 { if self.nodes[i].dest_hash == dest_hash && self.nodes[i].port == port { self.nodes[i] = { node_id, dest_hash, port, last_seen_ms: now_ms, } return true } } if self.nodes.length() >= 160 { // Evict oldest seen node outside top close neighborhood let mut oldest_idx = 0 let mut oldest_ms = self.nodes[0].last_seen_ms for i = 1; i < self.nodes.length(); i = i + 1 { if self.nodes[i].last_seen_ms < oldest_ms { oldest_ms = self.nodes[i].last_seen_ms oldest_idx = i } } let _ = self.nodes.remove(oldest_idx) } self.nodes.push({ node_id, dest_hash, port, last_seen_ms: now_ms, }) true } ///| /// Returns up to `limit` known DHT nodes sorted closest by 20-byte XOR distance to `target_20`. pub fn I2pDht::closest_nodes( self : I2pDht, target_20 : Bytes, limit~ : Int32 = 8, ) -> Array[DhtNode] { let pairs : Array[(Bytes, DhtNode)] = Array(capacity=self.nodes.length()) for n in self.nodes { pairs.push((xor_distance_20(n.node_id, target_20), n)) } pairs.sort_by(fn(a, b) { cmp_distance_20(a.0, b.0) }) let out : Array[DhtNode] = [] let cap = if limit < pairs.length() { limit } else { pairs.length() } for i = 0; i < cap; i = i + 1 { out.push(pairs[i].1) } out } ///| pub fn I2pDht::make_token(self : I2pDht, sender_hash : @common.Hash) -> Bytes { let w = @encoding.Writer::new(capacity=self.secret.length() + 32) w.write_bytes(self.secret) w.write_bytes(sender_hash.as_bytes()) @crypto.sha256(w.to_bytes())[:8].to_owned() } ///| pub fn I2pDht::verify_token( self : I2pDht, sender_hash : @common.Hash, token : Bytes, ) -> Bool { @crypto.ct_eq(self.make_token(sender_hash), token) } ///| pub fn I2pDht::store_peer( self : I2pDht, info_hash : Bytes, peer_hash : @common.Hash, now_ms : UInt64, ) -> Unit { if info_hash.length() != 20 { return } let expires_ms = now_ms + 1800000UL // 30 minutes for entry in self.peer_store { if @crypto.ct_eq(entry.0, info_hash) { let mut updated = false for j = 0; j < entry.1.length(); j = j + 1 { if entry.1[j].peer_hash == peer_hash { entry.1[j] = { peer_hash, expires_ms, } updated = true break } } if !updated { while entry.1.length() >= 64 { let _ = entry.1.remove(0) } entry.1.push({ peer_hash, expires_ms, }) } return } } while self.peer_store.length() >= 128 { let _ = self.peer_store.remove(0) } self.peer_store.push((info_hash, [{ peer_hash, expires_ms, }])) } ///| pub fn I2pDht::get_peers_local( self : I2pDht, info_hash : Bytes, now_ms : UInt64, ) -> Array[@common.Hash] { let out : Array[@common.Hash] = [] for entry in self.peer_store { if @crypto.ct_eq(entry.0, info_hash) { let mut j = 0 while j < entry.1.length() { if entry.1[j].expires_ms <= now_ms { let _ = entry.1.remove(j) } else { out.push(entry.1[j].peer_hash) j += 1 } } break } } out }