feat: implement NTCP2 protocol, native TCP transport, and live I2P interop

This commit is contained in:
nandi committed 2026-11-27 19:42:34 +00:00
1 parent dff69dfac6
commit e6d1c464dd
12 files changed
+2557 -2

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
///|
/// Live interop test against local `i2pd`'s `router.info` AND real public I2P NTCP2 peers
/// (when `/tmp/i2pd-interop/router.info` and `/tmp/i2pd-interop/seeds/peer_*.dat` exist).
test "live i2pd RouterInfo Ed25519 verify + real I2P NTCP2 handshake + Data Phase" {
// 1. Verify local i2pd's generated RouterInfo parsing & Ed25519 signature
let local_i2pd_ri_bytes = @ntcp2_net.read_file_bytes(
"/tmp/i2pd-interop/router.info",
) catch {
_ => return // skip when local i2pd interop fixture is not present
}
let local_i2pd_ri = @common.RouterInfo::decode(
@encoding.Reader::new(local_i2pd_ri_bytes),
)
assert_eq(local_i2pd_ri.verify_signature(), true)
let local_peer = @ntcp2_net.extract_ntcp2_peer(local_i2pd_ri)
assert_eq(local_peer.static_key.length(), 32)
assert_eq(local_peer.iv.length(), 16)
// 2. Create transient MoonBit router identity & signed RouterInfo
let ed_seed = @ntcp2_net.random_bytes(32)
let ed_pub = @crypto.ed25519_public_key(ed_seed)
let static_priv = @ntcp2_net.random_bytes(32)
let local_static = @noise.KeyPair::from_private(static_priv)
let local_iv = @ntcp2_net.random_bytes(16)
let local_id = @common.RouterIdentity::new_x25519_ed25519(
local_static.public_key,
ed_pub,
)
let addr_opts = @common.Mapping::from_entries([
("i", @encoding.base64_encode(local_iv)),
("s", @encoding.base64_encode(local_static.public_key)),
("v", "2"),
])
let local_ri : @common.RouterInfo = {
identity: local_id,
published: @ntcp2_net.unix_time_ms(),
addresses: [@common.RouterAddress::new(b'\x0e', "NTCP2", addr_opts)],
options: @common.Mapping::from_entries([
("caps", "LR"),
("netId", "2"),
("router.version", "0.9.64"),
]),
signature: b"",
}
let signed_local_ri = local_ri.sign_ed25519(ed_seed)
assert_eq(signed_local_ri.verify_signature(), true)
// 3. Complete a REAL NTCP2 handshake + Data Phase exchange against a live public I2P peer
let mut handshake_ok = false
let mut data_phase_ok = false
for idx = 0; idx < 15; idx = idx + 1 {
let path = "/tmp/i2pd-interop/seeds/peer_\{idx}.dat"
let raw = @ntcp2_net.read_file_bytes(path) catch { _ => continue }
let peer_ri = @common.RouterInfo::decode(@encoding.Reader::new(raw)) catch {
_ => continue
}
if !peer_ri.verify_signature() {
continue
}
// Prefer a floodfill peer so DatabaseLookup elicits a real Data Phase I2NP reply
match peer_ri.options.get("caps") {
Some(caps) => if !caps.contains("f") { continue }
None => continue
}
let peer = @ntcp2_net.extract_ntcp2_peer(peer_ri) catch { _ => continue }
// Skip IPv6 addresses in IPv4-only VM
if peer.host.contains(":") {
continue
}
let conn = @ntcp2_net.dial_ntcp2(
peer,
local_static,
signed_local_ri,
flood=false,
timeout_ms=5000,
) catch {
_ => continue
}
handshake_ok = true
println(
"HANDSHAKE OK with floodfill peer_\{idx} (\{peer.host}:\{peer.port})",
)
let now_sec = @ntcp2_net.unix_time_sec()
let lookup_ri = @i2np.I2npPayload::DatabaseLookup(
key=peer_ri.identity.hash(),
from=local_id.hash(),
flags=b'\x08', // direct reply, RouterInfo lookup
reply_tunnel_id=None,
excluded_peers=[],
)
let lookup_exp = @i2np.I2npPayload::DatabaseLookup(
key=@common.Hash::sha256(b"moon-i2p-probe"),
from=local_id.hash(),
flags=b'\x0c', // direct reply, exploration lookup
reply_tunnel_id=None,
excluded_peers=[],
)
conn.send_blocks([
DateTime(now_sec),
@ntcp2.i2np_block(4242U, now_sec + 60U, lookup_ri),
@ntcp2.i2np_block(4243U, now_sec + 60U, lookup_exp),
Padding(b"\x00\x00\x00\x00"),
]) catch {
_ => {
println("send_blocks failed")
conn.close()
continue
}
}
// Read at least one decrypted Data Phase frame back from the real I2P router
let blocks = conn.recv_blocks() catch {
e => {
match e {
Timeout => println("peer_\{idx} recv_blocks: Timeout")
Closed => println("peer_\{idx} recv_blocks: Closed")
IoError(m) => println("peer_\{idx} recv_blocks: IoError(\{m})")
Protocol(_) => println("peer_\{idx} recv_blocks: ProtocolError")
_ => println("peer_\{idx} recv_blocks: OtherError")
}
[]
}
}
conn.close()
if blocks.length() > 0 {
data_phase_ok = true
println(
"LIVE NTCP2 DATA PHASE OK with \{peer.host}:\{peer.port} (blocks=\{blocks.length()})",
)
break
}
}
assert_eq(handshake_ok, true)
assert_eq(data_phase_ok, true)
}
+17
View File
@@ -0,0 +1,17 @@
import {
"experiments/moon_i2p/encoding",
"experiments/moon_i2p/common",
"experiments/moon_i2p/i2np",
"experiments/moon_i2p/noise",
"experiments/moon_i2p/ntcp2",
}
import {
"experiments/moon_i2p/crypto",
} for "test"
supported_targets = "-all+native"
options(
"native-stub": [ "net_stub.c" ],
)
+366
View File
@@ -0,0 +1,366 @@
/*
* Native POSIX TCP client/server, CSPRNG, clock, and file I/O FFI stub
* for moon-i2p ntcp2_net & router (native target only).
*/
#define _POSIX_C_SOURCE 200809L
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "moonbit.h"
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
static char g_net_last_error[256] = {0};
static void net_set_error(const char *msg) {
if (msg == NULL) {
g_net_last_error[0] = '\0';
return;
}
strncpy(g_net_last_error, msg, sizeof(g_net_last_error) - 1);
g_net_last_error[sizeof(g_net_last_error) - 1] = '\0';
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_last_error_len(void) {
return (int32_t)strlen(g_net_last_error);
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_last_error_copy(moonbit_bytes_t dst, int32_t max_len) {
int32_t n = (int32_t)strlen(g_net_last_error);
if (n > max_len) {
n = max_len;
}
if (n > 0) {
memcpy(dst, g_net_last_error, (size_t)n);
}
return n;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_connect(
moonbit_bytes_t host_bytes,
int32_t host_len,
int32_t port) {
if (host_len <= 0 || host_len >= 256 || port <= 0 || port > 65535) {
net_set_error("invalid host or port");
return -1;
}
signal(SIGPIPE, SIG_IGN);
char host_buf[256];
memcpy(host_buf, host_bytes, (size_t)host_len);
host_buf[host_len] = '\0';
char port_buf[16];
snprintf(port_buf, sizeof(port_buf), "%d", port);
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo *res = NULL;
int gai_err = getaddrinfo(host_buf, port_buf, &hints, &res);
if (gai_err != 0) {
net_set_error(gai_strerror(gai_err));
return -1;
}
int fd = -1;
int last_errno = 0;
for (struct addrinfo *p = res; p != NULL; p = p->ai_next) {
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd < 0) {
last_errno = errno;
continue;
}
if (connect(fd, p->ai_addr, p->ai_addrlen) == 0) {
break;
}
last_errno = errno;
close(fd);
fd = -1;
}
freeaddrinfo(res);
if (fd < 0) {
net_set_error(strerror(last_errno ? last_errno : ECONNREFUSED));
return -1;
}
return (int32_t)fd;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_listen(
moonbit_bytes_t host_bytes,
int32_t host_len,
int32_t port) {
if (host_len <= 0 || host_len >= 256 || port < 0 || port > 65535) {
net_set_error("invalid listen host or port");
return -1;
}
signal(SIGPIPE, SIG_IGN);
char host_buf[256];
memcpy(host_buf, host_bytes, (size_t)host_len);
host_buf[host_len] = '\0';
char port_buf[16];
snprintf(port_buf, sizeof(port_buf), "%d", port);
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
struct addrinfo *res = NULL;
int gai_err = getaddrinfo(host_buf, port_buf, &hints, &res);
if (gai_err != 0) {
net_set_error(gai_strerror(gai_err));
return -1;
}
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd < 0) {
net_set_error(strerror(errno));
freeaddrinfo(res);
return -1;
}
int opt = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {
net_set_error(strerror(errno));
close(fd);
freeaddrinfo(res);
return -1;
}
freeaddrinfo(res);
if (listen(fd, 32) < 0) {
net_set_error(strerror(errno));
close(fd);
return -1;
}
return (int32_t)fd;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_local_port(int32_t fd) {
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
if (getsockname((int)fd, (struct sockaddr *)&addr, &len) < 0) {
net_set_error(strerror(errno));
return -1;
}
return (int32_t)ntohs(addr.sin_port);
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_accept(int32_t listen_fd, int32_t timeout_ms) {
if (timeout_ms >= 0) {
struct pollfd pfd;
pfd.fd = (int)listen_fd;
pfd.events = POLLIN;
pfd.revents = 0;
int rc = poll(&pfd, 1, (int)timeout_ms);
if (rc == 0) {
return -2; // timeout
}
if (rc < 0) {
net_set_error(strerror(errno));
return -1;
}
}
int cfd = accept((int)listen_fd, NULL, NULL);
if (cfd < 0) {
net_set_error(strerror(errno));
return -1;
}
return (int32_t)cfd;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_set_recv_timeout(int32_t fd, int32_t timeout_ms) {
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
if (setsockopt((int)fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
net_set_error(strerror(errno));
return -1;
}
return 0;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_send(
int32_t fd,
moonbit_bytes_t data,
int32_t offset,
int32_t len) {
ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL);
if (n < 0) {
net_set_error(strerror(errno));
return -1;
}
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_recv(
int32_t fd,
moonbit_bytes_t buf,
int32_t max_len) {
ssize_t n = recv((int)fd, buf, (size_t)max_len, 0);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return -2; // timeout
}
net_set_error(strerror(errno));
return -1;
}
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_poll_readable(int32_t fd, int32_t timeout_ms) {
struct pollfd pfd;
pfd.fd = (int)fd;
pfd.events = POLLIN;
pfd.revents = 0;
int rc = poll(&pfd, 1, (int)timeout_ms);
if (rc < 0) {
net_set_error(strerror(errno));
return -1;
}
return rc > 0 ? 1 : 0;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_shutdown_write(int32_t fd) {
if (shutdown((int)fd, SHUT_WR) < 0) {
net_set_error(strerror(errno));
return -1;
}
return 0;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_close(int32_t fd) {
if (close((int)fd) < 0) {
net_set_error(strerror(errno));
return -1;
}
return 0;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_random_bytes(moonbit_bytes_t buf, int32_t len) {
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
net_set_error(strerror(errno));
return -1;
}
int32_t got = 0;
while (got < len) {
ssize_t n = read(fd, buf + got, (size_t)(len - got));
if (n <= 0) {
net_set_error(strerror(errno));
close(fd);
return -1;
}
got += (int32_t)n;
}
close(fd);
return got;
}
MOONBIT_FFI_EXPORT
uint64_t moon_i2p_net_unix_time_ms(void) {
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
return (uint64_t)time(NULL) * 1000ULL;
}
return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L);
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_file_size(moonbit_bytes_t path_bytes, int32_t path_len) {
if (path_len <= 0 || path_len >= 1024) {
net_set_error("invalid path length");
return -1;
}
char path[1024];
memcpy(path, path_bytes, (size_t)path_len);
path[path_len] = '\0';
struct stat st;
if (stat(path, &st) < 0) {
net_set_error(strerror(errno));
return -1;
}
return (int32_t)st.st_size;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_read_file(
moonbit_bytes_t path_bytes,
int32_t path_len,
moonbit_bytes_t dst,
int32_t max_len) {
if (path_len <= 0 || path_len >= 1024) {
net_set_error("invalid path length");
return -1;
}
char path[1024];
memcpy(path, path_bytes, (size_t)path_len);
path[path_len] = '\0';
int fd = open(path, O_RDONLY);
if (fd < 0) {
net_set_error(strerror(errno));
return -1;
}
int32_t got = 0;
while (got < max_len) {
ssize_t n = read(fd, dst + got, (size_t)(max_len - got));
if (n < 0) {
net_set_error(strerror(errno));
close(fd);
return -1;
}
if (n == 0) {
break;
}
got += (int32_t)n;
}
close(fd);
return got;
}
MOONBIT_FFI_EXPORT
void moon_i2p_net_flush_stdout(void) {
fflush(stdout);
}
+57
View File
@@ -0,0 +1,57 @@
///|
test "ntcp2_net CSPRNG, clock, and TCP loopback" {
let r1 = @ntcp2_net.random_bytes(32)
let r2 = @ntcp2_net.random_bytes(32)
assert_eq(r1.length(), 32)
assert_eq(r2.length(), 32)
assert_true(r1 != r2)
assert_true(@ntcp2_net.unix_time_sec() > 1700000000U)
// Loopback TCP listener & client
let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0)
let port = listener.local_port()
assert_true(port > 0)
let client = @ntcp2_net.TcpSocket::connect("127.0.0.1", port)
let server = match listener.accept(timeout_ms=2000) {
Some(s) => s
None => fail("expected accepted TCP socket")
}
client.write_all(b"ping\n")
assert_eq(server.read_line(), Some("ping"))
server.write_all(b"pong\n")
assert_eq(client.read_line(), Some("pong"))
client.close()
server.close()
listener.close()
}
///|
test "extract_ntcp2_peer from signed RouterInfo" {
let ed_seed = @ntcp2_net.random_bytes(32)
let ed_pub = @crypto.ed25519_public_key(ed_seed)
let x_priv = @ntcp2_net.random_bytes(32)
let x_pub = @crypto.x25519_public_key(x_priv)
let iv = @ntcp2_net.random_bytes(16)
let ri_id = @common.RouterIdentity::new_x25519_ed25519(x_pub, ed_pub)
let addr_opts = @common.Mapping::from_entries([
("host", "127.0.0.1"),
("i", @encoding.base64_encode(iv)),
("port", "14567"),
("s", @encoding.base64_encode(x_pub)),
("v", "2"),
])
let ri : @common.RouterInfo = {
identity: ri_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")]),
signature: b"",
}
let signed = ri.sign_ed25519(ed_seed)
let peer = @ntcp2_net.extract_ntcp2_peer(signed)
assert_eq(peer.host, "127.0.0.1")
assert_eq(peer.port, 14567)
assert_eq(peer.static_key, x_pub)
assert_eq(peer.iv, iv)
assert_eq(peer.router_hash, ri_id.hash().as_bytes())
}
+718
View File
@@ -0,0 +1,718 @@
///|
/// Native POSIX TCP transport, OS CSPRNG/clock helpers, and NTCP2 session manager.
///|
#derive(Eq, Debug)
pub suberror Ntcp2NetError {
IoError(String)
Timeout
Closed
Protocol(@ntcp2.Ntcp2Error)
Common(@common.CommonError)
Noise(@noise.NoiseError)
InvalidPeer(String)
}
///|
extern "C" fn c_last_error_len() -> Int32 = "moon_i2p_net_last_error_len"
///|
#borrow(dst)
extern "C" fn c_last_error_copy(
dst : FixedArray[Byte],
max_len : Int32,
) -> Int32 = "moon_i2p_net_last_error_copy"
///|
#borrow(host)
extern "C" fn c_tcp_connect(
host : Bytes,
host_len : Int32,
port : Int32,
) -> Int32 = "moon_i2p_net_tcp_connect"
///|
#borrow(host)
extern "C" fn c_tcp_listen(
host : Bytes,
host_len : Int32,
port : Int32,
) -> Int32 = "moon_i2p_net_tcp_listen"
///|
extern "C" fn c_tcp_local_port(fd : Int32) -> Int32 = "moon_i2p_net_tcp_local_port"
///|
extern "C" fn c_tcp_accept(listen_fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_accept"
///|
extern "C" fn c_tcp_set_recv_timeout(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_set_recv_timeout"
///|
#borrow(data)
extern "C" fn c_tcp_send(
fd : Int32,
data : Bytes,
offset : Int32,
len : Int32,
) -> Int32 = "moon_i2p_net_tcp_send"
///|
#borrow(buf)
extern "C" fn c_tcp_recv(
fd : Int32,
buf : FixedArray[Byte],
max_len : Int32,
) -> Int32 = "moon_i2p_net_tcp_recv"
///|
extern "C" fn c_tcp_poll_readable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_readable"
///|
extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_net_tcp_shutdown_write"
///|
extern "C" fn c_tcp_close(fd : Int32) -> Int32 = "moon_i2p_net_tcp_close"
///|
#borrow(buf)
extern "C" fn c_random_bytes(buf : FixedArray[Byte], len : Int32) -> Int32 = "moon_i2p_net_random_bytes"
///|
extern "C" fn c_unix_time_ms() -> UInt64 = "moon_i2p_net_unix_time_ms"
///|
#borrow(path)
extern "C" fn c_file_size(path : Bytes, path_len : Int32) -> Int32 = "moon_i2p_net_file_size"
///|
#borrow(path, dst)
extern "C" fn c_read_file(
path : Bytes,
path_len : Int32,
dst : FixedArray[Byte],
max_len : Int32,
) -> Int32 = "moon_i2p_net_read_file"
///|
extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_net_flush_stdout"
///|
fn last_os_error() -> String {
let n = c_last_error_len()
if n <= 0 {
return "unknown OS error"
}
let buf = FixedArray::make(n, b'\x00')
let copied = c_last_error_copy(buf, n)
@encoding.utf8_bytes_to_string(Bytes::from_array(buf)[:copied].to_owned()) catch {
_ => "OS error"
}
}
///|
pub fn flush_stdout() -> Unit {
c_flush_stdout()
}
///|
/// Reads `n` cryptographically secure random bytes from `/dev/urandom`.
pub fn random_bytes(n : Int32) -> Bytes raise Ntcp2NetError {
if n <= 0 {
return b""
}
let buf = FixedArray::make(n, b'\x00')
let got = c_random_bytes(buf, n)
if got != n {
raise IoError("failed to read random bytes: \{last_os_error()}")
}
Bytes::from_array(buf)
}
///|
/// Returns the current Unix timestamp in milliseconds.
pub fn unix_time_ms() -> UInt64 {
c_unix_time_ms()
}
///|
/// Returns the current Unix timestamp in seconds.
pub fn unix_time_sec() -> UInt32 {
(c_unix_time_ms() / 1000UL).to_uint()
}
///|
/// Reads an entire local file into `Bytes`.
pub fn read_file_bytes(path : String) -> Bytes raise Ntcp2NetError {
let pb = @encoding.string_to_utf8_bytes(path)
let sz = c_file_size(pb, pb.length())
if sz < 0 {
raise IoError("stat(\{path}) failed: \{last_os_error()}")
}
if sz == 0 {
return b""
}
let buf = FixedArray::make(sz, b'\x00')
let got = c_read_file(pb, pb.length(), buf, sz)
if got < 0 {
raise IoError("read(\{path}) failed: \{last_os_error()}")
}
Bytes::from_array(buf)[:got].to_owned()
}
///|
/// Native POSIX TCP socket wrapper with exact-length reads and line reading.
pub struct TcpSocket {
mut fd : Int32
buf : FixedArray[Byte]
mut pos : Int32
mut len : Int32
}
///|
pub fn TcpSocket::connect(
host : String,
port : Int32,
) -> TcpSocket raise Ntcp2NetError {
let hb = @encoding.string_to_utf8_bytes(host)
let fd = c_tcp_connect(hb, hb.length(), port)
if fd < 0 {
raise IoError("connect(\{host}:\{port}) failed: \{last_os_error()}")
}
{ fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }
}
///|
pub fn TcpSocket::set_recv_timeout(
self : TcpSocket,
timeout_ms : Int32,
) -> Unit raise Ntcp2NetError {
if self.fd < 0 {
raise Closed
}
if c_tcp_set_recv_timeout(self.fd, timeout_ms) < 0 {
raise IoError("setsockopt(SO_RCVTIMEO) failed: \{last_os_error()}")
}
}
///|
pub fn TcpSocket::poll_readable(
self : TcpSocket,
timeout_ms : Int32,
) -> Bool raise Ntcp2NetError {
if self.pos < self.len {
return true
}
if self.fd < 0 {
raise Closed
}
let rc = c_tcp_poll_readable(self.fd, timeout_ms)
if rc < 0 {
raise IoError("poll failed: \{last_os_error()}")
}
rc > 0
}
///|
pub fn TcpSocket::write_all(
self : TcpSocket,
data : Bytes,
) -> Unit raise Ntcp2NetError {
if self.fd < 0 {
raise Closed
}
let total = data.length()
let mut sent = 0
while sent < total {
let n = c_tcp_send(self.fd, data, sent, total - sent)
if n < 0 {
raise IoError("send failed: \{last_os_error()}")
}
if n == 0 {
raise Closed
}
sent += n
}
}
///|
fn TcpSocket::refill(self : TcpSocket) -> Int32 raise Ntcp2NetError {
if self.fd < 0 {
raise Closed
}
let n = c_tcp_recv(self.fd, self.buf, self.buf.length())
if n == -2 {
raise Timeout
}
if n < 0 {
raise IoError("recv failed: \{last_os_error()}")
}
self.pos = 0
self.len = n
n
}
///|
/// Reads exactly `count` bytes from the socket (or raises `Closed`/`Timeout`/`IoError`).
pub fn TcpSocket::read_exact(
self : TcpSocket,
count : Int32,
) -> Bytes raise Ntcp2NetError {
if count <= 0 {
return b""
}
let out = FixedArray::make(count, b'\x00')
let mut got = 0
while got < count {
if self.pos < self.len {
let avail = self.len - self.pos
let need = count - got
let take = if avail < need { avail } else { need }
for i = 0; i < take; i = i + 1 {
out[got + i] = self.buf[self.pos + i]
}
self.pos += take
got += take
} else {
let n = self.refill()
if n == 0 {
raise Closed
}
}
}
Bytes::from_array(out)
}
///|
/// Reads up to `max_bytes` available bytes (returns empty `Bytes` on EOF).
pub fn TcpSocket::read_some(
self : TcpSocket,
max_bytes : Int32,
) -> Bytes raise Ntcp2NetError {
if max_bytes <= 0 {
return b""
}
if self.pos < self.len {
let avail = self.len - self.pos
let take = if avail < max_bytes { avail } else { max_bytes }
let out = FixedArray::make(take, b'\x00')
for i = 0; i < take; i = i + 1 {
out[i] = self.buf[self.pos + i]
}
self.pos += take
return Bytes::from_array(out)
}
let n = self.refill()
if n == 0 {
return b""
}
let take = if self.len < max_bytes { self.len } else { max_bytes }
let out = FixedArray::make(take, b'\x00')
for i = 0; i < take; i = i + 1 {
out[i] = self.buf[i]
}
self.pos = take
Bytes::from_array(out)
}
///|
/// Reads a `\n`-terminated UTF-8 line (stripping trailing `\r`). Returns `None` on clean EOF.
pub fn TcpSocket::read_line(self : TcpSocket) -> String? raise Ntcp2NetError {
let line : Array[Byte] = []
while true {
while self.pos < self.len {
let b = self.buf[self.pos]
self.pos += 1
if b == b'\n' {
if line.length() > 0 && line[line.length() - 1] == b'\r' {
let _ = line.pop()
}
let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch {
_ => raise IoError("invalid UTF-8 in line")
}
return Some(s)
}
line.push(b)
}
let n = self.refill()
if n == 0 {
if line.length() == 0 {
return None
}
let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch {
_ => raise IoError("invalid UTF-8 in line")
}
return Some(s)
}
}
None
}
///|
pub fn TcpSocket::shutdown_write(self : TcpSocket) -> Unit {
if self.fd >= 0 {
let _ = c_tcp_shutdown_write(self.fd)
}
}
///|
pub fn TcpSocket::close(self : TcpSocket) -> Unit {
if self.fd >= 0 {
let _ = c_tcp_close(self.fd)
self.fd = -1
}
}
///|
/// Native POSIX TCP server listener.
pub struct TcpListener {
mut fd : Int32
port : Int32
}
///|
pub fn TcpListener::bind(
host : String,
port : Int32,
) -> TcpListener raise Ntcp2NetError {
let hb = @encoding.string_to_utf8_bytes(host)
let fd = c_tcp_listen(hb, hb.length(), port)
if fd < 0 {
raise IoError("listen(\{host}:\{port}) failed: \{last_os_error()}")
}
let bound_port = c_tcp_local_port(fd)
{ fd, port: if bound_port > 0 { bound_port } else { port }, }
}
///|
pub fn TcpListener::local_port(self : TcpListener) -> Int32 {
self.port
}
///|
/// Accepts an incoming TCP connection. If `timeout_ms >= 0`, returns `None` on timeout.
pub fn TcpListener::accept(
self : TcpListener,
timeout_ms~ : Int32 = -1,
) -> TcpSocket? raise Ntcp2NetError {
if self.fd < 0 {
raise Closed
}
let cfd = c_tcp_accept(self.fd, timeout_ms)
if cfd == -2 {
return None
}
if cfd < 0 {
raise IoError("accept failed: \{last_os_error()}")
}
Some({ fd: cfd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, })
}
///|
pub fn TcpListener::close(self : TcpListener) -> Unit {
if self.fd >= 0 {
let _ = c_tcp_close(self.fd)
self.fd = -1
}
}
///|
/// Extracted NTCP2 connection parameters from a peer's `RouterInfo`.
#derive(Eq, Debug)
pub(all) struct Ntcp2PeerInfo {
router_hash : Bytes // 32-byte RH_B
static_key : Bytes // 32-byte X25519 's'
iv : Bytes // 16-byte 'i'
host : String
port : Int32
}
///|
fn parse_port_str(s : String) -> Int32? {
if s.length() == 0 {
return None
}
let mut v = 0
for i = 0; i < s.length(); i = i + 1 {
let c = s[i].to_int()
if c < 48 || c > 57 {
return None
}
v = v * 10 + (c - 48)
}
if v > 0 && v <= 65535 {
Some(v)
} else {
None
}
}
///|
/// Extracts the first reachable NTCP2 address (`host`, `port`, `s`, `i`) and `RH_B`
/// from a peer's `RouterInfo`.
pub fn extract_ntcp2_peer(
ri : @common.RouterInfo,
host_override~ : String? = None,
) -> Ntcp2PeerInfo raise Ntcp2NetError {
for addr in ri.addresses {
if addr.transport_style != "NTCP2" {
continue
}
let s_b64 = match addr.options.get("s") {
Some(v) => v
None => continue
}
let i_b64 = match addr.options.get("i") {
Some(v) => v
None => continue
}
let port_str = match addr.options.get("port") {
Some(v) => v
None => continue
}
let host = match host_override {
Some(h) => h
None =>
match addr.options.get("host") {
Some(v) => v
None => continue
}
}
let port = match parse_port_str(port_str) {
Some(p) => p
None => continue
}
let static_key = @encoding.base64_decode(s_b64) catch {
_ => raise InvalidPeer("invalid base64 in NTCP2 's' option")
}
let iv = @encoding.base64_decode(i_b64) catch {
_ => raise InvalidPeer("invalid base64 in NTCP2 'i' option")
}
return {
router_hash: ri.identity.hash().as_bytes(),
static_key,
iv,
host,
port,
}
}
raise InvalidPeer(
"no reachable NTCP2 address with s/i/port found in RouterInfo",
)
}
///|
/// Active NTCP2 encrypted TCP connection in Data Phase.
pub struct Ntcp2Conn {
socket : TcpSocket
session : @ntcp2.Ntcp2DataSession
remote_router_info : @common.RouterInfo?
}
///|
/// Connects to a remote NTCP2 peer over TCP and completes the full 3-message
/// NTCP2 handshake (`SessionRequest` -> `SessionCreated` -> `SessionConfirmed`).
pub fn dial_ntcp2(
peer : Ntcp2PeerInfo,
local_static : @noise.KeyPair,
local_ri : @common.RouterInfo,
flood~ : Bool = false,
timeout_ms~ : Int32 = 10000,
) -> Ntcp2Conn raise Ntcp2NetError {
let sock = TcpSocket::connect(peer.host, peer.port)
sock.set_recv_timeout(timeout_ms)
let hs = @ntcp2.Ntcp2Handshake::new_initiator(
local_static,
peer.static_key,
peer.router_hash,
peer.iv,
) catch {
e => {
sock.close()
raise Protocol(e)
}
}
let ephem_priv = random_bytes(32)
let ephem = @noise.KeyPair::from_private(ephem_priv) catch {
e => {
sock.close()
raise Noise(e)
}
}
hs.set_ephemeral(ephem)
// Prepare Msg 3 Part 2 blocks first so we know exact m3p2_len for Msg 1
let ri_blk = @ntcp2.router_info_block(local_ri, flood~) catch {
e => {
sock.close()
raise Protocol(e)
}
}
let m3_pad = random_bytes(16)
let m3_blocks : Array[@ntcp2.Ntcp2Block] = [ri_blk, Padding(m3_pad)]
let m3p2_pt = @ntcp2.encode_blocks(m3_blocks) catch {
e => {
sock.close()
raise Protocol(e)
}
}
let m3p2_ct_len = m3p2_pt.length() + 16
// Send Msg 1 (SessionRequest) with 16 bytes of random cleartext padding
let m1_pad = random_bytes(16)
let msg1 = hs.write_session_request(
m3p2_ct_len,
unix_time_sec(),
padding=m1_pad,
) catch {
e => {
sock.close()
raise Protocol(e)
}
}
sock.write_all(msg1)
// Read Msg 2 (SessionCreated): 64-byte head + pad_len bytes
let m2_head = sock.read_exact(64)
let m2_opts = hs.read_session_created_head(m2_head) catch {
e => {
sock.close()
raise Protocol(e)
}
}
let m2_pad_len = m2_opts.pad_len.reinterpret_as_int()
let m2_pad = if m2_pad_len > 0 { sock.read_exact(m2_pad_len) } else { b"" }
hs.finish_read_session_created(m2_pad) catch {
e => {
sock.close()
raise Protocol(e)
}
}
// Send Msg 3 (SessionConfirmed)
let msg3 = hs.write_session_confirmed(m3_blocks) catch {
e => {
sock.close()
raise Protocol(e)
}
}
sock.write_all(msg3)
let session = hs.into_data_session() catch {
e => {
sock.close()
raise Protocol(e)
}
}
{ socket: sock, session, remote_router_info: None, }
}
///|
/// Accepts an incoming NTCP2 handshake on an already-accepted `TcpSocket`.
pub fn accept_ntcp2(
sock : TcpSocket,
local_static : @noise.KeyPair,
local_router_hash : Bytes,
local_iv : Bytes,
timeout_ms~ : Int32 = 10000,
) -> Ntcp2Conn raise Ntcp2NetError {
sock.set_recv_timeout(timeout_ms)
let hs = @ntcp2.Ntcp2Handshake::new_responder(
local_static, local_router_hash, local_iv,
) catch {
e => raise Protocol(e)
}
let ephem_priv = random_bytes(32)
let ephem = @noise.KeyPair::from_private(ephem_priv) catch {
e => raise Noise(e)
}
hs.set_ephemeral(ephem)
// Read Msg 1 (SessionRequest)
let m1_head = sock.read_exact(64)
let m1_opts = hs.read_session_request_head(m1_head) catch {
e => raise Protocol(e)
}
let m1_pad_len = m1_opts.pad_len.reinterpret_as_int()
let m1_pad = if m1_pad_len > 0 { sock.read_exact(m1_pad_len) } else { b"" }
hs.finish_read_session_request(m1_pad) catch {
e => raise Protocol(e)
}
// Send Msg 2 (SessionCreated)
let m2_pad = random_bytes(16)
let msg2 = hs.write_session_created(unix_time_sec(), padding=m2_pad) catch {
e => raise Protocol(e)
}
sock.write_all(msg2)
// Read Msg 3 (SessionConfirmed)
let m3_total = 48 + hs.m3p2_len()
let msg3 = sock.read_exact(m3_total)
let blocks = hs.read_session_confirmed(msg3) catch { e => raise Protocol(e) }
let mut remote_ri : @common.RouterInfo? = None
for blk in blocks {
match blk {
RouterInfo(router_info~, ..) => {
let parsed = @common.RouterInfo::decode(
@encoding.Reader::new(router_info),
) catch {
e => raise Common(e)
}
remote_ri = Some(parsed)
}
_ => ()
}
}
let session = hs.into_data_session() catch { e => raise Protocol(e) }
{ socket: sock, session, remote_router_info: remote_ri, }
}
///|
/// Encrypts and sends a data-phase frame containing `blocks`.
pub fn Ntcp2Conn::send_blocks(
self : Ntcp2Conn,
blocks : Array[@ntcp2.Ntcp2Block],
) -> Unit raise Ntcp2NetError {
let frame = self.session.encrypt_frame(blocks) catch {
e => raise Protocol(e)
}
self.socket.write_all(frame)
}
///|
/// Reads, unmasks, and decrypts the next data-phase frame.
pub fn Ntcp2Conn::recv_blocks(
self : Ntcp2Conn,
) -> Array[@ntcp2.Ntcp2Block] raise Ntcp2NetError {
let len_hdr = self.socket.read_exact(2)
let frame_len = self.session.unmask_frame_length(len_hdr) catch {
e => raise Protocol(e)
}
if frame_len < 16 {
raise IoError("NTCP2 frame shorter than 16-byte MAC: \{frame_len}")
}
let ct = self.socket.read_exact(frame_len)
self.session.decrypt_frame_body(ct) catch {
e => raise Protocol(e)
}
}
///|
/// Convenience helper to send a single I2NP message in an NTCP2 Data Phase frame.
pub fn Ntcp2Conn::send_i2np(
self : Ntcp2Conn,
msg_id : UInt32,
expiration_sec : UInt32,
payload : @i2np.I2npPayload,
) -> Unit raise Ntcp2NetError {
let blk = @ntcp2.i2np_block(msg_id, expiration_sec, payload) catch {
e => raise Protocol(e)
}
self.send_blocks([blk])
}
///|
pub fn Ntcp2Conn::close(self : Ntcp2Conn) -> Unit {
self.socket.close()
}