feat: add public I2P network mode to router daemon
check / check (ubuntu-latest) (push) Failing after 26s
check / check (macos-latest) (push) Failing after 28s
check / check (windows-latest) (push) Failing after 29s

- 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.
This commit is contained in:
nandi committed 2026-11-28 00:11:28 -08:00
1 parent ae72b00323
commit 54cfb2faa9
25 files changed
+2033 -191

No files matched your search

+321 -20
View File
@@ -5,16 +5,20 @@
///|
priv struct PendingNetDbLookup {
target_hash : @common.Hash
lookup_type : Int32 // 1 = LeaseSet, 2 = RouterInfo, 3 = Exploration
reply_key : Bytes
reply_tag : Bytes
queried_peers : Array[@common.Hash]
candidate_peers : Array[@common.Hash]
started_ms : UInt64
kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2
mut last_query_ms : UInt64
kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2, 2 = background RI/exploration
client_idx : Int32
req_name : String
session_id : String
silent : Bool
from_port : UInt32
to_port : UInt32
}
///|
@@ -57,16 +61,39 @@ fn Router::build_session_leaseset2(
end_date_sec: now_sec + 600U,
})
}
let enc_key = match sess.x25519_pub {
Some(k) if k.length() == 32 => k
_ => {
let fk = sess.dest.inner.crypto_public_key()
if fk.length() == 32 {
fk
} else {
return None
}
}
}
let mut max_end = now_sec + 60U
for l in leases {
if l.end_date_sec > max_end {
max_end = l.end_date_sec
}
}
let diff = if max_end > now_sec { max_end - now_sec } else { 60U }
let expires_offset = if diff < 60U {
60U
} else if diff > 660U {
660U
} else {
diff
}
let ls2 : @common.LeaseSet2 = {
destination: sess.dest,
published_sec: now_sec,
expires_offset: 600U,
expires_offset,
flags: 0U,
offline_sig: None,
options: @common.Mapping::new(),
encryption_keys: [
{ key_type: X25519, key_data: sess.dest.inner.crypto_public_key(), },
],
encryption_keys: [{ key_type: X25519, key_data: enc_key, }],
leases,
signature: b"",
}
@@ -78,6 +105,9 @@ fn Router::build_session_leaseset2(
///|
fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit {
let now_sec = @ntcp2_net.unix_time_sec()
if self.public_mode && self.tunnels.inbound.length() == 0 {
return
}
let ls2 = match self.build_session_leaseset2(sess, now_sec) {
Some(l) => l
None => return
@@ -100,7 +130,7 @@ fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit {
data=raw,
)
for ff in floodfills {
let _ = self.send_i2np_to_peer(ff.identity.hash(), payload)
self.send_routed_i2np(ff.identity.hash(), None, payload)
}
}
@@ -158,19 +188,191 @@ fn Router::send_lookup_query(
if !is_hash_in(peer_hash, lk.queried_peers) {
lk.queried_peers.push(peer_hash)
}
// Proposal 154 ECIES encrypted reply (0x10) + LeaseSet lookup type (0x04)
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
lk.last_query_ms = now_ms
let excl : Array[@common.Hash] = []
let excl_cap = if lk.queried_peers.length() < 8 {
lk.queried_peers.length()
} else {
8
}
for ei = lk.queried_peers.length() - excl_cap
ei < lk.queried_peers.length()
ei = ei + 1 {
excl.push(lk.queried_peers[ei])
}
let has_tunnels = self.tunnels.inbound.length() > 0 &&
self.tunnels.outbound.length() > 0
if has_tunnels && self.tunnels.inbound[0].hops.length() > 0 {
let in_idx = lk.queried_peers.length() % self.tunnels.inbound.length()
let in_t = if self.tunnels.inbound[in_idx].hops.length() > 0 {
self.tunnels.inbound[in_idx]
} else {
self.tunnels.inbound[0]
}
let out_idx = lk.queried_peers.length() % self.tunnels.outbound.length()
let out_t = self.tunnels.outbound[out_idx]
let ibgw = in_t.hops[0]
let flags_int = 0x01 | (lk.lookup_type << 2) | 0x10
let lookup : @i2np.I2npPayload = DatabaseLookup(
key=lk.target_hash,
from=ibgw.router_hash,
flags=flags_int.to_byte(),
reply_tunnel_id=Some(ibgw.receive_tunnel_id),
excluded_peers=excl,
reply_key=Some(lk.reply_key),
reply_tags=[lk.reply_tag],
)
let mut wrapped : @i2np.I2npPayload? = None
match self.netdb.get_router_info(peer_hash) {
Some(ri) =>
if ri.identity.inner.crypto_type() == X25519 {
let xpub = ri.identity.inner.crypto_public_key()
if xpub.length() == 32 {
let ephem_opt = Some(@noise.KeyPair::from_private(next_rand_32())) catch {
_ => None
}
match ephem_opt {
Some(ephem) => {
let clove_opt = Some(
@ratchet.garlic_clove_block(
Local,
self.alloc_msg_id(),
now_sec + 60U,
lookup,
),
) catch {
_ => None
}
match clove_opt {
Some(clove) => {
let enc_opt = Some(
@ratchet.encrypt_router_garlic(xpub, ephem, [
DateTime(now_sec),
clove,
]),
) catch {
_ => None
}
match enc_opt {
Some(enc) => wrapped = Some(Garlic(data=enc))
None => ()
}
}
None => ()
}
}
None => ()
}
}
}
None => ()
}
let wire_payload = wrapped.unwrap_or(lookup)
let ok = try {
self.send_through_tunnel(
out_t.id,
Router(router_hash=peer_hash),
wire_payload,
)
true
} catch {
_ => false
}
if ok {
if self.debug {
println(
"[debug] NetDB lookup type=\{lk.lookup_type} key=\{lk.target_hash.to_b32_address()} -> peer=\{peer_hash.to_b32_address()} via tunnel \{out_t.id} (reply_ibgw=\{ibgw.router_hash.to_b32_address()}:\{ibgw.receive_tunnel_id})",
)
}
return
}
}
// Fallback direct query (used during bootstrap when 0 tunnels exist, or in 2-router tests)
let flags_int = (lk.lookup_type << 2) | 0x10
let lookup : @i2np.I2npPayload = DatabaseLookup(
key=lk.target_hash,
from=self.router_hash(),
flags=b'\x14',
flags=flags_int.to_byte(),
reply_tunnel_id=None,
excluded_peers=lk.queried_peers,
excluded_peers=excl,
reply_key=Some(lk.reply_key),
reply_tags=[lk.reply_tag],
)
let _ = self.send_i2np_to_peer(peer_hash, lookup)
}
///|
fn Router::has_pending_lookup(
self : Router,
target_hash : @common.Hash,
lookup_type : Int32,
) -> Bool {
for lk in self.pending_lookups {
if lk.target_hash == target_hash && lk.lookup_type == lookup_type {
return true
}
}
false
}
///|
fn Router::start_background_lookup(
self : Router,
target_hash : @common.Hash,
lookup_type : Int32,
preferred_peer~ : @common.Hash? = None,
) -> Unit {
if self.has_pending_lookup(target_hash, lookup_type) {
return
}
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
let ordered : Array[@common.Hash] = []
match preferred_peer {
Some(p) if p != self.router_hash() => ordered.push(p)
_ => ()
}
for p in peers {
if !is_hash_in(p, ordered) {
ordered.push(p)
}
}
if ordered.length() == 0 {
return
}
let reply_key = next_rand_32()
let tag_rand = @ntcp2_net.random_bytes(8) catch {
_ => Bytes::make(8, b'\x77')
}
let lk : PendingNetDbLookup = {
target_hash,
lookup_type,
reply_key,
reply_tag: tag_rand,
queried_peers: [],
candidate_peers: [],
started_ms: now_ms,
last_query_ms: now_ms,
kind: 2,
client_idx: -1,
req_name: "",
session_id: "",
silent: true,
from_port: 0U,
to_port: 0U,
}
self.pending_lookups.push(lk)
self.send_lookup_query(lk, ordered[0])
for i = 1; i < ordered.length(); i = i + 1 {
lk.candidate_peers.push(ordered[i])
}
}
///|
fn Router::start_netdb_lookup(
self : Router,
@@ -180,9 +382,12 @@ fn Router::start_netdb_lookup(
req_name : String,
session_id : String,
silent : Bool,
from_port~ : UInt32 = 0U,
to_port~ : UInt32 = 0U,
) -> Bool {
let now_sec = @ntcp2_net.unix_time_sec()
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 6)
if initial_peers.length() == 0 {
return false
}
@@ -192,20 +397,31 @@ fn Router::start_netdb_lookup(
}
let lk : PendingNetDbLookup = {
target_hash,
lookup_type: 1, // LeaseSet lookup
reply_key,
reply_tag: tag_rand,
queried_peers: [],
candidate_peers: [],
started_ms: @ntcp2_net.unix_time_ms(),
started_ms: now_ms,
last_query_ms: now_ms,
kind,
client_idx,
req_name,
session_id,
silent,
from_port,
to_port,
}
self.pending_lookups.push(lk)
self.send_lookup_query(lk, initial_peers[0])
for i = 1; i < initial_peers.length(); i = i + 1 {
let fanout = if self.public_mode && initial_peers.length() >= 2 {
2
} else {
1
}
for k = 0; k < fanout; k = k + 1 {
self.send_lookup_query(lk, initial_peers[k])
}
for i = fanout; i < initial_peers.length(); i = i + 1 {
lk.candidate_peers.push(initial_peers[i])
}
true
@@ -223,11 +439,39 @@ fn Router::handle_database_store_msg(
data : Bytes,
now_sec : UInt32,
) -> Unit {
let stype = store_type.to_int() & 0x0F
let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch {
_ => false
}
if stored && (store_type.to_int() & 0x0F) == 3 {
if self.debug && (stype == 3 || stored) {
println(
"[debug] NetDB DatabaseStore type=\{stype} stored=\{stored} key=\{key.to_b32_address()} (len=\{data.length()})",
)
}
if stype == 3 && stored {
self.complete_lookups_for_hash(key, now_sec)
} else if stype == 0 && stored {
// Complete any background RouterInfo lookups for `key` and feed new floodfill into active LS lookups
let mut idx = 0
while idx < self.pending_lookups.length() {
let lk = self.pending_lookups[idx]
if lk.kind == 2 && lk.lookup_type == 2 && lk.target_hash == key {
let _ = self.pending_lookups.remove(idx)
} else {
idx += 1
}
}
match self.netdb.get_router_info(key) {
Some(ri) if @netdb.is_floodfill(ri) =>
for lk in self.pending_lookups {
if lk.lookup_type == 1 &&
!is_hash_in(key, lk.queried_peers) &&
!is_hash_in(key, lk.candidate_peers) {
lk.candidate_peers.push(key)
}
}
_ => ()
}
}
if reply_token != 0U {
let status : @i2np.I2npPayload = DeliveryStatus(
@@ -345,6 +589,13 @@ fn Router::handle_database_search_reply_msg(
peer_hashes : Array[@common.Hash],
from : @common.Hash,
) -> Unit {
if self.debug {
println(
"[debug] NetDB DatabaseSearchReply key=\{key.to_b32_address()} refs=\{peer_hashes.length()} from=\{from.to_b32_address()}",
)
}
let max_queries = if self.public_mode { 16 } else { 8 }
let unknown_to_fetch : Array[@common.Hash] = []
for lk in self.pending_lookups {
if lk.target_hash == key {
if !is_hash_in(from, lk.queried_peers) {
@@ -353,12 +604,18 @@ fn Router::handle_database_search_reply_msg(
for ph in peer_hashes {
if ph != self.router_hash() &&
!is_hash_in(ph, lk.queried_peers) &&
!is_hash_in(ph, lk.candidate_peers) &&
self.netdb.get_router_info(ph) is Some(_) {
lk.candidate_peers.push(ph)
!is_hash_in(ph, lk.candidate_peers) {
if self.netdb.get_router_info(ph) is Some(_) {
lk.candidate_peers.push(ph)
} else if lk.lookup_type != 2 &&
unknown_to_fetch.length() < 4 &&
!is_hash_in(ph, unknown_to_fetch) {
unknown_to_fetch.push(ph)
}
}
}
while lk.candidate_peers.length() > 0 && lk.queried_peers.length() < 8 {
while lk.candidate_peers.length() > 0 &&
lk.queried_peers.length() < max_queries {
let next_peer = lk.candidate_peers.remove(0)
if !is_hash_in(next_peer, lk.queried_peers) {
self.send_lookup_query(lk, next_peer)
@@ -367,6 +624,9 @@ fn Router::handle_database_search_reply_msg(
}
}
}
for ph in unknown_to_fetch {
self.start_background_lookup(ph, 2, preferred_peer=Some(from))
}
}
///|
@@ -454,9 +714,28 @@ fn Router::complete_lookups_for_hash(
fn Router::poll_netdb_lookups(self : Router) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let timeout_ms = if self.public_mode { 25000UL } else { 8000UL }
let max_queries = if self.public_mode { 16 } else { 8 }
let mut i = 0
while i < self.pending_lookups.length() {
let lk = self.pending_lookups[i]
if lk.kind == 2 {
if lk.lookup_type == 2 &&
self.netdb.get_router_info(lk.target_hash) is Some(_) {
let _ = self.pending_lookups.remove(i)
continue
}
if now_ms > lk.started_ms + 15000UL {
let _ = self.pending_lookups.remove(i)
continue
}
if now_ms > lk.last_query_ms + 3000UL && lk.candidate_peers.length() > 0 {
let next_p = lk.candidate_peers.remove(0)
self.send_lookup_query(lk, next_p)
}
i += 1
continue
}
match self.netdb.get_lease_set2(lk.target_hash, now_sec) {
Some(ls2) => {
let _ = self.pending_lookups.remove(i)
@@ -475,7 +754,29 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit {
}
None => ()
}
if now_ms > lk.started_ms + 8000UL {
if self.public_mode &&
lk.queried_peers.length() < max_queries &&
now_ms > lk.last_query_ms + 2500UL {
if lk.candidate_peers.length() > 0 {
let next_p = lk.candidate_peers.remove(0)
if !is_hash_in(next_p, lk.queried_peers) {
self.send_lookup_query(lk, next_p)
}
} else {
let fresh = self.select_lookup_peers(
lk.target_hash,
lk.queried_peers,
now_sec,
2,
)
if fresh.length() > 0 {
self.send_lookup_query(lk, fresh[0])
} else {
lk.last_query_ms = now_ms
}
}
}
if now_ms > lk.started_ms + timeout_ms {
let _ = self.pending_lookups.remove(i)
if lk.client_idx < self.sam_clients.length() {
let c = self.sam_clients[lk.client_idx]
+85 -6
View File
@@ -28,6 +28,46 @@ 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,
@@ -63,14 +103,24 @@ fn Router::has_pending_dial(self : Router, target_hash : @common.Hash) -> Bool {
///|
fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
if target_hash == self.router_hash() || self.has_pending_dial(target_hash) {
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 { _ => 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,
@@ -78,7 +128,12 @@ fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
check_clock_skew=self.check_clock_skew,
remote_ri=Some(ri),
) catch {
_ => return
_ => {
if self.public_mode {
self.mark_peer_failed(target_hash, 60000UL)
}
return
}
}
self.pending_dials.push({ peer_hash: target_hash, dial, })
}
@@ -143,8 +198,11 @@ fn Router::send_routed_i2np(
target_tid : UInt32?,
payload : @i2np.I2npPayload,
) -> Unit {
if self.tunnels.outbound.length() > 0 {
let out_t = self.tunnels.outbound[0]
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)
@@ -324,6 +382,14 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
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
}
@@ -331,6 +397,14 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
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
}
@@ -344,6 +418,11 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
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
@@ -401,7 +480,7 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
None => break
}
}
if !alive || now_ms > peer.last_active_ms + 120000UL {
if !alive || now_ms > peer.last_active_ms + 180000UL {
peer.conn.close()
let _ = self.peers.remove(pi)
} else {
+355
View File
@@ -0,0 +1,355 @@
///|
/// Autonomous public I2P network bootstrap: live `.su3` reseed, NAT-friendly
/// Proposal 157 Inbound/Outbound tunnel pool maintenance, `hosts.txt` aliases,
/// and periodic NetDB floodfill exploration.
///|
pub let default_reseed_urls : Array[String] = [
"https://reseed.stormycloud.org/i2pseeds.su3", "https://reseed.diva.exchange/i2pseeds.su3",
"https://i2p.novg.net/i2pseeds.su3", "https://reseed2.i2p.net/i2pseeds.su3",
]
///|
/// Reseeds `NetDb` from verified public I2P HTTPS reseed servers until >= 20
/// routers are imported or all built-in URLs have been tried.
pub fn Router::auto_reseed(self : Router) -> Int32 {
let mut total = 0
for url in default_reseed_urls {
let n = self.reseed_from_url(url) catch {
_ => {
println(" Reseed skipped (\{url})")
continue
}
}
println(" Reseeded \{n} peer(s) from \{url}")
total += n
if total >= 20 {
break
}
}
total
}
///|
/// Loads `hostname=base64dest` addressbook aliases from a local `hosts.txt` file.
pub fn Router::load_hosts_file(
self : Router,
path : String,
) -> Int32 raise RouterError {
let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) }
let text = @encoding.utf8_bytes_to_string(raw) catch {
_ => raise Protocol("hosts file is not valid UTF-8")
}
let mut count = 0
for line_view in text.split("\n") {
let line = line_view.to_owned().trim().to_owned()
if line.length() == 0 || line.has_prefix("#") {
continue
}
let mut eq = -1
for i = 0; i < line.length(); i = i + 1 {
if line[i] == '=' {
eq = i
break
}
}
if eq > 0 && eq + 1 < line.length() {
let host = line[:eq].to_owned().trim().to_owned()
let dest_b64 = line[eq + 1:].to_owned().trim().to_owned()
if host.length() > 0 && dest_b64.length() > 100 {
self.register_alias(host, dest_b64)
count += 1
}
}
}
count
}
///|
fn Router::is_usable_public_peer(
self : Router,
h : @common.Hash,
ri : @common.RouterInfo,
now_ms : UInt64,
) -> Bool {
if h == self.router_hash() ||
self.is_peer_backed_off(h, now_ms) ||
ri.identity.inner.crypto_type() != X25519 {
return false
}
let info = @ntcp2_net.extract_ntcp2_peer(ri) catch { _ => return false }
if info.host.contains(":") ||
info.host == "127.0.0.1" ||
info.host == "0.0.0.0" {
return false
}
true
}
///|
fn Router::is_inbound_build_pending(self : Router) -> Int32 {
let mut n = 0
for pb in self.pending_builds {
if pb.direction == Inbound {
n += 1
}
}
n
}
///|
fn Router::is_outbound_build_pending(self : Router) -> Int32 {
let mut n = 0
for pb in self.pending_builds {
if pb.direction == Outbound {
n += 1
}
}
n
}
///|
fn is_peer_in_list(h : @common.Hash, list : Array[@common.Hash]) -> Bool {
for x in list {
if x == h {
return true
}
}
false
}
///|
fn Router::pick_usable_peers(
self : Router,
count : Int32,
excluded : Array[@common.Hash],
now_ms : UInt64,
) -> Array[@common.Hash] {
let out : Array[@common.Hash] = []
let total = self.netdb.routers.length()
if total == 0 || count <= 0 {
return out
}
let rbytes = @ntcp2_net.random_bytes(4) catch { _ => Bytes::make(4, b'\x01') }
let start = u32_from_be_prefix(rbytes).reinterpret_as_int() % total
for step = 0; step < total && out.length() < count; step = step + 1 {
let idx = (start + step) % total
let (h, ri) = self.netdb.routers[idx]
if is_peer_in_list(h, excluded) || is_peer_in_list(h, out) {
continue
}
if self.is_usable_public_peer(h, ri, now_ms) {
out.push(h)
}
}
out
}
///|
fn Router::pick_connected_hop(
self : Router,
excluded : Array[@common.Hash],
now_ms : UInt64,
) -> @common.Hash? {
if self.peers.length() == 0 {
return None
}
let rbytes = @ntcp2_net.random_bytes(4) catch { _ => Bytes::make(4, b'\x01') }
let start = u32_from_be_prefix(rbytes).reinterpret_as_int() %
self.peers.length()
for step = 0; step < self.peers.length(); step = step + 1 {
let idx = (start + step) % self.peers.length()
let ph = self.peers[idx].hash
if is_peer_in_list(ph, excluded) || self.is_peer_backed_off(ph, now_ms) {
continue
}
match self.netdb.get_router_info(ph) {
Some(ri) =>
if ri.identity.inner.crypto_type() == X25519 {
return Some(ph)
}
None => ()
}
}
None
}
///|
fn Router::step_public_bootstrap(self : Router) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms()
if now_ms < self.last_bootstrap_ms + 1500UL {
return
}
self.last_bootstrap_ms = now_ms
// 1. Keep up to 6 live outbound NTCP2 TCP peer sessions active
let target_peers = 6
if self.peers.length() + self.pending_dials.length() < target_peers {
let excl : Array[@common.Hash] = []
for p in self.peers {
excl.push(p.hash)
}
for pd in self.pending_dials {
excl.push(pd.peer_hash)
}
let need = target_peers -
(self.peers.length() + self.pending_dials.length())
let to_dial = self.pick_usable_peers(need, excl, now_ms)
for ph in to_dial {
self.ensure_peer_dial(ph)
}
}
// 2. Maintain >= 2 Inbound tunnels (behind NAT: 1-hop on connected peers first,
// then upgrade to `tunnel_hops`-hop `[IBGW -> connected_last_hop -> self]` once Outbound exists)
let pending_in = self.is_inbound_build_pending()
let mut in_full = 0
for t in self.tunnels.inbound {
if t.hops.length() >= self.tunnel_hops {
in_full += 1
}
}
let need_in_bootstrap = self.tunnels.inbound.length() + pending_in < 2
let need_in_upgrade = self.tunnel_hops >= 2 &&
self.tunnels.inbound.length() >= 1 &&
self.tunnels.outbound.length() >= 1 &&
in_full < 2 &&
self.tunnels.inbound.length() + pending_in < 4
if (need_in_bootstrap || need_in_upgrade) && pending_in < 2 {
let excl_in : Array[@common.Hash] = []
for t in self.tunnels.inbound {
if t.hops.length() > 0 {
excl_in.push(t.hops[t.hops.length() - 1].router_hash)
}
}
for pb in self.pending_builds {
if pb.direction == Inbound && pb.hops.length() > 0 {
excl_in.push(pb.hops[pb.hops.length() - 1].router_hash)
}
}
match self.pick_connected_hop(excl_in, now_ms) {
Some(h0) =>
if self.tunnel_hops >= 2 &&
self.tunnels.inbound.length() >= 1 &&
self.tunnels.outbound.length() >= 1 {
let out_t = self.tunnels.outbound[0]
let excl_ibgw : Array[@common.Hash] = [h0]
if out_t.hops.length() > 0 {
excl_ibgw.push(out_t.hops[out_t.hops.length() - 1].router_hash)
}
let ibgw_opt = match self.pick_connected_hop(excl_ibgw, now_ms) {
Some(c) => Some(c)
None => {
let usables = self.pick_usable_peers(1, excl_ibgw, now_ms)
if usables.length() == 1 {
Some(usables[0])
} else {
None
}
}
}
match ibgw_opt {
Some(ibgw) => {
let _ = self.build_tunnel(
[ibgw, h0],
Inbound,
outbound_via=Some(out_t),
) catch {
_ => 0U
}
}
None => ()
}
} else {
let _ = self.build_tunnel([h0], Inbound) catch { _ => 0U }
}
None => ()
}
}
// 3. Maintain >= 2 Outbound tunnels (replying via an active Inbound tunnel)
let pending_out = self.is_outbound_build_pending()
if self.tunnels.inbound.length() >= 1 &&
self.tunnels.outbound.length() + pending_out < 2 &&
pending_out < 3 {
let reply_in = self.tunnels.inbound[0]
if reply_in.hops.length() > 0 {
let reply_ibgw = reply_in.hops[0].router_hash
let excl_out : Array[@common.Hash] = [reply_ibgw]
for pb in self.pending_builds {
if pb.direction == Outbound {
for h in pb.hops {
excl_out.push(h.router_hash)
}
}
}
if self.tunnel_hops >= 2 {
match self.pick_connected_hop(excl_out, now_ms) {
Some(h0) => {
excl_out.push(h0)
let obep_opt = match self.pick_connected_hop(excl_out, now_ms) {
Some(c) => Some(c)
None => {
let obeps = self.pick_usable_peers(1, excl_out, now_ms)
if obeps.length() == 1 {
Some(obeps[0])
} else {
None
}
}
}
match obep_opt {
Some(obep) => {
let _ = self.build_tunnel(
[h0, obep],
Outbound,
reply_tunnel=Some(reply_in),
) catch {
_ => 0U
}
}
None => ()
}
}
None => ()
}
} else {
// Prefer an OBEP peer != reply_ibgw; if connected peer available use it, else any usable peer
match self.pick_connected_hop(excl_out, now_ms) {
Some(h0) => {
let _ = self.build_tunnel(
[h0],
Outbound,
reply_tunnel=Some(reply_in),
) catch {
_ => 0U
}
}
None => {
let obeps = self.pick_usable_peers(1, excl_out, now_ms)
if obeps.length() == 1 {
let _ = self.build_tunnel(
[obeps[0]],
Outbound,
reply_tunnel=Some(reply_in),
) catch {
_ => 0U
}
}
}
}
}
}
}
// 4. Periodic NetDB exploration once tunnels are up to learn additional live floodfills
if self.tunnels.inbound.length() >= 1 &&
self.tunnels.outbound.length() >= 1 &&
(self.last_explore_ms == 0UL || now_ms > self.last_explore_ms + 30000UL) {
self.last_explore_ms = now_ms
let rkey = @common.Hash::from_bytes(next_rand_32()) catch {
_ => self.router_hash()
}
self.start_background_lookup(rkey, 3)
}
}
+76 -10
View File
@@ -47,6 +47,9 @@ pub struct Router {
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
@@ -63,6 +66,11 @@ pub struct Router {
priv bridges : Array[StreamBridge]
priv remote_bridges : Array[RemoteStreamBridge]
priv aliases : Array[(String, String)] // hostname -> pub_b64
priv failed_peers : Array[(@common.Hash, UInt64)] // (router_hash, retry_after_ms)
priv mut lease_rr : Int32
priv mut outbound_rr : Int32
priv mut last_bootstrap_ms : UInt64
priv mut last_explore_ms : UInt64
}
///|
@@ -128,10 +136,15 @@ fn non_zero_random_bytes(n : Int32) -> Bytes {
///|
/// 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 {
@@ -142,6 +155,7 @@ pub fn Router::start(
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,
@@ -160,21 +174,34 @@ pub fn Router::start(
let id = @common.RouterIdentity::new_x25519_ed25519(
static_key.public_key,
ed_pub,
padding=id_pad,
) 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 caps = if floodfill { "LRf" } else { "LR" }
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(b'\x03', "NTCP2", addr_opts)],
addresses: [@common.RouterAddress::new(addr_cost, "NTCP2", addr_opts)],
options: @common.Mapping::from_entries([
("caps", caps),
("netId", "2"),
@@ -191,6 +218,13 @@ pub fn Router::start(
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
}
{
ed_seed,
static_key,
@@ -201,6 +235,9 @@ pub fn Router::start(
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,
@@ -217,9 +254,34 @@ pub fn Router::start(
bridges: [],
remote_bridges: [],
aliases: [],
failed_peers: [],
lease_rr: 0,
outbound_rr: 0,
last_bootstrap_ms: 0UL,
last_explore_ms: 0UL,
}
}
///|
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()
@@ -404,7 +466,8 @@ fn Router::handle_i2np_message(
TunnelGateway(tunnel_id~, data~) =>
self.handle_tunnel_gateway(tunnel_id, data, now_sec)
Garlic(data~) =>
if !self.try_handle_lookup_garlic_reply(data, now_sec) {
if !self.try_handle_build_garlic_reply(data) &&
!self.try_handle_lookup_garlic_reply(data, now_sec) {
self.handle_incoming_garlic(data, now_sec)
}
_ => ()
@@ -448,6 +511,9 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
}
self.poll_netdb_lookups()
self.poll_tunnel_builds()
if self.public_mode {
self.step_public_bootstrap()
}
if self.step_bridges() {
did_work = true
}
+57
View File
@@ -299,3 +299,60 @@ test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B
bob_acc.shutdown_write()
assert_eq(pump_read_until_eof(alice_data, rs), b"tunneled-ok")
}
///|
test "Proposal 157 Outbound tunnel replying via Inbound tunnel with OBEP ECIES Garlic" {
let router_b = @router.Router::start({
sam_host: "127.0.0.1",
sam_port: 0,
ntcp2_host: "127.0.0.1",
ntcp2_port: 0,
})
defer router_b.close()
let router_c = @router.Router::start({
sam_host: "127.0.0.1",
sam_port: 0,
ntcp2_host: "127.0.0.1",
ntcp2_port: 0,
})
defer router_c.close()
let router_a = @router.Router::start({
sam_host: "127.0.0.1",
sam_port: 0,
ntcp2_host: "127.0.0.1",
ntcp2_port: 0,
})
defer router_a.close()
for r in [router_a, router_b, router_c] {
let _ = r.netdb.store_router_info(router_a.router_info)
let _ = r.netdb.store_router_info(router_b.router_info)
let _ = r.netdb.store_router_info(router_c.router_info)
}
let rs = [router_a, router_b, router_c]
let in_tid = router_a.build_tunnel([router_b.router_hash()], Inbound)
for _i = 0; _i < 500; _i = _i + 1 {
step_routers(rs, 1)
if router_a.has_tunnel(in_tid) {
break
}
}
assert_true(router_a.has_tunnel(in_tid))
let reply_in = router_a.tunnels.inbound[0]
let out_tid = router_a.build_tunnel(
[router_c.router_hash()],
Outbound,
reply_tunnel=Some(reply_in),
)
let mut built_out = false
for _i = 0; _i < 800; _i = _i + 1 {
step_routers(rs, 1)
if router_a.has_tunnel(out_tid) {
built_out = true
break
}
}
assert_true(built_out)
}
+166 -25
View File
@@ -10,6 +10,7 @@ priv struct SamSession {
pub_b64 : String
b32 : String
virtual_tid : UInt32
x25519_pub : Bytes?
ed_seed : Bytes?
ratchet : @ratchet.RatchetSessionManager?
stream_mgr : @streaming.StreamManager?
@@ -42,7 +43,7 @@ priv struct RemoteStreamBridge {
peer_static_pub : Bytes
lease_gw : @common.Hash
lease_tid : UInt32
send_stream_id : UInt32
local_stream_id : UInt32
mut state : Int32 // 0 = waiting_syn_ack, 1 = open
silent : Bool
mut local_eof : Bool
@@ -53,8 +54,9 @@ priv struct RemoteStreamBridge {
}
///|
/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and
/// returns `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`.
/// Generates a valid canonical 391-byte Ed25519 I2P Destination (sig=7, crypto=0 ElGamal)
/// plus paired X25519 encryption keypair for LeaseSet2, and returns
/// `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`.
fn generate_transient_destination() -> (
@common.Destination,
String,
@@ -68,12 +70,8 @@ fn generate_transient_destination() -> (
}
let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
let x_kp = @noise.KeyPair::from_private(x_priv) catch { e => raise Noise(e) }
let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) }
let dest = @common.Destination::new_x25519_ed25519(
x_kp.public_key,
ed_pub,
padding=pad,
) catch {
let pad = @ntcp2_net.random_bytes(352) catch { e => raise Net(e) }
let dest = @common.Destination::new_ed25519(ed_pub, padding=pad) catch {
e => raise Common(e)
}
let pub_bytes = dest.to_bytes()
@@ -190,6 +188,9 @@ fn Router::flush_stream_outbound(
fallback_tid : UInt32,
send_ls2~ : Bool = false,
) -> Unit {
if peer_static_pub.length() != 32 {
return
}
let packets = conn.drain_outbound()
if packets.length() == 0 {
return
@@ -203,8 +204,18 @@ fn Router::flush_stream_outbound(
let mut tid = fallback_tid
match self.netdb.get_lease_set2(peer_hash, now_sec) {
Some(ls2) if ls2.leases.length() > 0 => {
gw = ls2.leases[0].tunnel_gw
tid = ls2.leases[0].tunnel_id
let valid : Array[@common.Lease2] = []
for l in ls2.leases {
if l.end_date_sec > now_sec {
valid.push(l)
}
}
let pool = if valid.length() > 0 { valid } else { ls2.leases }
let rr = if self.lease_rr < 0 { 0 } else { self.lease_rr }
self.lease_rr = (self.lease_rr + 1) & 0x3FFFFFFF
let chosen = pool[rr % pool.length()]
gw = chosen.tunnel_gw
tid = chosen.tunnel_id
}
_ => ()
}
@@ -251,6 +262,11 @@ fn Router::flush_stream_outbound(
) catch {
_ => continue
}
if self.debug {
println(
"[debug] send Garlic (\{wire.length()}B, ls2=\{send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}",
)
}
self.send_routed_i2np(gw, Some(tid), Garlic(data=wire))
}
}
@@ -263,6 +279,8 @@ fn Router::initiate_remote_stream(
target_dest : @common.Destination,
ls2 : @common.LeaseSet2,
silent : Bool,
from_port~ : UInt32 = 0U,
to_port~ : UInt32 = 0U,
) -> Unit {
let c = self.sam_clients[client_idx]
if c.closed {
@@ -299,9 +317,14 @@ fn Router::initiate_remote_stream(
return
}
let lease = ls2.leases[0]
if self.debug {
println(
"[debug] initiating remote stream to \{target_dest.b32_address()} leases=\{ls2.leases.length()} keys=\{ls2.encryption_keys.length()} first_gw=\{lease.tunnel_gw.to_b32_address()} tid=\{lease.tunnel_id}",
)
}
let now_ms = @ntcp2_net.unix_time_ms()
let peer_hash = target_dest.hash()
let conn = mgr.connect(peer_hash, now_ms) catch {
let conn = mgr.connect(peer_hash, now_ms, from_port~, to_port~) catch {
_ => {
if !silent {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR")
@@ -325,7 +348,7 @@ fn Router::initiate_remote_stream(
peer_static_pub: peer_static,
lease_gw: lease.tunnel_gw,
lease_tid: lease.tunnel_id,
send_stream_id: conn.send_stream_id,
local_stream_id: conn.local_stream_id,
state: 0,
silent,
local_eof: false,
@@ -369,6 +392,8 @@ fn Router::finish_remote_stream_connect(
ls2.destination,
ls2,
lk.silent,
from_port=lk.from_port,
to_port=lk.to_port,
)
}
@@ -387,6 +412,11 @@ fn Router::handle_incoming_garlic(
let res = Some(ratchet.decrypt_incoming(garlic_data)) catch { _ => None }
match res {
Some((_remote_static, blocks)) => {
if self.debug {
println(
"[debug] Garlic decrypted for session \{sess.id} (\{blocks.length()} blocks)",
)
}
// 1. Apply DatabaseStore cloves first so peer LeaseSet2 is cached for reply
for blk in blocks {
match blk {
@@ -421,9 +451,11 @@ fn Router::handle_incoming_garlic(
Data(data~) =>
match sess.stream_mgr {
Some(mgr) => {
let prev_streams = mgr.streams.length()
let conn_opt = mgr.handle_incoming_i2cp(data, now_ms) catch {
_ => None
}
let send_ls2_now = mgr.streams.length() > prev_streams
match conn_opt {
Some(conn) =>
// Immediately send any generated SYN-ACK or ACK back if peer LeaseSet2 is known
@@ -442,7 +474,7 @@ fn Router::handle_incoming_garlic(
pstat,
ls2.leases[0].tunnel_gw,
ls2.leases[0].tunnel_id,
send_ls2=true,
send_ls2=send_ls2_now,
)
None => ()
}
@@ -467,6 +499,40 @@ fn Router::handle_incoming_garlic(
None => ()
}
}
// Fallback: router-targeted Noise_N Garlic message addressed to self.static_key
let router_blocks = Some(
@ratchet.decrypt_router_garlic(self.static_key, garlic_data),
) catch {
_ => None
}
match router_blocks {
Some(blocks) =>
for blk in blocks {
match blk {
GarlicClove(i2np_short~, ..) => {
let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch {
_ => None
}
match decoded {
Some((hdr, inner)) => self.handle_i2np_message(None, hdr, inner)
None => ()
}
}
_ => ()
}
}
None =>
if self.debug {
let tag_hex = if garlic_data.length() >= 8 {
@encoding.hex_encode(garlic_data[:8].to_owned())
} else {
""
}
println(
"[debug] unhandled incoming Garlic (\{garlic_data.length()}B tag=\{tag_hex} sessions=\{self.sessions.length()})",
)
}
}
}
///|
@@ -645,6 +711,10 @@ fn Router::handle_sam_command(
)
None => None
}
let x25519_pub = match opt_xkp {
Some(xkp) => Some(xkp.public_key)
None => None
}
let sess : SamSession = {
id: sid,
dest,
@@ -652,6 +722,7 @@ fn Router::handle_sam_command(
pub_b64,
b32,
virtual_tid: self.alloc_tunnel_id(),
x25519_pub,
ed_seed: opt_seed,
ratchet,
stream_mgr,
@@ -713,6 +784,8 @@ fn Router::handle_sam_command(
Some(v) => v.to_lower() == "true"
None => false
}
let from_port = parse_sam_port(msg.get("FROM_PORT"))
let to_port = parse_sam_port(msg.get("TO_PORT"))
// 1. Check co-hosted local session fast path first
match self.find_session_by_pub(dest_b64) {
Some(target_sess) => {
@@ -773,7 +846,13 @@ fn Router::handle_sam_command(
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(ls2) =>
self.initiate_remote_stream(
client_idx, caller_sess, target_dest, ls2, silent,
client_idx,
caller_sess,
target_dest,
ls2,
silent,
from_port~,
to_port~,
)
None =>
if !self.start_netdb_lookup(
@@ -783,6 +862,8 @@ fn Router::handle_sam_command(
"",
caller_sess.id,
silent,
from_port~,
to_port~,
) {
if !silent {
let _ = send_sam_line(
@@ -914,19 +995,53 @@ fn Router::step_bridges(self : Router) -> Bool {
did_work
}
///|
fn parse_sam_port(s_opt : String?) -> UInt32 {
let s = match s_opt {
Some(v) => v
None => return 0U
}
if s.length() == 0 {
return 0U
}
let mut val = 0U
for ch in s {
if ch < '0' || ch > '9' {
return 0U
}
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
if val > 65535U {
return 0U
}
}
val
}
///|
fn find_stream_by_id(
mgr : @streaming.StreamManager,
sid : UInt32,
) -> @streaming.StreamConnection? {
for s in mgr.streams {
if s.send_stream_id == sid {
if s.local_stream_id == sid {
return Some(s)
}
}
None
}
///|
fn remove_stream_by_id(mgr : @streaming.StreamManager, sid : UInt32) -> Unit {
let mut i = 0
while i < mgr.streams.length() {
if mgr.streams[i].local_stream_id == sid {
let _ = mgr.streams.remove(i)
} else {
i += 1
}
}
}
///|
fn Router::step_remote_bridges(self : Router) -> Bool {
let now_ms = @ntcp2_net.unix_time_ms()
@@ -951,16 +1066,19 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
None => continue
}
let peer_ls2 = self.netdb.get_lease_set2(conn.remote_hash, now_sec)
let fallback_key = if peer_dest.inner.crypto_type() == X25519 {
peer_dest.inner.crypto_public_key()
} else {
b""
}
let (gw, tid, peer_static) = match peer_ls2 {
Some(l) if l.leases.length() > 0 =>
(
l.leases[0].tunnel_gw,
l.leases[0].tunnel_id,
extract_x25519_key(l).unwrap_or(
peer_dest.inner.crypto_public_key(),
),
extract_x25519_key(l).unwrap_or(fallback_key),
)
_ => (self.router_hash(), 0U, peer_dest.inner.crypto_public_key())
_ => (self.router_hash(), 0U, fallback_key)
}
if !c.accept_silent {
let _ = send_sam_line(c.sock, peer_dest.to_base64())
@@ -979,7 +1097,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
peer_static_pub: peer_static,
lease_gw: gw,
lease_tid: tid,
send_stream_id: conn.send_stream_id,
local_stream_id: conn.local_stream_id,
state: 1,
silent: c.accept_silent,
local_eof: false,
@@ -1005,13 +1123,14 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
}
// 2. Pump retransmits & flush outbound packets (ACKs, SYN-ACKs, retransmissions)
let rto_ms = if self.public_mode { 3500UL } else { 1500UL }
for sess in self.sessions {
let mgr = match sess.stream_mgr {
Some(m) => m
None => continue
}
for conn in mgr.streams {
let _ = conn.poll_retransmits(now_ms, rto_ms=1500UL) catch { _ => () }
let _ = conn.poll_retransmits(now_ms, rto_ms~) catch { _ => () }
match self.netdb.get_lease_set2(conn.remote_hash, now_sec) {
Some(ls2) if ls2.leases.length() > 0 =>
match extract_x25519_key(ls2) {
@@ -1023,7 +1142,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
pstat,
ls2.leases[0].tunnel_gw,
ls2.leases[0].tunnel_id,
send_ls2=false,
send_ls2=conn.state == SynSent,
)
None => ()
}
@@ -1033,6 +1152,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
}
// 3. Pump bidirectional SAM socket <-> StreamConnection I/O
let connect_timeout_ms = if self.public_mode { 30000UL } else { 12000UL }
let mut ri = 0
while ri < self.remote_bridges.length() {
let br = self.remote_bridges[ri]
@@ -1054,7 +1174,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
continue
}
}
let conn = match find_stream_by_id(mgr, br.send_stream_id) {
let conn = match find_stream_by_id(mgr, br.local_stream_id) {
Some(c) => c
None => {
br.sock.close()
@@ -1069,14 +1189,26 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
conn.state == Closed {
br.state = 1
did_work = true
if self.debug {
println(
"[debug] Streaming established to \{br.peer_hash.to_b32_address()} (local_sid=\{br.local_stream_id})",
)
}
if !br.silent {
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=OK")
}
} else if conn.state == Reset || now_ms > br.started_ms + 12000UL {
} else if conn.state == Reset ||
now_ms > br.started_ms + connect_timeout_ms {
did_work = true
if self.debug {
println(
"[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}",
)
}
if !br.silent {
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
}
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
@@ -1087,6 +1219,11 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
let avail = conn.read_available()
if avail.length() > 0 {
did_work = true
if self.debug {
println(
"[debug] stream \{br.local_stream_id} recv \{avail.length()}B",
)
}
br.sock.write_all(avail) catch {
_ => {
br.local_eof = true
@@ -1096,6 +1233,9 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
}
if conn.is_eof() && !br.remote_eof_sent {
did_work = true
if self.debug {
println("[debug] stream \{br.local_stream_id} EOF")
}
br.sock.shutdown_write()
br.remote_eof_sent = true
}
@@ -1134,6 +1274,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
)
if br.local_eof && conn.is_eof() && !conn.has_unacked() {
did_work = true
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
+246 -20
View File
@@ -11,6 +11,8 @@ priv struct PendingTunnelBuild {
created_sec : UInt32
expires_sec : UInt32
started_ms : UInt64
obep_garlic_key : Bytes?
obep_garlic_tag : Bytes?
}
///|
@@ -33,11 +35,15 @@ pub fn Router::has_tunnel(self : Router, tunnel_id : UInt32) -> Bool {
/// Initiates a Proposal 157 `ShortTunnelBuild` along `hop_hashes` (1..8 routers).
/// Returns the allocated local tunnel ID; drive completion with `Router::step()`
/// and check readiness via `Router::has_tunnel(tid)`.
/// When `reply_tunnel` is supplied for an `Outbound` tunnel, the OBEP encrypts the
/// `ShortTunnelBuildReply` with `RGarlicKeyAndTag` and routes it via that Inbound tunnel.
pub fn Router::build_tunnel(
self : Router,
hop_hashes : Array[@common.Hash],
direction : @tunnel.TunnelDirection,
expiration_sec~ : UInt32 = 600U,
reply_tunnel~ : @tunnel.Tunnel? = None,
outbound_via~ : @tunnel.Tunnel? = None,
) -> UInt32 raise RouterError {
let hop_count = hop_hashes.length()
if hop_count < 1 || hop_count > 8 {
@@ -56,6 +62,9 @@ pub fn Router::build_tunnel(
Some(r) => r
None => raise Protocol("missing RouterInfo for tunnel hop")
}
if ri.identity.inner.crypto_type() != X25519 {
raise Protocol("tunnel hop lacks X25519 crypto identity type")
}
let x_pub = ri.identity.inner.crypto_public_key()
if x_pub.length() != 32 {
raise Protocol("tunnel hop lacks X25519 identity key")
@@ -65,6 +74,20 @@ pub fn Router::build_tunnel(
}
let total_slots = if hop_count <= 4 { 4 } else { 8 }
let slot_perm : Array[Int32] = Array(capacity=total_slots)
for s = 0; s < total_slots; s = s + 1 {
slot_perm.push(s)
}
let rand_perm = @ntcp2_net.random_bytes(total_slots) catch {
_ => Bytes::make(total_slots, b'\x01')
}
for k = total_slots - 1; k > 0; k = k - 1 {
let ridx = rand_perm[k].to_int() % (k + 1)
let tmp = slot_perm[k]
slot_perm[k] = slot_perm[ridx]
slot_perm[ridx] = tmp
}
let specs : Array[@tunnel.ShortHopBuildSpec] = Array(capacity=hop_count)
let next_tids : Array[UInt32] = Array(capacity=hop_count)
for i = 0; i < hop_count; i = i + 1 {
@@ -73,11 +96,19 @@ pub fn Router::build_tunnel(
} else if direction == Inbound {
local_tid
} else {
0U
match reply_tunnel {
Some(in_t) if in_t.hops.length() > 0 => in_t.hops[0].receive_tunnel_id
_ => 0U
}
}
next_tids.push(next_tid)
let next_ident = if i + 1 < hop_count {
hop_hashes[i + 1]
} else if direction == Outbound {
match reply_tunnel {
Some(in_t) if in_t.hops.length() > 0 => in_t.hops[0].router_hash
_ => self.router_hash()
}
} else {
self.router_hash()
}
@@ -93,8 +124,13 @@ pub fn Router::build_tunnel(
e => raise Noise(e)
}
let pad = @ntcp2_net.random_bytes(8) catch { _ => b"" }
let hop_send_msg_id = if i + 1 < hop_count {
self.alloc_msg_id()
} else {
build_msg_id
}
specs.push({
slot_idx: i,
slot_idx: slot_perm[i],
hop_ident: hop_hashes[i],
hop_static_pub: hop_static_pubs[i],
ephemeral: ephem,
@@ -106,15 +142,15 @@ pub fn Router::build_tunnel(
layer_enc_type: b'\x00',
request_time_min: req_time_min,
request_expiration_sec: expiration_sec,
send_message_id: build_msg_id,
send_message_id: hop_send_msg_id,
options: @common.Mapping::new(),
},
padding: pad,
})
}
let dummies : Array[Bytes] = []
for _d = hop_count; _d < total_slots; _d = _d + 1 {
let dummies : Array[Bytes] = Array(capacity=total_slots)
for _d = 0; _d < total_slots; _d = _d + 1 {
let dummy = @ntcp2_net.random_bytes(218) catch {
_ => Bytes::make(218, b'\x5a')
}
@@ -137,6 +173,13 @@ pub fn Router::build_tunnel(
iv_key: keys.iv_key,
})
}
let last_keys = hop_slots_and_keys[hop_count - 1].1
let (obep_garlic_key, obep_garlic_tag) = if direction == Outbound &&
reply_tunnel is Some(_) {
(last_keys.garlic_key, last_keys.garlic_tag)
} else {
(None, None)
}
self.pending_builds.push({
tunnel_id: local_tid,
direction,
@@ -146,12 +189,59 @@ pub fn Router::build_tunnel(
created_sec: now_sec,
expires_sec: now_sec + expiration_sec,
started_ms: now_ms,
obep_garlic_key,
obep_garlic_tag,
})
let _ = self.send_i2np_to_peer(
hop_hashes[0],
ShortTunnelBuild(records~),
msg_id_override=Some(build_msg_id),
)
let build_payload : @i2np.I2npPayload = ShortTunnelBuild(records~)
let outer_mid = if hop_count == 1 && direction == Inbound {
Some(build_msg_id)
} else {
None
}
match outbound_via {
Some(out_t) if self.has_tunnel(out_t.id) => {
let obep_differs = out_t.hops.length() == 0 ||
out_t.hops[out_t.hops.length() - 1].router_hash != hop_hashes[0]
if obep_differs {
let ephem_n = @noise.KeyPair::from_private(next_rand_32()) catch {
e => raise Noise(e)
}
let clove = @ratchet.garlic_clove_block(
Local,
build_msg_id,
now_sec + 60U,
build_payload,
) catch {
_ => raise Protocol("garlic_clove failed")
}
let enc = @ratchet.encrypt_router_garlic(hop_static_pubs[0], ephem_n, [
DateTime(now_sec),
clove,
]) catch {
_ => raise Protocol("encrypt_router_garlic failed")
}
self.send_through_tunnel(
out_t.id,
Router(router_hash=hop_hashes[0]),
Garlic(data=enc),
)
} else {
self.send_through_tunnel(
out_t.id,
Router(router_hash=hop_hashes[0]),
build_payload,
msg_id_override=outer_mid,
)
}
}
_ => {
let _ = self.send_i2np_to_peer(
hop_hashes[0],
build_payload,
msg_id_override=outer_mid,
)
}
}
local_tid
}
@@ -162,6 +252,7 @@ pub fn Router::send_through_tunnel(
outbound_tunnel_id : UInt32,
target : @tunnel.DeliveryTarget,
payload : @i2np.I2npPayload,
msg_id_override~ : UInt32? = None,
) -> Unit raise RouterError {
let mut out_tun : @tunnel.Tunnel? = None
for t in self.tunnels.outbound {
@@ -178,7 +269,10 @@ pub fn Router::send_through_tunnel(
raise Protocol("outbound tunnel has zero hops")
}
let now_ms = @ntcp2_net.unix_time_ms()
let inner_mid = self.alloc_msg_id()
let inner_mid = match msg_id_override {
Some(id) => id
None => self.alloc_msg_id()
}
let std_bytes = @i2np.encode_standard_message(
inner_mid,
now_ms + 60000UL,
@@ -230,13 +324,30 @@ fn Router::try_complete_pending_tunnel_build(
records,
pb.hop_slots_and_keys,
) catch {
_ => return true
}
for c in codes {
if c != b'\x00' {
_ => {
if self.debug {
println("[debug] tunnel build \{pb.tunnel_id} reply decrypt failed")
}
return true
}
}
let mut all_ok = true
for hi = 0; hi < codes.length(); hi = hi + 1 {
if codes[hi] != b'\x00' {
all_ok = false
if self.public_mode && hi < pb.hops.length() {
self.mark_peer_failed(pb.hops[hi].router_hash, 45000UL)
}
if self.debug {
println(
"[debug] tunnel build \{pb.tunnel_id} hop \{hi} rejected code=\{codes[hi].to_int()}",
)
}
}
}
if !all_ok {
return true
}
let dir = pb.direction
self.tunnels.add_tunnel({
id: pb.tunnel_id,
@@ -245,12 +356,82 @@ fn Router::try_complete_pending_tunnel_build(
created_sec: pb.created_sec,
expires_sec: pb.expires_sec,
})
if self.debug {
let kind_s = match dir {
Inbound => "Inbound"
Outbound => "Outbound"
}
println(
"[debug] built \{kind_s} tunnel \{pb.tunnel_id} (\{pb.hops.length()}h) [in=\{self.tunnels.inbound_count()} out=\{self.tunnels.outbound_count()}]",
)
}
if dir == Inbound {
self.republish_all_sessions()
}
true
}
///|
fn Router::try_handle_build_garlic_reply(
self : Router,
garlic_data : Bytes,
) -> Bool {
if garlic_data.length() < 24 {
return false
}
let wire_tag = garlic_data[:8].to_owned()
for i = 0; i < self.pending_builds.length(); i = i + 1 {
let pb = self.pending_builds[i]
match (pb.obep_garlic_key, pb.obep_garlic_tag) {
(Some(gk), Some(gtag)) =>
if @crypto.ct_eq(wire_tag, gtag) {
let blocks = @ratchet.decrypt_ecies_lookup_reply(
gk, gtag, garlic_data,
) catch {
_ => return false
}
for blk in blocks {
match blk {
GarlicClove(i2np_short~, ..) => {
let decoded = Some(
@ratchet.decode_garlic_clove_i2np(i2np_short),
) catch {
_ => None
}
match decoded {
Some((hdr, ShortTunnelBuildReply(records~))) => {
let _ = hdr
let _ = self.try_complete_pending_tunnel_build(
pb.build_msg_id,
records,
)
return true
}
Some((hdr, inner)) => {
let _ = self.try_complete_pending_tunnel_build(
pb.build_msg_id,
match inner {
ShortTunnelBuild(records~) => records
_ => []
},
)
let _ = hdr
return true
}
None => ()
}
}
_ => ()
}
}
return true
}
_ => ()
}
}
false
}
///|
fn Router::handle_short_tunnel_build(
self : Router,
@@ -292,10 +473,32 @@ fn Router::handle_short_tunnel_build(
records=out_records,
)
if rec.next_tunnel_id != 0U {
let outer_payload : @i2np.I2npPayload = if rec.next_ident !=
self.router_hash() {
match (keys.garlic_key, keys.garlic_tag) {
(Some(gk), Some(gt)) => {
let clove = @ratchet.garlic_clove_block(
Local,
rec.send_message_id,
now_sec + 60U,
reply_payload,
) catch {
_ => return
}
let enc = @ratchet.encrypt_ecies_lookup_reply(gk, gt, [clove]) catch {
_ => return
}
Garlic(data=enc)
}
_ => reply_payload
}
} else {
reply_payload
}
let std = @i2np.encode_standard_message(
rec.send_message_id,
@ntcp2_net.unix_time_ms() + 60000UL,
reply_payload,
outer_payload,
) catch {
_ => return
}
@@ -373,7 +576,14 @@ fn Router::consume_cleartext_cell(
cleartext_cell : Bytes,
now_sec : UInt32,
) -> Unit {
let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch { _ => return }
let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch {
_ => {
if self.debug {
println("[debug] unpack_tunnel_cell checksum/format error")
}
return
}
}
for frag in frags {
match self.reassembler.push(frag) {
Some((target, full_payload)) =>
@@ -393,7 +603,14 @@ fn Router::handle_tunnel_data(
// 1. Check if we are the inbound tunnel endpoint (IBEP)
for in_t in self.tunnels.inbound {
if in_t.id == tunnel_id {
let clear = in_t.decrypt_inbound_cell(data) catch { _ => return }
let clear = in_t.decrypt_inbound_cell(data) catch {
_ => {
if self.debug {
println("[debug] inbound tunnel \{tunnel_id} decrypt error")
}
return
}
}
self.consume_cleartext_cell(clear, now_sec)
return
}
@@ -469,10 +686,19 @@ fn Router::poll_tunnel_builds(self : Router) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let _ = self.tunnels.prune_expired(now_sec)
let build_timeout = if self.public_mode { 20000UL } else { 10000UL }
let mut i = 0
while i < self.pending_builds.length() {
if now_ms > self.pending_builds[i].started_ms + 10000UL {
let _ = self.pending_builds.remove(i)
if now_ms > self.pending_builds[i].started_ms + build_timeout {
let timed_out = self.pending_builds.remove(i)
if self.public_mode {
for h in timed_out.hops {
self.mark_peer_failed(h.router_hash, 30000UL)
}
if self.debug {
println("[debug] tunnel build \{timed_out.tunnel_id} timed out")
}
}
} else {
i += 1
}