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:


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

  1. Set Shell Options

    set -e
    
    • Enables "exit on error" mode, so the script stops if any command fails.

  2. Install Dependencies

    apk add bash curl jq
    
    • Installs 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).

  3. Snapshot Restoration

    if [ -n "$SNAPSHOT" ] && [ ! -d "$CHAINDATA_DIR" ]; then
      wget -c $SNAPSHOT -O - | tar -xvf - -C $DATA_DIR
    fi
    
    • Checks if SNAPSHOT variable is set and chaindata directory 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.

  4. 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 geth Ethereum client with Optimism Layer 2-specific flags:

      • --syncmode full: Run full synchronization mode.

      • --datadir $DATA_DIR: Use /data as 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 0 disables new peer connections, probably to run as a non-listening or restricted node.

      • --nodiscover disables peer discovery to avoid unsolicited connections.

    • Runs the process in the background (&) and captures its PID for later management.

  5. 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 geth process.

    • It then waits in a loop until the process exits, ensuring graceful shutdown.

  6. Signal Trapping

    trap 'stop' TERM INT
    
    • Sets up traps to catch termination (SIGTERM) and interrupt (SIGINT) signals.

    • When these signals are received, the stop function is called.

  7. Execution

    start
    wait $PID
    
    • Starts the geth daemon.

    • Waits for the geth process 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

Important Implementation Details


Interaction with Other System Components


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.