mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
runtime: read the [stamps] section and pass a stamp policy to transport
This commit is contained in:
1 parent
92dbf5f0e8
commit
fb50850632
8 files changed
+587
-5
No files matched your search
@@ -104,9 +104,9 @@ impl ConfigSection {
|
||||
v.parse().ok()
|
||||
}
|
||||
|
||||
/// Parses like Python `float()`, which ConfigObj `as_float` uses.
|
||||
pub fn get_float(&self, key: &str) -> Option<f64> {
|
||||
let v = self.get(key)?;
|
||||
v.parse().ok()
|
||||
parse_python_float(self.get(key)?)
|
||||
}
|
||||
|
||||
pub fn get_list(&self, key: &str) -> Option<Vec<String>> {
|
||||
@@ -558,6 +558,25 @@ fn strip_comment(line: &str) -> &str {
|
||||
line
|
||||
}
|
||||
|
||||
/// Python `float()` also accepts single underscores between digits (PEP 515).
|
||||
fn parse_python_float(s: &str) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
if !s.contains('_') {
|
||||
return s.parse().ok();
|
||||
}
|
||||
let bytes = s.as_bytes();
|
||||
let grouped = bytes.iter().enumerate().all(|(i, &b)| {
|
||||
b != b'_'
|
||||
|| (i > 0
|
||||
&& bytes[i - 1].is_ascii_digit()
|
||||
&& bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
|
||||
});
|
||||
if !grouped {
|
||||
return None;
|
||||
}
|
||||
s.replace('_', "").parse().ok()
|
||||
}
|
||||
|
||||
fn parse_bool(s: &str) -> Option<bool> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"true" | "yes" | "on" | "1" => Some(true),
|
||||
@@ -611,6 +630,23 @@ enable_transport = False
|
||||
share_instance = Yes
|
||||
instance_name = default
|
||||
|
||||
##########################################################
|
||||
# This section configures stamping behaviour and defaults.
|
||||
# In most cases, you do not need to change this, but on
|
||||
# constrained systems especially, tuning these parameters
|
||||
# can be very beneficial. See "rnsd --exampleconfig" or
|
||||
# the manual for a full explanation of these parameters.
|
||||
|
||||
[stamps]
|
||||
|
||||
# destination_cost = 23.5
|
||||
# destination_value = 25.0
|
||||
# pr_cost = 15.8
|
||||
# pr_value = 15.8
|
||||
# lr_cost = 12.5
|
||||
# lr_stamp_timeout = 15
|
||||
# pr_stamp_timeout = 15
|
||||
|
||||
[logging]
|
||||
loglevel = 4
|
||||
|
||||
@@ -626,6 +662,30 @@ mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn get_float_accepts_python_float_syntax() {
|
||||
let mut sec = ConfigSection::new();
|
||||
for (raw, expected) in [
|
||||
("1_0", Some(10.0)),
|
||||
("1_0_0", Some(100.0)),
|
||||
("1e1_0", Some(1e10)),
|
||||
("+2", Some(2.0)),
|
||||
(".5", Some(0.5)),
|
||||
("1e400", Some(f64::INFINITY)),
|
||||
("1__0", None),
|
||||
("_1", None),
|
||||
("1_", None),
|
||||
("1_.5", None),
|
||||
("abc", None),
|
||||
("", None),
|
||||
] {
|
||||
sec.set("k", raw);
|
||||
assert_eq!(sec.get_float("k"), expected, "{raw:?}");
|
||||
}
|
||||
sec.set("k", "-nan");
|
||||
assert!(sec.get_float("k").unwrap().is_nan());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_empty() {
|
||||
let config = Config::parse("").unwrap();
|
||||
|
||||
@@ -1633,6 +1633,23 @@ 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).
|
||||
pub fn validate_stamp_costs(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<(), InterfaceFactoryError> {
|
||||
for field in ["destination_cost", "pr_cost"] {
|
||||
if section.has(field) && section.get_float(field).is_none() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "value is not a float".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Options shared across interface variants, applied post-construction.
|
||||
pub struct InterfacePostInit {
|
||||
pub outgoing: bool,
|
||||
@@ -1665,6 +1682,12 @@ pub struct InterfacePostInit {
|
||||
/// interface. Other relay policy gates still apply; locally originated
|
||||
/// announces bypass this option. Parser default: true.
|
||||
pub announces_from_internal: bool,
|
||||
/// Required announce stamp value on this interface, clamped to the stamp
|
||||
/// cost cap. `None` follows the global `[stamps] destination_cost`.
|
||||
pub destination_cost: Option<f64>,
|
||||
/// Required path request stamp value on this interface, clamped to the
|
||||
/// stamp cost cap. `None` follows the global `[stamps] pr_cost`.
|
||||
pub pr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl InterfacePostInit {
|
||||
@@ -1685,6 +1708,8 @@ impl InterfacePostInit {
|
||||
"ic_burst_penalty",
|
||||
"ic_held_release_interval",
|
||||
"ec_pr_freq",
|
||||
"destination_cost",
|
||||
"pr_cost",
|
||||
] {
|
||||
if section.has(field) && section.get_float(field).is_none() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
@@ -1745,6 +1770,12 @@ impl InterfacePostInit {
|
||||
ingress_overrides,
|
||||
recursive_prs: section.get_bool("recursive_prs").unwrap_or(false),
|
||||
announces_from_internal: section.get_bool("announces_from_internal").unwrap_or(true),
|
||||
destination_cost: section
|
||||
.get_float("destination_cost")
|
||||
.map(rns_transport::stamps::StampPolicy::clamp_cost),
|
||||
pr_cost: section
|
||||
.get_float("pr_cost")
|
||||
.map(rns_transport::stamps::StampPolicy::clamp_cost),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +78,9 @@ struct InterfaceControlMetadata {
|
||||
/// The network identity, in hex, that announced an auto-connected
|
||||
/// interface (Python `autoconnect_source`, Discovery.py:865).
|
||||
autoconnect_source: Option<String>,
|
||||
// Per-interface stamp costs, copied raw to spawned children (TCPInterface.py:608-609).
|
||||
destination_cost: Option<f64>,
|
||||
pr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
type InterfaceControlMap = Arc<std::sync::Mutex<HashMap<u64, InterfaceControlMetadata>>>;
|
||||
@@ -2373,6 +2376,12 @@ pub struct InitOptions {
|
||||
pub require_shared_instance: bool,
|
||||
/// Override the configured shared-instance transport for this process.
|
||||
pub shared_instance_type: Option<SharedInstanceType>,
|
||||
/// Python `Reticulum(enable_stamping=True)`: stamp emitted announces, path
|
||||
/// requests and link requests. `false` never clears a configured switch.
|
||||
pub enable_stamping: bool,
|
||||
/// Python `Reticulum(enforce_stamps=True)`: enforce announce, path request
|
||||
/// and link request stamps. `false` never clears a configured switch.
|
||||
pub enforce_stamps: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -2518,6 +2527,9 @@ pub struct ReticulumConfig {
|
||||
/// runtime does not load or merge these files; declare active interfaces
|
||||
/// in the primary configuration.
|
||||
pub bootstrap_configs: Vec<PathBuf>,
|
||||
|
||||
/// Network stamp policy from the `[stamps]` section.
|
||||
pub stamps: rns_transport::stamps::StampPolicy,
|
||||
}
|
||||
|
||||
impl Default for ReticulumConfig {
|
||||
@@ -2556,6 +2568,7 @@ impl Default for ReticulumConfig {
|
||||
rns_transport::discovery::blackhole_subscriber::UPDATE_INTERVAL.as_secs_f64(),
|
||||
log_timestamps: true,
|
||||
bootstrap_configs: Vec::new(),
|
||||
stamps: rns_transport::stamps::StampPolicy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2635,6 +2648,50 @@ fn config_float(
|
||||
.ok_or_else(|| invalid_config_value(section_name, key, "value is not a float"))
|
||||
}
|
||||
|
||||
/// Python `Reticulum.__apply_config` `[stamps]` keys. Booleans only switch
|
||||
/// features on; unknown keys are ignored.
|
||||
fn apply_stamps_section(
|
||||
policy: &mut rns_transport::stamps::StampPolicy,
|
||||
sec: &ConfigSection,
|
||||
) -> Result<(), ConfigError> {
|
||||
use rns_transport::stamps::StampPolicy;
|
||||
const S: &str = "stamps";
|
||||
if config_bool(S, sec, "enforce_stamps")? == Some(true) {
|
||||
policy.enforce();
|
||||
}
|
||||
if config_bool(S, sec, "stamp_destinations")? == Some(true) {
|
||||
policy.stamp_destinations = true;
|
||||
}
|
||||
if config_bool(S, sec, "stamp_prs")? == Some(true) {
|
||||
policy.stamp_prs = true;
|
||||
}
|
||||
if config_bool(S, sec, "always_stamp_lrs")? == Some(true) {
|
||||
policy.always_stamp_lrs = true;
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "destination_cost")? {
|
||||
policy.destination_cost = StampPolicy::clamp_cost(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "destination_value")? {
|
||||
policy.destination_value = StampPolicy::clamp_cost(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "pr_cost")? {
|
||||
policy.pr_cost = StampPolicy::clamp_cost(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "pr_value")? {
|
||||
policy.pr_value = StampPolicy::clamp_cost(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "lr_cost")? {
|
||||
policy.lr_cost = StampPolicy::clamp_link_cost(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "lr_stamp_timeout")? {
|
||||
policy.lr_stamp_timeout = StampPolicy::clamp_timeout(v);
|
||||
}
|
||||
if let Some(v) = config_float(S, sec, "pr_stamp_timeout")? {
|
||||
policy.pr_stamp_timeout = StampPolicy::clamp_timeout(v);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn config_u16(
|
||||
section_name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -2750,6 +2807,10 @@ impl ReticulumConfig {
|
||||
pub fn try_from_config(config: &Config) -> Result<Self, ConfigError> {
|
||||
let mut rc = ReticulumConfig::default();
|
||||
|
||||
if let Some(sec) = config.section("stamps") {
|
||||
apply_stamps_section(&mut rc.stamps, sec)?;
|
||||
}
|
||||
|
||||
if let Some(sec) = config.section("reticulum") {
|
||||
if let Some(value) = config_bool("reticulum", sec, "share_instance")? {
|
||||
rc.share_instance = value;
|
||||
@@ -2871,6 +2932,22 @@ impl ReticulumConfig {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// Apply constructor overrides after the configuration file, in Python's
|
||||
/// order (Reticulum.py:349-362).
|
||||
pub fn apply_init_options(&mut self, options: &InitOptions) {
|
||||
if options.enable_stamping {
|
||||
tracing::debug!("Network stamp generation activated");
|
||||
self.stamps.enable_stamping();
|
||||
}
|
||||
if options.enforce_stamps {
|
||||
tracing::debug!("Network stamp enforcement activated");
|
||||
self.stamps.enforce();
|
||||
}
|
||||
if let Some(shared_instance_type) = options.shared_instance_type {
|
||||
self.shared_instance_type = shared_instance_type;
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse configuration, panicking on a value error. Use `try_from_config`
|
||||
/// when configuration comes from users or requires recoverable validation.
|
||||
pub fn from_config(config: &Config) -> Self {
|
||||
@@ -2989,9 +3066,7 @@ pub async fn init_with_policy(
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
let mut rc = ReticulumConfig::try_from_config(&config).map_err(ReticulumError::Config)?;
|
||||
if let Some(shared_instance_type) = options.shared_instance_type {
|
||||
rc.shared_instance_type = shared_instance_type;
|
||||
}
|
||||
rc.apply_init_options(&options);
|
||||
match &policy {
|
||||
InstancePolicy::Configured => {}
|
||||
InstancePolicy::Standalone => rc.share_instance = false,
|
||||
@@ -3094,6 +3169,9 @@ pub async fn init_with_policy(
|
||||
let _ = transport_tx.try_send(TransportMessage::SetBlackholeSources {
|
||||
sources: rc.blackhole_sources.clone(),
|
||||
});
|
||||
let _ = transport_tx.try_send(TransportMessage::SetStampPolicy {
|
||||
policy: rc.stamps.clone(),
|
||||
});
|
||||
|
||||
// Python defaults the local shared-instance RPC key to a hash of the
|
||||
// PERSISTENT transport identity (internal_identity(), Reticulum.py:352),
|
||||
@@ -3521,6 +3599,17 @@ pub async fn init_with_policy(
|
||||
tracing::info!("transport node mode enabled");
|
||||
}
|
||||
|
||||
if instance_mode != InstanceMode::Client {
|
||||
for (name, section) in config.subsections("interfaces") {
|
||||
if let Err(e) = interface_factory::validate_stamp_costs(name, section) {
|
||||
shutdown_coordinator.start_and_wait().await;
|
||||
return Err(ReticulumError::Interface(format!(
|
||||
"failed to synthesize interface {name}: {e}"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut interfaces = match synthesize_interfaces(&config, rc.panic_on_interface_error) {
|
||||
Ok(interfaces) => interfaces,
|
||||
Err(e) => {
|
||||
@@ -4697,6 +4786,7 @@ async fn prepare_interface_with_role_and_overrides(
|
||||
}
|
||||
};
|
||||
let registry_owner = registration.owner();
|
||||
let child_stamp_costs;
|
||||
{
|
||||
let mut controls = interface_controls
|
||||
.lock()
|
||||
@@ -4707,6 +4797,12 @@ async fn prepare_interface_with_role_and_overrides(
|
||||
.and(handle.parent_id)
|
||||
.and_then(|parent| controls.get(&parent))
|
||||
.and_then(|parent| parent.ifac_netname.clone());
|
||||
let (destination_cost, pr_cost) = handle
|
||||
.parent_id
|
||||
.and_then(|parent| controls.get(&parent))
|
||||
.map(|parent| (parent.destination_cost, parent.pr_cost))
|
||||
.unwrap_or_default();
|
||||
child_stamp_costs = (destination_cost, pr_cost);
|
||||
controls.insert(
|
||||
id,
|
||||
InterfaceControlMetadata {
|
||||
@@ -4719,6 +4815,8 @@ async fn prepare_interface_with_role_and_overrides(
|
||||
ifac_netname,
|
||||
client_target: None,
|
||||
autoconnect_source: None,
|
||||
destination_cost,
|
||||
pr_cost,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -4759,6 +4857,8 @@ async fn prepare_interface_with_role_and_overrides(
|
||||
// inherit recursive_prs/announces_from_internal (TCPInterface.py:579+).
|
||||
recursive_prs: false,
|
||||
announces_from_internal: true,
|
||||
destination_cost: child_stamp_costs.0,
|
||||
pr_cost: child_stamp_costs.1,
|
||||
};
|
||||
Ok(PreparedInterfaceRegistration {
|
||||
transport_owner: handle.owner.clone(),
|
||||
@@ -4865,6 +4965,8 @@ fn clone_interface_post_init(
|
||||
ingress_overrides: post_init.ingress_overrides.clone(),
|
||||
recursive_prs: post_init.recursive_prs,
|
||||
announces_from_internal: post_init.announces_from_internal,
|
||||
destination_cost: post_init.destination_cost,
|
||||
pr_cost: post_init.pr_cost,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4910,6 +5012,9 @@ fn configured_peer_post_init(
|
||||
ingress_overrides: ingress_overrides.clone(),
|
||||
recursive_prs: false,
|
||||
announces_from_internal: true,
|
||||
// I2PInterface.py:854-855 copies these to configured peers.
|
||||
destination_cost: post_init.destination_cost,
|
||||
pr_cost: post_init.pr_cost,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5026,6 +5131,8 @@ async fn prepare_interface_with_post_init(
|
||||
ifac_size: post_init.ifac_size.unwrap_or(post_init.default_ifac_size),
|
||||
client_target: None,
|
||||
autoconnect_source: None,
|
||||
destination_cost: post_init.destination_cost,
|
||||
pr_cost: post_init.pr_cost,
|
||||
},
|
||||
);
|
||||
let entry = rns_transport::messages::InterfaceEntry {
|
||||
@@ -5060,6 +5167,8 @@ async fn prepare_interface_with_post_init(
|
||||
multipoint: false,
|
||||
recursive_prs: post_init.recursive_prs,
|
||||
announces_from_internal: post_init.announces_from_internal,
|
||||
destination_cost: post_init.destination_cost,
|
||||
pr_cost: post_init.pr_cost,
|
||||
};
|
||||
Ok(PreparedInterfaceRegistration {
|
||||
transport_owner: handle.owner.clone(),
|
||||
@@ -8925,6 +9034,8 @@ mod tests {
|
||||
ifac_netname: None,
|
||||
client_target: None,
|
||||
autoconnect_source: None,
|
||||
destination_cost: None,
|
||||
pr_cost: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -9072,6 +9183,8 @@ mod tests {
|
||||
ifac_netname: None,
|
||||
client_target: None,
|
||||
autoconnect_source: None,
|
||||
destination_cost: None,
|
||||
pr_cost: None,
|
||||
},
|
||||
);
|
||||
drop(registration);
|
||||
@@ -14391,6 +14504,8 @@ egress_control = Yes
|
||||
ifac_netname: None,
|
||||
client_target: None,
|
||||
autoconnect_source: None,
|
||||
destination_cost: None,
|
||||
pr_cost: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -14485,6 +14600,98 @@ egress_control = Yes
|
||||
assert_eq!(stats.lookup(930_003), InterfaceIfac::default());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_children_inherit_parent_stamp_costs_unresolved() {
|
||||
let parent_id = 930_011;
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let interface_controls: InterfaceControlMap =
|
||||
Arc::new(std::sync::Mutex::new(HashMap::new()));
|
||||
let interface_registry = InterfaceRegistry::default();
|
||||
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("destination_cost", "150");
|
||||
let post_init = interface_factory::InterfacePostInit::try_from_section(§ion).unwrap();
|
||||
assert_eq!(post_init.destination_cost, Some(100.0));
|
||||
assert_eq!(post_init.pr_cost, None);
|
||||
register_interface_with_post_init(
|
||||
&transport_tx,
|
||||
test_interface_handle(parent_id, None, "cost-parent"),
|
||||
&post_init,
|
||||
None,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Some(TransportMessage::RegisterInterface { entry, .. }) =
|
||||
transport_rx.recv().await.map(unwrap_owned_event)
|
||||
else {
|
||||
panic!("expected parent RegisterInterface");
|
||||
};
|
||||
assert_eq!((entry.destination_cost, entry.pr_cost), (Some(100.0), None));
|
||||
|
||||
let (role, inherited, key, size) =
|
||||
child_registration_from_parent(&interface_controls, Some(parent_id));
|
||||
register_interface_handle_with_role_and_overrides(
|
||||
&transport_tx,
|
||||
test_interface_handle(930_012, Some(parent_id), "cost-child"),
|
||||
role,
|
||||
inherited,
|
||||
key,
|
||||
size,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Some(TransportMessage::RegisterInterface { entry, .. }) =
|
||||
transport_rx.recv().await.map(unwrap_owned_event)
|
||||
else {
|
||||
panic!("expected child RegisterInterface");
|
||||
};
|
||||
// None stays None so the child keeps following the global pr_cost.
|
||||
assert_eq!((entry.destination_cost, entry.pr_cost), (Some(100.0), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamps_section_booleans_only_switch_on() {
|
||||
let config = Config::parse("[stamps]\nstamp_prs = no\nenforce_stamps = no\n").unwrap();
|
||||
let mut policy = rns_transport::stamps::StampPolicy {
|
||||
stamp_prs: true,
|
||||
stamps_enforced: true,
|
||||
..Default::default()
|
||||
};
|
||||
apply_stamps_section(&mut policy, config.section("stamps").unwrap()).unwrap();
|
||||
assert!(policy.stamp_prs);
|
||||
assert!(policy.stamps_enforced);
|
||||
assert!(!policy.lr_stamps_enforced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamps_section_bad_values_fail_config() {
|
||||
for body in ["stamp_prs = maybe", "pr_cost = abc", "lr_stamp_timeout = "] {
|
||||
let config = Config::parse(&format!("[stamps]\n{body}\n")).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
ReticulumConfig::try_from_config(&config),
|
||||
Err(ConfigError::InvalidValue { ref section, .. }) if section == "stamps"
|
||||
),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_parses_to_default_stamp_policy() {
|
||||
let config = Config::parse(Config::default_config()).unwrap();
|
||||
assert!(config.section("stamps").is_some());
|
||||
let rc = ReticulumConfig::try_from_config(&config).unwrap();
|
||||
assert_eq!(rc.stamps, rns_transport::stamps::StampPolicy::default());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interfaces_without_ifac_report_none_despite_a_configured_size() {
|
||||
let id = 930_101;
|
||||
@@ -15080,6 +15287,7 @@ enabled = yes
|
||||
InitOptions {
|
||||
require_shared_instance: true,
|
||||
shared_instance_type: Some(SharedInstanceType::Tcp),
|
||||
..InitOptions::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -15099,6 +15307,7 @@ enabled = yes
|
||||
InitOptions {
|
||||
require_shared_instance: false,
|
||||
shared_instance_type: Some(SharedInstanceType::Tcp),
|
||||
..InitOptions::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -28,6 +28,76 @@ instance_name = default
|
||||
# disabled.
|
||||
# static_transport_identity = no
|
||||
|
||||
[stamps]
|
||||
# This section configures stamping behaviour and defaults.
|
||||
# In most cases, you do not need to change this, but on
|
||||
# constrained systems especially, tuning these parameters
|
||||
# can be very beneficial
|
||||
|
||||
# During the 1.6.x phased transition to network stamp usage,
|
||||
# it is possible to enable early opt-in on stamp generation
|
||||
# and enforcement. RNS 1.6.0 includes all the required stamp
|
||||
# generation and verification functionality, and actively
|
||||
# validates stamps, while leaving generation, emission and
|
||||
# enforcement disabled by default for destinations and PRs.
|
||||
# Link requests will be stamped already from 1.6.0 if a cost
|
||||
# has been announced by the destination. Version 1.6.1 will
|
||||
# enable generation and emission by default, and version
|
||||
# 1.6.2 will finally activate enforcement. Any of these
|
||||
# options can be enabled early by configuration:
|
||||
|
||||
# stamp_destinations = yes
|
||||
# stamp_prs = yes
|
||||
# enforce_stamps = yes
|
||||
|
||||
|
||||
# The default required stamp cost for an announce, and its
|
||||
# destination to be considered valid. This applies both to
|
||||
# announces received directly, and transported by this node,
|
||||
# if transport is enabled. Any announced destination not
|
||||
# meeting the cost will be ignored.
|
||||
|
||||
# destination_cost = 23.5
|
||||
|
||||
|
||||
# The default value this instance will target when generating
|
||||
# new destination stamps. An application may set a higher
|
||||
# target, but applications requesting a lower value than the
|
||||
# default will always generate at least the default value.
|
||||
# Destination stamps are cached and reused, so a one-time
|
||||
# high-value generation is usually a good idea.
|
||||
|
||||
# destination_value = 25.0
|
||||
|
||||
|
||||
# The default required path request stamp cost. Path requests
|
||||
# that do not meet the requirement are ignored.
|
||||
|
||||
# pr_cost = 15.8
|
||||
|
||||
|
||||
# The default target value of path request stamps generated
|
||||
# by this instance.
|
||||
|
||||
# pr_value = 15.8
|
||||
|
||||
|
||||
# The default link request stamp cost to use, if one has not
|
||||
# been announced by the destination the link is established
|
||||
# to, or if it is unknown. In practice, all destinations will
|
||||
# include their required link cost in each announce, and this
|
||||
# option is rarely necessary.
|
||||
|
||||
# lr_cost = 12.5
|
||||
|
||||
|
||||
# The maximum amount of time to spend attempting to generate
|
||||
# a link request and path request stamps, in seconds.
|
||||
|
||||
# lr_stamp_timeout = 15
|
||||
# pr_stamp_timeout = 15
|
||||
|
||||
|
||||
[logging]
|
||||
loglevel = 4
|
||||
|
||||
|
||||
@@ -213,6 +213,8 @@ pub struct TransportActor {
|
||||
/// Allowed external source hashes for on-disk blackhole loading. Changing
|
||||
/// this vector alone does not reload or purge the table.
|
||||
pub blackhole_sources: Vec<[u8; 16]>,
|
||||
/// Network stamp policy from configuration and constructor switches.
|
||||
pub stamp_policy: crate::stamps::StampPolicy,
|
||||
/// Shared set of currently blackholed identity hashes for runtime Link checks.
|
||||
/// Managed mutation/cull paths rebuild it and filter expired entries. Direct
|
||||
/// public table mutation does not publish a snapshot; a poisoned snapshot
|
||||
@@ -456,6 +458,7 @@ impl TransportActor {
|
||||
static_transport_identity: false,
|
||||
local_hops_delta: 0,
|
||||
blackhole_sources: Vec::new(),
|
||||
stamp_policy: crate::stamps::StampPolicy::default(),
|
||||
blackholed_snapshot: Arc::new(std::sync::RwLock::new(HashSet::new())),
|
||||
is_shared_instance: false,
|
||||
shared_instance_client_mode: false,
|
||||
@@ -994,6 +997,10 @@ impl TransportActor {
|
||||
self.blackhole_sources = sources;
|
||||
self.load_python_blackhole_if_ready();
|
||||
}
|
||||
TransportMessage::SetStampPolicy { policy } => {
|
||||
debug!(?policy, "setting stamp policy");
|
||||
self.stamp_policy = policy;
|
||||
}
|
||||
TransportMessage::SharedConnectionLost => {
|
||||
tracing::warn!("shared instance connection lost — suspending transport");
|
||||
self.terminate_shared_peer_link_endpoints();
|
||||
@@ -2592,6 +2599,8 @@ mod tests {
|
||||
multipoint: false,
|
||||
recursive_prs: false,
|
||||
announces_from_internal: true,
|
||||
destination_cost: None,
|
||||
pr_cost: None,
|
||||
ingress: crate::ingress::IngressController::new(),
|
||||
announce_queue: Vec::new(),
|
||||
};
|
||||
|
||||
@@ -43,6 +43,7 @@ pub mod path_table;
|
||||
pub mod persistence;
|
||||
pub mod rate_limit;
|
||||
pub mod reverse_table;
|
||||
pub mod stamps;
|
||||
pub mod traffic;
|
||||
pub mod tunnel;
|
||||
|
||||
|
||||
@@ -324,6 +324,12 @@ pub struct InterfaceEntry {
|
||||
/// Whether to rebroadcast announces whose next-hop interface uses
|
||||
/// `InterfaceMode::Internal`.
|
||||
pub announces_from_internal: bool,
|
||||
/// Configured announce stamp requirement; `None` follows
|
||||
/// `StampPolicy::destination_cost`. Resolve with `StampPolicy::interface_destination_cost`.
|
||||
pub destination_cost: Option<f64>,
|
||||
/// Configured path request stamp requirement; `None` follows
|
||||
/// `StampPolicy::pr_cost`. Resolve with `StampPolicy::interface_pr_cost`.
|
||||
pub pr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl InterfaceEntry {
|
||||
@@ -370,6 +376,8 @@ impl InterfaceEntry {
|
||||
multipoint: false,
|
||||
recursive_prs: false,
|
||||
announces_from_internal: true,
|
||||
destination_cost: None,
|
||||
pr_cost: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -707,6 +715,11 @@ pub enum TransportMessage {
|
||||
SetBlackholeSources {
|
||||
sources: Vec<[u8; 16]>,
|
||||
},
|
||||
/// Replace the network stamp policy. The runtime sends it before any
|
||||
/// interface is registered.
|
||||
SetStampPolicy {
|
||||
policy: crate::stamps::StampPolicy,
|
||||
},
|
||||
/// Handle loss of the current shared-instance peer: invalidate routing state
|
||||
/// and terminate peer-bound Link endpoints. This is not a blanket pause of
|
||||
/// all packet processing. Submit through the current interface owner.
|
||||
@@ -817,6 +830,7 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str {
|
||||
TransportMessage::SetTransportEnabled { .. } => "SetTransportEnabled",
|
||||
TransportMessage::SetTransportIdentity { .. } => "SetTransportIdentity",
|
||||
TransportMessage::SetBlackholeSources { .. } => "SetBlackholeSources",
|
||||
TransportMessage::SetStampPolicy { .. } => "SetStampPolicy",
|
||||
TransportMessage::SharedConnectionLost => "SharedConnectionLost",
|
||||
TransportMessage::SharedConnectionRestored { .. } => "SharedConnectionRestored",
|
||||
TransportMessage::SynthesizeTunnel { .. } => "SynthesizeTunnel",
|
||||
@@ -1345,6 +1359,10 @@ impl std::fmt::Debug for TransportMessage {
|
||||
.debug_struct("SetBlackholeSources")
|
||||
.field("sources", sources)
|
||||
.finish(),
|
||||
Self::SetStampPolicy { policy } => f
|
||||
.debug_struct("SetStampPolicy")
|
||||
.field("policy", policy)
|
||||
.finish(),
|
||||
Self::SharedConnectionLost => f.debug_struct("SharedConnectionLost").finish(),
|
||||
Self::SharedConnectionRestored { interface_id } => f
|
||||
.debug_struct("SharedConnectionRestored")
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Network stamp policy: the switches and costs Python keeps on `Transport`.
|
||||
//!
|
||||
//! Python reference: `RNS/Transport.py:191-210` and the `[stamps]` parser in
|
||||
//! `RNS/Reticulum.py:505-551` (1.6.0).
|
||||
|
||||
pub use rns_identity::stamps::{LINK_COST_CAP, STAMP_COST_CAP};
|
||||
|
||||
/// Lower bound for `lr_stamp_timeout` and `pr_stamp_timeout`, in seconds.
|
||||
pub const STAMP_TIMEOUT_FLOOR: f64 = 0.020;
|
||||
/// Not configurable in Python 1.6.0.
|
||||
pub const STAMPER_PR_QUEUE_LENGTH: usize = 32;
|
||||
/// Not configurable in Python 1.6.0.
|
||||
pub const STAMPER_AN_QUEUE_LENGTH: usize = 32;
|
||||
|
||||
/// Effective stamp generation and enforcement policy for one instance.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct StampPolicy {
|
||||
/// Python `STAMPS_ENABLED`: check for and validate stamps.
|
||||
pub stamps_enabled: bool,
|
||||
/// Python `STAMPS_ENFORCED`.
|
||||
pub stamps_enforced: bool,
|
||||
/// Python `LR_STAMPS_ENFORCED`.
|
||||
pub lr_stamps_enforced: bool,
|
||||
/// Python `STAMP_DESTINATIONS`.
|
||||
pub stamp_destinations: bool,
|
||||
/// Python `STAMP_PRS`.
|
||||
pub stamp_prs: bool,
|
||||
/// Python `STAMP_LRS`.
|
||||
pub stamp_lrs: bool,
|
||||
/// Python `ALWAYS_STAMP_LRS`.
|
||||
pub always_stamp_lrs: bool,
|
||||
/// Python `DESTINATION_COST`.
|
||||
pub destination_cost: f64,
|
||||
/// Python `DESTINATION_VALUE`.
|
||||
pub destination_value: f64,
|
||||
/// Python `PR_COST`.
|
||||
pub pr_cost: f64,
|
||||
/// Python `PR_VALUE`.
|
||||
pub pr_value: f64,
|
||||
/// Python `LR_COST`.
|
||||
pub lr_cost: f64,
|
||||
/// Python `LINK_STAMP_TIMEOUT`, in seconds.
|
||||
pub lr_stamp_timeout: f64,
|
||||
/// Python `PR_STAMP_TIMEOUT`, in seconds.
|
||||
pub pr_stamp_timeout: f64,
|
||||
}
|
||||
|
||||
impl Default for StampPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stamps_enabled: true,
|
||||
stamps_enforced: false,
|
||||
lr_stamps_enforced: false,
|
||||
stamp_destinations: false,
|
||||
stamp_prs: false,
|
||||
stamp_lrs: true,
|
||||
always_stamp_lrs: false,
|
||||
destination_cost: 23.5,
|
||||
destination_value: 25.0,
|
||||
pr_cost: 15.8,
|
||||
pr_value: 15.8,
|
||||
lr_cost: 12.5,
|
||||
lr_stamp_timeout: 15.0,
|
||||
pr_stamp_timeout: 15.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StampPolicy {
|
||||
/// Python `max(0, min(v, STAMP_COST_CAP))`, including its NaN result of 0.
|
||||
pub fn clamp_cost(value: f64) -> f64 {
|
||||
clamp_to_cap(value, STAMP_COST_CAP)
|
||||
}
|
||||
|
||||
/// Python `max(0, min(v, LINK_COST_CAP))`.
|
||||
pub fn clamp_link_cost(value: f64) -> f64 {
|
||||
clamp_to_cap(value, LINK_COST_CAP)
|
||||
}
|
||||
|
||||
/// Python `max(0.020, v)`, including its NaN result of 0.020.
|
||||
pub fn clamp_timeout(value: f64) -> f64 {
|
||||
if value.is_nan() || value < STAMP_TIMEOUT_FLOOR {
|
||||
STAMP_TIMEOUT_FLOOR
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
/// The `enable_stamping` constructor switch.
|
||||
pub fn enable_stamping(&mut self) {
|
||||
self.stamp_destinations = true;
|
||||
self.stamp_prs = true;
|
||||
self.stamp_lrs = true;
|
||||
}
|
||||
|
||||
/// The `enforce_stamps` constructor switch and config key.
|
||||
pub fn enforce(&mut self) {
|
||||
self.stamps_enforced = true;
|
||||
self.lr_stamps_enforced = true;
|
||||
}
|
||||
|
||||
/// Python `Interface.destination_cost`: the interface value, else the global.
|
||||
pub fn interface_destination_cost(&self, interface_cost: Option<f64>) -> f64 {
|
||||
interface_cost.unwrap_or(self.destination_cost)
|
||||
}
|
||||
|
||||
/// Python `Interface.pr_cost`: the interface value, else the global.
|
||||
pub fn interface_pr_cost(&self, interface_cost: Option<f64>) -> f64 {
|
||||
interface_cost.unwrap_or(self.pr_cost)
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp_to_cap(value: f64, cap: f64) -> f64 {
|
||||
// Python's min(nan, cap) is nan and max(0, nan) is 0.
|
||||
if value.is_nan() || value < 0.0 {
|
||||
0.0
|
||||
} else if value > cap {
|
||||
cap
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn default_matches_python_transport_defaults() {
|
||||
let p = StampPolicy::default();
|
||||
assert!(p.stamps_enabled);
|
||||
assert!(!p.stamps_enforced);
|
||||
assert!(!p.lr_stamps_enforced);
|
||||
assert!(!p.stamp_destinations);
|
||||
assert!(!p.stamp_prs);
|
||||
assert!(p.stamp_lrs);
|
||||
assert!(!p.always_stamp_lrs);
|
||||
assert_eq!(p.destination_cost, 23.5);
|
||||
assert_eq!(p.destination_value, 25.0);
|
||||
assert_eq!(p.pr_cost, 15.8);
|
||||
assert_eq!(p.pr_value, 15.8);
|
||||
assert_eq!(p.lr_cost, 12.5);
|
||||
assert_eq!(p.lr_stamp_timeout, 15.0);
|
||||
assert_eq!(p.pr_stamp_timeout, 15.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_follow_python_min_max() {
|
||||
assert_eq!(StampPolicy::clamp_cost(f64::NAN), 0.0);
|
||||
assert_eq!(StampPolicy::clamp_cost(f64::INFINITY), 100.0);
|
||||
assert_eq!(StampPolicy::clamp_cost(f64::NEG_INFINITY), 0.0);
|
||||
assert_eq!(StampPolicy::clamp_cost(-5.0), 0.0);
|
||||
assert_eq!(StampPolicy::clamp_cost(150.0), 100.0);
|
||||
assert_eq!(StampPolicy::clamp_cost(7.25), 7.25);
|
||||
assert_eq!(StampPolicy::clamp_link_cost(41.0), 40.0);
|
||||
assert_eq!(StampPolicy::clamp_link_cost(f64::NAN), 0.0);
|
||||
assert_eq!(StampPolicy::clamp_timeout(f64::NAN), 0.02);
|
||||
assert_eq!(StampPolicy::clamp_timeout(0.001), 0.02);
|
||||
assert_eq!(StampPolicy::clamp_timeout(-1.0), 0.02);
|
||||
assert_eq!(StampPolicy::clamp_timeout(1e6), 1e6);
|
||||
assert_eq!(StampPolicy::clamp_timeout(f64::INFINITY), f64::INFINITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switches_set_python_flags() {
|
||||
let mut p = StampPolicy::default();
|
||||
p.enable_stamping();
|
||||
assert!(p.stamp_destinations && p.stamp_prs && p.stamp_lrs);
|
||||
assert!(!p.stamps_enforced && !p.lr_stamps_enforced);
|
||||
let mut p = StampPolicy::default();
|
||||
p.enforce();
|
||||
assert!(p.stamps_enforced && p.lr_stamps_enforced);
|
||||
assert!(!p.stamp_destinations && !p.stamp_prs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_costs_fall_back_to_current_global() {
|
||||
let mut p = StampPolicy::default();
|
||||
assert_eq!(p.interface_destination_cost(None), 23.5);
|
||||
assert_eq!(p.interface_pr_cost(Some(7.25)), 7.25);
|
||||
p.destination_cost = 30.0;
|
||||
assert_eq!(p.interface_destination_cost(None), 30.0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user