Files
moon-i2p/router/ntcp2_peers.mbt
T
nandi 54cfb2faa9
check / check (ubuntu-latest) (push) Failing after 26s
check / check (macos-latest) (push) Failing after 28s
check / check (windows-latest) (push) Failing after 29s
feat: add public I2P network mode to router daemon
- Add `--public`, `--hops`, `--hosts`, and `--debug` router flags; `--public` auto-reseeds from the live network and keeps a status loop running.
- Route NetDB lookups through tunnels with Noise_N garlic wrapping, fan out to two floodfills, and fetch unknown RouterInfos in the background.
- Back off failed NTCP2 peers and fall back to IPv6 addresses when no IPv4 NTCP2 address is available.
- Size session LeaseSet2 expiry from lease end dates and use the destination's X25519 key when present.
- Add canonical Ed25519 Destination KeyCertificate constructors with round-trip tests.
- Fix DatabaseStore gzip handling to honor the length prefix, and send `Wget/1.11.4` as the reseed User-Agent.
2026-11-28 00:11:28 -08:00

492 lines
12 KiB
MoonBit

///|
/// Non-blocking NTCP2 peer pool, outbound dialer, and Data Phase frame dispatcher.
///|
priv struct PendingPeerDial {
peer_hash : @common.Hash
dial : @ntcp2_net.PendingNtcp2Dial
}
///|
priv struct PeerSession {
hash : @common.Hash
conn : @ntcp2_net.Ntcp2Conn
mut last_active_ms : UInt64
}
///|
priv struct PendingPeerSend {
target_hash : @common.Hash
msg_id : UInt32
expiration_sec : UInt32
payload : @i2np.I2npPayload
queued_ms : UInt64
}
///|
pub fn Router::peer_count(self : Router) -> Int32 {
self.peers.length()
}
///|
fn Router::mark_peer_failed(
self : Router,
peer_hash : @common.Hash,
cooldown_ms : UInt64,
) -> Unit {
let until = @ntcp2_net.unix_time_ms() + cooldown_ms
for i = 0; i < self.failed_peers.length(); i = i + 1 {
if self.failed_peers[i].0 == peer_hash {
self.failed_peers[i] = (peer_hash, until)
return
}
}
if self.failed_peers.length() >= 512 {
let _ = self.failed_peers.remove(0)
}
self.failed_peers.push((peer_hash, until))
}
///|
fn Router::is_peer_backed_off(
self : Router,
peer_hash : @common.Hash,
now_ms : UInt64,
) -> Bool {
let mut i = 0
let mut backed_off = false
while i < self.failed_peers.length() {
if self.failed_peers[i].1 <= now_ms {
let _ = self.failed_peers.remove(i)
} else {
if self.failed_peers[i].0 == peer_hash {
backed_off = true
}
i += 1
}
}
backed_off
}
///|
fn Router::find_peer_hash_by_static(
self : Router,
static_pub : Bytes,
) -> @common.Hash? {
for entry in self.netdb.routers {
for addr in entry.1.addresses {
if addr.transport_style == "NTCP2" {
match addr.options.get("s") {
Some(s_b64) => {
let s_bytes = @encoding.base64_decode(s_b64) catch { _ => b"" }
if s_bytes.length() == 32 && @crypto.ct_eq(s_bytes, static_pub) {
return Some(entry.0)
}
}
None => ()
}
}
}
}
None
}
///|
fn Router::has_pending_dial(self : Router, target_hash : @common.Hash) -> Bool {
for pd in self.pending_dials {
if pd.peer_hash == target_hash {
return true
}
}
false
}
///|
fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms()
if target_hash == self.router_hash() ||
self.has_pending_dial(target_hash) ||
(self.public_mode && self.is_peer_backed_off(target_hash, now_ms)) {
return
}
let ri = match self.netdb.get_router_info(target_hash) {
Some(r) => r
None => return
}
let peer_info = @ntcp2_net.extract_ntcp2_peer(ri) catch {
_ => {
if self.public_mode {
self.mark_peer_failed(target_hash, 120000UL)
}
return
}
}
let dial = @ntcp2_net.PendingNtcp2Dial::start(
peer_info,
self.static_key,
self.router_info,
check_clock_skew=self.check_clock_skew,
remote_ri=Some(ri),
) catch {
_ => {
if self.public_mode {
self.mark_peer_failed(target_hash, 60000UL)
}
return
}
}
self.pending_dials.push({ peer_hash: target_hash, dial, })
}
///|
fn Router::send_i2np_to_peer(
self : Router,
target_hash : @common.Hash,
payload : @i2np.I2npPayload,
msg_id_override~ : UInt32? = None,
) -> UInt32 {
let mid = match msg_id_override {
Some(id) => id
None => self.alloc_msg_id()
}
let now_ms = @ntcp2_net.unix_time_ms()
let exp_sec = (now_ms / 1000UL).to_uint() + 60U
if target_hash == self.router_hash() {
self.pending_sends.push({
target_hash,
msg_id: mid,
expiration_sec: exp_sec,
payload,
queued_ms: now_ms,
})
return mid
}
// Prefer most recently active live session for target_hash
let mut idx = self.peers.length() - 1
while idx >= 0 {
if self.peers[idx].hash == target_hash {
let ok = try {
self.peers[idx].conn.send_i2np(mid, exp_sec, payload)
true
} catch {
_ => false
}
if ok {
self.peers[idx].last_active_ms = now_ms
return mid
}
self.peers[idx].conn.close()
let _ = self.peers.remove(idx)
}
idx -= 1
}
self.pending_sends.push({
target_hash,
msg_id: mid,
expiration_sec: exp_sec,
payload,
queued_ms: now_ms,
})
self.ensure_peer_dial(target_hash)
mid
}
///|
fn Router::send_routed_i2np(
self : Router,
target_gw : @common.Hash,
target_tid : UInt32?,
payload : @i2np.I2npPayload,
) -> Unit {
let out_len = self.tunnels.outbound.length()
if out_len > 0 {
let idx = if self.outbound_rr < 0 { 0 } else { self.outbound_rr % out_len }
self.outbound_rr = (self.outbound_rr + 1) & 0x3FFFFFFF
let out_t = self.tunnels.outbound[idx]
let target : @tunnel.DeliveryTarget = match target_tid {
Some(tid) => Tunnel(tunnel_id=tid, gateway=target_gw)
None => Router(router_hash=target_gw)
}
let routed = try {
self.send_through_tunnel(out_t.id, target, payload)
true
} catch {
_ => false
}
if routed {
return
}
}
match target_tid {
Some(tid) => {
let mid = self.alloc_msg_id()
let exp_ms = @ntcp2_net.unix_time_ms() + 60000UL
let std_bytes = @i2np.encode_standard_message(mid, exp_ms, payload) catch {
_ => return
}
let _ = self.send_i2np_to_peer(
target_gw,
TunnelGateway(tunnel_id=tid, data=std_bytes),
)
}
None => {
let _ = self.send_i2np_to_peer(target_gw, payload)
}
}
}
///|
fn Router::flush_pending_sends_for(
self : Router,
target_hash : @common.Hash,
peer : PeerSession,
) -> Bool {
let mut i = 0
while i < self.pending_sends.length() {
let ps = self.pending_sends[i]
if ps.target_hash == target_hash {
let ok = try {
peer.conn.send_i2np(ps.msg_id, ps.expiration_sec, ps.payload)
true
} catch {
_ => false
}
if !ok {
return false
}
peer.last_active_ms = @ntcp2_net.unix_time_ms()
let _ = self.pending_sends.remove(i)
} else {
i += 1
}
}
true
}
///|
fn Router::handle_peer_blocks(
self : Router,
peer_hash : @common.Hash,
blocks : Array[@ntcp2.Ntcp2Block],
) -> Bool {
let mut should_close = false
for blk in blocks {
match blk {
I2np(short_bytes) => {
let decoded = Some(
@i2np.decode_short_message(@encoding.Reader::new(short_bytes)),
) catch {
_ => None
}
match decoded {
Some((hdr, payload)) =>
self.handle_i2np_message(Some(peer_hash), hdr, payload)
None => ()
}
}
RouterInfo(router_info~, ..) => {
let ri = @common.RouterInfo::decode(@encoding.Reader::new(router_info)) catch {
_ => continue
}
let _ = self.netdb.store_router_info(ri) catch { _ => false }
}
Termination(..) => should_close = true
_ => ()
}
}
should_close
}
///|
fn Router::step_ntcp2_peers(self : Router) -> Bool {
let now_ms = @ntcp2_net.unix_time_ms()
let mut did_work = false
// 1. Accept any newly arrived TCP sockets into non-blocking responder handshakes
for _a = 0; _a < 8; _a = _a + 1 {
match (self.ntcp2_listener.accept_nonblocking() catch { _ => None }) {
Some(sock) => {
let pa_opt = Some(
@ntcp2_net.PendingNtcp2Accept::start(
sock,
self.static_key,
self.router_hash().as_bytes(),
self.ntcp2_iv,
replay_cache=Some(self.replay_cache),
check_clock_skew=self.check_clock_skew,
),
) catch {
_ => None
}
match pa_opt {
Some(pa) => {
self.pending_accepts.push(pa)
did_work = true
}
None => ()
}
}
None => break
}
}
// 2. Step pending inbound NTCP2 handshakes
let mut ai = 0
while ai < self.pending_accepts.length() {
let pa = self.pending_accepts[ai]
if now_ms > pa.started_at_ms() + 10000UL {
pa.close()
let _ = self.pending_accepts.remove(ai)
did_work = true
continue
}
let stepped = (pa.step(), false) catch { _ => (None, true) }
if stepped.1 {
pa.close()
let _ = self.pending_accepts.remove(ai)
did_work = true
continue
}
match stepped.0 {
Some(conn) => {
did_work = true
let _ = self.pending_accepts.remove(ai)
let mut peer_hash : @common.Hash? = None
match conn.remote_router_info {
Some(ri) => {
let _ = self.netdb.store_router_info(ri) catch { _ => false }
peer_hash = Some(ri.identity.hash())
}
None =>
peer_hash = self.find_peer_hash_by_static(
conn.session.remote_static(),
)
}
match peer_hash {
Some(ph) => {
let ps : PeerSession = { hash: ph, conn, last_active_ms: now_ms, }
self.peers.push(ps)
let _ = self.flush_pending_sends_for(ph, ps)
}
None => conn.close()
}
}
None => ai += 1
}
}
// 3. Step pending outbound NTCP2 dials
let mut di = 0
while di < self.pending_dials.length() {
let pd = self.pending_dials[di]
if now_ms > pd.dial.started_at_ms() + 10000UL {
pd.dial.close()
let _ = self.pending_dials.remove(di)
if self.public_mode {
self.mark_peer_failed(pd.peer_hash, 60000UL)
if self.debug {
println(
"[debug] NTCP2 dial timeout: \{pd.peer_hash.to_b32_address()}",
)
}
}
did_work = true
continue
}
let stepped = (pd.dial.step(), false) catch { _ => (None, true) }
if stepped.1 {
pd.dial.close()
let _ = self.pending_dials.remove(di)
if self.public_mode {
self.mark_peer_failed(pd.peer_hash, 60000UL)
if self.debug {
println(
"[debug] NTCP2 dial rejected: \{pd.peer_hash.to_b32_address()}",
)
}
}
did_work = true
continue
}
match stepped.0 {
Some(conn) => {
did_work = true
let _ = self.pending_dials.remove(di)
let ps : PeerSession = {
hash: pd.peer_hash,
conn,
last_active_ms: now_ms,
}
self.peers.push(ps)
if self.debug {
println(
"[debug] NTCP2 connected to \{pd.peer_hash.to_b32_address()} (peers=\{self.peers.length()})",
)
}
let _ = self.flush_pending_sends_for(pd.peer_hash, ps)
}
None => di += 1
}
}
// 4. Deliver any local loopback sends or retry/expire orphaned pending sends
let local_msgs : Array[PendingPeerSend] = []
let mut si = 0
while si < self.pending_sends.length() {
let ps = self.pending_sends[si]
if ps.target_hash == self.router_hash() {
local_msgs.push(ps)
let _ = self.pending_sends.remove(si)
did_work = true
} else if now_ms > ps.queued_ms + 15000UL {
let _ = self.pending_sends.remove(si)
} else {
si += 1
}
}
for ps in local_msgs {
self.handle_i2np_message(
Some(self.router_hash()),
{
msg_type: ps.payload.msg_type(),
msg_id: ps.msg_id,
expiration_sec: ps.expiration_sec,
},
ps.payload,
)
}
// 5. Non-blocking read & dispatch on all active NTCP2 peer sessions
let mut pi = 0
while pi < self.peers.length() {
let peer = self.peers[pi]
let mut alive = true
for _frame = 0; _frame < 32; _frame = _frame + 1 {
let recv_opt = peer.conn.try_recv_blocks() catch {
_ => {
alive = false
None
}
}
match recv_opt {
Some(blocks) => {
did_work = true
peer.last_active_ms = now_ms
if self.handle_peer_blocks(peer.hash, blocks) {
alive = false
break
}
}
None => break
}
}
if !alive || now_ms > peer.last_active_ms + 180000UL {
peer.conn.close()
let _ = self.peers.remove(pi)
} else {
pi += 1
}
}
did_work
}