init.sh
Overview
`init.sh` is a shell script designed to initialize and run an Optimism (an Ethereum Layer 2) blockchain node using the `geth` client with specific configurations. It automates environment setup, optional snapshot restoration, node startup, and graceful shutdown handling within a containerized environment.
This script ensures:
Required system packages (
bash,curl,jq) are installed.If a snapshot URL is provided and the blockchain data directory is empty, it downloads and extracts the snapshot to bootstrap the node quickly.
Launches the
gethEthereum client with Optimism-specific flags enabling full synchronization, HTTP and WebSocket RPC APIs, and sequencer connectivity.Handles termination signals (
SIGTERM,SIGINT) gracefully by shutting down thegethprocess cleanly.Keeps the container alive by waiting on the
gethprocess.
Detailed Explanation
Global Variables
Variable | Description |
|---|---|
`DATA_DIR` | Base directory for blockchain data (`/data`). |
`CHAINDATA_DIR` | Path to the `geth` chain data directory (`$DATA_DIR/geth/chaindata`). |
`SNAPSHOT` | Environment variable expected to hold a URL to a blockchain snapshot archive (optional). |
`PID` | Process ID of the running `geth` daemon (assigned when starting). |
Script Steps and Logic
Set Shell Options
set -eEnables "exit on error" mode, so the script stops if any command fails.
Install Dependencies
apk add bash curl jqInstalls essential utilities:
bash: shell interpreter (some scripts or commands may require it).curl: for fetching data from URLs.jq: JSON processor (may be used in extended scripts or for debugging).
Snapshot Restoration
if [ -n "$SNAPSHOT" ] && [ ! -d "$CHAINDATA_DIR" ]; then wget -c $SNAPSHOT -O - | tar -xvf - -C $DATA_DIR fiChecks if
SNAPSHOTvariable is set andchaindatadirectory does not exist.If true, downloads the snapshot archive from the URL and extracts it directly into
$DATA_DIR.This step bootstraps the node state from a snapshot, significantly speeding up sync.
Start Function
start() { geth \ --syncmode full \ --datadir $DATA_DIR \ --authrpc.jwtsecret /jwt.hex \ --authrpc.port 8551 \ --http \ --http.addr 0.0.0.0 \ --http.port 8545 \ --http.api eth,net,web3,debug,txpool,engine \ --http.vhosts "*" \ --http.corsdomain "*" \ --ws \ --ws.addr 0.0.0.0 \ --ws.port 8546 \ --ws.api eth,net,web3,debug,txpool,engine \ --ws.origins "*" \ --rollup.disabletxpoolgossip=true \ --rollup.sequencerhttp https://mainnet-sequencer.optimism.io \ --op-network op-mainnet \ --history.transactions 0 \ --cache 4096 \ --maxpeers 0 \ --nodiscover & PID="$!" }Launches the
gethEthereum client with Optimism Layer 2-specific flags:--syncmode full: Run full synchronization mode.--datadir $DATA_DIR: Use/dataas the data directory.--authrpc.jwtsecret /jwt.hex: Path to JWT secret file for authenticated RPC.--authrpc.port 8551: Port for authenticated RPC.HTTP and WebSocket servers enabled on all interfaces (
0.0.0.0) to expose RPC APIs on standard Ethereum ports (8545 HTTP, 8546 WS).APIs enabled:
eth,net,web3,debug,txpool,engine.Cross-origin and host headers are set permissively (
*) for broad accessibility.Rollup-specific flags disable txpool gossip and connect to the Optimism mainnet sequencer endpoint.
Network set to
op-mainnet.Transaction history indexing disabled (
--history.transactions 0).Cache size set to 4096 MB.
--maxpeers 0disables new peer connections, probably to run as a non-listening or restricted node.--nodiscoverdisables peer discovery to avoid unsolicited connections.
Runs the process in the background (
&) and captures its PID for later management.
Stop Function
stop() { echo "Catching signal and sending to PID: $PID" && kill $PID while $(kill -0 $PID 2>/dev/null); do sleep 1; done }On receiving termination signals, this function sends a kill signal to the
gethprocess.It then waits in a loop until the process exits, ensuring graceful shutdown.
Signal Trapping
trap 'stop' TERM INTSets up traps to catch termination (
SIGTERM) and interrupt (SIGINT) signals.When these signals are received, the
stopfunction is called.
Execution
start wait $PIDStarts the
gethdaemon.Waits for the
gethprocess to exit, keeping the container running as long as the node is active.
Usage Example
Assuming the environment variable `SNAPSHOT` is set to a valid snapshot archive URL (optional), run the script as:
export SNAPSHOT="https://example.com/optimism_snapshot.tar.gz"
./init.sh
The script will install dependencies, restore snapshot if needed, and start the Optimism
gethnode.The container or process will remain alive until interrupted.
On receiving
SIGTERMorSIGINT, the node shuts down gracefully.
Important Implementation Details
The script uses
apk(Alpine Linux’s package manager), indicating it is designed for Alpine-based container images.Snapshot restoration is conditional and done only if the chain data does not exist, preventing overwriting existing data.
The
gethcommand is tailored specifically for Optimism L2, with rollup-related flags and sequencer URL.The node exposes both HTTP and WebSocket interfaces with broad API access, useful for external clients and monitoring.
The script disables peer discovery and new peers, suggesting this node is intended for read-only or sequencer-related roles rather than full peer participation.
Signal trapping enables Kubernetes or container orchestrators to cleanly shut down the node process.
Interaction with Other System Components
Data Persistence: Uses
/datavolume mount expected to be persistent storage for blockchain data.Snapshot Source: External snapshot URL allows quick syncing; snapshots may come from trusted upstream sources or internal caching systems.
JWT Secret: Expects a file
/jwt.hexcontaining the JWT secret to secure authenticated RPC endpoints.Sequencer HTTP Endpoint: Connects to the Optimism sequencer service (
mainnet-sequencer.optimism.io) to participate in rollup coordination.Container Orchestration: Designed for running in container environments (e.g., Kubernetes), which manage lifecycle events and health monitoring.
RPC Consumers: The exposed HTTP and WS endpoints serve clients such as indexers, wallets, explorers, or APIs that query or interact with the Optimism blockchain.
Mermaid Diagram: Flowchart of Main Functions and Signal Handling
flowchart TD
A[Start Script] --> B[Install dependencies: bash, curl, jq]
B --> C{Is SNAPSHOT set and chaindata missing?}
C -- Yes --> D[Download and extract snapshot to /data]
C -- No --> E[Skip snapshot restoration]
D --> E
E --> F[Start geth daemon with Optimism flags]
F --> G[Store geth PID]
G --> H[Wait for geth process]
H --> I{Signal Received?}
I -- SIGTERM or SIGINT --> J[Call stop function]
J --> K[Send kill to geth PID]
K --> L[Wait until geth exits]
L --> M[Exit script]
I -- No --> H
Summary
This `init.sh` script is a crucial initialization utility for running an Optimism blockchain node in containerized environments. It handles environment setup, optional snapshot bootstrapping, launches `geth` with rollup-specific configurations exposing RPC APIs, and traps termination signals for graceful shutdown. Its modular and straightforward design enables reliable lifecycle management, essential for deploying blockchain nodes in production-grade orchestrated systems.