> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stablenet.network/llms.txt
> Use this file to discover all available pages before exploring further.

# Node Initialization and Lifecycle

## Purpose and Scope

This document describes the initialization sequence and lifecycle management of a StableNet node.\
It covers the process from command-line invocation to full shutdown, including configuration loading, genesis setup, component initialization, service coordination, and graceful termination.

Related documents:

* Genesis file creation and network initialization: [Genesis Setup and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization)
* Consensus-specific initialization (WBFT): [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol)
* General node configuration options: [Node Configuration](/en/getting-started/2.2-node-configuration)

## Overall Initialization Sequence

Node initialization follows the sequence below, from CLI flag parsing to a fully running node:

```
CLI flag parsing → configuration loading → node.Node creation
→ eth.Ethereum backend initialization (DB, chain, pool, miner)
→ API/protocol registration → service startup → runtime monitoring
```

## Configuration Phase

### Flag Parsing and Data Directory Setup

At startup, the node initializes internal defaults and then applies configuration in the following order: network presets, configuration files, and command-line flags, to determine the final runtime configuration.\
Settings applied later override values set in earlier stages.

| Order | Configuration Source    | Description                                         |
| ----: | ----------------------- | --------------------------------------------------- |
|     4 | Command-line flags      | Final overrides specified at runtime                |
|     3 | TOML configuration file | User-defined persistent settings                    |
|     2 | Network presets         | Network-specific defaults such as Mainnet / Testnet |
|     1 | Hardcoded defaults      | Initial defaults defined in code                    |

If the data directory is not explicitly specified, an internal default directory is used.

### Genesis Block Initialization

The genesis block defines the initial state of the blockchain. The node loads an existing genesis from the database, or initializes a new one if none exists.

For Anzeon/WBFT networks, genesis initialization includes the following additional steps:

1. Constructing the initial validator set including BLS public keys
2. Deploying system contracts (GovValidator, NativeCoinAdapter, etc.)
3. Encoding WBFT-specific Extra data
4. Setting initial gas tip parameters

## Node and Backend Creation

### Node Container

`node.Node` acts as the service orchestrator. It manages the P2P server, RPC endpoints, and registered services, and receives sub-services via `RegisterLifecycle()` and `RegisterAPIs()`.

### Ethereum Backend Initialization

`eth.Ethereum` is the main service implementing the full protocol. The `eth.New()` constructor performs initialization in the following order:

1. **Database setup**: Open the chaindata database including ancient/freezer storage
2. **State scheme selection**: Configure hash-based or path-based state storage
3. **Consensus engine creation**: Select WBFT, Clique, or Ethash based on chain configuration
4. **Etherbase setup**: Automatically derived from the node key for Anzeon networks
5. **BlockChain creation**: Load genesis and configure caches and snapshots
6. **Transaction pool setup**: Initialize legacypool and blobpool
7. **Protocol handler creation**: Configure P2P synchronization and propagation logic
8. **Miner creation**: Initialize the block assembly worker
9. **API and lifecycle registration**: Register RPC APIs, P2P protocols, and service lifecycles

### Transaction Pool Initialization

The transaction pool consists of two sub-pools:

* **legacypool**: Handles standard transactions and StableNet-specific transaction types
* **blobpool**: Handles EIP-4844 blob transactions

In Anzeon networks, the minimum gas tip is initialized from the GovValidator contract and applied to both the miner and the transaction pool.

### Miner and Consensus Integration

The Worker runs the following four main goroutines:

* **mainLoop**: Handles work requests and transaction events
* **newWorkLoop**: Triggers new block creation (WBFT: driven by consensus round events)
* **taskLoop**: Manages sealing tasks by calling `engine.Seal()`
* **resultLoop**: Processes sealed blocks and inserts them into the chain

## Service Registration and Lifecycle Management

### API Registration

The backend exposes the following RPC API namespaces:

* `eth`: Core Ethereum RPC methods
* `miner`: Block production control
* `admin`: Node and peer management
* `debug`: Tracing and diagnostic utilities
* `net`: Network information
* Consensus-engine-specific APIs (e.g., WBFT management functions)

### Protocol Registration

P2P protocols handle peer-to-peer communication:

* **eth**: Block and transaction propagation
* **snap**: State snapshot synchronization (if enabled)
* **wbft**: WBFT consensus message exchange

## Node Startup and Runtime

When `StartNode()` is called, services are started in registration order via `stack.Start()`, and runtime monitoring is enabled.

### Disk Space Monitoring

The node periodically monitors disk space to prevent data corruption due to low disk conditions.

* If `--datadir.minfreedisk` is set, that threshold is used
* Otherwise, an internal default threshold is applied
* A value of 0 disables monitoring

## Graceful Shutdown Sequence

When a shutdown signal is received or low disk space is detected, the node performs an orderly shutdown.

**Shutdown characteristics:**

* Services are stopped in reverse startup order
* Repeated signals can force termination
* The shutdown process is traced and logged
* All pending state changes are flushed to disk

### Shutdown Tracker

The shutdown tracker (`shutdowncheck`) detects abnormal terminations:

* Writes a shutdown marker at startup
* Removes the marker on graceful shutdown
* If a marker remains, the previous run is considered abnormal and a warning is logged

This mechanism enables early detection of potential database corruption.

## Consensus-Specific Initialization

### WBFT Consensus Startup

For Anzeon/WBFT networks, the following additional initialization steps are performed:

1. **Automatic etherbase setup**: Forced to the address derived from the node key
2. **Gas tip initialization**: Load the network-wide value from the GovValidator contract
3. **WBFT engine startup**: Start the engine with consensus round callbacks registered
4. **Worker WBFT mode activation**: Use an event-driven block production loop based on consensus signals

## Component Summary

| Component        | Initialization Function             | Primary Responsibility                            |
| ---------------- | ----------------------------------- | ------------------------------------------------- |
| Node             | `node.New()`                        | Service coordination, P2P server, RPC endpoints   |
| Ethereum Backend | `eth.New()`                         | Full protocol implementation and component wiring |
| Blockchain       | `core.NewBlockChain()`              | Canonical chain management and validation         |
| Transaction Pool | `txpool.New()`                      | Pending transaction management                    |
| Miner            | `miner.New()`                       | Block production coordination                     |
| Worker           | `newWorker()`                       | Transaction selection and block assembly          |
| Consensus Engine | `ethconfig.CreateConsensusEngine()` | Block validation and sealing                      |
| Protocol Handler | `newHandler()`                      | Block and transaction propagation                 |
| Downloader       | `downloader.New()`                  | Chain synchronization                             |
| P2P Server       | `p2p.Server`                        | Peer connections and protocol multiplexing        |
