lib.rs
Overview
This file provides foundational utility functions and data structures for key management, address normalization, and time calculations within the system. It acts as a core utility module that supports authentication and contract interactions by offering:
A
KeyPairstruct representing a public and secret key pair.Functions to normalize blockchain-style addresses.
Functions to read cryptographic keys from JSON files.
Time utility functions to compute future timestamps.
Modules for authentication (
auth), owner wallet management (owner_wallet), and contract root handling (root_contracts).
The file also contains unit tests that validate the address normalization logic.
Modules
auth(public): Handles authentication-related functionalities. Refer to auth for detailed usage and implementation.owner_wallet(private): Manages owner wallet operations. See owner_wallet for further details.root_contracts(public): Manages root contract interactions. See root_contracts.
Structs
KeyPair
#[derive(Clone, Debug, Deserialize)]
pub struct KeyPair {
pub public: String,
pub secret: String,
}
Represents a cryptographic key pair with:
public: AStringcontaining the public key.secret: AStringcontaining the secret (private) key.
This struct derives Clone, Debug, and Deserialize traits, allowing it to be cloned, printed for debugging, and deserialized from formats like JSON.
Usage example:
let keypair = KeyPair {
public: "public_key_string".to_string(),
secret: "secret_key_string".to_string(),
};
Functions
now_plus_n_secs
fn now_plus_n_secs(ttl: u64) -> u128
Computes a future timestamp in milliseconds since UNIX epoch by adding ttl seconds to the current system time.
Parameters:
ttl: Number of seconds to add to the current time.
Returns: A
u128representing the future time in milliseconds since UNIX epoch.Panics: If system time is before UNIX epoch (time went backwards).
Algorithm details:
Uses
std::time::SystemTime::now()to get the current time.Adds a
Durationofttlseconds.Converts the result to milliseconds since UNIX epoch.
Usage example:
let future_time_ms = now_plus_n_secs(3600); // 1 hour from now
normalize_address
fn normalize_address(s: &str) -> Option<String>
Normalizes a blockchain address string by extracting a 64-character hexadecimal key from the input.
Parameters:
s: Input address string that may contain prefixes separated by a colon:.
Returns:
Some(String)containing the normalized 64-character hexadecimal address if valid.Noneif the address is invalid (wrong length or contains non-hex characters).
Implementation details:
Trims whitespace from the input.
Splits the string on the last colon (
:) and takes the substring after the colon if present.Validates that the remaining string is exactly 64 characters long and contains only hexadecimal characters.
Returns the normalized string or
Noneif validation fails.
Usage example:
let input = "0:8e8dad0462a4d5c528e18251846f24bc5c04cd1871115fb1e9b00c9741f60800";
let normalized = normalize_address(input);
assert_eq!(normalized, Some("8e8dad0462a4d5c528e18251846f24bc5c04cd1871115fb1e9b00c9741f60800".to_string()));
read_keys_from_file
pub fn read_keys_from_file(path: &str) -> Result<KeyPair, Box<dyn std::error::Error>>
Reads and deserializes a JSON file containing a KeyPair.
Parameters:
path: The file path as a string slice.
Returns:
Ok(KeyPair)on success.Errwrapping any I/O or deserialization error encountered.
Implementation details:
Opens the file at the given path.
Wraps the file in a buffered reader for efficient reading.
Uses
serde_json::from_readerto deserialize JSON content into theKeyPairstruct.
Usage example:
match read_keys_from_file("keys.json") {
Ok(keypair) => println!("Public key: {}", keypair.public),
Err(e) => eprintln!("Failed to read keys: {}", e),
}
Testing
The file includes comprehensive unit tests for normalize_address covering cases such as:
Plain 64-character hex strings.
Addresses with prefixes separated by colon (
:).Addresses with whitespace padding.
Invalid addresses that are too short, too long, or contain invalid characters.
These tests ensure robust parsing and normalization of address inputs.
Interaction with Other Parts of the System
The
authmodule likely uses theKeyPairstruct and normalization utilities to manage authentication credentials.owner_walletmodule may rely on key reading and address normalization to handle wallet operations securely.root_contractsinteracts with blockchain contracts and possibly requires normalized addresses and key pairs to sign transactions or verify identities.
This file acts as a utility and foundational layer, supporting key management and address validation across the system's authentication and blockchain-related components.
Mermaid Diagram: File Structure and Function Relationships
flowchart TD
A[lib.rs] --> B[KeyPair Struct]
A --> C["now_plus_n_secs()"]
A --> D["normalize_address()"]
A --> E["read_keys_from_file()"]
A --> F[auth module]
A --> G[owner_wallet module]
A --> H[root_contracts module]
C --> I[SystemTime.now]
D --> J[Address String Parsing]
E --> K[File IO]
E --> L[serde_json Deserialization]
This diagram illustrates the main components and their relationships within lib.rs, showing how utility functions and modules are interconnected.