VanguardState

Struct VanguardState 

Source
pub struct VanguardState {
    pub layer2: Vec<GuardNode>,
    pub layer3: Vec<GuardNode>,
    pub state_file: String,
    pub rendguard: RendGuard,
    pub pickle_revision: u32,
    pub enable_vanguards: bool,
}
Expand description

Persistent vanguard state containing guard layers and rendguard tracking.

Contains the layer 2 and layer 3 guard lists, along with rendguard state. This state is persisted to disk in Python pickle format for compatibility.

§Guard Layers

┌─────────────────────────────────────────────────────────────────────────┐
│                         VanguardState                                   │
│                                                                         │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │ Layer 2 Guards (HSLayer2Nodes)                                  │    │
│  │ • 4-8 guards (configurable)                                     │    │
│  │ • Lifetime: 1-45 days (configurable)                            │    │
│  │ • Used for second hop in HS circuits                            │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                                                         │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │ Layer 3 Guards (HSLayer3Nodes)                                  │    │
│  │ • 4-8 guards (configurable)                                     │    │
│  │ • Lifetime: 1-48 hours (configurable)                           │    │
│  │ • Used for third hop in HS circuits                             │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                                                         │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │ RendGuard                                                       │    │
│  │ • Tracks rendezvous point usage                                 │    │
│  │ • Detects statistical attacks                                   │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────┘

§State File Format

The state file uses Python pickle format with the following structure:

VanguardState {
    layer2: [GuardNode, ...],
    layer3: [GuardNode, ...],
    state_file: String,
    rendguard: RendGuard,
    pickle_revision: u32,
}

§Thread Safety

VanguardState is not thread-safe. It should be accessed from a single task or protected with appropriate synchronization.

§Example

use vanguards_rs::vanguards::VanguardState;
use std::path::Path;

// Load existing state or create new
let mut state = VanguardState::load_or_create(Path::new("vanguards.state"));

// Check current guards
println!("Layer 2: {}", state.layer2_guardset());
println!("Layer 3: {}", state.layer3_guardset());

// Save state
state.write_to_file(Path::new("vanguards.state")).unwrap();

§See Also

Fields§

§layer2: Vec<GuardNode>

Layer 2 guard nodes (second hop).

§layer3: Vec<GuardNode>

Layer 3 guard nodes (third hop).

§state_file: String

Path to the state file.

§rendguard: RendGuard

Rendezvous point usage tracking.

§pickle_revision: u32

Version number for pickle compatibility.

§enable_vanguards: bool

Whether vanguards are enabled (runtime flag, not persisted).

Implementations§

Source§

impl VanguardState

Source

pub fn new(state_file: &str) -> Self

Creates a new empty vanguard state.

Source

pub fn load_or_create(path: &Path) -> Self

Loads state from a file or creates new state if the file doesn’t exist.

§Arguments
  • path - Path to the state file
§Returns

The loaded or newly created state.

Source

pub fn read_from_file(path: &Path) -> Result<Self>

Reads state from a pickle file with validation.

Validates that:

  • All fingerprints are valid 40-character hex strings
  • No timestamps are in the future (with 1 hour tolerance)
  • The file format is valid
§Errors

Returns Error::State if the file cannot be read, parsed, or fails validation.

Source

pub fn validate(&self) -> Result<()>

Validates the state for integrity.

Checks:

  • All fingerprints are valid 40-character hex strings
  • No timestamps are in the future (with 1 hour tolerance for clock skew)
§Errors

Returns Error::State if validation fails.

Source

pub fn write_to_file(&self, path: &Path) -> Result<()>

Writes state to a pickle file with atomic write and secure permissions.

Uses atomic write (write to temp file, then rename) to prevent corruption. On Unix systems, sets file permissions to 0600 (owner read/write only).

§Errors

Returns Error::State if the file cannot be written.

Source

pub fn layer2_guardset(&self) -> String

Returns the layer 2 guard fingerprints as a comma-separated string.

Source

pub fn layer3_guardset(&self) -> String

Returns the layer 3 guard fingerprints as a comma-separated string.

Source

pub fn calculate_guard_lifetime(min_hours: u32, max_hours: u32) -> f64

Calculates a guard lifetime using max of two uniform random samples.

This distribution favors longer lifetimes, providing better security by reducing guard rotation frequency.

§Arguments
  • min_hours - Minimum lifetime in hours
  • max_hours - Maximum lifetime in hours
§Returns

Lifetime in seconds.

Source

pub fn add_new_layer2( &mut self, generator: &BwWeightedGenerator, excluded: &ExcludeNodes, config: &VanguardsConfig, ) -> Result<()>

Adds a new layer 2 guard.

Selects a guard using the provided generator, avoiding duplicates and excluded nodes.

Source

pub fn add_new_layer3( &mut self, generator: &BwWeightedGenerator, excluded: &ExcludeNodes, config: &VanguardsConfig, ) -> Result<()>

Adds a new layer 3 guard.

Selects a guard using the provided generator, avoiding duplicates and excluded nodes.

Source

pub fn remove_down_from_layer( layer: &mut Vec<GuardNode>, consensus_fps: &HashSet<String>, )

Removes guards that are no longer in the consensus.

Source

pub fn remove_expired_from_layer(layer: &mut Vec<GuardNode>)

Removes guards whose rotation time has expired.

Source

pub fn remove_excluded_from_layer( layer: &mut Vec<GuardNode>, router_map: &HashMap<String, &RouterStatusEntry>, excluded: &ExcludeNodes, )

Removes guards that match the ExcludeNodes configuration.

Source

pub fn replenish_layers( &mut self, generator: &BwWeightedGenerator, excluded: &ExcludeNodes, config: &VanguardsConfig, ) -> Result<()>

Replenishes guard layers to configured counts.

First trims layers if they exceed configured counts, then adds new guards until the configured count is reached.

Trait Implementations§

Source§

impl Clone for VanguardState

Source§

fn clone(&self) -> VanguardState

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for VanguardState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for VanguardState

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for VanguardState

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for VanguardState

Source§

fn eq(&self, other: &VanguardState) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for VanguardState

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for VanguardState

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,