> ## 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.

# Genesis Configuration and Network Initialization

## Purpose and Scope

This document explains how to generate the genesis block, initialize the chain, and prepare validator keys for the StableNet network. It covers both automated generation using the `genesis_generator` tool and manual genesis file authoring.

Related documents:

* [Node Configuration](/en/getting-started/2.2-node-configuration) — runtime options and configuration for initialized nodes
* [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview) — detailed structure and storage layout of system contracts
* [Network Deployment](/en/operations-guide/11.1-network-deployment) — production network deployment procedures
* [Validator Operations](/en/operations-guide/11.2-validator-operations) — validator node operation and key management

## Genesis File Structure

The genesis file is a JSON file that defines the initial state of the blockchain, including chain configuration, initial account allocations, and consensus parameters.

### Core Genesis Fields

`Genesis` structure:

| Field        | Type                  | Description                                                     |
| ------------ | --------------------- | --------------------------------------------------------------- |
| `Config`     | `*params.ChainConfig` | Chain configuration including fork rules and consensus settings |
| `Timestamp`  | `uint64`              | Genesis block timestamp                                         |
| `ExtraData`  | `[]byte`              | In Anzeon chains, WBFT validator information RLP-encoded        |
| `GasLimit`   | `uint64`              | Initial block gas limit                                         |
| `Difficulty` | `*big.Int`            | Initial difficulty (1 in Anzeon)                                |
| `Alloc`      | `types.GenesisAlloc`  | Pre-allocated accounts and deployed contract code               |
| `BaseFee`    | `*big.Int`            | EIP-1559 base fee                                               |

### Anzeon Consensus Configuration

For Anzeon/WBFT chains, the `ChainConfig` includes an `Anzeon` field.

This configuration defines two validator sets:

* **`Init`**: Validators active from block 1 until the first epoch (hardcoded in the genesis block ExtraData)
* **`SystemContracts.GovValidator`**: Validator set applied from the second epoch onward (modifiable via governance)

Unless there is a specific reason, these two sets should be identical.\
For details on the epoch transition mechanism, see [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol).

## System Contracts

StableNet deploys five system contracts at fixed addresses in the genesis block:

| Contract          | Address                                      | Purpose                                         |
| ----------------- | -------------------------------------------- | ----------------------------------------------- |
| NativeCoinAdapter | `0x0000000000000000000000000000000000001000` | ERC20 wrapper for the native coin               |
| GovValidator      | `0x0000000000000000000000000000000000001001` | Validator set management and gas tip governance |
| GovMasterMinter   | `0x0000000000000000000000000000000000001002` | Master minter registry                          |
| GovMinter         | `0x0000000000000000000000000000000000001003` | Mint/burn governance                            |
| GovCouncil        | `0x0000000000000000000000000000000000001004` | Blacklist and certified account governance      |

System contracts are deployed without owners and can only be upgraded via hard forks.\
For detailed initialization parameters, storage slots, and dependencies of each contract, see [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview).

### Genesis Initialization Parameters

The following parameters must be configured at genesis.

**GovValidator**:

| Parameter       | Description                                         | Default                     |
| --------------- | --------------------------------------------------- | --------------------------- |
| `members`       | Governance member addresses (comma-separated)       | Required                    |
| `validators`    | Validator addresses (comma-separated)               | Required                    |
| `blsPublicKeys` | BLS public keys (0x-prefixed, comma-separated)      | Required                    |
| `quorum`        | Minimum number of votes required to pass a proposal | Required                    |
| `expiry`        | Proposal expiration time (seconds)                  | 604800 (7 days)             |
| `memberVersion` | Member set version                                  | "1"                         |
| `maxProposals`  | Maximum concurrent proposals (1–50)                 | 3                           |
| `gasTip`        | Mandatory gas tip (wei)                             | 27600000000000 (27600 Gwei) |

`members`, `validators`, and `blsPublicKeys` are parallel lists managed in the same order.\
Values at the same index across lists define a single validator identity.

* **Operator address** (`members`): EOA or multisig address used for governance voting and validator registration/removal
* **Validator address** (`validators`): Address used for consensus message signing and coinbase (block fee recipient), derived from the node’s `nodekey`
* **BLS public key** (`blsPublicKeys`): BLS public key derived from the validator key, used for WBFT PREPARE/COMMIT aggregate signatures

For detailed key roles, derivation, and operational guidance, see [Validator Operations](/en/operations-guide/11.2-validator-operations).

**NativeCoinAdapter**:

| Parameter       | Description                        | Default     |
| --------------- | ---------------------------------- | ----------- |
| `name`          | Token name                         | "WKRC"      |
| `symbol`        | Token symbol                       | "WKRC"      |
| `decimals`      | Decimal places                     | "18"        |
| `currency`      | Fiat currency label                | "KRW"       |
| `masterMinter`  | GovMasterMinter contract address   | `0x...1002` |
| `minters`       | GovMinter contract address         | `0x...1003` |
| `minterAllowed` | Maximum mintable amount per minter | 10^28       |

## Validator Key Preparation

Each validator’s keys must be generated before network initialization.

### Node Key Generation

Use the `bootnode` utility to generate node keys:

```bash theme={null}
# Generate node key
bootnode -genkey nodekey

# Inspect derived address and BLS keys
bootnode -nodekey nodekey -writeaddress
```

Values derived from the node key:

| Derived Item      | Function                                    | Purpose                                       |
| ----------------- | ------------------------------------------- | --------------------------------------------- |
| Validator address | `crypto.PubkeyToAddress(nodeKey.PublicKey)` | Block signing address (coinbase)              |
| BLS private key   | `bls.DeriveFromECDSA(nodeKey)`              | Consensus message signing                     |
| BLS public key    | `blsKey.PublicKey().Marshal()`              | Registered in genesis (48 bytes, hex-encoded) |

For validator key security, rotation, and multisig operator keys, see [Validator Operations](/en/operations-guide/11.2-validator-operations).

## genesis\_generator Tool

`genesis_generator` is a CLI tool that generates a genesis file with correctly configured system contracts.

### Build

```bash theme={null}
cd go-stablenet
make genesis_generator

# Binary location: build/bin/genesis_generator
```

### Interactive Mode

Running without arguments starts interactive mode:

```bash theme={null}
./build/bin/genesis_generator
```

You will be prompted for:

1. **Consensus engine selection**: choose Anzeon (WBFT)
2. **Number of nodes**: single-node or multi-node
3. **Node key paths**: path to each validator’s node key file (default: `./nodekey`)
4. **Quorum configuration**: governance quorum for multi-node setups (min 2, max = validator count)
5. **Chain ID**: unique network identifier (random if omitted)

The tool automatically derives validator addresses and BLS keys from node keys.

### Command-Line Flags

Non-interactive usage is also supported ([`cmd/genesis_generator/genesis_generator.go` 50–100](https://github.com/stable-net/go-stablenet/blob/master/cmd/genesis_generator/genesis_generator.go#L50-L100)):

| Flag            | Type     | Description                                   | Default      |
| --------------- | -------- | --------------------------------------------- | ------------ |
| `--chainId`     | `int`    | Network chain ID                              | Random       |
| `--validators`  | `string` | Validator addresses (comma-separated)         | -            |
| `--blsKeys`     | `string` | BLS public keys (comma-separated)             | -            |
| `--members`     | `string` | Governance member addresses (comma-separated) | -            |
| `--quorum`      | `int`    | Governance quorum                             | -            |
| `--epochLength` | `int`    | Blocks per epoch                              | 10           |
| `--blockPeriod` | `int`    | Target block time (seconds)                   | 1            |
| `--gasLimit`    | `uint64` | Genesis block gas limit                       | -            |
| `--output`      | `string` | Output file path                              | genesis.json |

### Generation Examples

Single-validator network:

```bash theme={null}
./build/bin/genesis_generator \
  --chainId 9999 \
  --validators 0xaa5f...1234 \
  --blsKeys 0xaec4...5678 \
  --members 0xaa5f...1234 \
  --quorum 1 \
  --output genesis.json
```

Multi-validator network:

```bash theme={null}
./build/bin/genesis_generator \
  --chainId 9999 \
  --validators 0xaa5f...1234,0x294f...5678 \
  --blsKeys 0xaec4...abcd,0x91b2...efgh \
  --members 0xaa5f...1234,0x294f...5678 \
  --quorum 2 \
  --epochLength 10 \
  --blockPeriod 1 \
  --output genesis.json
```

### Genesis Validation

During generation, `genesis_generator` automatically validates:

1. Matching lengths of `Init.Validators` and `Init.BLSPublicKeys` arrays
2. Correct hex encoding and length (96 bytes) of each BLS public key
3. Valid Ethereum address format for all validator and member addresses
4. Valid ranges for epoch length, block period, and timeout values
5. Correct system contract addresses

## Chain Initialization

### Running gstable init

Initialize the chain database with the genesis file:

```bash theme={null}
# Initialize with default data directory
gstable init genesis.json

# Specify a custom data directory
gstable init genesis.json --datadir /data/gstable
```

Initialization steps:

1. Load genesis file and validate Anzeon configuration
2. Generate WBFT ExtraData from the initial validator set
3. Deploy system contracts via `InjectContracts()`
4. Commit the genesis block to the database

If an existing database is found, the provided genesis is checked against the stored genesis.\
A mismatch results in a `GenesisMismatchError`.

### Starting Nodes After Initialization

```bash theme={null}
# Start a validator node
gstable --datadir /data/gstable \
  --networkid 9999 \
  --mine \
  --nodekey /path/to/nodekey \
  --syncmode full \
  --port 30303

# With explicit bootnodes
gstable --datadir /data/gstable \
  --networkid 9999 \
  --bootnodes "enode://pubkey@ip:port"
```

For full runtime options, see [Node Configuration](/en/getting-started/2.2-node-configuration).

## Two-Phase Validator Initialization

StableNet manages validator sets in two phases:

**Phase 1: First Epoch (Block 1 \~ epochLength)**

* Defined in `Anzeon.Init.Validators`
* Hardcoded in the genesis block ExtraData
* Not modifiable via governance

**Phase 2: From Second Epoch Onward**

* Defined in `SystemContracts.GovValidator.Params`
* Validator set updated at epoch blocks by reading GovValidator contract state
* Modifiable via governance voting

This design allows the chain to bootstrap with a minimal validator set and then transition to governance-controlled validator management.\
For details, see [Validator Governance](/en/governance-system/5.3-validator-governance-\(govvalidator\)).

## Network-Specific Configuration

### Mainnet

* **Chain ID**: 8282
* **Network flag**: `--mainnet`
* **Bootnodes**: automatically configured (`params.StableNetMainnetBootnodes`)
* **Genesis**: embedded in the binary (no init required)

```bash theme={null}
# Start a Mainnet node (genesis auto-loaded)
gstable --mainnet --syncmode full --datadir /data/gstable
```

### Testnet

* **Chain ID**: 8283
* **Network flag**: `--testnet`
* **Bootnodes**: automatically configured (`params.StableNetTestnetBootnodes`)
* **Genesis**: embedded in the binary (no init required)

```bash theme={null}
# Start a Testnet node
gstable --testnet --syncmode full --datadir /data/gstable
```

### Private Network

Private networks require a custom genesis file.

**Setup procedure:**

1. Generate node keys for each validator (`bootnode -genkey`)
2. Generate the genesis file using `genesis_generator`
3. Run `gstable init genesis.json` on all nodes
4. Start nodes with `--networkid` and `--bootnodes` specified

**Recommended parameters for private networks:**

| Parameter     | Development                                     | Production              |
| ------------- | ----------------------------------------------- | ----------------------- |
| `chainId`     | Unique value not colliding with public networks | Same                    |
| `epochLength` | 5–10 (fast validator changes)                   | 100+                    |
| `blockPeriod` | 1 second                                        | 1–3 seconds             |
| `quorum`      | 1 (single node)                                 | ≥ 2/3 of validators     |
| `gasLimit`    | Default                                         | Adjust to network needs |

**Private network startup example:**

```bash theme={null}
# 1. Generate node keys
bootnode -genkey nodekey1
bootnode -genkey nodekey2

# 2. Generate genesis (interactive mode recommended)
./build/bin/genesis_generator

# 3. Initialize each node
gstable init genesis.json --datadir /data/node1
gstable init genesis.json --datadir /data/node2

# 4. Start the first node
gstable --datadir /data/node1 \
  --networkid 9999 \
  --mine \
  --nodekey nodekey1 \
  --syncmode full \
  --port 30303

# 5. Start the second node (using the first as bootnode)
gstable --datadir /data/node2 \
  --networkid 9999 \
  --mine \
  --nodekey nodekey2 \
  --syncmode full \
  --port 30304 \
  --bootnodes "enode://<node1-pubkey>@<node1-ip>:30303"
```

For production deployment checklists, Docker deployment, and Debian packages, see [Network Deployment](/en/operations-guide/11.1-network-deployment).

## Post-Initialization Verification

After initialization, verify the following:

```bash theme={null}
# Attach to the node
gstable attach /data/gstable/gstable.ipc

# Check chain ID
> eth.chainId()

# Check genesis block
> eth.getBlock(0)

# Check validator set (system contract call)
> eth.call({to: "0x0000000000000000000000000000000000001001", data: "0x..."})

# Check peer connections
> admin.peers.length

# Check mining status (validator node)
> eth.mining

# Check block production
> eth.blockNumber
```

## Common Initialization Issues and Resolutions

### Genesis Mismatch Error

**Error**: `GenesisMismatchError: database contains incompatible genesis`

**Cause**: Attempting to initialize with a genesis file that does not match the existing database.

**Resolution**:

```bash theme={null}
# Option 1: Remove existing chain data and reinitialize
rm -rf /data/gstable/gstable/chaindata
gstable init genesis.json --datadir /data/gstable

# Option 2: Use the correct genesis.json matching the existing chain
```

### Validator Count Mismatch

**Error**: `Invalid genesis config: validator count mismatch`

**Cause**: Length mismatch between `Init.Validators` and `Init.BLSPublicKeys`.

**Resolution**: Ensure `members`, `validators`, and `blsPublicKeys` all have the same number of entries.

### System Contract Deployment Failure

**Error**: `Failed to inject system contracts`

**Cause**: Invalid initialization parameters or missing contract bytecode.

**Resolution**: Verify system contract parameters, especially address format (`0x` prefix, 40 hex chars) and comma-separated list syntax.

### BLS Key Format Error

**Error**: `Invalid BLS public key format`

**Cause**: Incorrect hex encoding or length of the BLS key.

**Resolution**: BLS public keys must include a `0x` prefix and be exactly 98 characters long\
(`0x` + 96-byte hex encoding = `0x` + 192 hex characters).\
Verify using `bootnode -nodekey`.

### Init vs GovValidator Validator Mismatch Warning

If `Init.Validators` and `SystemContracts.GovValidator.Params.validators` differ, the validator set will change at the transition from the first to the second epoch.\
Unless intentional, keep both sets identical.
