Files
moon-i2p/router/router.mbt
T
nandi cadb8cd898
check / check (macos-latest) (push) Failing after 31s
check / check (windows-latest) (push) Failing after 31s
check / check (ubuntu-latest) (push) Failing after 34s
feat: add native MoonBit I2P router core and embedded SAMv3 bridge
2026-11-27 19:49:34 +00:00

680 lines
18 KiB
MoonBit

///|
/// Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager,
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge (single-threaded poll loop).
///|
#derive(Eq, Debug)
pub suberror RouterError {
Net(@ntcp2_net.Ntcp2NetError)
Crypto(@crypto.CryptoError)
Common(@common.CommonError)
Noise(@noise.NoiseError)
NetDb(@netdb.NetDbError)
}
///|
/// 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,
}
}
///|
priv struct SamSession {
id : String
pub_b64 : String
b32 : String
}
///|
priv struct SamClientConn {
sock : @ntcp2_net.TcpSocket
mut session_id : String?
mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged
mut accept_session_id : String
mut accept_silent : Bool
mut closed : Bool
}
///|
priv struct StreamBridge {
a : @ntcp2_net.TcpSocket
b : @ntcp2_net.TcpSocket
mut a_eof : Bool
mut b_eof : Bool
}
///|
/// 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
priv sessions : Array[SamSession]
priv sam_clients : Array[SamClientConn]
priv bridges : Array[StreamBridge]
priv aliases : Array[(String, String)] // hostname -> pub_b64
}
///|
/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and
/// returns `(dest, pub_b64, priv_b64, ed_seed)`.
fn generate_transient_destination() -> (
@common.Destination,
String,
String,
Bytes,
) 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 x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
let x_pub = @crypto.x25519_public_key(x_priv) catch { e => raise Crypto(e) }
let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) }
let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub, padding=pad) catch {
e => raise Common(e)
}
let pub_bytes = dest.to_bytes()
let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64)
priv_w.write_bytes(pub_bytes)
priv_w.write_bytes(x_priv)
priv_w.write_bytes(ed_seed)
let pub_b64 = @encoding.base64_encode(pub_bytes)
let priv_b64 = @encoding.base64_encode(priv_w.to_bytes())
(dest, pub_b64, priv_b64, ed_seed)
}
///|
/// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`,
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge.
pub fn Router::start(config : RouterConfig) -> 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 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,
) catch {
e => raise Common(e)
}
let addr_opts = @common.Mapping::from_entries([
("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 ri : @common.RouterInfo = {
identity: id,
published: @ntcp2_net.unix_time_ms(),
addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)],
options: @common.Mapping::from_entries([
("caps", "LR"),
("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 router : Router = {
ed_seed,
static_key,
ntcp2_iv,
router_info: signed_ri,
netdb,
tunnels: @tunnel.TunnelManager::new(),
ntcp2_listener,
sam_listener,
sessions: [],
sam_clients: [],
bridges: [],
aliases: [],
}
router
}
///|
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()
}
///|
pub fn Router::register_alias(
self : Router,
hostname : String,
dest_pub_b64 : String,
) -> Unit {
let key = hostname.to_lower()
for i = 0; i < self.aliases.length(); i = i + 1 {
if self.aliases[i].0 == key {
self.aliases[i] = (key, dest_pub_b64)
return
}
}
self.aliases.push((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
}
///|
pub fn Router::close(self : Router) -> Unit {
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()
}
self.sam_listener.close()
self.ntcp2_listener.close()
}
///|
fn Router::find_session_by_id(self : Router, id : String) -> SamSession? {
for s in self.sessions {
if s.id == id {
return Some(s)
}
}
None
}
///|
fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? {
for s in self.sessions {
if s.pub_b64 == pub_b64 {
return Some(s)
}
}
None
}
///|
fn Router::resolve_name(
self : Router,
name : String,
client_session_id : String?,
) -> String? {
if name == "ME" {
match client_session_id {
Some(sid) =>
match self.find_session_by_id(sid) {
Some(s) => return Some(s.pub_b64)
None => ()
}
None => ()
}
return None
}
let lower = name.to_lower()
// Check local aliases
for entry in self.aliases {
if entry.0 == lower {
return Some(entry.1)
}
}
// Check active local sessions by .b32.i2p
for s in self.sessions {
if s.b32 == lower {
return Some(s.pub_b64)
}
}
// Check NetDB LeaseSet2 entries by .b32.i2p
let now_sec = @ntcp2_net.unix_time_sec()
match self.netdb.get_lease_set2_by_b32(lower, now_sec) {
Some(ls2) => return Some(ls2.destination.to_base64())
None => ()
}
None
}
///|
fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool {
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch {
_ => return false
}
true
}
///|
fn Router::handle_sam_command(
self : Router,
client_idx : Int32,
line : String,
) -> Unit {
let client = self.sam_clients[client_idx]
let msg = @sam.SamMessage::parse(line) catch {
_ => {
let _ = send_sam_line(
client.sock,
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error",
)
return
}
}
match (msg.verb, msg.subcommand) {
("HELLO", Some("VERSION")) => {
let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3")
}
("DEST", Some("GENERATE")) => {
let (_dest, pub_b64, priv_b64, _seed) = generate_transient_destination() catch {
_ => {
let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR")
return
}
}
let _ = send_sam_line(
client.sock,
"DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}",
)
}
("NAMING", Some("LOOKUP")) => {
let name = match msg.get("NAME") {
Some(n) => n
None => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=INVALID_KEY NAME=",
)
return
}
}
match self.resolve_name(name, client.session_id) {
Some(val) => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}",
)
}
None => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}",
)
}
}
}
("SESSION", Some("CREATE")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id",
)
return
}
}
if self.find_session_by_id(sid) is Some(_) {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=DUPLICATED_ID",
)
return
}
let dest_param = match msg.get("DESTINATION") {
Some(d) => d
None => "TRANSIENT"
}
let (dest, pub_b64, priv_b64, opt_seed) = if dest_param == "TRANSIENT" {
let (d, pb, prb, seed) = generate_transient_destination() catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=I2P_ERROR",
)
return
}
}
(d, pb, prb, Some(seed))
} else {
let raw = @encoding.base64_decode(dest_param) catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=INVALID_KEY",
)
return
}
}
let d = @common.Destination::decode(@encoding.Reader::new(raw)) catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=INVALID_KEY",
)
return
}
}
(d, d.to_base64(), dest_param, None)
}
let b32 = dest.b32_address()
// Publish a signed LeaseSet2 for transient destinations into our NetDB
match opt_seed {
Some(seed) => {
let now_sec = @ntcp2_net.unix_time_sec()
let ls2 : @common.LeaseSet2 = {
destination: dest,
published_sec: now_sec,
expires_offset: 600U,
flags: 0U,
options: @common.Mapping::new(),
encryption_keys: [
{ key_type: X25519, key_data: dest.inner.crypto_public_key(), },
],
leases: [
{
tunnel_gw: self.router_hash(),
tunnel_id: (10000 + self.sessions.length()).reinterpret_as_uint(),
end_date_sec: now_sec + 600U,
},
],
signature: b"",
}
let signed_ls2 = ls2.sign_ed25519(seed) catch { _ => ls2 }
let _ = self.netdb.store_lease_set2(signed_ls2, now_sec) catch {
_ => false
}
}
None => ()
}
self.sessions.push({ id: sid, pub_b64, b32, })
client.session_id = Some(sid)
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}",
)
}
("STREAM", Some("ACCEPT")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
if self.find_session_by_id(sid) is None {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
let silent = match msg.get("SILENT") {
Some(v) => v.to_lower() == "true"
None => false
}
client.mode = 1
client.accept_session_id = sid
client.accept_silent = silent
if !silent {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
}
}
("STREAM", Some("CONNECT")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
let caller_sess = match self.find_session_by_id(sid) {
Some(s) => s
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
let dest_b64 = match msg.get("DESTINATION") {
Some(d) => d
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY")
return
}
}
let silent = match msg.get("SILENT") {
Some(v) => v.to_lower() == "true"
None => false
}
let target_sess = match self.find_session_by_pub(dest_b64) {
Some(s) => s
None => {
if !silent {
let _ = send_sam_line(
client.sock,
"STREAM STATUS RESULT=CANT_REACH_PEER",
)
}
client.closed = true
client.sock.close()
return
}
}
// Find a waiting STREAM ACCEPT client for target_sess.id
let mut acceptor_idx = -1
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id {
acceptor_idx = i
break
}
}
if acceptor_idx < 0 {
if !silent {
let _ = send_sam_line(
client.sock,
"STREAM STATUS RESULT=CANT_REACH_PEER",
)
}
client.closed = true
client.sock.close()
return
}
let acceptor = self.sam_clients[acceptor_idx]
if !silent {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
}
if !acceptor.accept_silent {
let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64)
}
// Promote both sockets into a bidirectional raw stream bridge
client.mode = 2
acceptor.mode = 2
self.bridges.push({
a: client.sock,
b: acceptor.sock,
a_eof: false,
b_eof: false,
})
}
_ => {
let _ = send_sam_line(
client.sock,
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command",
)
}
}
}
///|
/// Runs one non-blocking event-loop tick (accepting SAMv3 & NTCP2 connections,
/// processing SAMv3 commands, and pumping bridged stream relays).
pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
// 1. Accept any pending SAMv3 TCP connection
match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) {
Some(sock) =>
self.sam_clients.push({
sock,
session_id: None,
mode: 0,
accept_session_id: "",
accept_silent: false,
closed: false,
})
None => ()
}
// 2. Accept any pending incoming NTCP2 TCP connection (non-blocking)
match (self.ntcp2_listener.accept(timeout_ms=0) catch { _ => None }) {
Some(sock) => {
let res = try {
let conn = @ntcp2_net.accept_ntcp2(
sock,
self.static_key,
self.router_hash().as_bytes(),
self.ntcp2_iv,
timeout_ms=2000,
)
match conn.remote_router_info {
Some(peer_ri) => {
let _ = self.netdb.store_router_info(peer_ri) catch { _ => false }
}
None => ()
}
conn.close()
true
} catch {
_ => {
sock.close()
false
}
}
let _ = res
}
None => ()
}
// 3. Process readable SAMv3 command sockets
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if c.closed || c.mode != 0 {
continue
}
let ready = c.sock.poll_readable(0) catch { _ => false }
if !ready {
continue
}
match (c.sock.read_line() catch { _ => None }) {
Some(line) => if line.length() > 0 { self.handle_sam_command(i, line) }
None => {
c.closed = true
c.sock.close()
}
}
}
// 4. Pump bidirectional raw byte bridges for active STREAM connections
let mut bi = 0
while bi < self.bridges.length() {
let br = self.bridges[bi]
if !br.a_eof {
let r = br.a.poll_readable(0) catch { _ => false }
if r {
let data = br.a.read_some(4096) catch { _ => b"" }
if data.length() == 0 {
br.a_eof = true
br.b.shutdown_write()
} else {
br.b.write_all(data) catch {
_ => br.b_eof = true
}
}
}
}
if !br.b_eof {
let r = br.b.poll_readable(0) catch { _ => false }
if r {
let data = br.b.read_some(4096) catch { _ => b"" }
if data.length() == 0 {
br.b_eof = true
br.a.shutdown_write()
} else {
br.a.write_all(data) catch {
_ => br.a_eof = true
}
}
}
}
if br.a_eof && br.b_eof {
br.a.close()
br.b.close()
let _ = self.bridges.remove(bi)
} else {
bi += 1
}
}
}
///|
/// Runs the router event loop indefinitely.
pub fn Router::run(self : Router) -> Unit {
while true {
self.step(poll_ms=10)
}
}