#!/bin/sh # Default to 4 nodes if no argument provided NUM_NODES="${1:-4}" # Validate input if ! echo "$NUM_NODES" | grep -qE '^[0-9]+$'; then echo "Error: Number of nodes must be a positive integer" echo "Usage: $0 [number_of_nodes]" echo "Example: $0 7" exit 1 fi if [ "$NUM_NODES" -lt 1 ]; then echo "Error: Number of nodes must be at least 1" exit 1 fi echo "Starting testnet with $NUM_NODES nodes (preserving existing data)..." # Check if testnet directory exists and has the expected number of nodes if [ ! -d "testnet/node0" ]; then echo "Error: No existing testnet found. Run ./startfresh-testnet.sh first to create the testnet." exit 1 fi # Count existing nodes existing_nodes=0 for i in $(seq 0 99); do if [ -d "testnet/node$i" ]; then existing_nodes=$((existing_nodes + 1)) else break fi done if [ "$NUM_NODES" -gt "$existing_nodes" ]; then echo "Error: Requested $NUM_NODES nodes but only $existing_nodes nodes exist in testnet/" echo "Run ./startfresh-testnet.sh $NUM_NODES to create additional nodes." exit 1 fi echo "Found $existing_nodes existing nodes, starting first $NUM_NODES nodes..." # Check if binary exists, build if needed if [ ! -f "./didplcbft" ]; then echo "Binary not found, building didplcbft..." go build -trimpath fi # Array to store background process IDs pids="" # Cleanup function to kill all background processes cleanup() { echo "" echo "Shutting down all nodes..." # Kill all background processes for pid in $pids; do if kill -0 "$pid" 2>/dev/null; then echo " Stopping node process $pid..." kill "$pid" 2>/dev/null fi done # Clean up temporary fifo files for i in $(seq 0 99); do rm -f "/tmp/didplcbft-node$i-stdout" "/tmp/didplcbft-node$i-stderr" 2>/dev/null done # Wait for all processes to terminate wait $pids 2>/dev/null echo "All nodes stopped." exit 0 } # Set up signal traps trap cleanup INT TERM EXIT # Launch all nodes in parallel echo "Launching $NUM_NODES nodes in parallel..." for i in $(seq 0 $((NUM_NODES - 1))); do if [ -d "testnet/node$i" ]; then echo " Starting node$i..." mkfifo "/tmp/didplcbft-node$i-stdout" 2>/dev/null || true mkfifo "/tmp/didplcbft-node$i-stderr" 2>/dev/null || true # Start sed processes to prefix output sed "s/^/[node$i-stdout] /" < "/tmp/didplcbft-node$i-stdout" & sed "s/^/[node$i-stderr] /" < "/tmp/didplcbft-node$i-stderr" & # Start the didplcbft process with redirected output ./didplcbft --data-dir "testnet/node$i" > "/tmp/didplcbft-node$i-stdout" 2> "/tmp/didplcbft-node$i-stderr" & pid=$! pids="$pids $pid" echo " PID: $pid" else echo " Warning: node$i directory not found, skipping..." fi done echo "" echo "All $NUM_NODES nodes are now running." echo "Press Ctrl+C to stop all nodes." echo "" # Wait for all background processes wait $pids # If we reach here, all processes have terminated normally echo "All nodes have terminated."