Files
super_ball_thrower/tests/helpers/timing_utils.sh
2025-12-17 09:43:21 -04:00

70 lines
1.7 KiB
Bash
Executable File

#!/bin/bash
# Timing Utilities for Superball Protocol Tests
# Get current timestamp in seconds
get_timestamp() {
date +%s
}
# Measure delay between two timestamps
measure_delay() {
local start_time=$1
local end_time=$2
echo $((end_time - start_time))
}
# Verify delay is within acceptable range (with jitter tolerance)
verify_delay() {
local expected=$1
local actual=$2
local tolerance=${3:-10} # Default 10% tolerance for jitter
local min=$((expected - expected * tolerance / 100))
local max=$((expected + expected * tolerance / 100))
if [ $actual -ge $min ] && [ $actual -le $max ]; then
return 0
else
echo "Delay verification failed: expected ${expected}s (±${tolerance}%), got ${actual}s"
return 1
fi
}
# Wait for event with timeout
wait_for_event() {
local event_id=$1
local relay=$2
local timeout=${3:-30}
local start_time=$(get_timestamp)
while true; do
local current_time=$(get_timestamp)
local elapsed=$((current_time - start_time))
if [ $elapsed -ge $timeout ]; then
echo "Timeout waiting for event $event_id"
return 1
fi
# Check if event exists on relay
if nak req --relay "$relay" -i "$event_id" --timeout 2 2>/dev/null | grep -q "$event_id"; then
echo $current_time
return 0
fi
sleep 1
done
}
# Calculate jitter percentage
calculate_jitter() {
local expected=$1
local actual=$2
local diff=$((actual - expected))
local abs_diff=${diff#-} # Absolute value
local jitter_pct=$((abs_diff * 100 / expected))
echo $jitter_pct
}