docs: cite upstream files without line numbers in comments

This commit is contained in:
DeFiDude committed 2026-11-12 06:58:07 -07:00
1 parent 8fade5d1e9
commit 88724e75d0
120 files changed
+1027 -1027

No files matched your search

+1 -1
View File
@@ -250,7 +250,7 @@ mod tests {
assert_ne!(t1, t2);
}
/// Legacy AES-128 round-trip via 32-byte key (Python `Token.py:62-65`).
/// Legacy AES-128 round-trip via 32-byte key (Python `Token.py`).
#[test]
fn test_encrypt_decrypt_roundtrip_aes128() {
let key = [0x42u8; 32];
+7 -7
View File
@@ -1,5 +1,5 @@
//! `git-remote-rns`: the git remote helper for `rns://` URLs
//! (`RNS/Utilities/rngit/client.py@1.6.0`).
//! (`RNS/Utilities/rngit/client.py`).
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -18,11 +18,11 @@ use rns_runtime::reticulum::{LinkConnectOptions, ReticulumHandle};
use rns_tools::rsg::pyfmt::py_fromhex;
use rns_transport::messages::PathRequestOptions;
/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py:74`).
/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py`).
const LOG_MAXSIZE: u64 = 5 * 1024 * 1024;
/// `client_log`, appended per line and rotated to `.1` past `LOG_MAXSIZE`
/// as `RNS.log` does with `LOG_FILE` (`RNS/__init__.py:137-143`).
/// as `RNS.log` does with `LOG_FILE` (`RNS/__init__.py`).
#[derive(Clone)]
struct ClientLog(PathBuf);
@@ -109,7 +109,7 @@ fn response_value(value: rmpv::Value) -> Response {
}
}
/// `abort()`; `sys.exit` also runs Reticulum's exit handler (Reticulum.py:389).
/// `abort()`; `sys.exit` also runs Reticulum's exit handler (Reticulum.py).
fn abort(
reason: Abort,
link: Option<&LinkSessionHandle>,
@@ -133,7 +133,7 @@ async fn path_ready(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
&& matches!(handle.recall_without_use(hash).await, Ok(Some(_)))
}
/// `Transport.await_path` with `medium_path_timeout(PATH_TIMEOUT)` (`client.py:229`).
/// `Transport.await_path` with `medium_path_timeout(PATH_TIMEOUT)` (`client.py`).
async fn await_path(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
if path_ready(handle, hash).await {
return true;
@@ -234,7 +234,7 @@ fn main() {
}
let destination = config.resolve_destination(&url.destination);
// connect_server (client.py:223-244)
// connect_server (client.py)
let hash = match py_fromhex(&destination) {
Ok(hash) => hash,
Err(e) => abort(
@@ -274,7 +274,7 @@ fn main() {
status("\rEstablishing link...");
// The Link fails at its own establishment timeout, which ends run()'s
// max(15, establishment_timeout) wait (client.py:341-346).
// max(15, establishment_timeout) wait (client.py).
let options = LinkConnectOptions {
client_label: "git-remote-rns".to_string(),
identify: true,
+11 -11
View File
@@ -1,4 +1,4 @@
//! `rngit-rs`: the Reticulum Git repository node (`RNS/Utilities/rngit/server.py@1.6.0`).
//! `rngit-rs`: the Reticulum Git repository node (`RNS/Utilities/rngit/server.py`).
use std::collections::HashMap;
use std::path::PathBuf;
@@ -202,7 +202,7 @@ fn deferred_page(
}
}
/// The `nomadnetwork.node` destination (`pages.py:179-183`): app data is the node name.
/// The `nomadnetwork.node` destination (`pages.py`): app data is the node name.
async fn start_page_node(
handle: &rns_runtime::reticulum::ReticulumHandle,
identity: Identity,
@@ -394,7 +394,7 @@ struct SyncArgs {
version: bool,
}
/// `rngit fork`, `rngit mirror` and `rngit sync` (`server.py:193-215`, `262-275`).
/// `rngit fork`, `rngit mirror` and `rngit sync` (`server.py`).
async fn clone_subcommand(op: Operation, argv: Vec<String>) {
// (version, config, rnsconfig, identity, source, target, verbose, quiet)
let parsed = match op {
@@ -496,7 +496,7 @@ struct PermsCliArgs {
version: bool,
}
/// `rngit work` (`server.py:182-191`, `255-260`, `106-122`).
/// `rngit work` (`server.py`).
async fn work_subcommand(argv: Vec<String>) {
use rns_git::client::work::{CommonArgs, WorkArgs, run_client, run_work};
let args = WorkCliArgs::parse_from(argv);
@@ -540,7 +540,7 @@ async fn work_subcommand(argv: Vec<String>) {
.await
}
/// `rngit perms` (`server.py:175-180`, `245-253`, `100-104`).
/// `rngit perms` (`server.py`).
async fn perms_subcommand(argv: Vec<String>) {
use rns_git::client::perms::{perms_target, run_perms};
use rns_git::client::work::{CommonArgs, run_client};
@@ -613,13 +613,13 @@ struct ReleaseArgs {
version: bool,
}
/// `ReticulumGitClient.abort` (`server.py:402-403`).
/// `ReticulumGitClient.abort` (`server.py`).
async fn abort(handle: &rns_runtime::reticulum::ReticulumHandle, message: &str) -> ! {
println!("{message}");
rns_tools::exit(handle, 1).await
}
/// `rngit create` (`server.py:85-87`, `create_repository` `server.py:569-604`).
/// `rngit create` (`server.py`, `create_repository` `server.py`).
async fn create(args: CreateArgs) {
use rns_git::server::client::{ClientConfig, client_config_dir, create_outcome};
use rns_git::server::{IDX_REPOSITORY, PATH_CREATE};
@@ -809,7 +809,7 @@ impl ReleaseRemote for LinkRemote {
}
}
/// `rngit release` (`server.py:84-99`, `715-1239`).
/// `rngit release` (`server.py`).
async fn release(args: ReleaseArgs) {
use rns_git::client::releases::{Fail, ReleaseOp};
use rns_git::server::client::{ClientConfig, client_config_dir};
@@ -1004,7 +1004,7 @@ async fn release(args: ReleaseArgs) {
}
}
/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py:74`).
/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py`).
const LOG_MAXSIZE: u64 = 5 * 1024 * 1024;
/// The `-s` log file: appended per line and rotated to `.1` past
@@ -1372,7 +1372,7 @@ async fn main() {
}
let mut last_page_announce: Option<Instant> = None;
// The jobs loop (server.py:2656-2661): the first tick announces when an interval is set.
// The jobs loop (server.py): the first tick announces when an interval is set.
let announce_interval = config.announce_interval;
let mut last_announce: Option<Instant> = None;
let mut last_persist = Instant::now();
@@ -1407,7 +1407,7 @@ async fn main() {
}
last_announce = Some(Instant::now());
}
// The page node's own jobs loop (pages.py:218-228) announces on the same interval.
// The page node's own jobs loop (pages.py) announces on the same interval.
if let Some(pages) = &pages
&& announce_interval != 0
&& last_page_announce
+5 -5
View File
@@ -1,6 +1,6 @@
//! `rngit fork`, `rngit mirror` and `rngit sync` (`fork_repository`,
//! `mirror_repository`, `_remote_clone_operation`, `sync_repository`,
//! `server.py:606-716@1.6.0`).
//! `server.py`).
use std::io::Write;
use std::path::PathBuf;
@@ -60,7 +60,7 @@ fn reply_text(response: &[u8], fallback: &str) -> String {
}
/// What `_remote_clone_operation` and `sync_repository` print for a reply
/// (`server.py:646-667`, `694-711`): `Ok` on success, `Err` for the abort text.
/// (`server.py`): `Ok` on success, `Err` for the abort text.
pub fn outcome(op: Operation, repo_path: &str, response: Option<&[u8]>) -> Result<String, String> {
let Some(response) = response.filter(|r| !r.is_empty()) else {
return Err("No response from remote".into());
@@ -84,7 +84,7 @@ fn prettyhex(hash: &[u8]) -> String {
format!("<{}>", hex::encode(hash))
}
/// `ReticulumGitClient.abort` (`server.py:433-434`).
/// `ReticulumGitClient.abort` (`server.py`).
async fn abort(handle: &ReticulumHandle, message: &str) -> ! {
println!("{message}");
rns_tools::exit(handle, 1).await
@@ -152,7 +152,7 @@ pub async fn run(op: Operation, args: ClientArgs) -> ! {
}
};
// fork_repository / mirror_repository, then _resolve_aliased_url (server.py:610-626).
// fork_repository / mirror_repository, then _resolve_aliased_url (server.py).
let mut source = None;
if op != Operation::Sync {
let Some(src) = non_empty(args.source) else {
@@ -177,7 +177,7 @@ pub async fn run(op: Operation, args: ClientArgs) -> ! {
abort(&handle, "No remote specified").await;
}
// connect_remote (server.py:466-483).
// connect_remote (server.py).
let remote = args.target;
let destination = match config.parse_remote_destination_url(&remote) {
Ok(hash) => hash,
+1 -1
View File
@@ -1,4 +1,4 @@
//! `rngit` client subcommands (`ReticulumGitClient`, `server.py:281-1830@1.6.0`).
//! `rngit` client subcommands (`ReticulumGitClient`, `server.py`).
pub mod forks;
pub mod perms;
+2 -2
View File
@@ -1,5 +1,5 @@
//! `rngit perms` (`group_permissions` and `repository_permissions`,
//! `server.py:1241-1339@1.6.0`).
//! `server.py`).
use std::io::Write;
@@ -17,7 +17,7 @@ pub enum PermsTarget {
Repository,
}
/// `args.remote.rstrip("/")` and the component count (`server.py:245-249`);
/// `args.remote.rstrip("/")` and the component count (`server.py`);
/// `None` is "Invalid URL".
pub fn perms_target(remote: &str) -> Option<(String, PermsTarget)> {
let remote = remote.trim_end_matches('/').to_string();
+13 -13
View File
@@ -1,4 +1,4 @@
//! `rngit release` (`ReticulumGitClient` release methods, `server.py:715-1239@1.6.0`).
//! `rngit release` (`ReticulumGitClient` release methods, `server.py`).
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -15,7 +15,7 @@ use crate::server::client::ClientConfig;
use crate::server::releases::py_basename;
use crate::server::{IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND};
/// The `rngit release` operations (`server.py:89-98`).
/// The `rngit release` operations (`server.py`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReleaseOp {
List,
@@ -185,7 +185,7 @@ fn py_str(value: &Value) -> String {
rns_tools::rsg::pyfmt::py_str(value)
}
/// `list_releases` after the Link is up (`server.py:774-818`).
/// `list_releases` after the Link is up (`server.py`).
pub fn list_releases(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -272,7 +272,7 @@ pub fn list_releases(
Ok(())
}
/// `view_release` after the Link is up (`server.py:832-877`).
/// `view_release` after the Link is up (`server.py`).
pub fn view_release(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -344,7 +344,7 @@ pub fn view_release(
}
/// `delete_release` and `latest_release` after the Link is up
/// (`server.py:1160-1192`, `1203-1239`): confirm, then send.
/// (`server.py`): confirm, then send.
pub fn confirm_and_send(
out: &mut dyn Write,
input: &mut dyn std::io::BufRead,
@@ -433,7 +433,7 @@ pub fn fnmatch(name: &str, pattern: &str) -> bool {
go(&name, &pattern)
}
/// `signer` on fetch/verify: a 32-hex required signer hash (`server.py:881-884`).
/// `signer` on fetch/verify: a 32-hex required signer hash (`server.py`).
pub fn required_signer(signer: Option<&str>) -> Result<Option<Vec<u8>>, Fail> {
let Some(signer) = signer.filter(|s| !s.is_empty()) else {
return Ok(None);
@@ -461,7 +461,7 @@ impl Manifest {
}
}
/// The manifest checks of `fetch_release` (`server.py:888-898`, `936-945`).
/// The manifest checks of `fetch_release` (`server.py`).
/// `inside_try` selects how an exception surfaces.
fn check_manifest(
rsg: Vec<u8>,
@@ -530,7 +530,7 @@ fn file_valid(rsg: &[u8], path: &Path, required: Option<&[u8]>) -> Result<bool,
.map_err(|e| Fail::Abort(format!("Error fetching release: {e}")))
}
/// `fetch_release` (`server.py:879-1013`); `verify` is `offline`. Files land
/// `fetch_release` (`server.py`); `verify` is `offline`. Files land
/// in the current directory. `Ok` is the exit code.
pub fn fetch_release(
out: &mut dyn Write,
@@ -765,10 +765,10 @@ pub fn fetch_release(
Ok(0)
}
/// `RELEASE_NOTES_TEMPLATE` (`server.py:5081-5084`).
/// `RELEASE_NOTES_TEMPLATE` (`server.py`).
const RELEASE_NOTES_TEMPLATE: &str = "# Enter release notes for {TAG}.\n# Lines starting with '#' will be ignored.\n# Save and exit the editor when done, or exit without saving to abort.\n";
/// `_edit_release_notes` (`server.py:719-760`). `None` cancels the release.
/// `_edit_release_notes` (`server.py`). `None` cancels the release.
fn edit_release_notes(out: &mut dyn Write, tag: &str) -> Option<String> {
let mut editor = std::env::var("EDITOR").unwrap_or_default();
if editor.is_empty() {
@@ -825,7 +825,7 @@ fn edit_release_notes(out: &mut dyn Write, tag: &str) -> Option<String> {
(!notes.is_empty()).then_some(notes)
}
/// `__commit_hash_from_tag` (`server.py:395-410`), run in `./`.
/// `__commit_hash_from_tag` (`server.py`), run in `./`.
fn commit_hash_from_tag(tag: &str) -> Option<String> {
let output = std::process::Command::new("git")
.args(["rev-list", "-n", "1", tag])
@@ -860,7 +860,7 @@ fn generation_failed(e: impl std::fmt::Display) -> Fail {
Fail::Abort(format!("Release manifest generation failed: {e}"))
}
/// `create_release` (`server.py:1015-1149`). `signer` is an identity path;
/// `create_release` (`server.py`). `signer` is an identity path;
/// without it the client identity signs. `Ok` is the exit code.
#[allow(clippy::too_many_arguments)]
pub fn create_release(
@@ -1077,7 +1077,7 @@ pub fn create_release(
Ok(0)
}
/// `list` and `view` share the connect-then-request shape (`server.py:762-877`).
/// `list` and `view` share the connect-then-request shape (`server.py`).
pub fn run_simple(
out: &mut dyn Write,
input: &mut dyn std::io::BufRead,
+14 -14
View File
@@ -1,5 +1,5 @@
//! `rngit work` (`ReticulumGitClient.work_*` and the editor helpers,
//! `server.py:1347-1923@1.6.0`).
//! `server.py`).
use std::io::{BufRead, Write};
use std::path::PathBuf;
@@ -15,12 +15,12 @@ use super::releases::{Connect, Fail, Remote, Response};
use crate::server::client::{ClientConfig, client_config_dir};
use crate::server::{APP_NAME, IDX_REPOSITORY};
/// `COMMENT_TEMPLATE`, `CREATE_DOC_TEMPLATE` and `PERMISSIONS_TEMPLATE` (`server.py:5086-5088`).
/// `COMMENT_TEMPLATE`, `CREATE_DOC_TEMPLATE` and `PERMISSIONS_TEMPLATE` (`server.py`).
pub const COMMENT_TEMPLATE: &str = "# Remove this line and enter your update. Save and exit when done, or save an empty document to abort abort.";
pub const CREATE_DOC_TEMPLATE: &str = "# Remove this line and enter your document content. Save and exit when done, or save an empty document to abort abort.";
pub const PERMISSIONS_TEMPLATE: &str = "# No permissions are currently defined for this entity. Add them below, and save and exit when you are done.";
/// The `rngit work` operations (`server.py:112-122`).
/// The `rngit work` operations (`server.py`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorkOp {
List,
@@ -228,7 +228,7 @@ fn py_strip(s: &str) -> &str {
s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c))
}
/// `_edit_work_content` (`server.py:1844-1887`): template lines are dropped,
/// `_edit_work_content` (`server.py`): template lines are dropped,
/// the rest stripped; empty is None.
pub fn edit_work_content(out: &mut dyn Write, content: &str, is_comment: bool) -> Option<String> {
let editor = find_editor(out)?;
@@ -259,7 +259,7 @@ pub fn edit_work_content(out: &mut dyn Write, content: &str, is_comment: bool) -
}
}
/// `_edit_permissions` (`server.py:1889-1923`): the file as saved, even empty.
/// `_edit_permissions` (`server.py`): the file as saved, even empty.
pub fn edit_permissions(out: &mut dyn Write, content: &str) -> Option<String> {
let editor = find_editor(out)?;
let template = if content.is_empty() {
@@ -284,7 +284,7 @@ fn request(repo_path: &str, fields: Vec<(&str, Value)>) -> Value {
const CLEAR: &str = "\r \r";
/// `work_list` after the Link is up (`server.py:1359-1402`).
/// `work_list` after the Link is up (`server.py`).
fn work_list(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -377,7 +377,7 @@ fn work_list(
Ok(())
}
/// `work_view` after the Link is up (`server.py:1416-1477`).
/// `work_view` after the Link is up (`server.py`).
fn work_view(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -486,7 +486,7 @@ fn result_field(body: &[u8], key: &str, context: &str) -> Result<String, Fail> {
.ok_or_else(|| Fail::Abort(format!("{context}: '{key}'")))
}
/// `work_create` and `work_propose` after the Link is up (`server.py:1491-1567`).
/// `work_create` and `work_propose` after the Link is up (`server.py`).
fn work_new(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -539,7 +539,7 @@ fn work_new(
Ok(())
}
/// `work_edit` after the Link is up (`server.py:1581-1621`).
/// `work_edit` after the Link is up (`server.py`).
fn work_edit(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -590,7 +590,7 @@ fn work_edit(
Ok(())
}
/// `work_delete` after the Link is up (`server.py:1635-1661`).
/// `work_delete` after the Link is up (`server.py`).
fn work_delete(
out: &mut dyn Write,
input: &mut dyn BufRead,
@@ -626,7 +626,7 @@ fn work_delete(
Ok(())
}
/// `work_comment` after the Link is up (`server.py:1675-1704`).
/// `work_comment` after the Link is up (`server.py`).
fn work_comment(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -658,7 +658,7 @@ fn work_comment(
Ok(())
}
/// `work_complete` and `work_activate` after the Link is up (`server.py:1718-1782`).
/// `work_complete` and `work_activate` after the Link is up (`server.py`).
fn work_move(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -686,7 +686,7 @@ fn work_move(
}
/// The get, edit and set round of every permissions command
/// (`server.py:1255-1287`, `1796-1834`).
/// (`server.py`).
pub(crate) fn edit_remote_permissions(
out: &mut dyn Write,
remote: &mut dyn Remote,
@@ -709,7 +709,7 @@ pub(crate) fn edit_remote_permissions(
}
/// `rngit work <repository> <operation>` once Reticulum is up
/// (`server.py:106-122`, `1347-1838`). `Ok` is the exit code.
/// (`server.py`). `Ok` is the exit code.
pub fn run_work(
out: &mut dyn Write,
input: &mut dyn BufRead,
+12 -12
View File
@@ -1,8 +1,8 @@
//! Micron syntax highlighting: a port of `RNS/Utilities/rngit/highlight.py@1.6.0`.
//! Micron syntax highlighting: a port of `RNS/Utilities/rngit/highlight.py`.
//!
//! Upstream colours code only when the optional Pygments package is
//! installed (`highlight.py:141-154`, `:178-202`). This port has no lexer and
//! always takes upstream's path without Pygments (`highlight.py:156-176`):
//! installed (`highlight.py`). This port has no lexer and
//! always takes upstream's path without Pygments (`highlight.py`):
//! a Micron literal block. [`MicronFormatter`] is ported for token streams
//! from any lexer that names its tokens the way Pygments does.
@@ -11,7 +11,7 @@ use std::collections::HashMap;
/// Theme key to `rrggbb` colour; `None` means no colour tag.
pub type Theme = HashMap<String, Option<String>>;
/// Python `SyntaxHighlighter._get_default_theme` (`highlight.py:44-139`).
/// Python `SyntaxHighlighter._get_default_theme` (`highlight.py`).
pub fn default_theme() -> Theme {
DEFAULT_THEME
.iter()
@@ -19,7 +19,7 @@ pub fn default_theme() -> Theme {
.collect()
}
/// Python `SyntaxHighlighter` (`highlight.py:35-209`) without Pygments.
/// Python `SyntaxHighlighter` (`highlight.py`) without Pygments.
#[derive(Debug, Clone)]
pub struct SyntaxHighlighter {
pub theme: Theme,
@@ -43,7 +43,7 @@ impl SyntaxHighlighter {
false
}
/// Python `highlight` (`highlight.py:156-176`). Upstream doubles
/// Python `highlight` (`highlight.py`). Upstream doubles
/// backslashes on every path except empty content.
pub fn highlight(
&self,
@@ -58,7 +58,7 @@ impl SyntaxHighlighter {
}
}
/// Python `highlight_code` (`highlight.py:312-314`).
/// Python `highlight_code` (`highlight.py`).
pub fn highlight_code(
content: &str,
filename: Option<&str>,
@@ -68,12 +68,12 @@ pub fn highlight_code(
SyntaxHighlighter::new(theme).highlight(content, filename, language)
}
/// Python `_plain_text` (`highlight.py:204-206`).
/// Python `_plain_text` (`highlight.py`).
fn plain_text(content: &str) -> String {
format!("`=\n{}\n`=", content.replace('`', "\\`"))
}
/// Python `MicronFormatter` (`highlight.py:212-309`).
/// Python `MicronFormatter` (`highlight.py`).
#[derive(Debug, Clone)]
pub struct MicronFormatter {
pub theme: Theme,
@@ -84,7 +84,7 @@ impl MicronFormatter {
Self { theme }
}
/// Python `format` (`highlight.py:217-278`). A token type is its dotted
/// Python `format` (`highlight.py`). A token type is its dotted
/// Pygments name, such as `Token.Name.Function`.
pub fn format<'a>(&self, tokens: impl IntoIterator<Item = (&'a str, &'a str)>) -> String {
let mut out = String::new();
@@ -148,7 +148,7 @@ impl MicronFormatter {
}
}
/// Python `_get_color_key_for_token` (`highlight.py:280-297`): the nearest
/// Python `_get_color_key_for_token` (`highlight.py`): the nearest
/// mapped ancestor of the token type.
fn color_key_for_token(ttype: &str) -> Option<&'static str> {
let mut current = Some(ttype);
@@ -161,7 +161,7 @@ fn color_key_for_token(ttype: &str) -> Option<&'static str> {
None
}
/// Python `_escape_value` (`highlight.py:303-305`).
/// Python `_escape_value` (`highlight.py`).
fn escape_value(value: &str) -> String {
value.replace('\\', "\\\\").replace('`', "\\`")
}
+20 -20
View File
@@ -1,12 +1,12 @@
//! Markdown to Micron conversion: a port of `MarkdownToMicron` and
//! `convert_markdown_to_micron` from `RNS/Utilities/rngit/util.py@1.6.0`
//! `convert_markdown_to_micron` from `RNS/Utilities/rngit/util.py`
//! (`:79-816`).
//!
//! Upstream's regular expressions are matched by hand with the same Python
//! `re` semantics: `\s` is Python's Unicode whitespace, `\d` any Unicode
//! decimal digit. Display width is the character count, which is what
//! upstream uses when the optional `wcwidth` module is absent
//! (`util.py:150-156`). Input lines never contain `\n`: `format_block`
//! (`util.py`). Input lines never contain `\n`: `format_block`
//! splits on it first, as upstream does.
use std::convert::Infallible;
@@ -44,7 +44,7 @@ pub enum Align {
Right,
}
/// Python `MarkdownToMicron` (`util.py:79-811`).
/// Python `MarkdownToMicron` (`util.py`).
#[derive(Debug, Clone)]
pub struct MarkdownToMicron {
pub max_width: usize,
@@ -62,7 +62,7 @@ impl Default for MarkdownToMicron {
}
}
/// Python `convert_markdown_to_micron` (`util.py:814-816`).
/// Python `convert_markdown_to_micron` (`util.py`).
pub fn convert_markdown_to_micron(text: &str) -> Result<String, MarkdownError> {
MarkdownToMicron::default().format_block(text)
}
@@ -95,7 +95,7 @@ impl MarkdownToMicron {
pub const TABLE_MIN_COL_WIDTH: usize = 3;
/// An empty or absent `url_scope` selects `:/page/`, as upstream's
/// `url_scope or ":/page/"` does (`util.py:130-145`).
/// `url_scope or ":/page/"` does (`util.py`).
pub fn new(
max_width: usize,
syntax_highlighter: Option<SyntaxHighlighter>,
@@ -120,7 +120,7 @@ impl MarkdownToMicron {
self.local_url_scope = url_scope.to_string();
}
/// Back to the scope given at construction (`util.py:148`).
/// Back to the scope given at construction (`util.py`).
pub fn restore_url_scope(&mut self) {
self.local_url_scope = self.initial_url_scope.clone();
}
@@ -129,7 +129,7 @@ impl MarkdownToMicron {
text.len()
}
/// Python `format_block` (`util.py:158-302`).
/// Python `format_block` (`util.py`).
pub fn format_block(&self, text: &str) -> Result<String, MarkdownError> {
let mut st = BlockState::default();
for line in text.split('\n') {
@@ -193,7 +193,7 @@ impl MarkdownToMicron {
Ok(st.out.join("\n"))
}
/// Python `format_line(line)` (`util.py:304-322`).
/// Python `format_line(line)` (`util.py`).
pub fn format_line(&self, line: &str) -> Result<String, MarkdownError> {
let mut line = line.replace('\\', "\\\\");
if line.starts_with('-') && !line.starts_with("---") && !line.starts_with("- ") {
@@ -226,12 +226,12 @@ impl MarkdownToMicron {
self.format_inline(&line)
}
/// Python `format_line(line, mode="codeblock")` (`util.py:305`).
/// Python `format_line(line, mode="codeblock")` (`util.py`).
pub fn format_codeblock_line(&self, line: &str) -> String {
escape_literals(line)
}
/// Python `_format_inline` (`util.py:324-371`).
/// Python `_format_inline` (`util.py`).
pub fn format_inline(&self, text: &str) -> Result<String, MarkdownError> {
let mut links: Vec<(String, String)> = Vec::new();
let mut codes: Vec<String> = Vec::new();
@@ -283,12 +283,12 @@ impl MarkdownToMicron {
}
}
/// Python `format_table` (`util.py:423-528`); `align` empty means none.
/// Python `format_table` (`util.py`); `align` empty means none.
pub fn format_table(&self, rows: &[String], align: &str) -> Result<Vec<String>, MarkdownError> {
self.table(rows, align, false, |cell| self.format_inline(cell))
}
/// Python `format_table_raw` (`util.py:530-631`): cells are not formatted
/// Python `format_table_raw` (`util.py`): cells are not formatted
/// and the header row is not escaped.
pub fn format_table_raw(&self, rows: &[String], align: &str) -> Vec<String> {
let Ok(lines) = self.table(rows, align, true, |cell| {
@@ -390,7 +390,7 @@ impl MarkdownToMicron {
Ok(result)
}
/// Python `_visible_width` (`util.py:667-674`): the six tag patterns are
/// Python `_visible_width` (`util.py`): the six tag patterns are
/// removed one pass each, in upstream's order.
fn visible_width(&self, text: &[char]) -> usize {
let hex = |c: &[char], from: usize, n: usize| {
@@ -419,7 +419,7 @@ impl MarkdownToMicron {
self.display_width(&s)
}
/// Python `_pad_cell` (`util.py:676-688`).
/// Python `_pad_cell` (`util.py`).
fn pad_cell(&self, text: &str, width: usize, align: Align) -> String {
let text = self.truncate_cell(text, width);
let c: Vec<char> = text.chars().collect();
@@ -434,7 +434,7 @@ impl MarkdownToMicron {
}
}
/// Python `_truncate_cell` (`util.py:690-746`). Upstream appends the open
/// Python `_truncate_cell` (`util.py`). Upstream appends the open
/// toggle closers in `set` order, which varies per process; this emits
/// them in `!*_=` order, one of upstream's possible outputs.
fn truncate_cell(&self, text: &str, width: usize) -> String {
@@ -503,7 +503,7 @@ impl MarkdownToMicron {
out
}
/// Python `_wrap_text` (`util.py:748-811`).
/// Python `_wrap_text` (`util.py`).
fn wrap_text(&self, text: &str, width: usize) -> Vec<String> {
if text.is_empty() {
return vec![String::new()];
@@ -614,7 +614,7 @@ impl BlockState {
Ok(())
}
/// Upstream's `except Exception` fallback (`util.py:218-224`) has no
/// Upstream's `except Exception` fallback (`util.py`) has no
/// counterpart: the highlighter here cannot fail.
fn flush_code(&mut self, m: &MarkdownToMicron) {
if self.code_buffer.is_empty() {
@@ -742,7 +742,7 @@ fn table_row_group(c: &[char]) -> Option<&[char]> {
None
}
/// Python `_is_table_row` (`util.py:408-413`).
/// Python `_is_table_row` (`util.py`).
fn is_table_row(line: &str) -> bool {
if !line.contains('|') {
return false;
@@ -784,7 +784,7 @@ fn is_table_separator(line: &str) -> bool {
c[j..].iter().all(|x| py_space(*x))
}
/// Python `_parse_table_row` (`util.py:633-654`).
/// Python `_parse_table_row` (`util.py`).
fn parse_table_row(line: &str) -> Vec<String> {
let line = py_strip(line);
let line = line.strip_prefix('|').unwrap_or(line);
@@ -809,7 +809,7 @@ fn parse_table_row(line: &str) -> Vec<String> {
cells
}
/// Python `_parse_table_alignments` (`util.py:656-665`).
/// Python `_parse_table_alignments` (`util.py`).
fn parse_table_alignments(line: &str) -> Vec<Align> {
parse_table_row(line)
.iter()
+1 -1
View File
@@ -1,4 +1,4 @@
//! The stats page charts (`render_chart_halfblock`, `render_combined_chart`, `pages.py:2740-2928@1.6.0`).
//! The stats page charts (`render_chart_halfblock`, `render_combined_chart`, `pages.py`).
use super::{CLR_DIM, RCLR_DOWNLOAD, RCLR_FETCH, RCLR_PUSH, RCLR_VIEW};
+1 -1
View File
@@ -1,4 +1,4 @@
//! `/media` and the `/file/*` handlers (`pages.py:1750-2037@1.6.0`).
//! `/media` and the `/file/*` handlers (`pages.py`).
use std::io::{Read, Seek, Write};
use std::path::PathBuf;
+1 -1
View File
@@ -1,4 +1,4 @@
//! Git data extraction for the page node (`pages.py:2043-2616@1.6.0`).
//! Git data extraction for the page node (`pages.py`).
use std::io::Read;
use std::path::Path;
+3 -3
View File
@@ -1,4 +1,4 @@
//! The Nomad Network page node (`RNS/Utilities/rngit/pages.py@1.6.0`).
//! The Nomad Network page node (`RNS/Utilities/rngit/pages.py`).
mod chart;
mod files;
@@ -108,7 +108,7 @@ const PLAIN_TEMPLATES: [&str; 12] = [
"work", "work_doc",
];
/// The `[pages]` keys `NomadNetworkNode.__init__` reads (`pages.py:159-177`).
/// The `[pages]` keys `NomadNetworkNode.__init__` reads (`pages.py`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PageOptions {
pub use_nerdfonts: bool,
@@ -400,7 +400,7 @@ impl PageNode {
}
}
/// `render_template` (`pages.py:292-313`).
/// `render_template` (`pages.py`).
pub(crate) fn render(
&self,
page_content: &str,
+3 -3
View File
@@ -1,4 +1,4 @@
//! The `/page/*.mu` handlers (`pages.py:366-1748@1.6.0`).
//! The `/page/*.mu` handlers (`pages.py`).
use std::path::{Path, PathBuf};
use std::time::Instant;
@@ -31,7 +31,7 @@ fn capitalize(s: &str) -> String {
}
}
/// `format_diff` (`pages.py:2653-2674`).
/// `format_diff` (`pages.py`).
fn format_diff(diff: &str) -> String {
let doubled = diff.replace('\\', "\\\\");
let mut lines = Vec::new();
@@ -66,7 +66,7 @@ fn format_diff(diff: &str) -> String {
lines.join("\n")
}
/// `format_commit` (`pages.py:2676-2684`).
/// `format_commit` (`pages.py`).
fn format_commit(message: &str) -> String {
message
.replace('\\', "\\\\")
+14 -14
View File
@@ -1,5 +1,5 @@
//! `git-remote-rns`, the git remote helper for `rns://` URLs
//! (`RNS/Utilities/rngit/client.py@1.6.0`), without the network part.
//! (`RNS/Utilities/rngit/client.py`), without the network part.
use std::collections::BTreeMap;
use std::io::{BufRead, Write};
@@ -15,18 +15,18 @@ use crate::server::{
IDX_REPOSITORY, IDX_RESULT_CODE, PATH_DELETE, PATH_FETCH, PATH_LIST, PATH_PUSH,
};
/// The file written when the config directory has none (`client.py:681-718`).
/// The file written when the config directory has none (`client.py`).
pub const DEFAULT_CLIENT_CONFIG: &str = include_str!("client_default_config.txt");
pub const REF_BATCH_SIZE: usize = 25;
pub const PATH_TIMEOUT: f64 = 15.0;
/// `send_request`'s default timeout, used for every request (`client.py:310`).
/// `send_request`'s default timeout, used for every request (`client.py`).
pub const REQUEST_TIMEOUT: f64 = 7200.0;
const LOG_NONE: i64 = -1;
const LOG_EXTREME: i64 = 8;
/// The parts of an `rns://<destination>/<group>/<repo>` URL (`client.py:60-71`).
/// The parts of an `rns://<destination>/<group>/<repo>` URL (`client.py`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HelperUrl {
pub destination: String,
@@ -35,7 +35,7 @@ pub struct HelperUrl {
}
impl HelperUrl {
/// The repository path sent on the wire (`client.py:117`).
/// The repository path sent on the wire (`client.py`).
pub fn repo_path(&self) -> String {
format!("{}/{}", self.group, self.repo)
}
@@ -64,7 +64,7 @@ pub fn parse_args(args: &[String]) -> Result<HelperUrl, (String, i32)> {
})
}
/// The config directory (`client.py:134-137`). When `~/.config/rngit/config`
/// The config directory (`client.py`). When `~/.config/rngit/config`
/// exists upstream picks `~/.rngit/reticulum`, not `~/.config/rngit`.
pub fn resolve_config_dir(configdir: Option<&Path>, home: &Path) -> PathBuf {
if let Some(dir) = configdir {
@@ -78,7 +78,7 @@ pub fn resolve_config_dir(configdir: Option<&Path>, home: &Path) -> PathBuf {
}
}
/// What `__apply_config` takes from `client_config` (`client.py:168-187`).
/// What `__apply_config` takes from `client_config` (`client.py`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientConfig {
pub ref_batch_size: usize,
@@ -164,7 +164,7 @@ impl ClientConfig {
})
}
/// `__resolve_destination_alias` (`client.py:206-215`): a 32-character hex
/// `__resolve_destination_alias` (`client.py`): a 32-character hex
/// string as given, else a configured alias, else the input unchanged.
pub fn resolve_destination(&self, destination: &str) -> String {
if is_hash_hex(destination) {
@@ -177,7 +177,7 @@ impl ClientConfig {
}
}
/// Load `client_identity`, creating it when missing (`client.py:189-196`).
/// Load `client_identity`, creating it when missing (`client.py`).
/// A new identity that cannot be saved is still used, as upstream does.
pub fn load_or_create_identity(path: &Path) -> Option<Identity> {
if path.is_file() {
@@ -248,7 +248,7 @@ impl Abort {
}
}
/// `escape_for_stdout` (`client.py:451-464`), per code point.
/// `escape_for_stdout` (`client.py`), per code point.
pub fn escape_for_stdout(value: &str) -> String {
let mut out = String::from("\"");
for c in value.chars() {
@@ -377,7 +377,7 @@ impl<T: Transport> RemoteHelper<T> {
.ok_or_else(|| Abort::new("Request failed or timed out"))
}
/// The command loop (`client.py:337-421`), from `run()` after the link is up.
/// The command loop (`client.py`), from `run()` after the link is up.
pub fn run(
&mut self,
stdin: &mut dyn BufRead,
@@ -464,7 +464,7 @@ impl<T: Transport> RemoteHelper<T> {
Ok(())
}
/// `handle_git_list` (`client.py:423-449`).
/// `handle_git_list` (`client.py`).
fn handle_list(
&mut self,
stdout: &mut dyn Write,
@@ -521,7 +521,7 @@ impl<T: Transport> RemoteHelper<T> {
.collect()
}
/// `process_fetch_queue` (`client.py:466-545`).
/// `process_fetch_queue` (`client.py`).
fn process_fetch_queue(
&mut self,
mut queue: Vec<(String, String)>,
@@ -646,7 +646,7 @@ impl<T: Transport> RemoteHelper<T> {
})
}
/// `process_push_queue` (`client.py:547-678`).
/// `process_push_queue` (`client.py`).
fn process_push_queue(
&mut self,
queue: Vec<(String, String)>,
+9 -9
View File
@@ -1,16 +1,16 @@
//! The `rngit create` client side (`ReticulumGitClient`, `server.py:281-604@1.6.0`).
//! The `rngit create` client side (`ReticulumGitClient`, `server.py`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use rns_tools::rsg::pyfmt::py_fromhex;
/// `__default_rngit_config__` (`client.py:681-718`) as ConfigObj writes it.
/// `__default_rngit_config__` (`client.py`) as ConfigObj writes it.
pub const DEFAULT_CLIENT_CONFIG: &str = include_str!("default_client_config.txt");
const PROTO_SPEC: &str = "rns://";
/// `ReticulumGitClient.__init__` config directory (`server.py:336-339`),
/// `ReticulumGitClient.__init__` config directory (`server.py`),
/// including upstream's `~/.rngit/reticulum` when `~/.config/rngit/config` exists.
pub fn client_config_dir(configdir: Option<&Path>) -> PathBuf {
if let Some(dir) = configdir {
@@ -25,7 +25,7 @@ pub fn client_config_dir(configdir: Option<&Path>) -> PathBuf {
}
/// The `[logging] loglevel` and `[aliases]` that `__apply_config` reads
/// (`server.py:368-382`). A missing file is created from the default.
/// (`server.py`). A missing file is created from the default.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ClientConfig {
pub loglevel: Option<i64>,
@@ -70,7 +70,7 @@ impl ClientConfig {
Ok(out)
}
/// `__resolve_destination_alias` (`server.py:384-393`).
/// `__resolve_destination_alias` (`server.py`).
fn resolve(&self, alias: &str) -> String {
let is_hash = alias.chars().count() == 32 && py_fromhex(alias).is_ok_and(|h| !h.is_empty());
if is_hash {
@@ -106,13 +106,13 @@ impl ClientConfig {
py_fromhex(&hexhash).map_err(|e| format!("Invalid destination hash: {e}"))
}
/// `parse_remote_destination_url` (`server.py:425-433`): the abort text on error.
/// `parse_remote_destination_url` (`server.py`): the abort text on error.
pub fn parse_remote_destination_url(&self, remote: &str) -> Result<Vec<u8>, String> {
let (hexhash, _) = self.destination(remote)?;
Self::decode(&hexhash)
}
/// `parse_remote_group_url` (`server.py:446-454`): hash and group.
/// `parse_remote_group_url` (`server.py`): hash and group.
pub fn parse_remote_group_url(&self, remote: &str) -> Result<(Vec<u8>, String), String> {
let (hexhash, components) = self.destination(remote)?;
if components.len() != 2 {
@@ -122,7 +122,7 @@ impl ClientConfig {
Ok((hash, components[1].clone()))
}
/// `parse_remote_url` (`server.py:405-413`): hash, group and repository.
/// `parse_remote_url` (`server.py`): hash, group and repository.
pub fn parse_remote_url(&self, remote: &str) -> Result<(Vec<u8>, String, String), String> {
let (hexhash, components) = self.destination(remote)?;
if components.len() != 3 {
@@ -134,7 +134,7 @@ impl ClientConfig {
}
/// What `create_repository` prints for a `/git/create` reply
/// (`server.py:588-600`): `Ok` on success, `Err` for the abort text.
/// (`server.py`): `Ok` on success, `Err` for the abort text.
pub fn create_outcome(repo_path: &str, response: Option<&[u8]>) -> Result<String, String> {
let Some(response) = response.filter(|r| !r.is_empty()) else {
return Err("No response from remote".into());
+4 -4
View File
@@ -1,5 +1,5 @@
//! Node configuration: `ReticulumGitNode.__init__` and `__apply_config`
//! (`server.py:2018-2249@1.6.0`).
//! (`server.py`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -12,7 +12,7 @@ use super::perms::{ALL_TGTS, resolve_identity_alias};
use super::py_len;
/// The file upstream writes when the config directory has none
/// (`__default_rngit_config__`, `server.py:4913-5080`).
/// (`__default_rngit_config__`, `server.py`).
pub const DEFAULT_CONFIG: &str = include_str!("default_config.txt");
pub const DEFAULT_NODE_NAME: &str = "Anonymous Git Node";
@@ -177,7 +177,7 @@ impl NodeConfig {
}
/// The config directory as `ReticulumGitNode.__init__` picks it
/// (`server.py:2021-2028`).
/// (`server.py`).
pub fn resolve_config_dir(configdir: Option<&Path>) -> PathBuf {
if let Some(dir) = configdir {
return dir.to_path_buf();
@@ -195,7 +195,7 @@ pub fn resolve_config_dir(configdir: Option<&Path>) -> PathBuf {
}
/// The config text, writing [`DEFAULT_CONFIG`] first when the file is
/// missing (`__create_default_config`, `server.py:2070-2075`).
/// missing (`__create_default_config`, `server.py`).
pub fn read_or_create_config(configdir: &Path) -> std::io::Result<String> {
let path = configdir.join("config");
if path.is_file() {
+14 -14
View File
@@ -1,5 +1,5 @@
//! `/git/fork`, `/git/mirror`, `/git/sync` and the periodic mirror job
//! (`server.py:2098-2172`, `2762-2836`, `3213-3362@1.6.0`).
//! (`server.py`).
use std::io::Read;
use std::path::{Path, PathBuf};
@@ -18,13 +18,13 @@ use super::{
IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, RES_REMOTE_FAIL,
};
/// `CLONE_PROTOS` (`server.py:1978`).
/// `CLONE_PROTOS` (`server.py`).
pub const CLONE_PROTOS: [&str; 4] = ["rns", "http", "https", "ssh"];
/// `sync_check_interval` (`server.py:1998`): seconds between mirror job runs.
/// `sync_check_interval` (`server.py`): seconds between mirror job runs.
pub const SYNC_CHECK_INTERVAL: u64 = 15 * 60;
/// `ls-remote` is the only git call upstream bounds (`server.py:2790-2791`).
/// `ls-remote` is the only git call upstream bounds (`server.py`).
const LS_REMOTE_TIMEOUT: Duration = Duration::from_secs(30);
/// What a clone handler makes: a fork or a mirror.
@@ -125,7 +125,7 @@ fn now_secs() -> i64 {
.map_or(0, |d| d.as_secs() as i64)
}
/// `__mirror_synced` (`server.py:2762-2769`): 0 when unset or unreadable.
/// `__mirror_synced` (`server.py`): 0 when unset or unreadable.
pub fn mirror_synced(path: &Path) -> i64 {
match git(Some(path), &["config", "repository.rngit.upstream.sync"]) {
Ok(out) if out.status.success() => py_int(&lossy(&out.stdout)).unwrap_or(0),
@@ -133,7 +133,7 @@ pub fn mirror_synced(path: &Path) -> i64 {
}
}
/// `__set_mirror_synced` (`server.py:2771-2779`).
/// `__set_mirror_synced` (`server.py`).
pub fn set_mirror_synced(path: &Path) -> bool {
let now = now_secs().to_string();
git(
@@ -143,7 +143,7 @@ pub fn set_mirror_synced(path: &Path) -> bool {
.is_ok_and(|out| out.status.success())
}
/// `__update_head_to_source_default` (`server.py:2785-2836`): point HEAD at
/// `__update_head_to_source_default` (`server.py`): point HEAD at
/// the source's default branch, else at the first local branch.
pub fn update_head_to_source_default(repo_path: &Path, source_url: &str) -> bool {
tracing::debug!(
@@ -225,7 +225,7 @@ pub fn update_head_to_source_default(repo_path: &Path, source_url: &str) -> bool
}
}
/// `__sync_mirror` / `__sync_fork` (`server.py:2110-2172`): fetch every ref
/// `__sync_mirror` / `__sync_fork` (`server.py`): fetch every ref
/// from the source; a mirror also follows the source's HEAD.
fn sync_upstream(kind: RepoType, label: &str, path: &Path, source: &str) -> bool {
let what = match kind {
@@ -275,7 +275,7 @@ fn capitalise(word: &str) -> String {
.unwrap_or_default()
}
/// `__sync_mirrors` (`server.py:2098-2108`): every mirror whose last sync is
/// `__sync_mirrors` (`server.py`): every mirror whose last sync is
/// older than `mirror_interval` seconds. Forks are never synced here. Returns
/// at once when a run is already in progress.
pub fn sync_mirrors(repos: &RwLock<Repositories>, mirror_interval: i64, sync_lock: &Mutex<()>) {
@@ -332,7 +332,7 @@ fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
Ok(())
}
/// `handle_fork` (`server.py:3213-3215`). `None` sends no response.
/// `handle_fork` (`server.py`). `None` sends no response.
pub fn handle_fork(
repos: &RwLock<Repositories>,
identity: Option<&[u8; 16]>,
@@ -346,7 +346,7 @@ pub fn handle_fork(
handle_remote_clone(repos, identity, data, RepoType::Fork)
}
/// `handle_mirror` (`server.py:3217-3219`). `None` sends no response.
/// `handle_mirror` (`server.py`). `None` sends no response.
pub fn handle_mirror(
repos: &RwLock<Repositories>,
identity: Option<&[u8; 16]>,
@@ -360,7 +360,7 @@ pub fn handle_mirror(
handle_remote_clone(repos, identity, data, RepoType::Mirror)
}
/// `_handle_remote_clone` (`server.py:3221-3330`). An identified link and a
/// `_handle_remote_clone` (`server.py`). An identified link and a
/// remote identity are the same condition here: both come from LINKIDENTIFY.
fn handle_remote_clone(
repos: &RwLock<Repositories>,
@@ -438,7 +438,7 @@ fn handle_remote_clone(
}))
}
/// The `try` body of `_handle_remote_clone` (`server.py:3248-3324`).
/// The `try` body of `_handle_remote_clone` (`server.py`).
fn clone_into(
repos: &RwLock<Repositories>,
hash: &[u8; 16],
@@ -562,7 +562,7 @@ fn clone_into(
}
}
/// `handle_sync` (`server.py:3332-3362`). `None` sends no response.
/// `handle_sync` (`server.py`). `None` sends no response.
pub fn handle_sync(
repos: &RwLock<Repositories>,
identity: Option<&[u8; 16]>,
+9 -9
View File
@@ -1,4 +1,4 @@
//! `/git/*` request handlers (`server.py:2870-2929@1.6.0`).
//! `/git/*` request handlers (`server.py`).
use std::process::{Command, Stdio};
@@ -39,7 +39,7 @@ pub(super) fn get<'a>(map: &'a [(Value, Value)], key: &Value) -> Option<&'a Valu
/// A request map and its parsed repository path.
type Parsed<'a> = (&'a [(Value, Value)], Option<(&'a str, &'a str)>);
/// Common checks of every handler (`server.py:2872-2874`); `Err` is the reply.
/// Common checks of every handler (`server.py`); `Err` is the reply.
/// `Ok(None)` is upstream raising before its try (key 0 not a string), which
/// sends no response.
fn request_path<'a>(
@@ -61,7 +61,7 @@ fn request_path<'a>(
Ok(Some((map, parse_repository_path(path))))
}
/// `handle_list` (`server.py:2870-2929`). `None` sends no response.
/// `handle_list` (`server.py`). `None` sends no response.
pub fn handle_list(
repos: &Repositories,
identity: Option<&[u8; 16]>,
@@ -159,7 +159,7 @@ pub fn identity_text(identity: Option<&[u8; 16]>) -> String {
identity.map_or("None".to_string(), |h| format!("<{}>", hex::encode(h)))
}
/// `log_request` (`server.py:2705-2707`).
/// `log_request` (`server.py`).
pub fn log_request(repos: &Repositories, message: &str, identity: Option<&[u8; 16]>) {
if identity.is_some_and(|h| repos.blocked.iter().any(|b| b.as_slice() == h)) {
tracing::debug!("Blocked: {message}");
@@ -239,7 +239,7 @@ fn writable_repository(
.clone())
}
/// `handle_fetch` (`server.py:2931-3004`). `None` sends no response.
/// `handle_fetch` (`server.py`). `None` sends no response.
pub fn handle_fetch(
repos: &std::sync::RwLock<Repositories>,
stats: &Stats,
@@ -363,7 +363,7 @@ fn fetch_bundle(
})
}
/// `handle_push` (`server.py:3006-3100`). `None` sends no response.
/// `handle_push` (`server.py`). `None` sends no response.
pub fn handle_push(
repos: &std::sync::RwLock<Repositories>,
stats: &Stats,
@@ -540,7 +540,7 @@ fn push_operations(
Ok(vec![super::RES_OK])
}
/// `handle_delete` (`server.py:3102-3134`). `None` sends no response.
/// `handle_delete` (`server.py`). `None` sends no response.
pub fn handle_delete(
repos: &std::sync::RwLock<Repositories>,
stats: &Stats,
@@ -590,10 +590,10 @@ pub fn handle_delete(
}
}
/// `REPO_CREATE_PERMS_TEMPLATE` (`server.py:5090`).
/// `REPO_CREATE_PERMS_TEMPLATE` (`server.py`).
pub(super) const REPO_CREATE_PERMS_TEMPLATE: &str = "adm:{IDENTITY_HASH}";
/// `handle_create` (`server.py:3141-3211`). `None` sends no response.
/// `handle_create` (`server.py`). `None` sends no response.
/// Group permissions are checked without the blocklist, as upstream does.
pub fn handle_create(
repos: &std::sync::RwLock<Repositories>,
+10 -10
View File
@@ -1,5 +1,5 @@
//! Repository groups and repositories on disk (`load_repository_group`,
//! `update_group_permissions`, `load_repository`, `server.py:2528-2645@1.6.0`).
//! `update_group_permissions`, `load_repository`, `server.py`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -54,7 +54,7 @@ fn git_stdout(cwd: &Path, args: &[&str]) -> Option<String> {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// `_ensure_git` (`server.py:2709-2712`).
/// `_ensure_git` (`server.py`).
pub fn git_available() -> bool {
Command::new("git")
.arg("--version")
@@ -65,7 +65,7 @@ pub fn git_available() -> bool {
.is_ok_and(|s| s.success())
}
/// `__is_fork` / `__is_mirror` (`server.py:2734-2760`).
/// `__is_fork` / `__is_mirror` (`server.py`).
fn upstream_source(path: &Path, kind: &str) -> Option<String> {
if git_stdout(path, &["config", "repository.rngit.type"])? != kind {
return None;
@@ -95,7 +95,7 @@ impl Repositories {
Ok(repos)
}
/// `load_repository_group` (`server.py:2528-2546`).
/// `load_repository_group` (`server.py`).
pub fn load_group(
&mut self,
name: &str,
@@ -128,7 +128,7 @@ impl Repositories {
Ok(())
}
/// `update_group_permissions` (`server.py:2548-2602`): the group's
/// `update_group_permissions` (`server.py`): the group's
/// `.allowed` file first, then its `[access]` statements appended.
pub fn update_group_permissions(&mut self, name: &str, config: &NodeConfig) {
let aliases = self.aliases.clone();
@@ -160,7 +160,7 @@ impl Repositories {
group.permissions = permissions;
}
/// `load_repository` (`server.py:2621-2645`). A repository `.allowed`
/// `load_repository` (`server.py`). A repository `.allowed`
/// file that cannot be read is an error, as upstream lets it raise.
pub fn load_repository(&mut self, group_name: &str, path: &Path) -> Result<bool, AllowedError> {
let Some(group) = self.groups.get_mut(group_name) else {
@@ -199,7 +199,7 @@ impl Repositories {
Ok(true)
}
/// `resolve_permission` (`server.py:2311-2369`), the only resolver that
/// `resolve_permission` (`server.py`), the only resolver that
/// checks the blocklist.
pub fn resolve_permission(
&self,
@@ -220,7 +220,7 @@ impl Repositories {
super::perms::resolve_repository(&g.permissions, &r.permissions, hash, perm)
}
/// `resolve_group_permission` (`server.py:2371-2396`).
/// `resolve_group_permission` (`server.py`).
pub fn resolve_group_permission(&self, hash: &[u8; 16], group: &str, perm: Perm) -> bool {
self.groups
.get(group)
@@ -232,7 +232,7 @@ impl Repositories {
}
}
/// `parse_request_repository_path` (`server.py:2292-2300`).
/// `parse_request_repository_path` (`server.py`).
pub fn parse_repository_path(path: &str) -> Option<(&str, &str)> {
let mut parts = path.split('/');
let (Some(group), Some(repo), None) = (parts.next(), parts.next(), parts.next()) else {
@@ -241,7 +241,7 @@ pub fn parse_repository_path(path: &str) -> Option<(&str, &str)> {
(super::py_len(group) <= 256 && super::py_len(repo) <= 256).then_some((group, repo))
}
/// `parse_request_group_path` (`server.py:2302-2309`).
/// `parse_request_group_path` (`server.py`).
pub fn parse_group_path(path: &str) -> Option<&str> {
(!path.contains('/') && super::py_len(path) <= 256).then_some(path)
}
+2 -2
View File
@@ -1,4 +1,4 @@
//! The rngit repository node (`RNS/Utilities/rngit/server.py@1.6.0`).
//! The rngit repository node (`RNS/Utilities/rngit/server.py`).
pub mod client;
pub mod config;
@@ -11,7 +11,7 @@ pub mod releases;
pub mod stats;
pub mod work;
/// `APP_NAME` plus the aspect (`__init__.py:31`, `server.py:2063`).
/// `APP_NAME` plus the aspect (`__init__.py`, `server.py`).
pub const APP_NAME: &str = "git.repositories";
pub const PATH_LIST: &str = "/git/list";
+10 -10
View File
@@ -1,5 +1,5 @@
//! Permission statements, `.allowed` files and the permission decision
//! (`server.py:2251-2526@1.6.0`).
//! (`server.py`).
use std::collections::BTreeMap;
use std::path::Path;
@@ -20,7 +20,7 @@ pub enum Perm {
}
impl Perm {
/// The wire value (`PERM_*`, `server.py:1927-1935`).
/// The wire value (`PERM_*`, `server.py`).
pub fn code(self) -> u8 {
match self {
Perm::Read => 0x01,
@@ -67,7 +67,7 @@ impl Perm {
}
}
/// One of the eight stored lists (`ALL_PERMS`, `server.py:1945`).
/// One of the eight stored lists (`ALL_PERMS`, `server.py`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PermList {
Read,
@@ -116,7 +116,7 @@ pub enum Target {
}
impl Target {
/// The wire value (`TGT_NONE`/`TGT_ALL`, `server.py:1947-1948`).
/// The wire value (`TGT_NONE`/`TGT_ALL`, `server.py`).
pub fn code(&self) -> Option<u8> {
match self {
Target::None => Some(0x01),
@@ -130,7 +130,7 @@ pub const TGT_NONE_SMPHR: [&str; 3] = ["n", "none", "nobody"];
pub const TGT_ALL_SMPHR: [&str; 3] = ["a", "all", "everyone"];
pub const ALL_TGTS: [&str; 6] = ["n", "none", "nobody", "a", "all", "everyone"];
/// `__resolve_identity_alias` (`server.py:2251-2261`).
/// `__resolve_identity_alias` (`server.py`).
pub fn resolve_identity_alias(alias: &str, aliases: &BTreeMap<String, String>) -> String {
if ALL_TGTS.contains(&alias.to_lowercase().as_str()) {
return alias.to_string();
@@ -146,7 +146,7 @@ pub fn resolve_identity_alias(alias: &str, aliases: &BTreeMap<String, String>) -
.unwrap_or_else(|| alias.to_string())
}
/// `parse_permission` (`server.py:2263-2290`): either half is `None` when
/// `parse_permission` (`server.py`): either half is `None` when
/// it does not parse.
pub fn parse_permission(
statement: &str,
@@ -208,7 +208,7 @@ impl Permissions {
}
}
/// `permissions_from_allowed_input` (`server.py:2470-2510`).
/// `permissions_from_allowed_input` (`server.py`).
pub fn from_allowed_input(input: &str, aliases: &BTreeMap<String, String>) -> Self {
let mut perms = Permissions::default();
for line in py_splitlines(input) {
@@ -256,7 +256,7 @@ pub enum AllowedError {
NotUtf8,
}
/// `load_allowed_permissions` (`server.py:2512-2526`): an executable file is
/// `load_allowed_permissions` (`server.py`): an executable file is
/// run with no arguments and its stdout parsed (the exit status is
/// ignored); the flag says whether it was run.
pub fn load_allowed_permissions(
@@ -293,7 +293,7 @@ fn decide(list: &[Target], admins: &[Target], hash: &[u8; 16]) -> Option<bool> {
}
/// `resolve_permission`'s decision once group and repository are known
/// (`server.py:2311-2369`); the blocklist is checked by the caller.
/// (`server.py`); the blocklist is checked by the caller.
pub fn resolve_repository(
group: &Permissions,
repository: &Permissions,
@@ -313,7 +313,7 @@ pub fn resolve_repository(
decide(group.get(list), group.get(PermList::Admin), hash).unwrap_or(false)
}
/// `resolve_group_permission`'s decision (`server.py:2371-2396`); upstream
/// `resolve_group_permission`'s decision (`server.py`); upstream
/// does not check the blocklist here.
pub fn resolve_group(group: &Permissions, hash: &[u8; 16], perm: Perm) -> bool {
let Some(list) = perm.list() else {
+6 -6
View File
@@ -1,5 +1,5 @@
//! `/mgmt/perms`: group and repository permission files
//! (`handle_perms` and helpers, `server.py:4443-4643@1.6.0`).
//! (`handle_perms` and helpers, `server.py`).
use std::collections::BTreeMap;
use std::io::Write;
@@ -24,7 +24,7 @@ fn py_strip(s: &str) -> &str {
s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c))
}
/// The validation every permission setter runs (`server.py:4380-4393`,
/// The validation every permission setter runs (`server.py`,
/// `4504-4517`): the first statement that does not parse, by 1-based line.
pub(crate) fn invalid_line(content: &str, aliases: &BTreeMap<String, String>) -> Option<String> {
for (number, line) in py_splitlines(content).into_iter().enumerate() {
@@ -114,7 +114,7 @@ fn write_allowed(path: &Path, content: &str) -> Option<Vec<u8>> {
}
}
/// `_group_permissions` and its steps (`server.py:4473-4547`).
/// `_group_permissions` and its steps (`server.py`).
fn group_permissions(
repos: &RwLock<Repositories>,
config: &NodeConfig,
@@ -158,7 +158,7 @@ fn group_permissions(
Ok(vec![RES_OK])
}
/// `update_repository_permissions` (`server.py:2604-2619`): the repository
/// `update_repository_permissions` (`server.py`): the repository
/// file alone replaces the repository's lists.
fn update_repository_permissions(repos: &mut Repositories, group: &str, repository: &str) {
let aliases = repos.aliases.clone();
@@ -179,7 +179,7 @@ fn update_repository_permissions(repos: &mut Repositories, group: &str, reposito
}
}
/// `_repository_permissions` and its steps (`server.py:4549-4635`). Setting
/// `_repository_permissions` and its steps (`server.py`). Setting
/// takes group READ and ADMIN on top of repository ADMIN.
fn repository_permissions(
repos: &RwLock<Repositories>,
@@ -229,7 +229,7 @@ fn repository_permissions(
Ok(vec![RES_OK])
}
/// `handle_perms` (`server.py:4443-4471`).
/// `handle_perms` (`server.py`).
pub fn handle_perms(
repos: &RwLock<Repositories>,
config: &NodeConfig,
+15 -15
View File
@@ -1,4 +1,4 @@
//! `/mgmt/release` and the on-disk release tree (`server.py:3368-3788`).
//! `/mgmt/release` and the on-disk release tree (`server.py`).
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -225,7 +225,7 @@ fn meta_int(meta: &[(String, String)], key: &str) -> Result<i64, Raised> {
}
}
/// `ConfigObj._quote` (`configobj.py:1749-1837`) without the triple-quote
/// `ConfigObj._quote` (`configobj.py`) without the triple-quote
/// path, which no release key needs.
fn quote_value(value: &str) -> Option<String> {
if value.is_empty() {
@@ -289,7 +289,7 @@ pub(crate) fn data_for_pages(release_dir: &Path, tag: &str) -> Option<Value> {
release_data(release_dir, tag).ok().flatten()
}
/// One list entry (`server.py:3425-3450`), in insertion order.
/// One list entry (`server.py`), in insertion order.
fn list_entry(release_dir: &Path, entry: &str) -> Result<Value, Raised> {
let meta = read_meta(&release_dir.join("META"))?;
let created = meta_int(&meta, "created")?;
@@ -333,7 +333,7 @@ fn list_entry(release_dir: &Path, entry: &str) -> Result<Value, Raised> {
]))
}
/// `releases_list_data` (`server.py:3406-3480`): the entries, newest first,
/// `releases_list_data` (`server.py`): the entries, newest first,
/// and the published tag the `latest` file names.
fn releases_list_data(releases_path: &Path) -> Result<(Vec<Value>, Option<String>), Raised> {
if !releases_path.is_dir() {
@@ -388,7 +388,7 @@ fn releases_list_data(releases_path: &Path) -> Result<(Vec<Value>, Option<String
Ok((releases, latest_release))
}
/// `release_data` (`server.py:3492-3547`).
/// `release_data` (`server.py`).
fn release_data(release_dir: &Path, tag: &str) -> Result<Option<Value>, Raised> {
let meta_path = release_dir.join("META");
if !meta_path.is_file() {
@@ -511,7 +511,7 @@ fn release_dir_of(releases_path: &Path, tag: &str) -> Result<PathBuf, Vec<u8>> {
Ok(release_dir)
}
/// `_release_list` (`server.py:3482-3490`).
/// `_release_list` (`server.py`).
fn release_list(releases_path: &Path) -> Vec<u8> {
if !releases_path.is_dir() {
return prepend(0, &pack(&Value::Array(Vec::new())).unwrap_or_default());
@@ -530,7 +530,7 @@ fn release_list(releases_path: &Path) -> Vec<u8> {
}
}
/// `_release_view` (`server.py:3549-3575`).
/// `_release_view` (`server.py`).
fn release_view(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
let tag = match lookup_tag(data) {
Ok(Some(tag)) => tag,
@@ -554,7 +554,7 @@ fn release_view(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
}
}
/// `_release_fetch` (`server.py:3577-3608`).
/// `_release_fetch` (`server.py`).
fn release_fetch(releases_path: &Path, data: &[(Value, Value)]) -> Result<Reply, Raised> {
let Some(tag) = lookup_tag_unresolved(data)? else {
return Ok(Reply::Bytes(status(
@@ -626,7 +626,7 @@ fn tag_exists(repository_path: &Path, tag: &str) -> Result<bool, Raised> {
Ok(output.status.success())
}
/// `_release_create_init` (`server.py:3619-3667`).
/// `_release_create_init` (`server.py`).
fn release_create_init(
releases_path: &Path,
repository_path: &Path,
@@ -725,7 +725,7 @@ fn write_thanks(path: &Path) -> Result<(), Raised> {
std::fs::write(path, pack(&value)?).map_err(|_| Raised)
}
/// `_release_create_artifact` (`server.py:3669-3704`).
/// `_release_create_artifact` (`server.py`).
fn release_create_artifact(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
let tag = get(data, "tag").cloned().unwrap_or_else(|| Value::from(""));
let artifact_name = get(data, "artifact_name").cloned().unwrap_or(Value::Nil);
@@ -787,7 +787,7 @@ fn release_create_artifact(releases_path: &Path, data: &[(Value, Value)]) -> Vec
}
}
/// `_release_create_finalize` (`server.py:3706-3741`).
/// `_release_create_finalize` (`server.py`).
fn release_create_finalize(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
let tag = match checked_tag(data, "No tag specified") {
Ok(tag) => tag,
@@ -834,7 +834,7 @@ fn write_latest(releases_path: &Path, tag: &str) -> Result<(), Raised> {
std::fs::rename(&tmp_path, &latest_path).map_err(|_| Raised)
}
/// `_release_delete` (`server.py:3743-3761`).
/// `_release_delete` (`server.py`).
fn release_delete(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
let tag = match checked_tag(data, "No tag specified") {
Ok(tag) => tag,
@@ -859,7 +859,7 @@ fn release_delete(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
}
}
/// `_release_latest` (`server.py:3763-3788`).
/// `_release_latest` (`server.py`).
fn release_latest(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
let tag = match checked_tag(data, "No tag specified") {
Ok(tag) => tag,
@@ -886,7 +886,7 @@ fn release_latest(releases_path: &Path, data: &[(Value, Value)]) -> Vec<u8> {
}
}
/// `_release_create` (`server.py:3610-3617`).
/// `_release_create` (`server.py`).
fn release_create(
releases_path: &Path,
repository_path: &Path,
@@ -904,7 +904,7 @@ fn release_create(
}
}
/// `handle_release` (`server.py:3368-3404`). `None` when upstream raises
/// `handle_release` (`server.py`). `None` when upstream raises
/// before its try (key 0 not a string: no response is sent).
pub fn handle_release(
repos: &RwLock<Repositories>,
+13 -13
View File
@@ -1,5 +1,5 @@
//! Node statistics: the stats file, the recording gates and the repository
//! summary (`server.py:2077-2096`, `4640-4911@1.6.0`).
//! summary (`server.py`).
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -7,7 +7,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use rmpv::Value;
/// `stats_job_interval` (`server.py:1993`), seconds between writes of the file.
/// `stats_job_interval` (`server.py`), seconds between writes of the file.
pub const STATS_JOB_INTERVAL: u64 = 180;
/// A node of the stats tree. Maps refer to children by index, so one child can
@@ -22,7 +22,7 @@ enum Node {
///
/// Upstream creates missing groups and repositories from the class attributes
/// `STATS_INIT_GROUP` and `STATS_INIT_REPO` without copying them
/// (`server.py:4642-4643`), so every group and repository first recorded in a
/// (`server.py`), so every group and repository first recorded in a
/// process is the same object, and counts recorded under one show under all.
#[derive(Debug)]
struct Tree {
@@ -232,7 +232,7 @@ impl Gate {
}
/// The stats file, its ignore lists and the recording gates
/// (`server.py:1988-2096`, `4763-4911`).
/// (`server.py`).
#[derive(Debug)]
pub struct Stats {
tree: Mutex<Tree>,
@@ -242,7 +242,7 @@ pub struct Stats {
}
impl Stats {
/// `__load_stats` (`server.py:2077-2088`). A missing file is written with
/// `__load_stats` (`server.py`). A missing file is written with
/// the initial value; a file that cannot be read leaves the initial value.
/// `ignored` is `stats_ignore_identities`; upstream parses
/// `stats_push_ignore_identities` too but never reads it.
@@ -276,7 +276,7 @@ impl Stats {
&self.path
}
/// `__persist_stats` (`server.py:2090-2096`): `stats.tmp`, renamed over the file.
/// `__persist_stats` (`server.py`): `stats.tmp`, renamed over the file.
pub fn persist(&self) {
let tree = self.tree.lock().unwrap_or_else(|e| e.into_inner());
let bytes = encode(&tree.to_value(tree.root));
@@ -299,7 +299,7 @@ impl Stats {
}
}
/// `view_succeeded` (`server.py:4763-4768`): the front page, a group, or a repository.
/// `view_succeeded` (`server.py`): the front page, a group, or a repository.
pub fn view_succeeded(
&self,
group: Option<&str>,
@@ -316,22 +316,22 @@ impl Stats {
}
}
/// `fetch_succeeded` (`server.py:4770-4773`).
/// `fetch_succeeded` (`server.py`).
pub fn fetch_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
self.repo_event(Gate::Repo("fetch"), group, repo, identity, true);
}
/// `push_succeeded` (`server.py:4775-4777`): no ignore list is consulted.
/// `push_succeeded` (`server.py`): no ignore list is consulted.
pub fn push_succeeded(&self, group: &str, repo: &str) {
self.repo_event(Gate::Repo("push"), group, repo, None, false);
}
/// `download_succeeded` (`server.py:4779-4782`).
/// `download_succeeded` (`server.py`).
pub fn download_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
self.repo_event(Gate::Repo("download"), group, repo, identity, true);
}
/// `release_download_succeeded` (`server.py:4784-4787`).
/// `release_download_succeeded` (`server.py`).
pub fn release_download_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
self.repo_event(Gate::Repo("release_download"), group, repo, identity, true);
}
@@ -352,7 +352,7 @@ impl Stats {
}
}
/// `repository_stats` (`server.py:4645-4761`): `None` without the stats permission.
/// `repository_stats` (`server.py`): `None` without the stats permission.
pub fn repository_stats(
&self,
repos: &super::layout::Repositories,
@@ -524,7 +524,7 @@ fn local_date(secs: i64) -> (i64, i64, i64) {
)
}
/// `_get_day` (`server.py:4789-4792`): `%Y-%m-%d` in local time.
/// `_get_day` (`server.py`): `%Y-%m-%d` in local time.
pub fn local_day(secs: i64) -> String {
let (year, month, day) = local_date(secs);
format!("{year:04}-{month:02}-{day:02}")
+14 -14
View File
@@ -1,6 +1,6 @@
//! `/mgmt/work`: work documents on the server
//! (`handle_work` and `resolve_doc_permission`, `server.py:2398-2468`,
//! `3789-4441@1.6.0`).
//! (`handle_work` and `resolve_doc_permission`, `server.py`,
//! `3789-4441`).
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -17,7 +17,7 @@ use super::{
IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, RES_REMOTE_FAIL,
};
/// `WORK_DOC_LIMIT` (`server.py:1976`), counted in code points.
/// `WORK_DOC_LIMIT` (`server.py`), counted in code points.
pub const WORK_DOC_LIMIT: usize = 256 * 1024;
/// Upstream raised inside its `try`, replying "Remote error".
@@ -147,7 +147,7 @@ fn allowed_path(work_path: &Path, doc_id: i128) -> PathBuf {
PathBuf::from(format!("{}/{doc_id}.allowed", work_path.display()))
}
/// `resolve_doc_permission` (`server.py:2398-2468`): the document's
/// `resolve_doc_permission` (`server.py`): the document's
/// `.allowed` file decides first, then the repository and group as
/// `resolve_permission` does, without the blocklist.
pub fn resolve_doc_permission(
@@ -213,7 +213,7 @@ pub(crate) fn load_document(path: &Path) -> Option<Value> {
rmpv::decode::read_value(&mut &bytes[..]).ok()
}
/// `_work_save_document` (`server.py:3888-3900`).
/// `_work_save_document` (`server.py`).
fn save_document(path: &Path, document: &Value) -> bool {
let saved = (|| -> std::io::Result<()> {
let dir = path.parent().unwrap_or(Path::new("."));
@@ -382,7 +382,7 @@ fn check_signature(
Ok((!valid).then(|| status(RES_INVALID_REQ, "Invalid signature")))
}
/// `_work_list` (`server.py:3902-3936`).
/// `_work_list` (`server.py`).
fn work_list(
work_path: &Path,
data: &Request,
@@ -454,7 +454,7 @@ fn work_list(
ok_with(map(result))
}
/// `_work_view` (`server.py:3938-3996`).
/// `_work_view` (`server.py`).
fn work_view(work_path: &Path, data: &Request) -> Vec<u8> {
if !valid_scope(&data.name("scope", "all")) {
return status(RES_INVALID_REQ, "Invalid request");
@@ -517,7 +517,7 @@ fn work_view(work_path: &Path, data: &Request) -> Vec<u8> {
]))
}
/// `_work_create` and `_work_propose` (`server.py:3998-4085`), which differ
/// `_work_create` and `_work_propose` (`server.py`), which differ
/// in the scope they store under and the ownership file propose writes.
fn work_new(
work_path: &Path,
@@ -586,7 +586,7 @@ fn work_new(
])))
}
/// `_work_edit` (`server.py:4087-4147`).
/// `_work_edit` (`server.py`).
fn work_edit(work_path: &Path, data: &Request, identity: &Identity) -> Result<Vec<u8>, Raised> {
let scope = data.name("scope", "active");
let content = data.text("content")?;
@@ -667,7 +667,7 @@ fn work_edit(work_path: &Path, data: &Request, identity: &Identity) -> Result<Ve
Ok(vec![RES_OK])
}
/// `_work_delete` (`server.py:4149-4197`).
/// `_work_delete` (`server.py`).
fn work_delete(
work_path: &Path,
data: &Request,
@@ -708,7 +708,7 @@ fn work_delete(
Ok(vec![RES_OK])
}
/// `_work_comment` (`server.py:4199-4248`).
/// `_work_comment` (`server.py`).
fn work_comment(work_path: &Path, data: &Request, identity: &Identity) -> Result<Vec<u8>, Raised> {
let scope = data.name("scope", "active");
let content = py_strip(&data.text("content")?).to_string();
@@ -774,7 +774,7 @@ fn move_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
std::fs::rename(src, &dst)
}
/// `_work_complete` and `_work_activate` (`server.py:4250-4318`).
/// `_work_complete` and `_work_activate` (`server.py`).
fn work_move(
work_path: &Path,
data: &Request,
@@ -811,7 +811,7 @@ fn work_move(
]))
}
/// `_work_perms` and its get/set steps (`server.py:4320-4440`).
/// `_work_perms` and its get/set steps (`server.py`).
fn work_perms(
work_path: &Path,
data: &Request,
@@ -881,7 +881,7 @@ fn work_perms(
Ok(vec![RES_OK])
}
/// `handle_work` (`server.py:3789-3862`). `None` sends no response.
/// `handle_work` (`server.py`). `None` sends no response.
pub fn handle_work(
repos: &RwLock<Repositories>,
identity: Option<&Identity>,
+4 -4
View File
@@ -1,8 +1,8 @@
//! Request validators from `RNS/Utilities/rngit/util.py@1.6.0`.
//! Request validators from `RNS/Utilities/rngit/util.py`.
use rns_tools::rsg::pyfmt::py_fromhex;
/// Python `san_ref` (`util.py:36-63`): the ref when it passes upstream's
/// Python `san_ref` (`util.py`): the ref when it passes upstream's
/// subset of `git check-ref-format`. A ref without `/` (`HEAD`, `main`) and
/// any character below `(` are rejected, as upstream does.
pub fn san_ref(reference: &str) -> Option<&str> {
@@ -29,7 +29,7 @@ pub fn san_ref(reference: &str) -> Option<&str> {
Some(reference)
}
/// Python `san_refs` (`util.py:65-70`) for a list: the list when every ref
/// Python `san_refs` (`util.py`) for a list: the list when every ref
/// passes [`san_ref`]. Upstream returns an empty list unchanged, which its
/// callers then treat as a failure because it is falsy.
pub fn san_refs<S: AsRef<str>>(refs: &[S]) -> Option<&[S]> {
@@ -38,7 +38,7 @@ pub fn san_refs<S: AsRef<str>>(refs: &[S]) -> Option<&[S]> {
.then_some(refs)
}
/// Python `san_sha` (`util.py:73-77`): at least 40 characters that
/// Python `san_sha` (`util.py`): at least 40 characters that
/// `bytes.fromhex` accepts. There is no upper bound, and `fromhex` skips
/// whitespace between byte pairs.
pub fn san_sha(sha: &str) -> Option<&str> {
+4 -4
View File
@@ -310,7 +310,7 @@ impl AnnounceData {
}
}
/// Trailing announce stamp extension: marker, flags, stamp, lr_cost (Identity.py:86-90).
/// Trailing announce stamp extension: marker, flags, stamp, lr_cost (Identity.py).
pub const ANNOUNCE_EXT_LENGTH: usize = 18;
pub const ANNOUNCE_EXT_HEADER_LENGTH: usize = 2;
pub const ANNOUNCE_EXT_MARKER: u8 = 0xC1;
@@ -329,7 +329,7 @@ pub struct AnnounceStampExt {
}
impl AnnounceStampExt {
/// `0xC1 | flags | stamp | cost_bytes[1] | cost_bytes[0]` (Destination.py:351-352).
/// `0xC1 | flags | stamp | cost_bytes[1] | cost_bytes[0]` (Destination.py).
pub fn encode(&self) -> Result<[u8; ANNOUNCE_EXT_LENGTH], crate::stamps::StampError> {
let cost = crate::stamps::cost_to_bytes(self.lr_cost)?;
let mut ext = [0u8; ANNOUNCE_EXT_LENGTH];
@@ -400,7 +400,7 @@ pub enum AnnounceExtParse<'a> {
Present(AnnounceExt<'a>),
}
/// Parse the last 18 bytes of app_data as a stamp extension (Identity.py:840-856).
/// Parse the last 18 bytes of app_data as a stamp extension (Identity.py).
pub fn parse_announce_ext(app_data: Option<&[u8]>) -> AnnounceExtParse<'_> {
let Some(app_data) = app_data else {
return AnnounceExtParse::Absent;
@@ -455,7 +455,7 @@ impl AnnounceStampCheck {
}
impl AnnounceData {
/// Check the stamp extension against `required_value` (Identity.py:840-870).
/// Check the stamp extension against `required_value` (Identity.py).
/// The workblock is `destination_hash || public_key || name_hash`, unexpanded.
pub fn check_stamp(
&self,
+2 -2
View File
@@ -1007,7 +1007,7 @@ impl Destination {
}
/// As [`Self::create_announce_at`], appending the stamp extension to the
/// resolved app data before signing (Destination.py:347-361@1.6.0). Pass
/// resolved app data before signing (Destination.py). Pass
/// [`Self::announce_stamp_ext`] when the stamp policy stamps destinations.
pub fn create_announce_with_ext_at(
&mut self,
@@ -1311,7 +1311,7 @@ pub const DESTINATION_STAMP_EXTENSION: &str = ".dstamp";
pub const STAMP_FILE_VERSION: u64 = 1;
const STAMP_FILE_MAX_LEN: usize = 1024;
/// `<storage>/stamps/<hex hash>.dstamp` (Stamps.py:871-875@1.6.0).
/// `<storage>/stamps/<hex hash>.dstamp` (Stamps.py).
pub fn destination_stamp_path(
storage_dir: &std::path::Path,
destination_hash: &[u8; 16],
+1 -1
View File
@@ -543,7 +543,7 @@ impl PersistentRatchetRing {
let mut ring = if self.path.is_file() {
RatchetRing::load_verified(&self.path, identity)?.into_ring()
} else {
// Destination.py:569-573: a missing file is re-initialised as an empty ring.
// Destination.py: a missing file is re-initialised as an empty ring.
let ring = RatchetRing::new();
ring.save_verified(&self.path, identity)?;
ring
@@ -4298,7 +4298,7 @@ mod tests {
assert_eq!(received.load(Ordering::Relaxed), 0);
}
/// Python RNodeInterface.py:881-896: the last RSSI, SNR and quality stay
/// Python RNodeInterface.py: the last RSSI, SNR and quality stay
/// on the interface, so every later packet carries them.
#[tokio::test]
async fn usb_packets_carry_the_last_signal_report() {
+10 -10
View File
@@ -577,7 +577,7 @@ impl Shared {
}
/// Open the discovery and data sockets of one NIC, adopt it and start its
/// tasks (AutoInterface.py:253-312, :337-347).
/// tasks (AutoInterface.py).
fn start_nic(self: &Arc<Self>, nic: &NicAddrs) -> Result<NicHandle, NicError> {
let (unicast, mcast, beacon) = self.discovery_sockets(nic).map_err(NicError::Discovery)?;
let scope = nic.scope_id;
@@ -719,7 +719,7 @@ impl Shared {
self.beacon_interval() * 3.25
}
/// `announce_handler` / `peer_announce` (AutoInterface.py:485-520).
/// `announce_handler` / `peer_announce` (AutoInterface.py).
async fn beacon_loop(self: Arc<Self>, sock: UdpSocket, link_local: Ipv6Addr, scope: u32) {
let token = discovery_token(&self.group_id, &link_local);
let dest = SocketAddrV6::new(self.mcast_group, self.discovery_port, 0, scope);
@@ -736,7 +736,7 @@ impl Shared {
}
}
/// `discovery_handler` (AutoInterface.py:358-374).
/// `discovery_handler` (AutoInterface.py).
async fn discovery_loop(self: Arc<Self>, sock: UdpSocket, ifname: String, scope: u32) {
let mut buf = [0u8; DISCOVERY_BUFFER];
loop {
@@ -774,7 +774,7 @@ impl Shared {
self.add_peer(src, ifname, scope).await;
}
/// `add_peer` (AutoInterface.py:526-607).
/// `add_peer` (AutoInterface.py).
async fn add_peer(self: &Arc<Self>, addr: Ipv6Addr, ifname: &str, scope: u32) {
let outcome = self.core().discovered(addr, ifname, scope, Instant::now());
match outcome {
@@ -851,7 +851,7 @@ impl Shared {
online: online.clone(),
rxb: Some(rxb.clone()),
txb: Some(txb),
// AutoInterfacePeer never sets `name` (AutoInterface.py:636-650).
// AutoInterfacePeer never sets `name` (AutoInterface.py).
inspection: Some(InterfaceInspectionSource::identified(
InterfaceIdentity::new(name, "None", "AutoInterfacePeer"),
)),
@@ -869,7 +869,7 @@ impl Shared {
)
}
/// The data listener's `process_incoming` (AutoInterface.py:613-615).
/// The data listener's `process_incoming` (AutoInterface.py).
async fn data_loop(self: Arc<Self>, sock: UdpSocket) {
let mut buf = vec![0u8; DATA_BUFFER];
loop {
@@ -902,7 +902,7 @@ impl Shared {
}
}
/// `peer_jobs` (AutoInterface.py:376-483).
/// `peer_jobs` (AutoInterface.py).
async fn run_jobs(self: Arc<Self>) {
loop {
tokio::time::sleep(std::time::Duration::from_secs_f64(PEER_JOB_INTERVAL)).await;
@@ -1042,7 +1042,7 @@ struct ChildTask {
}
/// `AutoInterfacePeer.process_incoming` / `process_outgoing`
/// (AutoInterface.py:652-681). Ends, and deregisters the child, once the
/// (AutoInterface.py). Ends, and deregisters the child, once the
/// parent drops the peer or transport drops the child.
async fn child_task(mut task: ChildTask) {
loop {
@@ -1088,7 +1088,7 @@ async fn child_task(mut task: ChildTask) {
.await;
}
/// `detach` (AutoInterface.py:619-632): closes every socket, stops every
/// `detach` (AutoInterface.py): closes every socket, stops every
/// task and takes the spawned peers down with the parent.
struct Teardown {
shared: Arc<Shared>,
@@ -1200,7 +1200,7 @@ pub async fn spawn_auto_interface(
})
}
/// `peers` and the `AutoInterface[name]` identity for interface stats (Reticulum.py:1726-1728).
/// `peers` and the `AutoInterface[name]` identity for interface stats (Reticulum.py).
fn auto_inspection(shared: &Arc<Shared>) -> InterfaceInspectionSource {
let shared = Arc::downgrade(shared);
let last = Arc::new(AtomicU64::new(0));
+1 -1
View File
@@ -78,7 +78,7 @@ pub fn list_network_interfaces() -> Result<Vec<NetworkInterfaceInfo>, String> {
}
/// Clear the scope that BSD kernels embed in the second segment of a
/// link-local address (`descope_linklocal`, AutoInterface.py:80-85).
/// link-local address (`descope_linklocal`, AutoInterface.py).
#[cfg(any(target_os = "macos", test))]
fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
if (addr.segments()[0] & 0xffc0) != 0xfe80 {
+4 -4
View File
@@ -96,7 +96,7 @@ impl Core {
self.timed_out.insert(ifname.to_string(), timed_out)
}
/// `add_peer` (AutoInterface.py:526-607): a beacon from `addr` passed the
/// `add_peer` (AutoInterface.py): a beacon from `addr` passed the
/// token check on `ifname`.
pub fn discovered(
&mut self,
@@ -149,7 +149,7 @@ impl Core {
}
/// `process_incoming` of the parent and the peer child
/// (AutoInterface.py:613-615, :652-668): only data from a source with a
/// (AutoInterface.py): only data from a source with a
/// spawned child is delivered, duplicates seen on another NIC within the
/// TTL are dropped, and delivered data refreshes the peer.
pub fn inbound(&mut self, src: Ipv6Addr, data: &[u8], now: Instant) -> Option<ChildLink> {
@@ -167,7 +167,7 @@ impl Core {
Some(child)
}
/// Timed-out peers (`peer_jobs`, AutoInterface.py:382-396).
/// Timed-out peers (`peer_jobs`, AutoInterface.py).
pub fn expire(&mut self, now: Instant, peering_timeout: f64) -> Vec<(Ipv6Addr, Peer)> {
let expired: Vec<Ipv6Addr> = self
.peers
@@ -181,7 +181,7 @@ impl Core {
.collect()
}
/// Peers due a reverse peering beacon (AutoInterface.py:398-408).
/// Peers due a reverse peering beacon (AutoInterface.py).
pub fn reverse_due(&mut self, now: Instant, interval: f64) -> Vec<(Ipv6Addr, String, u32)> {
let mut due = Vec::new();
for (addr, peer) in &mut self.peers {
+7 -7
View File
@@ -75,7 +75,7 @@ const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
#[derive(Debug, Clone)]
pub struct BackboneServerConfig {
pub name: String,
/// Host to bind; required unless `device` is set (BackboneInterface.py:162-168).
/// Host to bind; required unless `device` is set (BackboneInterface.py).
pub listen_ip: Option<String>,
pub listen_port: u16,
pub prefer_ipv6: bool,
@@ -125,7 +125,7 @@ pub struct BackboneClientConfig {
pub target_port: u16,
pub prefer_ipv6: bool,
/// Parsed like Python, which stores it but connects with
/// [`INITIAL_CONNECT_TIMEOUT`] (BackboneInterface.py:979).
/// [`INITIAL_CONNECT_TIMEOUT`] (BackboneInterface.py).
pub connect_timeout_secs: u64,
/// Retries allowed within one outage; `None` retries forever.
pub max_reconnect_tries: Option<usize>,
@@ -155,7 +155,7 @@ impl BackboneClientConfig {
}
}
/// Python `str(BackboneClientInterface)` (BackboneInterface.py:1114-1117).
/// Python `str(BackboneClientInterface)` (BackboneInterface.py).
pub fn python_name(&self) -> String {
format!(
"BackboneInterface[{}/{}:{}]",
@@ -412,7 +412,7 @@ async fn backbone_read_loop(
rxb: ByteCounter,
(bitrate, ifac_size): (u64, usize),
) {
// ReceiveBuffer(HW_MTU, HEADER_MINSIZE, HW_MTU + ifac_size) (BackboneInterface.py:892-893@1.6.0).
// ReceiveBuffer(HW_MTU, HEADER_MINSIZE, HW_MTU + ifac_size) (BackboneInterface.py).
let hw_mtu = crate::tcp::hardware_mtu(bitrate, None) as usize;
let mut deframer = hdlc::HdlcDeframer::with_limits(
hw_mtu,
@@ -969,7 +969,7 @@ pub async fn spawn_backbone_client_observed(
let task_egress = egress.clone();
let (teardown_tx, teardown) = crate::tcp::ClientTeardown::channel();
// Python connects once, synchronously, before the interface is handed to
// transport (BackboneInterface.py:921-922, :979).
// transport (BackboneInterface.py).
let initial_timeout = Duration::from_secs(INITIAL_CONNECT_TIMEOUT);
let mut initial_attempt = Some(
tokio::time::timeout(
@@ -986,7 +986,7 @@ pub async fn spawn_backbone_client_observed(
let max_tries = config.max_reconnect_tries;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
// Retries within the current outage (BackboneInterface.py:1007-1023).
// Retries within the current outage (BackboneInterface.py).
let mut attempts: usize = 0;
loop {
@@ -1014,7 +1014,7 @@ pub async fn spawn_backbone_client_observed(
tune_stream(&stream);
attempts = 0;
// Python synthesizes on every connection (BackboneInterface.py:922,
// Python synthesizes on every connection (BackboneInterface.py,
// :1019).
let synthesis = config
.tunnel_identity
+6 -6
View File
@@ -1296,7 +1296,7 @@ impl BleRNodeConfig {
}
/// Station-ID beacon parameters, disabled for oversized callsigns
/// (Python RNodeInterface.py:333-343).
/// (Python RNodeInterface.py).
fn beacon_from_config(config: &BleRNodeConfig) -> Option<(Duration, Bytes)> {
config
.id_interval
@@ -6749,8 +6749,8 @@ mod tests {
}
/// Python's `RNodeInterface` also drives BLE: any READY releases the queue
/// (RNodeInterface.py:1099-1100), and the last RSSI, SNR and quality stay
/// on the interface across packets (:881-896).
/// (RNodeInterface.py), and the last RSSI, SNR and quality stay
/// on the interface across packets.
#[tokio::test]
async fn native_ble_any_ready_releases_the_queue_and_signal_stats_persist() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -7797,7 +7797,7 @@ mod tests {
q: Some(100.0),
};
let before = signal;
// Python keeps r_stat_rssi/snr/q after a packet (RNodeInterface.py:707-710).
// Python keeps r_stat_rssi/snr/q after a packet (RNodeInterface.py).
for _ in 0..2 {
let rnode::RNodeResponse::Packet(rns_transport::messages::TransportMessage::Inbound(
packet,
@@ -7831,7 +7831,7 @@ mod tests {
assert_eq!(signal.rssi, Some(-65.0));
}
/// Python RNodeInterface.py:883-894: each SNR report also sets the quality
/// Python RNodeInterface.py: each SNR report also sets the quality
/// for the reported spreading factor; without one the old value stays.
#[test]
fn test_response_snr_updates_quality_for_the_reported_spreading_factor() {
@@ -7852,7 +7852,7 @@ mod tests {
assert_eq!((signal.snr, signal.q), (Some(8.0), Some(52.6)));
}
/// Python RNodeInterface.py:1099-1100 runs `process_queue` for each READY
/// Python RNodeInterface.py runs `process_queue` for each READY
/// payload byte, whatever its value.
#[test]
fn test_response_ready_ignores_the_payload_value() {
+7 -7
View File
@@ -268,7 +268,7 @@ async fn sam_session_create<R: AsyncRead + Unpin>(
/// i2plib `stream_connect` resolves a destination ending in `.i2p` with
/// `NAMING LOOKUP` on its own SAM connection and connects to the full key
/// (RNS/vendor/i2plib/aiosam.py:34-50, :120-121).
/// (RNS/vendor/i2plib/aiosam.py).
async fn sam_resolve_destination(
sam_host: &str,
sam_port: u16,
@@ -388,7 +388,7 @@ async fn connect_to_sam(sam_host: &str, sam_port: u16) -> Result<TcpStream, SamE
let addr = format!("{}:{}", sam_host, sam_port);
let stream = TcpStream::connect(&addr).await.map_err(SamError::Io)?;
let _ = stream.set_nodelay(true);
// Python's per-platform I2P peer timeouts (I2PInterface.py:443-455).
// Python's per-platform I2P peer timeouts (I2PInterface.py).
crate::tcp::set_tcp_keepalive_tuned(&stream, true);
Ok(stream)
}
@@ -452,7 +452,7 @@ impl I2PServerConfig {
}
/// i2plib's signature type for new destinations, EdDSA-SHA512-Ed25519
/// (RNS/vendor/i2plib/sam.py:91-93).
/// (RNS/vendor/i2plib/sam.py).
const NEW_DESTINATION_SIGNATURE_TYPE: u8 = 7;
/// The stored key, `None` when there is none yet, read into buffers that are
@@ -483,7 +483,7 @@ fn store_private_key(path: &std::path::Path, key: &str) -> std::io::Result<()> {
/// The b32 address of the destination in a SAM private key: the hash of its
/// first 387 bytes plus its certificate (i2plib `Destination.base32`,
/// RNS/vendor/i2plib/sam.py:113-129).
/// RNS/vendor/i2plib/sam.py).
pub fn destination_b32(private_key: &str) -> Option<String> {
let key = i2p_base64_decode(private_key)?;
let certificate = usize::from(u16::from_be_bytes(key.get(385..387)?.try_into().ok()?));
@@ -568,7 +568,7 @@ impl I2PClientConfig {
}
}
/// Python `str(I2PInterfacePeer)` (I2PInterface.py:714-715).
/// Python `str(I2PInterfacePeer)` (I2PInterface.py).
pub fn python_name(&self) -> String {
format!("I2PInterfacePeer[{}]", self.name)
}
@@ -780,7 +780,7 @@ pub async fn spawn_i2p_client(
);
pacer.reset();
// Python synthesizes on every connection (I2PInterface.py:503,
// Python synthesizes on every connection (I2PInterface.py,
// :533).
let synthesis = config
.tunnel_identity
@@ -1496,7 +1496,7 @@ mod tests {
}
/// Only the destination, keys plus certificate, names the address
/// (i2plib sam.py:113-129); the golden is checked against i2plib in tests.
/// (i2plib sam.py); the golden is checked against i2plib in tests.
#[test]
fn the_b32_address_hashes_only_the_destination() {
let ed25519 = [5, 0, 4, 0, 7, 0, 0];
+2 -2
View File
@@ -350,7 +350,7 @@ impl crate::serial_io::SerialGeneration for KissGeneration {
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
// Python counts the unframed payload here (KISSInterface.py:275).
// Python counts the unframed payload here (KISSInterface.py).
txb.fetch_add(data.len() as u64, Ordering::Relaxed);
}
Err(e) => return GenerationEnd::WriteFailed(e),
@@ -426,7 +426,7 @@ mod tests {
assert!(cfg.id_interval.is_none() && cfg.id_callsign.is_none());
}
/// Python KISSInterface.py:350-353 — beacon payload is the callsign
/// Python KISSInterface.py — beacon payload is the callsign
/// zero-padded to 15 bytes; longer callsigns pass through unchanged.
#[test]
fn test_beacon_frame_payload_padding() {
+7 -7
View File
@@ -450,8 +450,8 @@ async fn run_local_client_connection(
) -> LocalClientConnectionEnd {
let interface_id = io.interface_id;
let mut buf = [0u8; 8192];
// LocalInterface.py:81-82@1.6.0: the receive buffer follows HW_MTU, which a
// forced bitrate re-optimises (Reticulum.py:443-448@1.6.0).
// LocalInterface.py: the receive buffer follows HW_MTU, which a
// forced bitrate re-optimises (Reticulum.py).
let hw_mtu = io
.force_bitrate
.filter(|bitrate| *bitrate > 0)
@@ -661,7 +661,7 @@ pub async fn spawn_local_server(
let label = endpoint.python_label();
let unix_path =
(!matches!(endpoint, LocalEndpoint::Tcp(_))).then(|| config.socket_path.clone());
// LocalInterface.py:372, :485-487.
// LocalInterface.py.
let server_identity = InterfaceIdentity::new(
format!("Shared Instance[{label}]"),
"Reticulum",
@@ -681,7 +681,7 @@ pub async fn spawn_local_server(
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::debug!(name = %client_name, %peer, "local client connected");
// LocalInterface.py:351-353, :420-424 and :443.
// LocalInterface.py and :443.
let identity = match &unix_path {
Some(path) => InterfaceIdentity::new(
format!("LocalInterface[{label}]"),
@@ -763,7 +763,7 @@ pub async fn spawn_local_client(
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let endpoint = LocalEndpoint::parse(&config.socket_path);
// Reticulum.py:437-441: named "Local shared instance".
// Reticulum.py: named "Local shared instance".
let identity = InterfaceIdentity::new(
format!("LocalInterface[{}]", endpoint.python_label()),
"Local shared instance",
@@ -901,7 +901,7 @@ mod tests {
#[test]
fn forced_bitrate_delay_is_payload_airtime() {
// Upstream sleeps len / bitrate * 8 (LocalInterface.py:228-236).
// Upstream sleeps len / bitrate * 8 (LocalInterface.py).
assert_eq!(forced_bitrate_delay(400, 1000), Duration::from_millis(3200));
}
@@ -1259,7 +1259,7 @@ mod tests {
}
/// Python's `LocalClientInterface` drops outgoing traffic while offline
/// (LocalInterface.py:218), so nothing queued during an outage reaches
/// (LocalInterface.py), so nothing queued during an outage reaches
/// the restarted shared instance.
#[cfg(unix)]
#[tokio::test]
+9 -9
View File
@@ -2459,7 +2459,7 @@ impl RNodeStream {
// the same read timeout as a serial port.
stream.set_read_timeout(Some(Duration::from_millis(RNODE_READ_TIMEOUT_MS)))?;
stream.set_nodelay(true)?;
// RNodeInterface.py:1516-1527,1557-1558: the full set on Linux only,
// RNodeInterface.py: the full set on Linux only,
// keepalive with the idle time on Apple, nothing elsewhere.
#[cfg(target_os = "linux")]
crate::socket_tuning::set_keepalive_tuned(
@@ -3362,7 +3362,7 @@ pub struct RNodeSignalStats {
}
/// What an RNode last reported about its radio, kept as Python keeps the
/// `r_*` attributes that `get_interface_stats()` reads (Reticulum.py:1651-1690).
/// `r_*` attributes that `get_interface_stats()` reads (Reticulum.py).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RNodeRadioStats {
pub frequency: Option<u32>,
@@ -3388,10 +3388,10 @@ pub struct RNodeRadioStats {
/// Which upstream class the report belongs to: their attributes differ.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RNodeRadioKind {
/// `RNodeInterface` (RNodeInterface.py:785-1070).
/// `RNodeInterface` (RNodeInterface.py).
Single,
/// `RNodeSubInterface`: its own radio settings and signal, airtime fixed
/// at 0.0 because the parent keeps channel time (RNodeMultiInterface.py:625-800, 998-1001).
/// at 0.0 because the parent keeps channel time (RNodeMultiInterface.py).
Sub,
}
@@ -3407,7 +3407,7 @@ impl RNodeRadioStats {
CMD_BANDWIDTH => self.bandwidth = u32_at(frame).or(self.bandwidth),
CMD_TXPOWER => {
if let Some(&byte) = frame.first() {
// The multi-radio parent reads it signed (RNodeMultiInterface.py:655).
// The multi-radio parent reads it signed (RNodeMultiInterface.py).
self.txpower = Some(match kind {
RNodeRadioKind::Single => i64::from(byte),
RNodeRadioKind::Sub => i64::from(byte as i8),
@@ -3491,7 +3491,7 @@ impl RNodeRadioStats {
keys.push(("interference_last_ts", V::Float(ts)));
keys.push(("interference_last_dbm", V::Int(dbm)));
}
// RNodeInterface.get_battery_state_string (RNodeInterface.py:1218-1226).
// RNodeInterface.get_battery_state_string (RNodeInterface.py).
match self.battery_state {
0x00 => {}
0x01 => keys.push(("battery_state", V::Str("discharging".into()))),
@@ -3801,7 +3801,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
let radio_stats = Arc::new(std::sync::Mutex::new(RNodeRadioStats::default()));
let task_radio_stats = radio_stats.clone();
let mode = config.mode;
// Python RNodeInterface.py:333-343: oversized callsigns disable beaconing.
// Python RNodeInterface.py: oversized callsigns disable beaconing.
let beacon: Option<(Duration, Bytes)> = config
.id_interval
.zip(config.id_callsign.clone())
@@ -5102,7 +5102,7 @@ mod tests {
assert!(!message.contains("port parse"), "{message}");
}
/// Python parity (RNodeInterface.py:878,880): RSSI = raw byte − 157,
/// Python parity (RNodeInterface.py): RSSI = raw byte − 157,
/// SNR = signed byte × 0.25.
#[test]
fn test_rssi_snr_decode_matches_python() {
@@ -5256,7 +5256,7 @@ mod tests {
);
}
/// Byte-exact vs Python `setSTALock`/`setLTALock` (RNodeInterface.py:612-630):
/// Byte-exact vs Python `setSTALock`/`setLTALock` (RNodeInterface.py):
/// `at = int(pct * 100)` big-endian u16, KISS-escaped, framed per command.
#[test]
fn test_airtime_sequence_matches_python_encoding() {
+4 -4
View File
@@ -187,7 +187,7 @@ pub struct RNodeMultiConfig {
/// Up to `MAX_SUBINTERFACES` radios on this device.
pub subinterfaces: Vec<SubInterfaceConfig>,
/// Station-ID beacon, parent-level: when due, the callsign is sent on
/// all subinterfaces (Python RNodeMultiInterface.py:849-859).
/// all subinterfaces (Python RNodeMultiInterface.py).
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
@@ -976,7 +976,7 @@ pub async fn spawn_rnode_multi_interface_observed(
online: online.clone(),
rxb: Some(rxb.clone()),
txb: Some(txb.clone()),
// RNodeMultiInterface.py:1164-1165.
// RNodeMultiInterface.py.
inspection: Some(
rnode::RNodeRadioStats::inspection(radio.clone(), rnode::RNodeRadioKind::Sub)
.with_identity(rns_transport::messages::InterfaceIdentity::new(
@@ -1042,7 +1042,7 @@ pub async fn spawn_rnode_multi_interface_observed(
};
handles.insert(0, parent);
// Python RNodeMultiInterface.py:281-291 — oversized callsigns disable beaconing.
// Python RNodeMultiInterface.py — oversized callsigns disable beaconing.
let beacon: Option<(Duration, Bytes)> = config
.id_interval
.zip(config.id_callsign.clone())
@@ -1299,7 +1299,7 @@ impl MultiDriver {
}
let sub = &self.subs[local];
sub.txb.fetch_add(data.len() as u64, Ordering::Relaxed);
// Python's parent counts the KISS-escaped payload (RNodeMultiInterface.py:540-544).
// Python's parent counts the KISS-escaped payload (RNodeMultiInterface.py).
self.parent_txb
.fetch_add(kiss::escape(&data).len() as u64, Ordering::Relaxed);
let frame = build_subinterface_data_frame(sub.vport, &data);
+13 -13
View File
@@ -36,7 +36,7 @@ pub const BITRATE_GUESS: u64 = 10_000_000;
/// Python `Interface.DEFAULT_IFAC_SIZE` for TCP, the IFAC size when none is configured.
pub const DEFAULT_IFAC_SIZE: usize = 16;
/// The hardware MTU after `optimise_mtu()` (Interface.py:255-267@1.6.0), or a
/// The hardware MTU after `optimise_mtu()` (Interface.py), or a
/// fixed MTU. Upstream leaves `HW_MTU = None` below 62.5 kbps; that is the base MTU here.
pub(crate) fn hardware_mtu(bitrate: u64, fixed_mtu: Option<u32>) -> u32 {
fixed_mtu
@@ -45,7 +45,7 @@ pub(crate) fn hardware_mtu(bitrate: u64, fixed_mtu: Option<u32>) -> u32 {
}
/// Reported MTU and packet capacity: packets up to the hardware MTU, frames up
/// to the hardware MTU plus the IFAC size (TCPInterface.py:338-341@1.6.0).
/// to the hardware MTU plus the IFAC size (TCPInterface.py).
pub(crate) fn hardware_capacity(
bitrate: u64,
fixed_mtu: Option<u32>,
@@ -62,7 +62,7 @@ pub const TCP_KEEPIDLE: u32 = 5;
pub const TCP_KEEPINTVL: u32 = 2;
pub const TCP_KEEPCNT: u32 = 12;
/// Python's per-platform TCP timeouts (TCPInterface.py:181-207): the full
/// Python's per-platform TCP timeouts (TCPInterface.py): the full
/// set on Linux (and Android), keepalive with the idle time on Apple
/// platforms, nothing elsewhere. `i2p_tunneled` selects the longer I2P values.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream, i2p_tunneled: bool) {
@@ -108,7 +108,7 @@ pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream, i2p_tunneled: bool) {
}
/// Python `get_address_for_if` / `get_address_for_host` of the TCP and
/// Backbone listeners (TCPInterface.py:469-504): `device` wins over
/// Backbone listeners (TCPInterface.py): `device` wins over
/// `listen_ip`, neither is an error, and nothing falls back to a wildcard.
pub async fn resolve_bind_address(
listen_ip: Option<&str>,
@@ -185,7 +185,7 @@ pub struct TcpClientConfig {
/// Use the longer socket timeouts for a TCP connection tunneled over I2P.
pub i2p_tunneled: bool,
/// Parsed like Python, which stores it but connects with
/// [`INITIAL_CONNECT_TIMEOUT`] (TCPInterface.py:241).
/// [`INITIAL_CONNECT_TIMEOUT`] (TCPInterface.py).
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
@@ -218,7 +218,7 @@ impl TcpClientConfig {
}
}
/// Python `str(TCPClientInterface)` (TCPInterface.py:457-461).
/// Python `str(TCPClientInterface)` (TCPInterface.py).
pub fn python_name(&self) -> String {
format!(
"TCPInterface[{}/{}:{}]",
@@ -232,7 +232,7 @@ impl TcpClientConfig {
#[derive(Debug, Clone)]
pub struct TcpServerConfig {
pub name: String,
/// Host to bind; required unless `device` is set (TCPInterface.py:550).
/// Host to bind; required unless `device` is set (TCPInterface.py).
pub listen_ip: Option<String>,
pub listen_port: u16,
pub kiss_framing: bool,
@@ -241,7 +241,7 @@ pub struct TcpServerConfig {
/// Bind to this network device's address instead of `listen_ip`
/// (Python `device =` option).
pub device: Option<String>,
/// Accepted clients take the I2P socket timeouts (TCPInterface.py:589).
/// Accepted clients take the I2P socket timeouts (TCPInterface.py).
pub i2p_tunneled: bool,
/// Bitrate the hardware MTU is optimised for; accepted clients inherit it.
pub bitrate: u64,
@@ -458,7 +458,7 @@ async fn tcp_write_loop(
state.online.store(false, Ordering::SeqCst);
}
/// Python's initiator `teardown()` (TCPInterface.py:437-455): the interface
/// Python's initiator `teardown()` (TCPInterface.py): the interface
/// stays registered and offline, and queued outbound packets are discarded
/// until the runtime stops it.
pub(crate) async fn hold_torn_down(
@@ -545,7 +545,7 @@ pub async fn spawn_tcp_client_observed(
let identity = InterfaceIdentity::new(&python_name, &config.name, "TCPClientInterface");
let (teardown_tx, teardown) = ClientTeardown::channel();
// Python connects once, synchronously, before the interface is handed to
// transport (TCPInterface.py:162-163, :241).
// transport (TCPInterface.py).
let mut initial_attempt = Some(
tokio::time::timeout(
std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT),
@@ -561,7 +561,7 @@ pub async fn spawn_tcp_client_observed(
let addr = format!("{}:{}", config.target_host, config.target_port);
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
// Retries within the current outage (TCPInterface.py:271-290).
// Retries within the current outage (TCPInterface.py).
let mut attempts: usize = 0;
loop {
@@ -607,7 +607,7 @@ pub async fn spawn_tcp_client_observed(
state.online.store(true, Ordering::SeqCst);
attempts = 0;
// Python synthesizes on every non-KISS connection
// (TCPInterface.py:178-179, :298-299).
// (TCPInterface.py).
let synthesis = config
.tunnel_identity
.as_ref()
@@ -1009,7 +1009,7 @@ mod tests {
}
/// Python's initiator teardown keeps the interface registered and
/// offline after the retry budget is spent (TCPInterface.py:437-455).
/// offline after the retry budget is spent (TCPInterface.py).
#[tokio::test]
async fn give_up_keeps_interface_registered_and_offline() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(8);
+2 -2
View File
@@ -131,7 +131,7 @@ pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
/// Start a client connection as Python does: traffic queued while offline,
/// after a failed first connect or during an outage, is dropped
/// (TCPInterface.py:314-315), then the connection's synthesis is queued, and
/// (TCPInterface.py), then the connection's synthesis is queued, and
/// only then does the interface report online. A first connect that succeeded
/// before the handle was returned is already online and has nothing to drop.
pub(crate) async fn open_client_connection(
@@ -169,7 +169,7 @@ pub enum InterfaceMode {
Roaming = 0x04,
Boundary = 0x05,
Gateway = 0x06,
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance interfaces.
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py) — local/shared-instance interfaces.
Internal = 0x07,
}
+5 -5
View File
@@ -50,7 +50,7 @@ impl UdpInterfaceConfig {
}
/// Python `get_broadcast_for_if`: the network broadcast of the device's first
/// IPv4 address, computed from its prefix (UDPInterface.py:50-54, netinfo.py:66-70).
/// IPv4 address, computed from its prefix (UDPInterface.py, netinfo.py).
fn broadcast_for_device(device: &str) -> Option<std::net::Ipv4Addr> {
if_addrs::get_if_addrs()
.ok()?
@@ -93,7 +93,7 @@ pub async fn spawn_udp_interface(
}
// Python listens only when both the address and the port are known, and
// otherwise stays offline, so transport never sends on it (UDPInterface.py:90-108).
// otherwise stays offline, so transport never sends on it (UDPInterface.py).
let socket = match (listen_ip_cfg.as_deref(), config.listen_port) {
(Some(ip), Some(port)) => {
let socket = UdpSocket::bind((ip, port)).await?;
@@ -108,7 +108,7 @@ pub async fn spawn_udp_interface(
let online2 = online.clone();
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
// UDPInterface.py:141-142 renders the bind address as configured.
// UDPInterface.py renders the bind address as configured.
let shown_port = match &socket {
Some(socket) => socket.local_addr()?.port(),
None => config.listen_port.unwrap_or(0),
@@ -147,8 +147,8 @@ pub async fn spawn_udp_interface(
};
// Sends use their own broadcast socket, as Python's per-send socket does,
// so send errors never reach the listener (UDPInterface.py:131-140).
// Transport skips an offline interface (Transport.py:1676), so a
// so send errors never reach the listener (UDPInterface.py).
// Transport skips an offline interface (Transport.py), so a
// forward-only interface never transmits either.
let send_socket = match forward_addr {
Some(_) if listening => {
+2 -2
View File
@@ -59,7 +59,7 @@ pub const CMD_REMOTE_INPUT: u16 = 0x0A01;
pub const EVT_MSG: u16 = 0x0000;
pub const EVT_SYSTEM_BOOT: u16 = 0x0001;
pub const EVT_CORE_INIT: u16 = 0x0002;
// "Board hardware initialization" (1.3.8 WeaveInterface.py:342, newer firmware boot event)
// "Board hardware initialization" (1.3.8 WeaveInterface.py, newer firmware boot event)
pub const EVT_BOARD_INIT: u16 = 0x0003;
// Driver events (0x1xxx)
@@ -115,7 +115,7 @@ pub const EVT_STAT_UPTIME: u16 = 0xE001;
pub const EVT_STAT_TIMEBASE: u16 = 0xE002;
pub const EVT_STAT_CPU: u16 = 0xE003;
pub const EVT_STAT_TASK_CPU: u16 = 0xE004;
// EVT_STAT_MEMORY data = [free u32 BE][total u32 BE] (1.3.8 WeaveInterface.py:760-761)
// EVT_STAT_MEMORY data = [free u32 BE][total u32 BE] (1.3.8 WeaveInterface.py)
pub const EVT_STAT_MEMORY: u16 = 0xE005;
pub const EVT_STAT_STORAGE: u16 = 0xE006;
+2 -2
View File
@@ -84,7 +84,7 @@ impl KeepaliveState {
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
// Upstream's responder answers only when a full interval has passed
// since its own last packet (Link.py:1219@1.6.0), which is its reply
// since its own last packet (Link.py), which is its reply
// to the previous keepalive: a request sent exactly on the interval
// arrives a moment early by the responder's clock and gets no reply.
let interval = self.keepalive_interval.mul_f64(1.0 + KEEPALIVE_SEND_MARGIN);
@@ -124,7 +124,7 @@ impl KeepaliveState {
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
// The initiator's watchdog runs on the stretched interval, so its second
// keepalive and the STALE transition still share one pass (Link.py:836-843).
// keepalive and the STALE transition still share one pass (Link.py).
let stale_time = if self.is_initiator {
self.stale_time.mul_f64(1.0 + KEEPALIVE_SEND_MARGIN)
} else {
+18 -18
View File
@@ -160,7 +160,7 @@ fn peer_reported_rtt(secs: f64) -> Option<Duration> {
}
/// Length of a handshake packet as Link.py counts it in `establishment_cost`:
/// the HEADER_1 packet carrying `payload` (Link.py:215, :401, :459, :496).
/// the HEADER_1 packet carrying `payload` (Link.py).
fn packet_len(payload: &[u8]) -> usize {
rns_wire::constants::HEADER_MINSIZE + payload.len()
}
@@ -222,8 +222,8 @@ pub struct Link {
pub establishment_rate: Option<f64>,
/// Expected in-flight data rate (bits/sec), refreshed after each resource transfer.
pub expected_rate: Option<f64>,
/// Path length in hops: initiator sets it at creation (Link.py:282), the
/// destination side from the LRRTT packet at activation (Link.py:525).
/// Path length in hops: initiator sets it at creation (Link.py), the
/// destination side from the LRRTT packet at activation (Link.py).
pub expected_hops: Option<u8>,
pub destination_hash: [u8; 16],
@@ -330,7 +330,7 @@ impl Link {
/// Create an outbound link with caller-supplied ephemeral keys, such as
/// keys from [`crate::stamp::generate_stamped_ephemeral_keys`], signalling
/// `signalled_mtu` as Link.py:392-397@1.6.0 does.
/// `signalled_mtu` as Link.py does.
pub fn new_initiator_with_keys(
destination_hash: [u8; 16],
hops: u8,
@@ -480,7 +480,7 @@ impl Link {
) {
Ok(keys) => keys,
Err(error) => {
// Link.py closes the link when the key exchange raises (Link.py:533-536).
// Link.py closes the link when the key exchange raises (Link.py).
self.state = LinkState::Closed;
self.purge_keys();
return Err(error.into());
@@ -584,7 +584,7 @@ impl Link {
if !ENABLED_MODES.contains(&request.signalling.mode) {
return Err(HandshakeError::UnsupportedMode(request.signalling.mode));
}
// The offered MTU is adopted unclamped (Link.py:202-207@1.6.0).
// The offered MTU is adopted unclamped (Link.py).
let accepted_mtu = LinkMtu::try_from_signal(Some(request.signalling.mtu))?;
let accepted_mdu = accepted_mtu.checked_mdu()?;
@@ -651,7 +651,7 @@ impl Link {
establishment_cost,
establishment_rate: None,
expected_rate: None,
// Populated by the runtime from the LRRTT packet hops (Link.py:525).
// Populated by the runtime from the LRRTT packet hops (Link.py).
expected_hops: None,
destination_hash,
stamp_value: crate::stamp::link_request_stamp_value(&destination_hash, request_data),
@@ -681,7 +681,7 @@ impl Link {
/// An undecryptable packet is ignored. A decrypted payload that is not a
/// msgpack number returns [`HandshakeError::MalformedRtt`] and leaves the
/// link in HANDSHAKE; Link.py tears the link down in that case
/// (Link.py:622-624), which the owner must do.
/// (Link.py), which the owner must do.
pub fn receive_rtt_packet(&mut self, encrypted_data: &[u8]) -> Result<(), HandshakeError> {
if self.state != LinkState::Handshake {
return Err(HandshakeError::InvalidSignature);
@@ -1502,7 +1502,7 @@ impl Link {
}
/// `bytes` is the link payload after the context byte (ciphertext), the
/// same unit as `record_rx` — Packet.py:291 txbytes += len(ciphertext).
/// same unit as `record_rx` — Packet.py txbytes += len(ciphertext).
pub fn record_tx(&mut self, bytes: usize) {
self.tx_bytes += bytes as u64;
self.tx_count += 1;
@@ -1528,7 +1528,7 @@ impl Link {
.should_respond_to_keepalive_at(Instant::now())
}
/// `bytes` is the link payload after the context byte (Link.py:929).
/// `bytes` is the link payload after the context byte (Link.py).
pub fn record_rx(&mut self, bytes: usize) {
self.rx_bytes += bytes as u64;
self.rx_count += 1;
@@ -1655,7 +1655,7 @@ impl Link {
LinkAction::None
}
LinkState::Active => {
// One Link.py watchdog pass (Link.py:831-845): the keepalive
// One Link.py watchdog pass (Link.py): the keepalive
// and the STALE transition can happen together.
let send_keepalive = self.keepalive.should_send_keepalive_at(now);
if send_keepalive {
@@ -1705,14 +1705,14 @@ impl Link {
}
/// Record that an inbound packet other than a keepalive arrived; refreshes
/// `no_data_for` (Link.py:1030).
/// `no_data_for` (Link.py).
pub fn record_inbound_data(&mut self) {
self.keepalive.last_data = std::time::Instant::now();
}
/// Close reason Link.py records for a close started on this side:
/// `InitiatorClosed` on the initiator, `DestinationClosed` on the
/// responder (Link.py:756-757). `Timeout` is kept.
/// responder (Link.py). `Timeout` is kept.
fn local_close_reason(&self, reason: CloseReason) -> CloseReason {
match reason {
CloseReason::Timeout => CloseReason::Timeout,
@@ -1736,7 +1736,7 @@ impl Link {
}
/// Handle a received teardown packet and close the link on success. The
/// reason names the peer's role (Link.py:764-765).
/// reason names the peer's role (Link.py).
pub fn receive_teardown(&mut self, encrypted_data: &[u8]) -> bool {
match self.decrypt(encrypted_data) {
Ok(plaintext) => {
@@ -1897,7 +1897,7 @@ impl Link {
}
/// Resource part size on this Link: `mtu - HEADER_MAXSIZE - IFAC_MIN_SIZE`
/// (Resource.py:346-347@1.6.0).
/// (Resource.py).
pub fn resource_sdu(&self) -> usize {
(self.mtu as usize).saturating_sub(rns_wire::constants::HEADER_MAXSIZE + 1)
}
@@ -3371,8 +3371,8 @@ mod tests {
assert!(link.keepalive.last_keepalive_sent.is_some());
}
/// Initiator knows expected_hops at creation (Link.py:282); the responder
/// side stays unset until the runtime observes the LRRTT hops (Link.py:525).
/// Initiator knows expected_hops at creation (Link.py); the responder
/// side stays unset until the runtime observes the LRRTT hops (Link.py).
#[test]
fn test_expected_hops_initiator_only_at_creation() {
let dest_hash = [0xAB; 16];
@@ -3694,7 +3694,7 @@ mod tests {
}
/// Link.py's initiator goes STALE only on a watchdog pass that also sends a
/// keepalive (Link.py:836-843), whatever the phase of a 1 s tick.
/// keepalive (Link.py), whatever the phase of a 1 s tick.
#[test]
fn initiator_sends_a_keepalive_on_the_tick_it_goes_stale() {
for phase_ms in [0u64, 300, 600, 900] {
+5 -5
View File
@@ -1,5 +1,5 @@
//! Link request stamps: the initiator's X25519 key is a stamp over the
//! destination hash and its Ed25519 key (RNS/Link.py:187-200, :344-382@1.6.0).
//! destination hash and its Ed25519 key (RNS/Link.py).
use std::num::NonZeroUsize;
use std::sync::Arc;
@@ -16,7 +16,7 @@ use crate::handshake::EphemeralKeys;
const KEYSTAMP_POOLING_THRESHOLD: f64 = 10.0;
/// The link request stamping switches an initiator reads (Transport.py:196-205@1.6.0).
/// The link request stamping switches an initiator reads (Transport.py).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinkStampPolicy {
/// Python `STAMP_LRS`.
@@ -42,14 +42,14 @@ impl Default for LinkStampPolicy {
impl LinkStampPolicy {
/// The cost to stamp a request at, given the destination's recalled link
/// cost; `None` means unstamped keys (Link.py:310-313).
/// cost; `None` means unstamped keys (Link.py).
pub fn request_cost(&self, recalled: Option<f64>) -> Option<f64> {
let cost = recalled.or(self.always_stamp_lrs.then_some(self.lr_cost))?;
(cost != 0.0 && self.stamp_lrs).then_some(cost)
}
/// A stop control whose deadline is `timeout` from now. Costs from 10 up
/// use every CPU, as Python pools keystamp work there (Stamps.py:336@1.6.0).
/// use every CPU, as Python pools keystamp work there (Stamps.py).
pub fn control(&self, cost: f64) -> StampControl {
let threads = if cost >= KEYSTAMP_POOLING_THRESHOLD {
std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN)
@@ -113,7 +113,7 @@ impl LinkRequestStamper {
}
/// Create an initiator Link with a stamped request where upstream stamps
/// one, signalling `signalled_mtu` (Link.py:392-397@1.6.0). Blocks the
/// one, signalling `signalled_mtu` (Link.py). Blocks the
/// calling thread while grinding, up to the policy timeout.
pub fn new_initiator(
&self,
+24 -24
View File
@@ -53,7 +53,7 @@ pub const PROCESSING_GRACE: f64 = 1.0;
pub const PART_TIMEOUT_FACTOR: f64 = 4.0;
pub const PART_TIMEOUT_FACTOR_AFTER_RTT: f64 = 2.0;
pub const PROOF_TIMEOUT_FACTOR: f64 = 3.0;
/// Proof-cache queries a sender makes before giving up (Resource.py:1106).
/// Proof-cache queries a sender makes before giving up (Resource.py).
pub const PROOF_CACHE_QUERIES: usize = 3;
pub const RETRY_GRACE_TIME: f64 = 0.25;
pub const PER_RETRY_DELAY: f64 = 0.5;
@@ -201,7 +201,7 @@ impl WindowState {
}
/// Grow the window after a drained request round; the minimum follows a
/// growing window (Resource.py:917-920).
/// growing window (Resource.py).
pub fn grow(&mut self) {
if self.window < self.window_max {
self.window += 1;
@@ -213,13 +213,13 @@ impl WindowState {
}
/// Count a fast round from the first part's request/response rate
/// (Resource.py:866-875). Fast rounds are never reset.
/// (Resource.py). Fast rounds are never reset.
pub fn on_first_part(&mut self, req_resp_rate: f64) {
self.count_fast(req_resp_rate);
}
/// Count fast and very-slow rounds from a drained window's data rate
/// (Resource.py:930-940). Very-slow rounds count only before any fast
/// (Resource.py). Very-slow rounds count only before any fast
/// round, and demotion leaves the current window unclamped.
pub fn on_window_drained(&mut self, req_data_rate: f64) {
self.count_fast(req_data_rate);
@@ -245,7 +245,7 @@ impl WindowState {
/// Shrink after a part timeout. Nothing changes at the window minimum;
/// otherwise the ceiling follows, closing a gap wider than the
/// flexibility by one more step (Resource.py:633-638).
/// flexibility by one more step (Resource.py).
pub fn shrink(&mut self) {
if self.window > self.window_min {
self.window -= 1;
@@ -836,7 +836,7 @@ pub enum ResourceError {
#[error("decompression failed")]
DecompressionFailed,
/// Upstream rejects this with RESOURCE_RCL and tears the Link down
/// (Resource.py:703-709); every other assembly error sends nothing.
/// (Resource.py); every other assembly error sends nothing.
#[error("decompressed resource exceeds the size limit")]
DecompressedTooLarge,
#[error("invalid metadata prefix: declared {declared} bytes, available {available} bytes")]
@@ -867,7 +867,7 @@ pub const MAX_RESOURCE_SIZE: usize = 134_217_727;
/// Default bound on the advertised total size of an inbound Resource that is
/// reassembled in memory (128 MiB - 1). Local difference from upstream, which
/// assembles every inbound Resource to storage and has no such bound
/// (Resource.py:202-207, 714-754@1.6.0). Streaming inbound reassembly to the
/// (Resource.py). Streaming inbound reassembly to the
/// consumer would remove the need for it.
pub const DEFAULT_INBOUND_REASSEMBLY_LIMIT: usize = MAX_RESOURCE_SIZE;
@@ -1485,7 +1485,7 @@ pub enum TransferAction {
}
/// Packet hash of the RESOURCE_PRF packet a receiver sends on `link_id`
/// with `proof_data`, the key a CACHE_REQUEST names (Resource.py:670-673).
/// with `proof_data`, the key a CACHE_REQUEST names (Resource.py).
pub fn resource_proof_packet_hash(link_id: &[u8; 16], proof_data: &[u8]) -> [u8; 32] {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
@@ -1539,7 +1539,7 @@ pub struct OutboundTransfer {
// Python sets the sender's `rtt` once, from advertisement to first request.
rtt_sampled: bool,
failure_reason: Option<String>,
/// Proof-cache queries left before the sender gives up (Resource.py:1106).
/// Proof-cache queries left before the sender gives up (Resource.py).
proof_queries_left: usize,
/// Advertisement wait per attempt before PROCESSING_GRACE; `None` uses
/// `rtt * TRAFFIC_TIMEOUT_FACTOR`, as Resource does without a timeout.
@@ -1712,7 +1712,7 @@ impl OutboundTransfer {
}
/// Python `Resource.cancel()` on the initiator: fail and send ICL
/// (Resource.py:1124-1132). The owner sends it only while the Link is
/// (Resource.py). The owner sends it only while the Link is
/// active, then concludes; the next poll returns `Failed(reason)`.
pub fn cancel(&mut self, reason: &str) -> TransferAction {
self.resource.state = ResourceState::Failed;
@@ -1756,7 +1756,7 @@ impl OutboundTransfer {
}
}
/// Python's AWAITING_PROOF watchdog (Resource.py:656-675).
/// Python's AWAITING_PROOF watchdog (Resource.py).
fn check_proof_timeout(&mut self) -> TransferAction {
if self.proof_wait_started().elapsed() <= self.proof_wait() {
return TransferAction::None;
@@ -2057,7 +2057,7 @@ impl OutboundTransfer {
}
}
// Resource.request (Resource.py:1009-1106).
// Resource.request (Resource.py).
let now = Instant::now();
if !self.rtt_sampled {
self.rtt_sampled = true;
@@ -2112,7 +2112,7 @@ impl OutboundTransfer {
fn progress_timeout(&self) -> Duration {
// rtt * timeout_factor * max_retries + sender_grace_time + the
// receiver's summed per-retry delays (Resource.py:647-649).
// receiver's summed per-retry delays (Resource.py).
let retry_wait = PER_RETRY_DELAY * (MAX_RETRIES * (MAX_RETRIES + 1) / 2) as f64;
self.rtt
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
@@ -2225,7 +2225,7 @@ pub struct InboundTransfer {
rtt_seeded: bool,
}
/// Link facts an incoming resource starts from (Resource.py:215-224, 565-575).
/// Link facts an incoming resource starts from (Resource.py).
#[derive(Debug, Clone, Copy)]
pub struct InboundLinkFacts {
pub rtt: Duration,
@@ -2334,7 +2334,7 @@ impl InboundTransfer {
/// Refresh `self.eifr` in bits/sec: the last window's data rate, else
/// the previous resource's EIFR, else `establishment_cost * 8 / rtt`
/// (Resource.py:565-575).
/// (Resource.py).
pub fn update_eifr(&mut self) {
let rtt_secs = self.rtt.as_secs_f64().max(0.001);
let rate = if self.req_data_rtt_rate != 0.0 {
@@ -2366,7 +2366,7 @@ impl InboundTransfer {
return TransferAction::None;
}
let payload_len = data.len();
// Every part, duplicates included, is activity (Resource.py:850-852).
// Every part, duplicates included, is activity (Resource.py).
self.last_activity = Instant::now();
self.retries_left = MAX_RETRIES;
@@ -2376,7 +2376,7 @@ impl InboundTransfer {
if let Some(sent) = self.req_sent {
let sample = self.last_activity.duration_since(sent);
if !self.rtt_seeded {
// The first sample keeps the Link RTT (Resource.py:859-860).
// The first sample keeps the Link RTT (Resource.py).
self.rtt_seeded = true;
} else if sample < self.rtt {
self.rtt = self.rtt.mul_f64(0.95).max(sample);
@@ -2410,7 +2410,7 @@ impl InboundTransfer {
}
if self.outstanding_parts == 0 {
// Resource.py:914-942.
// Resource.py.
self.resource.window.grow();
if let Some(sent_at) = self.req_sent {
let rtt = self.last_activity.duration_since(sent_at).as_secs_f64();
@@ -2504,7 +2504,7 @@ impl InboundTransfer {
.map_or(0, |len| rns_wire::constants::HEADER_MINSIZE + len);
self.req_resp = None;
// Snapshot the byte counter so the next round's completion can
// compute the delta over this window. Python Resource.py:964.
// compute the delta over this window. Python Resource.py.
self.rtt_rxd_bytes_at_part_req = self.rtt_rxd_bytes;
TransferAction::SendRequest(request_data)
@@ -2578,7 +2578,7 @@ impl InboundTransfer {
self.waiting_for_hmu = false;
return self.request_next();
} else {
// Resource.cancel() on the receiver sends RCL (Resource.py:644-646, 1133-1139).
// Resource.cancel() on the receiver sends RCL (Resource.py).
return self.cancel();
}
}
@@ -3115,7 +3115,7 @@ mod tests {
}
// A very-slow demotion lowers the ceiling but never clamps the current window,
// and fast rounds are only counted, never reset (Resource.py:930-940).
// and fast rounds are only counted, never reset (Resource.py).
#[test]
fn very_slow_demotion_keeps_window_and_counters_are_sticky() {
let mut w = WindowState::new();
@@ -3877,7 +3877,7 @@ mod tests {
panic!()
};
// The sender RTT is the advertisement-to-first-request time, set once
// (Resource.py:1009-1013).
// (Resource.py).
sender.started_at = ago_or_skip!(Duration::from_secs(30));
sender.handle_request(&request);
assert!(sender.rtt >= Duration::from_secs(30));
@@ -3912,7 +3912,7 @@ mod tests {
assert_eq!(sender.resource.state, ResourceState::Advertised);
receiver.receive_part(sender.resource.parts[0].clone());
// Resource.receive_part refreshes activity and retries for every part,
// duplicates included (Resource.py:850-852).
// duplicates included (Resource.py).
receiver.retries_left = 3;
receiver.receive_part(sender.resource.parts[0].clone());
assert_eq!(receiver.retries_left, MAX_RETRIES);
@@ -4645,7 +4645,7 @@ mod tests {
let mut multi_in = MultiSegmentInbound::new(total_segments, original_hash);
for mut segment in multi_out.segments {
// Receivers strip metadata from segment 1 only (Resource.py:718).
// Receivers strip metadata from segment 1 only (Resource.py).
let mut flags = segment.flags;
flags.has_metadata &= segment.segment_index == 1;
let mut inbound = InboundTransfer::from_advertisement(
+2 -2
View File
@@ -83,7 +83,7 @@ impl MessageBase for StreamDataMessage {
let payload = &raw[2..];
if compressed {
// Mirror Python `Buffer.py:94-98`, which also rejects an empty
// Mirror Python `Buffer.py`, which also rejects an empty
// compressed payload: cap decompression at MAX_CHUNK_LEN
// (16 KiB) so a malicious peer can't expand a tiny bz2 payload into
// a large allocation. The streaming hard-cap in `bz2_decompress`
@@ -157,7 +157,7 @@ mod tests {
}
/// Regression for A2026-04.P-01: Buffer-protocol decompression must cap at
/// `MAX_CHUNK_LEN` (16 KiB), matching Python `Buffer.py:96`. A bz2 payload
/// `MAX_CHUNK_LEN` (16 KiB), matching Python `Buffer.py`. A bz2 payload
/// that decompresses past that bound is a compression-bomb attack and must
/// be rejected rather than amplified into a large allocation.
#[test]
+1 -1
View File
@@ -321,7 +321,7 @@ impl Config {
}
/// The `[filter]` section as Python `Reticulum.__apply_config` reads it
/// (Reticulum.py:487-503); malformed values are errors.
/// (Reticulum.py); malformed values are errors.
pub fn filter_policy(
&self,
) -> Result<rns_transport::destination_filter::FilterPolicy, ConfigError> {
@@ -1,9 +1,9 @@
//! Destination stamps for announces, generated off the async runtime.
//!
//! Python reference (1.6.0): `Destination.announce`, `_await_stamp` and
//! `_announce` (`RNS/Destination.py:208-213, 266-365`), the stamper queue
//! (`RNS/Transport.py:99-120, 1445-1493`) and stamp persistence
//! (`RNS/Stamps.py:862-930`). One worker thread serves every destination of
//! `_announce` (`RNS/Destination.py`), the stamper queue
//! (`RNS/Transport.py`) and stamp persistence
//! (`RNS/Stamps.py`). One worker thread serves every destination of
//! the process, one job at a time. An announce requested while its stamp is
//! missing or below target is parked and sent when the stamp is ready.
+21 -21
View File
@@ -329,7 +329,7 @@ fn parse_interface_mode(s: &str) -> Option<InterfaceMode> {
"roaming" => Some(InterfaceMode::Roaming),
"boundary" => Some(InterfaceMode::Boundary),
"gateway" | "gw" => Some(InterfaceMode::Gateway),
// Python 1.3.8 MODE_INTERNAL (Reticulum.py:721,737-738).
// Python 1.3.8 MODE_INTERNAL (Reticulum.py).
"internal" => Some(InterfaceMode::Internal),
_ => None,
}
@@ -794,7 +794,7 @@ fn synthesize_tcp_client(
field: format!("{name}.fixed_mtu"),
message: "must be a representable nonnegative integer".into(),
})?;
// Python's `if fixed_mtu:` leaves zero unset (TCPInterface.py:110).
// Python's `if fixed_mtu:` leaves zero unset (TCPInterface.py).
config.fixed_mtu = (mtu != 0).then_some(mtu);
}
if let Some(retries) = section.get_uint("max_reconnect_tries") {
@@ -812,7 +812,7 @@ fn synthesize_tcp_client(
}
/// The bitrate `optimise_mtu` uses and the IFAC size a frame may add to the
/// hardware MTU (Reticulum.py:1018-1020, :1127-1131@1.6.0).
/// hardware MTU (Reticulum.py).
fn receive_sizing(
section: &ConfigSection,
post_init: &InterfacePostInit,
@@ -851,7 +851,7 @@ fn ifac_credential(
}
/// Validate explicit IFAC byte sizes and TCP client `fixed_mtu` before driver
/// startup. A fixed MTU must be at least 500 (TCPInterface.py:110-116). This
/// startup. A fixed MTU must be at least 500 (TCPInterface.py). This
/// does not validate every interface field; automatic capacity selection
/// happens during runtime registration.
pub fn validate_config_capacity(
@@ -885,7 +885,7 @@ fn synthesize_tcp_server(
mode: InterfaceMode,
) -> Result<InterfaceConfig, InterfaceFactoryError> {
// `port` wins over `listen_port`; `listen_ip` or `device` is required
// (TCPInterface.py:523-524, :541-550).
// (TCPInterface.py).
let port = match parse_port_opt(name, "port", section)? {
Some(port) => port,
None => parse_port_opt(name, "listen_port", section)?.ok_or_else(|| {
@@ -938,7 +938,7 @@ fn synthesize_udp(
config.forward_ip = Some(ip.to_string());
}
config.forward_port = parse_port_opt(name, "forward_port", section)?;
// `port` defaults both ports (UDPInterface.py:68-72).
// `port` defaults both ports (UDPInterface.py).
let port = parse_port_opt(name, "port", section)?;
config.listen_port = config.listen_port.or(port);
config.forward_port = config.forward_port.or(port);
@@ -1055,7 +1055,7 @@ fn synthesize_kiss_serial(
let baud_rate = parse_serial_line_value(name, section, &["speed", "baud_rate"], 9600u32)?;
// Python KISSInterface.py:86-97 — TNC timing defaults 350/20/64/20,
// Python KISSInterface.py — TNC timing defaults 350/20/64/20,
// serial 8N1, flow_control off, optional station-ID beacon.
let tnc = parse_kiss_tnc_params(name, section)?;
Ok(InterfaceConfig::KissSerial(KissSerialConfig {
@@ -1114,13 +1114,13 @@ fn synthesize_auto(
.unwrap_or(rns_interface::auto::McastAddrType::Temporary);
// Python `as_list`; an empty whitelist allows every interface
// (AutoInterface.py:111-112, :229).
// (AutoInterface.py).
let devices = section
.get_list("devices")
.filter(|devices| !devices.is_empty());
let ignored_devices = section.get_list("ignored_devices").unwrap_or_default();
// Reticulum.py:1018-1020, :1204: only `bitrate` counts, and only from
// Reticulum.py: only `bitrate` counts, and only from
// MINIMUM_BITRATE up; a user `configured_bitrate` key is overwritten.
let configured_bitrate = section
.get_uint("bitrate")
@@ -1554,14 +1554,14 @@ fn synthesize_i2p(
mode: InterfaceMode,
) -> Result<InterfaceConfig, InterfaceFactoryError> {
let connectable = section.get_bool("connectable").unwrap_or(false);
// Python `as_list`: each item is a peer (I2PInterface.py:731, :812-813).
// Python `as_list`: each item is a peer (I2PInterface.py).
let peers = section.get_list("peers").unwrap_or_default();
// Python has neither key and runs the interface idle; nothing to register.
if !connectable && peers.is_empty() {
warn!(interface = %name, "I2PInterface has neither connectable nor peers; nothing to do");
return Err(InterfaceFactoryError::Disabled(name.to_string()));
}
// Rust-only keys first, then i2plib's `I2P_SAM_ADDRESS` (i2plib/utils.py:29-35).
// Rust-only keys first, then i2plib's `I2P_SAM_ADDRESS` (i2plib/utils.py).
let env_address = std::env::var("I2P_SAM_ADDRESS").ok().and_then(|value| {
let (host, port) = value.split_once(':')?;
Some((
@@ -1831,7 +1831,7 @@ fn synthesize_ax25kiss(
let baud_rate = parse_serial_line_value(name, section, &["speed", "baud_rate"], 9600u32)?;
// Python AX25KISSInterface requires an explicit 0..=15 SSID
// (default -1 fails validation, AX25KISSInterface.py:138-139).
// (default -1 fails validation, AX25KISSInterface.py).
let ssid_raw = section
.get_int("ssid")
.ok_or_else(|| InterfaceFactoryError::MissingField {
@@ -1846,7 +1846,7 @@ fn synthesize_ax25kiss(
}
let ssid = ssid_raw as u8;
// Python defaults: 350/20/64/20 (AX25KISSInterface.py:141-144).
// Python defaults: 350/20/64/20 (AX25KISSInterface.py).
let tnc = parse_kiss_tnc_params(name, section)?;
let preamble = u32::from(tnc.preamble_ms);
let txtail = u32::from(tnc.txtail_ms);
@@ -1879,7 +1879,7 @@ fn synthesize_backbone(
mode: InterfaceMode,
client_type: bool,
) -> Result<InterfaceConfig, InterfaceFactoryError> {
// Reticulum.py:1210-1222: `listen_on`, `remote` and `port` overwrite
// Reticulum.py: `listen_on`, `remote` and `port` overwrite
// `listen_ip`, `target_host` and both ports; `target_host` or the client
// type selects a client.
let listen_ip = section
@@ -1969,7 +1969,7 @@ fn synthesize_backbone(
}
/// Python parses the stamp cost keys before checking `enabled`, so a bad value
/// aborts startup even on a disabled interface (Reticulum.py:963-971).
/// aborts startup even on a disabled interface (Reticulum.py).
pub fn validate_stamp_costs(
name: &str,
section: &ConfigSection,
@@ -2288,7 +2288,7 @@ mod tests {
let mut section = enabled_section();
section.set("type", "TCPServerInterface");
section.set("listen_port", "4242");
// Upstream requires `listen_ip` or `device` (TCPInterface.py:550).
// Upstream requires `listen_ip` or `device` (TCPInterface.py).
assert!(matches!(
synthesize_interface("test_srv", &section),
Err(InterfaceFactoryError::MissingField { field, .. }) if field == "listen_ip"
@@ -2513,7 +2513,7 @@ mod tests {
assert_eq!(pi.announce_rate_penalty, Some(0));
}
/// Python KISSInterface.py:86-97 defaults: 350/20/64/20, 8N1, no beacon.
/// Python KISSInterface.py defaults: 350/20/64/20, 8N1, no beacon.
#[cfg(feature = "serial")]
#[test]
fn test_synthesize_kiss_defaults_match_python() {
@@ -2563,7 +2563,7 @@ mod tests {
}
}
/// Python AX25KISSInterface.py:141-144 defaults + 0..=15 SSID requirement.
/// Python AX25KISSInterface.py defaults + 0..=15 SSID requirement.
#[cfg(feature = "serial")]
#[test]
fn test_synthesize_ax25kiss_defaults_and_ssid() {
@@ -2894,7 +2894,7 @@ mod tests {
}
/// Python reads both lists with `as_list`, and an empty whitelist allows
/// every interface (AutoInterface.py:111-112, :154-162, :229).
/// every interface (AutoInterface.py).
#[test]
fn auto_device_lists_read_like_python_as_list() {
let lists = |devices: &str, ignored: &str| {
@@ -3474,7 +3474,7 @@ mod tests {
assert_eq!(pi.announce_cap, None);
}
/// Python takes each `as_list` item as a peer (I2PInterface.py:731, :812-813).
/// Python takes each `as_list` item as a peer (I2PInterface.py).
#[test]
fn i2p_peers_read_like_python_as_list() {
let peers = |value: &str| {
@@ -3674,7 +3674,7 @@ mod tests {
));
section.set("port", "4242");
// A listener needs `listen_ip` or `device` (BackboneInterface.py:162-168).
// A listener needs `listen_ip` or `device` (BackboneInterface.py).
assert!(matches!(
synthesize_interface("backbone_defaults", &section),
Err(InterfaceFactoryError::MissingField { field, .. }) if field == "listen_ip"
+3 -3
View File
@@ -329,7 +329,7 @@ async fn wait_for_response(
) -> Result<Vec<u8>, LinkClientError> {
// The request timeout, capped by the overall deadline, applies until a
// response Resource is accepted;
// after that the Resource watchdog ends a stalled transfer (Link.py:1475-1522).
// after that the Resource watchdog ends a stalled transfer (Link.py).
// Between segments no watchdog runs, so the request timeout bounds each gap.
let request_bound = deadline >= req_timeout;
let deadline_at = Instant::now() + deadline.min(req_timeout);
@@ -455,7 +455,7 @@ async fn wait_for_response(
let rtt = link.rtt.unwrap_or(Duration::from_millis(500));
let mut flags = adv.flags;
// Only segment 1 carries metadata bytes (Resource.py:718).
// Only segment 1 carries metadata bytes (Resource.py).
if adv.segment_index > 1 {
flags.has_metadata = false;
}
@@ -723,7 +723,7 @@ async fn poll_response_resources(
)
.await?;
}
// Out of retries: Resource.cancel() sends RCL (Resource.py:1133-1139).
// Out of retries: Resource.cancel() sends RCL (Resource.py).
TransferAction::SendCancel(_, resource_hash) if link.state == LinkState::Active => {
send_link_data(
transport_tx,
+3 -3
View File
@@ -177,7 +177,7 @@ pub(crate) struct ValidatedLinkProof {
/// Wait for the first cryptographically valid LRPROOF while the Link remains
/// pending. Invalid candidates are unauthenticated input and cannot terminate
/// establishment or select the endpoint interface. A signed proof that closes
/// the Link (a low-order key, as Link.py:533-536) ends the wait.
/// the Link (a low-order key, as Link.py) ends the wait.
pub(crate) async fn wait_for_valid_proof(
delivery_rx: &mut mpsc::Receiver<DestinationEvent>,
link: &mut Link,
@@ -238,7 +238,7 @@ pub(crate) async fn wait_for_valid_proof(
}
/// What Link.py takes from the path table for a new initiator Link
/// (Link.py:304-309): the hops and the first-hop timeout that extends the
/// (Link.py): the hops and the first-hop timeout that extends the
/// establishment timeout.
pub(crate) async fn initiator_path_timing(
transport_tx: &mpsc::Sender<TransportMessage>,
@@ -284,7 +284,7 @@ async fn query(
}
/// Record an inbound packet on an initiator Link as Link.py's `__receive`
/// does (Link.py:1024-1032): a keepalive refreshes liveness but not data,
/// does (Link.py): a keepalive refreshes liveness but not data,
/// and the responder-only 0xFF request is ignored.
pub(crate) fn record_initiator_inbound(link: &mut Link, raw: &[u8]) {
let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(raw) else {
+30 -30
View File
@@ -1360,7 +1360,7 @@ impl LinkManager {
/// Tear down, with LINKCLOSE, every active Link whose `no_data_for` exceeds
/// `timeout`, as LXMRouter.clean_links does for propagation links
/// (LXMRouter.py:1072-1080). Keepalives do not count as data.
/// (LXMRouter.py). Keepalives do not count as data.
pub fn set_data_inactivity_timeout(&mut self, timeout: Option<std::time::Duration>) {
self.data_inactivity_timeout = timeout;
}
@@ -1977,7 +1977,7 @@ impl LinkManager {
}
/// Ask transport whether a verified LINKIDENTIFY came from a blackholed
/// identity before accepting it (Link.py:1067-1070).
/// identity before accepting it (Link.py).
fn check_identity_blackhole(&mut self, link_id: [u8; 16], remote_pub: [u8; 64]) {
let (response_tx, result_rx) = oneshot::channel();
let staged = Self::stage_required_link_control(
@@ -3333,7 +3333,7 @@ impl LinkManager {
}
let request_data = &raw[data_offset..];
// Link.py:214 reads packet.hops after Transport.py:2028 increments it;
// Link.py reads packet.hops after Transport.py increments it;
// the delivered raw is unadjusted.
let hops = header.hops.saturating_add(1);
@@ -3344,7 +3344,7 @@ impl LinkManager {
return;
}
// Link.validate_request (Link.py:193-195@1.6.0): the cost is read now, so
// Link.validate_request (Link.py): the cost is read now, so
// a changed set_link_cost applies to the next request.
let policy = crate::destination_stamper::policy();
if policy.lr_stamps_enforced {
@@ -3662,7 +3662,7 @@ impl LinkManager {
match active.link.receive_rtt_packet(data) {
Ok(()) => {
// +1 mirrors Python's increment-on-receive
// (Transport.py:1491) before Link.py:525 reads
// (Transport.py) before Link.py reads
// packet.hops; the delivered raw is unadjusted.
active.link.expected_hops = Some(header.hops.saturating_add(1));
tracing::info!(
@@ -3682,7 +3682,7 @@ impl LinkManager {
}
}
Err(rns_link::handshake::HandshakeError::MalformedRtt) => {
// Link.py:622-624 tears the link down.
// Link.py tears the link down.
tracing::warn!(
link_id = hex::encode(link_id),
"malformed LRRTT, tearing down link"
@@ -3739,7 +3739,7 @@ impl LinkManager {
active.link.record_inbound();
active.link.record_rx(data.len());
// Keepalives are NOT encrypted (Packet.py:205-208).
// Keepalives are NOT encrypted (Packet.py).
if data.first() == Some(&rns_link::constants::KEEPALIVE_REQUEST) {
// Only the responder replies.
if active.link.is_initiator {
@@ -3856,7 +3856,7 @@ impl LinkManager {
&proof_data,
rns_wire::context::PacketContext::None,
) {
// Proofs to a link count into txbytes (Link.py:388, Packet.py:291).
// Proofs to a link count into txbytes (Link.py, Packet.py).
active.link.record_tx(proof_data.len());
tracing::debug!(
link_id = hex::encode(link_id),
@@ -4415,7 +4415,7 @@ impl LinkManager {
}
}
rns_wire::context::PacketContext::Resource => {
// Python encrypts payload ONCE before chunking (Resource.py:424);
// Python encrypts payload ONCE before chunking (Resource.py);
// chunks ride raw. Decrypt happens in InboundTransfer::complete.
let mut teardown_corrupt = false;
if let Some(active) = self.active_links.get_mut(&link_id) {
@@ -4486,7 +4486,7 @@ impl LinkManager {
}
if let Some(rh) = completed_rh {
// Reverses pre-chunk encryption (Resource.py:424).
// Reverses pre-chunk encryption (Resource.py).
let decrypt_fn = |data: &[u8]| -> Result<
Vec<u8>,
rns_protocol::resource::ResourceError,
@@ -4559,7 +4559,7 @@ impl LinkManager {
break 'resource_part;
}
// PROOF+RESOURCE_PRF = plaintext, PacketType::Proof
// (Packet.py:195-197). Each split segment still needs its
// (Packet.py). Each split segment still needs its
// own proof or the sender retries.
if !Self::send_resource_action(
&self.transport_tx,
@@ -4762,7 +4762,7 @@ impl LinkManager {
Some(Err(error)) => {
// Only a decompression overflow is rejected and tears
// the Link down; a corrupt assembly sends nothing
// (Resource.py:703-709, 732-738).
// (Resource.py).
if matches!(
error,
rns_protocol::resource::ResourceError::DecompressedTooLarge
@@ -4813,7 +4813,7 @@ impl LinkManager {
}
}
rns_wire::context::PacketContext::ResourceReq => {
// Receiver's HMU for outbound transfer (Link.py:1104-1124).
// Receiver's HMU for outbound transfer (Link.py).
if let Some(active) = self.active_links.get_mut(&link_id) {
active.link.record_inbound();
active.link.record_rx(data.len());
@@ -4882,7 +4882,7 @@ impl LinkManager {
}
}
rns_wire::context::PacketContext::ResourceIcl => {
// Sender-initiated cancel of an inbound transfer (Link.py:1135-1142).
// Sender-initiated cancel of an inbound transfer (Link.py).
if let Some(active) = self.active_links.get_mut(&link_id) {
active.link.record_inbound();
active.link.record_rx(data.len());
@@ -4901,7 +4901,7 @@ impl LinkManager {
.then_some(rh)
});
if let Some(resource_id) = resource_id {
// Link.py:1199-1206 runs Resource.cancel(), which answers with RCL.
// Link.py runs Resource.cancel(), which answers with RCL.
if let Some(action) =
active.inbound_resources.get_mut(&rh).map(|t| t.cancel())
&& active.link.state == LinkState::Active
@@ -4934,7 +4934,7 @@ impl LinkManager {
}
}
rns_wire::context::PacketContext::ResourceRcl => {
// Receiver-initiated reject of an outbound transfer (Link.py:1144-1151).
// Receiver-initiated reject of an outbound transfer (Link.py).
if let Some(active) = self.active_links.get_mut(&link_id) {
active.link.record_inbound();
active.link.record_rx(data.len());
@@ -5019,7 +5019,7 @@ impl LinkManager {
rns_wire::context::PacketContext::ResourcePrf => {
if let Some(active) = self.active_links.get_mut(&link_id) {
active.link.record_inbound();
// RESOURCE_PRF proofs route through Link.receive (Transport.py:2268).
// RESOURCE_PRF proofs route through Link.receive (Transport.py).
active.link.record_rx(data.len());
if data.len() >= 64 {
let mut rh = [0u8; 32];
@@ -5304,7 +5304,7 @@ impl LinkManager {
}
let action = match action {
TransferAction::SendCancel(cancel_type, hash) => {
// Resource.cancel(): RCL only while the Link is active (Resource.py:1133-1139).
// Resource.cancel(): RCL only while the Link is active (Resource.py).
if active.link.state == LinkState::Active {
Self::send_resource_action(
&self.transport_tx,
@@ -5315,7 +5315,7 @@ impl LinkManager {
TransferAction::SendCancel(cancel_type, hash),
);
}
// Removed before resource_concluded, so no carryover (Resource.py:1137-1142).
// Removed before resource_concluded, so no carryover (Resource.py).
TransferAction::Failed("resource transfer timed out".to_string())
}
action => action,
@@ -5406,7 +5406,7 @@ impl LinkManager {
for (resource_hash, action) in outbound_watchdog_actions {
let action = match action {
TransferAction::SendCancel(cancel_type, hash) => {
// Resource.cancel(): ICL only while the Link is active (Resource.py:1124-1132).
// Resource.cancel(): ICL only while the Link is active (Resource.py).
if active.link.state == LinkState::Active {
Self::send_resource_action(
&self.transport_tx,
@@ -5568,7 +5568,7 @@ impl LinkManager {
.map(|(link_id, active)| (*link_id, active.link.role()))
.collect();
for (link_id, role) in idle {
// Link.teardown records the reason from the local role (Link.py:756-757).
// Link.teardown records the reason from the local role (Link.py).
let reason = match role {
LinkRole::Initiator => CloseReason::InitiatorClosed,
LinkRole::Responder => CloseReason::DestinationClosed,
@@ -6162,7 +6162,7 @@ impl LinkManager {
/// Python `Link.resource_concluded` for an incoming resource: keep its
/// window and EIFR for the next one and refresh `expected_rate`
/// (Link.py:1344-1350).
/// (Link.py).
fn inbound_resource_concluded(
last_inbound_resource: &mut HashMap<[u8; 16], (usize, Option<f64>)>,
link: &mut Link,
@@ -7713,7 +7713,7 @@ impl LinkManager {
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
// Python refuses outbound only on CLOSED links (Packet.py:286); Stale
// Python refuses outbound only on CLOSED links (Packet.py); Stale
// links stay sendable so peers can probe and recover them.
if !matches!(active.link.state, LinkState::Active | LinkState::Stale) {
return Err(LinkSendError::LinkNotActive);
@@ -8114,7 +8114,7 @@ impl LinkManager {
}
}
// Destination.py:730-749: another writer may have rotated the ring file.
// Destination.py: another writer may have rotated the ring file.
let mut ratchets = self
.destination_ratchets
.write()
@@ -8130,7 +8130,7 @@ impl LinkManager {
ring.reload(identity)
});
if let Err(error) = reloaded {
// Destination.py:559-568: an unreadable ring file disables ratchets.
// Destination.py: an unreadable ring file disables ratchets.
tracing::error!(
path = %ring.path().display(),
%error,
@@ -9066,7 +9066,7 @@ mod tests {
};
let idle = std::time::Duration::from_secs(181);
// A keepalive does not refresh the data clock (Link.py:1030).
// A keepalive does not refresh the data clock (Link.py).
lm.active_links
.get_mut(&link_id)
.unwrap()
@@ -9882,8 +9882,8 @@ mod tests {
}
/// Destination side learns expected_hops from the LRRTT packet at
/// activation (Link.py:525); +1 mirrors Python's increment-on-receive.
/// The initiator keeps its construction-time value (Link.py:282).
/// activation (Link.py); +1 mirrors Python's increment-on-receive.
/// The initiator keeps its construction-time value (Link.py).
#[test]
fn lrrtt_activation_sets_expected_hops_on_destination_side() {
let dest_hash = [0x37; 16];
@@ -12484,8 +12484,8 @@ mod tests {
));
}
/// 1.3.8 stats parity (Packet.py:291): tx counts the link payload after
/// the context byte — the same unit rx counts (Link.py:929) — so a channel
/// 1.3.8 stats parity (Packet.py): tx counts the link payload after
/// the context byte — the same unit rx counts (Link.py) — so a channel
/// echo round-trip yields matching data counters on both peers.
#[test]
fn channel_echo_round_trip_counts_matching_tx_rx_bytes() {
+5 -5
View File
@@ -1217,7 +1217,7 @@ impl LinkSession {
let (mut link, request_data) =
crate::link_stamp::new_initiator(&transport_tx, config.destination_hash, config.hops)
.await?;
// Python starts the establishment watchdog after stamping (Link.py:404-405).
// Python starts the establishment watchdog after stamping (Link.py).
let deadline = Instant::now()
.checked_add(config.establishment_timeout)
.ok_or_else(|| LinkSessionError::HandshakeFailed("unrepresentable timeout".into()))?;
@@ -2346,7 +2346,7 @@ async fn send_resource_action(
rns_wire::flags::PacketType::Data,
),
TransferAction::SendCancel(cancel_type, resource_hash) => {
// Resource.cancel() sends ICL/RCL only on an active Link (Resource.py:1126, 1134).
// Resource.cancel() sends ICL/RCL only on an active Link (Resource.py).
if link.state != LinkState::Active {
return Ok(());
}
@@ -3314,7 +3314,7 @@ async fn complete_inbound_segment(
.map_err(|_| rns_protocol::resource::ResourceError::DecryptFailed)
};
let completion = inbound.transfer.complete(Some(&decrypt));
// Link.resource_concluded (Link.py:1344-1350).
// Link.resource_concluded (Link.py).
resources.last_inbound = Some((
inbound.transfer.resource.window.window,
inbound.transfer.eifr,
@@ -3328,7 +3328,7 @@ async fn complete_inbound_segment(
Ok(completed) => completed,
Err(error) => {
// Only a decompression overflow is rejected and tears the Link
// down; a corrupt assembly sends nothing (Resource.py:703-709, 732-738).
// down; a corrupt assembly sends nothing (Resource.py).
let reject = matches!(
error,
rns_protocol::resource::ResourceError::DecompressedTooLarge
@@ -3676,7 +3676,7 @@ async fn handle_inbound_resource_cancel(
let Some(inbound) = resources.inbound.get_mut(&segment) else {
return;
};
// Link.py:1199-1206 runs Resource.cancel(), which answers with RCL.
// Link.py runs Resource.cancel(), which answers with RCL.
let action = inbound.transfer.cancel();
let resource_id = inbound.resource_id;
let _ = send_resource_action(transport_tx, attached_interface, link, action).await;
+3 -3
View File
@@ -1,4 +1,4 @@
//! Stamped link requests for initiators (RNS/Link.py:300-395@1.6.0): the cost
//! Stamped link requests for initiators (RNS/Link.py): the cost
//! is the one the destination announced, recalled from Transport, and keys are
//! ground off the async runtime under `lr_stamp_timeout`.
@@ -80,7 +80,7 @@ pub fn link_mtu_discovery() -> bool {
crate::reticulum::get_instance().is_none_or(|handle| handle.link_mtu_discovery())
}
/// The MTU a new link request to `destination_hash` signals (Link.py:392-397@1.6.0):
/// The MTU a new link request to `destination_hash` signals (Link.py):
/// the next-hop interface's hardware MTU when discovery is on and that interface
/// autoconfigures or fixes its MTU, otherwise the base MTU.
pub async fn signalled_link_mtu(
@@ -116,7 +116,7 @@ pub async fn signalled_link_mtu(
}
/// The request keys upstream would use for a link to `destination_hash`:
/// stamped at the destination's announced cost (Link.py:310-316@1.6.0), with
/// stamped at the destination's announced cost (Link.py), with
/// the grind on the blocking pool. Synchronous owners hand the result to
/// their `provide_link_request_keys`. Dropping the future cancels the grind.
pub async fn link_request_keys(
+16 -16
View File
@@ -64,7 +64,7 @@ pub(crate) async fn start_remote_management_with_stats(
app_name,
Some(signing_key),
);
// Python's management Links take the Link default (Link.py:239).
// Python's management Links take the Link default (Link.py).
lm.set_resource_strategy(rns_link::link::ResourceStrategy::AcceptNone);
let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes());
@@ -139,9 +139,9 @@ fn peer_allowed(allowed: &[[u8; 16]], peer: &[u8; 16]) -> bool {
/// Request: `[include_link_count, include_profiling?]`.
/// Response: the control port's stats dict, then the link count when it is
/// asked for, then the profiling results when they are (Transport.py:3325-3337).
/// asked for, then the profiling results when they are (Transport.py).
/// Rust runs no profiler, so those are nil, as Python's are until its profiler
/// has run (Reticulum.py:1956-1965).
/// has run (Reticulum.py).
fn handle_status(
tx: &mpsc::Sender<TransportMessage>,
data: &[u8],
@@ -182,7 +182,7 @@ fn handle_status(
/// Request: `[command: "table"|"rates", destination?: bytes, max_hops?: int]`.
/// Response: the control port's path or rate table, filtered
/// (Transport.py:3346-3371).
/// (Transport.py).
fn handle_path(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u8>> {
let request = parse_path_request(data)?;
let destination = request.destination.as_ref();
@@ -237,7 +237,7 @@ fn handle_path(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u
}
/// Python keeps an entry when a destination argument other than nil equals
/// its hash (Transport.py:3361, :3368), so a hash of another length, or one
/// its hash (Transport.py), so a hash of another length, or one
/// sent as a string, matches nothing.
fn wanted(destination: Option<&rmpv::Value>, hash: &[u8; 16]) -> bool {
match destination {
@@ -247,7 +247,7 @@ fn wanted(destination: Option<&rmpv::Value>, hash: &[u8; 16]) -> bool {
}
}
/// Python's `hops <= max_hops` (Reticulum.py:1738), or `None` where Python
/// Python's `hops <= max_hops` (Reticulum.py), or `None` where Python
/// cannot compare the two, which makes its handler raise and send nothing.
fn within_hops(max_hops: Option<&rmpv::Value>, hops: u8) -> Option<bool> {
let Some(max_hops) = max_hops.filter(|max_hops| !max_hops.is_nil()) else {
@@ -263,7 +263,7 @@ fn within_hops(max_hops: Option<&rmpv::Value>, hops: u8) -> Option<bool> {
}
}
/// Python's `/status` flags (Transport.py:3329-3335).
/// Python's `/status` flags (Transport.py).
#[derive(Debug, PartialEq, Eq)]
struct StatusRequest {
link_count: bool,
@@ -271,7 +271,7 @@ struct StatusRequest {
}
/// `None` unless the request is a non-empty list, which Python leaves
/// unanswered (Transport.py:3329).
/// unanswered (Transport.py).
fn parse_status_request(data: &[u8]) -> Option<StatusRequest> {
let v: rmpv::Value = rmp_serde::from_slice(data).ok()?;
let flags = v.as_array().filter(|flags| !flags.is_empty())?;
@@ -292,7 +292,7 @@ fn python_eq_true(value: &rmpv::Value) -> bool {
}
}
/// Python's `/path` arguments, kept as sent (Transport.py:3350-3355).
/// Python's `/path` arguments, kept as sent (Transport.py).
struct PathRequest {
command: String,
destination: Option<rmpv::Value>,
@@ -603,7 +603,7 @@ mod tests {
}
/// Python's `/status` answers with `get_interface_stats()` itself
/// (Transport.py:3325-3337), so `rnstatus -R` needs the full 1.5.5 key set.
/// (Transport.py), so `rnstatus -R` needs the full 1.5.5 key set.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_status_carries_every_python_155_key() {
let tx = spawn_mock_transport();
@@ -652,8 +652,8 @@ mod tests {
}
/// `rnpath -R -r` sorts the remote rate table on `last` and reads every
/// rate field (rnpath.py:327-370); Python returns whole rate-table entries
/// (Transport.py:3364-3369, Reticulum.py:1747-1766).
/// rate field (rnpath.py); Python returns whole rate-table entries
/// (Transport.py, Reticulum.py).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_rates_return_whole_python_rate_entries() {
let tx = spawn_mock_transport();
@@ -709,8 +709,8 @@ mod tests {
/// Python appends the link count when the first flag `== True`, then the
/// profiling results when the second does, and answers nothing unless the
/// request is a non-empty list (Transport.py:3325-3337). Until a profiler
/// has run, the results are nil (Reticulum.py:1956-1965).
/// request is a non-empty list (Transport.py). Until a profiler
/// has run, the results are nil (Reticulum.py).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_status_flags_follow_python() {
use rmpv::Value;
@@ -809,8 +809,8 @@ mod tests {
}
/// Python keeps a path when `hops <= max_hops` compares true and a
/// destination argument equals its hash (Reticulum.py:1738,
/// Transport.py:3361, :3368): a hash of another length, or one sent as a
/// destination argument equals its hash (Reticulum.py,
/// Transport.py): a hash of another length, or one sent as a
/// string, matches nothing, and a `max_hops` it cannot compare raises,
/// so no answer is sent.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+109 -109
View File
@@ -76,9 +76,9 @@ struct InterfaceControlMetadata {
/// `target_ip`, `target_port`), which auto-connect checks.
client_target: Option<(String, u16)>,
/// The network identity, in hex, that announced an auto-connected
/// interface (Python `autoconnect_source`, Discovery.py:865).
/// interface (Python `autoconnect_source`, Discovery.py).
autoconnect_source: Option<String>,
// Per-interface stamp costs, copied raw to spawned children (TCPInterface.py:608-609).
// Per-interface stamp costs, copied raw to spawned children (TCPInterface.py).
destination_cost: Option<f64>,
pr_cost: Option<f64>,
/// What a connection this interface accepts takes from it.
@@ -86,7 +86,7 @@ struct InterfaceControlMetadata {
}
/// The listener settings Python copies to each accepted connection
/// (TCPInterface.py:588-646, BackboneInterface.py:706-757, I2PInterface.py:861-912).
/// (TCPInterface.py, BackboneInterface.py, I2PInterface.py).
#[derive(Clone)]
struct SpawnInheritance {
mode: rns_interface::traits::InterfaceMode,
@@ -171,7 +171,7 @@ struct TransportCompletion {
const RUNTIME_INTERFACE_DRAIN_DEADLINE: Duration = Duration::from_secs(10);
/// Python `Transport.application_identity.hash`: one random requester per
/// process for destination type requests (Transport.py:449).
/// process for destination type requests (Transport.py).
fn application_requester() -> [u8; 16] {
static REQUESTER: OnceLock<[u8; 16]> = OnceLock::new();
*REQUESTER.get_or_init(|| Identity::new().hash)
@@ -269,7 +269,7 @@ impl RuntimeShutdownCoordinator {
}
/// Python's exit handler deregisters this process's destination types
/// from the shared instance first (Reticulum.py:189).
/// from the shared instance first (Reticulum.py).
fn install_exit_unwants(&self, target: SharedRpcTarget) {
*self
.inner
@@ -1285,14 +1285,14 @@ pub struct DiscoveryRuntime {
announcer_started: Mutex<bool>,
subscriber_started: Mutex<bool>,
local_interfaces: Mutex<Vec<LocalDiscoveryInterface>>,
/// Any configured section is discoverable, enabled or not (Reticulum.py:1074-1080).
/// Any configured section is discoverable, enabled or not (Reticulum.py).
announcer_configured: AtomicBool,
autoconnected: Mutex<HashMap<[u8; 32], AutoconnectedInterface>>,
bootstrap_interfaces: Mutex<Vec<u64>>,
/// Configs of `bootstrap_only` interfaces, re-spawned when no
/// auto-connected interface is online (Reticulum.py:1275).
/// auto-connected interface is online (Reticulum.py).
bootstrap_configs: Mutex<Vec<BootstrapConfig>>,
/// A bootstrap-only I2P interface stays attached (Reticulum.py:888), so
/// A bootstrap-only I2P interface stays attached (Reticulum.py), so
/// Python never re-enables bootstrap interfaces beside it.
i2p_bootstrap: AtomicBool,
autoconnect_lock: Mutex<()>,
@@ -1300,7 +1300,7 @@ pub struct DiscoveryRuntime {
initial_autoconnect_ran: AtomicBool,
}
/// An auto-connected interface under the monitor (Discovery.py:651-718).
/// An auto-connected interface under the monitor (Discovery.py).
struct AutoconnectedInterface {
/// `None` while the interface is still being spawned.
id: Option<u64>,
@@ -1341,7 +1341,7 @@ struct LocalDiscoveryInterface {
online: Option<Arc<AtomicBool>>,
/// Overrides `config.reachable_on` once the interface learns its address.
reachable_on: Option<tokio::sync::watch::Receiver<Option<String>>>,
/// Python `location_cmd` (Reticulum.py:1096).
/// Python `location_cmd` (Reticulum.py).
location_cmd: Option<String>,
}
@@ -1775,7 +1775,7 @@ impl ReticulumHandle {
}
async fn default_packet_receipt_timeout(&self, destination_hash: [u8; 16]) -> Duration {
// Reticulum.py:1985-1987 and Transport.py:3488@1.6.0 fallbacks.
// Reticulum.py and Transport.py fallbacks.
let first_hop =
self.first_hop_timeout(destination_hash)
.await
@@ -2025,8 +2025,8 @@ impl ReticulumHandle {
}
/// Return the next-hop interface MTU in bytes, when available. A Client's
/// next hop is its own local shared-instance interface (Transport.py:3508,
/// 3517-3524@1.6.0). This interface value is not a negotiated Link payload
/// next hop is its own local shared-instance interface (Transport.py,
/// 3517-3524). This interface value is not a negotiated Link payload
/// budget or the MTU of every hop on the path.
pub async fn next_hop_hardware_mtu(
&self,
@@ -2303,7 +2303,7 @@ impl ReticulumHandle {
/// A destination type request: registered locally, and on a shared-instance
/// client also with the shared instance, whose answer is returned. A failed
/// RPC answers false (Reticulum.py:2224-2267).
/// RPC answers false (Reticulum.py).
async fn destination_type_request(
&self,
local: TransportQuery,
@@ -2335,7 +2335,7 @@ impl ReticulumHandle {
/// Python `Reticulum.attach_interface`: brings up a configured interface
/// that is not running, even one disabled in its section. True, false, or
/// `None` when the configuration has no such section. A shared-instance
/// client forwards the call to the instance (Reticulum.py:850-875, 2141-2148).
/// client forwards the call to the instance (Reticulum.py).
pub async fn attach_interface(&self, name: &str) -> Result<Option<bool>, ControlError> {
if self.instance_mode == InstanceMode::Client {
return self
@@ -2350,7 +2350,7 @@ impl ReticulumHandle {
/// Python `Reticulum.detach_interface`: stops and removes a running
/// interface and the connections it spawned. `None` when no interface has
/// that name (Reticulum.py:877-904, 2150-2157).
/// that name (Reticulum.py).
pub async fn detach_interface(&self, name: &str) -> Result<Option<bool>, ControlError> {
if self.instance_mode == InstanceMode::Client {
return self
@@ -2364,7 +2364,7 @@ impl ReticulumHandle {
}
/// Python `Reticulum.reload_interface`: detaches a running interface and
/// attaches it again from the current configuration (Reticulum.py:906-920).
/// attaches it again from the current configuration (Reticulum.py).
pub async fn reload_interface(&self, name: &str) -> Result<Option<bool>, ControlError> {
if self.instance_mode == InstanceMode::Client {
return self
@@ -2528,7 +2528,7 @@ impl ReticulumHandle {
}
/// Python `Reticulum.required_announces_only`: only shared-instance
/// clients may restrict their own announce ingress (Reticulum.py:2216-2222).
/// clients may restrict their own announce ingress (Reticulum.py).
pub async fn required_announces_only(&self, enabled: bool) -> bool {
if self.instance_mode != InstanceMode::Client {
return false;
@@ -2666,7 +2666,7 @@ impl ReticulumHandle {
}
/// Blackholed identity hashes, which listing discovered interfaces culls
/// (Discovery.py:528, :554-555); empty when the query fails.
/// (Discovery.py); empty when the query fails.
async fn blackholed_identity_set(&self) -> std::collections::HashSet<[u8; 16]> {
match self
.query_control_result(TransportQuery::GetBlackholedIdentities)
@@ -2755,7 +2755,7 @@ fn transport_query_to_rpc_request(query: &TransportQuery) -> Option<crate::rpc::
},
TransportQuery::GetBlackholedIdentities => RpcRequest::GetBlackholedIdentities,
// Python 1.3.8 is_blackholed() proxies to the shared instance
// (Reticulum.py:1655-1659).
// (Reticulum.py).
TransportQuery::IsBlackholed { hash } => RpcRequest::IsBlackholed {
identity_hash: hash.to_vec(),
},
@@ -2774,7 +2774,7 @@ fn transport_query_to_rpc_request(query: &TransportQuery) -> Option<crate::rpc::
} => RpcRequest::BlackholeIdentity {
identity_hash: hash.to_vec(),
until: ttl.map(|ttl| unix_now() + ttl),
// Reticulum.py:2196@1.6.0 forwards the caller's reason, None when unlabelled.
// Reticulum.py forwards the caller's reason, None when unlabelled.
reason: reason_label.clone().or_else(|| {
(*reason != rns_transport::blackhole::BlackholeReason::Manual)
.then(|| reason.as_str().to_string())
@@ -2980,7 +2980,7 @@ impl SharedInstanceType {
}
/// Python forces TCP wherever `platformutils.use_af_unix()` is false
/// (Reticulum.py:815-820): only Linux and Android have abstract sockets.
/// (Reticulum.py): only Linux and Android have abstract sockets.
fn on_this_platform(self) -> Self {
if cfg!(target_os = "linux") || rns_interface::local::is_android() {
self
@@ -3006,7 +3006,7 @@ pub struct InitOptions {
pub enforce_stamps: bool,
/// Embedder choice: an interface that fails to build or start is recorded
/// in [`ReticulumHandle::startup_interface_failures`] and the rest start.
/// Off, startup stops as upstream does (Reticulum.py:1306-1311).
/// Off, startup stops as upstream does (Reticulum.py).
pub keep_starting_after_interface_failure: bool,
}
@@ -3075,7 +3075,7 @@ async fn detect_shared_tcp_server(port: u16) -> bool {
.is_ok_and(|r| r.is_ok())
}
/// Binds without listening; upstream learns the same by binding its server (Reticulum.py:414-426).
/// Binds without listening; upstream learns the same by binding its server (Reticulum.py).
fn shared_tcp_port_is_free(port: u16) -> bool {
let Ok(socket) = tokio::net::TcpSocket::new_v4() else {
return false;
@@ -3088,7 +3088,7 @@ fn shared_tcp_port_is_free(port: u16) -> bool {
.is_ok()
}
/// Reticulum.py:458-463: an unreachable shared instance leaves this process standalone.
/// Reticulum.py: an unreachable shared instance leaves this process standalone.
fn shared_instance_unreachable(error: &dyn std::fmt::Display) -> InstanceMode {
tracing::error!("Local shared instance appears to be running, but it could not be connected");
tracing::error!("The contained exception was: {error}");
@@ -3435,7 +3435,7 @@ fn warn_deprecated_alias(alias: &str, key: &str) {
}
/// The aliases Python accepts for `autoconnect_interface_mode`; any other
/// value is ignored (Reticulum.py:715-728).
/// value is ignored (Reticulum.py).
fn parse_autoconnect_interface_mode(value: &str) -> Option<rns_interface::traits::InterfaceMode> {
use rns_interface::traits::InterfaceMode;
match value.to_lowercase().as_str() {
@@ -3635,7 +3635,7 @@ impl ReticulumConfig {
"required_discovery_value",
);
}
// Reticulum.py:674-677 keeps only a positive value; Discovery.py:495 defaults the rest.
// Reticulum.py keeps only a positive value; Discovery.py defaults the rest.
if let Some(v) = config_float("reticulum", sec, "required_discovery_value")?.or(
config_float("reticulum", sec, "discover_interfaces_required_value")?,
) {
@@ -3656,7 +3656,7 @@ impl ReticulumConfig {
if let Some(list) = sec.get_list("blackhole_sources") {
rc.blackhole_sources = parse_hash16_list("blackhole_sources", Some(list))?;
}
// Reticulum.py:593-596: float minutes, clamped to min 2, stored ×60.
// Reticulum.py: float minutes, clamped to min 2, stored ×60.
if let Some(v) = config_float("reticulum", sec, "blackhole_update_interval")? {
rc.blackhole_update_interval = v.max(2.0) * 60.0;
}
@@ -3666,7 +3666,7 @@ impl ReticulumConfig {
}
// Python promotes the identity while synthesizing a discoverable
// interface (Reticulum.py:1078-1083).
// interface (Reticulum.py).
if !rc.enable_transport
&& !rc.static_transport_identity
&& config
@@ -3693,7 +3693,7 @@ impl ReticulumConfig {
}
/// Apply constructor overrides after the configuration file, in Python's
/// order (Reticulum.py:349-362).
/// order (Reticulum.py).
pub fn apply_init_options(&mut self, options: &InitOptions) {
if options.enable_stamping {
tracing::debug!("Network stamp generation activated");
@@ -3715,14 +3715,14 @@ impl ReticulumConfig {
}
}
/// Python 1.3.8 Transport.py:234-238: the wire-facing transport identity is
/// Python 1.3.8 Transport.py: the wire-facing transport identity is
/// ephemeral per boot exactly when transport is disabled and
/// `static_transport_identity` is unset.
fn uses_ephemeral_transport_identity(rc: &ReticulumConfig) -> bool {
!rc.enable_transport && !rc.static_transport_identity
}
/// Python 1.3.8 Transport.py:240: per-boot random hop delta,
/// Python 1.3.8 Transport.py: per-boot random hop delta,
/// `(ord(os.urandom(1)) % 6) + 2` = 2..=7.
fn generate_local_hops_delta() -> u8 {
(rns_crypto::random::random_bytes(1)[0] % 6) + 2
@@ -3850,12 +3850,12 @@ pub async fn init_with_policy(
let announce_dispatch = actor.announce_dispatch_handle();
actor.is_foreground = is_foreground.clone();
actor.initialize_storage(paths.storage_dir.clone());
// Python 1.3.8 Transport.py:234-238: non-transport nodes get a fresh
// Python 1.3.8 Transport.py: non-transport nodes get a fresh
// per-boot wire-facing transport identity unless static_transport_identity
// is set. Pre-seed the actor's hash so runtime-side wire consumers
// (discovery announcer, blackhole publisher/subscriber) share the value.
actor.static_transport_identity = rc.static_transport_identity;
// Python 1.3.8 Transport.py:240: one random 2..=7 delta per boot;
// Python 1.3.8 Transport.py: one random 2..=7 delta per boot;
// should_apply_delta gates actual application.
if rc.local_hops_delta {
actor.local_hops_delta = generate_local_hops_delta();
@@ -3943,7 +3943,7 @@ pub async fn init_with_policy(
});
// Python defaults the local shared-instance RPC key to a hash of the
// PERSISTENT transport identity (internal_identity(), Reticulum.py:352),
// PERSISTENT transport identity (internal_identity(), Reticulum.py),
// so RPC auth stays stable across the per-boot ephemeral rotation.
if rc.rpc_key.is_none()
&& let Some(private_key) = transport_identity.get_private_key()
@@ -4342,7 +4342,7 @@ pub async fn init_with_policy(
.into());
}
// Reticulum.py:423-426, 465-466: only becoming the shared instance fails the requirement.
// Reticulum.py: only becoming the shared instance fails the requirement.
if options.require_shared_instance
&& (would_own_shared_instance || instance_mode == InstanceMode::Shared)
{
@@ -4573,7 +4573,7 @@ pub async fn init_with_policy(
}
}
// Python announces an I2P interface itself, never its
// peers (Discovery.py:112); without a server the
// peers (Discovery.py); without a server the
// first peer stands in.
let announced = match iface_config {
interface_factory::InterfaceConfig::I2P(_) => {
@@ -4598,7 +4598,7 @@ pub async fn init_with_policy(
);
}
// Python never detaches an I2PInterface
// (Reticulum.py:809).
// (Reticulum.py).
if bootstrap_only
&& !matches!(
iface_config,
@@ -4780,7 +4780,7 @@ pub async fn init_with_policy(
}
// Python serves remote management on Transport.identity
// (Transport.py:367-368), the hash `rnstatus -R` and `rnpath -R` take.
// (Transport.py), the hash `rnstatus -R` and `rnpath -R` take.
match crate::remote_management::start_remote_management_with_stats(
transport_tx.clone(),
&handle.transport_identity,
@@ -4812,7 +4812,7 @@ pub async fn init_with_policy(
management_announces.extend(start_network_destinations(&transport_tx, network_identity));
}
// Transport.py:534,645-650@1.6.0: only a transport instance has a probe destination,
// Transport.py: only a transport instance has a probe destination,
// and it is built on Transport.identity.
if instance_mode != InstanceMode::Client && rc.enable_transport && rc.respond_to_probes {
match crate::probe::spawn_announced_probe_responder(
@@ -4873,7 +4873,7 @@ async fn run_accepted_child_registration_pump(
};
let (role, ingress_overrides, ifac_key, ifac_size) =
child_registration_from_parent(&interface_controls, sub_handle.parent_id);
// LocalInterface.py:429,455@1.6.0: a spawned client copies the bitrate, not the MTU.
// LocalInterface.py: a spawned client copies the bitrate, not the MTU.
if role == rns_transport::messages::InterfaceRole::LocalClient
&& let Some(bitrate) = forced_shared_bitrate.filter(|bitrate| *bitrate > 0)
{
@@ -5043,9 +5043,9 @@ enum InterfaceFailureWatch {
RNode(rns_interface::rnode::RNodeDriverSubscription),
#[cfg(feature = "serial")]
RNodeMulti(rns_interface::rnode_multi::RNodeMultiFailures),
/// TCP or Backbone client teardown (TCPInterface.py:437-442).
/// TCP or Backbone client teardown (TCPInterface.py).
ClientTeardown(rns_interface::tcp::ClientTeardown),
/// Serial, KISS or AX.25 KISS runtime port error (SerialInterface.py:203-210).
/// Serial, KISS or AX.25 KISS runtime port error (SerialInterface.py).
#[cfg(feature = "serial")]
Serial(rns_interface::serial::SerialFailures),
}
@@ -5235,7 +5235,7 @@ fn apply_forced_shared_instance_bitrate(
handle.bitrate = bitrate;
handle.mtu =
rns_interface::traits::optimise_mtu(bitrate).unwrap_or(rns_wire::constants::MTU as u32);
// HDLC.py ReceiveBuffer and Transport.py:2014@1.6.0 bound frames by the optimised HW_MTU.
// HDLC.py ReceiveBuffer and Transport.py bound frames by the optimised HW_MTU.
handle.packet_capacity = rns_transport::messages::InterfacePacketCapacity::new(
handle.mtu,
handle.mtu,
@@ -5273,7 +5273,7 @@ async fn adopt_shared_instance_client(
role: rns_transport::messages::InterfaceRole::SharedInstancePeer,
ingress_overrides: rns_transport::ingress::IngressOverrides::default(),
ifac_key: None,
// LocalInterface.py:66@1.6.0 bounds frames at HW_MTU + DEFAULT_IFAC_SIZE.
// LocalInterface.py bounds frames at HW_MTU + DEFAULT_IFAC_SIZE.
ifac_size: rns_interface::tcp::DEFAULT_IFAC_SIZE,
kind: InterfaceKind::Standard,
multipoint: false,
@@ -5945,14 +5945,14 @@ async fn register_owned_interface_with_post_init(
.map(|_| ())
}
/// Python's configured `bitrate`, which counts from `MINIMUM_BITRATE` (Reticulum.py:1018-1020).
/// Python's configured `bitrate`, which counts from `MINIMUM_BITRATE` (Reticulum.py).
fn configured_bitrate(post_init: &interface_factory::InterfacePostInit) -> Option<u64> {
post_init
.bitrate
.filter(|bitrate| *bitrate >= MINIMUM_BITRATE)
}
/// Python's post-init `optimise_mtu` after a configured bitrate (Reticulum.py:1127-1128),
/// Python's post-init `optimise_mtu` after a configured bitrate (Reticulum.py),
/// for the interface classes with `AUTOCONFIGURE_MTU`.
fn apply_configured_bitrate_mtu(
iface_config: &interface_factory::InterfaceConfig,
@@ -6000,7 +6000,7 @@ fn clone_interface_post_init(
}
/// Python's I2P key file for an interface: the old name when that file
/// exists, else one bound to the transport identity (I2PInterface.py:229-238).
/// exists, else one bound to the transport identity (I2PInterface.py).
fn i2p_key_path(storage_dir: &Path, name: &str, transport_identity_hash: &[u8; 16]) -> PathBuf {
let dir = storage_dir.join("i2p");
let name_hash = rns_crypto::sha::sha256(name.as_bytes());
@@ -7142,7 +7142,7 @@ fn interface_config_mode_mut(
}
}
/// Python Reticulum.py:841-848: a `discoverable` interface must run in
/// Python Reticulum.py: a `discoverable` interface must run in
/// Gateway, Internal, or Access Point mode for discovery to be useful, so
/// other modes are auto-corrected (AP for RNode radios, Gateway otherwise)
/// with a notice.
@@ -7228,7 +7228,7 @@ fn discovery_config_for_interface(
};
let iface_name = interface_config_name(iface_config);
// Upstream parses these only for a discoverable interface, and a bad value
// stops startup (Reticulum.py:1077-1106@1.6.0).
// stops startup (Reticulum.py).
let key_error = |key: &str, what: &str| {
invalid_config_value(&format!("interfaces.{iface_name}"), key, what)
};
@@ -7265,12 +7265,12 @@ fn discovery_config_for_interface(
None,
),
// Python announces a KISS-framed TCP client as a KISS interface
// (Discovery.py:230-234).
// (Discovery.py).
interface_factory::InterfaceConfig::TcpClient(c) if c.kiss_framing => {
("KISSInterface", None, None, None, None, None, None)
}
// A target host makes a BackboneClientInterface, which Python never
// announces (Reticulum.py:1120-1122, BackboneInterface.py:154).
// announces (Reticulum.py, BackboneInterface.py).
interface_factory::InterfaceConfig::Backbone(c) if c.target_host.is_some() => {
return Ok(None);
}
@@ -7287,7 +7287,7 @@ fn discovery_config_for_interface(
None,
),
// The server announces its own b32 once SAM assigns it
// (Discovery.py:215-216).
// (Discovery.py).
interface_factory::InterfaceConfig::I2P(_) => {
("I2PInterface", None, None, None, None, None, None)
}
@@ -7333,7 +7333,7 @@ fn discovery_config_for_interface(
}
address
});
// Only KISS announces the discovery_* radio keys; RNode sends its own (Discovery.py:216-232).
// Only KISS announces the discovery_* radio keys; RNode sends its own (Discovery.py).
let discovery_frequency = uint_key("discovery_frequency")?;
let discovery_bandwidth = uint_key("discovery_bandwidth")?;
let (frequency, bandwidth) = if interface_type == "KISSInterface" {
@@ -7380,7 +7380,7 @@ fn discovery_config_for_interface(
}))
}
/// Upstream's announcer `sanitize`: drop CR and LF, then strip (Discovery.py:123-128).
/// Upstream's announcer `sanitize`: drop CR and LF, then strip (Discovery.py).
fn sanitize_discovery_value(value: &str) -> String {
value.replace(['\n', '\r'], "").trim().to_string()
}
@@ -7394,7 +7394,7 @@ fn hex_to_16(hex: &str) -> Option<[u8; 16]> {
}
/// Python reads `discovery_stamp_value` with `as_float` and generates at 16
/// when it is unset or 0 (Reticulum.py:1090, Discovery.py:134).
/// when it is unset or 0 (Reticulum.py, Discovery.py).
fn discovery_stamp_value(
float_key: &dyn Fn(&str) -> Result<Option<f64>, ConfigError>,
) -> Result<f64, ConfigError> {
@@ -7409,7 +7409,7 @@ fn discovery_stamp_value(
}
/// Upstream announces only an IP address or hostname and logs an error for
/// anything else (Discovery.py:203-206@1.6.0).
/// anything else (Discovery.py).
fn configured_reachable_on(section: &ConfigSection) -> Option<String> {
let reachable_on = sanitize_discovery_value(section.get("reachable_on")?);
if rns_transport::discovery::address::is_valid_address(&reachable_on) == Some(true) {
@@ -7424,7 +7424,7 @@ fn configured_reachable_on(section: &ConfigSection) -> Option<String> {
}
/// Python announces a server only with a configured `reachable_on`, and logs
/// an error at each announce it skips (Discovery.py:120, :186-188).
/// an error at each announce it skips (Discovery.py).
fn server_reachable_on(
section: &ConfigSection,
iface_config: &interface_factory::InterfaceConfig,
@@ -7449,7 +7449,7 @@ fn discovery_announce_interval_secs(
if let Some(minutes) = section.get_float("discovery_announce_interval") {
return Ok((minutes.max(0.0) * 60.0).round().max(1.0) as u64);
}
// Upstream: whole minutes, at least five, six hours when unset (Reticulum.py:1085-1089).
// Upstream: whole minutes, at least five, six hours when unset (Reticulum.py).
match section.get("announce_interval") {
None => Ok(6 * 60 * 60),
Some(value) => value
@@ -7665,7 +7665,7 @@ async fn run_discovery_publisher(
crate::destination_stamper::load_stored_stamp(&mut discovery_destination, announce_identity);
let mut discovery_stamps = crate::destination_stamper::DestinationStamps::<()>::new();
let mut registered: HashMap<u64, Option<String>> = HashMap::new();
// Python's last_discovery_announce and job sleep (Discovery.py:103-119).
// Python's last_discovery_announce and job sleep (Discovery.py).
let mut last_announce: HashMap<u64, tokio::time::Instant> = HashMap::new();
let mut next_prepare = tokio::time::Instant::now()
+ Duration::from_secs(rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS);
@@ -7679,7 +7679,7 @@ async fn run_discovery_publisher(
_ = handle.transport_tx.closed() => break,
_ = tick.tick() => {}
}
// Python walks the live interface list on every pass (Discovery.py:108).
// Python walks the live interface list on every pass (Discovery.py).
let locals = handle.discovery.local_interfaces.lock().await.clone();
publications.retain(|id, _| locals.iter().any(|local| local.id == *id));
if let Some(announcer) = announcer.as_mut() {
@@ -7944,7 +7944,7 @@ async fn run_discovery_publisher(
/// Evaluate executable `reachable_on` and `location_cmd` values and validate
/// the address before an announce, as Python does; `None` aborts this
/// announce (Discovery.py:136-207).
/// announce (Discovery.py).
async fn resolve_discovery_inputs(
mut config: DiscoveryInterfaceConfig,
location_cmd: Option<&str>,
@@ -8005,7 +8005,7 @@ async fn resolve_discovery_inputs(
}
/// Python's `lat,lon,height` checks for `location_cmd` output
/// (Discovery.py:146-155).
/// (Discovery.py).
// Plain comparisons let NaN through, as upstream's do.
#[allow(clippy::manual_range_contains)]
fn parse_discovery_location(output: &str) -> Result<(f64, f64, f64), String> {
@@ -8051,12 +8051,12 @@ async fn run_discovery_command(path: &Path) -> Result<String, String> {
Ok(stdout)
}
/// Python's `is_ip_address` (Discovery.py:982-986).
/// Python's `is_ip_address` (Discovery.py).
fn is_ip_address(value: &str) -> bool {
value.parse::<std::net::IpAddr>().is_ok()
}
/// Python's `is_hostname` (Discovery.py:1001-1007).
/// Python's `is_hostname` (Discovery.py).
fn is_hostname(hostname: &str) -> bool {
let hostname = hostname.strip_suffix('.').unwrap_or(hostname);
if hostname.len() > 253 {
@@ -8076,7 +8076,7 @@ fn is_hostname(hostname: &str) -> bool {
})
}
/// Python's `connect_discovered` (Discovery.py:732-743): one pass over the
/// Python's `connect_discovered` (Discovery.py): one pass over the
/// stored transport records, then each new discovery.
async fn run_discovery_autoconnect(
handle: ReticulumHandle,
@@ -8154,7 +8154,7 @@ async fn maybe_autoconnect_discovered(handle: &ReticulumHandle, record: Discover
if discovered_endpoint_exists(handle, &host, port).await {
return;
}
// Python's `endpoint_hash` (Discovery.py:747-752).
// Python's `endpoint_hash` (Discovery.py).
let key = rns_crypto::sha::sha256(format!("{host}:{port}").as_bytes());
{
let mut connected = handle.discovery.autoconnected.lock().await;
@@ -8200,7 +8200,7 @@ async fn maybe_autoconnect_discovered(handle: &ReticulumHandle, record: Discover
/// Python auto-connects only Backbone interfaces of a transport node running
/// a trusted stack and release, unless unverified stacks are allowed; the
/// transport requirement holds either way (Discovery.py:780-802).
/// transport requirement holds either way (Discovery.py).
fn autoconnect_admits(record: &DiscoveredInterface, config: &ReticulumConfig) -> bool {
let admitted = rns_transport::discovery::autoconnect::qualifies(
&record.info,
@@ -8227,7 +8227,7 @@ fn discovered_ifac_value(value: &Option<String>) -> Option<String> {
}
/// Python refuses an interface whose advertised costs exceed the stamp values
/// this node generates (Discovery.py:804-813).
/// this node generates (Discovery.py).
fn autoconnect_costs_acceptable(
record: &DiscoveredInterface,
stamps: &rns_transport::stamps::StampPolicy,
@@ -8252,7 +8252,7 @@ fn autoconnect_costs_acceptable(
dst_cost <= dst_value && pr_cost <= pr_value
}
/// Python's `autoconnect_interface_name` (Discovery.py:771-779).
/// Python's `autoconnect_interface_name` (Discovery.py).
async fn autoconnect_interface_name(handle: &ReticulumHandle, name: &str) -> String {
let names: std::collections::HashSet<String> = match handle
.query_transport(TransportQuery::GetInterfaceStats)
@@ -8294,7 +8294,7 @@ async fn spawn_discovered_backbone_client(
config.tunnel_identity = Some(rns_interface::traits::TunnelIdentity(
handle.transport_identity.clone(),
));
// Discovery.py:884 adds the interface with configured_bitrate=5E6.
// Discovery.py adds the interface with configured_bitrate=5E6.
config.bitrate = 5_000_000;
let spawned = rns_interface::backbone::spawn_backbone_client_observed(
config,
@@ -8311,11 +8311,11 @@ async fn spawn_discovered_backbone_client(
.expect("empty interface defaults are valid")
.with_default_ifac_size(16);
finalize_post_init(&mut post_init, &handle.config);
// Python's `configured_bitrate=5E6` (Discovery.py:884).
// Python's `configured_bitrate=5E6` (Discovery.py).
post_init.bitrate = Some(5_000_000);
// Discovery.py:881: autoconnect_interface_gravity, else AC_GRAVITY (0).
// Discovery.py: autoconnect_interface_gravity, else AC_GRAVITY (0).
post_init.gravity = Some(handle.config.autoconnect_interface_gravity.unwrap_or(0));
// Discovery.py:880: True when configured, otherwise None.
// Discovery.py: True when configured, otherwise None.
post_init.announces_to_internal = handle.config.autoconnect_announces_to_internal;
post_init.ifac_network_name = discovered_ifac_value(&record.info.ifac_netname);
post_init.ifac_passphrase =
@@ -8342,7 +8342,7 @@ async fn spawn_discovered_backbone_client(
Ok((id, online))
}
/// Python's `__monitor_job` (Discovery.py:659-718): detach interfaces that
/// Python's `__monitor_job` (Discovery.py): detach interfaces that
/// stay down, forget ones detached elsewhere, trade bootstrap interfaces for
/// online auto-connected ones and refill free slots.
async fn run_autoconnect_monitor(handle: ReticulumHandle) {
@@ -8360,7 +8360,7 @@ async fn run_autoconnect_monitor(handle: ReticulumHandle) {
}
async fn autoconnect_monitor_tick(handle: &ReticulumHandle) {
// Upstream DETACH_THRESHOLD is in seconds (Discovery.py:476, :684).
// Upstream DETACH_THRESHOLD is in seconds (Discovery.py).
let threshold = Duration::from_secs(rns_transport::discovery::DETACH_THRESHOLD_TICKS);
let limit = handle.config.autoconnect_discovered_interfaces;
let registered: std::collections::HashSet<u64> = handle
@@ -8489,7 +8489,7 @@ fn autoconnect_from_monitor(
}
/// Python re-synthesizes every bootstrap-only interface config once no
/// auto-connected interface is online (Discovery.py:701-705).
/// auto-connected interface is online (Discovery.py).
async fn respawn_bootstrap_interfaces(handle: &ReticulumHandle) {
let configs: Vec<(
interface_factory::InterfaceConfig,
@@ -8660,7 +8660,7 @@ async fn attach_interface_section(
);
}
let ids: Vec<u64> = spawned.into_iter().map(|(id, _, _)| id).collect();
// Python never detaches an I2PInterface (Reticulum.py:888).
// Python never detaches an I2PInterface (Reticulum.py).
if interface_bootstrap_only(config, &iface_config)
&& !matches!(iface_config, interface_factory::InterfaceConfig::I2P(_))
{
@@ -8674,7 +8674,7 @@ async fn attach_interface_section(
Ok(ids)
}
/// Python's `interface_exists` (Discovery.py:754-770): a client interface
/// Python's `interface_exists` (Discovery.py): a client interface
/// already aimed at this host and port, or an I2P interface at this address.
async fn discovered_endpoint_exists(handle: &ReticulumHandle, host: &str, port: u16) -> bool {
let aimed = handle
@@ -8702,7 +8702,7 @@ async fn discovered_endpoint_exists(handle: &ReticulumHandle, host: &str, port:
}
/// Python never auto-connects to an onion address, nor to the literal
/// addresses 127.0.0.1 and 0.0.0.0 (Discovery.py:814-825, :978-985).
/// addresses 127.0.0.1 and 0.0.0.0 (Discovery.py).
fn refused_autoconnect_host(host: &str) -> bool {
host.to_lowercase().ends_with(".onion") || ["127.0.0.1", "0.0.0.0"].contains(&host)
}
@@ -8795,7 +8795,7 @@ async fn start_blackhole_publisher(
}
});
// Transport.py:495@1.6.0.
// Transport.py
if let Some(destination) = lm.destination_mut() {
destination.set_link_cost(BLACKHOLE_LINK_COST);
}
@@ -8812,10 +8812,10 @@ async fn start_blackhole_publisher(
Ok((dest_hash, announce))
}
/// Interval between management announces (Transport.py:359@1.6.0).
/// Interval between management announces (Transport.py).
const MGMT_ANNOUNCE_INTERVAL: Duration =
Duration::from_secs(rns_transport::constants::MGMT_ANNOUNCE_INTERVAL as u64);
/// Delay before the first management announce (Transport.py:522-523@1.6.0).
/// Delay before the first management announce (Transport.py).
const MGMT_ANNOUNCE_FIRST_DELAY: Duration = Duration::from_secs(15);
/// Asks one of the transport's management destinations to announce itself.
@@ -8873,7 +8873,7 @@ pub(crate) fn register_management_destination(
}
/// The `rnstransport.network.instance.<hash>` and `rnstransport.network`
/// destinations on the network identity (Transport.py:501-507@1.6.0).
/// destinations on the network identity (Transport.py).
fn start_network_destinations(
transport_tx: &mpsc::Sender<TransportMessage>,
network_identity: &Identity,
@@ -8904,7 +8904,7 @@ fn start_network_destinations(
}
/// Announce every management destination 15 s after start and then every
/// two hours (Transport.py:1359-1368@1.6.0).
/// two hours (Transport.py).
async fn run_management_announcer(destinations: Vec<ManagementAnnounce>, shutdown: ShutdownSignal) {
let mut wait = MGMT_ANNOUNCE_FIRST_DELAY;
loop {
@@ -8926,7 +8926,7 @@ async fn start_blackhole_subscriber(handle: ReticulumHandle) {
}
*started = true;
drop(started);
// BlackholeUpdater.start registers its announce type (Discovery.py:908).
// BlackholeUpdater.start registers its announce type (Discovery.py).
handle
.wants_destination_type("rnstransport.info.blackhole")
.await;
@@ -8966,7 +8966,7 @@ async fn start_blackhole_subscriber(handle: ReticulumHandle) {
rns_transport::discovery::BLACKHOLE_ASPECT_FILTER,
Some(&source_hash),
);
// Discovery.py:964-971: without a path, retry on the next job
// Discovery.py: without a path, retry on the next job
// run; once a path exists the source waits a full interval.
if handle
.await_path(
@@ -9075,7 +9075,7 @@ fn ensure_runtime_interface_admission(
.map_err(|_| "runtime is shutting down; interface spawn rejected".to_string())
}
/// Any initiator that gives up panics the instance (TCPInterface.py:435-442).
/// Any initiator that gives up panics the instance (TCPInterface.py).
fn watch_runtime_client_teardown(
handle: &ReticulumHandle,
name: &str,
@@ -10540,7 +10540,7 @@ async fn spawn_interface_with_rnode_startup_options(
));
}
// Python runs the server and one peer interface per configured
// peer, each named "<name> to <peer>" (I2PInterface.py:793-819).
// peer, each named "<name> to <peer>" (I2PInterface.py).
let mut handles = Vec::new();
let mut next = Some(id);
if c.connectable {
@@ -10797,7 +10797,7 @@ fn load_or_create_network_identity(path: &Path) -> Result<Arc<Identity>, Reticul
}
/// A section that fails to build stops startup whatever
/// `panic_on_interface_error` says (Reticulum.py:1307-1311); an unknown type
/// `panic_on_interface_error` says (Reticulum.py); an unknown type
/// is only logged, as upstream does for a missing external module. With
/// `failures`, a failed section is recorded there and the rest are built.
fn synthesize_interfaces(
@@ -13081,7 +13081,7 @@ loglevel = 7
assert_eq!(rc.shared_instance_type, SharedInstanceType::Tcp);
}
/// Python Reticulum.py:815-820: Unix sockets serve the shared instance
/// Python Reticulum.py: Unix sockets serve the shared instance
/// only where `platformutils.use_af_unix()` holds, whatever was requested.
fn python_unix_request() -> SharedInstanceType {
if cfg!(target_os = "linux") || rns_interface::local::is_android() {
@@ -14545,7 +14545,7 @@ loglevel = 7
}
/// An interface announces the address it learns at runtime
/// (Discovery.py:215-216); a later change waits for the interval instead
/// (Discovery.py); a later change waits for the interval instead
/// of announcing at once, so a flapping address cannot flood announces.
#[tokio::test(start_paused = true)]
async fn discovery_publisher_announces_a_learned_address_on_its_interval() {
@@ -15008,9 +15008,9 @@ loglevel = 7
}
}
/// Python reads only `reachable_on` (Reticulum.py:999), and a Backbone
/// Python reads only `reachable_on` (Reticulum.py), and a Backbone
/// client is a `BackboneClientInterface`, which never supports discovery
/// (Reticulum.py:1120-1122, Discovery.py:77-78, BackboneInterface.py:154).
/// (Reticulum.py, Discovery.py, BackboneInterface.py).
#[test]
fn network_discovery_uses_the_configured_reachable_on() {
let discovery = |endpoint: &str, key: &str| {
@@ -15076,7 +15076,7 @@ loglevel = 7
/// Upstream sends a nil name without `discovery_name`, announces only a
/// valid `reachable_on`, and fails startup on a discovery key it cannot
/// parse (Reticulum.py:1077-1106, Discovery.py:173, :203-206@1.6.0).
/// parse (Reticulum.py, Discovery.py).
#[test]
fn discovery_keys_parse_like_upstream() {
let discovery = |extra: &str| {
@@ -15125,7 +15125,7 @@ loglevel = 7
}
/// Python announces a KISS-framed TCP client as a KISS interface with its
/// discovery radio parameters and no address (Discovery.py:182-185, :230-234).
/// discovery radio parameters and no address (Discovery.py).
#[test]
fn a_kiss_framed_tcp_client_is_discovered_as_a_kiss_interface() {
let config = Config::parse("[interfaces]\n[[kiss tnc]]\ntype = TCPClientInterface\nenabled = yes\nkiss_framing = yes\ntarget_host = 10.0.0.2\ntarget_port = 8001\ndiscoverable = yes\ndiscovery_frequency = 433775000\ndiscovery_modulation = 2\ndiscovery_spreading_factor = 7\ndiscovery_coding_rate = 5\ndiscovery_channel = 3\nreachable_on = 10.0.0.2\n").unwrap();
@@ -15157,7 +15157,7 @@ loglevel = 7
);
}
/// Serial KISS/AX.25 never announce; RNode announces its own radio, no address (Interface.py:118).
/// Serial KISS/AX.25 never announce; RNode announces its own radio, no address (Interface.py).
#[cfg(feature = "serial")]
#[test]
fn only_upstream_discoverable_radio_types_announce() {
@@ -15238,7 +15238,7 @@ loglevel = 7
assert_eq!(h.blackhole_sources()[0], [0xAA; 16]);
}
/// Python's `autoconnect_unverified_implementations` (Reticulum.py:632-634).
/// Python's `autoconnect_unverified_implementations` (Reticulum.py).
#[test]
fn autoconnect_unverified_implementations_is_parsed_and_off_by_default() {
assert!(!ReticulumConfig::default().autoconnect_unverified_implementations);
@@ -15249,7 +15249,7 @@ loglevel = 7
}
/// Only Backbone interfaces from Python 1.5.7 or later, unless unverified
/// stacks are allowed (Discovery.py:782-798).
/// stacks are allowed (Discovery.py).
#[test]
fn discovered_interfaces_auto_connect_like_python() {
let record = |interface_type: &str, impl_name: Option<&str>, version: Option<&str>| {
@@ -15381,7 +15381,7 @@ loglevel = 7
assert_eq!(rc.ingress_overrides.held_release_interval, Some(3.5));
}
/// Python Reticulum.py:841-848 parity: discoverable interfaces are
/// Python Reticulum.py parity: discoverable interfaces are
/// auto-corrected to Gateway/AP mode unless already Internal or
/// `ignore_config_warnings` is enabled.
#[test]
@@ -15488,7 +15488,7 @@ egress_control = Yes
assert!(rc.static_transport_identity);
assert!(!uses_ephemeral_transport_identity(&rc));
// Python Transport.py:234-238: transport nodes never rotate.
// Python Transport.py: transport nodes never rotate.
let rc = ReticulumConfig::from_config(
&Config::parse("[reticulum]\nenable_transport = yes\n").unwrap(),
);
@@ -15516,7 +15516,7 @@ egress_control = Yes
#[test]
fn local_hops_delta_value_stays_in_python_range() {
// Python Transport.py:240: (rand_byte % 6) + 2 = 2..=7.
// Python Transport.py: (rand_byte % 6) + 2 = 2..=7.
for _ in 0..256 {
let delta = generate_local_hops_delta();
assert!((2..=7).contains(&delta), "delta {delta} out of range");
@@ -15528,7 +15528,7 @@ egress_control = Yes
let rc = ReticulumConfig::from_config(&Config::parse("[reticulum]\n").unwrap());
assert_eq!(rc.blackhole_update_interval, 3600.0);
// Reticulum.py:593-596: minutes ×60 into seconds.
// Reticulum.py: minutes ×60 into seconds.
let rc = ReticulumConfig::from_config(
&Config::parse("[reticulum]\nblackhole_update_interval = 30\n").unwrap(),
);
@@ -15583,7 +15583,7 @@ egress_control = Yes
#[test]
fn internal_interface_mode_parses_and_discovery_autocorrects() {
// Python 1.3.8 Reticulum.py:721,737-738: mode = internal → MODE_INTERNAL.
// Python 1.3.8 Reticulum.py: mode = internal → MODE_INTERNAL.
let base = "[interfaces]\n\n[[Test TCP]]\ntype = TCPClientInterface\nenabled = yes\n\
target_host = 127.0.0.1\ntarget_port = 4242\nmode = internal\n";
let config = Config::parse(base).unwrap();
@@ -15593,7 +15593,7 @@ egress_control = Yes
rns_interface::traits::InterfaceMode::Internal
);
// Reticulum.py:856-863 in RNS 1.4.0: Internal is a supported
// Reticulum.py in RNS 1.4.0: Internal is a supported
// discovery mode and must not be auto-corrected.
let config = Config::parse(&format!("{base}discoverable = yes\n")).unwrap();
let mut interfaces = synthesize_interfaces(&config, None).unwrap();
@@ -17835,7 +17835,7 @@ txpower = 17
let _ = std::fs::remove_dir_all(&dir);
}
/// TCPInterface.py:437-442: a client that spends its retry budget panics
/// TCPInterface.py: a client that spends its retry budget panics
/// the instance when `panic_on_interface_error` is set.
#[tokio::test]
async fn tcp_client_teardown_stops_the_runtime_when_panic_on_interface_error_is_set() {
@@ -17870,7 +17870,7 @@ txpower = 17
assert_eq!(handle.interface_panic(), Some("Unreachable"));
}
/// TCPInterface.py:435-442 / BackboneInterface.py:1088-1091: a client
/// TCPInterface.py / BackboneInterface.py: a client
/// added at runtime that gives up also panics the instance.
#[tokio::test]
async fn runtime_backbone_client_teardown_stops_the_runtime_when_panic_on_interface_error_is_set()
@@ -18007,7 +18007,7 @@ txpower = 17
(result, dir)
}
// Reticulum.py:435-466: neither bindable nor connectable means standalone, required or not.
// Reticulum.py: neither bindable nor connectable means standalone, required or not.
#[tokio::test]
async fn required_shared_instance_falls_back_to_standalone_when_unreachable() {
let holder = tokio::net::TcpSocket::new_v4().unwrap();
@@ -18030,7 +18030,7 @@ txpower = 17
let _ = std::fs::remove_dir_all(&dir);
}
// Reticulum.py:468-472: without sharing there is no shared instance to require.
// Reticulum.py: without sharing there is no shared instance to require.
#[tokio::test]
async fn required_shared_instance_is_not_enforced_without_sharing() {
let (result, dir) = init_requiring_shared_instance(
@@ -1,5 +1,5 @@
//! Auto-connecting discovered interfaces as Python's `InterfaceDiscovery`
//! does (Discovery.py:747-870).
//! does (Discovery.py).
use super::*;
use rns_transport::discovery::app_data::DiscoveryInfo;
@@ -69,7 +69,7 @@ fn hub_config(uplink_port: u16) -> String {
}
/// Python never auto-connects to an onion address, nor to the literal
/// addresses 127.0.0.1 and 0.0.0.0 (Discovery.py:814-825, :982).
/// addresses 127.0.0.1 and 0.0.0.0 (Discovery.py).
#[tokio::test]
async fn autoconnect_refuses_onion_and_local_addresses() {
let port = unused_port().await;
@@ -98,7 +98,7 @@ async fn autoconnect_refuses_onion_and_local_addresses() {
}
/// Python connects once per endpoint, and never beside a client interface
/// already aimed at it (`interface_exists`, Discovery.py:747-770), however
/// already aimed at it (`interface_exists`, Discovery.py), however
/// many announcers name the endpoint.
#[tokio::test]
async fn autoconnect_connects_once_per_endpoint() {
@@ -123,8 +123,8 @@ async fn autoconnect_connects_once_per_endpoint() {
}
/// Python names the network that announced an auto-connected interface in
/// its stats, as the announcer's identity hash in hex (Discovery.py:865,
/// Reticulum.py:1611-1612), and `rnstatus` prints it (rnstatus.py:525-526).
/// its stats, as the announcer's identity hash in hex (Discovery.py,
/// Reticulum.py), and `rnstatus` prints it (rnstatus.py).
#[tokio::test]
async fn an_autoconnected_interface_names_its_source() {
let (uplink_port, port) = (unused_port().await, unused_port().await);
@@ -289,7 +289,7 @@ async fn wait_names(
/// Python's monitor keeps bootstrap interfaces while no auto-connected
/// interface is online, detaches one that stays down for 12 s, and
/// re-enables bootstrap interfaces once none is attached
/// (Discovery.py:659-718).
/// (Discovery.py).
#[tokio::test(flavor = "multi_thread")]
async fn autoconnect_monitor_detaches_dead_interfaces_and_restores_bootstrap() {
let bootstrap_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -343,7 +343,7 @@ async fn autoconnect_monitor_detaches_dead_interfaces_and_restores_bootstrap() {
/// Python tears bootstrap interfaces down only once the target number of
/// auto-connected interfaces is online, and gives them `configured_bitrate`
/// 5 Mbit/s (Discovery.py:695-699, :884).
/// 5 Mbit/s (Discovery.py).
#[tokio::test(flavor = "multi_thread")]
async fn bootstrap_interfaces_yield_to_an_online_autoconnected_interface() {
let listeners = [
@@ -394,7 +394,7 @@ async fn bootstrap_interfaces_yield_to_an_online_autoconnected_interface() {
}
/// Python makes a non-transport instance with a discoverable interface keep
/// a static transport identity (Reticulum.py:1078-1083).
/// a static transport identity (Reticulum.py).
#[test]
fn a_discoverable_interface_makes_the_transport_identity_static() {
let parse =
@@ -413,7 +413,7 @@ fn a_discoverable_interface_makes_the_transport_identity_static() {
/// Python runs an executable `reachable_on` and announces its output only
/// when it is an address or hostname; otherwise the announce is skipped
/// (Discovery.py:183-207).
/// (Discovery.py).
#[cfg(unix)]
#[tokio::test]
async fn an_executable_reachable_on_is_evaluated_and_validated() {
@@ -22,9 +22,9 @@ async fn is_local_destination(handle: &ReticulumHandle, dest: [u8; 16]) -> bool
}
/// `rnstatus -R` and `rnpath -R` take the remote's transport identity hash
/// and derive `rnstransport.remote.management` from it (rnstatus.py:367-369),
/// and derive `rnstransport.remote.management` from it (rnstatus.py),
/// because Python registers that destination on `Transport.identity`
/// (Transport.py:367-368).
/// (Transport.py).
#[tokio::test]
async fn remote_management_answers_on_the_transport_identity() {
let dir = config_dir(
@@ -1,6 +1,6 @@
//! Attaching, detaching and reloading configured interfaces at run time, as
//! Python's `Reticulum._attach_interface`, `_detach_interface` and
//! `_reload_interface` do (Reticulum.py:850-920).
//! `_reload_interface` do (Reticulum.py).
use super::*;
fn config_dir(config: &str) -> PathBuf {
@@ -294,7 +294,7 @@ async fn an_i2p_interface_runs_its_server_and_every_peer() {
}
/// Python announces only the `I2PInterface` itself; its peers are not
/// discoverable (Interface.py:119, Discovery.py:112, :140). Rust has no
/// discoverable (Interface.py, Discovery.py). Rust has no
/// interface for a non-connectable server, so its first peer stands in.
#[tokio::test]
async fn a_discoverable_i2p_interface_announces_once() {
@@ -365,7 +365,7 @@ async fn own_b32(handle: &ReticulumHandle) -> String {
}
/// Python announces a connectable I2P interface at its own b32 address
/// (Discovery.py:215-216), never at a configured peer's.
/// (Discovery.py), never at a configured peer's.
#[tokio::test]
async fn a_connectable_i2p_interface_announces_its_own_b32() {
let (sam_port, _streams) = fake_sam(0).await;
@@ -395,7 +395,7 @@ async fn a_connectable_i2p_interface_announces_its_own_b32() {
/// Python keeps a connectable I2P interface's private key in `storage/i2p`,
/// in a file named for the interface and the transport identity, and reuses
/// it, so the interface keeps its address across restarts
/// (I2PInterface.py:225-255).
/// (I2PInterface.py).
#[tokio::test]
async fn a_connectable_i2p_interface_keeps_its_key_across_restarts() {
let (sam_port, _streams) = fake_sam(0).await;
@@ -435,7 +435,7 @@ async fn a_connectable_i2p_interface_keeps_its_key_across_restarts() {
let _ = std::fs::remove_dir_all(dir);
}
/// Python's key file for an I2P interface (I2PInterface.py:229-238).
/// Python's key file for an I2P interface (I2PInterface.py).
fn python_i2p_key_file(storage: &Path, name: &str, transport_identity_hash: &[u8; 16]) -> PathBuf {
let mut material = rns_crypto::sha::sha256(name.as_bytes()).to_vec();
material.extend_from_slice(&rns_crypto::sha::sha256(transport_identity_hash));
@@ -483,7 +483,7 @@ async fn an_unreadable_i2p_key_file_is_never_replaced() {
}
/// Python's configured peers take their interface's mode, announce and
/// ingress settings as well as its IFAC (I2PInterface.py:814-857).
/// ingress settings as well as its IFAC (I2PInterface.py).
#[tokio::test]
async fn configured_i2p_peers_inherit_their_interface_settings() {
let (sam_port, _streams) = fake_sam(0).await;
@@ -977,7 +977,7 @@ const FIRST_ATTEMPT_TIMEOUT_SECS: u64 = 1;
/// A failed connection attempt is an outage too: traffic queued while a
/// client's first attempts fail is dropped, so however much was queued the
/// synthesis opens the connection (Python drops traffic while offline,
/// TCPInterface.py:314-315).
/// TCPInterface.py).
async fn assert_failed_first_attempts_drop_their_backlog(tag: &str, port: u16, interface: &str) {
let dir = config_dir(
tag,
+12 -12
View File
@@ -137,7 +137,7 @@ pub struct RncpSendRequest<'a> {
/// One transfer progress update: the logical fraction, and the bytes of the
/// current segment moved on the link, `get_segment_progress() *
/// get_transfer_size()` as rncp's `-P` rate reads them (rncp.py:330-331).
/// get_transfer_size()` as rncp's `-P` rate reads them (rncp.py).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RncpProgress {
pub progress: f32,
@@ -182,7 +182,7 @@ pub enum RncpEvent {
}
/// The value a fetch handler answers with, and the status a fetch client
/// derives from it (rncp.py:172-208, 463-474).
/// derives from it (rncp.py).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FetchReply {
Found,
@@ -292,7 +292,7 @@ fn process_cwd() -> String {
}
/// The path a fetch request names, or `None` when it falls outside the jail
/// (rncp.py:177-185). `jail` is already absolute and normalised.
/// (rncp.py). `jail` is already absolute and normalised.
fn fetch_request_path(
jail: Option<&str>,
data: &str,
@@ -450,7 +450,7 @@ pub async fn spawn_rncp_listener(
Arc::new(cfg.allowed.iter().copied().collect());
let allow_all = cfg.allow_all;
// Every incoming link: ACCEPT_APP with the identity check (rncp.py:234-266).
// Every incoming link: ACCEPT_APP with the identity check (rncp.py).
let (identified_tx, mut identified_rx) = mpsc::channel::<([u8; 16], [u8; 16])>(64);
link_mgr.set_link_identified_channel(identified_tx);
link_mgr.set_resource_strategy(ResourceStrategy::AcceptApp);
@@ -584,7 +584,7 @@ pub async fn spawn_rncp_listener(
})
}
/// Upstream's `fetch_request` (rncp.py:172-208). The LinkManager has already
/// Upstream's `fetch_request` (rncp.py). The LinkManager has already
/// applied the ALLOW_ALL / ALLOW_LIST policy.
fn serve_fetch(
request: DestinationRequest,
@@ -662,7 +662,7 @@ async fn save_payload(
data: &[u8],
overwrite: bool,
) -> Result<PathBuf, String> {
// rncp.py:286-293: the basename must name an entry directly in save_dir.
// rncp.py: the basename must name an entry directly in save_dir.
let basename = basename(file_name).to_string();
if basename.is_empty() || basename == "." || basename == ".." {
return Err(format!("invalid save path for {file_name:?}"));
@@ -857,7 +857,7 @@ async fn query(
.map_err(|_| RncpError::TransportUnavailable)
}
/// Path wait, link request and identification (rncp.py:394-450, 651-706).
/// Path wait, link request and identification (rncp.py).
/// The path wait lasts `path_timeout`; the proof wait ends at the later of
/// that deadline and the link establishment timeout.
async fn establish(
@@ -875,7 +875,7 @@ async fn establish(
)
.await?;
// Link.py:308-309: first_hop_timeout + ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, hops).
// Link.py: first_hop_timeout + ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, hops).
let hops = match query(transport_tx, TransportQuery::HopsTo { dest: dest_hash }).await? {
TransportQueryResponse::IntResult(hops) => u8::try_from(hops.max(1)).unwrap_or(u8::MAX),
_ => 1,
@@ -1001,7 +1001,7 @@ async fn close_link<T>(
}
}
/// Run the initiator side of the link watchdog (Link.py:799-857): keepalives,
/// Run the initiator side of the link watchdog (Link.py): keepalives,
/// stale detection and request timeouts.
async fn service_link(
transport_tx: &mpsc::Sender<TransportMessage>,
@@ -1178,7 +1178,7 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
}
}
rns_wire::context::PacketContext::ResourcePrf => {
// PROOF+RESOURCE_PRF plaintext = resource_hash(32) || proof(32) (Packet.py:195-197).
// PROOF+RESOURCE_PRF plaintext = resource_hash(32) || proof(32) (Packet.py).
if body.len() < 64 {
continue;
}
@@ -1316,7 +1316,7 @@ async fn discover_pubkey(
})
.await
.map_err(|_| RncpError::TransportUnavailable)?;
// rncp.py:394-406: one path request, then poll has_path until the deadline.
// rncp.py: one path request, then poll has_path until the deadline.
let deadline = Instant::now() + path_wait;
loop {
if let TransportQueryResponse::BoolResult(true) =
@@ -1580,7 +1580,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
}
}
TransferAction::Failed(reason) => failed = Some(reason),
// Out of retries: Resource.cancel() sends RCL (Resource.py:1133-1139).
// Out of retries: Resource.cancel() sends RCL (Resource.py).
TransferAction::SendCancel(_, resource_hash) => {
if let Ok(encrypted) = link.encrypt(&resource_hash) {
let raw = build_data_packet(
+15 -15
View File
@@ -195,7 +195,7 @@ pub struct PathTableEntry {
pub hops: u8,
pub expires: f64,
/// Destination stamp value: `None` when the destination is unknown, 0 when
/// known but unstamped (Reticulum.py:1884-1885).
/// known but unstamped (Reticulum.py).
#[serde(default)]
pub value: Option<f64>,
/// Last use in Unix seconds; 0 when never used.
@@ -326,7 +326,7 @@ pub struct InterfaceStatEntry {
}
/// What a transport instance adds to its interface stats
/// (Reticulum.py:1700-1705).
/// (Reticulum.py).
#[derive(Debug, Clone, Copy)]
pub(crate) struct TransportStats {
pub(crate) transport_id: [u8; 16],
@@ -336,7 +336,7 @@ pub(crate) struct TransportStats {
}
/// Python's top-level traffic, packet, link and path counters
/// (Reticulum.py:1806-1852).
/// (Reticulum.py).
pub(crate) type TrafficTotals = rns_transport::messages::TrafficTotalsRpcEntry;
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -785,7 +785,7 @@ pub(crate) fn encode_optional_bool(value: Option<bool>) -> Result<Vec<u8>, RpcEr
encode_umsgpack(&value.map(PyValue::Bool).unwrap_or(PyValue::None))
}
/// A float, or integer 0 when the timeout is unknown (Transport.py:3552).
/// A float, or integer 0 when the timeout is unknown (Transport.py).
pub(crate) fn encode_medium_path_timeout(seconds: Option<f64>) -> Result<Vec<u8>, RpcError> {
encode_umsgpack(&seconds.map(PyValue::Float).unwrap_or(PyValue::Int(0)))
}
@@ -896,7 +896,7 @@ pub(crate) fn encode_interface_stats(
}
/// Remote management's `/status` answer: `[stats]`, then the link count and
/// nil profiling results when asked for, in that order (Transport.py:3325-3337).
/// nil profiling results when asked for, in that order (Transport.py).
pub(crate) fn encode_remote_status(
entries: &[InterfaceStatEntry],
transport: Option<&TransportStats>,
@@ -915,7 +915,7 @@ pub(crate) fn encode_remote_status(
encode_umsgpack(&PyValue::List(response))
}
/// The inbound queue keys of `get_interface_stats()` (Reticulum.py:1829-1843@1.6.0).
/// The inbound queue keys of `get_interface_stats()` (Reticulum.py).
fn queue_stats(q: &InboundQueueSnapshot) -> Vec<(&'static str, PyValue)> {
let int = |n: u64| PyValue::Int(i128::from(n));
let height = |n: usize| int(n as u64);
@@ -949,7 +949,7 @@ fn queue_stats(q: &InboundQueueSnapshot) -> Vec<(&'static str, PyValue)> {
]
}
/// `Reticulum.get_interface_stats()` (Reticulum.py:1619-1852@1.6.0) for the
/// `Reticulum.get_interface_stats()` (Reticulum.py) for the
/// control port and remote management alike.
fn interface_stats_value(
entries: &[InterfaceStatEntry],
@@ -965,7 +965,7 @@ fn interface_stats_value(
Some(t) => {
let int = |value: u64| PyValue::Int(i128::from(value));
// Python's speeds become floats once an interface is measured, and
// its frequency sums once a frequency is (Transport.py:746-813).
// its frequency sums once a frequency is (Transport.py).
let speed = |value: f64| {
if t.measured {
PyValue::Float(value)
@@ -1065,7 +1065,7 @@ fn interface_stat_value(e: &InterfaceStatEntry) -> PyValue {
let int = |value: u64| PyValue::Int(i128::from(value));
let optional = |value: Option<PyValue>| value.unwrap_or(PyValue::None);
// Python's `current_*_speed` are unset (reported as 0) until the first
// traffic count, and floats after it (Reticulum.py:1696-1724).
// traffic count, and floats after it (Reticulum.py).
let speed = |index: usize, fallback: u64| match e.speeds {
Some(speeds) => PyValue::Float(speeds[index]),
None => int(fallback),
@@ -1698,7 +1698,7 @@ fn i64_from_i128(v: i128) -> Result<i64, RpcError> {
i64::try_from(v).map_err(|_| RpcError::Deserialize(format!("integer out of range: {v}")))
}
/// Python `Interface.MODE_*` (Interface.py:45-51) for a Debug-formatted mode.
/// Python `Interface.MODE_*` (Interface.py) for a Debug-formatted mode.
fn python_interface_mode(mode: &str) -> u8 {
match mode {
"Full" => 0x01,
@@ -2318,7 +2318,7 @@ pub async fn connect_unix_and_request_bytes(
}
/// Python's top-level byte totals and packet rates in an `interface_stats`
/// answer (Reticulum.py:1806-1825).
/// answer (Reticulum.py).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InterfaceStatsTotals {
pub rxb: u64,
@@ -2466,7 +2466,7 @@ pub enum RpcError {
}
/// Keys Python 1.5.5 `get_interface_stats()` gives every interface
/// (Reticulum.py:1501-1663); `rnstatus` indexes most of them unguarded.
/// (Reticulum.py); `rnstatus` indexes most of them unguarded.
#[cfg(test)]
pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
"clients",
@@ -2523,7 +2523,7 @@ pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
"packet_filter_hits",
];
/// Totals in every Python 1.5.5 stats dict (Reticulum.py:1673-1714).
/// Totals in every Python 1.5.5 stats dict (Reticulum.py).
#[cfg(test)]
pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
"interfaces",
@@ -2564,7 +2564,7 @@ pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
"rss",
];
/// Added only by a transport instance (Reticulum.py:1700-1705).
/// Added only by a transport instance (Reticulum.py).
#[cfg(test)]
pub(crate) const PYTHON_TRANSPORT_KEYS: &[&str] = &[
"transport_id",
@@ -3218,7 +3218,7 @@ mod tests {
const FX_REQ_DESTINATION_DATA_USED: &str = "82b064657374696e6174696f6e5f64617461a475736564b064657374696e6174696f6e5f68617368c410cccccccccccccccccccccccccccccccc";
const FX_REQ_IDENTITY_DATA_RETAIN: &str = "82ad6964656e746974795f64617461a672657461696ead6964656e746974795f68617368c410dddddddddddddddddddddddddddddddd";
// Path-table replies: RNS 1.6.0 umsgpack over the dict get_path_table builds
// (Reticulum.py:1887-1891), unknown and stamped destinations.
// (Reticulum.py), unknown and stamped destinations.
const FX_RESP_PATH_TABLE: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565c0a47573656400a76c725f636f7374c0a9696e74657266616365b2544350496e746572666163655b746573745d";
const FX_RESP_PATH_TABLE_STAMPED: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565cb4018500000000000a475736564cb41d26580cfe00000a76c725f636f7374cb400a000000000000a9696e74657266616365b2544350496e746572666163655b746573745d";
const FX_RESP_BLACKHOLE_DICT: &str = "81c4104242424242424242424242424242424283a6736f75726365c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa5756e74696ccb4093480000000000a6726561736f6ea6706172697479";
+7 -7
View File
@@ -158,7 +158,7 @@ pub(crate) fn stat_entries(
i2p_connectable: e.i2p_connectable,
i2p_b32: e.i2p_b32.map(|b32| format!("{b32}.b32.i2p")),
tunnel_state: e.i2p_tunnel_state.map(|state| {
// I2PInterfacePeer.TUNNEL_STATE_* (Reticulum.py:1638-1647).
// I2PInterfacePeer.TUNNEL_STATE_* (Reticulum.py).
match state {
0x01 => "Tunnel Active",
0x00 => "Creating Tunnel",
@@ -525,7 +525,7 @@ async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result<Vec<u8>, R
/// Python's `Transport.lowest_interface_bitrate`: the minimum over online
/// interfaces with a bitrate, keeping the last value when none qualifies
/// (Transport.py:708).
/// (Transport.py).
async fn lowest_interface_bitrate(backend: &RpcBackend) -> Result<Option<u64>, RpcResponse> {
use rns_transport::messages::{TransportQuery, TransportQueryResponse};
let interfaces =
@@ -551,7 +551,7 @@ async fn lowest_interface_bitrate(backend: &RpcBackend) -> Result<Option<u64>, R
Ok(*cached)
}
/// Python's `Transport.medium_path_timeout()` for a known bitrate (Transport.py:3550-3553).
/// Python's `Transport.medium_path_timeout()` for a known bitrate (Transport.py).
fn medium_path_timeout(lowest_bitrate: u64) -> f64 {
let bits = (rns_wire::constants::MTU * 8) as f64;
2.0 * (bits / lowest_bitrate.max(crate::constants::MINIMUM_BITRATE) as f64)
@@ -881,7 +881,7 @@ async fn process_rpc_request(
}
RpcRequest::DropAnnounceQueues => {
match authoritative_query!(TransportQuery::DropAnnounceQueues, "announce queue drop") {
// Transport.drop_announce_queues returns None (Transport.py:4214-4224).
// Transport.drop_announce_queues returns None (Transport.py).
TransportQueryResponse::Ok => RpcResponse::OptBoolResult(None),
_ => unexpected_transport_response("announce queue drop"),
}
@@ -927,7 +927,7 @@ async fn process_rpc_request(
reason,
} => {
let Some(hash) = hash_to_array(&identity_hash) else {
// Reticulum.py:2192,2203: a wrong-length hash answers False.
// Reticulum.py: a wrong-length hash answers False.
return RpcResponse::BoolResult(false);
};
// `until` (absolute unix ts) → relative TTL; past timestamps
@@ -958,7 +958,7 @@ async fn process_rpc_request(
}
RpcRequest::UnblackholeIdentity { identity_hash } => {
let Some(hash) = hash_to_array(&identity_hash) else {
// Reticulum.py:2192,2203: a wrong-length hash answers False.
// Reticulum.py: a wrong-length hash answers False.
return RpcResponse::BoolResult(false);
};
match authoritative_query!(
@@ -1273,7 +1273,7 @@ mod tests {
}
/// A transport instance adds its identity, network identity, uptime and
/// probe responder to the stats dict (Reticulum.py:1700-1705).
/// probe responder to the stats dict (Reticulum.py).
#[tokio::test]
async fn interface_stats_answer_names_the_transport_instance() {
let (actor, tx) = rns_transport::actor::TransportActor::new();
+18 -18
View File
@@ -143,7 +143,7 @@ struct Args {
destination: Option<String>,
}
// rncp.py:376-385 and :615-624 share this text for send and fetch.
// rncp.py and :615-624 share this text for send and fetch.
fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], String> {
if hex_str.chars().count() != 32 {
return Err(
@@ -160,7 +160,7 @@ fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], String> {
const ERASE: &str = "\x1b[2K\r";
const SYMS: [char; 7] = ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'];
/// rncp.py:54-68 (`prepare_identity`): `-i` is used as given, and an identity
/// rncp.py (`prepare_identity`): `-i` is used as given, and an identity
/// that cannot be saved is still used for this run.
async fn prepare_identity(
handle: &ReticulumHandle,
@@ -192,7 +192,7 @@ async fn prepare_identity(
id
}
/// rncp.py:891-908 (`size_str`).
/// rncp.py (`size_str`).
fn size_str(num: f64, suffix: char) -> String {
let mut num = if suffix == 'b' { num * 8.0 } else { num };
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] {
@@ -208,7 +208,7 @@ fn size_str(num: f64, suffix: char) -> String {
format!("{num:.2}Y{suffix}")
}
/// `RNS.prettytime` (RNS/__init__.py:239-290) for the float durations rncp prints.
/// `RNS.prettytime` (RNS/__init__.py) for the float durations rncp prints.
fn prettytime(time: f64) -> String {
let neg = time < 0.0;
let mut time = time.abs();
@@ -262,13 +262,13 @@ fn python_float(v: f64) -> String {
}
}
/// `str(round(prg * 100.0, 1))` (rncp.py:582, :746).
/// `str(round(prg * 100.0, 1))` (rncp.py).
fn percent_str(progress: f64) -> String {
python_float(format!("{:.1}", progress * 100.0).parse().unwrap_or(0.0))
}
/// Resource `total_size`: data plus the 3-byte length and msgpack of
/// `{"name": <basename>}` (Resource.py:263-271, rncp.py:629).
/// `{"name": <basename>}` (Resource.py, rncp.py).
fn resource_total_size(data_size: u64, file_name: &str) -> f64 {
let meta = rmpv::Value::Map(vec![(
rmpv::Value::String("name".into()),
@@ -300,7 +300,7 @@ struct UiState {
}
impl UiState {
/// rncp.py:323-356 (`sender_progress`): speed over the last 32 updates.
/// rncp.py (`sender_progress`): speed over the last 32 updates.
fn update(&mut self, progress: f64, phy_got: f64) {
let now = Instant::now();
self.started.get_or_insert(now);
@@ -332,7 +332,7 @@ impl UiState {
let cs = size_str((self.progress * total).trunc(), 'B');
let ts = size_str(total, 'B');
let ss = size_str(self.speed, 'b');
// rncp.py:577-579, 753-755.
// rncp.py.
let phy_str = if self.phy_rates {
format!(" ({}ps at physical layer)", size_str(self.phy_speed, 'b'))
} else {
@@ -431,7 +431,7 @@ impl Ui {
}
}
/// rncp.py:576-577: the erase before the fetch progress, without a line under `-S`.
/// rncp.py: the erase before the fetch progress, without a line under `-S`.
fn transfer_started(&self) {
let mut st = self.lock();
if !self.silent {
@@ -472,7 +472,7 @@ pub(crate) async fn main() {
std::io::stderr,
);
// rncp.py:824-880.
// rncp.py.
let positionals = args.file.is_some() && args.destination.is_some();
if args.listen || args.print_identity {
run_listen(args).await;
@@ -489,7 +489,7 @@ pub(crate) async fn main() {
}
}
/// rncp.py:394-430 / :640-676: request a path unless one is known, wait
/// rncp.py / :640-676: request a path unless one is known, wait
/// `max(-w, medium path timeout)` for it, and return the time left for the
/// link, which rncp waits for until the later of that deadline and the link
/// establishment timeout.
@@ -546,7 +546,7 @@ async fn run_fetch(args: Args) -> ! {
process::exit(0);
};
// rncp.py:364-374: the save directory is checked before the hash.
// rncp.py: the save directory is checked before the hash.
let save_dir = match args.save.as_deref() {
Some(p) => {
let path = expand_tilde(p);
@@ -643,7 +643,7 @@ async fn run_fetch(args: Args) -> ! {
fail("The transfer failed");
};
// rncp.py:543-567: every answered request failure exits 0.
// rncp.py: every answered request failure exits 0.
match result {
Err(RncpError::Interrupted) => {
println!();
@@ -846,7 +846,7 @@ async fn run_send(args: Args) -> ! {
let mut st = ui.lock();
st.tick = Tick::Off;
st.progress = 1.0;
// The send's final line drops the physical rate once the resource is done (rncp.py:753).
// The send's final line drops the physical rate once the resource is done (rncp.py).
st.phy_rates = false;
let total = st.total_size.unwrap_or(0.0);
let dt = st.started.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
@@ -952,7 +952,7 @@ async fn run_listen(args: Args) -> ! {
process::exit(0);
}
// rncp.py:118-170: -n skips the allowed_identities file and -a entirely.
// rncp.py: -n skips the allowed_identities file and -a entirely.
let allow_all = args.no_auth;
let allowed = if allow_all {
Vec::new()
@@ -1076,7 +1076,7 @@ fn spawn_listen_announcer(
loop {
send_rncp_announce(&transport_tx, &mut destination, &identity, destination_hash).await;
// rncp.py:86-87, 222-230: -1 and 0 both announce once.
// rncp.py: -1 and 0 both announce once.
if interval_seconds <= 0 {
break;
}
@@ -1122,7 +1122,7 @@ async fn send_rncp_announce(
}
/// The `-a` values plus the first existing allowed_identities file, each
/// validated as a 16-byte hex hash (rncp.py:121-167).
/// validated as a 16-byte hex hash (rncp.py).
fn allowed_identities(cli: &[String], candidates: &[PathBuf]) -> Result<Vec<[u8; 16]>, String> {
let mut entries: Vec<String> = cli.to_vec();
if let Some(path) = candidates.iter().find(|p| p.is_file()) {
@@ -1188,7 +1188,7 @@ async fn start_interruptible(
}
}
/// `max(-w, reticulum.get_medium_path_timeout())` (rncp.py:405, 662).
/// `max(-w, reticulum.get_medium_path_timeout())` (rncp.py).
async fn path_timeout(handle: &ReticulumHandle, timeout: f64) -> Duration {
let medium = rns_tools::medium_path_timeout(handle).await;
let secs = if timeout.is_finite() {
+7 -7
View File
@@ -354,7 +354,7 @@ async fn run(args: &Args, ctx: &mut Ctx) -> u8 {
std::io::stderr,
);
// validate_args (rnid.py:84-101)
// validate_args (rnid.py)
let ops = [
paths_active(&args.encrypt),
paths_active(&args.decrypt),
@@ -793,7 +793,7 @@ async fn recall(
let Some((dest, key)) = found else {
return Ok(None);
};
// Identity.recall marks the matched destination used (Identity.py:148,158).
// Identity.recall marks the matched destination used (Identity.py).
let _ = handle
.query_control(TransportQuery::UseDestination { dest: *dest })
.await;
@@ -834,7 +834,7 @@ async fn spin(
}
// ---------------------------------------------------------------------------
// Identity loading and resolution (rnid.py:200-370)
// Identity loading and resolution (rnid.py)
// ---------------------------------------------------------------------------
/// `RNS.Identity.from_file`: the file always holds a 64-byte private key.
@@ -1198,7 +1198,7 @@ async fn announce(args: &Args, ctx: &mut Ctx, aspects: &str, identity: &Identity
Ok(())
}
/// `validate()` for one path (rnid.py:606-671). Unlike upstream, the legacy
/// `validate()` for one path (rnid.py). Unlike upstream, the legacy
/// branch checks every listed file before succeeding.
fn validate(args: &Args, path: &str, target: &Target<'_>) -> Step {
let validate_path = expanduser(path);
@@ -1423,7 +1423,7 @@ fn validate_message(args: &Args, signature_path: &str, target: &Target<'_>) -> S
Ok(())
}
/// The `recurse()` metadata printer of `validate_message` (rnid.py:701-723).
/// The `recurse()` metadata printer of `validate_message` (rnid.py).
fn format_meta_entry(out: &mut String, entry: &Value, key: &str, level: usize) {
const MAX_WIDTH: usize = 64;
let indent = " ".repeat(level);
@@ -1701,7 +1701,7 @@ fn read_full(input: &mut std::fs::File, buffer: &mut [u8]) -> std::io::Result<us
fn decrypt(args: &Args, path: &str, identity: &Identity) -> Step {
let rfe_path = expanduser(path);
// Case-sensitive, and only the final suffix is stripped (rnid.py:903-908).
// Case-sensitive, and only the final suffix is stripped (rnid.py).
let Some(stem) = rfe_path.strip_suffix(".rfe") else {
println!("The file {rfe_path} does not appear to be a Reticulum encrypted file");
return Err(R_INVALID_FILE);
@@ -1876,7 +1876,7 @@ fn wrap_rsg(rsg: &[u8]) -> String {
wrap_rsg_str(&String::from_utf8_lossy(rsg))
}
/// `wrap_rsg_str` (rnid.py:524-536): 64-character rows padded with `=`.
/// `wrap_rsg_str` (rnid.py): 64-character rows padded with `=`.
fn wrap_rsg_str(rsg: &str) -> String {
const HEADER: &str = "#### Start of rsg data ";
const FOOTER: &str = " End of rsg data ####";
+41 -41
View File
@@ -37,9 +37,9 @@ const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
const SPINNER: [char; 7] = ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'];
/// rnpath.py:42.
/// rnpath.py.
const OUTPUT_RST: &str = "\r \r";
/// rnpath.py:478,489.
/// rnpath.py.
const LOOKUP_RST: &str = "\r \r";
const DEST_LENGTH_INVALID: &str =
"Destination length is invalid, must be 32 hexadecimal characters (16 bytes).";
@@ -166,7 +166,7 @@ pub(crate) async fn main() -> ExitCode {
);
let destination = args.destination.as_deref().filter(|d| !d.is_empty());
// rnpath.py:525-528.
// rnpath.py.
if !(args.drop_announces
|| args.table
|| args.rates
@@ -197,7 +197,7 @@ pub(crate) async fn main() -> ExitCode {
Ok(ctx) => ctx,
Err(code) => return code,
};
// rnpath.py:108-110
// rnpath.py
let registration = rns_tools::RpcRegistration::want(
ctx.endpoint.clone(),
ctx.rpc_key.clone(),
@@ -211,7 +211,7 @@ pub(crate) async fn main() -> ExitCode {
}
async fn dispatch_local(args: &Args, ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
// Dispatch order of rnpath.py:132-490.
// Dispatch order of rnpath.py.
if args.blackholed {
return show_blackholed(ctx, destination).await;
}
@@ -239,12 +239,12 @@ async fn dispatch_local(args: &Args, ctx: &ClientCtx, destination: Option<&str>)
query_path(ctx, destination, args.timeout).await
}
/// rnpath.py:249-255 and its copies: a 32-character hex destination.
/// rnpath.py and its copies: a 32-character hex destination.
fn parse_destination(input: Option<&str>) -> Result<[u8; 16], &'static str> {
parse_hex16(input, DEST_LENGTH_INVALID, DEST_INVALID)
}
/// rnpath.py:94-100.
/// rnpath.py.
fn parse_hash(input: Option<&str>) -> Result<[u8; 16], &'static str> {
parse_hex16(input, HASH_LENGTH_INVALID, HASH_INVALID)
}
@@ -311,7 +311,7 @@ impl ClientCtx {
}
/// `RNS.Transport.identity` of a shared-instance client: ephemeral unless
/// `static_transport_identity` is set (Transport.py:440-445).
/// `static_transport_identity` is set (Transport.py).
fn local_transport_identity(&self) -> Option<[u8; 16]> {
if !self.static_transport_identity {
return None;
@@ -420,7 +420,7 @@ fn local_rpc_failure_message(
}
}
/// rnpath.py:132-206: `-b` lists the shared instance's blackhole list.
/// rnpath.py: `-b` lists the shared instance's blackhole list.
async fn show_blackholed(ctx: &ClientCtx, filter: Option<&str>) -> ExitCode {
let entries = match request(ctx, &RpcRequest::GetBlackholedIdentities).await {
Ok(RpcResponse::BlackholeList(entries)) => entries,
@@ -458,7 +458,7 @@ struct BlackholeLine {
source: Option<Vec<u8>>,
}
/// rnpath.py:176-206, shared by `-b` and `-p`.
/// rnpath.py, shared by `-b` and `-p`.
fn print_blackhole_list(
entries: &[BlackholeLine],
filter: Option<&str>,
@@ -513,7 +513,7 @@ fn blackhole_lines(
lines
}
/// rnpath.py:181-184: at most 64 characters, the last one an ellipsis.
/// rnpath.py: at most 64 characters, the last one an ellipsis.
fn truncate_reason(reason: &str) -> String {
const RMLEN: usize = 64;
if reason.chars().count() <= RMLEN {
@@ -525,7 +525,7 @@ fn truncate_reason(reason: &str) -> String {
}
}
/// rnpath.py:208-225.
/// rnpath.py.
async fn do_blackhole(
ctx: &ClientCtx,
destination: Option<&str>,
@@ -567,7 +567,7 @@ async fn do_blackhole(
ExitCode::SUCCESS
}
/// rnpath.py:227-243.
/// rnpath.py.
async fn do_unblackhole(ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
let id = match parse_hash(destination) {
Ok(id) => id,
@@ -612,7 +612,7 @@ fn table_filter(destination: Option<&str>) -> Result<Option<[u8; 16]>, ExitCode>
}
}
/// rnpath.py:245-306, local shared instance.
/// rnpath.py, local shared instance.
async fn show_path_table(
ctx: &ClientCtx,
destination: Option<&str>,
@@ -643,7 +643,7 @@ fn print_path_table(
usage: bool,
now: f64,
) -> ExitCode {
// rnpath.py:276-283 dumps the whole table, filter or not.
// rnpath.py dumps the whole table, filter or not.
if json {
println!("{}", path_table_json(&table));
return ExitCode::SUCCESS;
@@ -665,7 +665,7 @@ fn print_path_table(
ExitCode::SUCCESS
}
/// rnpath.py:302.
/// rnpath.py.
fn path_table_line(entry: &rpc::PathTableEntry, now: f64) -> String {
format!(
"{} {:>3}h via {} on {} expires in {} {}",
@@ -678,17 +678,17 @@ fn path_table_line(entry: &rpc::PathTableEntry, now: f64) -> String {
)
}
/// rnpath.py:287-288: most recently used first.
/// rnpath.py: most recently used first.
fn sort_by_usage(entries: &mut [rpc::PathTableEntry]) {
entries.sort_by(|a, b| b.used.total_cmp(&a.used));
}
/// The `(dv:<value>/lc:<lr_cost>)` tail of an rnpath 1.6.0 table line (rnpath.py:302).
/// The `(dv:<value>/lc:<lr_cost>)` tail of an rnpath 1.6.0 table line (rnpath.py).
fn cost_suffix(value: Option<f64>, lr_cost: Option<f64>) -> String {
format!("(dv:{}/lc:{})", pretty_cost(value), pretty_cost(lr_cost))
}
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py:276-282).
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py).
/// Upstream sends `value` and `used` as int 0 when unset, and floats otherwise.
fn path_table_json(entries: &[rpc::PathTableEntry]) -> String {
let rows: Vec<String> = entries
@@ -723,7 +723,7 @@ fn py_int_or_float(value: f64) -> String {
}
}
/// rnpath.py:308-390, local shared instance.
/// rnpath.py, local shared instance.
async fn show_rate_table(ctx: &ClientCtx, destination: Option<&str>, json: bool) -> ExitCode {
let filter = match table_filter(destination) {
Ok(filter) => filter,
@@ -768,7 +768,7 @@ fn print_rate_table(
ExitCode::SUCCESS
}
/// rnpath.py:355-386.
/// rnpath.py.
fn rate_table_lines(entry: &rpc::RateTableEntry, now: f64) -> Vec<String> {
let hash = pretty_hex_rep(&entry.hash);
let Some(&start_ts) = entry.timestamps.first() else {
@@ -805,8 +805,8 @@ fn rate_table_lines(entry: &rpc::RateTableEntry, now: f64) -> Vec<String> {
)]
}
/// `json.dumps` of the rate table rows, in upstream key order (Storage.py:162-163,
/// Reticulum.py:1911).
/// `json.dumps` of the rate table rows, in upstream key order (Storage.py,
/// Reticulum.py).
fn rate_table_json(entries: &[rpc::RateTableEntry]) -> String {
let rows: Vec<String> = entries
.iter()
@@ -825,7 +825,7 @@ fn rate_table_json(entries: &[rpc::RateTableEntry]) -> String {
format!("[{}]", rows.join(", "))
}
/// rnpath.py:392-400.
/// rnpath.py.
async fn drop_announces(ctx: &ClientCtx) -> ExitCode {
println!("Dropping announce queues on all interfaces...");
match request(ctx, &RpcRequest::DropAnnounceQueues).await {
@@ -838,7 +838,7 @@ async fn drop_announces(ctx: &ClientCtx) -> ExitCode {
}
}
/// rnpath.py:402-421.
/// rnpath.py.
async fn drop_path(ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
let dest = match parse_destination(destination) {
Ok(dest) => dest,
@@ -867,7 +867,7 @@ async fn drop_path(ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
}
}
/// rnpath.py:423-442.
/// rnpath.py.
async fn drop_all_via(ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
let via = match parse_destination(destination) {
Ok(via) => via,
@@ -896,7 +896,7 @@ async fn drop_all_via(ctx: &ClientCtx, destination: Option<&str>) -> ExitCode {
}
}
/// rnpath.py:444-490: request a path through the shared instance and wait
/// rnpath.py: request a path through the shared instance and wait
/// `max(-w, medium_path_timeout)` with the spinner.
async fn query_path(ctx: &ClientCtx, destination: Option<&str>, timeout: f64) -> ExitCode {
let dest = match parse_destination(destination) {
@@ -982,7 +982,7 @@ async fn query_path_attached(
}
/// Print one spinner frame every 100 ms until `done` or the deadline
/// (rnpath.py:465-472, rnprobe.py:85-91). Returns whether `done` held.
/// (rnpath.py, rnprobe.py). Returns whether `done` held.
async fn spin_until<F, Fut>(deadline: Option<Instant>, mut done: F) -> bool
where
F: FnMut() -> Fut,
@@ -1072,7 +1072,7 @@ fn now_epoch() -> f64 {
.unwrap_or(0.0)
}
/// Start the runtime used for `-R` and `-p`, as rnpath.py:108 does.
/// Start the runtime used for `-R` and `-p`, as rnpath.py does.
async fn start_runtime(args: &Args) -> Result<ReticulumHandle, ExitCode> {
let handle = init(
args.config.as_deref(),
@@ -1085,7 +1085,7 @@ async fn start_runtime(args: &Args) -> Result<ReticulumHandle, ExitCode> {
eprintln!("rnpath-rs: failed to initialize Reticulum runtime: {e:?}");
ExitCode::from(1)
})?;
// rnpath.py:108-110
// rnpath.py
handle.wants_destination_type(MGMT_APP).await;
handle.wants_destination_type(BLACKHOLE_APP).await;
Ok(handle)
@@ -1097,7 +1097,7 @@ async fn stop_runtime(handle: ReticulumHandle, code: ExitCode) -> ExitCode {
code
}
/// rnpath.py:43-58: wait for a path to the remote destination, printing the
/// rnpath.py: wait for a path to the remote destination, printing the
/// request line when one is needed. Exit 12 on timeout.
async fn await_remote_path(
handle: &ReticulumHandle,
@@ -1138,14 +1138,14 @@ async fn await_remote_path(
}
}
/// `Transport.medium_path_timeout()` (Transport.py:3550-3553).
/// `Transport.medium_path_timeout()` (Transport.py).
fn medium_path_timeout_for_bitrate(lowest_bitrate: u64) -> f64 {
let bits = (rns_wire::constants::MTU * 8) as f64;
2.0 * (bits / lowest_bitrate.max(rns_runtime::constants::MINIMUM_BITRATE) as f64)
+ rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT
}
/// rnpath.py:59-92 and the request: one link query, with upstream's
/// rnpath.py and the request: one link query, with upstream's
/// progress lines and link failure messages (exit 10).
async fn remote_query(
handle: &ReticulumHandle,
@@ -1174,7 +1174,7 @@ async fn remote_query(
// A timed-out receipt has no response; callers report it as a failed request.
Err(LinkClientError::RequestFailed(RequestFailure::TimedOut)) => Ok(Vec::new()),
// Upstream's link-closed callback prints, but its exit() runs off the
// main thread, so the pending request still fails (rnpath.py:61-76).
// main thread, so the pending request still fails (rnpath.py).
Err(LinkClientError::RequestFailed(RequestFailure::LinkClosed(reason))) => {
if let Some(text) = rns_tools::link_closed_text(reason) {
println!("{OUTPUT_RST}{text}");
@@ -1192,7 +1192,7 @@ async fn remote_query(
}
}
/// rnpath.py:146-206: `-p` fetches `/list` from the transport whose identity
/// rnpath.py: `-p` fetches `/list` from the transport whose identity
/// hash is the destination argument, filtered by `list_filter`.
async fn run_remote_blackhole_list(args: &Args) -> ExitCode {
let identity_hash = match parse_hash(args.destination.as_deref()) {
@@ -1254,7 +1254,7 @@ async fn remote_blackhole_list(
)
}
/// rnpath.py:111-130 and the remote branches: `-t` and `-r` over
/// rnpath.py and the remote branches: `-t` and `-r` over
/// `rnstransport.remote.management`; other actions are not implemented upstream.
async fn run_remote(args: &Args, remote: &str) -> ExitCode {
let remote_hash = match parse_destination(Some(remote)) {
@@ -1298,7 +1298,7 @@ async fn run_remote(args: &Args, remote: &str) -> ExitCode {
stop_runtime(handle, code).await
}
/// The remote branches that print "not implemented" and exit 255 (rnpath.py:135-449).
/// The remote branches that print "not implemented" and exit 255 (rnpath.py).
fn remote_unimplemented(args: &Args) -> Option<&'static str> {
if args.blackholed {
Some("Listing blackholed identities on remote instances not yet implemented")
@@ -1329,7 +1329,7 @@ async fn remote_management(
let dest_value = filter
.map(|f| rmpv::Value::Binary(f.to_vec()))
.unwrap_or(rmpv::Value::Nil);
// rnpath.py:263,326.
// rnpath.py.
let request = if args.table {
let max = args.max.map(rmpv::Value::from).unwrap_or(rmpv::Value::Nil);
vec![rmpv::Value::from("table"), dest_value, max]
@@ -1347,7 +1347,7 @@ async fn remote_management(
Err(code) => return code,
};
let now = now_epoch();
// A falsy reply, including an empty table, is reported as a failure (rnpath.py:266-273).
// A falsy reply, including an empty table, is reported as a failure (rnpath.py).
if args.table {
match rpc::decode_response_for_request(&bytes, &RpcRequest::GetPathTable { max_hops: None })
{
@@ -1373,7 +1373,7 @@ fn remote_request_failed() -> ExitCode {
ExitCode::from(10)
}
/// rnpath.py:542-561 for an integer timestamp, from `datetime` differences.
/// rnpath.py for an integer timestamp, from `datetime` differences.
fn pretty_date(time: f64, now: f64) -> String {
let diff = now - time;
let day_diff = (diff / 86400.0).floor() as i64;
@@ -1525,7 +1525,7 @@ mod tests {
assert_eq!(order, [4, 2, 1, 3]);
}
/// rnpath.py:181-202: reason truncation, the `by` suffix and the filter string.
/// rnpath.py: reason truncation, the `by` suffix and the filter string.
#[test]
fn blackhole_lines_truncate_reason_and_filter_on_rendered_text() {
let own = [0xdd; 16];
+1 -1
View File
@@ -5,7 +5,7 @@ use clap::Parser;
use rns_runtime::lifecycle::ShutdownSignal;
use rns_tools::RS_RETICULUM_VERSION;
/// `__example_rnpkg_config__` (rnpkg.py:76-77).
/// `__example_rnpkg_config__` (rnpkg.py).
const EXAMPLE_CONFIG: &str = "# This is an example package manager configuration file.\n";
#[derive(Parser)]
+7 -7
View File
@@ -103,7 +103,7 @@ pub(crate) async fn main() {
);
return;
};
// rnprobe.py:57-67: input errors print to stdout and exit 0.
// rnprobe.py: input errors print to stdout and exit 0.
let dest_hash: [u8; 16] = if dest_hex.chars().count() != 32 {
println!("Destination length is invalid, must be 32 hexadecimal characters (16 bytes).");
return;
@@ -169,7 +169,7 @@ async fn run(args: &Args, handle: &ReticulumHandle, dest_hash: [u8; 16], full_na
let size = args.size.unwrap_or(DEFAULT_PROBE_SIZE);
let timeout = args.timeout.filter(|t| *t != 0.0);
// rnprobe.py:79-95.
// rnprobe.py.
if !local_has_path(handle, dest_hash).await {
let _ = handle
.request_path(dest_hash, PathRequestOptions::default())
@@ -231,7 +231,7 @@ async fn run(args: &Args, handle: &ReticulumHandle, dest_hash: [u8; 16], full_na
if sent > 0 {
tokio::time::sleep(wait).await;
}
// rnprobe.py:114-119: the packed length is reported.
// rnprobe.py: the packed length is reported.
let payload = rns_crypto::random::random_bytes(size);
let packet = match destination.pack_packet(
&payload,
@@ -281,7 +281,7 @@ async fn run(args: &Args, handle: &ReticulumHandle, dest_hash: [u8; 16], full_na
flush();
}
// rnprobe.py:134-143, and the receipt's own timeout (Packet.py:432-433).
// rnprobe.py, and the receipt's own timeout (Packet.py).
let probe_deadline = deadline_after(probe_timeout(handle, dest_hash, timeout).await);
let outcome = probe.wait(probe_deadline, json).await;
match outcome {
@@ -379,7 +379,7 @@ async fn send_probe(
identity: &rns_identity::identity::Identity,
dest_hash: [u8; 16],
) -> Option<PendingProbe> {
// Packet.py:430-433: first-hop timeout plus TIMEOUT_PER_HOP per hop.
// Packet.py: first-hop timeout plus TIMEOUT_PER_HOP per hop.
let first_hop = handle
.first_hop_timeout(dest_hash)
.await
@@ -459,7 +459,7 @@ impl PendingProbe {
}
}
/// rnprobe.py:165-186: over RPC on a shared-instance client, else from the proof packet.
/// rnprobe.py: over RPC on a shared-instance client, else from the proof packet.
async fn reception_stats(
handle: &ReticulumHandle,
proof_hash: Option<[u8; 32]>,
@@ -523,7 +523,7 @@ fn f32_to_f64(value: f32) -> f64 {
format!("{value}").parse().unwrap_or(f64::from(value))
}
/// rnprobe.py:157-163.
/// rnprobe.py.
fn rtt_string(rtt: Duration) -> String {
let rtt = rtt.as_secs_f64();
if rtt >= 1.0 {
+1 -1
View File
@@ -727,7 +727,7 @@ pub(crate) async fn main() {
);
}
tracing::info!("reticulum started in {:?} mode", handle.instance_mode);
// Python's discovery stamps come from RNS itself (Discovery.py:87,266).
// Python's discovery stamps come from RNS itself (Discovery.py).
handle
.enable_on_network_discovery(std::sync::Arc::new(
rns_transport::discovery::RnsDiscoveryStamper,
+1 -1
View File
@@ -367,7 +367,7 @@ async fn run_initiator(args: Args, config_dir: PathBuf) -> ExitCode {
progress_tx: Some(progress_tx),
};
// initiator.py:156
// initiator.py
handle.wants_destination_type(APP_NAME).await;
let result = rnsh_client_execute(handle.transport_tx.clone(), cfg).await;
terminate_task.abort();
+26 -26
View File
@@ -45,7 +45,7 @@ const LOCAL_RPC_TIMEOUT: Duration = Duration::from_secs(10);
const REMOTE_LINK_TIMEOUT: Duration = Duration::from_secs(30);
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
/// rnstatus.py:79.
/// rnstatus.py.
const CLR: &str = "\r \r";
#[derive(Parser)]
@@ -199,7 +199,7 @@ fn warn_deprecated_spellings() {
}
/// Output of one run. Direct output is written out at each progress point;
/// monitor mode buffers a whole frame, as rnstatus.py:930-951 does.
/// monitor mode buffers a whole frame, as rnstatus.py does.
struct Out {
buf: String,
direct: bool,
@@ -292,7 +292,7 @@ pub(crate) async fn main() -> ExitCode {
ExitCode::from(code)
}
/// rnstatus.py:920-955: one instance across refreshes; each frame is
/// rnstatus.py: one instance across refreshes; each frame is
/// rendered into a buffer, then printed after `ESC[H ESC[2J`.
async fn run_monitor(args: &Args, session: &Session) -> u8 {
let interrupt = ShutdownSignal::new();
@@ -308,7 +308,7 @@ async fn run_monitor(args: &Args, session: &Session) -> u8 {
_ = tokio::time::sleep(monitor_sleep(args.monitor_interval, started.elapsed())) => {}
_ = interrupt.wait() => {}
}
// rnstatus.py:965-966: KeyboardInterrupt prints an empty line.
// rnstatus.py: KeyboardInterrupt prints an empty line.
if interrupt.is_triggered() {
write_stdout("\n");
return 0;
@@ -316,19 +316,19 @@ async fn run_monitor(args: &Args, session: &Session) -> u8 {
}
}
/// rnstatus.py:953-955: sleep `max(interval - render time, 0.2)`.
/// rnstatus.py: sleep `max(interval - render time, 0.2)`.
fn monitor_sleep(interval_secs: f64, elapsed: Duration) -> Duration {
Duration::from_secs_f64((interval_secs - elapsed.as_secs_f64()).max(0.2))
}
/// The Reticulum instance rnstatus runs with: a shared-instance client for
/// local queries, as `RNS.Reticulum(require_shared_instance=True)`, or any
/// instance for `-R` (rnstatus.py:157-169).
/// instance for `-R` (rnstatus.py).
struct Session {
handle: ReticulumHandle,
rpc_key: Vec<u8>,
first_remote_request: std::sync::atomic::AtomicBool,
/// Monitor mode's remote link, reused while it stays up (rnstatus.py:139-146).
/// Monitor mode's remote link, reused while it stays up (rnstatus.py).
remote_link: tokio::sync::Mutex<Option<RemoteLink>>,
}
@@ -410,7 +410,7 @@ impl Session {
rmpv::decode::read_value(&mut bytes.as_slice()).map_err(|e| e.to_string())
}
/// `program_setup` (rnstatus.py:155-880).
/// `program_setup` (rnstatus.py).
async fn status(&self, args: &Args, out: &mut Out) -> Flow {
for (name, operation) in [
(&args.attach, ManageOperation::Attach),
@@ -495,7 +495,7 @@ impl Session {
}
}
/// `--attach/--detach/--reload` (rnstatus.py:171-198).
/// `--attach/--detach/--reload` (rnstatus.py).
async fn manage(&self, operation: ManageOperation, name: &str, out: &mut Out) -> u8 {
let (verb, done, doing) = match operation {
ManageOperation::Attach => ("attach", "attached", "attaching"),
@@ -542,7 +542,7 @@ fn local_rpc_key(config_dir: &Path, rc: &ReticulumConfig) -> Vec<u8> {
}
}
/// rnstatus.py:373-391: the remote hash and management identity, or the
/// rnstatus.py: the remote hash and management identity, or the
/// message upstream prints before exiting 20.
fn remote_inputs(remote: &str, identity: Option<&Path>) -> Result<([u8; 16], Identity), String> {
let Some(identity_path) = identity else {
@@ -584,7 +584,7 @@ fn expand_user(path: &Path) -> PathBuf {
}
impl Session {
/// rnstatus.py:66-151 `get_remote_status`: wait for a path, then ask
/// rnstatus.py `get_remote_status`: wait for a path, then ask
/// `/status` over a link. `Err` carries an exit code.
async fn remote_status(
&self,
@@ -626,7 +626,7 @@ impl Session {
out.flush_now();
}
// The first request asks for profiling too; refreshes send only the
// link-count flag (rnstatus.py:115,126).
// link-count flag (rnstatus.py).
let request = if first {
Value::Array(vec![
Value::Boolean(args.link_stats),
@@ -695,7 +695,7 @@ impl Session {
Ok(result)
}
/// `-d`/`-D` (rnstatus.py:216-367).
/// `-d`/`-D` (rnstatus.py).
async fn discovered(&self, args: &Args, out: &mut Out) -> u8 {
let paths = StoragePaths::from_config_dir(&self.handle.config_dir);
let store = match DiscoveryStore::open(&paths.storage_dir) {
@@ -794,7 +794,7 @@ async fn one_shot_query(
impl Session {
/// Monitor mode: request on the remote link while it is active, else open
/// a new one (rnstatus.py:139-146).
/// a new one (rnstatus.py).
async fn monitor_query(
&self,
identity_hash: [u8; 16],
@@ -887,7 +887,7 @@ impl Session {
/// The stored info dictionary as `list_discovered_interfaces` returns it:
/// the file's keys in order, the name sanitized, `"None"` IFAC values
/// dropped, and the status appended (Discovery.py:533-568).
/// dropped, and the status appended (Discovery.py).
fn stored_info(root: &Path, record: &DiscoveredInterface) -> Value {
let mut map = std::fs::read(root.join(record.filename()))
.ok()
@@ -915,7 +915,7 @@ fn set_key(map: &mut Vec<(Value, Value)>, key: &str, value: Value) {
}
// ---------------------------------------------------------------------------
// The stats renderer: rnstatus.py:410-870.
// The stats renderer: rnstatus.py.
const HIDDEN_PREFIXES: &[&str] = &[
"LocalInterface[",
@@ -926,7 +926,7 @@ const HIDDEN_PREFIXES: &[&str] = &[
"I2PInterfacePeer[Connected peer",
];
/// Python's sort keys (rnstatus.py:432-454); an unknown key sorts nothing.
/// Python's sort keys (rnstatus.py); an unknown key sorts nothing.
fn sort_key(name: &str) -> Option<fn(&Value) -> f64> {
fn k(i: &Value, key: &str) -> f64 {
num(get(i, key)).f()
@@ -1084,7 +1084,7 @@ fn render_status(
outln!(out);
}
/// One interface block (rnstatus.py:481-758).
/// One interface block (rnstatus.py).
fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
let astats = args.announce_stats;
let pstats = args.pr_stats;
@@ -1448,7 +1448,7 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
outln!(out, " Traffic : {txstat}\n {rxstat}");
}
/// The optional radio, Weave and I2P lines (rnstatus.py:554-619), with
/// The optional radio, Weave and I2P lines (rnstatus.py), with
/// upstream's labels as printed.
fn render_radio_lines(out: &mut Out, ifstat: &Value) {
if has(ifstat, "noise_floor") {
@@ -1560,7 +1560,7 @@ fn render_radio_lines(out: &mut Out, ifstat: &Value) {
}
}
/// The traffic totals blocks (rnstatus.py:770-833).
/// The traffic totals blocks (rnstatus.py).
fn render_totals(out: &mut Out, stats: &Value, astats: bool, pstats: bool, pps: bool) {
let n = |k: &str| num(get(stats, k)).f();
let (mut rxb_str, mut txb_str) = pair(n("rxb"), n("txb"));
@@ -1649,7 +1649,7 @@ fn pair(rx: f64, tx: f64) -> (String, String) {
(rx, tx)
}
/// `-q` (rnstatus.py:836-853).
/// `-q` (rnstatus.py).
fn render_queues(out: &mut Out, stats: &Value) {
let line = |pressure: &str, count: &str, dropped: &str, label: &str| {
let d = get(stats, dropped);
@@ -1692,7 +1692,7 @@ fn render_queues(out: &mut Out, stats: &Value) {
);
}
/// `RNS.Profiler.format_results` (RNS/__init__.py:581-620).
/// `RNS.Profiler.format_results` (RNS/__init__.py).
fn format_profiling(results: &Value) -> String {
let tags: Vec<&Value> = match results {
Value::Map(entries) => entries.iter().map(|(_, v)| v).collect(),
@@ -1899,7 +1899,7 @@ fn pad(s: &mut String, width: usize) {
}
/// `json.dumps` with default separators; bytes are written as hex, which
/// is what rnstatus converts them to before dumping (rnstatus.py:227-233,412-425).
/// is what rnstatus converts them to before dumping (rnstatus.py).
fn py_json(value: &Value) -> String {
match value {
Value::Nil | Value::Ext(..) => "null".to_string(),
@@ -1984,7 +1984,7 @@ fn unix_now() -> f64 {
}
// ---------------------------------------------------------------------------
// Discovered interfaces (rnstatus.py:236-367).
// Discovered interfaces (rnstatus.py).
fn print_discovered_summary(
out: &mut Out,
@@ -2179,7 +2179,7 @@ fn finite_location(value: Option<f64>) -> Option<f64> {
value.filter(|number| number.is_finite())
}
/// Python's `impl_name version`, when the record names both (rnstatus.py:250-251).
/// Python's `impl_name version`, when the record names both (rnstatus.py).
fn discovered_stack(record: &DiscoveredInterface) -> Option<String> {
match (&record.info.impl_name, &record.info.impl_version) {
(Some(name), Some(version)) if !name.is_empty() && !version.is_empty() => {
@@ -2190,7 +2190,7 @@ fn discovered_stack(record: &DiscoveredInterface) -> Option<String> {
}
/// Whether Python lists this record: stale and stack-less records are hidden
/// unless asked for (rnstatus.py:255-256).
/// unless asked for (rnstatus.py).
fn discovered_shown(record: &DiscoveredInterface, show_stale: bool, show_unknown: bool) -> bool {
(show_stale || record.status != Some(DiscoveryStatus::Stale))
&& (show_unknown || discovered_stack(record).is_some())
+9 -9
View File
@@ -170,7 +170,7 @@ async fn start(args: &Args, interrupt: &ShutdownSignal) -> ReticulumHandle {
}
}
/// `prepare_identity` (rnx.py:50-61): load the identity file or write a new one there.
/// `prepare_identity` (rnx.py): load the identity file or write a new one there.
fn prepare_identity(path: Option<&Path>, handle: &ReticulumHandle) -> Identity {
let path = path.map(Path::to_path_buf).unwrap_or_else(|| {
StoragePaths::from_config_dir(&handle.config_dir)
@@ -341,7 +341,7 @@ async fn listen(args: &Args, interrupt: &ShutdownSignal) -> ! {
rns_tools::exit(&handle, 0).await;
}
/// `spin` (rnx.py:254-272): an animated message on stdout while `until` runs.
/// `spin` (rnx.py): an animated message on stdout while `until` runs.
async fn spin<F: std::future::Future>(msg: &str, until: F) -> F::Output {
const SYMS: [char; 7] = ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'];
let mut out = std::io::stdout();
@@ -373,7 +373,7 @@ fn secs(seconds: f64) -> Duration {
}
async fn run_client(args: &Args, handle: &ReticulumHandle, destination_hash: [u8; 16]) -> i32 {
// rnx.py:345
// rnx.py
handle.wants_destination_type(APP_NAME).await;
let identity = prepare_identity(args.identity.as_deref(), handle);
let mut client = Client {
@@ -410,7 +410,7 @@ async fn run_commands(args: &Args, client: &mut Client<'_>, timeout: Timeout) ->
interactive(args, client, timeout).await
}
/// The interactive loop (rnx.py:613-666).
/// The interactive loop (rnx.py).
async fn interactive(args: &Args, client: &mut Client<'_>, timeout: Timeout) -> i32 {
let (line_tx, mut line_rx) = mpsc::channel::<Option<String>>(1);
std::thread::spawn(move || {
@@ -469,7 +469,7 @@ struct Client<'a> {
}
impl Client<'_> {
/// Ensure a path, as `execute` does before linking (rnx.py:350-354).
/// Ensure a path, as `execute` does before linking (rnx.py).
async fn ensure_path(&self, timeout: Timeout) -> bool {
let handle = self.handle;
let hash = self.destination_hash;
@@ -494,7 +494,7 @@ impl Client<'_> {
tokio::time::timeout(secs(wait), found).await.is_ok()
}
/// Open the Link with `max(-w, establishment timeout)` (rnx.py:366-376).
/// Open the Link with `max(-w, establishment timeout)` (rnx.py).
/// Returns the session and its measured round trip.
async fn connect(&self, noid: bool, timeout: Timeout) -> Option<(LinkSession, f64)> {
let handle = self.handle;
@@ -585,7 +585,7 @@ impl Client<'_> {
);
tokio::pin!(request);
// `-W` bounds only the result transfer; when it passes, the receipt
// still holds no response (rnx.py:425-430, 443, 527-532).
// still holds no response (rnx.py).
let result = match args.result_timeout {
Some(w) => tokio::select! {
r = &mut request => Some(r),
@@ -647,7 +647,7 @@ impl Client<'_> {
}
}
/// Write remote output first, then the trailer lines, as rnx.py:461-520 orders them.
/// Write remote output first, then the trailer lines, as rnx.py orders them.
fn write_split(parsed: &rns_tools::rnx::Response, rendered: &rns_tools::rnx::Rendered) {
let remote_out = parsed.stdout.as_deref().map_or(0, <[u8]>::len);
let (out, trailer) = rendered
@@ -663,7 +663,7 @@ fn write_split(parsed: &rns_tools::rnx::Response, rendered: &rns_tools::rnx::Ren
let _ = stdout.flush();
}
/// `len(umsgpack.packb([time.time(), path_hash, data]))` (Link.py:573-574).
/// `len(umsgpack.packb([time.time(), path_hash, data]))` (Link.py).
fn packed_request_size(data: &rmpv::Value) -> u64 {
let request = rmpv::Value::Array(vec![
rmpv::Value::F64(0.0),
+5 -5
View File
@@ -189,7 +189,7 @@ where
}
/// The line rnstatus and rnpath print for a remote link's `teardown_reason`,
/// none for a local close (rnstatus.py:87-100, rnpath.py:62-76).
/// none for a local close (rnstatus.py, rnpath.py).
pub fn link_closed_text(reason: Option<rns_runtime::prelude::CloseReason>) -> Option<&'static str> {
use rns_runtime::prelude::CloseReason;
match reason {
@@ -206,7 +206,7 @@ pub fn link_closed_text(reason: Option<rns_runtime::prelude::CloseReason>) -> Op
const EXIT_SHUTDOWN_DEADLINE: Duration = Duration::from_secs(10);
/// Shut the runtime down as Python's exit handler does before the process
/// ends (Reticulum.py:186-195): a shared-instance client first deregisters its
/// ends (Reticulum.py): a shared-instance client first deregisters its
/// destination types, so no registration outlives the tool run.
pub async fn shut_down(handle: &ReticulumHandle) {
let _ = tokio::time::timeout(EXIT_SHUTDOWN_DEADLINE, handle.shutdown_and_wait()).await;
@@ -220,7 +220,7 @@ pub async fn exit(handle: &ReticulumHandle, code: i32) -> ! {
/// Destination types a tool that talks to the shared instance over RPC alone
/// registers there, with its own requester hash, as upstream's tools do
/// through `Reticulum.wants_destination_type` (Reticulum.py:2224-2267).
/// through `Reticulum.wants_destination_type` (Reticulum.py).
pub struct RpcRegistration {
endpoint: SharedInstanceRpcEndpoint,
rpc_key: Vec<u8>,
@@ -285,8 +285,8 @@ impl RpcRegistration {
}
}
/// Reticulum.get_medium_path_timeout (Reticulum.py:2011-2029): ask the shared
/// instance, or compute Transport.medium_path_timeout (Transport.py:3550-3553)
/// Reticulum.get_medium_path_timeout (Reticulum.py): ask the shared
/// instance, or compute Transport.medium_path_timeout (Transport.py)
/// from the lowest online interface bitrate. 0 when unknown or on error.
pub async fn medium_path_timeout(handle: &ReticulumHandle) -> f64 {
if handle.instance_mode == InstanceMode::Client {
+17 -17
View File
@@ -8,11 +8,11 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use rmpv::Value;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// Destination aspects `rnx.execute` (rnx.py:70).
/// Destination aspects `rnx.execute` (rnx.py).
pub const APP_NAME: &str = "rnx.execute";
/// Request handler path (rnx.py:115-122).
/// Request handler path (rnx.py).
pub const COMMAND_PATH: &str = "command";
/// `remote_exec_grace` (rnx.py:325).
/// `remote_exec_grace` (rnx.py).
pub const REMOTE_EXEC_GRACE: f64 = 2.0;
/// `RNS.Transport.PATH_REQUEST_TIMEOUT`, the default `-w`, sent as an integer.
pub const DEFAULT_TIMEOUT: i64 = 15;
@@ -40,7 +40,7 @@ impl Timeout {
}
}
/// `request_data` as `execute` builds it (rnx.py:379-385).
/// `request_data` as `execute` builds it (rnx.py).
pub fn request_value(
command: &str,
timeout: Timeout,
@@ -58,7 +58,7 @@ pub fn request_value(
])
}
/// A decoded request as `execute_received_command` reads it (rnx.py:156-160).
/// A decoded request as `execute_received_command` reads it (rnx.py).
#[derive(Debug, Clone, PartialEq)]
pub struct CommandRequest {
pub command: String,
@@ -107,7 +107,7 @@ impl CommandRequest {
}
}
/// The result array (rnx.py:170-179).
/// The result array (rnx.py).
#[derive(Debug, Clone, PartialEq)]
pub struct CommandResult {
pub executed: bool,
@@ -164,7 +164,7 @@ fn now() -> f64 {
}
/// `out[0:limit]` with Python slice semantics, applied only when
/// `len(out) > limit` (rnx.py:225-238).
/// `len(out) > limit` (rnx.py).
pub fn truncate(out: &[u8], limit: Option<i64>) -> Vec<u8> {
let len = out.len() as i64;
match limit {
@@ -180,7 +180,7 @@ pub fn truncate(out: &[u8], limit: Option<i64>) -> Vec<u8> {
}
}
/// `execute_received_command` (rnx.py:155-252): run the command without a
/// `execute_received_command` (rnx.py): run the command without a
/// shell, feed stdin, SIGTERM it once the timeout passes, truncate output.
pub async fn execute(request: &CommandRequest) -> CommandResult {
let started = now();
@@ -268,7 +268,7 @@ pub async fn execute(request: &CommandRequest) -> CommandResult {
}
}
/// A response as the client indexes it (rnx.py:438-452).
/// A response as the client indexes it (rnx.py).
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
pub executed: bool,
@@ -351,7 +351,7 @@ pub struct TransferStats {
pub elapsed: f64,
}
/// Text the client writes for an executed result (rnx.py:461-520).
/// Text the client writes for an executed result (rnx.py).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rendered {
pub stdout: Vec<u8>,
@@ -451,7 +451,7 @@ pub fn render(
r
}
/// The process status for `-m` (rnx.py:536-540): the remote code as Python's
/// The process status for `-m` (rnx.py): the remote code as Python's
/// `exit()` passes it to the OS, or 240 without one.
pub fn mirrored_exit_code(retcode: Option<i64>) -> i32 {
retcode.map_or(240, |code| (code & 0xff) as i32)
@@ -471,7 +471,7 @@ pub fn py_float(x: f64) -> String {
}
}
/// `size_str` (rnx.py:680-697).
/// `size_str` (rnx.py).
pub fn size_str(num: f64, suffix: char) -> String {
let mut num = if suffix == 'b' { num * 8.0 } else { num };
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] {
@@ -487,7 +487,7 @@ pub fn size_str(num: f64, suffix: char) -> String {
format!("{num:.2}Y{suffix}")
}
/// `pretty_time` without `verbose` (rnx.py:699-739).
/// `pretty_time` without `verbose` (rnx.py).
pub fn pretty_time(time: f64) -> String {
let days = (time / 86400.0).floor() as i64;
let time = time.rem_euclid(86400.0);
@@ -520,7 +520,7 @@ pub fn pretty_time(time: f64) -> String {
}
/// The allowed-identities files the listener reads, first existing wins
/// (rnx.py:94-101).
/// (rnx.py).
pub fn allowed_identity_files(home: Option<&Path>) -> Vec<PathBuf> {
let mut files = vec![PathBuf::from("/etc/rnx/allowed_identities")];
if let Some(home) = home {
@@ -531,7 +531,7 @@ pub fn allowed_identity_files(home: Option<&Path>) -> Vec<PathBuf> {
}
/// Parse an allowed-identities file: only lines of exactly 32 characters
/// count, and one that is not hex fails (rnx.py:102-108).
/// count, and one that is not hex fails (rnx.py).
pub fn parse_allowed_identities(text: &str) -> Result<Vec<[u8; 16]>, String> {
let mut allowed = Vec::new();
for line in text.replace('\r', "").split('\n') {
@@ -552,7 +552,7 @@ pub fn parse_allowed_identities(text: &str) -> Result<Vec<[u8; 16]>, String> {
}
/// Validate a 32-character hash argument with upstream's messages
/// (rnx.py:80-93, 328-336).
/// (rnx.py).
pub fn parse_hash_arg(value: &str) -> Result<[u8; 16], String> {
if value.chars().count() != 32 {
return Err(
@@ -567,7 +567,7 @@ pub fn parse_hash_arg(value: &str) -> Result<[u8; 16], String> {
}
/// A one-shot client's output and exit code for a received response value
/// (rnx.py:437-549).
/// (rnx.py).
pub fn client_result(
value: &Value,
detailed: bool,
+3 -3
View File
@@ -1,5 +1,5 @@
//! RSG/RSM signature containers: `create_rsg`, `validate_rsg` and
//! `extract_signed_rsg_data` from `RNS/Utilities/rnid.py:400-487@1.6.0`.
//! `extract_signed_rsg_data` from `RNS/Utilities/rnid.py`.
//! Validation follows Python's control flow, including which malformed
//! envelopes are "invalid" and which raise (rnid exits 254 for those).
@@ -391,7 +391,7 @@ pub fn validate_rsg(
}
/// The state `Identity.load_public_key` leaves a public-only identity in
/// (`RNS/Identity.py:1136-1156@1.6.0`).
/// (`RNS/Identity.py`).
enum SigningKey {
/// The X25519 key did not load: `validate` raises.
None,
@@ -445,7 +445,7 @@ pub enum RsmStructure {
Invalid(&'static str),
}
/// Python `check_release_rsm_structure` (`RNS/Utilities/rnid.py:588-600@1.6.0`)
/// Python `check_release_rsm_structure` (`RNS/Utilities/rnid.py`)
/// over the signed data of a valid manifest. `Err` is the exception text.
pub fn check_release_rsm_structure(signed_data: &Value) -> Result<RsmStructure, String> {
let release_meta = py_get(signed_data, "meta")?;
+3 -3
View File
@@ -1,7 +1,7 @@
//! RSM metadata loading for `rnid -S -E`: a port of `rsg_meta_from_file`
//! (`RNS/Utilities/rnid.py:566-575@1.6.0`) over the vendored ConfigObj
//! (`RNS/vendor/configobj.py@1.6.0`: parse, `%(name)s` interpolation,
//! validate, dict) and Validator (`RNS/vendor/validate.py@1.6.0`). Error
//! (`RNS/Utilities/rnid.py`) over the vendored ConfigObj
//! (`RNS/vendor/configobj.py`: parse, `%(name)s` interpolation,
//! validate, dict) and Validator (`RNS/vendor/validate.py`). Error
//! strings are the text of the Python exception rnid prints.
use std::path::Path;
+1 -1
View File
@@ -1,5 +1,5 @@
//! Python `str()`/`repr()` rendering of msgpack values, as printed by
//! `rnid -V <file>.rsm --meta` (`RNS/Utilities/rnid.py:697-723@1.6.0`),
//! `rnid -V <file>.rsm --meta` (`RNS/Utilities/rnid.py`),
//! and of the exceptions the rsg tools print.
use rmpv::Value;
+45 -45
View File
@@ -3,7 +3,7 @@ use crate::announce_validation::{CachedAnnounce, InvalidAnnounce, ValidatedAnnou
use crate::now_f64;
/// Where an inbound packet comes from. Python re-injects held announces and
/// cached packets with `ifac_handled=True` (Interface.py:296, Transport.py:3460),
/// cached packets with `ifac_handled=True` (Interface.py, Transport.py),
/// and its byte counters live in the interface drivers, so neither passes
/// IFAC or counts as received traffic again.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -14,7 +14,7 @@ enum InboundOrigin {
}
/// A transit link proof's verdict; only a bad signature is a protocol
/// violation (Transport.py:2668).
/// violation (Transport.py).
#[derive(PartialEq, Eq)]
enum TransitProof {
Valid,
@@ -24,7 +24,7 @@ enum TransitProof {
/// The app_data upstream remembers: `b""` for a ratchet announce with nothing
/// after the signature, since its `None` threshold ignores the ratchet
/// (Identity.py:815-834), and `None` once a valid stamp strip leaves nothing (:867).
/// (Identity.py), and `None` once a valid stamp strip leaves nothing.
pub(super) fn remembered_app_data(
announce: &rns_identity::announce::AnnounceData,
stamp: &rns_identity::announce::AnnounceStampCheck,
@@ -47,7 +47,7 @@ impl TransportActor {
}
/// An announce the ingress controller held, released for processing; it
/// can be held again (Interface.py:278-297).
/// can be held again (Interface.py).
pub(super) fn on_released_announce(&mut self, announce: crate::ingress::HeldAnnounce) {
self.on_inbound_inner(
crate::messages::InboundPacket {
@@ -62,7 +62,7 @@ impl TransportActor {
}
/// Python `Interface.protocol_violation`, `ifac_violation` and
/// `packet_filter_hit` (Interface.py:327-338).
/// `packet_filter_hit` (Interface.py).
pub(super) fn protocol_violation(&mut self, interface_id: InterfaceId) {
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.protocol_violations = entry.protocol_violations.saturating_add(1);
@@ -70,7 +70,7 @@ impl TransportActor {
}
/// Upstream drops stamp and blackhole rejections silently; anything else
/// is a protocol violation (Transport.py:2046-2051, :2450-2451).
/// is a protocol violation (Transport.py).
fn reject_announce(
&mut self,
header: &rns_wire::header::PacketHeader,
@@ -146,13 +146,13 @@ impl TransportActor {
.record_rx(packet.interface_id, packet.raw.len() as u64);
}
// Transport.py:1990-2010: frames of two bytes or less are protocol
// Transport.py: frames of two bytes or less are protocol
// violations before any IFAC handling.
if packet.raw.len() <= 2 {
self.protocol_violation(packet.interface_id);
return;
}
// Upstream bounds the frame only after IFAC (Transport.py:2014,
// Upstream bounds the frame only after IFAC (Transport.py,
// HW_MTU + ifac_size, the default IFAC size without IFAC).
let clear_limit = if origin == InboundOrigin::CachedPacket {
500
@@ -230,7 +230,7 @@ impl TransportActor {
}
};
// Python 1.3.8 Packet.py:247-248: unpack() rejects on-wire hop counts
// Python 1.3.8 Packet.py: unpack() rejects on-wire hop counts
// >= PATHFINDER_M for every packet type. Checked on the RAW hops byte,
// before the inbound hop adjustment; kept at the inbound boundary so
// locally built packets and vector tooling are unaffected.
@@ -244,7 +244,7 @@ impl TransportActor {
return;
}
// Packet.unpack rejects a zero-length data field (Packet.py:275).
// Packet.unpack rejects a zero-length data field (Packet.py).
if data_offset >= raw.len() {
debug!(
interface_id = packet.interface_id,
@@ -254,7 +254,7 @@ impl TransportActor {
return;
}
// Transport.HOP_LIMITER, on wire hops (Transport.py:2022).
// Transport.HOP_LIMITER, on wire hops (Transport.py).
if parsed.hops >= self.hop_limiter {
trace!(
hops = parsed.hops,
@@ -288,7 +288,7 @@ impl TransportActor {
// A handful of contexts legitimately repeat (keepalives, resource
// transfer frames, channel traffic): they bypass Python's packet
// filter and the hashlist (Transport.py:1635-1640).
// filter and the hashlist (Transport.py).
let skip_hashlist = matches!(
parsed.context,
rns_wire::context::PacketContext::Keepalive
@@ -300,9 +300,9 @@ impl TransportActor {
);
// PLAIN and GROUP packets travel one hop at most and are never
// announced (Transport.py:1642-1666). Checked on wire hops before
// announced (Transport.py). Checked on wire hops before
// the hashlist, so a dropped copy reserves no hash; the shared
// owner already filtered its ingress (:1627).
// owner already filtered its ingress.
if !skip_hashlist
&& !from_shared_owner
&& matches!(
@@ -333,7 +333,7 @@ impl TransportActor {
let Some(ingress) = self.interfaces.get(&packet.interface_id) else {
return;
};
// A relay has no capacity refusal (Transport.py:2331-2375).
// A relay has no capacity refusal (Transport.py).
if self.local_destinations.contains(&parsed.destination_hash)
&& ingress
.packet_capacity
@@ -388,13 +388,13 @@ impl TransportActor {
}
// Destination-type filtering runs after the packet filter and before
// the hash is remembered (Transport.py:2030-2041, :2235).
// the hash is remembered (Transport.py).
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce
&& !self.admit_announce_type(&raw[data_offset..], parsed.hops, packet.interface_id)
{
return;
}
// Transport.py:2044: announce frames above the base MTU.
// Transport.py: announce frames above the base MTU.
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce
&& raw.len() > rns_wire::constants::MTU
{
@@ -405,7 +405,7 @@ impl TransportActor {
if check_hashlist {
self.packet_hashlist.insert(pkt_hash);
}
// Python records PHY stats in `_inbound`, after the packet filter (Transport.py:2192-2209).
// Python records PHY stats in `_inbound`, after the packet filter (Transport.py).
self.record_packet_metrics(pkt_hash, packet_metrics);
parsed.hops = self.adjusted_inbound_hops(parsed.hops, packet.interface_id);
@@ -512,7 +512,7 @@ impl TransportActor {
}
};
// Identity.validate_announce (Identity.py:749-889): the cache, then
// Identity.validate_announce (Identity.py): the cache, then
// the stamp, then the blackhole check, then the signature.
let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
let stamps_enabled = self.stamp_policy.stamps_enabled;
@@ -688,7 +688,7 @@ impl TransportActor {
// Python remembers every freshly validated announce, replays included,
// before it decides whether the path changes; a validation-cache hit
// only re-remembers a destination that was forgotten
// (Identity.py:109-126, :717-727).
// (Identity.py).
match self.recent_announces.entry(header.destination_hash) {
std::collections::hash_map::Entry::Occupied(mut o) if !cache_hit => {
let e = o.get_mut();
@@ -726,7 +726,7 @@ impl TransportActor {
}
}
// Own announces are validated and remembered but route nothing (Transport.py:2453-2454).
// Own announces are validated and remembered but route nothing (Transport.py).
if self.local_destinations.contains(&header.destination_hash) {
debug!("not routing own announce");
return;
@@ -749,7 +749,7 @@ impl TransportActor {
// Same-hop neighbor rebroadcast counts toward the local cap;
// strict hops+1 forward drops our queued copy outright.
// Only HEADER_2 copies come from a rebroadcasting transport node
// (Transport.py:2454); copies heard before our first send count too.
// (Transport.py); copies heard before our first send count too.
if self.is_transport_enabled
&& header.transport_id.is_some()
&& let Some(existing) = self.announce_table.get(&header.destination_hash)
@@ -800,7 +800,7 @@ impl TransportActor {
} else if announce_emitted != path_timebase {
false
} else {
// Transport.py:2522-2532: the same emission heard on a
// Transport.py: the same emission heard on a
// higher-gravity interface replaces the path.
let gravity = |id| self.interfaces.get(&id).map(|entry| entry.gravity);
matches!(
@@ -822,7 +822,7 @@ impl TransportActor {
if should_add {
// Only path-updating announces on interfaces with a rate target
// touch the rate table (Transport.py:2578-2591).
// touch the rate table (Transport.py).
let rate_limit = (header.context != rns_wire::context::PacketContext::PathResponse)
.then(|| self.interfaces.get(&interface_id))
.flatten()
@@ -899,7 +899,7 @@ impl TransportActor {
interface_id,
iface_mode,
);
// Transport.py:2510,2726@1.6.0: a replacement keeps the path's use.
// Transport.py: a replacement keeps the path's use.
entry.used = self
.path_table
.get(&header.destination_hash)
@@ -917,7 +917,7 @@ impl TransportActor {
entry.packet_hash = Some(announce_packet_hash);
if rate_blocked {
// Rate-blocked announces update routing fields only, never
// liveness, and create no entry (Transport.py:2712-2724).
// liveness, and create no entry (Transport.py).
if let Some(existing) = self.path_table.get_mut(&header.destination_hash) {
existing.next_hop = entry.next_hop;
existing.hops = entry.hops;
@@ -953,7 +953,7 @@ impl TransportActor {
}
// Wake any callers waiting on a path for this destination.
self.fire_path_waiters(&header.destination_hash);
// Transport.py:2751-2754@1.6.0.
// Transport.py
self.inflight_path_requests.remove(&header.destination_hash);
if self
@@ -1008,7 +1008,7 @@ impl TransportActor {
let app_data_for_handlers = announce_app_data;
// The desiring interface is unused: the response rebroadcasts once
// everywhere through the announce table (Transport.py:2626-2648).
// everywhere through the announce table (Transport.py).
if is_from_local_client
&& header.context == rns_wire::context::PacketContext::PathResponse
&& self
@@ -1133,7 +1133,7 @@ impl TransportActor {
.path_table
.get_live(&header.destination_hash)
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
// Python 1.3.8 Transport.py:1550-1551: to_local_client also covers
// Python 1.3.8 Transport.py: to_local_client also covers
// proofs whose reverse entry came in from a local client.
let proof_for_local_client = self
.reverse_table
@@ -1172,7 +1172,7 @@ impl TransportActor {
}
// Tunnel synthesis: install the tunnel, and replay its cached paths,
// once the signature verifies (Transport.py:2788-2805).
// once the signature verifies (Transport.py).
if header.destination_hash == tunnel_synth_dest {
if let Some(payload_start) = self.data_payload_offset(raw, header) {
match crate::tunnel::TunnelSynthesisData::unpack(&raw[payload_start..])
@@ -1193,7 +1193,7 @@ impl TransportActor {
self.restore_tunnel_paths(&tunnel_id, interface_id);
}
// Wrong length or a bad signature is a silent drop
// (Transport.py:3067-3084).
// (Transport.py).
None => debug!(interface_id, "invalid tunnel synthesis"),
}
}
@@ -1220,7 +1220,7 @@ impl TransportActor {
);
if self.local_destinations.contains(&header.destination_hash) {
if self.link_packet_on_unbound_interface(header, interface_id) {
// Transport.py:2858-2866: un-claim the hash so the copy arriving
// Transport.py: un-claim the hash so the copy arriving
// over the Link's attached interface is still accepted.
self.packet_hashlist
.remove(&rns_wire::hash::packet_hash(raw, header.flags.header_type));
@@ -1365,7 +1365,7 @@ impl TransportActor {
) {
Ok(attenuated) => attenuated,
// Python cannot re-encode a clamped MTU for a disabled
// mode and counts it (Transport.py:2354-2361).
// mode and counts it (Transport.py).
Err(crate::link_transit::LinkTransitError::UnsupportedTransitModeTransform) => {
self.protocol_violation(interface_id);
return;
@@ -1470,7 +1470,7 @@ impl TransportActor {
// next-hop address, not interface inequality, prevent packet loops.
let mut forwarded =
self.rewrite_forwarded_transport_packet(raw, header, path, to_local_client)?;
// Python 1.3.8 Transport.py:1687: substitute the delta for
// Python 1.3.8 Transport.py: substitute the delta for
// local-client-originated packets leaving the shared instance.
if self.local_hops_delta != 0 && from_local_client && !to_local_client {
forwarded[1] = self.local_hops_delta;
@@ -1510,7 +1510,7 @@ impl TransportActor {
&& self.local_hops_delta != 0
&& header.flags.header_type == rns_wire::flags::HeaderType::Header2)
{
// Python 1.3.8 Transport.py:1613-1619: with the delta active,
// Python 1.3.8 Transport.py: with the delta active,
// HEADER_2 frames delivered to local shared clients get their
// transport headers stripped, same as the one-hop case.
let mut flags = header.flags;
@@ -1708,7 +1708,7 @@ impl TransportActor {
return;
}
// Python re-balances the path from a validly signed proof that
// took a different number of hops (Transport.py:2886-2912).
// took a different number of hops (Transport.py).
if header.hops != link_entry.remaining_hops
&& _interface_id == link_entry.interface_id
&& !link_entry.validated
@@ -1735,7 +1735,7 @@ impl TransportActor {
let outbound_interface = link_entry.interface_id;
let target_interface = link_entry.receiving_interface;
let destination_hash = link_entry.destination_hash;
// Python 1.3.8 Transport.py:1552/2222: instance-local
// Python 1.3.8 Transport.py/2222: instance-local
// links are exempt from delta mangling (1.3.7 eacff56f).
let instance_local_link = self.is_local_client_interface(link_entry.interface_id)
&& self.is_local_client_interface(link_entry.receiving_interface);
@@ -1847,7 +1847,7 @@ impl TransportActor {
// match — a proof on the wrong interface means a routing change or
// a spoof. Older entries without that field route unconditionally.
if self.is_transport_enabled || from_local_client || proof_for_local_client {
// Python 1.3.8 Transport.py:2287: delta for local-client-origin
// Python 1.3.8 Transport.py: delta for local-client-origin
// proofs; proofs headed to local clients exempt (1.3.7 eacff56f).
let proof_hops =
if !from_local_client || proof_for_local_client || self.local_hops_delta == 0 {
@@ -1930,7 +1930,7 @@ impl TransportActor {
};
let from_local_client = self.is_local_client_interface(interface_id);
// Python 1.3.8 Transport.py:1548-1553 (the 1.3.7 eacff56f fix): links
// Python 1.3.8 Transport.py (the 1.3.7 eacff56f fix): links
// between two local clients of this shared instance are exempt from
// delta mangling.
let instance_local_link = self.is_local_client_interface(entry.interface_id)
@@ -1941,7 +1941,7 @@ impl TransportActor {
if !self.is_transport_enabled && !shared_client_path {
return false;
}
// Transport.py:2396-2402: nothing but the proof may cross before validation.
// Transport.py: nothing but the proof may cross before validation.
if !entry.validated {
debug!(
link_id = hex::encode(header.destination_hash),
@@ -2006,7 +2006,7 @@ impl TransportActor {
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
// Python 1.3.8 Transport.py:1731: delta for local-client link
// Python 1.3.8 Transport.py: delta for local-client link
// traffic leaving the instance; instance-local links exempt.
forwarded[1] =
if !from_local_client || instance_local_link || self.local_hops_delta == 0 {
@@ -2038,7 +2038,7 @@ impl TransportActor {
entry.timestamp = now_f64();
}
self.send_to_interface(target_interface, &forwarded);
// Transport.py:2438-2440@1.6.0.
// Transport.py
if let Some(path) = self.path_table.get_mut(&entry.destination_hash) {
path.mark_used();
}
@@ -2124,12 +2124,12 @@ impl TransportActor {
}
}
/// Python's terminus re-balance (Transport.py:2954-2984): the first validly
/// Python's terminus re-balance (Transport.py): the first validly
/// signed proof for a pending local Link ends its pending state and, when
/// its hops differ from the path hops at request time, rewrites the path
/// hops and marks the path responsive.
/// Returns whether the proof goes on to the Link: only with the expected
/// hops, after any re-balance (Transport.py:2988-2992).
/// hops, after any re-balance (Transport.py).
fn rebalance_at_link_terminus(
&mut self,
raw: &[u8],
@@ -2148,7 +2148,7 @@ impl TransportActor {
{
return expected_hops == Some(header.hops);
}
// A valid proof ends the pending state, so a replay cannot re-balance (Transport.py:2954).
// A valid proof ends the pending state, so a replay cannot re-balance (Transport.py).
self.pending_local_link_hops
.remove(&header.destination_hash);
if expected_hops == Some(header.hops) {
@@ -25,7 +25,7 @@ impl TransportActor {
return LinkEndpointBindResult::InterfaceUnavailable;
}
// Link.py:512-513@1.6.0: an initiator binds once the proof validated.
// Link.py: an initiator binds once the proof validated.
if binding.role == crate::messages::LinkEndpointRole::Initiator
&& let Some((destination, _)) = self
.pending_local_link_destinations
+10 -10
View File
@@ -249,9 +249,9 @@ impl TransportActor {
self.process_announce_queues(now);
}
/// Transport.py:1118-1160@1.6.0. A leaf or shared-instance client lingers
/// Transport.py A leaf or shared-instance client lingers
/// never-used paths for 12 minutes, a transport node for 1.75 hours
/// (Transport.py:451-454@1.6.0).
/// (Transport.py).
fn cull_path_table(&mut self, now: f64) {
let linger = if !self.is_transport_enabled || self.shared_instance_client_mode {
UNUSED_PATH_LINGER_LEAF
@@ -283,7 +283,7 @@ impl TransportActor {
blocked_interface: Option<InterfaceId>,
now: f64,
) -> bool {
// Transport.py:1420-1426@1.6.0: a destination is queued once.
// Transport.py: a destination is queued once.
if self
.pending_discovery_prs
.iter()
@@ -324,7 +324,7 @@ impl TransportActor {
};
self.last_discovery_pr_tx = now;
// Transport.py:4061-4080: one tag, stamped once when stamping is on,
// Transport.py: one tag, stamped once when stamping is on,
// on every interface but the blocked one.
let request_tag = rns_crypto::random::random_bytes(16);
self.forward_path_request(
@@ -432,7 +432,7 @@ impl TransportActor {
self.last_held_announce_check = 0.0;
}
/// Python `Interface.process_announce_queue` (Interface.py:410-451):
/// Python `Interface.process_announce_queue` (Interface.py):
/// drop stale entries, send the fewest-hops, oldest entry, and consume it
/// whatever the send outcome. Python re-arms a timer at each `wait_time`;
/// here each tick sends every entry whose slot has passed, chaining slots
@@ -559,7 +559,7 @@ impl TransportActor {
.map_or(f64::INFINITY, |entry| entry.announce_allowed_at)
}
/// Python's interface job (Transport.py:1329-1337): re-evaluate both burst
/// Python's interface job (Transport.py): re-evaluate both burst
/// limiters, then release at most one held announce per interface.
fn process_held_announces(&mut self, _now: f64) {
let iface_ids: Vec<InterfaceId> = self.interfaces.keys().copied().collect();
@@ -577,7 +577,7 @@ impl TransportActor {
"releasing held announce"
);
// Released announces re-enter as ingress limited (Interface.py:300).
// Released announces re-enter as ingress limited (Interface.py).
self.inbound_rx.push_ingress_limited(
&self.inbound_queues,
crate::inbound_queues::Queued::ReleasedAnnounce(announce),
@@ -675,7 +675,7 @@ impl TransportActor {
);
}
// Identity.py:466-470: expire remembered ratchets past RATCHET_EXPIRY.
// Identity.py: expire remembered ratchets past RATCHET_EXPIRY.
let mut expired = 0usize;
for announce in self.recent_announces.values_mut() {
if announce.ratchet.is_some() && announce.live_ratchet(now).is_none() {
@@ -833,7 +833,7 @@ mod cleanup_tests {
assert!(actor.recent_announces.is_empty());
}
/// Transport.py:1420-1426@1.6.0: a destination already waiting in the
/// Transport.py: a destination already waiting in the
/// discovery queue is not queued again.
#[test]
fn discovery_queue_holds_a_destination_once() {
@@ -844,7 +844,7 @@ mod cleanup_tests {
assert_eq!(actor.pending_discovery_prs.len(), 2);
}
/// Transport.py:1022-1029, 1249-1253@1.6.0: one cull pass removes every
/// Transport.py: one cull pass removes every
/// reverse entry past REVERSE_TIMEOUT, with no batch cap.
#[test]
fn one_cull_removes_every_stale_reverse_entry() {
+61 -61
View File
@@ -124,7 +124,7 @@ pub struct TransportActor {
/// Python's interface traffic count and top-level stats counters.
traffic_count: rpc::TrafficCount,
/// Python's `local_client_rssi_cache`, `_snr_cache` and `_q_cache`: one
/// 512-entry list per metric, first match wins (Transport.py:320-324).
/// 512-entry list per metric, first match wins (Transport.py).
pub packet_rssi_cache: VecDeque<([u8; 32], f32)>,
pub packet_snr_cache: VecDeque<([u8; 32], f32)>,
pub packet_q_cache: VecDeque<([u8; 32], f32)>,
@@ -151,7 +151,7 @@ pub struct TransportActor {
/// App names of registered destinations; link-id channel aliases are not here.
registered_destination_names: HashMap<[u8; 16], String>,
/// RESOURCE_PRF packets this instance sent, which Python force-caches
/// (Resource.py:775-777), with the time each was stored.
/// (Resource.py), with the time each was stored.
proof_cache: HashMap<[u8; 32], (Bytes, f64)>,
proof_cache_order: VecDeque<[u8; 32]>,
/// Duplex routes for Links whose initiator and responder are registered
@@ -162,7 +162,7 @@ pub struct TransportActor {
// Only active caller-owned temporary destinations can allocate an attempt.
pending_local_link_requests: HashMap<[u8; 16], HashMap<InterfaceId, crate::InterfaceOwnerId>>,
/// Destination and path hops of each pending local Link request, Python's
/// `link.expected_hops` (Link.py:307), until a proof re-balances it.
/// `link.expected_hops` (Link.py), until a proof re-balances it.
pending_local_link_hops: HashMap<[u8; 16], ([u8; 16], Option<u8>)>,
/// Destination of each sent local Link request, with the route it was
/// sent on, until the Link is bound (established) or abandoned; Python's
@@ -204,7 +204,7 @@ pub struct TransportActor {
last_tables_cull: f64,
/// Last never-used path pool check; starts at construction so the first
/// check waits one interval (Transport.py:516@1.6.0).
/// check waits one interval (Transport.py).
pub path_pool_last_checked: f64,
/// Destinations with a path request admitted and not yet answered
/// (Python `inflight_path_requests`), with the admission time.
@@ -260,9 +260,9 @@ pub struct TransportActor {
/// public table mutation does not publish a snapshot; a poisoned snapshot
/// lock prevents publication.
pub blackholed_snapshot: Arc<std::sync::RwLock<HashSet<[u8; 16]>>>,
/// Per-packet announce validation results (Identity.py:676-715).
/// Per-packet announce validation results (Identity.py).
pub announce_validation: crate::announce_validation::AnnounceValidationCache,
/// Path-request stamp worker and generated-stamp cache (Transport.py:209-217).
/// Path-request stamp worker and generated-stamp cache (Transport.py).
pub pr_stamper: crate::pr_stamper::PathRequestStamper,
/// Whether this actor currently uses a shared-instance peer. Routing policy
@@ -369,7 +369,7 @@ pub struct RecentAnnounce {
/// without valid payloads are rejected.
pub name_hash: [u8; 10],
/// Network stamp from the announce extension, kept even when it is below
/// the required value (Identity.py:109-126).
/// the required value (Identity.py).
pub stamp: Option<[u8; rns_identity::stamps::NETWORK_STAMP_SIZE]>,
/// Stamp value; 0 for an unstamped announce, as upstream stores it.
pub stamp_value: f64,
@@ -379,7 +379,7 @@ pub struct RecentAnnounce {
impl RecentAnnounce {
/// Remember a ratchet carried by an announce. Re-receiving the same ratchet
/// keeps its first receive time (Identity.py:535-551, Storage.py:429-451).
/// keeps its first receive time (Identity.py, Storage.py).
pub(crate) fn remember_ratchet(&mut self, ratchet: Option<[u8; 32]>, now: f64) {
if let Some(ratchet) = ratchet
&& self.ratchet != Some(ratchet)
@@ -472,7 +472,7 @@ impl TransportActor {
}
/// As [`Self::new_with_capacity`], with per-class inbound queue lengths
/// for registered interfaces (`qlen_in_*`, Transport.py:420-427).
/// for registered interfaces (`qlen_in_*`, Transport.py).
pub fn new_with_queues(
channel_cap: usize,
hashlist_cap: usize,
@@ -703,7 +703,7 @@ impl TransportActor {
}
/// Path requests from an interface in a path-request burst wait in the
/// ingress-limited queue, behind every other class (Transport.py:2133-2134).
/// ingress-limited queue, behind every other class (Transport.py).
fn handle_inbound_event(
&mut self,
class: crate::inbound_queues::TrafficClass,
@@ -724,7 +724,7 @@ impl TransportActor {
.push_ingress_limited(&self.inbound_queues, Queued::Message(msg));
}
Queued::Message(msg) => {
// Python carries the class on the packet into path_request (Transport.py:3761).
// Python carries the class on the packet into path_request (Transport.py).
self.processing_ingress_limited = class == TrafficClass::IngressLimited;
self.handle_message(*msg);
self.processing_ingress_limited = false;
@@ -1195,7 +1195,7 @@ impl TransportActor {
existing.owner.retire();
}
self.path_table.drop_all_via(id);
// A new interface starts without a tunnel (Interface.py:127).
// A new interface starts without a tunnel (Interface.py).
self.void_tunnel_interface(id);
self.link_table.remove_interface(id);
self.retire_recursive_discovery_interface(id);
@@ -1318,7 +1318,7 @@ impl TransportActor {
return;
}
// Local Links stay out of the transit link table, which Python
// reserves for relayed Links (Transport.py:3264-3273).
// reserves for relayed Links (Transport.py).
// Link-addressed packets (LRRTT, Resource, Keepalive, …) use
// link_id as their destination_hash, not the original
@@ -1380,7 +1380,7 @@ impl TransportActor {
.is_some_and(|entry| entry.role == InterfaceRole::SharedInstancePeer)
}
/// Python 1.3.8 Transport.should_apply_delta (Transport.py:1356-1359):
/// Python 1.3.8 Transport.should_apply_delta (Transport.py):
/// mangle only locally-originated (hops==0) non-PLAIN/GROUP packets, never
/// when this node is itself a shared-instance client, and never on
/// local-client / shared-instance edges.
@@ -1398,7 +1398,7 @@ impl TransportActor {
&& !self.is_shared_instance_peer_interface(interface_id)
}
/// Python 1.3.8 Transport.mangle_hops (Transport.py:1362-1365): rewrite
/// Python 1.3.8 Transport.mangle_hops (Transport.py): rewrite
/// the hops byte to the per-boot delta. `transport_insert` additionally
/// re-frames a HEADER_1 announce as HEADER_2|TRANSPORT carrying this
/// node's transport identity hash (packet grows by 17 bytes).
@@ -1487,7 +1487,7 @@ impl TransportActor {
self.state_dirty = true;
}
/// Python 1.3.8 Transport.py:234-238: when transport is disabled and
/// Python 1.3.8 Transport.py: when transport is disabled and
/// `static_transport_identity` is unset (the default), the wire-facing
/// transport identity becomes a fresh per-boot identity while the
/// persisted one is retained as `internal_identity_hash`
@@ -1516,7 +1516,7 @@ impl TransportActor {
/// Rebuild the shared blackhole snapshot from the authoritative table.
/// Called after every blackhole-table mutation; TTL-expired entries drop
/// out here and on the periodic cull (Python parity: the 60s expiry job,
/// Transport.py:986-1002).
/// Transport.py).
fn publish_blackhole_snapshot(&mut self) {
// Identity._reset_validation_caches on every blackhole change.
self.announce_validation.reset();
@@ -1548,7 +1548,7 @@ impl TransportActor {
}
/// Python `shared_connection_reappeared`: each registered destination
/// announces as a path response (Transport.py:4203-4207); owners of
/// announces as a path response (Transport.py); owners of
/// non-SINGLE destinations refuse to build an announce.
fn request_announces_from_local_destinations(&mut self) {
let destinations: Vec<(
@@ -1712,7 +1712,7 @@ impl TransportActor {
}
/// Reap waiters whose caller gave up. The caller owns the deadline, as
/// Python `await_path(timeout)` does (Transport.py:3666-3683).
/// Python `await_path(timeout)` does (Transport.py).
fn expire_path_waiters(&mut self, _now: f64) {
self.path_waiters.retain(|_, waiters| {
waiters.retain(|(reply, _)| !reply.is_closed());
@@ -1773,7 +1773,7 @@ impl TransportActor {
}
}
/// Transport.py:839-866@1.6.0: a Link that was never established expires
/// Transport.py: a Link that was never established expires
/// the path on a non-transport instance and, unless this is a
/// shared-instance client, queues a throttled rediscovery request.
/// Unlike upstream, a route newer than the one the request used is kept.
@@ -1806,8 +1806,8 @@ impl TransportActor {
}
}
/// Transport.py:3632-3648@1.6.0, with the lifetime of the interface the
/// path was learned on (:3616-3621).
/// Transport.py, with the lifetime of the interface the
/// path was learned on.
pub(super) fn mark_path_responsive(&mut self, dest: &[u8; 16]) -> bool {
let Some(interface_id) = self.path_table.get(dest).map(|path| path.interface_id) else {
return false;
@@ -1962,7 +1962,7 @@ impl TransportActor {
match entry.tx.try_send(data) {
Ok(()) => {
self.count_tx_packet();
// Python counts every transmitted announce (Transport.py:1827).
// Python counts every transmitted announce (Transport.py).
if rns_wire::header::PacketHeader::unpack(raw).is_ok_and(|(header, _)| {
header.flags.packet_type == rns_wire::flags::PacketType::Announce
}) {
@@ -2066,7 +2066,7 @@ impl TransportActor {
}
}
/// Transport.prioritize_interfaces (Transport.py:704-706): fastest first,
/// Transport.prioritize_interfaces (Transport.py): fastest first,
/// registration order among equal bitrates.
fn prioritized_interface_ids(&self) -> Vec<InterfaceId> {
let mut ids: Vec<InterfaceId> = self.interfaces.keys().copied().collect();
@@ -2088,11 +2088,11 @@ impl TransportActor {
.into_iter()
.filter(|id| {
let entry = &self.interfaces[id];
// Transport.py:1676: broadcast only where OUT and online.
// Transport.py: broadcast only where OUT and online.
except != Some(*id) && entry.direction.outbound && !offline_for_send(entry)
})
.collect();
// Python 1.3.8 Transport.py:1342-1344: locally-originated non-announce
// Python 1.3.8 Transport.py: locally-originated non-announce
// packets get the per-boot hops delta, decided per egress interface.
let delta_header = (self.local_hops_delta != 0)
.then(|| rns_wire::header::PacketHeader::unpack(raw).ok())
@@ -2133,7 +2133,7 @@ impl TransportActor {
return false;
}
// Python 1.3.8 Transport.py:1210-1240 hoists the instance-local check
// Python 1.3.8 Transport.py hoists the instance-local check
// and the announce's next-hop (learned-from) interface.
// `from_iface_mode`: None = no live path; Some(None) = path via an
// unregistered interface (Python's mode-less hasattr case);
@@ -2150,7 +2150,7 @@ impl TransportActor {
.is_some_and(|i| i.announces_to_internal == Some(true));
// Mode-independent gate: a non-local announce whose next-hop interface
// doesn't exist is never rebroadcast (Transport.py:1216-1218).
// doesn't exist is never rebroadcast (Transport.py).
if !local && from_iface_mode.is_none() {
pathing!(
dest = hex::encode(destination_hash),
@@ -2161,7 +2161,7 @@ impl TransportActor {
}
// Per-interface announces_from_internal opt-out for internal-origin
// announces; checked before the egress-mode gates (Transport.py:1220).
// announces; checked before the egress-mode gates (Transport.py).
if !local
&& !entry.announces_from_internal
&& from_iface_mode == Some(Some(InterfaceMode::Internal))
@@ -2179,7 +2179,7 @@ impl TransportActor {
InterfaceMode::Internal => {
// Internal egress relays everything except mode-less-origin
// announces and, unless the origin sets announces_to_internal,
// boundary-origin ones (Transport.py:1706-1714@1.6.0).
// boundary-origin ones (Transport.py).
local
|| match from_iface_mode {
Some(None) => false,
@@ -2229,7 +2229,7 @@ impl TransportActor {
.collect();
let mut accepted = false;
for id in ids {
// Python 1.3.8 Transport.py:1345: delta-mangled HEADER_1 announces
// Python 1.3.8 Transport.py: delta-mangled HEADER_1 announces
// are re-framed as HEADER_2|TRANSPORT with our transport identity.
let sent = match &header {
Some(h) if self.should_apply_delta(h, id) => {
@@ -2348,8 +2348,8 @@ impl TransportActor {
}
/// `None` when the cached announce fails to parse — Python 1.3.8
/// Transport.py:2984 treats that as a cache miss and never emits the raw
/// bytes (unpack also rejects hops >= PATHFINDER_M, Packet.py:247-248).
/// Transport.py treats that as a cache miss and never emits the raw
/// bytes (unpack also rejects hops >= PATHFINDER_M, Packet.py).
fn path_response_from_cached_announce(
&self,
cached_raw: &[u8],
@@ -2474,7 +2474,7 @@ fn offline_for_send(entry: &InterfaceEntry) -> bool {
entry.role != InterfaceRole::LocalClient && interface_marked_offline(entry)
}
/// Seconds until the next capped announce may leave (Interface.py:428-430).
/// Seconds until the next capped announce may leave (Interface.py).
fn announce_wait_time(entry: &InterfaceEntry, len: usize) -> f64 {
(len as f64 * 8.0 / entry.bitrate as f64) / entry.announce_cap
}
@@ -2521,7 +2521,7 @@ fn rand_window() -> f64 {
r * PATHFINDER_RW
}
/// Python `path_request` search decision (Transport.py:3774-3784@1.6.0):
/// Python `path_request` search decision (Transport.py):
/// `None` means no search, `Some(None)` a search on every interface, and
/// `Some(Some(modes))` a search limited to those interface modes.
fn path_search_modes(
@@ -2531,7 +2531,7 @@ fn path_search_modes(
if recursive_prs || mode_discovers_unknown_paths(mode) {
Some(None)
} else if mode == InterfaceMode::Boundary {
// Interface.py:56@1.6.0 BOUNDARY_SEARCH_MODES.
// Interface.py BOUNDARY_SEARCH_MODES.
Some(Some(&[InterfaceMode::Boundary, InterfaceMode::Gateway]))
} else {
None
@@ -2539,7 +2539,7 @@ fn path_search_modes(
}
fn mode_discovers_unknown_paths(mode: InterfaceMode) -> bool {
// Python 1.3.8 Interface.py:55 DISCOVER_PATHS_FOR.
// Python 1.3.8 Interface.py DISCOVER_PATHS_FOR.
matches!(
mode,
InterfaceMode::AccessPoint
@@ -7847,7 +7847,7 @@ mod tests {
let dest_hash = [0xAA; 16];
let next_hop = [0xBB; 16];
// Transport.py:1659-1664: a one-hop neighbour is sent the raw packet.
// Transport.py: a one-hop neighbour is sent the raw packet.
let path_entry =
crate::path_table::PathEntry::new(Some(next_hop), 1, 1, InterfaceMode::Gateway);
actor.path_table.insert(dest_hash, path_entry);
@@ -8360,7 +8360,7 @@ mod tests {
);
}
/// Python `Transport._outbound` (Transport.py:1746-1791): a capped
/// Python `Transport._outbound` (Transport.py): a capped
/// rebroadcast leaves at once on an empty queue and opens the
/// `tx_time / announce_cap` window; the next one queues behind it and
/// `process_announce_queues` releases it only once the window passes.
@@ -8397,7 +8397,7 @@ mod tests {
assert!(actor.interfaces[&1].announce_queue.is_empty());
}
/// Python 1.3.8 Transport.py:1286-1308 keeps one queued announce per
/// Python 1.3.8 Transport.py keeps one queued announce per
/// destination and replaces it only when the wire emission time advances.
#[test]
fn rebroadcast_queue_coalesces_destination_to_freshest_announce() {
@@ -8574,7 +8574,7 @@ mod tests {
);
}
// Python 1.3.8 Transport.py:234-238: transport disabled + default config
// Python 1.3.8 Transport.py: transport disabled + default config
// swaps the wire-facing identity to a per-boot ephemeral one, keeping the
// persisted hash as the internal identity.
#[test]
@@ -8649,7 +8649,7 @@ mod tests {
assert_eq!(actor.ephemeral_identity_hash, None);
}
// ---- local_hops_delta (Python 1.3.8 Transport.py:1356-1365, 1.3.7
// ---- local_hops_delta (Python 1.3.8 Transport.py.3.7
// eacff56f instance-local exclusions) ----
fn make_data_packet_with_dest_type(
@@ -8711,7 +8711,7 @@ mod tests {
assert_eq!(&sent[2..], &raw[2..]);
while rx.try_recv().is_ok() {} // drain the automatic path request
// PLAIN and GROUP destinations are excluded (Transport.py:1358).
// PLAIN and GROUP destinations are excluded (Transport.py).
for dest_type in [
rns_wire::flags::DestinationType::Plain,
rns_wire::flags::DestinationType::Group,
@@ -8784,7 +8784,7 @@ mod tests {
let (entry, mut rx) = make_test_interface("iface1");
actor.interfaces.insert(1, entry);
// Transport-wrapped send (Transport.py:1153): hops byte = delta.
// Transport-wrapped send (Transport.py): hops byte = delta.
let dest_a = [0x31; 16];
actor.path_table.insert(
dest_a,
@@ -8803,7 +8803,7 @@ mod tests {
assert_eq!(header.transport_id, Some([0xBB; 16]));
assert_eq!(header.hops, 3, "wrapped send must carry the delta");
// Direct send (Transport.py:1186-1187): mangle_hops.
// Direct send (Transport.py): mangle_hops.
let dest_b = [0x32; 16];
actor.path_table.insert(
dest_b,
@@ -8863,7 +8863,7 @@ mod tests {
#[test]
fn local_hops_delta_link_table_substitution_and_instance_local_exemption() {
// Shared-instance host forwarding link traffic for a local client
// (Transport.py:1731).
// (Transport.py).
let (mut actor, _tx) = TransportActor::new();
actor.local_hops_delta = 6;
@@ -8953,7 +8953,7 @@ mod tests {
#[test]
fn local_hops_delta_lrproof_transit_exclusions() {
// Destination is a local client, initiator is external: the proof
// leaving the instance gets the delta (Transport.py:2222).
// leaving the instance gets the delta (Transport.py).
let (mut actor, _tx) = TransportActor::new();
actor.local_hops_delta = 6;
actor.is_transport_enabled = true;
@@ -9051,7 +9051,7 @@ mod tests {
#[test]
fn local_hops_delta_reverse_proof_exclusions() {
// Proof originated by a local client heading to an external requester
// gets the delta (Transport.py:2287).
// gets the delta (Transport.py).
let (mut actor, _tx) = TransportActor::new();
actor.local_hops_delta = 6;
actor.is_transport_enabled = true;
@@ -9103,7 +9103,7 @@ mod tests {
#[test]
fn local_hops_delta_strips_transport_header_on_local_client_delivery() {
// Transport.py:1613-1619: with the delta active, HEADER_2 frames
// Transport.py: with the delta active, HEADER_2 frames
// delivered to a local shared client lose their transport headers.
let (mut actor, _tx) = TransportActor::new();
actor.local_hops_delta = 6;
@@ -9149,7 +9149,7 @@ mod tests {
}
// Shared snapshot consumed by the runtime link layer for the Python 1.3.8
// Link.py:966-968 blackholed-identity link teardown.
// Link.py blackholed-identity link teardown.
#[test]
fn blackhole_snapshot_tracks_rpc_mutations() {
let (mut actor, _tx) = TransportActor::new();
@@ -10076,7 +10076,7 @@ mod tests {
);
}
/// Python 1.3.8 Packet.py:247-248: raw hops byte >= PATHFINDER_M is
/// Python 1.3.8 Packet.py: raw hops byte >= PATHFINDER_M is
/// malformed for every packet type; 127 is the maximum valid value.
#[test]
fn inbound_hop_count_at_or_above_max_is_dropped_for_all_packet_types() {
@@ -10560,7 +10560,7 @@ mod tests {
else {
panic!("receipt not delivered");
};
// Packet.py:505,529@1.6.0: the receipt keeps the proof packet.
// Packet.py: the receipt keeps the proof packet.
assert_eq!(
proof_hash,
Some(rns_wire::hash::packet_hash(
@@ -10651,7 +10651,7 @@ mod tests {
);
}
/// Python 1.3.8 Transport.py:1216-1218: mode-independent block when the
/// Python 1.3.8 Transport.py: mode-independent block when the
/// destination is not instance-local and no next-hop interface exists.
#[test]
fn announce_broadcast_blocked_without_next_hop_interface_unless_local() {
@@ -10679,7 +10679,7 @@ mod tests {
);
}
/// Python 1.3.8 Transport.py:1220-1236: internal-mode egress and
/// Python 1.3.8 Transport.py: internal-mode egress and
/// announces_from_internal origin gating.
#[test]
fn internal_mode_announce_gating_matches_python_138() {
@@ -10715,7 +10715,7 @@ mod tests {
"full egress relays boundary-origin announces"
);
// Transport.py:1711@1.6.0: a boundary origin with announces_to_internal
// Transport.py: a boundary origin with announces_to_internal
// set passes internal egress.
actor.interfaces.get_mut(&1).unwrap().announces_to_internal = Some(true);
actor.broadcast_announce_on_interfaces(&raw_b, None);
@@ -10767,7 +10767,7 @@ mod tests {
);
}
/// Python 1.3.8 Transport.py:1219-1221: announces_from_internal=False on
/// Python 1.3.8 Transport.py: announces_from_internal=False on
/// the egress interface blocks internal-origin announces, ordered before
/// the egress-mode gates.
#[test]
@@ -10815,9 +10815,9 @@ mod tests {
);
}
/// Python 1.3.8 Transport.py:2946-2947 (commit 03ddb082): recursive_prs
/// Python 1.3.8 Transport.py (commit 03ddb082): recursive_prs
/// forces unknown-path discovery independent of interface mode; Internal
/// joins DISCOVER_PATHS_FOR (Interface.py:55).
/// joins DISCOVER_PATHS_FOR (Interface.py).
#[test]
fn recursive_prs_option_forces_unknown_path_discovery() {
assert!(mode_discovers_unknown_paths(InterfaceMode::Internal));
@@ -10846,7 +10846,7 @@ mod tests {
);
}
/// Python 1.3.8 Transport.py:2685-2697: next_hop/next_hop_interface fall
/// Python 1.3.8 Transport.py: next_hop/next_hop_interface fall
/// back to the transport identity / shared-instance interface for
/// instance-local destinations.
#[test]
@@ -10939,7 +10939,7 @@ mod tests {
));
}
/// Python 1.3.8 Transport.py:2984: a cached announce that fails to unpack
/// Python 1.3.8 Transport.py: a cached announce that fails to unpack
/// is a miss — no path response is synthesized from raw bytes.
#[test]
fn path_response_from_unparseable_cached_announce_is_a_miss() {
@@ -11317,7 +11317,7 @@ mod tests {
}
/// Python 1.5 counts a path request only once its tag passes the
/// duplicate gate (Transport.py:1847-1858), where 1.4 counted every one.
/// duplicate gate (Transport.py), where 1.4 counted every one.
#[test]
fn duplicate_path_requests_do_not_count_toward_ingress_frequency() {
let (mut actor, _tx) = TransportActor::new();
+33 -33
View File
@@ -4,15 +4,15 @@ use crate::now_f64;
/// Bound on the in-memory resource proof cache; Python keeps one file per proof.
const PROOF_CACHE_MAX_ENTRIES: usize = 1024;
/// Path-request lengths (Transport.py:3975-3980).
/// Path-request lengths (Transport.py).
pub(super) const PR_LEGACY_LENGTH: usize = 32;
pub(super) const PR_LENGTH: usize = 48;
pub(super) const PR_STAMPED_LENGTH: usize = 64;
pub(super) const PR_EXT_HEADER_LENGTH: usize = 2;
pub(super) const PR_EXT_PAYLOAD_LENGTH: usize = 16;
/// Transport.validate_pr_stamp (Transport.py:4011-4016): material `dst || tag`.
/// `0xC1 0x00` followed by the stamp (Transport.py:3720, :4049).
/// Transport.validate_pr_stamp (Transport.py): material `dst || tag`.
/// `0xC1 0x00` followed by the stamp (Transport.py).
fn stamped_path_request_ext(
stamp: &crate::pr_stamper::PathRequestStamp,
) -> [u8; PR_EXT_PAYLOAD_LENGTH] {
@@ -22,7 +22,7 @@ fn stamped_path_request_ext(
ext
}
/// Transport.py:3930-3936: marks a relayed unstamped request from a stamping node.
/// Transport.py: marks a relayed unstamped request from a stamping node.
const LENIENT_PATH_REQUEST_EXT: [u8; PR_EXT_PAYLOAD_LENGTH] = {
let mut ext = [0u8; PR_EXT_PAYLOAD_LENGTH];
ext[0] = rns_identity::announce::ANNOUNCE_EXT_MARKER;
@@ -219,11 +219,11 @@ impl TransportActor {
"outbound: routed via path"
);
// Python 1.3.8 Transport.py:1153/1186: local_hops_delta
// Python 1.3.8 Transport.py/1186: local_hops_delta
// replaces the zero hops byte on the way out.
let apply_delta = self.should_apply_delta(&parsed, target_interface);
// Transport.py:1625-1654: wrap beyond one hop, or at one hop
// Transport.py: wrap beyond one hop, or at one hop
// when this node sits behind a shared instance.
let wrap = path_hops > 1 || (path_hops == 1 && self.is_shared_instance);
let sent = if let Some(next_hop) = path_next_hop.filter(|_| wrap) {
@@ -256,7 +256,7 @@ impl TransportActor {
);
self.send_to_interface(target_interface, &new_raw)
} else {
// Transport.py:1626,1646: an already-wrapped packet is not sent.
// Transport.py: an already-wrapped packet is not sent.
false
}
} else if apply_delta {
@@ -266,7 +266,7 @@ impl TransportActor {
self.send_to_interface(target_interface, &request.raw)
};
// Transport.py:1618@1.6.0: traffic marks use, never liveness.
// Transport.py: traffic marks use, never liveness.
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
path.mark_used();
}
@@ -300,7 +300,7 @@ impl TransportActor {
false
}
};
// Packet.py:309-311: a packet that went nowhere keeps no receipt.
// Packet.py: a packet that went nowhere keeps no receipt.
if !sent && let Some(hash) = new_receipt {
self.receipt_table.remove(&hash);
}
@@ -317,7 +317,7 @@ impl TransportActor {
if let Some(sent) = self.dispatch_local_link_attached(&request, interface_id) {
return sent;
}
// Transport.py:1672-1676: an attached interface is used only while online.
// Transport.py: an attached interface is used only while online.
if self
.interfaces
.get(&interface_id)
@@ -358,7 +358,7 @@ impl TransportActor {
let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
self.packet_hashlist.insert(pkt_hash);
// Python's outbound applies should_apply_delta on attached-
// interface sends too (Transport.py:1342-1345).
// interface sends too (Transport.py).
if self.should_apply_delta(&parsed, interface_id) {
let transport_insert = parsed.flags.packet_type
== rns_wire::flags::PacketType::Announce
@@ -498,7 +498,7 @@ impl TransportActor {
}
/// Python's packet cache holds only the resource proofs this instance
/// sent; files expire after `PATH_TIMEOUT` (Reticulum.py:1438-1446).
/// sent; files expire after `PATH_TIMEOUT` (Reticulum.py).
pub(super) fn cache_proof(&mut self, packet_hash: [u8; 32], raw: Bytes) {
if self
.proof_cache
@@ -514,7 +514,7 @@ impl TransportActor {
}
}
/// Python `Transport.get_cached_packet(packet_hash)` (Transport.py:3398-3437).
/// Python `Transport.get_cached_packet(packet_hash)` (Transport.py).
fn cached_proof(&self, packet_hash: &[u8; 32]) -> Option<Bytes> {
self.proof_cache
.get(packet_hash)
@@ -531,9 +531,9 @@ impl TransportActor {
/// A CACHE_REQUEST for one of our established Links is answered by
/// re-sending the cached packet's data on that Link, and dropped on a
/// miss (Transport.py:2845-2855). Any other request replays a cache hit
/// miss (Transport.py). Any other request replays a cache hit
/// through inbound when transport handling applies, and otherwise returns
/// false so normal processing continues (Transport.py:2271-2287, :3439-3452).
/// false so normal processing continues (Transport.py).
pub(super) fn handle_cache_request(
&mut self,
raw: &[u8],
@@ -588,7 +588,7 @@ impl TransportActor {
}
/// Python `Transport.cache_request`: replay a local hit, otherwise send
/// a CACHE_REQUEST to the destination (Transport.py:3455-3464).
/// a CACHE_REQUEST to the destination (Transport.py).
pub(super) fn send_cache_request(&mut self, packet_hash: [u8; 32], destination_hash: [u8; 16]) {
if let Some(cached) = self.cached_proof(&packet_hash) {
self.replay_cached_packet(cached);
@@ -653,7 +653,7 @@ impl TransportActor {
let is_from_local_client = self.is_local_client_interface(interface_id);
// Transport.py:2071-2086 and parse_path_request (:3982-4005).
// Transport.py and parse_path_request.
if data.len() > PR_STAMPED_LENGTH {
self.protocol_violation(interface_id);
return;
@@ -693,7 +693,7 @@ impl TransportActor {
trace!(dest = %hex::encode(requested_dest), "ignoring duplicate path request");
return;
}
// Transport.py:2099-2129: the flags byte is not consulted, so the
// Transport.py: the flags byte is not consulted, so the
// lenient 0xC1 0xFF marker fails like any invalid stamp.
if self.stamp_policy.stamps_enabled {
let required_value = self.interface_pr_cost(interface_id);
@@ -722,11 +722,11 @@ impl TransportActor {
}
}
// Python counts a path request once its tag and stamp pass these gates
// (Transport.py:2088-2131).
// (Transport.py).
self.record_interface_event(interface_id, InterfaceEvent::ReceivedPathRequest, raw_len);
self.count_transport_event(InterfaceEvent::ReceivedPathRequest);
// Transport.py:2136-2158@1.6.0: a request for a destination already
// Transport.py: a request for a destination already
// in flight joins the waiting requesters instead of being processed.
if self.inflight_path_requests.contains_key(&requested_dest) {
// A leaf answers batched requesters only for its local clients;
@@ -795,7 +795,7 @@ impl TransportActor {
&& path.interface_id == interface_id;
if requestor_is_next_hop || same_roaming_interface {
// Transport.py:3962-3969@1.6.0: answered, even when declined.
// Transport.py: answered, even when declined.
self.inflight_path_requests.remove(&requested_dest);
}
if requestor_is_next_hop {
@@ -818,7 +818,7 @@ impl TransportActor {
.and_then(|hash| self.cached_announce_raw(&hash))
.map(|raw| (path.hops, raw));
if let Some((hops, raw)) = cached_raw {
// Python 1.3.8 Transport.py:2984: unparseable cached announce
// Python 1.3.8 Transport.py: unparseable cached announce
// aborts the answer entirely (no fall-through to discovery).
let Some(response) =
self.path_response_from_cached_announce(&raw, requested_dest, hops)
@@ -872,7 +872,7 @@ impl TransportActor {
}
}
// Python 1.3.8 Transport.py:2946-2947: recursive_prs forces discovery
// Python 1.3.8 Transport.py: recursive_prs forces discovery
// independent of interface mode (flag checked first).
let search = self
.interfaces
@@ -908,7 +908,7 @@ impl TransportActor {
return;
}
// Transport.py:3893-3897: never reached while enforcement drops
// Transport.py: never reached while enforcement drops
// unstamped requests above.
if ext.is_none() && self.stamp_policy.stamps_enforced {
tracing::error!(
@@ -952,7 +952,7 @@ impl TransportActor {
}
}
/// Transport.py:3930-3936, :3955-3956: a stamping node relays someone
/// Transport.py: a stamping node relays someone
/// else's unstamped request with the lenient marker instead of a stamp.
fn lenient_relay_ext(
&self,
@@ -964,7 +964,7 @@ impl TransportActor {
}
}
/// Transport.py:3699-3704: destination, transport id, tag, then any
/// Transport.py: destination, transport id, tag, then any
/// received extension unchanged.
fn build_path_request_packet(
&self,
@@ -1020,7 +1020,7 @@ impl TransportActor {
self.send_path_request_ext(destination_hash, interface_id, tag, None, recursive);
}
/// Python `request_path` on one interface (Transport.py:3685-3745): a
/// Python `request_path` on one interface (Transport.py): a
/// supplied extension is sent unchanged; otherwise, under `stamp_prs`, a
/// cached stamp is appended or generation is queued and nothing is sent yet.
pub(super) fn send_path_request_ext(
@@ -1045,7 +1045,7 @@ impl TransportActor {
}
/// Resolve the request tag and extension. `None` means the request waits
/// for the stamper (Transport.py:3707-3720).
/// for the stamper (Transport.py).
#[allow(clippy::type_complexity)]
fn stamp_path_request_or_queue(
&mut self,
@@ -1086,7 +1086,7 @@ impl TransportActor {
None
}
/// Python `stamp_path_request` after generation (Transport.py:4038-4051).
/// Python `stamp_path_request` after generation (Transport.py).
pub(super) fn on_path_request_stamp_ready(
&mut self,
result: crate::pr_stamper::PathRequestStampResult,
@@ -1132,7 +1132,7 @@ impl TransportActor {
}
/// One request, stamped once, offered on every outbound interface but
/// `except`, limited to `modes` when given (Transport.py:3936-3947@1.6.0).
/// `except`, limited to `modes` when given (Transport.py).
pub(super) fn forward_path_request_ext(
&mut self,
destination_hash: [u8; 16],
@@ -1276,7 +1276,7 @@ impl TransportActor {
}
if should_add {
// Transport.py:3115-3127@1.6.0 keeps the saved timestamp and use.
// Transport.py keeps the saved timestamp and use.
let entry = crate::path_table::PathEntry {
timestamp: tunnel_path.timestamp,
next_hop: tunnel_path.next_hop,
@@ -1316,7 +1316,7 @@ impl TransportActor {
}
}
/// The header Python's `RNS.Packet(link, ...)` packs (Packet.py:180-190).
/// The header Python's `RNS.Packet(link, ...)` packs (Packet.py).
fn link_packet_header(
link_id: [u8; 16],
packet_type: rns_wire::flags::PacketType,
@@ -1347,7 +1347,7 @@ mod cache_miss_tests {
#[test]
fn live_path_without_cached_announce_uses_normal_discovery_gates() {
// A Boundary requester searches only Boundary and Gateway interfaces
// (Transport.py:3781-3783@1.6.0), so the Full route gets no request.
// (Transport.py), so the Full route gets no request.
for (mode, discovers, sent) in [
(InterfaceMode::Gateway, true, true),
(InterfaceMode::Boundary, true, false),
@@ -552,7 +552,7 @@ impl TransportActor {
let Some(entry) = self.interfaces.get_mut(&interface) else {
return Admission::Retired;
};
// Transport.py:3940 and :1676: offline interfaces get no request.
// Transport.py and :1676: offline interfaces get no request.
if !entry.direction.outbound || offline_for_send(entry) {
return Admission::Retired;
}
@@ -158,7 +158,7 @@ pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSn
);
}
// Publisher files are written only when fetched (Discovery.py:938-943).
// Publisher files are written only when fetched (Discovery.py).
if let Some(local_identity_hash) = snapshot.transport_identity_hash {
let blackhole_dir = dir.join("blackhole");
if let Err(e) = crate::persistence::save_local_blackhole_file(
@@ -331,7 +331,7 @@ impl TransportActor {
/// Full persist of routing state, known destinations and the hashlist
/// (Python `Reticulum.__persist_data`), off-actor.
pub(super) fn persist_data_async(&mut self) {
// Reticulum.py:1415@1.6.0: a persist already running skips this one untimed.
// Reticulum.py: a persist already running skips this one untimed.
if self
.routing_save_in_flight
.load(std::sync::atomic::Ordering::Acquire)
@@ -703,7 +703,7 @@ impl TransportActor {
return;
};
let now_ts = now();
// Python defers the first announce-cache clean (Transport.py:509).
// Python defers the first announce-cache clean (Transport.py).
self.last_announce_cache_sweep = now_ts + ANNOUNCE_CACHE_SWEEP_DEFER;
// Python destination_table — canonical interop shape. Defer interface
@@ -759,7 +759,7 @@ impl TransportActor {
interface_name: cached.interface_reference.clone(),
interface_hash: Some(pe.interface_hash.to_vec()),
packet_hash: Some(pe.packet_hash.to_vec()),
// Transport.py:557@1.6.0: a legacy row loads as used now.
// Transport.py: a legacy row loads as used now.
used: Some(pe.used.unwrap_or(now_ts)),
});
self.recent_announces
@@ -861,7 +861,7 @@ impl TransportActor {
// Python tunnels — canonical interop shape. A path loads only when
// its cached announce is present, and every tunnel loads unbound
// until a synthesis rebinds it (Transport.py:462-499).
// until a synthesis rebinds it (Transport.py).
let python_tunnels_path = dir.join("tunnels");
let loaded_python_tunnel_table = if python_tunnels_path.exists() {
match crate::persistence::load_python_tunnel_table(&python_tunnels_path) {
@@ -912,7 +912,7 @@ impl TransportActor {
.map(|blob| blob.to_vec())
.collect(),
packet_hash: Some(tp.packet_hash.to_vec()),
// Transport.py:617@1.6.0: a legacy row loads as used now.
// Transport.py: a legacy row loads as used now.
used: Some(tp.used.unwrap_or(now_ts)),
});
self.recent_announces
@@ -1071,7 +1071,7 @@ impl TransportActor {
}
/// Write `blackhole/local` now, as upstream does on every local change
/// (Transport.py:4489-4491, 4512-4514).
/// (Transport.py).
pub(super) fn persist_local_blackhole(&mut self) {
if self.shared_instance_client_mode {
return;
@@ -10,7 +10,7 @@ pub(super) struct DiscoveryOperation {
pub(super) timeout: f64,
requesters: Vec<Waiter>,
/// False while the entry only batches requesters behind an in-flight
/// request and no fan-out has started (Transport.py:2150-2156@1.6.0).
/// request and no fan-out has started (Transport.py).
engaged: bool,
}
@@ -181,7 +181,7 @@ impl TransportActor {
}
/// Add a requester behind an in-flight path request without starting a
/// fan-out (Transport.py:2143-2156@1.6.0).
/// fan-out (Transport.py).
pub(super) fn batch_inflight_requester(
&mut self,
destination: [u8; 16],
@@ -193,7 +193,7 @@ impl TransportActor {
/// `engage` starts a fan-out unless one is already engaged; an entry that
/// only batched requesters is engaged with a fresh deadline
/// (Transport.py:3888-3926@1.6.0).
/// (Transport.py).
fn admit_discovery_requester(
&mut self,
destination: [u8; 16],
@@ -304,7 +304,7 @@ impl TransportActor {
if !now.is_finite() || now >= operation.timeout {
return;
}
// Python recalls the answered identity with use marking (Transport.py:2696).
// Python recalls the answered identity with use marking (Transport.py).
if !operation.requesters.is_empty() {
self.use_destination(&destination);
}
+16 -16
View File
@@ -48,7 +48,7 @@ impl TransportActor {
}
TransportQuery::GetInterfaceStats => {
let now = now_f64();
// Reticulum.py:1620: stats follow Transport.interfaces, bitrate order.
// Reticulum.py: stats follow Transport.interfaces, bitrate order.
let mut stats: Vec<InterfaceStatRpcEntry> = self
.prioritized_interface_ids()
.into_iter()
@@ -195,7 +195,7 @@ impl TransportActor {
TransportQueryResponse::IntResult(self.link_table.len() as i64)
}
// Counts validated links. Python 1.6.0 means to, but indexes the
// link id instead of the entry (Transport.py:3577).
// link id instead of the entry (Transport.py).
TransportQuery::GetActiveLinkCount => TransportQueryResponse::IntResult(
self.link_table
.iter()
@@ -243,7 +243,7 @@ impl TransportActor {
timestamp: entry.timestamp,
})
});
// Identity.py:164-170: fall back to a registered local destination.
// Identity.py: fall back to a registered local destination.
let recalled = recalled.or_else(|| {
self.local_destination_keys.get(&dest).map(|public_key| {
RecalledDestinationRpcEntry {
@@ -277,7 +277,7 @@ impl TransportActor {
.unwrap_or(crate::constants::PATHFINDER_M),
)),
TransportQuery::GetNextHop { dest } => {
// Python 1.3.8 Transport.py:2685-2688: local destinations
// Python 1.3.8 Transport.py: local destinations
// resolve to Transport.identity.hash.
let next_hop = self
.path_table
@@ -292,7 +292,7 @@ impl TransportActor {
TransportQueryResponse::HashResult(next_hop)
}
TransportQuery::GetNextHopIfName { dest } => {
// Python 1.3.8 Transport.py:2691-2697: local destinations
// Python 1.3.8 Transport.py: local destinations
// resolve to the shared-instance interface (None off shared hosts).
let name = self
.path_table
@@ -301,7 +301,7 @@ impl TransportActor {
.or_else(|| self.local_destination_interface_id(&dest))
.and_then(|id| self.interfaces.get(&id))
.map(|i| {
// Python answers `str(interface)` (Reticulum.py:1960), as stats name it.
// Python answers `str(interface)` (Reticulum.py), as stats name it.
i.inspection
.as_ref()
.and_then(|source| source.identity())
@@ -406,7 +406,7 @@ impl TransportActor {
reason,
reason_label,
} => {
// Transport.py:4487-4497: an existing entry is left untouched.
// Transport.py: an existing entry is left untouched.
if self.blackhole_table.contains(&hash) {
return TransportQueryResponse::OptBoolResult(None);
}
@@ -770,7 +770,7 @@ impl TransportActor {
/// Next-hop interface for a local destination: the shared-instance server
/// interface, mirroring Python 1.3.8 Transport.next_hop_interface's
/// destinations_map fallback (Transport.py:2695-2696).
/// destinations_map fallback (Transport.py).
fn local_destination_interface_id(
&self,
dest: &[u8; 16],
@@ -801,7 +801,7 @@ struct TrafficSample {
}
/// Python `Transport.count_traffic_loop` state and the packet counters it
/// reports (Transport.py:736-814).
/// reports (Transport.py).
#[derive(Debug)]
pub(super) struct TrafficCount {
started: std::time::Instant,
@@ -833,7 +833,7 @@ use crate::messages::TrafficTotalsRpcEntry;
impl TransportActor {
/// Python `Interface.received_announce` and siblings: count on the
/// interface, then the bytes and a frequency sample on its parent
/// (Interface.py:307-329, TCPInterface.py:655-673).
/// (Interface.py, TCPInterface.py).
pub(super) fn record_interface_event(
&mut self,
id: InterfaceId,
@@ -866,12 +866,12 @@ impl TransportActor {
}
/// Python `Transport.rx_packets += 1` once a packet passes the packet
/// filter (Transport.py:2026).
/// filter (Transport.py).
pub(super) fn count_rx_packet(&mut self) {
self.traffic_count.totals.rx_packets += 1;
}
/// Python `Transport.tx_packets += 1` per `Transport.transmit` (Transport.py:1557).
/// Python `Transport.tx_packets += 1` per `Transport.transmit` (Transport.py).
pub(super) fn count_tx_packet(&mut self) {
self.traffic_count.totals.tx_packets += 1;
}
@@ -1000,7 +1000,7 @@ impl TransportActor {
}
/// A Backbone listener reports its children's bursts: whether any is active,
/// the earliest activation, and how many (BackboneInterface.py:185-259).
/// the earliest activation, and how many (BackboneInterface.py).
fn aggregate_backbone_bursts(stats: &mut [crate::messages::InterfaceStatRpcEntry]) {
let listeners: Vec<InterfaceId> = stats
.iter()
@@ -1053,7 +1053,7 @@ fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f6
}
impl TransportActor {
/// Python `Transport.first_hop_timeout` (Transport.py:3539-3542).
/// Python `Transport.first_hop_timeout` (Transport.py).
pub(super) fn first_hop_timeout(&self, dest: &[u8; 16]) -> f64 {
self.path_table
.get_live(dest)
@@ -1068,7 +1068,7 @@ impl TransportActor {
}
/// Python's receipt timeout for a non-Link destination:
/// `first_hop_timeout + TIMEOUT_PER_HOP * hops_to` (Packet.py:427-433).
/// `first_hop_timeout + TIMEOUT_PER_HOP * hops_to` (Packet.py).
pub(super) fn default_receipt_timeout(&self, dest: &[u8; 16]) -> std::time::Duration {
let hops = self
.path_table
@@ -1081,7 +1081,7 @@ impl TransportActor {
}
}
/// Python returns the first matching cache entry (Reticulum.py:2085-2093).
/// Python returns the first matching cache entry (Reticulum.py).
fn first_packet_metric(cache: &VecDeque<([u8; 32], f32)>, packet_hash: &[u8; 32]) -> Option<f64> {
cache
.iter()
@@ -11,7 +11,7 @@ fn limited() -> (InterfaceEntry, mpsc::Receiver<Bytes>) {
}
/// Python `process_announce_queue` consumes the entry and counts it sent
/// whatever `Transport.transmit` did with it (Interface.py:436-443).
/// whatever `Transport.transmit` did with it (Interface.py).
#[test]
fn announce_queue_full_send_consumes_entry_and_counts_it() {
let (mut actor, _) = TransportActor::new();
@@ -1,5 +1,5 @@
//! Python remembers the identity of every validated announce before it decides
//! whether the announce changes a path (Transport.py:2172, Identity.py:511-589):
//! whether the announce changes a path (Transport.py, Identity.py):
//! a replay teaches the identity but leaves the path and the handlers alone.
use super::*;
use rns_wire::context::PacketContext;
@@ -84,7 +84,7 @@ fn a_replayed_announce_still_teaches_its_identity() {
}
/// Python's `Identity.remember` refreshes the remembered entry's time and
/// app data on every validated announce (Identity.py:108-113), which keeps a
/// app data on every validated announce (Identity.py), which keeps a
/// pathless destination from being culled.
#[test]
fn a_replay_refreshes_the_remembered_identity() {
@@ -109,7 +109,7 @@ fn a_replay_refreshes_the_remembered_identity() {
);
}
/// A paused handler is skipped (Transport.py:2769@1.6.0) while the announce
/// A paused handler is skipped (Transport.py) while the announce
/// still updates the path table; resuming takes effect for the next announce.
#[test]
fn a_paused_handler_skips_announces_but_paths_are_learned() {
@@ -171,7 +171,7 @@ fn announce_at(
}
/// Python remembers a ratchet only from an announce that carries one
/// (Identity.py:726), so a newer ratchet-less announce keeps the old ratchet.
/// (Identity.py), so a newer ratchet-less announce keeps the old ratchet.
#[test]
fn a_ratchetless_announce_keeps_the_remembered_ratchet() {
let mut actor = hub();
@@ -206,8 +206,8 @@ fn recalled_ratchet(actor: &mut TransportActor, dest: [u8; 16]) -> Option<[u8; 3
}
/// Identity.clean_known_destinations expires remembered ratchets older than
/// RATCHET_EXPIRY (Identity.py:466-470) and get_ratchet refuses them
/// (Identity.py:626); the destination itself is kept.
/// RATCHET_EXPIRY (Identity.py) and get_ratchet refuses them
/// (Identity.py); the destination itself is kept.
#[test]
fn remembered_ratchets_expire_after_thirty_days() {
let mut actor = hub();
@@ -239,7 +239,7 @@ fn remembered_ratchets_expire_after_thirty_days() {
);
}
/// Re-receiving the same ratchet does not restart its expiry (Identity.py:538).
/// Re-receiving the same ratchet does not restart its expiry (Identity.py).
#[test]
fn a_repeated_ratchet_keeps_its_first_receive_time() {
let mut actor = hub();
@@ -1,6 +1,6 @@
//! Held and cached announces re-enter inbound processing as Python
//! re-injects them: past IFAC, without counting their bytes again
//! (Interface.py:296, Transport.py:3107-3119).
//! (Interface.py, Transport.py).
use super::*;
use crate::ingress::HeldAnnounce;
@@ -125,7 +125,7 @@ fn a_wire_announce_without_valid_ifac_is_dropped_and_never_held() {
assert!(!actor.path_table.has_path(&unsigned_destination));
}
/// Python's 5 s interface job re-evaluates the limiter (Transport.py:1329-1337),
/// Python's 5 s interface job re-evaluates the limiter (Transport.py),
/// so a burst clears on a quiet interface without another announce.
#[test]
fn interface_job_clears_a_burst_on_a_quiet_interface() {
@@ -1,4 +1,4 @@
//! Per-class inbound queues (Transport.py:50-97, :2133-2134, :2165-2170).
//! Per-class inbound queues (Transport.py).
use super::*;
use crate::inbound_queues::{InboundQueueLengths, Queued, TrafficClass};
@@ -153,7 +153,7 @@ fn path_requests_during_a_path_request_burst_wait_behind_every_other_class() {
/// Python decides at preprocess time and passes `ingress_limited` into
/// `path_request`, so a queued ingress-limited request is never forwarded
/// recursively even if the burst ended meanwhile (Transport.py:3761, :3777, :3903).
/// recursively even if the burst ended meanwhile (Transport.py).
#[test]
fn an_ingress_limited_path_request_is_not_forwarded_recursively() {
for (class, forwarded) in [
@@ -1,6 +1,6 @@
//! Python 1.5.5 per-interface counters in interface stats: announce and path
//! request counts, protocol and IFAC violations, packet filter hits and
//! dropped transmit bytes (Interface.py:303-338, Reticulum.py:1640-1663).
//! dropped transmit bytes (Interface.py, Reticulum.py).
use super::*;
use rns_wire::context::PacketContext;
use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, TransportType};
@@ -83,7 +83,7 @@ fn packet(
}
/// `rest` follows the destination: a tag, or a requestor transport id and a
/// tag (Transport.py:1832-1835).
/// tag (Transport.py).
fn path_request(destination: [u8; 16], rest: &[u8]) -> Bytes {
let pr_destination = rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.path.request",
@@ -305,7 +305,7 @@ fn a_full_transmit_queue_counts_dropped_bytes() {
}
/// Python counts a path request once its destination and tag pass the
/// duplicate gate (Transport.py:1847-1858), so a repeat sent through another
/// duplicate gate (Transport.py), so a repeat sent through another
/// requestor neither counts nor brings the ingress limit closer.
#[test]
fn a_repeated_path_request_tag_is_not_counted() {
@@ -385,7 +385,7 @@ fn totals(actor: &mut TransportActor) -> crate::messages::TrafficTotalsRpcEntry
}
/// Spawned children add their announce bytes and samples, not counts, to the
/// parent (Interface.py:307-311, TCPInterface.py:655-658).
/// parent (Interface.py, TCPInterface.py).
#[test]
fn a_parent_takes_its_childrens_announce_bytes_but_not_their_counts() {
let mut actor = hub();
@@ -408,7 +408,7 @@ fn a_parent_takes_its_childrens_announce_bytes_but_not_their_counts() {
}
/// Totals sum top-level interfaces other than the shared-instance server and
/// keep what they counted when an interface leaves (Transport.py:736-814).
/// keep what they counted when an interface leaves (Transport.py).
#[test]
fn traffic_totals_are_cumulative_over_top_level_interfaces() {
let mut actor = hub();
@@ -443,7 +443,7 @@ fn traffic_totals_are_cumulative_over_top_level_interfaces() {
}
/// `unupcount` counts paths never used and `actpcount` the rest
/// (Transport.py:3564-3569, Reticulum.py:1848-1850).
/// (Transport.py, Reticulum.py).
#[test]
fn traffic_totals_count_never_used_paths() {
let mut actor = hub();
@@ -78,7 +78,7 @@ fn packet_capacity_opaque_modes_relay_unless_a_clamp_is_needed() {
vec![0x42; 64]
);
}
// A sub-base offer is relayed without a range check (Transport.py:2338-2361).
// A sub-base offer is relayed without a range check (Transport.py).
for mtu in [1, 499] {
let exact = payload(1, mtu);
assert_eq!(
@@ -116,7 +116,7 @@ fn packet_capacity_checks_clear_and_wire_with_ifac_before_admission() {
let (tx, mut messages) = mpsc::channel(4);
actor.local_destinations.insert(dest);
actor.destination_channels.insert(dest, tx);
// Transport.py:2014@1.6.0 bounds the IFAC-stripped frame by HW_MTU + ifac_size.
// Transport.py bounds the IFAC-stripped frame by HW_MTU + ifac_size.
let mut clear = make_data_packet(dest, 0).to_vec();
clear.resize(508 + 8, 0);
ingress(
@@ -1,4 +1,4 @@
//! The announce validation caches (Identity.py:676-790).
//! The announce validation caches (Identity.py).
use std::collections::{HashMap, VecDeque};
@@ -61,7 +61,7 @@ impl AnnounceValidationCache {
Self::default()
}
/// Identity.py:750-790.
/// Identity.py.
pub fn lookup(
&self,
packet_hash: &[u8; 32],
@@ -98,7 +98,7 @@ impl AnnounceValidationCache {
CachedAnnounce::Miss
}
/// Identity.py:686-700: keeps the first result and clears any invalidation.
/// Identity.py: keeps the first result and clears any invalidation.
pub fn insert_valid(&mut self, packet_hash: [u8; 32], result: ValidatedAnnounce) {
if let std::collections::hash_map::Entry::Vacant(entry) = self.valid.entry(packet_hash) {
entry.insert(result);
@@ -115,7 +115,7 @@ impl AnnounceValidationCache {
}
}
/// Identity.py:704-713: a newer invalidation replaces the old one in place.
/// Identity.py: a newer invalidation replaces the old one in place.
pub fn insert_invalid(&mut self, packet_hash: [u8; 32], reason: InvalidAnnounce) {
if self.invalid.insert(packet_hash, reason).is_none() {
self.invalid_order.push_back(packet_hash);
@@ -128,7 +128,7 @@ impl AnnounceValidationCache {
}
}
/// Identity.py:678-680, called whenever the blackhole set changes.
/// Identity.py, called whenever the blackhole set changes.
pub fn reset(&mut self) {
self.valid.clear();
self.valid_order.clear();
+1 -1
View File
@@ -26,7 +26,7 @@ pub enum AwaitPathError {
}
/// Wait up to `timeout` for a cached or newly learned path to `destination_hash`.
/// A zero `timeout` means `PATH_REQUEST_TIMEOUT`, as Python's `await_path` (Transport.py:3678).
/// A zero `timeout` means `PATH_REQUEST_TIMEOUT`, as Python's `await_path` (Transport.py).
/// The deadline includes waiting to submit the command, not just its reply.
/// Success reflects actor path state and does not probe the remote application.
///
+5 -5
View File
@@ -36,20 +36,20 @@ pub const LINK_TIMEOUT: f64 = 900.0;
/// for that Link; transport never falls back to another interface.
pub const LINK_ENDPOINT_EGRESS_QUEUE_CAPACITY: usize = 256;
/// Never-used path linger on a transport node (Transport.py:228@1.6.0).
/// Never-used path linger on a transport node (Transport.py).
pub const UNUSED_PATH_LINGER: f64 = 60.0 * 60.0 * 1.75;
/// Never-used path linger on a leaf or shared-instance client (Transport.py:229@1.6.0).
/// Never-used path linger on a leaf or shared-instance client (Transport.py).
pub const UNUSED_PATH_LINGER_LEAF: f64 = 60.0 * 12.0;
/// Never-used paths kept by the pool cull (Transport.py:231@1.6.0).
/// Never-used paths kept by the pool cull (Transport.py).
pub const PATH_POOL_UNUSED_TARGET: usize = 2048;
/// Interfaces below this bitrate linger never-used paths longer (Transport.py:232-233@1.6.0).
/// Interfaces below this bitrate linger never-used paths longer (Transport.py).
pub const PATH_SLOW_BITRATE: u64 = 25_000;
pub const PATH_SLOW_LINGER_FACTOR: f64 = 10.0;
/// Interval between never-used pool checks (Transport.py:350@1.6.0).
/// Interval between never-used pool checks (Transport.py).
pub const PATH_POOL_CHECK_INTERVAL: f64 = 5.0 * 60.0;
/// Reverse table entry timeout (8 minutes).
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more