feat: add native MoonBit I2P router core and embedded SAMv3 bridge
This commit is contained in:
1 parent
4866f3c46d
commit
cadb8cd898
6 files changed
+913
-42
No files matched your search
@@ -1,81 +1,81 @@
|
|||||||
# moon-i2p
|
# moon-i2p
|
||||||
|
|
||||||
A clean, zero-dependency, pure-[MoonBit](https://www.moonbitlang.com/) port of the modern **I2P (Invisible Internet Project)** protocol suite targeting `wasm`, `wasm-gc`, `js`, and `native`.
|
A clean, zero-dependency, pure-[MoonBit](https://www.moonbitlang.com/) implementation of the modern **I2P (Invisible Internet Project)** protocol suite and native router core, with pure protocol packages targeting `wasm`, `wasm-gc`, `js`, and `native`.
|
||||||
|
|
||||||
## Architecture & Implemented Modules
|
## Architecture & Implemented Modules
|
||||||
|
|
||||||
```
|
```
|
||||||
moon-i2p/
|
moon-i2p/
|
||||||
├── encoding/ # I2P Base64 (-/~), Base32 (.b32.i2p), big-endian Reader/Writer, UTF-8, Hex
|
├── encoding/ # I2P Base64 (-/~), Base32 (.b32.i2p), big-endian Reader/Writer, UTF-8, Hex
|
||||||
├── crypto/ # Pure-MoonBit SHA-256, HMAC-SHA256, HKDF-SHA256, ChaCha20-Poly1305, X25519, SipHash-2-4
|
├── crypto/ # Pure-MoonBit SHA-256, SHA-512, HMAC/HKDF-SHA256, ChaCha20-Poly1305, AES-256-CBC, X25519, Ed25519, SipHash-2-4
|
||||||
├── common/ # Hash, KeyTypes, Certificate/KeyCertificate, Mapping, Destination, RouterIdentity, RouterInfo, Lease2, LeaseSet2
|
├── common/ # Hash, KeyTypes, Certificate/KeyCertificate, Mapping, Destination, RouterIdentity, signed RouterInfo & LeaseSet2
|
||||||
├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages
|
├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages
|
||||||
├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking
|
├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking
|
||||||
|
├── ntcp2/ # Pure-MoonBit NTCP2 (Noise_XKaesobfse+hs2+hs3, AES-256-CBC obfuscation, SipHash KDF, data-phase blocks)
|
||||||
|
├── ntcp2_net/ # Native POSIX TCP transport, OS CSPRNG/clock, and NTCP2 dial/accept session manager
|
||||||
|
├── netdb/ # Pure-MoonBit NetDB & Floodfill Kademlia DHT (XOR distance, daily routing keys, Ed25519-verified store)
|
||||||
|
├── tunnel/ # Pure-MoonBit Proposal 157 ShortTunnelBuild (218B records), 1024B TunnelData AES-256-CBC layer crypto, fragmentation & relay
|
||||||
├── sam/ # SAMv3 text protocol parser, serializer, and command builders
|
├── sam/ # SAMv3 text protocol parser, serializer, and command builders
|
||||||
├── sam_client/ # Native POSIX TCP SAMv3 client with sane modern I2P defaults
|
├── sam_client/ # Native POSIX TCP SAMv3 client with sane modern I2P defaults
|
||||||
|
├── router/ # Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager, NTCP2 listener & embedded SAMv3 bridge
|
||||||
├── cmd/main/ # Pure protocol demo CLI entrypoint
|
├── cmd/main/ # Pure protocol demo CLI entrypoint
|
||||||
|
├── cmd/router/ # Native MoonBit I2P router daemon (`--sam`, `--ntcp2-port`, `--peer`)
|
||||||
├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`)
|
├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`)
|
||||||
└── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`) and end-to-end test (`e2e_test.py`)
|
└── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`) and end-to-end test (`e2e_test.py`)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Verified Test Vectors
|
### Verified Test Vectors & Interop
|
||||||
Every cryptographic primitive in `crypto/` is verified against official standards:
|
Every cryptographic primitive in `crypto/` is verified against official standards:
|
||||||
- **SHA-256**: FIPS 180-4 / NIST test vectors
|
- **SHA-256 & SHA-512**: FIPS 180-4 / NIST test vectors
|
||||||
- **HMAC-SHA256**: RFC 4231 test cases 1 & 2
|
- **HMAC-SHA256**: RFC 4231 test cases 1 & 2
|
||||||
- **HKDF-SHA256**: RFC 5869 test case 1
|
- **HKDF-SHA256**: RFC 5869 test case 1
|
||||||
- **ChaCha20-Poly1305 AEAD**: RFC 8439 Section 2.8.2
|
- **ChaCha20-Poly1305 AEAD**: RFC 8439 Section 2.8.2
|
||||||
|
- **AES-256 & AES-256-CBC**: NIST FIPS-197 Appendix C.3 & SP 800-38A F.2.5/F.2.6
|
||||||
- **X25519**: RFC 7748 Sections 5.2 & 6.1
|
- **X25519**: RFC 7748 Sections 5.2 & 6.1
|
||||||
|
- **Ed25519**: RFC 8032 Section 7.1 test vectors 1–3 (+ non-canonical `S >= L` & tamper rejection)
|
||||||
- **SipHash-2-4**: Official SipHash reference test vector
|
- **SipHash-2-4**: Official SipHash reference test vector
|
||||||
|
- **Live I2P Interop**: Verified real `i2pd` `router.info` parsing + Ed25519 signature verification, and full live NTCP2 handshake (Msg 1 → Msg 2 → Msg 3 → Data Phase SipHash length-masked AEAD frames) against a live public I2P floodfill router.
|
||||||
|
|
||||||
## Running the SAMv3 Client (Native)
|
## Running the Native MoonBit Router & SAMv3 Client
|
||||||
|
|
||||||
The native client (`cmd/client`) connects to an I2P SAMv3 bridge with sane modern defaults:
|
```bash
|
||||||
|
# Build the native router and client binaries
|
||||||
|
moon build --target native cmd/router
|
||||||
|
moon build --target native cmd/client
|
||||||
|
|
||||||
|
# Start the MoonBit router (transient keys, NTCP2 listener + embedded SAMv3 bridge on 127.0.0.1:7656)
|
||||||
|
./_build/native/debug/build/cmd/router/router.exe --sam 127.0.0.1:7656 --ntcp2-port 14568
|
||||||
|
|
||||||
|
# In another terminal, talk to our MoonBit router with cmd/client:
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe keygen
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe listen "hello back"
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe lookup <listener.b32.i2p>
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe dial <listener.b32.i2p> "hello over i2p"
|
||||||
|
```
|
||||||
|
|
||||||
|
Default SAMv3 client settings:
|
||||||
- **Bridge:** `127.0.0.1:7656` (override with `--sam <host:port>` or `I2P_SAM_HOST` / `I2P_SAM_PORT`)
|
- **Bridge:** `127.0.0.1:7656` (override with `--sam <host:port>` or `I2P_SAM_HOST` / `I2P_SAM_PORT`)
|
||||||
- **Protocol:** SAM `3.1`–`3.3`
|
- **Protocol:** SAM `3.1`–`3.3`
|
||||||
- **Keys:** `TRANSIENT` destination, `SIGNATURE_TYPE=7` (`EdDSA_SHA512_Ed25519`)
|
- **Keys:** `TRANSIENT` destination, `SIGNATURE_TYPE=7` (`EdDSA_SHA512_Ed25519`)
|
||||||
- **I2CP Tunnel Defaults:** `i2cp.leaseSetEncType=4,0` (ECIES-X25519 preferred), 3-hop / 3-tunnel inbound & outbound pools
|
- **I2CP Tunnel Defaults:** `i2cp.leaseSetEncType=4,0` (ECIES-X25519 preferred), 3-hop / 3-tunnel inbound & outbound pools
|
||||||
|
|
||||||
```bash
|
|
||||||
# Build the native client binary
|
|
||||||
moon build --target native cmd/client
|
|
||||||
|
|
||||||
# Start an I2P router with SAMv3 enabled (e.g. i2pd --sam.enabled=true)
|
|
||||||
# or use the bundled local loopback SAMv3 bridge for testing:
|
|
||||||
# python3 scripts/mock_sam.py
|
|
||||||
|
|
||||||
# Generate a new Ed25519 I2P destination
|
|
||||||
./_build/native/debug/build/cmd/client/client.exe keygen
|
|
||||||
|
|
||||||
# Resolve an I2P hostname
|
|
||||||
./_build/native/debug/build/cmd/client/client.exe lookup stats.i2p
|
|
||||||
|
|
||||||
# Fetch an eepsite over a transient STREAM session
|
|
||||||
./_build/native/debug/build/cmd/client/client.exe http-get stats.i2p /
|
|
||||||
|
|
||||||
# Peer-to-peer STREAM listener and dialer
|
|
||||||
./_build/native/debug/build/cmd/client/client.exe listen "hello back"
|
|
||||||
./_build/native/debug/build/cmd/client/client.exe dial <listener.b32.i2p> "hello over i2p"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Running Checks & Tests
|
## Running Checks & Tests
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
moon check --target wasm
|
|
||||||
moon test --target wasm
|
moon test --target wasm
|
||||||
moon check --target native
|
moon test --target js
|
||||||
moon test --target native
|
moon test --target native
|
||||||
moon build --target native cmd/client && python3 scripts/e2e_test.py
|
moon build --target native cmd/router && moon build --target native cmd/client
|
||||||
|
python3 scripts/e2e_test.py
|
||||||
```
|
```
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
1. **Phase 1–2 (Completed):** Core encoding, pure-MoonBit modern crypto, I2P Common Structures, I2NP messages, `Noise_XK_25519_ChaChaPoly_SHA256` state machine, NTCP2 SipHash length masking, SAMv3 protocol codec, and working native SAMv3 TCP client + CLI (`sam_client/`, `cmd/client/`).
|
- [x] **Phase 1–2:** Core encoding, pure-MoonBit modern crypto, I2P Common Structures, I2NP messages, `Noise_XK_25519_ChaChaPoly_SHA256`, SAMv3 codec, and native SAMv3 TCP client + CLI (`sam_client/`, `cmd/client/`).
|
||||||
2. **Phase 3 (Signatures & Ratchet):**
|
- [x] **Phase 3 (Signatures & Block Crypto):** Pure-MoonBit **SHA-512**, **Ed25519** (RFC 8032), **AES-256-CBC** (FIPS-197 / SP 800-38A), and Ed25519-signed `RouterInfo` & `LeaseSet2` (Proposal 123).
|
||||||
- Pure-MoonBit **Ed25519** signing & verification (`RouterInfo` & `LeaseSet2` signatures).
|
- [x] **Phase 4 (Direct Transport):** Full **NTCP2** protocol (`ntcp2/`) + native POSIX TCP transport (`ntcp2_net/`), verified live against public I2P floodfill routers.
|
||||||
- **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end sessions.
|
- [x] **Phase 5 (Router Core):** Pure-MoonBit **NetDB** & Floodfill Kademlia DHT (`netdb/`), Proposal 157 **ShortTunnelBuild** & 1024-byte `TunnelData` layer crypto/relay (`tunnel/`), and native **Router Core** + embedded SAMv3 bridge (`router/`, `cmd/router/`).
|
||||||
3. **Phase 4 (Direct Transports):**
|
- [ ] **Phase 6 (Full End-to-End I2P Network Tunneling):**
|
||||||
- **NTCP2** full TCP transport (AES-256-CBC ephemeral key obfuscation, options/padding blocks, session manager).
|
- **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end remote peer sessions.
|
||||||
4. **Phase 5 (Router Core):**
|
- Active remote floodfill NetDB lookup/publish over NTCP2 + gzip decompression for `DatabaseStore` type 0.
|
||||||
- **NetDB** & Floodfill DHT (Kademlia XOR routing with daily routing key derivation).
|
- **I2P Streaming** (SYN/ACK/windowing) & **Repliable Datagrams** over multi-hop remote tunnels.
|
||||||
- **Tunnel** builder (`ShortTunnelBuild` Proposal 157), layered tunnel encryption, and tunnel pool management.
|
|
||||||
- **Streaming** & **Repliable Datagrams** libraries.
|
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
///|
|
||||||
|
fn parse_port(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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn split_host_port(spec : String) -> (String, Int32)? {
|
||||||
|
let mut colon = -1
|
||||||
|
for i = 0; i < spec.length(); i = i + 1 {
|
||||||
|
if spec[i] == ':' {
|
||||||
|
colon = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if colon <= 0 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let host = spec[:colon].to_owned()
|
||||||
|
let port_s = spec[colon + 1:].to_owned()
|
||||||
|
match parse_port(port_s) {
|
||||||
|
Some(p) => Some((host, p))
|
||||||
|
None => None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn main {
|
||||||
|
let args = @env.args()
|
||||||
|
let mut sam_host = "127.0.0.1"
|
||||||
|
let mut sam_port = 7656
|
||||||
|
let mut ntcp2_host = "127.0.0.1"
|
||||||
|
let mut ntcp2_port = 0
|
||||||
|
let peer_files : Array[String] = []
|
||||||
|
|
||||||
|
let mut i = 1
|
||||||
|
while i < args.length() {
|
||||||
|
match args[i] {
|
||||||
|
"--sam" =>
|
||||||
|
if i + 1 < args.length() {
|
||||||
|
match split_host_port(args[i + 1]) {
|
||||||
|
Some((h, p)) => {
|
||||||
|
sam_host = h
|
||||||
|
sam_port = p
|
||||||
|
}
|
||||||
|
None => println("warning: ignoring invalid --sam \{args[i + 1]}")
|
||||||
|
}
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
"--ntcp2-port" =>
|
||||||
|
if i + 1 < args.length() {
|
||||||
|
match parse_port(args[i + 1]) {
|
||||||
|
Some(p) => ntcp2_port = p
|
||||||
|
None => println("warning: ignoring invalid --ntcp2-port")
|
||||||
|
}
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
"--ntcp2-host" =>
|
||||||
|
if i + 1 < args.length() {
|
||||||
|
ntcp2_host = args[i + 1]
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
"--peer" =>
|
||||||
|
if i + 1 < args.length() {
|
||||||
|
peer_files.push(args[i + 1])
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
_ => i += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let r = @i2p_router.Router::start({
|
||||||
|
sam_host,
|
||||||
|
sam_port,
|
||||||
|
ntcp2_host,
|
||||||
|
ntcp2_port,
|
||||||
|
}) catch {
|
||||||
|
_ => {
|
||||||
|
println("error: failed to start moon-i2p router")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for pf in peer_files {
|
||||||
|
let _ = r.load_peer_file(pf) catch {
|
||||||
|
_ => {
|
||||||
|
println("warning: failed to load peer RouterInfo from \{pf}")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println("moon-i2p router started (transient identity)")
|
||||||
|
println(" Router Hash: \{r.router_hash().to_base64()}")
|
||||||
|
println(" Router B32: \{r.router_hash().to_b32_address()}")
|
||||||
|
println(" NTCP2: \{ntcp2_host}:\{r.ntcp2_port()}")
|
||||||
|
println(" SAMv3: \{sam_host}:\{r.sam_port()}")
|
||||||
|
println(" NetDB peers: \{r.netdb.router_count()}")
|
||||||
|
@ntcp2_net.flush_stdout()
|
||||||
|
r.run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import {
|
||||||
|
"moonbitlang/core/env",
|
||||||
|
"experiments/moon_i2p/ntcp2_net",
|
||||||
|
"experiments/moon_i2p/router" @i2p_router,
|
||||||
|
}
|
||||||
|
|
||||||
|
pkgtype(kind: "executable")
|
||||||
|
|
||||||
|
supported_targets = "-all+native"
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import {
|
||||||
|
"experiments/moon_i2p/encoding",
|
||||||
|
"experiments/moon_i2p/crypto",
|
||||||
|
"experiments/moon_i2p/common",
|
||||||
|
"experiments/moon_i2p/noise",
|
||||||
|
"experiments/moon_i2p/ntcp2_net",
|
||||||
|
"experiments/moon_i2p/netdb",
|
||||||
|
"experiments/moon_i2p/tunnel",
|
||||||
|
"experiments/moon_i2p/sam",
|
||||||
|
}
|
||||||
|
|
||||||
|
supported_targets = "-all+native"
|
||||||
@@ -0,0 +1,679 @@
|
|||||||
|
///|
|
||||||
|
/// Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager,
|
||||||
|
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge (single-threaded poll loop).
|
||||||
|
|
||||||
|
///|
|
||||||
|
#derive(Eq, Debug)
|
||||||
|
pub suberror RouterError {
|
||||||
|
Net(@ntcp2_net.Ntcp2NetError)
|
||||||
|
Crypto(@crypto.CryptoError)
|
||||||
|
Common(@common.CommonError)
|
||||||
|
Noise(@noise.NoiseError)
|
||||||
|
NetDb(@netdb.NetDbError)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Configuration for `Router::start`.
|
||||||
|
pub(all) struct RouterConfig {
|
||||||
|
sam_host : String
|
||||||
|
sam_port : Int32
|
||||||
|
ntcp2_host : String
|
||||||
|
ntcp2_port : Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn RouterConfig::default() -> RouterConfig {
|
||||||
|
{
|
||||||
|
sam_host: "127.0.0.1",
|
||||||
|
sam_port: 7656,
|
||||||
|
ntcp2_host: "127.0.0.1",
|
||||||
|
ntcp2_port: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
priv struct SamSession {
|
||||||
|
id : String
|
||||||
|
pub_b64 : String
|
||||||
|
b32 : String
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
priv struct SamClientConn {
|
||||||
|
sock : @ntcp2_net.TcpSocket
|
||||||
|
mut session_id : String?
|
||||||
|
mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged
|
||||||
|
mut accept_session_id : String
|
||||||
|
mut accept_silent : Bool
|
||||||
|
mut closed : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
priv struct StreamBridge {
|
||||||
|
a : @ntcp2_net.TcpSocket
|
||||||
|
b : @ntcp2_net.TcpSocket
|
||||||
|
mut a_eof : Bool
|
||||||
|
mut b_eof : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Live MoonBit I2P Router Core instance.
|
||||||
|
pub struct Router {
|
||||||
|
ed_seed : Bytes
|
||||||
|
static_key : @noise.KeyPair
|
||||||
|
ntcp2_iv : Bytes
|
||||||
|
router_info : @common.RouterInfo
|
||||||
|
netdb : @netdb.NetDb
|
||||||
|
tunnels : @tunnel.TunnelManager
|
||||||
|
ntcp2_listener : @ntcp2_net.TcpListener
|
||||||
|
sam_listener : @ntcp2_net.TcpListener
|
||||||
|
priv sessions : Array[SamSession]
|
||||||
|
priv sam_clients : Array[SamClientConn]
|
||||||
|
priv bridges : Array[StreamBridge]
|
||||||
|
priv aliases : Array[(String, String)] // hostname -> pub_b64
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and
|
||||||
|
/// returns `(dest, pub_b64, priv_b64, ed_seed)`.
|
||||||
|
fn generate_transient_destination() -> (
|
||||||
|
@common.Destination,
|
||||||
|
String,
|
||||||
|
String,
|
||||||
|
Bytes,
|
||||||
|
) raise RouterError {
|
||||||
|
let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||||
|
let ed_pub = @crypto.ed25519_public_key(ed_seed) catch {
|
||||||
|
e => raise Crypto(e)
|
||||||
|
}
|
||||||
|
let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||||
|
let x_pub = @crypto.x25519_public_key(x_priv) catch { e => raise Crypto(e) }
|
||||||
|
let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) }
|
||||||
|
let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub, padding=pad) catch {
|
||||||
|
e => raise Common(e)
|
||||||
|
}
|
||||||
|
let pub_bytes = dest.to_bytes()
|
||||||
|
let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64)
|
||||||
|
priv_w.write_bytes(pub_bytes)
|
||||||
|
priv_w.write_bytes(x_priv)
|
||||||
|
priv_w.write_bytes(ed_seed)
|
||||||
|
let pub_b64 = @encoding.base64_encode(pub_bytes)
|
||||||
|
let priv_b64 = @encoding.base64_encode(priv_w.to_bytes())
|
||||||
|
(dest, pub_b64, priv_b64, ed_seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`,
|
||||||
|
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge.
|
||||||
|
pub fn Router::start(config : RouterConfig) -> Router raise RouterError {
|
||||||
|
let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||||
|
let ed_pub = @crypto.ed25519_public_key(ed_seed) catch {
|
||||||
|
e => raise Crypto(e)
|
||||||
|
}
|
||||||
|
let static_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||||
|
let static_key = @noise.KeyPair::from_private(static_priv) catch {
|
||||||
|
e => raise Noise(e)
|
||||||
|
}
|
||||||
|
let ntcp2_iv = @ntcp2_net.random_bytes(16) catch { e => raise Net(e) }
|
||||||
|
let ntcp2_listener = @ntcp2_net.TcpListener::bind(
|
||||||
|
config.ntcp2_host,
|
||||||
|
config.ntcp2_port,
|
||||||
|
) catch {
|
||||||
|
e => raise Net(e)
|
||||||
|
}
|
||||||
|
let sam_listener = @ntcp2_net.TcpListener::bind(
|
||||||
|
config.sam_host,
|
||||||
|
config.sam_port,
|
||||||
|
) catch {
|
||||||
|
e => {
|
||||||
|
ntcp2_listener.close()
|
||||||
|
raise Net(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let id = @common.RouterIdentity::new_x25519_ed25519(
|
||||||
|
static_key.public_key,
|
||||||
|
ed_pub,
|
||||||
|
) catch {
|
||||||
|
e => raise Common(e)
|
||||||
|
}
|
||||||
|
let addr_opts = @common.Mapping::from_entries([
|
||||||
|
("host", config.ntcp2_host),
|
||||||
|
("i", @encoding.base64_encode(ntcp2_iv)),
|
||||||
|
("port", "\{ntcp2_listener.local_port()}"),
|
||||||
|
("s", @encoding.base64_encode(static_key.public_key)),
|
||||||
|
("v", "2"),
|
||||||
|
])
|
||||||
|
let ri : @common.RouterInfo = {
|
||||||
|
identity: id,
|
||||||
|
published: @ntcp2_net.unix_time_ms(),
|
||||||
|
addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)],
|
||||||
|
options: @common.Mapping::from_entries([
|
||||||
|
("caps", "LR"),
|
||||||
|
("netId", "2"),
|
||||||
|
("router.version", "0.9.64"),
|
||||||
|
]),
|
||||||
|
signature: b"",
|
||||||
|
}
|
||||||
|
let signed_ri = ri.sign_ed25519(ed_seed) catch { e => raise Common(e) }
|
||||||
|
let netdb = @netdb.NetDb::new()
|
||||||
|
let _ = netdb.store_router_info(signed_ri) catch { e => raise NetDb(e) }
|
||||||
|
let router : Router = {
|
||||||
|
ed_seed,
|
||||||
|
static_key,
|
||||||
|
ntcp2_iv,
|
||||||
|
router_info: signed_ri,
|
||||||
|
netdb,
|
||||||
|
tunnels: @tunnel.TunnelManager::new(),
|
||||||
|
ntcp2_listener,
|
||||||
|
sam_listener,
|
||||||
|
sessions: [],
|
||||||
|
sam_clients: [],
|
||||||
|
bridges: [],
|
||||||
|
aliases: [],
|
||||||
|
}
|
||||||
|
router
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Router::sam_port(self : Router) -> Int32 {
|
||||||
|
self.sam_listener.local_port()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Router::ntcp2_port(self : Router) -> Int32 {
|
||||||
|
self.ntcp2_listener.local_port()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Router::router_hash(self : Router) -> @common.Hash {
|
||||||
|
self.router_info.identity.hash()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Router::register_alias(
|
||||||
|
self : Router,
|
||||||
|
hostname : String,
|
||||||
|
dest_pub_b64 : String,
|
||||||
|
) -> Unit {
|
||||||
|
let key = hostname.to_lower()
|
||||||
|
for i = 0; i < self.aliases.length(); i = i + 1 {
|
||||||
|
if self.aliases[i].0 == key {
|
||||||
|
self.aliases[i] = (key, dest_pub_b64)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.aliases.push((key, dest_pub_b64))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Loads a peer `RouterInfo` file from disk, verifies its Ed25519 signature,
|
||||||
|
/// and stores it in `self.netdb`.
|
||||||
|
pub fn Router::load_peer_file(
|
||||||
|
self : Router,
|
||||||
|
path : String,
|
||||||
|
) -> @common.RouterInfo raise RouterError {
|
||||||
|
let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) }
|
||||||
|
let ri = @common.RouterInfo::decode(@encoding.Reader::new(raw)) catch {
|
||||||
|
e => raise Common(e)
|
||||||
|
}
|
||||||
|
let _ = self.netdb.store_router_info(ri) catch { e => raise NetDb(e) }
|
||||||
|
ri
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Router::close(self : Router) -> Unit {
|
||||||
|
for c in self.sam_clients {
|
||||||
|
if !c.closed {
|
||||||
|
c.sock.close()
|
||||||
|
c.closed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for b in self.bridges {
|
||||||
|
b.a.close()
|
||||||
|
b.b.close()
|
||||||
|
}
|
||||||
|
self.sam_listener.close()
|
||||||
|
self.ntcp2_listener.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Router::find_session_by_id(self : Router, id : String) -> SamSession? {
|
||||||
|
for s in self.sessions {
|
||||||
|
if s.id == id {
|
||||||
|
return Some(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? {
|
||||||
|
for s in self.sessions {
|
||||||
|
if s.pub_b64 == pub_b64 {
|
||||||
|
return Some(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Router::resolve_name(
|
||||||
|
self : Router,
|
||||||
|
name : String,
|
||||||
|
client_session_id : String?,
|
||||||
|
) -> String? {
|
||||||
|
if name == "ME" {
|
||||||
|
match client_session_id {
|
||||||
|
Some(sid) =>
|
||||||
|
match self.find_session_by_id(sid) {
|
||||||
|
Some(s) => return Some(s.pub_b64)
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let lower = name.to_lower()
|
||||||
|
// Check local aliases
|
||||||
|
for entry in self.aliases {
|
||||||
|
if entry.0 == lower {
|
||||||
|
return Some(entry.1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Check active local sessions by .b32.i2p
|
||||||
|
for s in self.sessions {
|
||||||
|
if s.b32 == lower {
|
||||||
|
return Some(s.pub_b64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Check NetDB LeaseSet2 entries by .b32.i2p
|
||||||
|
let now_sec = @ntcp2_net.unix_time_sec()
|
||||||
|
match self.netdb.get_lease_set2_by_b32(lower, now_sec) {
|
||||||
|
Some(ls2) => return Some(ls2.destination.to_base64())
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool {
|
||||||
|
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch {
|
||||||
|
_ => return false
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Router::handle_sam_command(
|
||||||
|
self : Router,
|
||||||
|
client_idx : Int32,
|
||||||
|
line : String,
|
||||||
|
) -> Unit {
|
||||||
|
let client = self.sam_clients[client_idx]
|
||||||
|
let msg = @sam.SamMessage::parse(line) catch {
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match (msg.verb, msg.subcommand) {
|
||||||
|
("HELLO", Some("VERSION")) => {
|
||||||
|
let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3")
|
||||||
|
}
|
||||||
|
("DEST", Some("GENERATE")) => {
|
||||||
|
let (_dest, pub_b64, priv_b64, _seed) = generate_transient_destination() catch {
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
("NAMING", Some("LOOKUP")) => {
|
||||||
|
let name = match msg.get("NAME") {
|
||||||
|
Some(n) => n
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"NAMING REPLY RESULT=INVALID_KEY NAME=",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match self.resolve_name(name, client.session_id) {
|
||||||
|
Some(val) => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("SESSION", Some("CREATE")) => {
|
||||||
|
let sid = match msg.get("ID") {
|
||||||
|
Some(id) => id
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.find_session_by_id(sid) is Some(_) {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=DUPLICATED_ID",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let dest_param = match msg.get("DESTINATION") {
|
||||||
|
Some(d) => d
|
||||||
|
None => "TRANSIENT"
|
||||||
|
}
|
||||||
|
let (dest, pub_b64, priv_b64, opt_seed) = if dest_param == "TRANSIENT" {
|
||||||
|
let (d, pb, prb, seed) = generate_transient_destination() catch {
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=I2P_ERROR",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(d, pb, prb, Some(seed))
|
||||||
|
} else {
|
||||||
|
let raw = @encoding.base64_decode(dest_param) catch {
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=INVALID_KEY",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let d = @common.Destination::decode(@encoding.Reader::new(raw)) catch {
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=INVALID_KEY",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(d, d.to_base64(), dest_param, None)
|
||||||
|
}
|
||||||
|
let b32 = dest.b32_address()
|
||||||
|
// Publish a signed LeaseSet2 for transient destinations into our NetDB
|
||||||
|
match opt_seed {
|
||||||
|
Some(seed) => {
|
||||||
|
let now_sec = @ntcp2_net.unix_time_sec()
|
||||||
|
let ls2 : @common.LeaseSet2 = {
|
||||||
|
destination: dest,
|
||||||
|
published_sec: now_sec,
|
||||||
|
expires_offset: 600U,
|
||||||
|
flags: 0U,
|
||||||
|
options: @common.Mapping::new(),
|
||||||
|
encryption_keys: [
|
||||||
|
{ key_type: X25519, key_data: dest.inner.crypto_public_key(), },
|
||||||
|
],
|
||||||
|
leases: [
|
||||||
|
{
|
||||||
|
tunnel_gw: self.router_hash(),
|
||||||
|
tunnel_id: (10000 + self.sessions.length()).reinterpret_as_uint(),
|
||||||
|
end_date_sec: now_sec + 600U,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
signature: b"",
|
||||||
|
}
|
||||||
|
let signed_ls2 = ls2.sign_ed25519(seed) catch { _ => ls2 }
|
||||||
|
let _ = self.netdb.store_lease_set2(signed_ls2, now_sec) catch {
|
||||||
|
_ => false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
self.sessions.push({ id: sid, pub_b64, b32, })
|
||||||
|
client.session_id = Some(sid)
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
("STREAM", Some("ACCEPT")) => {
|
||||||
|
let sid = match msg.get("ID") {
|
||||||
|
Some(id) => id
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.find_session_by_id(sid) is None {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let silent = match msg.get("SILENT") {
|
||||||
|
Some(v) => v.to_lower() == "true"
|
||||||
|
None => false
|
||||||
|
}
|
||||||
|
client.mode = 1
|
||||||
|
client.accept_session_id = sid
|
||||||
|
client.accept_silent = silent
|
||||||
|
if !silent {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("STREAM", Some("CONNECT")) => {
|
||||||
|
let sid = match msg.get("ID") {
|
||||||
|
Some(id) => id
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let caller_sess = match self.find_session_by_id(sid) {
|
||||||
|
Some(s) => s
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let dest_b64 = match msg.get("DESTINATION") {
|
||||||
|
Some(d) => d
|
||||||
|
None => {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let silent = match msg.get("SILENT") {
|
||||||
|
Some(v) => v.to_lower() == "true"
|
||||||
|
None => false
|
||||||
|
}
|
||||||
|
let target_sess = match self.find_session_by_pub(dest_b64) {
|
||||||
|
Some(s) => s
|
||||||
|
None => {
|
||||||
|
if !silent {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"STREAM STATUS RESULT=CANT_REACH_PEER",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
client.closed = true
|
||||||
|
client.sock.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Find a waiting STREAM ACCEPT client for target_sess.id
|
||||||
|
let mut acceptor_idx = -1
|
||||||
|
for i = 0; i < self.sam_clients.length(); i = i + 1 {
|
||||||
|
let c = self.sam_clients[i]
|
||||||
|
if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id {
|
||||||
|
acceptor_idx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acceptor_idx < 0 {
|
||||||
|
if !silent {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"STREAM STATUS RESULT=CANT_REACH_PEER",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
client.closed = true
|
||||||
|
client.sock.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let acceptor = self.sam_clients[acceptor_idx]
|
||||||
|
if !silent {
|
||||||
|
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
|
||||||
|
}
|
||||||
|
if !acceptor.accept_silent {
|
||||||
|
let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64)
|
||||||
|
}
|
||||||
|
// Promote both sockets into a bidirectional raw stream bridge
|
||||||
|
client.mode = 2
|
||||||
|
acceptor.mode = 2
|
||||||
|
self.bridges.push({
|
||||||
|
a: client.sock,
|
||||||
|
b: acceptor.sock,
|
||||||
|
a_eof: false,
|
||||||
|
b_eof: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let _ = send_sam_line(
|
||||||
|
client.sock,
|
||||||
|
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Runs one non-blocking event-loop tick (accepting SAMv3 & NTCP2 connections,
|
||||||
|
/// processing SAMv3 commands, and pumping bridged stream relays).
|
||||||
|
pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
|
||||||
|
// 1. Accept any pending SAMv3 TCP connection
|
||||||
|
match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) {
|
||||||
|
Some(sock) =>
|
||||||
|
self.sam_clients.push({
|
||||||
|
sock,
|
||||||
|
session_id: None,
|
||||||
|
mode: 0,
|
||||||
|
accept_session_id: "",
|
||||||
|
accept_silent: false,
|
||||||
|
closed: false,
|
||||||
|
})
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Accept any pending incoming NTCP2 TCP connection (non-blocking)
|
||||||
|
match (self.ntcp2_listener.accept(timeout_ms=0) catch { _ => None }) {
|
||||||
|
Some(sock) => {
|
||||||
|
let res = try {
|
||||||
|
let conn = @ntcp2_net.accept_ntcp2(
|
||||||
|
sock,
|
||||||
|
self.static_key,
|
||||||
|
self.router_hash().as_bytes(),
|
||||||
|
self.ntcp2_iv,
|
||||||
|
timeout_ms=2000,
|
||||||
|
)
|
||||||
|
match conn.remote_router_info {
|
||||||
|
Some(peer_ri) => {
|
||||||
|
let _ = self.netdb.store_router_info(peer_ri) catch { _ => false }
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
conn.close()
|
||||||
|
true
|
||||||
|
} catch {
|
||||||
|
_ => {
|
||||||
|
sock.close()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = res
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Process readable SAMv3 command sockets
|
||||||
|
for i = 0; i < self.sam_clients.length(); i = i + 1 {
|
||||||
|
let c = self.sam_clients[i]
|
||||||
|
if c.closed || c.mode != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let ready = c.sock.poll_readable(0) catch { _ => false }
|
||||||
|
if !ready {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
match (c.sock.read_line() catch { _ => None }) {
|
||||||
|
Some(line) => if line.length() > 0 { self.handle_sam_command(i, line) }
|
||||||
|
None => {
|
||||||
|
c.closed = true
|
||||||
|
c.sock.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Pump bidirectional raw byte bridges for active STREAM connections
|
||||||
|
let mut bi = 0
|
||||||
|
while bi < self.bridges.length() {
|
||||||
|
let br = self.bridges[bi]
|
||||||
|
if !br.a_eof {
|
||||||
|
let r = br.a.poll_readable(0) catch { _ => false }
|
||||||
|
if r {
|
||||||
|
let data = br.a.read_some(4096) catch { _ => b"" }
|
||||||
|
if data.length() == 0 {
|
||||||
|
br.a_eof = true
|
||||||
|
br.b.shutdown_write()
|
||||||
|
} else {
|
||||||
|
br.b.write_all(data) catch {
|
||||||
|
_ => br.b_eof = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !br.b_eof {
|
||||||
|
let r = br.b.poll_readable(0) catch { _ => false }
|
||||||
|
if r {
|
||||||
|
let data = br.b.read_some(4096) catch { _ => b"" }
|
||||||
|
if data.length() == 0 {
|
||||||
|
br.b_eof = true
|
||||||
|
br.a.shutdown_write()
|
||||||
|
} else {
|
||||||
|
br.a.write_all(data) catch {
|
||||||
|
_ => br.a_eof = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if br.a_eof && br.b_eof {
|
||||||
|
br.a.close()
|
||||||
|
br.b.close()
|
||||||
|
let _ = self.bridges.remove(bi)
|
||||||
|
} else {
|
||||||
|
bi += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Runs the router event loop indefinitely.
|
||||||
|
pub fn Router::run(self : Router) -> Unit {
|
||||||
|
while true {
|
||||||
|
self.step(poll_ms=10)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
///|
|
||||||
|
test "Router transient startup, self-signed RouterInfo, and embedded SAMv3 bridge" {
|
||||||
|
let r = @router.Router::start({
|
||||||
|
sam_host: "127.0.0.1",
|
||||||
|
sam_port: 0,
|
||||||
|
ntcp2_host: "127.0.0.1",
|
||||||
|
ntcp2_port: 0,
|
||||||
|
})
|
||||||
|
assert_eq(r.router_info.verify_signature(), true)
|
||||||
|
assert_eq(r.netdb.router_count(), 1)
|
||||||
|
assert_true(r.sam_port() > 0)
|
||||||
|
assert_true(r.ntcp2_port() > 0)
|
||||||
|
|
||||||
|
// Connect to embedded SAMv3 bridge and run HELLO + DEST GENERATE + SESSION CREATE + NAMING LOOKUP
|
||||||
|
let sock = @ntcp2_net.TcpSocket::connect("127.0.0.1", r.sam_port())
|
||||||
|
r.step(poll_ms=50)
|
||||||
|
|
||||||
|
sock.write_all(b"HELLO VERSION MIN=3.1 MAX=3.3\n")
|
||||||
|
r.step(poll_ms=50)
|
||||||
|
assert_eq(sock.read_line(), Some("HELLO REPLY RESULT=OK VERSION=3.3"))
|
||||||
|
|
||||||
|
sock.write_all(b"DEST GENERATE SIGNATURE_TYPE=7\n")
|
||||||
|
r.step(poll_ms=50)
|
||||||
|
let dest_line = match sock.read_line() {
|
||||||
|
Some(l) => l
|
||||||
|
None => fail("expected DEST REPLY")
|
||||||
|
}
|
||||||
|
assert_true(dest_line.has_prefix("DEST REPLY PUB="))
|
||||||
|
|
||||||
|
sock.write_all(
|
||||||
|
b"SESSION CREATE STYLE=STREAM ID=test1 DESTINATION=TRANSIENT\n",
|
||||||
|
)
|
||||||
|
r.step(poll_ms=50)
|
||||||
|
let sess_line = match sock.read_line() {
|
||||||
|
Some(l) => l
|
||||||
|
None => fail("expected SESSION STATUS")
|
||||||
|
}
|
||||||
|
assert_true(sess_line.has_prefix("SESSION STATUS RESULT=OK DESTINATION="))
|
||||||
|
assert_eq(r.netdb.leaseset_count(), 1)
|
||||||
|
|
||||||
|
sock.write_all(b"NAMING LOOKUP NAME=ME\n")
|
||||||
|
r.step(poll_ms=50)
|
||||||
|
let lookup_line = match sock.read_line() {
|
||||||
|
Some(l) => l
|
||||||
|
None => fail("expected NAMING REPLY")
|
||||||
|
}
|
||||||
|
assert_true(lookup_line.has_prefix("NAMING REPLY RESULT=OK NAME=ME VALUE="))
|
||||||
|
|
||||||
|
sock.close()
|
||||||
|
r.close()
|
||||||
|
}
|
||||||
Reference in new issue
Block a user