///| /// Native MoonBit I2P Router Core with transient/persistent SAM sessions, NetDB floodfill /// protocol, Proposal 157 multi-hop TunnelManager, non-blocking NTCP2 peer pool, /// Proposal 144 ECIES-X25519-AEAD-Ratchet Garlic, and Ed25519 I2P Streaming. ///| #derive(Eq, Debug) pub suberror RouterError { Net(@ntcp2_net.Ntcp2NetError) Crypto(@crypto.CryptoError) Common(@common.CommonError) Noise(@noise.NoiseError) NetDb(@netdb.NetDbError) I2np(@i2np.I2npError) Tunnel(@tunnel.TunnelError) Protocol(String) } ///| /// Configuration for `Router::start`. pub(all) struct RouterConfig { sam_host : String sam_port : Int32 ntcp2_host : String ntcp2_port : Int32 } ///| pub fn RouterConfig::default() -> RouterConfig { { sam_host: "127.0.0.1", sam_port: 7656, ntcp2_host: "127.0.0.1", ntcp2_port: 0, } } ///| /// Live MoonBit I2P Router Core instance. pub struct Router { ed_seed : Bytes static_key : @noise.KeyPair ntcp2_iv : Bytes router_info : @common.RouterInfo netdb : @netdb.NetDb tunnels : @tunnel.TunnelManager ntcp2_listener : @ntcp2_net.TcpListener sam_listener : @ntcp2_net.TcpListener check_clock_skew : Bool public_mode : Bool tunnel_hops : Int32 debug : Bool priv mut next_msg_id : UInt32 priv mut next_tunnel_id : UInt32 priv mut next_stream_id : UInt32 priv replay_cache : @ntcp2.EphemeralReplayCache priv pending_accepts : Array[@ntcp2_net.PendingNtcp2Accept] priv pending_dials : Array[PendingPeerDial] priv peers : Array[PeerSession] priv pending_sends : Array[PendingPeerSend] priv pending_lookups : Array[PendingNetDbLookup] priv pending_builds : Array[PendingTunnelBuild] priv reassembler : @tunnel.FragmentReassembler priv sessions : Array[SamSession] priv sam_clients : Array[SamClientConn] priv bridges : Array[StreamBridge] priv remote_bridges : Array[RemoteStreamBridge] priv aliases : Array[(String, String)] // hostname -> pub_b64 priv b32_aliases : Array[(String, String)] // hostname -> lowercase <52>.b32.i2p priv failed_peers : Array[(@common.Hash, UInt64)] // (router_hash, retry_after_ms) priv ratchet_resets : Array[(@common.Hash, UInt64)] // (peer_hash, last_reset_ms) priv mut http_proxy_listener : @ntcp2_net.TcpListener? priv http_proxy_conns : Array[HttpProxyConn] priv mut http_proxy_session_id : String? priv mut torrent_engine : TorrentEngine? priv mut torrent_api_listener : @ntcp2_net.TcpListener? priv torrent_api_conns : Array[TorrentApiConn] priv mut lease_rr : Int32 priv mut outbound_rr : Int32 priv mut last_bootstrap_ms : UInt64 priv mut last_explore_ms : UInt64 } ///| fn u32_from_be_prefix(b : Bytes) -> UInt32 { ( (b[0].to_uint() << 24) | (b[1].to_uint() << 16) | (b[2].to_uint() << 8) | b[3].to_uint() ) & 0x7FFFFFFFU } ///| fn Router::alloc_msg_id(self : Router) -> UInt32 { let mut id = self.next_msg_id if id == 0U { id = 1U } self.next_msg_id = id + 1U id } ///| fn Router::alloc_tunnel_id(self : Router) -> UInt32 { let mut id = self.next_tunnel_id if id == 0U { id = 1U } self.next_tunnel_id = id + 1U id } ///| fn Router::alloc_stream_id(self : Router) -> UInt32 { let mut id = self.next_stream_id if id == 0U { id = 1U } self.next_stream_id = id + 1U id } ///| fn next_rand_32() -> Bytes { @ntcp2_net.random_bytes(32) catch { _ => Bytes::make(32, b'\x42') } } ///| fn non_zero_random_bytes(n : Int32) -> Bytes { let raw = @ntcp2_net.random_bytes(n) catch { _ => return Bytes::make(n, b'\x01') } let out = FixedArray::make(n, b'\x01') for i = 0; i < raw.length(); i = i + 1 { out[i] = if raw[i] == b'\x00' { b'\x01' } else { raw[i] } } Bytes::from_array(out) } ///| /// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`, /// NTCP2 TCP listener, and embedded SAMv3 TCP bridge. /// In `public_mode` with loopback/unspecified `ntcp2_host`, advertises an unpublished /// firewalled `LU` RouterInfo (required for outbound NTCP2 to live public routers behind NAT). pub fn Router::start( config : RouterConfig, floodfill~ : Bool = false, check_clock_skew~ : Bool = true, public_mode~ : Bool = false, tunnel_hops~ : Int32 = 1, debug~ : Bool = false, ) -> Router raise RouterError { let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } let ed_pub = @crypto.ed25519_public_key(ed_seed) catch { e => raise Crypto(e) } let static_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } let static_key = @noise.KeyPair::from_private(static_priv) catch { e => raise Noise(e) } let ntcp2_iv = @ntcp2_net.random_bytes(16) catch { e => raise Net(e) } let id_pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) } let ntcp2_listener = @ntcp2_net.TcpListener::bind( config.ntcp2_host, config.ntcp2_port, ) catch { e => raise Net(e) } let sam_listener = @ntcp2_net.TcpListener::bind( config.sam_host, config.sam_port, ) catch { e => { ntcp2_listener.close() raise Net(e) } } let id = @common.RouterIdentity::new_x25519_ed25519( static_key.public_key, ed_pub, padding=id_pad, ) catch { e => raise Common(e) } let is_firewalled = public_mode && (config.ntcp2_host == "127.0.0.1" || config.ntcp2_host == "0.0.0.0") let addr_opts = if is_firewalled { @common.Mapping::from_entries([ ("caps", "4"), ("s", @encoding.base64_encode(static_key.public_key)), ("v", "2"), ]) } else { @common.Mapping::from_entries([ ("caps", "4"), ("host", config.ntcp2_host), ("i", @encoding.base64_encode(ntcp2_iv)), ("port", "\{ntcp2_listener.local_port()}"), ("s", @encoding.base64_encode(static_key.public_key)), ("v", "2"), ]) } let addr_cost : Byte = if is_firewalled { b'\x0e' } else { b'\x03' } let caps = if floodfill { "LRf" } else if is_firewalled { "LU" } else { "LR" } let ri : @common.RouterInfo = { identity: id, published: @ntcp2_net.unix_time_ms(), addresses: [@common.RouterAddress::new(addr_cost, "NTCP2", addr_opts)], options: @common.Mapping::from_entries([ ("caps", caps), ("netId", "2"), ("router.version", "0.9.64"), ]), signature: b"", } let signed_ri = ri.sign_ed25519(ed_seed) catch { e => raise Common(e) } let netdb = @netdb.NetDb::new() let _ = netdb.store_router_info(signed_ri) catch { e => raise NetDb(e) } let rseed = @ntcp2_net.random_bytes(12) catch { _ => Bytes::make(12, b'\x01') } let m0 = u32_from_be_prefix(rseed[:4].to_owned()) | 1U let t0 = u32_from_be_prefix(rseed[4:8].to_owned()) % 0x0FFFFFFFU + 10000U let s0 = u32_from_be_prefix(rseed[8:12].to_owned()) % 0x0FFFFFFFU + 100U let clamped_hops = if tunnel_hops < 1 { 1 } else if tunnel_hops > 4 { 4 } else { tunnel_hops } let r : Router = { ed_seed, static_key, ntcp2_iv, router_info: signed_ri, netdb, tunnels: @tunnel.TunnelManager::new(), ntcp2_listener, sam_listener, check_clock_skew, public_mode, tunnel_hops: clamped_hops, debug, next_msg_id: m0, next_tunnel_id: t0, next_stream_id: s0, replay_cache: @ntcp2.EphemeralReplayCache::new(max_entries=1024), pending_accepts: [], pending_dials: [], peers: [], pending_sends: [], pending_lookups: [], pending_builds: [], reassembler: @tunnel.FragmentReassembler::new(), sessions: [], sam_clients: [], bridges: [], remote_bridges: [], aliases: [], b32_aliases: [], failed_peers: [], ratchet_resets: [], http_proxy_listener: None, http_proxy_conns: [], http_proxy_session_id: None, torrent_engine: None, torrent_api_listener: None, torrent_api_conns: [], lease_rr: 0, outbound_rr: 0, last_bootstrap_ms: 0UL, last_explore_ms: 0UL, } if public_mode { r.register_default_public_aliases() } r } ///| pub fn Router::inbound_tunnel_count(self : Router) -> Int32 { self.tunnels.inbound_count() } ///| pub fn Router::outbound_tunnel_count(self : Router) -> Int32 { self.tunnels.outbound_count() } ///| pub fn Router::pending_build_count(self : Router) -> Int32 { self.pending_builds.length() } ///| pub fn Router::pending_dial_count(self : Router) -> Int32 { self.pending_dials.length() } ///| pub fn Router::sam_port(self : Router) -> Int32 { self.sam_listener.local_port() } ///| pub fn Router::ntcp2_port(self : Router) -> Int32 { self.ntcp2_listener.local_port() } ///| pub fn Router::router_hash(self : Router) -> @common.Hash { self.router_info.identity.hash() } ///| fn remove_alias_entry(list : Array[(String, String)], key : String) -> Unit { let mut i = 0 while i < list.length() { if list[i].0 == key { let _ = list.remove(i) } else { i += 1 } } } ///| fn upsert_alias_entry( list : Array[(String, String)], key : String, val : String, ) -> Unit { for i = 0; i < list.length(); i = i + 1 { if list[i].0 == key { list[i] = (key, val) return } } list.push((key, val)) } ///| pub fn Router::register_alias( self : Router, hostname : String, dest_pub_b64 : String, ) -> Unit { let key = hostname.to_lower() if parse_b32_hash(dest_pub_b64) is Some(_) { remove_alias_entry(self.aliases, key) upsert_alias_entry(self.b32_aliases, key, dest_pub_b64.to_lower()) } else { remove_alias_entry(self.b32_aliases, key) upsert_alias_entry(self.aliases, key, dest_pub_b64) } } ///| /// Loads a peer `RouterInfo` file from disk, verifies its Ed25519 signature, /// and stores it in `self.netdb`. pub fn Router::load_peer_file( self : Router, path : String, ) -> @common.RouterInfo raise RouterError { let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) } let ri = @common.RouterInfo::decode(@encoding.Reader::new(raw)) catch { e => raise Common(e) } let _ = self.netdb.store_router_info(ri) catch { e => raise NetDb(e) } ri } ///| /// Scans a directory of `.dat` `RouterInfo` files, verifies Ed25519 signatures, /// and returns how many peer entries were loaded into `self.netdb`. pub fn Router::load_peer_dir( self : Router, dir_path : String, ) -> Int32 raise RouterError { let files = @ntcp2_net.list_dir_files(dir_path) catch { e => raise Net(e) } let mut loaded = 0 let sep = if dir_path.has_suffix("/") { "" } else { "/" } for fname in files { let full_path = "\{dir_path}\{sep}\{fname}" let ok = try { let _ = self.load_peer_file(full_path) true } catch { _ => false } if ok { loaded += 1 } } loaded } ///| /// Parses raw `.su3` reseed bytes, verifies each contained `RouterInfo`'s Ed25519 /// signature, and stores valid peers in `self.netdb`. pub fn Router::load_reseed_su3_bytes( self : Router, su3_bytes : Bytes, ) -> Int32 raise RouterError { let ris = @common.parse_reseed_su3(su3_bytes) catch { e => raise Common(e) } let mut count = 0 for ri in ris { let stored = self.netdb.store_router_info(ri) catch { _ => false } if stored { count += 1 } } count } ///| /// Loads a local `.su3` reseed file into `self.netdb`. pub fn Router::load_reseed_su3_file( self : Router, path : String, ) -> Int32 raise RouterError { let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) } self.load_reseed_su3_bytes(raw) } ///| /// Fetches an HTTPS `.su3` reseed bundle via system `curl` and imports verified peers. pub fn Router::reseed_from_url( self : Router, url : String, ) -> Int32 raise RouterError { let raw = @ntcp2_net.fetch_https_bytes(url) catch { e => raise Net(e) } self.load_reseed_su3_bytes(raw) } ///| pub fn Router::close(self : Router) -> Unit { for ac in self.torrent_api_conns { if !ac.closed { ac.sock.close() ac.closed = true } } match self.torrent_api_listener { Some(l) => { l.close() self.torrent_api_listener = None } None => () } for pc in self.http_proxy_conns { if !pc.closed { pc.sock.close() pc.closed = true } } match self.http_proxy_listener { Some(l) => { l.close() self.http_proxy_listener = None } None => () } for c in self.sam_clients { if !c.closed { c.sock.close() c.closed = true } } for b in self.bridges { b.a.close() b.b.close() } for rb in self.remote_bridges { if !rb.closed { rb.sock.close() rb.closed = true } } for pa in self.pending_accepts { pa.close() } for pd in self.pending_dials { pd.dial.close() } for p in self.peers { p.conn.close() } self.sam_listener.close() self.ntcp2_listener.close() } ///| fn Router::handle_i2np_message( self : Router, from_peer : @common.Hash?, hdr : @i2np.ShortHeader, payload : @i2np.I2npPayload, ) -> Unit { let now_sec = @ntcp2_net.unix_time_sec() match payload { DatabaseStore( key~, store_type~, reply_token~, reply_tunnel_id~, reply_gateway~, data~ ) => self.handle_database_store_msg( from_peer, key, store_type, reply_token, reply_tunnel_id, reply_gateway, data, now_sec, ) DatabaseLookup( key~, from~, flags~, reply_tunnel_id~, excluded_peers~, reply_key~, reply_tags~ ) => self.handle_database_lookup_msg( from_peer, key, from, flags, reply_tunnel_id, excluded_peers, reply_key, reply_tags, now_sec, ) DatabaseSearchReply(key~, peer_hashes~, from~) => self.handle_database_search_reply_msg(key, peer_hashes, from) ShortTunnelBuild(records~) => self.handle_short_tunnel_build(hdr.msg_id, records, now_sec) ShortTunnelBuildReply(records~) => self.handle_short_tunnel_build_reply(hdr.msg_id, records) TunnelData(tunnel_id~, data~) => self.handle_tunnel_data(tunnel_id, data) TunnelGateway(tunnel_id~, data~) => self.handle_tunnel_gateway(tunnel_id, data, now_sec) Garlic(data~) => if !self.try_handle_build_garlic_reply(data) && !self.try_handle_lookup_garlic_reply(data, now_sec) { self.handle_incoming_garlic(data, now_sec) } _ => () } } ///| fn Router::push_sam_client(self : Router, sock : @ntcp2_net.TcpSocket) -> Unit { self.sam_clients.push({ sock, recv_buf: [], session_id: None, mode: 0, accept_session_id: "", accept_silent: false, closed: false, }) } ///| /// Runs one non-blocking event-loop tick (accepting SAMv3 & NTCP2 connections, /// stepping handshakes & peer sessions, servicing NetDB/tunnel/Garlic/Streaming, /// and pumping SAMv3 stream relays). Sleeps up to `poll_ms` only when idle. pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit { let mut did_work = false for _i = 0; _i < 8; _i = _i + 1 { match (self.sam_listener.accept(timeout_ms=0) catch { _ => None }) { Some(sock) => { self.push_sam_client(sock) did_work = true } None => break } } if self.step_ntcp2_peers() { did_work = true } if self.step_sam_clients() { did_work = true } if self.step_http_proxy() { did_work = true } if self.step_torrent_engine() { did_work = true } if self.step_torrent_api() { did_work = true } self.poll_netdb_lookups() self.poll_tunnel_builds() if self.public_mode { self.step_public_bootstrap() } if self.step_bridges() { did_work = true } if self.step_remote_bridges() { did_work = true } if !did_work && poll_ms > 0 { match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) { Some(sock) => self.push_sam_client(sock) None => () } } } ///| /// Runs the router event loop indefinitely. pub fn Router::run(self : Router) -> Unit { while true { self.step(poll_ms=10) } }