Module utils

Module utils 

Source
Expand description

Utility functions for CHIE Protocol.

Structs§

BucketedTimeSeries
Bucketed time series for aggregating metrics into fixed time intervals.
CircuitBreaker
Circuit breaker for fault tolerance
ExponentialBackoff
Exponential backoff calculator for retry logic.
Histogram
Histogram for tracking value distributions (e.g., latency).
SlidingWindow
Sliding window for time-series analytics.
SlidingWindowRateLimiter
Rate limiter using sliding window algorithm.
StreamingStats
Streaming statistics calculator using Welford’s online algorithm. Computes mean, variance, and standard deviation in a single pass without storing all values in memory.
TimeBucket
Fixed-size time bucket for aggregating metrics over time periods.
TimeWindow
Time window for tracking events within a specific time period.

Enums§

CircuitState
Circuit breaker states

Functions§

actual_chunk_size
Calculate the actual size of a specific chunk (last chunk may be smaller).
average
Calculate the average of two values.
batch_by_size
Batch items into groups where the size of each batch is determined by a size function. Ensures no batch exceeds max_size.
bps_to_mbps
Convert bits per second to megabits per second.
byte_to_chunk_index
Calculate which chunk contains a given byte offset. Returns the chunk index that contains the specified byte.
bytes_to_gb_f64
Convert bytes to gigabytes with precision (f64 version for non-const contexts).
calculate_bandwidth_mbps
Calculate bandwidth in Mbps from bytes and duration.
calculate_content_price
Calculate content pricing based on size and demand.
calculate_creator_share
Calculate creator share from total points.
calculate_demand_multiplier
Calculate reward multiplier based on demand/supply ratio.
calculate_ema
Calculate exponential moving average.
calculate_growth_rate
Calculate compound growth rate.
calculate_latency_ms
Calculate latency from start and end timestamps.
calculate_mean
Calculate mean of values.
calculate_median
Calculate median of a slice of values.
calculate_moving_average
Calculate moving average over a window.
calculate_percentage
Calculate percentage with proper rounding.
calculate_percentage_change
Calculate percentage change between two values. Returns positive for increase, negative for decrease. Returns 0.0 if old_value is 0.
calculate_percentile
Calculate percentile of a slice of values (p should be between 0.0 and 1.0).
calculate_platform_fee
Calculate platform fee from total points.
calculate_provider_earnings
Calculate provider earnings after fees and creator share.
calculate_rate
Calculate rate (events per time unit). Returns events per second.
calculate_reputation_bonus
Calculate reputation boost for consistent good behavior.
calculate_reputation_decay
Calculate reputation score with decay over time.
calculate_reward_with_penalty
Calculate reward with multiplier and penalty based on latency.
calculate_sliding_window_count
Calculate sliding window rate limit.
calculate_stats
Calculate min, max, and average from a slice of values.
calculate_std_dev
Calculate standard deviation from a slice of values.
calculate_storage_cost
Calculate storage cost per month (points per GB).
calculate_token_bucket
Calculate tokens available in a token bucket.
calculate_uptime_percentage
Calculate uptime percentage from total time and downtime.
calculate_z_score
Calculate z-score for anomaly detection.
chunk_byte_range
Get the byte range (start, end) for a specific chunk. Returns (start_byte, end_byte_exclusive) for the chunk.
chunk_offset
Calculate the byte offset for a chunk index. Returns the starting byte position in the content for the given chunk.
chunk_vec
Split a vector into chunks of specified size. Returns a vector of vectors, where each inner vector has at most chunk_size elements.
cid_to_short_id
Generate a short identifier (8 chars) from a CID for display purposes. Takes first 8 characters after “Qm” prefix if present, otherwise first 8 chars.
clamp
Clamp a value between a minimum and maximum.
constant_time_eq
Constant-time comparison of two byte slices to prevent timing attacks. Returns true if slices are equal, false otherwise. This is critical for comparing signatures, hashes, and nonces securely.
constant_time_eq_32
Constant-time comparison of two 32-byte arrays (common for hashes/keys). Optimized version for fixed-size arrays.
count_set_bits
Count the number of set bits (1s) in a byte slice.
decode_hex
Decode hexadecimal string to bytes.
deduplicate_preserve_order
Deduplicate a vector while preserving order.
encode_hex
Encode bytes as hexadecimal string.
estimate_transfer_time
Calculate estimated transfer time in seconds.
extract_peer_id_from_multiaddr
Extract the peer ID from a libp2p multiaddress string. Example: “/ip4/127.0.0.1/tcp/4001/p2p/QmPeerId” -> “QmPeerId”
find_duplicates
Find duplicate items in a vector. Returns a vector of items that appear more than once.
flatten
Flatten a vector of vectors into a single vector.
format_bandwidth
Format bandwidth as string.
format_bytes
Format bytes as human-readable string (KB, MB, GB, TB).
format_duration_ms
Format duration in milliseconds as human-readable string.
format_points
Format points with thousands separator.
format_ratio_as_percentage
Format a ratio as a percentage string.
format_timestamp
Format Unix timestamp (milliseconds) as human-readable string. Returns format like “2024-12-16 14:30:45 UTC”.
gb_to_bytes_f64
Convert gigabytes to bytes (f64 version for non-const contexts).
generate_nonce
Generate a random nonce for challenge-response.
generate_session_id
Generate a human-readable session ID.
generate_slug
Generate URL-friendly slug from a string. Converts to lowercase, replaces spaces/special chars with hyphens, removes consecutive hyphens.
get_file_extension
Get file extension from filename. Returns the extension without the dot, or empty string if no extension.
group_by
Group items by a key extraction function. Returns a HashMap where keys are the result of the key function and values are vectors of items.
has_valid_extension
Check if a filename has a valid extension (non-empty and alphanumeric).
is_all_zeros
Check if all bytes in a slice are zero.
is_outlier_iqr
Check if value is an outlier using IQR method.
is_private_ipv4
Check if an IPv4 address is in a private range. Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8.
is_rate_limit_allowed
Check if an action is allowed under rate limiting (token bucket).
is_safe_string
Check if a string contains only safe characters (no control chars except whitespace).
is_timestamp_valid
Check if a timestamp is within the valid range (not too old, not in future).
is_valid_chunk_index
Check if a chunk index is valid for the given content size.
is_valid_cid
Parse content CID and validate basic format.
is_valid_email
Validate email format (basic check).
is_valid_hex
Verify hex string is valid.
is_valid_ipv4
Validate IPv4 address format.
is_valid_ipv6
Validate IPv6 address format (basic check).
is_valid_multiaddr
Parse multiaddr and check if it’s valid (basic check).
is_valid_peer_id
Check if a peer ID format is valid (basic check).
is_valid_peer_id_format
Validate peer ID format (basic check for IPFS/libp2p peer IDs). Checks if it starts with common prefixes and has reasonable length.
is_valid_port
Validate port number.
is_valid_url
Validate HTTP/HTTPS URL format.
is_valid_username
Validate username (alphanumeric, underscore, hyphen, 3-20 chars).
is_within_tolerance
Check if a value is within a tolerance of a target.
lerp
Linear interpolation between two values.
mbps_to_bps
Convert megabits per second to bits per second.
merge_sorted
Merge two sorted vectors into a single sorted vector.
mime_to_category_hint
Detect common file types from MIME type strings. Returns a category hint that can help with content classification.
ms_to_secs
Convert milliseconds to seconds.
normalize
Normalize a value to 0.0-1.0 range based on min and max bounds. Values outside bounds are clamped to 0.0 or 1.0.
normalize_tag
Normalize tag for search/comparison.
now_ms
Get current Unix timestamp in milliseconds.
now_secs
Get current Unix timestamp in seconds.
parse_bandwidth_str
Parse bandwidth from string (e.g., “100 Mbps”, “1 Gbps”).
parse_duration_str
Parse human-readable duration string to milliseconds. Supports formats like “1h30m”, “45s”, “2h”, “500ms”. Returns None if the format is invalid.
partition
Partition a vector into two vectors based on a predicate. Returns (matching, non_matching).
random_jitter
Apply random jitter to a value for backoff/retry timing.
rotate_bytes_left
Rotate bytes left by n positions. Wraps around: [1,2,3,4] rotated left by 1 = [2,3,4,1]
rotate_bytes_right
Rotate bytes right by n positions. Wraps around: [1,2,3,4] rotated right by 1 = [4,1,2,3]
round_down_to_multiple
Round down to the nearest multiple of n.
round_up_to_multiple
Round up to the nearest multiple of n.
sanitize_string
Sanitize string for display (remove control characters).
sanitize_tag
Sanitize a tag by trimming whitespace and converting to lowercase.
sanitize_tags
Validate and sanitize a list of tags.
secs_to_ms
Convert seconds to milliseconds.
skip
Skip the first N items and return the rest.
take
Take the first N items from a vector.
truncate_string
Truncate a string to a maximum length, adding “…” if truncated.
update_reputation
Update reputation based on success/failure events.
validate_and_sanitize_tag
Sanitize and validate tag.
validate_bandwidth_reasonable
Validate bandwidth is not suspiciously high.
validate_blake3_hash
Validate BLAKE3 hash format (32 bytes).
validate_challenge_nonce
Validate challenge nonce format (32 bytes).
validate_chunk_indices_batch
Batch validate chunk indices are within bounds.
validate_chunk_size
Validate chunk size is within acceptable range.
validate_cids_batch
Batch validate CIDs and return invalid ones.
validate_content_size_in_range
Validate content size is within platform limits.
validate_ed25519_public_key
Validate Ed25519 public key format (32 bytes).
validate_ed25519_signature
Validate Ed25519 signature format (64 bytes).
validate_emails_batch
Batch validate emails and return invalid ones.
validate_hash_length
Validate hash has correct length.
validate_latency
Validate latency is within acceptable range.
validate_nonce_length
Validate nonce has correct length.
validate_price_range
Validate price is within acceptable range.
validate_proof_freshness
Validate proof timestamp is recent (within tolerance).
validate_public_key_length
Validate public key has correct length.
validate_signature_length
Validate signature has correct length.
validate_tags_list
Validate all tags in a list and return valid ones.
validate_usernames_batch
Batch validate usernames and return invalid ones.
xor_bytes
XOR two byte slices into a new vector. Returns a vector with the XOR of each byte pair. If slices have different lengths, uses the shorter length.
zip_with
Zip two vectors together, stopping at the length of the shorter vector.