# Anzeon WBFT Consensus Protocol Source: https://docs.stablenet.network/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol ## Purpose and Scope This document provides an in-depth technical description of the Anzeon WBFT consensus protocol used in StableNet.\ It covers the Byzantine fault tolerance mechanism, epoch-based validator management, BLS signature aggregation, block production integration, and the relationships between consensus components and system contracts. For information on validator set management through governance and voting, see [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)).\ For details on block production and transaction selection, refer to [Block Production and Mining](/en/consensus-and-block-production/4.2-block-production-and-mining). ## Overview Anzeon WBFT is a specialized variant of the WEMIX Byzantine Fault Tolerance (WBFT) consensus engine, adapted to StableNet’s Proof-of-Authority architecture.\ WBFT is an evolution of QBFT (Quorum Byzantine Fault Tolerance) that preserves Byzantine fault tolerance while providing scalability tailored to operational environments. ### Relationship Between WBFT and QBFT | Protocol | Characteristics | Target Network | | --------------- | -------------------------------------------------------- | ------------------------ | | **QBFT** | Base BFT, permissioned validators | Private / PoA networks | | **WBFT** | QBFT + staking + diligence + slashing | Public / Hybrid networks | | **Anzeon WBFT** | WBFT with staking and rewards removed, optimized for PoA | StableNet | ### Key Modifications in Anzeon WBFT Anzeon WBFT removes or simplifies the following elements from standard WBFT to align with StableNet’s stablecoin-oriented design. * **Removal of staking mechanism**: Validator eligibility is determined through GovValidator governance, not token staking * **Removal of block rewards**: No new token issuance; validators earn only transaction fees * **Removal of legacy WPoA**: Uses a pure WBFT engine without backward compatibility layers * **Diligence-based rewards**: BaseFee is distributed to validators based on diligence metrics * **Governance-driven configuration**: Validator sets and gas tips are managed by system contracts ### Consensus Properties | Property | Value | | ----------------------------- | -------------------------------------------------- | | **Byzantine Fault Tolerance** | Tolerates up to f = ⌊(n-1)/3⌋ Byzantine validators | | **Finality** | Immediate (final), no rollback | | **Block Time** | Configurable, default 1 second | | **Epoch Length** | Configurable, default 10 blocks | | **Signature Scheme** | BLS12-381 aggregated signatures | | **Proposer Selection** | Default round-robin, configurable | ## Configuration and Initialization ### AnzeonConfig Structure The `AnzeonConfig` structure in the chain configuration defines all parameters required for WBFT consensus. #### WBFT Configuration Fields | Field | Type | Description | | -------------------------- | --------- | ------------------------------- | | `EpochLength` | `uint64` | Number of blocks per epoch | | `BlockPeriodSeconds` | `uint64` | Target time between blocks | | `RequestTimeoutSeconds` | `uint64` | Initial consensus round timeout | | `MaxRequestTimeoutSeconds` | `*uint64` | Maximum timeout value | | `ProposerPolicy` | `*uint64` | Proposer selection policy | #### Init Configuration The `Init` section defines the initial validator set active during the first epoch.\ This set applies from block 1 through the first epoch block; afterward, the validator set managed by the GovValidator contract is used. ### Genesis Configuration Example The initial validator set and WBFT parameters must be explicitly included in the genesis block, and responsibility for validator management is transferred to GovValidator after epoch 1. ## Consensus Architecture ### Rounds and Epochs Anzeon WBFT divides the consensus process into two layers: **epochs** and **rounds**. An **epoch** consists of a fixed number of blocks, and validator set changes are only allowed at epoch blocks.\ A **round** represents a single attempt to reach consensus for a given block; if it fails, the protocol transitions to the next round with an increased timeout. ### Block Period and Timeouts | Timer | Purpose | | -------------------------- | ------------------------- | | `BlockPeriodSeconds` | Block production interval | | `RequestTimeoutSeconds` | Initial consensus timeout | | `MaxRequestTimeoutSeconds` | Maximum timeout | Timeouts increase exponentially as rounds progress and never exceed the configured maximum. ## Byzantine Fault Tolerance Mechanism Anzeon WBFT uses a two-phase commit protocol consisting of PREPARE and COMMIT phases, leveraging BLS signature aggregation in each phase. ### BLS Signature Aggregation BLS aggregated signatures combine signatures from multiple validators into a single signature, significantly reducing network overhead and verification cost. * Reduced signature size * Single verification operation * Safety guaranteed with 2f+1 signatures ### Quorum Requirements With n validators and f = ⌊(n-1)/3⌋ tolerated Byzantine validators, the required number of signatures is as follows: | Phase | Quorum Size | | ----------- | ----------- | | **PREPARE** | 2f + 1 | | **COMMIT** | 2f + 1 | ## Validator Set Management ### EpochInfo Structure `EpochInfo` contains the validator set information valid for a specific epoch and is encoded in the `WBFTExtra` field of the block header. ### Epoch Transition Process The following steps are performed during an epoch transition: 1. Check whether the current block is an epoch block 2. Retrieve the latest validator list from the GovValidator contract 3. Construct a new EpochInfo 4. Embed it in the first block header of the epoch 5. Activate the new validator set ## Block Production Integration Unlike standard Ethereum consensus, Anzeon WBFT triggers the worker through the consensus engine. ### WBFT Worker Loop In WBFT mode, block production is initiated only through the `readyToCommitCh` event, and periodic recommit is not performed. | Aspect | Standard Mining | WBFT Mining | | ------- | --------------- | --------------------- | | Trigger | Timer-based | Consensus event-based | | Seal | Asynchronous | Synchronous (BFT) | | Reorg | Allowed | Restricted | ### Gas Tip Updates After each block, the worker queries the GovValidator contract to synchronize the network-wide gas tip and update transaction pool filtering criteria. ## Block Header Extra Data ### WBFTExtra Structure WBFT-related metadata and signatures are RLP-encoded and stored in the `Extra` field of the block header. | Field | Genesis | Creation | PREPARE | COMMIT | Final | | ------------- | ------- | -------- | ------- | ------ | ----- | | VanityData | ✓ | ✓ | ✓ | ✓ | ✓ | | Round | 0 | Set | ✓ | ✓ | ✓ | | EpochInfo | ✓ | Boundary | ✓ | ✓ | ✓ | | GasTip | ✓ | ✓ | ✓ | ✓ | ✓ | | PreparedSeal | Empty | Empty | Set | ✓ | ✓ | | CommittedSeal | Empty | Empty | Empty | Set | ✓ | ## Protocol Messages WBFT uses the following message types to reach block consensus: | Message | Purpose | | ------------ | -------------------------- | | PREPARE | Block proposal | | PREPARE-VOTE | Proposal approval | | COMMIT | Prepared block propagation | | COMMIT-VOTE | Final approval | | ROUND-CHANGE | Request round transition | ## Architecture Summary Anzeon WBFT has a tightly integrated architecture involving genesis configuration, the consensus engine, the worker, and system contracts. 1. Consensus parameters and initial validators are defined in the genesis 2. The consensus engine controls block production by the worker 3. Consensus results and validator information are encoded in the block header 4. Validator sets are updated via GovValidator at epoch blocks 5. Gas tip policies are immediately reflected in transaction processing # Block Production and Mining Source: https://docs.stablenet.network/en/consensus-and-block-production/4.2-block-production-and-mining ## Purpose and Scope This page describes the full flow by which a StableNet node produces and mines blocks.\ It covers the role of the worker, block candidate assembly, transaction selection and execution, and the process of submitting the generated block to the consensus engine (WBFT) for finalization.\ For details on the WBFT consensus protocol itself, including voting, BLS signature aggregation, and epoch management, see [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol). ## Worker Architecture The `worker` is the core component responsible for block production in StableNet.\ It selects and executes transactions from the transaction pool, assembles blocks, and submits completed block candidates to the consensus engine for sealing. ### Worker Structure The worker maintains multiple goroutines to process each stage of block production in parallel. | Component | Goroutine | Purpose | | ------------- | --------- | ------------------------------------------------------------------ | | `mainLoop` | Yes | Handles work requests and events, coordinates block assembly | | `newWorkLoop` | Yes | Triggers block creation based on chain events or consensus signals | | `taskLoop` | Yes | Submits assembled blocks to the consensus engine | | `resultLoop` | Yes | Receives sealed blocks and writes them to the chain | **Key Fields** * `current *environment` : Execution environment of the block currently being assembled * `coinbase common.Address` : Block producer address (validator address) * `tip *uint256.Int` : Minimum gas tip required for transaction inclusion * `pendingTasks map[common.Hash]*task` : Block tasks awaiting sealing * `txsCh`, `chainHeadCh`, `readyToCommitCh` : Channels for transactions, chain head updates, and consensus signals ### Worker Initialization When Anzeon mode is enabled, the worker initializes by reading the network-wide gas tip from the GovValidator contract.\ Afterward, each time a new block is added to the chain, a callback is triggered to re-read the latest gas tip and update internal state and transaction pool filtering criteria. ## Block Production Flow ### WBFT vs Origin Work Loop StableNet uses different block production strategies depending on whether the consensus engine is WBFT. * **Origin (Ethereum default)**: Attempts new blocks periodically based on a timer * **WBFT**: Starts block production only when the consensus engine emits a `readyToCommitCh` signal In WBFT mode, blocks are created only at the exact moment when the node is selected as the proposer, preventing unnecessary re-assembly. ### WBFT Ready-to-Commit Mechanism The WBFT engine requests block production via the `readyToCommit(round)` callback.\ The `round` value indicates the current consensus round, where `round = 0` is the initial attempt and `round > 0` represents retries after previous failures. ## Block Assembly Process ### Main Loop and Commit Work `mainLoop()` receives consensus signals or chain events and then invokes `commitWork()`, which performs the actual block assembly.\ This function sequentially creates the block header, prepares the execution environment, and executes transactions. ### prepareWork – Block Header Setup `prepareWork()` prepares the header and execution environment for a new block. **Steps** 1. **Select parent block**: Choose the latest chain head or a specified parent 2. **Timestamp validation**: Adjust to ensure the timestamp is later than the parent block 3. **Header creation**: Initialize base header fields via `makeHeader()` 4. **Environment setup**: Create state snapshot and gas pool via `makeEnv()` 5. **Engine preparation**: Call `engine.Prepare()` to set consensus-specific fields, including proposer and coinbase for WBFT ### Transaction Selection and Execution `fillTransactions()` selects transactions from the transaction pool that are eligible for inclusion in the current block.\ Selection is based on gas tip, nonce ordering, and per-account validity checks. ### commitTransactions – Execution Loop `commitTransactions()` executes the selected transactions sequentially. * On `ErrNonceTooLow`, the transaction is skipped and the next nonce transaction for the same account is attempted * On successful execution, a receipt is recorded and execution proceeds to the next transaction * On fatal errors, all subsequent transactions from the same account are excluded ### applyTransaction – State Transition Each transaction is applied to the state via `applyTransaction()`. 1. Create a pre-execution state snapshot 2. Execute EVM logic and apply state changes via `core.ApplyTransaction()` 3. Revert to the snapshot on failure 4. On success, add the transaction and receipt to the block Nonce validation, balance checks, gas accounting, and EVM execution are all handled internally by `core.ApplyTransaction()`. ### Block Finalization Once all transactions are executed, the block enters the finalization phase.\ In a WBFT environment, since there are no block rewards, `Finalize()` performs minimal work, mainly computing the state root and receipt root. ## Sealing and Result Handling ### Task Submission Loop `taskLoop()` submits completed blocks to the consensus engine. * **WBFT**: The block is passed to the consensus engine, initiating PREPARE and COMMIT voting * **Other engines**: Engine-specific sealing logic is executed Results are delivered back to the worker through `resultCh`. ### Result Handling Loop `resultLoop()` receives sealed blocks and writes them to the chain. * Set block hash, block number, and transaction index in receipts * Persist the block and state root to the database * In Anzeon mode, re-query the GovValidator contract after block insertion to refresh the gas tip ## Transaction Filtering and Gas Tip Handling ### Gas Tip Handling in Anzeon In the Anzeon network, gas tips are not individually configured by validators but are globally managed by governance (GovValidator).\ `updateGasTipFromContract()` reads the contract state and updates the minimum gas tip requirement for both the worker and the transaction pool. This ensures: 1. Only transactions paying sufficient gas tips are included in block candidates 2. Gas tip changes take effect immediately from the next block 3. The transaction pool proactively filters out transactions below the required threshold ### Transaction Prioritization Transactions are ordered using the `transactionsByPriceAndNonce` structure. **Priority Rules** 1. **Local transactions first** 2. **Effective gas price**: `min(gasTipCap + baseFee, gasFeeCap)` 3. **Nonce ordering**: Sequential processing within each account 4. **Cross-account price comparison**: Higher effective gas price first Blob transactions and regular transactions are managed separately internally, but final selection follows the same pricing rules. ## Environment and State Management ### Execution Environment The `environment` structure holds all execution state required during block assembly. | Field | Purpose | | --------------------------- | ----------------------------------- | | `signer types.Signer` | Transaction signature verification | | `state *state.StateDB` | State trie | | `tcount int` | Number of transactions in the block | | `gasPool *core.GasPool` | Remaining gas limit | | `header *types.Header` | Header of the block being built | | `txs []*types.Transaction` | Included transactions | | `receipts []*types.Receipt` | Execution receipts | The environment is created in `makeEnv()`, which prepares a state copy based on the parent block and initializes the gas pool. ### State Changes and Commit State changes are managed in the following order. 1. Modify StateDB through transaction execution 2. Roll back using snapshots when necessary 3. Commit state to the trie after successful block sealing 4. Persist the block and state root to the database `updateSnapshot()` maintains the pending block state to support RPC calls such as `eth_getBlockByNumber("pending")`. ## Integration with Miner Wrapper The `Miner` type wraps the `worker` and controls block production based on node synchronization status.\ Block production is paused during chain synchronization and automatically resumed once synchronization completes. ## Summary Flow The block production process can be summarized as follows. 1. Consensus engine or chain event triggers block production 2. Worker prepares the block header and execution environment 3. Transactions are selected and executed 4. The block is finalized and submitted to the consensus engine 5. After sealing, the block is written to the chain and gas tips are synchronized Through this structure, StableNet maintains a stable block production pipeline tightly integrated with WBFT consensus. # Consensus and Block Production Source: https://docs.stablenet.network/en/consensus-and-block-production/index ## Purpose and Scope This document describes the consensus mechanism and block production process of StableNet.\ It covers the Anzeon WBFT consensus protocol, the block production pipeline, validator management, and the application of the gas tip policy. For details on the validator governance contract, see [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)). For transaction processing within a block, see [Transaction Processing](/en/transaction-processing/index). ## Consensus Architecture Overview StableNet uses the **Anzeon WBFT** consensus engine, which is a Proof-of-Authority (PoA) variant of the Wemix Byzantine Fault Tolerance protocol.\ The consensus layer coordinates with the block production layer (Worker) to create, validate, and finalize blocks. ### System Components ## Anzeon WBFT Consensus Protocol ### Protocol Characteristics Anzeon WBFT is the application of the WBFT consensus algorithm tailored for StableNet. Its key characteristics are as follows: | Property | Value | | -------------------- | ---------------------------------------- | | **Type** | Byzantine Fault Tolerant (BFT) | | **Model** | Proof-of-Authority (PoA) | | **Block Time** | 1 second (configurable) | | **Finality** | Deterministic, immediate | | **Signature Scheme** | BLS (Boneh–Lynn–Shacham) | | **Fault Tolerance** | Up to f = ⌊(n-1)/3⌋ Byzantine validators | | **Epoch Length** | 10 blocks (configurable) | ### Differences from Standard WBFT Anzeon WBFT removes several features from the original WBFT implementation to align with StableNet’s stablecoin-oriented design. **Key Modifications** 1. **No staking requirement**: Validators are managed purely through governance voting, without token deposits 2. **No block rewards**: Validators earn only transaction fees, preserving a 1:1 stablecoin peg 3. **Anzeon fork enabled**: Anzeon is active from the genesis block 4. **BLS key storage change**: Moved from the `GovStaking` contract to the `GovValidator` contract 5. **Removed governance contracts**: `GovStaking`, `GovConfig`, `GovNCP`, and `GovRewardeeImp` are not used ### Consensus Configuration Anzeon configuration is defined in the genesis block. **Configuration Structure** * `anzeon.wbft`: Core consensus parameters (epoch length, block period, timeouts) * `anzeon.init`: Initial validator set active during epoch 0 * `anzeon.systemContracts.govValidator`: Validator governance parameters, including the validator set from epoch 1 onward **Important:** `init.validators` applies only to the first epoch.\ The `govValidator.validators` parameter defines the active validator set starting from epoch 1. ### Block Finalization Flow WBFT consensus follows a two-phase commit protocol (PREPARE and COMMIT) with BLS signature aggregation for efficiency.\ A block is considered finalized and irreversible once `2f+1` validators (where `f` is the maximum number of tolerated Byzantine faults) have signed both phases. ## Block Production Pipeline The Worker component ([`miner/worker.go`](https://github.com/stable-net/go-stablenet/blob/master/miner/worker.go)) is responsible for assembling and producing blocks.\ It coordinates transaction selection, state transitions, and integration with the consensus engine. ### Worker Architecture ### Worker Event Loop (WBFT Mode) In WBFT mode, the worker uses a simplified event loop compared to standard Ethereum mining. **Key Differences from Standard Mining** 1. **No periodic re-commit**: Standard Ethereum miners periodically rebuild blocks to include higher-fee transactions, whereas WBFT relies on consensus timing 2. **Consensus-driven timing**: The `readyToCommitCh` signal is emitted by the WBFT engine when it is time to produce a block 3. **Round-based**: Each consensus round triggers exactly one block production attempt ### Block Assembly Process The `commitWork()` function orchestrates the entire block assembly process. **Core Functions** * **`commitWork(interrupt, timestamp)`**: Main coordinator, handles interrupt signals * **`generateWork(params)`**: Builds the execution environment and state * **`commitTransactions(txs, coinbase)`**: Applies transactions sequentially while respecting the gas limit * **`commit(env, interval)`**: Submits work to the consensus engine for finalization ### Transaction Selection and Ordering **Transaction Selection Algorithm** 1. **Fetch pending transactions**: Retrieve all transactions from the pool that satisfy the minimum gas tip requirement 2. **Local priority**: Local transactions are processed first 3. **Gas tip application**: In Anzeon mode, regular accounts must use the gas tip defined by `GovValidator`, while authorized accounts may specify a custom tip 4. **Nonce ordering**: Transactions must be processed sequentially by nonce within each account 5. **Price ordering**: Across accounts, transactions with higher effective gas prices have priority 6. **Gas limit enforcement**: Stop when the block gas limit is reached ### Gas Tip Management StableNet’s gas tip policy is enforced through the Worker’s integration with the `GovValidator` contract. **Implementation Details** * **Initialization**: The Worker reads the gas tip from `GovValidator` during creation * **Callback registration**: The blockchain registers `updateGasTipFromContract` as a callback after each block import * **Synchronization**: The Worker’s internal `tip` field and the transaction pool’s minimum price are updated together * **Lock-free updates**: The callback only updates state, avoiding lock contention with the Worker’s main loop ## Validator Management ### Key Management StableNet validators use three keys for governance, block production, and consensus messaging.\ For detailed descriptions of each key’s role, usage, and derivation, see [Validator Operations](/en/operations-guide/11.2-validator-operations). ### Validator Registration and Rotation **Validator Set Updates** 1. **Epoch blocks**: Validator set changes are applied only at epoch blocks 2. **Contract reads**: When producing an epoch block, the WBFT engine reads the current validator list from `GovValidator` 3. **Member versioning**: The `memberVersion` field tracks changes, and the WBFT engine detects updates by comparing versions 4. **Immediate effect**: Once a new epoch starts, the validator set remains fixed for the duration of that epoch ### Genesis vs Runtime Validator Sets StableNet supports two validator set specifications in its genesis configuration. **Important Configuration Notes** * **Epoch 0**: The validator set active from block 1 to the first epoch block is defined by `anzeon.init.validators` * **Epoch 1+**: From block `epochLength + 1`, the validator set is read from the `validators` parameter of the `GovValidator` contract * **Best practice**: Unless a controlled validator migration is intended, these two lists should be identical ## Integration Points ### Worker–WBFT Integration The Worker and the WBFT engine coordinate through a callback-based mechanism. **Code Flow** 1. **Startup**: `eth.StartMining()` calls `miner.Start()`, which invokes `worker.start()` 2. **Engine start**: `worker.start()` calls `wbftEngine.Start()` with the `readyToCommit` callback 3. **Consensus trigger**: When the WBFT core determines it is time to propose a block, it calls `readyToCommit(round)` 4. **Block creation**: The callback signals `readyToCommitCh`, triggering `commitWork()` 5. **Sealing**: The assembled block is sent to `engine.Seal()` for consensus processing ### Miner Initialization The miner is initialized during Ethereum backend setup. **Anzeon-Specific Settings** * **Forced etherbase**: In Anzeon mode, the etherbase is automatically set to the node key–derived address and cannot be configured by the user * **Gas tip initialization**: The Worker reads the initial gas tip from `GovValidator` during configuration ## Summary StableNet’s consensus and block production system has the following characteristics: 1. **Deterministic finality**: Anzeon WBFT provides immediate, irreversible finality through BFT consensus 2. **Governance-driven validators**: Validator sets are fully managed by on-chain governance via the `GovValidator` contract 3. **Stablecoin-aligned economics**: No block rewards, no token burning, validators earn only transaction fees 4. **Dynamic gas tip policy**: Network-wide gas tips enforced and automatically updated by `GovValidator` 5. **Key security model**: Separation of governance, block production, and consensus signing keys 6. **Epoch-based rotation**: Validator set changes are applied only at epoch blocks for stability The Worker component acts as the central coordinator, integrating transaction pool management, state transitions, consensus engine interaction, and governance policy enforcement into a consistent block production pipeline. # Node Initialization and Lifecycle Source: https://docs.stablenet.network/en/core-architecture/3.1-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 | # Blockchain Management Source: https://docs.stablenet.network/en/core-architecture/3.2-blockchain-management ## Purpose and Scope This document describes the blockchain management subsystem responsible for maintaining the canonical chain, inserting blocks, and handling chain reorganization.\ It explains how `BlockChain` and `HeaderChain` track block headers, bodies, receipts, and metadata required for chain selection and state management. Related documents: * State management and StateDB architecture: [State Management](/en/core-architecture/3.3-state-management) * Transaction pool management: [Transaction Pool](/en/core-architecture/3.4-transaction-pool) * Consensus-specific block sealing: [Consensus and Block Production](/en/consensus-and-block-production/index) ## Core Structures ### BlockChain The `BlockChain` type is the central component that manages the canonical blockchain.\ It coordinates block insertion, validation, state execution, and chain reorganization, and works together with the consensus engine (`consensus.Engine`), fork choice logic (`ForkChoice`), state processor (`Processor`), and block validator (`Validator`). It tracks several key heads as internal state: the current canonical head (`currentBlock`), the snapshot synchronization reference block (`currentSnapBlock`), the finalized block (`currentFinalBlock`), and the safe block (`currentSafeBlock`).\ These head pointers are updated according to consensus rules and fork choice results. ### HeaderChain `HeaderChain` is a lightweight chain structure that manages block header storage and number–hash mappings.\ It is responsible for header-level validation and chain traversal, and coordinates header chain reorganization and canonical header mapping updates.\ Full block insertion is handled by `BlockChain`, while `HeaderChain` is used as a subordinate component. ## Canonical Chain Management The canonical chain represents the official chain path followed by the node. The blockchain maintains two core mappings: * **Number → Hash**: The canonical block hash for a given block number * **Hash → Number**: The block number corresponding to a given block hash These mappings are updated consistently during chain reorganization and are used as the reference for RPC queries and internal validation. ### State Loading at Initialization During initialization, the `loadLastState()` method restores chain state from disk: 1. Read the last head block hash from the database 2. Load the head block using the hash 3. Set the current block (`currentBlock`) 4. Load the header chain head 5. Load the snapshot reference block and finalized block ## Block Insertion Pipeline Block insertion is a multi-stage process that includes validation, execution, and canonical chain updates. ### Insertion Flow Overview The `InsertChain()` method is the main entry point for inserting a batch of blocks, and internally proceeds through the following stages: ``` Pre-check → Header validation → Body validation → State execution → State validation → State commit → Fork choice decision → Event publication ``` ### Stage Descriptions **1. Pre-check** * Check the future block cache (`futureBlocks`) * Detect duplicate block insertion * Verify parent block existence **2. Header Validation** * Call the consensus engine’s `VerifyHeader()` * For WBFT, verify proposer, signatures, and validator set consistency * Validate block number, timestamp, and gas limit rules **3. Body Validation** * Call `ValidateBody()` * Verify transaction root hash matches the header * In WBFT environments, ensure that no uncle blocks are present **4. State Execution** * Create a StateDB based on the parent block state * Execute each transaction via `ApplyTransaction()` and run the EVM * Accumulate receipts and gas usage **5. State Validation** * Call `ValidateState()` * Validate gas usage, receipt bloom, and state root **6. State Commit** * Write the block and receipts to the database * Commit the state trie and update snapshots **7. Fork Choice Decision** * Evaluate the priority of the new block according to the consensus engine and fork choice rules * Perform chain reorganization if required **8. Event Publication** * Emit `ChainEvent` and `ChainHeadEvent` * Notify logs and the transaction pool of the new head ## Chain Reorganization Chain reorganization (reorg) occurs when a chain with higher priority than the current canonical chain appears according to fork choice rules.\ In StableNet’s WBFT environment, chain selection is based on consensus rules and epoch-based validator agreement rather than total difficulty. ### Reorganization Process 1. **Fork choice decision**: The `ForkChoice` logic determines whether the new block should be adopted as canonical 2. **Common ancestor discovery**: Find the divergence point between the existing chain and the new chain 3. **Canonical mapping update**: Update number–hash mappings via `HeaderChain.Reorg()` 4. **Head pointer update**: Update `currentBlock`, `currentFinalBlock`, and `currentSafeBlock` Key behaviors of `HeaderChain.Reorg()` include: 1. Simple extension if the parent is the current head 2. Removal of replaced canonical mappings 3. Rewriting mappings while traversing back to the common ancestor 4. Recording headers of the new chain as canonical 5. Persisting the new head header hash to the database ## Caching The blockchain uses LRU caches to minimize disk access: | Cache | Size | Purpose | | --------------- | ---- | ----------------------------------- | | `bodyCache` | 256 | Block body cache | | `blockCache` | 256 | Full block cache | | `receiptsCache` | 32 | Transaction receipt cache | | `txLookupCache` | 1024 | Transaction location lookup | | `futureBlocks` | 256 | Temporary storage for future blocks | ## Chain Recovery ### SetHead The `SetHead()` method rewinds the chain to a specified block number. Typical use cases include: * Recovering state after corrupted blocks * Skipping known problematic blocks * Re-synchronizing after chain rule changes ### Reset `Reset()` removes all chain data and restores the blockchain to the genesis state. ### SnapSyncCommitHead Called after snapshot synchronization completes to set the synchronized block as the canonical head: 1. Verify block existence 2. Activate the state storage 3. Validate state trie accessibility 4. Update the current block pointer 5. Rebuild snapshot structures ## Database Schema ### Block Storage Keys | Key Pattern | Value Type | Purpose | | -------------- | ------------------ | --------------------------------- | | `h{num}n` | `common.Hash` | Canonical hash for a block number | | `h{hash}n` | `uint64` | Block number for a hash | | `H{hash}{num}` | `*types.Header` | Block header | | `b{hash}{num}` | `*types.Body` | Block body | | `r{hash}{num}` | `[]*types.Receipt` | Transaction receipts | ### Chain State Keys | Key | Purpose | | --------------- | ----------------------------- | | `LastBlock` | Canonical block head hash | | `LastHeader` | Canonical header head hash | | `LastFast` | Snapshot reference block hash | | `LastFinalized` | Finalized block hash | | `SnapshotRoot` | Snapshot root | ## Error Handling | Error | Condition | Handling | | ------------------------- | ----------------------- | ----------------------- | | `ErrKnownBlock` | Block already processed | Ignored | | `ErrNoGenesis` | Missing genesis | Initialization required | | `ErrBannedHash` | Block hash is banned | Rewind chain | | `ErrUnknownAncestor` | Missing parent block | Request from peers | | `ErrPrunedAncestor` | Parent state pruned | Snapshot sync required | | `errInsertionInterrupted` | Insertion interrupted | Abort current insertion | # State Management Source: https://docs.stablenet.network/en/core-architecture/3.3-state-management ## Purpose and Scope This document describes the state management system in StableNet that maintains and manages the global state, including all account balances, nonces, contract code, and contract storage.\ The state management layer provides a caching interface on top of a Merkle Patricia Trie structure, tracks state transitions that occur during transaction execution, and commits state changes at the block level. Related documents: * Transaction execution and state transitions: [Transaction Processing](/en/transaction-processing/index) * Trie database schema: [Storage Architecture](/en/storage-architecture/index) * State usage during block execution: [Blockchain Management](/en/core-architecture/3.2-blockchain-management) ## StateDB Architecture `StateDB` is the core interface responsible for accessing and modifying state. It is defined in `core/state/statedb.go`, provides an in-memory caching layer on top of the account trie, and manages the full lifecycle of state objects representing individual accounts. Key components: * **trie**: the account trie that stores account state * **snaps**: snapshot trees for fast state access (optional) * **stateObjects**: in-memory cache of account objects (`map[common.Address]*stateObject`) * **journal**: a journal that records state changes for rollback * **originalRoot**: the state root at the start of the current block execution StateDB is created at the beginning of block execution with a specific state root, accumulates state changes while executing transactions within the block, and computes and commits a new state root at the end of the block. ## State Objects A `stateObject` is an internal structure that represents the state of a single account, including balance, nonce, code, and storage.\ It is cached in memory and clearly distinguishes between modified (dirty) state and committed state. ### StateAccount Structure Each account’s persistent data is stored in the `StateAccount` structure defined in `core/types/state_account.go`: | Field | Type | Description | | ---------- | -------------- | ------------------------------------------------ | | `Nonce` | `uint64` | Transaction counter | | `Balance` | `*uint256.Int` | Account balance in Wei | | `Root` | `common.Hash` | Storage trie root | | `CodeHash` | `[]byte` | Contract code hash | | `Extra` | `uint64` | StableNet extension field (account policy flags) | The `Extra` field is a StableNet extension used to represent account policy state defined by the governance layer. ### State Object Lifecycle State objects are managed through the following stages: 1. **Create / Load**: `getStateObject()` retrieves the object from cache or loads it from the trie or snapshot if absent 2. **Modify**: balance, nonce, and storage values are updated in memory during transaction execution 3. **Finalize**: on `Finalise()`, dirty state is moved to the pending state 4. **Commit**: on `Commit()`, changes are written to the trie and persisted to the database ## Trie Structure State is managed using a hierarchical Merkle Patricia Trie structure: * **Account Trie**: a single trie storing the state of all accounts, keyed by address hash * **Storage Trie**: one per contract account, storing contract variable values Key operations include: | Operation | StateDB Method | Description | | -------------- | --------------------- | -------------------- | | Load account | `getStateObject()` | Load account state | | Update account | `updateStateObject()` | Update account state | | Delete account | `deleteStateObject()` | Remove account | | Load storage | `GetState()` | Read storage slot | | Update storage | `SetState()` | Update storage slot | ## Caching Layers To reduce the cost of state access, a multi-level caching architecture is used: ``` Request → StateDB cache → Snapshot layer → Trie node cache → Disk database ``` 1. **StateDB Cache**\ Keeps `stateObject` instances in memory. It manages `dirtyStorage` modified in the current transaction, `pendingStorage` finalized but not yet committed, and `originStorage` for change tracking. 2. **Snapshot Layer**\ Provides account and storage data in a flat key–value structure, bypassing trie traversal. This significantly improves read performance and is generated and updated asynchronously. 3. **Trie Node Cache**\ Managed by the trie database, separating recently accessed clean nodes and modified (dirty) nodes not yet written to disk. 4. **Disk Database**\ The final persistent storage, holding encoded trie nodes and state data. ## Journaling and Snapshots The journal system records all state changes sequentially, enabling transaction-level rollback.\ If an error occurs during execution, all state changes made by that transaction can be precisely reverted. ### Snapshots and Reverts * **`Snapshot()`**: creates a rollback checkpoint for the current state and returns a journal index * **`RevertToSnapshot()`**: restores all changes made after the specified snapshot in reverse order The journal records the following types of changes: * Balance, nonce, and code updates * Storage slot updates * `selfdestruct` flags * Access list changes * Log additions A snapshot is created before each EVM call, and if execution fails, only the state changes within that call scope are rolled back. ## State Commit State commits are performed at the block level and persist changes to permanent storage. ### Commit Flow ``` Finalise → IntermediateRoot → Commit ``` **1. Finalise** * Move dirty storage to pending storage * Clean up empty accounts (EIP-161) * Called repeatedly after transaction execution **2. IntermediateRoot** * Compute roots of all storage tries * Update the account trie * Return the current state root, used to compute the receipt root **3. Commit** * Commit account and storage tries to disk * Update the trie database * Commit snapshots * Return the final state root ### State Change Tracking With the path-based state scheme (PBSS), the following tracking maps are maintained for efficient state management and pruning: * **accounts / storages**: accounts and storage entries modified in the current block * **accountsOrigin / storagesOrigin**: original values before modification * **stateObjectsDestruct**: information about deleted accounts This information is passed to the trie database during commit and used for state management optimizations. ## Database Integration StateDB integrates with the trie database through the `Database` interface defined in `core/state/database.go`.\ Both hash-based and path-based (PBSS) state schemes are supported. ### Database Configuration | Setting | Default | Description | | ---------------- | ---------- | ---------------------------------------- | | `StateScheme` | HashScheme | State storage scheme | | `TrieCleanLimit` | 256 MB | Clean cache size | | `TrieDirtyLimit` | 256 MB | Dirty cache size | | `SnapshotLimit` | 256 MB | Snapshot cache size | | `Preimages` | false | Whether to store trie key preimages | | `StateHistory` | 0 | Number of blocks to retain state history | Key interface methods: * `OpenTrie(root)` * `OpenStorageTrie(stateRoot, addrHash, root, trie)` * `ContractCode(addrHash, codeHash)` * `TrieDB()` ## State Prefetching State prefetching is an optimization technique that preloads required trie nodes during block execution.\ It is started with `StartPrefetcher()` and stopped with `StopPrefetcher()`. The prefetcher predicts which accounts and storage slots transactions will access and loads them into cache in advance, reducing disk I/O wait time and improving block processing performance. ## Performance Metrics StateDB collects the following metrics to monitor state management performance: * Account and storage read/write/commit times * Snapshot lookup and commit times * Trie database commit times * Number of modified accounts and storage slots These metrics help node operators analyze state processing bottlenecks and tune performance. # Transaction Pool Source: https://docs.stablenet.network/en/core-architecture/3.4-transaction-pool ## Purpose and Scope The transaction pool manages **pending transactions** that have been submitted to the node but are not yet included in a block. Its primary responsibilities are as follows: 1. **Acceptance**: Receive transactions from RPC clients and P2P peers 2. **Validation**: Verify signatures, nonce, balance, and gas-related rules 3. **Storage**: Store transactions in memory based on their executability state 4. **Provisioning**: Provide transactions to the miner/worker for block assembly 5. **Propagation**: Broadcast transactions over the P2P network 6. **Querying**: Expose pool status through RPC APIs Related documents: * Transaction execution: [State Transitions](/en/transaction-processing/6.2-state-transitions-and-gas) * Transaction data structures: [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding) * Transaction consumption during block production: [Block Production](/en/consensus-and-block-production/4.2-block-production-and-mining) ## Architecture Overview `txpool.TxPool` acts as the central coordinator for transaction management. ``` RPC (eth_sendRawTransaction) ──┐ ├→ TxPool.Add() → validation → queued/pending classification P2P (NewPooledTransactionHashes) ┘ │ ├→ NewTxsEvent published ├→ P2P propagation └→ Worker.Pending() → block assembly ``` The transaction pool consists of two sub-pools: * **legacypool**: Handles standard transactions (types 0x00–0x04, 0x16) * **blobpool**: Handles blob transactions (EIP-4844) ## Transaction Submission Paths Transactions enter the pool through one of the following paths. ### RPC Submission Transactions submitted via `eth_sendRawTransaction` or `eth_sendTransaction` are classified as **local transactions**.\ Local transactions are prioritized and are relatively protected by the eviction policy when the pool is under pressure. ### P2P Submission Transactions received from peers via the `eth` protocol are classified as **remote transactions**.\ Remote transactions are subject to more conservative validation policies and have a lower default priority. ## Transaction Validation All transactions accepted via `TxPool.Add()` must pass the following validation steps. | Validation Item | Description | | -------------------- | -------------------------------------------------------------------- | | **Signature** | ECDSA signature verification and sender address recovery | | **Nonce** | Comparison against the sender’s current on-chain nonce | | **Balance** | Sufficient balance to cover value + maximum gas cost | | **Gas Limit** | Must be below the block gas limit and above intrinsic gas | | **Gas Price / Tip** | Must satisfy the pool’s minimum gas requirements | | **Transaction Type** | Type-specific field and rule validation | | **Fee Delegation** | For fee-delegated transactions, validate payer signature and balance | ### Gas Price and Gas Tip Validation For EIP-1559-based transactions (types 0x02, 0x04, 0x16), the effective gas tip is calculated as: ``` EffectiveGasTip = min(GasTipCap, GasFeeCap - BaseFee) ``` In the Anzeon network, gas tip rules differ by account type: * **Authorized accounts**: May use the `GasTipCap` specified in the transaction * **General accounts**: Must satisfy the governance-defined `GasTip` included in the block header ## Internal Pool Structure ### Pending Transactions * Sender nonce exactly matches the current on-chain nonce * Immediately executable * Candidates for inclusion in the next block * Provided to the worker via `Pending()` ### Queued Transactions * Sender nonce is a future value * Cannot be executed until preceding nonce transactions are processed * Automatically promoted to pending once conditions are met ## Capacity Limits The transaction pool uses **slot-based capacity limits** to control memory usage and mitigate denial-of-service (DoS) attacks.\ Each transaction occupies one or more slots depending on its size, and limits are enforced at both the account level and the global level. | Limit Type | Parameter | Default | Description | | ------------------- | -------------- | ------- | ------------------------------------------------------------ | | Per-account Pending | `AccountSlots` | 16 | Maximum slots a single account may hold in pending state | | Per-account Queued | `AccountQueue` | 64 | Maximum slots a single account may hold in queued state | | Global Pending | `GlobalSlots` | 5120 | Total pending slots shared by all accounts | | Global Queued | `GlobalQueue` | 1024 | Total queued slots shared by all accounts | | Minimum Gas Price | `PriceLimit` | 1 Gwei | Minimum effective gas price accepted by the pool | | Replacement Bump | `PriceBump` | 10% | Minimum gas price increase required to replace a transaction | Although the default `PriceLimit` is 1 Gwei, StableNet applies the network-wide `GasTip` value determined by GovValidator governance as the effective baseline. ## Transaction Eviction Rules When the transaction pool reaches its capacity limit, it evicts transactions with the lowest priority to make room for new ones.\ Eviction decisions consider both **slot-based capacity constraints** and **fee-based priority ordering**. The core principles are: * **Priority-based eviction**\ Transactions are ordered by fee priority, and the lowest-priority transactions are removed first. * **Account-level limits first**\ If a specific account exceeds its per-account slot limits (`AccountSlots`, `AccountQueue`), that account’s transactions are evicted first. * **Global eviction on overflow**\ If global pending or queued slot limits (`GlobalSlots`, `GlobalQueue`) are exceeded, the lowest-priority transactions across all accounts are evicted. * **Local transaction protection**\ Locally submitted transactions have lower eviction priority than remote transactions and are preserved whenever possible. This policy ensures stable memory usage while preferentially retaining transactions with higher fees and better execution prospects. ## Transaction Replacement Rules A new transaction with the same sender and nonce may replace an existing transaction only if it offers an effective gas price at least `PriceBump` higher than the existing one. `PriceBump` is applied as a **percentage-based relative increase**.\ For example, with `PriceBump = 10%`, the new transaction’s effective gas price must be at least 10% higher than the existing transaction. This mechanism allows users to increase gas conditions to mitigate processing delays. ## Transaction Query APIs ### txpool RPC Namespace * `txpool_content`: Retrieve all pending and queued transactions * `txpool_contentFrom(address)`: Retrieve transactions for a specific address * `txpool_status`: Retrieve counts of pending and queued transactions * `txpool_inspect`: Human-readable summary view ### Backend Access Methods Through `EthAPIBackend`, the following internal methods are available: * `SendTx(tx)` * `GetPoolTransaction(hash)` * `GetPoolTransactions()` * `GetPoolNonce(addr)` * `Stats()` ## Event System When a transaction is accepted into the pool, a `NewTxsEvent` is published. Primary subscribers: * **Worker**: Incorporates transactions into the current block candidate * **P2P Handler**: Propagates transactions to other peers * **RPC Subscribers**: Provides pending transaction notifications Events can be subscribed to via `SubscribeNewTxsEvent()`. ## Integration with Block Production During block assembly, the worker calls `TxPool.Pending()` to retrieve executable transactions.\ The returned structure is organized as `address → nonce-ordered transaction list`. ### Ordering Priority 1. Effective gas tip 2. Nonce order within each account 3. Executability 4. Anzeon authorized account status ## P2P Network Integration ### Propagation Flow Transactions added to the local pool are propagated to peers by hash, with full transactions requested as needed. ### Reception Flow 1. Peer announces transaction hashes 2. Missing hashes are identified 3. Full transactions are requested 4. Transactions are validated and added to the pool 5. Accepted transactions are re-propagated ## Pool Updates on Block Reception When a new block is inserted into the chain, the transaction pool performs the following steps: 1. Remove transactions included in the block 2. Update sender nonces 3. Promote queued transactions 4. Revalidate based on updated balances 5. Remove transactions that are no longer valid In the Anzeon network, this process also queries the GovValidator contract to synchronize the latest gas tip policy with both the pool and the worker. # Transaction Types and Encoding Source: https://docs.stablenet.network/en/core-architecture/3.5-transaction-types-and-encoding ## Purpose and Scope This document describes the **data structures**, **type hierarchy**, and **encoding formats** of transactions used in StableNet.\ It covers the six supported transaction types, the role of each type, encoding formats (RLP, binary, JSON), as well as signing and hash calculation rules. Related documents: * Transaction lifecycle: [Transaction Processing](/en/transaction-processing/index) * State transition execution: [State Transitions](/en/transaction-processing/6.2-state-transitions-and-gas) * Transaction submission via APIs: [Transaction Submission and Signing](/en/transaction-processing/6.4-gas-fee-policy) ## Transaction Type Hierarchy StableNet supports six transaction types through a polymorphic type hierarchy.\ All transaction types implement the `TxData` interface and are wrapped by the top-level `Transaction` structure. ### Supported Types | Type | Constant | Value | Description | | ------------- | ----------------------------- | --------- | -------------------------------------- | | Legacy | `LegacyTxType` | 0x00 | Pre–EIP-2718 legacy format | | Access List | `AccessListTxType` | 0x01 | EIP-2930 access list transaction | | Dynamic Fee | `DynamicFeeTxType` | 0x02 | EIP-1559 dynamic fee transaction | | Blob | `BlobTxType` | 0x03 | EIP-4844 data availability transaction | | Set Code | `SetCodeTxType` | 0x04 | EIP-7702 code delegation | | Fee Delegated | `FeeDelegateDynamicFeeTxType` | 0x16 (22) | StableNet fee-delegated transaction | ### TxData Interface All transaction types implement the `TxData` interface (`core/types/transaction.go`), which defines the following responsibilities: * **Type identification**: `txType() byte` * **Field accessors**: `chainID()`, `nonce()`, `gas()`, `gasPrice()`, `gasTipCap()`, `gasFeeCap()`, `value()`, `to()`, `data()`, `accessList()` * **Signature handling**: `rawSignatureValues()`, `setSignatureValues()` * **Fee delegation extension**: `feePayer()`, `rawFeePayerSignatureValues()` * **Gas calculation**: `effectiveGasPrice(baseFee, gasTip)` * **Encoding/decoding**: `encode(*bytes.Buffer)`, `decode([]byte)` ### Transaction Wrapper The `Transaction` structure acts as a common wrapper for all transaction types and provides: * **Type-agnostic interface**: Holds an internal `TxData` implementation * **First-seen timestamp**: Records when the transaction was first observed locally * **Cached computations**: Hash, size, sender, and fee payer addresses cached via `atomic.Value` * **Immutability**: Transactions are immutable after creation; modifications require creating a new instance ## Individual Transaction Types ### Legacy Transaction (Type 0x00) The basic transaction format used prior to EIP-2718, with the simplest structure. | Field | Type | Description | | ------------- | ----------------- | --------------------------------------------- | | `Nonce` | `uint64` | Account nonce | | `GasPrice` | `*big.Int` | Gas price in Wei | | `Gas` | `uint64` | Gas limit | | `To` | `*common.Address` | Recipient address (nil for contract creation) | | `Value` | `*big.Int` | Transferred value | | `Data` | `[]byte` | Call data | | `V`, `R`, `S` | `*big.Int` | ECDSA signature values | ### Access List Transaction (Type 0x01) Introduced by EIP-2930, this transaction pre-declares addresses and storage keys accessed during execution. Additional characteristics: * **Includes `ChainID`**: Prevents replay attacks * **Includes `AccessList`**: Address and storage slot list * **Simplified signature format**: Uses `yParity` (0 or 1) ### Dynamic Fee Transaction (Type 0x02) An EIP-1559-based transaction that separates base fee and priority fee. | Field | Description | | ----------- | ---------------------- | | `GasTipCap` | Maximum priority fee | | `GasFeeCap` | Maximum total gas cost | The effective gas price is calculated as: `min(GasTipCap + BaseFee, GasFeeCap)` In StableNet, governance policy may restrict `GasTipCap` to a block-header-defined value. ### Blob Transaction (Type 0x03) A data availability transaction introduced by EIP-4844. Additional fields: * **`BlobFeeCap`**: Maximum fee per blob gas * **`BlobHashes`**: Versioned blob commitment hashes * **`Sidecar`**: Actual blob data Constraints: * Contract creation is not allowed * Sidecar data is excluded from hash calculation * Blob-related values use `uint256.Int` ### Set Code Transaction (Type 0x04) An EIP-7702-based transaction that allows an EOA to delegate execution code. Additional field: * **`AuthList`**: Authorization list for code delegation Constraints: * Contract creation is not allowed * `AuthList` must not be empty * Delegations already processed are not rolled back even if execution fails ### Fee-Delegated Transaction (Type 0x16) A StableNet-specific extension where a third party pays the gas fee. Additional fields: * **`FeePayer`**: Fee-paying address * **`FV`, `FR`, `FS`**: Fee payer signature values Two signatures are required: 1. Sender signature: Approves the transaction contents 2. Fee payer signature: Approves payment of gas fees During state transition, only the fee payer’s balance is used to pay gas costs. ## Encoding Formats ### RLP Encoding RLP is the primary format used for network transmission and storage. Legacy transactions: ``` RLP([Nonce, GasPrice, Gas, To, Value, Data, V, R, S]) ``` Typed transactions: ``` type_byte || RLP([field1, field2, ...]) ``` The first byte distinguishes legacy and typed transactions. ### Binary Encoding `MarshalBinary()` / `UnmarshalBinary()` provide the canonical EIP-2718 binary encoding.\ This encoding is used for hash and signature calculation. ### JSON Encoding A human-readable format used by RPC interfaces. * All numeric values are hex-encoded strings * Typed transactions include `yParity` * `v` and `yParity` must be consistent ## Transaction Signing ### Signer Selection Logic The signer is selected based on chain configuration and block state. ``` if IsCancun(blockNumber, blockTime): → CancunSigner else if AnzeonEnabled(): → AnzeonSigner else if IsLondon(blockNumber): → LondonSigner else if IsBerlin(blockNumber): → EIP2930Signer else if IsEIP155(blockNumber): → EIP155Signer else if IsHomestead(blockNumber): → HomesteadSigner else: → FrontierSigner ``` `AnzeonSigner` handles StableNet extensions, including Set Code transactions. ### Signing and Recovery * Signatures are generated over the hash excluding signature fields * The sender address is recovered via `Sender()` * For fee-delegated transactions, the fee payer address is recovered separately via `FeePayer()` ## Transaction Hashing ### Hash Calculation Rules Legacy transactions: ``` keccak256(rlp([...])) ``` Typed transactions: ``` keccak256(type_byte || rlp([...])) ``` Hashes are cached after the first computation. ### Blob Transaction Special Case Blob transaction hashes do not include sidecar data.\ The hash remains identical regardless of whether the sidecar is present. ## Integration with State Transitions Before execution, a transaction is converted into a `Message` structure via `TransactionToMessage()`. * Extract sender and fee payer addresses * Compute gas pricing * Apply fee delegation information * Include flags to skip signature checks for RPC calls This ensures that transactions follow a unified execution path for both block execution and RPC simulation. # Block Structure and Encoding Source: https://docs.stablenet.network/en/core-architecture/3.6-block-structure-and-encoding ## Purpose and Scope This document describes the **block and header structure**, **encoding formats**, **hash calculation**, **Merkle root construction**, and **WBFT-specific Extra data structures** used in the StableNet blockchain.\ It focuses on how blocks are composed and validated, and what data is included in the header during the consensus process. Related documents: * Transaction data structures: [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding) * Block validation and chain insertion: [Blockchain Management](/en/core-architecture/3.2-blockchain-management) * Block production process: [Block Production](/en/consensus-and-block-production/4.2-block-production-and-mining) ## Block Structure Overview A block consists of a **header** containing metadata, a **body** containing transactions, and optional **withdrawals** and **uncles** lists.\ In StableNet (WBFT-based), uncles are not used and are always empty. ### Block Type Key fields of the `Block` structure (`core/types/block.go`): | Field | Type | Description | | -------------- | -------------- | ------------------------------------------------- | | `header` | `*Header` | Block header containing metadata and Merkle roots | | `transactions` | `Transactions` | List of transactions included in the block | | `uncles` | `[]*Header` | Uncle block headers (not used) | | `withdrawals` | `Withdrawals` | Withdrawals list (optional after Shanghai) | | `hash` | `atomic.Value` | Cached block hash | | `size` | `atomic.Value` | Cached RLP-encoded size | Blocks are treated as **immutable** objects after creation.\ Internal data is copied during construction, and cached hash and size values never change afterward. ## Header Structure The `Header` is the core metadata of a block and contains cryptographic commitments to the block contents and execution results. ### Core Header Fields | Field | Type | Description | | ------------- | ---------------- | ----------------------------------------------- | | `ParentHash` | `common.Hash` | Parent block header hash | | `UncleHash` | `common.Hash` | Uncle list hash (`EmptyUncleHash` in StableNet) | | `Coinbase` | `common.Address` | Block fee recipient address (validator address) | | `Root` | `common.Hash` | State trie root after block execution | | `TxHash` | `common.Hash` | Transaction Merkle root | | `ReceiptHash` | `common.Hash` | Receipt Merkle root | | `Bloom` | `Bloom` | Log bloom filter | | `Difficulty` | `*big.Int` | Block difficulty (WBFT: always 1) | | `Number` | `*big.Int` | Block number | | `GasLimit` | `uint64` | Block gas limit | | `GasUsed` | `uint64` | Total gas used | | `Time` | `uint64` | Block timestamp | | `Extra` | `[]byte` | WBFT consensus data (RLP-encoded) | | `MixDigest` | `common.Hash` | PoW field (unused in WBFT) | | `Nonce` | `BlockNonce` | PoW field (unused in WBFT) | **StableNet specifics:** * `Difficulty` is set to 1 to identify WBFT blocks * `Coinbase` is the validator’s consensus signing address and may differ from the operator address * `Extra` contains WBFT round data, aggregated signatures, gas tip, and epoch information * `GasLimit` is operated as a fixed value defined by chain parameters ### Fork-Specific Optional Fields The following fields exist only after specific forks and are included in RLP encoding only when non-nil. | Field | EIP | Fork | Description | | ------------------ | -------- | -------- | ------------------------ | | `BaseFee` | EIP-1559 | London | Block base fee | | `WithdrawalsHash` | EIP-4895 | Shanghai | Withdrawals Merkle root | | `BlobGasUsed` | EIP-4844 | Cancun | Blob gas usage | | `ExcessBlobGas` | EIP-4844 | Cancun | Excess blob gas | | `ParentBeaconRoot` | EIP-4788 | Cancun | Beacon chain parent root | ## Body Structure The block body contains executable data: * **Transactions**: Transaction list * **Uncles**: Uncle headers (not used) * **Withdrawals**: Withdrawals list (after the relevant fork) ## RLP Encoding Both blocks and headers use Recursive Length Prefix (RLP) encoding. ### Block Encoding A block is encoded as the following RLP list: ``` [header, transactions, uncles, withdrawals] ``` For pre-Shanghai blocks, the `withdrawals` element is omitted. ### Header Encoding Headers are RLP-encoded in the defined field order.\ Optional fields are included only when present. ## Block and Header Hashing ### Standard Hashing The block hash is calculated **only from the header**. ``` block_hash = keccak256(rlp(header)) ``` The computed hash is cached to avoid repeated calculation. ### WBFT-Specific Header Hashing In WBFT, consensus signatures are included in the `Extra` field.\ Therefore, **signatures must be excluded from the hash used for signing**. This is handled by `WBFTFilteredHeader()`: * Removes `PreparedSeal` and `CommittedSeal` * Preserves round number, epoch info, and gas tip * Applied only when `Difficulty == 1` This prevents circular dependencies between signatures and hashes. ### Round-Dependent Hashes During WBFT consensus rounds, a round-specific hash is used.\ Even for the same block proposal, different rounds result in different signing hashes. ## WBFT Extra Data Structure WBFT consensus data is stored in the header’s `Extra` field as RLP-encoded data. ### WBFTExtra Structure | Field | Type | Description | | ------------------- | --------------------- | ----------------------------------- | | `VanityData` | `[]byte` | Vanity data | | `RandaoReveal` | `[]byte` | BLS signature for randomness | | `PrevRound` | `uint32` | Previous consensus round | | `PrevPreparedSeal` | `*WBFTAggregatedSeal` | Previous prepare aggregated seal | | `PrevCommittedSeal` | `*WBFTAggregatedSeal` | Previous commit aggregated seal | | `Round` | `uint32` | Current consensus round | | `PreparedSeal` | `*WBFTAggregatedSeal` | Current prepare aggregated seal | | `CommittedSeal` | `*WBFTAggregatedSeal` | Current commit aggregated seal | | `GasTip` | `*big.Int` | Governance-defined gas tip | | `EpochInfo` | `*EpochInfo` | Next epoch info (epoch blocks only) | Fields with nil values are excluded from RLP encoding. ### WBFTAggregatedSeal Represents a BLS-aggregated signature from multiple validators. | Field | Type | Description | | ----------- | ----------- | ---------------------------- | | `Sealers` | `SealerSet` | Bitmap of signing validators | | `Signature` | `[]byte` | Aggregated BLS signature | ### EpochInfo Included only in epoch blocks and defines the validator set for the next epoch. | Field | Type | Description | | --------------- | -------------- | ------------------------- | | `Candidates` | `[]*Candidate` | All validator candidates | | `Validators` | `[]uint32` | Active validator indices | | `BLSPublicKeys` | `[][]byte` | Validator BLS public keys | ## Merkle Root Calculation ### TxHash Calculated by building a Merkle Patricia Trie from the transaction list.\ An empty list uses `EmptyTxsHash`. ### ReceiptHash Calculated in the same way from the receipt list.\ The bloom filter is derived from receipts. ### UncleHash The hash of the uncle header list.\ In StableNet, this is always `EmptyUncleHash`. ### WithdrawalsHash Calculated from the withdrawals list in post-Shanghai blocks. ## Block Construction ### NewBlock Function `NewBlock()` constructs a block using the following steps: 1. Copy the header 2. Compute the transaction Merkle root 3. Compute the receipt root and bloom 4. Compute the uncle hash 5. Assemble the body data For WBFT blocks: * `Difficulty = 1` * `Extra` contains the encoded `WBFTExtra` * `EpochInfo` is included only in epoch blocks After Shanghai, `NewBlockWithWithdrawals()` is used. ## Header Sanity Checks `Header.SanityCheck()` prevents DoS attacks caused by malformed inputs. | Field | Constraint | | ------------ | --------------------- | | `Number` | 64-bit range | | `Difficulty` | Reasonable bit length | | `Extra` | Maximum size limit | | `BaseFee` | uint256 range | ## Block Size Calculation The block size is the total RLP-encoded size and can be queried via `Block.Size()`.\ If blob transactions are included, sidecar data is also counted toward the size. # Core Architecture Source: https://docs.stablenet.network/en/core-architecture/index ## Purpose and Scope This document provides an overview of StableNet’s core blockchain components and their interaction model. It explains the overall architecture of StableNet by focusing on the roles of each component and the relationships between them. For detailed information on specific subsystems, refer to the following: * Node startup and service registration: [Node Initialization and Lifecycle](/en/core-architecture/3.1-node-initialization-and-lifecycle) * Block insertion and chain reorganization: [Blockchain Management](/en/core-architecture/3.2-blockchain-management) * State trie and account management: [State Management](/en/core-architecture/3.3-state-management) * Transaction validation and queues: [Transaction Pool](/en/core-architecture/3.4-transaction-pool) * Transaction data structures: [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding) * Block data structures: [Block Structure and Encoding](/en/core-architecture/3.6-block-structure-and-encoding) * Consensus mechanisms: [Consensus and Block Production](/en/consensus-and-block-production/index) * P2P networking: [Networking](/en/networking/index) * RPC interfaces: [RPC and APIs](/en/rpc-and-apis/index) ## Architecture Overview A StableNet node is composed of a layered architecture. At the top sits the node container (`node.Node`), within which the Ethereum protocol implementation (`eth.Ethereum`) coordinates core components such as the blockchain, transaction pool, and consensus engine. ``` node.Node (service container) ├─ P2P server, RPC/IPC/WS servers, account manager │ └─ eth.Ethereum (protocol implementation) ├─ BlockChain ← canonical chain, block insertion/validation ├─ StateDB ← account/storage state management ├─ TxPool ← pending transaction management ├─ Miner/Worker ← block assembly and sealing ├─ Engine ← consensus (WBFT/Clique/Ethash) └─ Handler ← P2P synchronization, block/tx propagation ``` ## Core Components ### node.Node — Service Container The top-level container that manages the lifecycle of all services. It initializes the P2P server, RPC/IPC/WebSocket servers, and databases, and starts and stops registered services in order. It does not contain blockchain logic; instead, it provides the infrastructure layer required to run a node. ### eth.Ethereum — Ethereum Protocol Implementation The main service that coordinates core blockchain components. During initialization, it creates and connects the database, blockchain, transaction pool, miner/worker, and consensus engine. It also registers RPC APIs and P2P protocols with the node, enabling external interaction. ### BlockChain — Canonical Chain Management The core component responsible for managing the canonical chain. It coordinates block validation, insertion, state execution, and chain reorganization (reorg). Block validity is verified through the consensus engine, while account and storage state are managed via StateDB. Frequently accessed blocks and receipts are cached using LRU caches to optimize query performance. For details, see [Blockchain Management](/en/core-architecture/3.2-blockchain-management). ### StateDB — State Management Provides a caching layer on top of the Merkle Patricia Trie to manage account balances, nonces, contract code, and storage. State changes during transaction execution are journaled to support rollback on failure, and snapshots are used to enable fast state queries. For details, see [State Management](/en/core-architecture/3.3-state-management). ### TxPool — Transaction Pool Manages pending transactions that have not yet been included in a block. Transactions are received via RPC and P2P, validated for signature, nonce, balance, and gas conditions, and then classified as executable (pending) or future (queued). The pool consists of a `legacypool` for standard transactions and a `blobpool` for blob transactions (EIP-4844). For details, see [Transaction Pool](/en/core-architecture/3.4-transaction-pool). ### Miner/Worker — Block Production The block proposer assembles a block candidate by including pending transactions and finalizes it through validator consensus via the consensus engine. The Worker runs four goroutines—`mainLoop`, `newWorkLoop`, `taskLoop`, and `resultLoop`—to perform transaction selection, block assembly, sealing requests, and result handling in parallel. ### consensus.Engine — Consensus Engine An interface that abstracts block validation and sealing. In StableNet, the Anzeon WBFT consensus engine is used, and it is responsible for block proposal, voting, and seal verification. ## StableNet-Specific Design StableNet is based on go-ethereum, but it introduces the following extensions to support stablecoin operations and governance-centric consensus. ### Anzeon WBFT Consensus * **Governance-based validators**: The validator set is determined by voting results from the GovValidator contract; staking is not used. * **No block rewards**: There is no inflation from new issuance; validators are rewarded only through transaction fees. * **BLS signature aggregation**: BLS aggregated signatures are used for PREPARE/COMMIT consensus messages to reduce verification costs. * **Epoch-based validator updates**: Changes to the validator set are applied only at epoch blocks. ### Gas Fee Policy * **Governance-controlled gas tip**: The minimum gas tip (priority fee) is managed as a network-wide value by the GovValidator contract. * **Approved account exceptions**: Accounts approved by governance are allowed to specify custom gas tips. * **Dynamic gas tip propagation**: The latest gas tip is synchronized to the worker and transaction pool each time a new block is added to the chain. ### Fee Delegation Using the StableNet-specific transaction type (0x16), the sender and the fee payer can be separated. In this case, ECDSA signatures from both the sender and the fee payer are required. ### Automatic Etherbase Configuration In the Anzeon network, the etherbase is automatically derived from the node’s operational key (nodekey) and cannot be manually configured by the user. ## Initialization Flow Summary A StableNet node is initialized in the following order: 1. **CLI flag parsing** — Load network settings, data directory, and TOML configuration 2. **Node creation** — `node.Node` prepares P2P, RPC, and database infrastructure 3. **Database opening** — Initialize chaindata and ancient (freezer) stores 4. **Consensus engine creation** — Select WBFT/Clique/Ethash based on chain configuration 5. **Blockchain initialization** — Load genesis, create BlockChain, configure snapshots 6. **Transaction pool setup** — Create legacypool and blobpool 7. **Miner/worker creation** — Start goroutines related to block assembly 8. **API and protocol registration** — Register RPC handlers and P2P protocols 9. **Service startup** — Start registered services in order For detailed initialization steps, see [Node Initialization and Lifecycle](/en/core-architecture/3.1-node-initialization-and-lifecycle). ## Data Flow Overview ### Transaction Processing Flow ``` User/DApp → RPC (eth_sendRawTransaction) → TxPool.Add() — signature, nonce, balance, gas validation → classified as pending transaction → propagated to the P2P network → Miner calls Pending() → block assembly → consensus.Engine.Seal() → block sealing → BlockChain.InsertChain() → chain insertion → state commit and event publication ``` ### Block Synchronization Flow ``` Peer node → P2P protocol → Handler receives block → BlockChain.InsertChain() — header, body, and state validation → chain reorganization (reorg) if necessary → notify TxPool of new head → pool state update ``` ## Database Structure The storage layer is composed of the following hierarchy: * **ChainDB**: A persistent store based on LevelDB or Pebble that stores blocks, receipts, and canonical mappings. * **Ancient Store (Freezer)**: Separates old block data into an append-only store to manage ChainDB size. * **TrieDB**: Manages Merkle Patricia Trie nodes and supports both hash-based and path-based schemes. * **Snapshot**: Stores state in a flattened key-value structure to enable fast queries. For details, see [Storage Architecture](/en/storage-architecture/index). ## Chain Configuration Chain-specific parameters are defined in `params.ChainConfig` and control fork activation points, consensus rules, and network-specific settings. | Item | Description | | ---------------------- | ----------------------------------------------------------- | | `ChainID` | Unique chain identifier | | Fork activation blocks | Block heights at which EIPs are activated | | `Anzeon` | WBFT consensus parameters and system contract configuration | The Anzeon configuration includes consensus parameters such as block period (`BlockPeriod`), epoch size (`Epoch`), and request timeout (`RequestTimeout`), as well as system contract initialization information. # Build and CI/CD Source: https://docs.stablenet.network/en/development-tools/10.1-building-and-cicd ## Purpose and Scope This document describes the overall build system and CI/CD pipeline of go-stablenet.\ It covers how to build binaries in a local environment, the structure of the CI/CD pipeline, and the process for generating release artifacts, with a focus on **pre-built binaries as the primary distribution method**. For information on installing pre-built binaries or configuring a running node, see [Installation and Building](/en/getting-started/2.1-installation-and-building) and [Node Configuration](/en/getting-started/2.2-node-configuration). ## Build System Architecture The go-stablenet project uses a **dual-layer build system**. 1. **Makefile**\ An interface for developers to quickly build binaries or run tests locally. 2. **build/ci.go**\ An integrated build tool responsible for CI/CD execution, cross-compilation, and release archive generation. The Makefile internally invokes `build/ci.go` and is designed so that local builds and CI builds produce results that are as identical as possible. ### Build System Components * `Makefile`: Developer-facing entry point * `build/ci.go`: Core logic for CI/CD and release automation * `build/bin/`: Output directory for local build artifacts * `internal/build/`: Checksum, download, and verification logic * `params/version.go`: Version definition ## Version Management Version information is centrally managed in `params/version.go` and is embedded into all binaries at build time. ### Version Structure | Component | Source | Example | | ---------- | ---------------------- | ---------- | | Major | `params.VersionMajor` | `0` | | Minor | `params.VersionMinor` | `1` | | Patch | `params.VersionPatch` | `0` | | Meta | `params.VersionMeta` | `stable` | | Git Commit | Injected at build time | `a1b2c3d4` | | Git Date | Derived from commit | `20240115` | ### Version String Formats * **Version**: `0.1.0` * **VersionWithMeta**: `0.1.0-stable` * **ArchiveVersion**: `0.1.0-a1b2c3d4` * **VersionWithCommit**: `0.1.0-stable-a1b2c3d4-20240115` Version metadata is injected at compile time using linker flags. ```text theme={null} -X github.com/ethereum/go-ethereum/internal/version.gitCommit= -X github.com/ethereum/go-ethereum/internal/version.gitDate= ``` ## Local Builds ### Makefile-Based Builds The Makefile simplifies the most common build tasks. | Target | Command | Output | | ------------------ | ------------------------ | ----------------------- | | gstable | `make gstable` | Main node binary | | genesis\_generator | `make genesis_generator` | Genesis generation tool | | all | `make all` | All executables | | test | `make test` | Run tests | | lint | `make lint` | Run linting | | clean | `make clean` | Clean build artifacts | All outputs are generated in the `build/bin/` directory. ### build/ci.go-Based Builds `build/ci.go` is a tool for reproducing the same build conditions locally as in the CI environment. Primary responsibilities: * Cross-compilation * Release archive generation * Checksum verification * Application of CI-specific build flags ## Cross Compilation The build system supports the following architectures: * `amd64` * `386` * `arm` (GOARM v5/v6/v7) * `arm64` ### ARM64 Example ```bash theme={null} GOOS=linux GOARCH=arm64 make gstable ``` ### ARM v7 Example ```bash theme={null} GOOS=linux GOARCH=arm GOARM=7 make gstable ``` ## CI/CD Pipeline Architecture go-stablenet uses a **multi-platform CI environment**. ### CI Platform Matrix | Platform | OS | Architectures | Purpose | | --------- | ------- | ---------------------- | --------------------- | | Travis CI | Linux | amd64, arm64, 386, arm | Main builds and tests | | Travis CI | macOS | amd64, arm64 | macOS binaries | | AppVeyor | Windows | amd64, 386 | Windows builds | ### Travis CI * Triggers: master branch, tags, pull requests * Multi-Go-version testing * Docker image builds * Release archive generation ### AppVeyor * Windows-only builds * ZIP archive generation * Signed binary outputs ## Release Artifacts ### Archive Generation Release archives include executables and license files. | Archive | Platform | | ------- | ------------- | | tar.gz | Linux / macOS | | zip | Windows | Filename format:\ `gstable-{platform}-{arch}-{version}.{ext}` ### Signing and Upload * Optional PGP or Signify signatures * Upload to Azure Blob Storage * Performed only for master or tagged builds ## CI Tests and Linting ### Tests CI tests are executed with the following conditions: * Timeout: 20 minutes * Limited parallelism (`-p 1`) * Integration test tags enabled * Optional race detection ### Linting `golangci-lint` is used, with the following linters enabled: * goimports * govet * staticcheck * ineffassign * misspell * unused * whitespace ## Dependency Management All external dependencies are managed via `build/checksums.txt`. * SHA256 verification before download * Reproducible builds * Identical behavior in CI and local builds ## Build Flags and Linker Settings ### Build Tags | Tag | Purpose | | --------------------- | ------------------------------------ | | urfave\_cli\_no\_docs | Disable CLI documentation generation | | ckzg | Enable KZG cryptography | | integrationtests | Integration tests | | netgo | Pure Go networking | | osusergo | Pure Go user lookup | ### Linker Flags ```text theme={null} -ldflags "-X ...gitCommit -X ...gitDate -s -trimpath" ``` ## Summary The key characteristics of the go-stablenet build and CI/CD system are: 1. Dual-layer structure using Makefile and build/ci.go 2. Multi-platform CI 3. Cross-compilation support 4. Reproducible release artifacts 5. Checksum-based dependency verification 6. Embedded version metadata in all binaries This architecture provides StableNet with a consistent and predictable build and deployment environment. # devp2p CLI Tools Source: https://docs.stablenet.network/en/development-tools/10.2-devp2p-cli-tools ## Purpose and Scope This document describes the `devp2p` command-line tool, a developer utility for interacting with and testing the StableNet peer-to-peer networking layer.\ `devp2p` provides commands for DNS-based node discovery management, node discovery protocol testing (Discovery v4 and v5), node key management, network crawling, and protocol conformance testing. For instructions on building the tool itself, see [Build and CI/CD](/en/development-tools/10.1-building-and-cicd). For broader information on testing frameworks and debugging, see [Testing Framework](/en/development-tools/10.4-testing-framework). ## Command Structure Overview The `devp2p` CLI consists of multiple top-level commands, each providing a related set of operations for network development and testing. ### Command Hierarchy * `dns`\ DNS-based node discovery (EIP-1459) tree management * `discv4`\ Discovery v4 (UDP-based) protocol testing and diagnostics * `discv5`\ Discovery v5 (encrypted, topic-based) protocol testing and diagnostics * `key`\ Node key generation and conversion, enode URL generation * `crawl`\ Network crawling and node set maintenance * `test`\ Execution of Discovery protocol conformance test suites ## DNS Discovery Management The `dns` command group provides tools for managing DNS-based node discovery trees as defined in EIP-1459.\ DNS discovery is used in environments where node lists are distributed and updated via DNS TXT records. ### DNS Command Architecture A DNS discovery tree consists of the following elements: * Root TXT record (`enrtree-root`) * Signed tree nodes * Child TXT records pointing to ENR records * Sequence numbers and signatures The `devp2p dns` commands manage this entire structure using a local directory-based representation. ### DNS Sync Command `dns sync` downloads a DNS discovery tree from a remote URL and stores it in a local directory. | Flag | Description | Default | | ----------- | ----------------- | ------- | | `--timeout` | DNS query timeout | None | **Behavior:** * Fetch the DNS tree root from the URL * Traverse the entire tree by following TXT records * Verify signatures for each node * Store the complete tree as local files ### DNS Sign Command `dns sign` signs an existing DNS discovery tree with a private key, updating the sequence number and root signature. | Flag | Description | Required | | ---------- | ---------------- | --------------------- | | `--domain` | Tree domain name | Yes | | `--seq` | Sequence number | No (auto-incremented) | **Behavior:** * Load the local tree * Load the private key * Update the sequence number * Sign the root node * Save the updated tree ### DNS TXT Export The `to-txt` subcommand exports a signed DNS discovery tree into a text file containing standard DNS TXT record entries.\ This file can be used for manual deployment or inspection. ```text theme={null} example.com. TXT "enrtree-root:v1 e=ABC123... l=DEF456... seq=1 sig=789..." _abc123.example.com. TXT "enrtree://..." ``` > Automated deployment to external DNS providers such as Cloudflare or Route53 is not supported by StableNet and is therefore out of scope for this document. ## Node Discovery v4 Tools The `discv4` command group provides tools for testing and diagnosing the Discovery v4 protocol (UDP-based node discovery). ### Discovery v4 Ping Sends a PING packet to a remote node and waits for a PONG response to verify connectivity. **Key Flags (discoveryNodeFlags):** * `--bootnodes`: Bootstrap node list * `--nodekeyhex`: Hex-encoded node private key * `--nodekey`: Path to node key file * `--listen`: Local UDP listen address * `--extip`: External IP to record in the ENR **Execution Flow:** 1. Create a UDP listener 2. Initialize a `discover.UDPv4` instance 3. Send a PING to the target node 4. Wait for a PONG response 5. Calculate and print round-trip time (RTT) ### Discovery v4 ENR Request Requests a node’s ENR (Ethereum Node Record) using the EIP-868 `ENRRequest` message. **Execution Flow:** 1. Verify connectivity via PING 2. Send an ENRRequest 3. Receive an ENRResponse 4. Validate and display the ENR ### Discovery v4 Resolve Performs a Kademlia-style lookup to locate a specific node in the DHT. **Execution Flow:** 1. Connect to bootstrap nodes 2. Repeatedly send FINDNODE requests 3. Return the ENR when the target node is found ### Discovery v4 Crawl Crawls the DHT to discover reachable nodes and updates the `nodes.json` file. | Flag | Description | Default | | ------------ | -------------------------- | ---------- | | `--timeout` | Crawl time limit | 30 minutes | | `--parallel` | Number of parallel queries | 16 | **Crawling Algorithm:** 1. Load existing `nodes.json` as the seed set 2. Repeatedly query random nodes 3. Validate nodes via PING 4. Retain only responsive nodes in the result set 5. Perform periodic revalidation **Revalidation Policy:** * Nodes are re-pinged after `revalidateInterval` * Unresponsive nodes are removed from the result set ### Discovery v4 Test Suite Runs Discovery v4 protocol conformance tests against a target node. **Test Categories:** * Ping tests * FindNode tests * Amplification tests * Spoofing tests ## Node Discovery v5 Tools The `discv5` command group provides tools for testing and diagnosing the Discovery v5 protocol. ### Discovery v5 Operations #### Ping Verifies node connectivity through Discovery v5 PING/PONG exchanges. #### Resolve Searches for nodes using Discovery v5 DHT lookups. #### Crawl Crawls the network using the Discovery v5 protocol. ## Node Key Management The `key` command group provides utilities for node key generation and conversion. ### Key Generation Generates a new ECDSA private key used for node identity. ### Enode URL Generation Generates an enode URL from a private key. ```text theme={null} enode://pubkey@ip:port?discport=udp ``` ## File Formats ### Node Key File Format ```text theme={null} 64-character-hex-string ``` ## Integration with the P2P Stack The `devp2p` CLI tool uses the same networking components as the full node. * `p2p/discover` * `p2p/enode` * `p2p/dnsdisc` * `crypto` # Data Import and Export Utilities Source: https://docs.stablenet.network/en/development-tools/10.3-data-import-and-export-utilities This document describes the data import and export utilities provided by StableNet for managing blockchain data, snapshots, and database contents.\ These utilities enable file-based chain synchronization, blockchain backups, historical data archiving, and database manipulation. For live chain synchronization over the P2P network, see [Chain Synchronization](/en/networking/7.3-chain-synchronization). For database architecture and storage mechanisms, see [Database Layer and Merkle Patricia Tries](/en/storage-architecture/9.1-database-layer-and-merkle-patricia-tries) and [Ancient Store and Data Lifecycle](/en/storage-architecture/9.3-ancient-store-and-data-lifecycle). ## Overview StableNet provides a set of command-line utilities for importing and exporting various types of blockchain data.\ These utilities operate in a **file-based** manner rather than via network connections and serve the following purposes: * **Offline synchronization**: Node bootstrapping using trusted chain dumps * **Backup and recovery**: Chain state backups for disaster recovery * **Historical archiving**: Preservation of historical block data using the Era1 format * **Database migration**: Movement of raw database data between nodes * **Testing and development**: Selective import/export of specific chain ranges All utilities automatically detect gzip compression via the `.gz` extension and\ support interrupt-based termination for long-running operations. ## Chain Import and Export ### ImportChain `ImportChain` reads blocks from an RLP-encoded file and inserts them into the blockchain.\ Processing is performed in batches to limit memory usage. * Batch size: 2500 blocks * The genesis block is automatically skipped * Existing blocks are not re-inserted * SIGINT / SIGTERM signals are detected for safe interruption Missing block detection uses the following criteria: * At or below the current head: `HasBlock` * Above the current head: `HasBlockAndState` ### ExportChain `ExportChain` exports the entire blockchain into a single RLP file. * Overwrites the target file if it already exists * Applies gzip compression when using the `.gz` extension * Internally uses `blockchain.Export` ### ExportAppendChain `ExportAppendChain` appends a specified block range to an existing file. * Suitable for incremental backups or segmented exports * Writes blocks from `first` to `last` (inclusive) ## Era1 History Format Era1 is a standard historical data format defined by the Ethereum Portal Network specification.\ A single Era1 file contains approximately 8192 blocks (one epoch) and includes the following data: * Block headers and bodies * Receipts * Total difficulty ### ImportHistory Restores the chain from genesis using an Era1 directory. Requirements: * The current block height must be 0 * A `checksums.txt` file must be present * Era1 file naming conventions must be followed Processing flow: 1. List Era1 files in the directory 2. Verify SHA256 checksums 3. Process blocks per Era1 file 4. Skip the genesis block 5. Insert data in the order HeaderChain → ReceiptChain 6. Periodically log progress ### ExportHistory Exports chain data in the Era1 format. * The `step` value is typically 8192 * File names include the accumulator root hash * `checksums.txt` is generated automatically ## Preimage Import and Export Preimages are the original key data prior to hashing in the state trie. ### ImportPreimages Restores preimage data from an RLP file into the database. * Processed in batches (1024 entries) * Uses the Keccak256 hash as the key * This feature is **deprecated and scheduled for removal** ### ExportPreimages Exports all preimages stored in the database to a file. ### ExportSnapshotPreimages Extracts only the preimages required for a specific snapshot root. * Account address preimages * All storage key preimages for those accounts * Fails if any required preimage is missing ## LevelDB Data Import and Export Low-level database operations support state transfer or recovery between nodes. ### LDB Export Header Structure * Magic: `"gethdbdump"` * Version: 0 * Kind: Data type * UnixTime: Export timestamp ### ImportLDBData Imports raw key-value pairs into the database. * Operation codes: Add / Delete * Immediate flush when batch size is exceeded * Interrupt checks every 1000 entries ### ExportChaindata A generalized database export utility.\ Processes multiple data sources via the `ChainDataIterator` interface. ```text theme={null} type ChainDataIterator interface { Next() (byte, []byte, []byte, bool) Release() } ``` ## Data Integrity and Validation ### Checksum Verification During Era1 imports, each file is fully verified using SHA256 before processing.\ This guarantees integrity prior to parsing. ### Block Validation * Duplicate block elimination * Header and body validation via the consensus engine * State availability checks ## Interrupt Handling All long-running operations follow this pattern: 1. Create an interrupt channel 2. Handle SIGINT / SIGTERM 3. Close the channel upon signal reception 4. Periodically check the channel in the main loop ## File Format Summary | Format | Extension | Compression | Content | Use Case | | --------- | --------- | ------------ | -------------- | --------------- | | RLP Chain | .rlp | Optional .gz | Block sequence | Full backup | | Era1 | .era1 | None | Epoch blocks | History archive | | LDB | .ldb | Optional .gz | Raw KV | DB migration | | Preimages | .rlp | Optional .gz | Trie preimage | State recovery | ### Automatic Compression Detection Logic ```text theme={null} if strings.HasSuffix(fn, ".gz") { reader, _ = gzip.NewReader(reader) writer = gzip.NewWriter(writer) } ``` ## Progress Reporting * Default log interval: 8 seconds * Reported information: * Operation type * Current position * Cumulative elapsed time ## Command-Line Integration | Command | Function | Description | | ----------------------------- | ----------------- | ----------------- | | gstable import | ImportChain | Import RLP chain | | gstable export | ExportChain | Export full chain | | gstable export `first` `last` | ExportAppendChain | Export range | | gstable import-history | ImportHistory | Import Era1 | | gstable export-history | ExportHistory | Export Era1 | | gstable import-preimages | ImportPreimages | Import preimages | | gstable export-preimages | ExportPreimages | Export preimages | | gstable db import | ImportLDBData | Import raw DB | | gstable db export | ExportChaindata | Export raw DB | # Test Framework Source: https://docs.stablenet.network/en/development-tools/10.4-testing-framework ## Purpose and Scope The test framework provides infrastructure for running standardized Ethereum JSON test fixtures to validate core protocol behavior.\ Its goal is to verify that transaction processing, block validation, state transitions, and consensus rules operate correctly across a range of hard-fork configurations. The test fixtures use data from the `tests` directory included in the StableNet codebase and are executed directly on top of the StableNet implementation. For EVM-specific testing tools, see [EVM Testing Tools](/en/development-tools/10.5-evm-testing-tools). For general build and CI/CD flows, see [Build and CI/CD](/en/development-tools/10.1-building-and-cicd). ## Test Type Overview The test framework supports four major test categories to validate different aspects of the protocol. | Test Type | Purpose | JSON Structure | Execution | | --------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------- | | **State Tests** | Validate transaction processing without block context | `stJSON` containing pre-state, transaction, and post-state | Execute a single transaction on top of genesis | | **Block Tests** | Validate full blocks including header/body and state transitions | `btJSON` containing genesis and a block sequence | Insert blocks sequentially | | **Transaction Tests** | Validate RLP encoding and sender derivation | Transaction RLP with expected sender per fork | Decode and verify sender | | **Difficulty Tests** | Validate difficulty calculation rules | Parent header and expected difficulty | Compare against consensus engine output | ## Test Infrastructure Architecture ### testMatcher Pattern Matching `testMatcher` controls test selection, configuration overrides, and expected-failure handling via regular-expression rules. | Pattern Type | Method | Purpose | | ---------------- | ------------------------ | -------------------------------------------------- | | `skiploadpat` | `skipLoad(pattern)` | Skip JSON loading itself to reduce memory usage | | `slowpat` | `slow(pattern)` | Exclude in `-short` mode or on 32-bit environments | | `failpat` | `fails(pattern, reason)` | Mark known failing tests | | `configpat` | `config(pattern, cfg)` | Override chain config for specific tests | | `runonlylistpat` | `runonly(pattern)` | Run only tests matching the specified pattern | ## Running State Tests State tests execute a single transaction against a pre-state and validate the resulting state root and logs, allowing transaction processing logic to be verified in isolation. ### StateTest Implementation Overview State tests generate and run subtests for each fork combination and input index. Key methods: | Method | Purpose | | ------------------ | ----------------------------------------------- | | `Subtests()` | Enumerate all fork/index combinations | | `Run(...)` | Execute and verify results | | `RunNoVerify(...)` | Execute without verification (for benchmarking) | | `checkError(...)` | Validate whether an error was expected | ### Execution Flow Summary 1. Parse fork string and load chain config 2. Create genesis block and set up pre-state 3. Convert the transaction into a `core.Message` 4. Create EVM context and execute the transaction 5. Commit state and compute state root 6. Compare against expected state root, logs, and exceptions ### Running Across Storage Schema Variants Each State test is executed across the following four combinations: * `hash / trie`: hash-based scheme without snapshots * `hash / snap`: hash-based scheme with snapshots * `path / trie`: path-based scheme without snapshots * `path / snap`: path-based scheme with snapshots This validates consistency across both StateDB and snapshot layers. ## Running Block Tests Block tests insert a block sequence into an actual chain and validate the final state and header chain to confirm end-to-end blockchain behavior. ### BlockTest Implementation Overview Block tests include the following tasks: * Create a genesis block from test data * Insert test blocks sequentially * Handle valid vs invalid blocks * Validate final state and header chain If a block JSON lacks `BlockHeader`, `transactions`, and `UncleHeaders`, that block is treated as **invalid**, and insertion failure is the expected behavior. ### Execution Flow Summary 1. Commit genesis state to the DB 2. Initialize the blockchain including the consensus engine and caches 3. Insert test blocks sequentially 4. Validate account state against the final StateDB 5. Validate header consistency by walking backward from the chain head ## Transaction Tests Transaction tests validate that RLP decoding and sender derivation behave correctly under different fork rules. The framework verifies: 1. Whether RLP decoding succeeds 2. Sender recovery via ECDSA signatures 3. Validity of intrinsic gas calculation 4. Transaction hash consistency ## Fork Configuration The test framework predefines chain configurations for all Ethereum hard forks. Examples include: | Fork | Key Characteristics | | --------- | --------------------- | | Frontier | Initial release | | Byzantium | Difficulty bomb delay | | Istanbul | Gas cost adjustments | | London | EIP-1559 BaseFee | | Merge | Transition to PoS | | Cancun | Blob transactions | | Anzeon | WBFT consensus | Fork strings may include EIP overrides such as `"Berlin+1884+1283"`, and are configured dynamically at runtime. ## Test Directory Structure Test data is organized using a standardized directory structure. ```text theme={null} tests/ ├── testdata/ │ ├── BlockchainTests/ │ ├── GeneralStateTests/ │ ├── TransactionTests/ │ ├── RLPTests/ │ ├── BasicTests/ │ └── LegacyTests/ ├── spec-tests/ │ └── fixtures/ │ ├── blockchain_tests/ │ └── state_tests/ └── evm-benchmarks/ └── benchmarks/ ``` ## EVM Command Integration The `cmd/evm` tool provides a CLI interface for running Block tests. ### blocktest Command Overview Key flags include: * `--run`: select tests via regular expression * `--machine`: output JSON-based EVM traces * `--dump`: dump final state after execution ## Benchmarking Support State tests support benchmark execution for performance measurement. Benchmarks measure: * Gas throughput (mgas/s) * Total execution time * Effective throughput accounting for gas refunds This enables quantitative analysis of how EVM and StateDB changes impact performance. ## Error Handling and Verification ### Expected Exception Handling Tests determine success by comparing expected exceptions with actual outcomes. | Expected | Actual | Result | | ------------------ | ------------ | ------ | | No exception | No error | Pass | | Exception expected | Error occurs | Pass | | No exception | Error occurs | Fail | | Exception expected | No error | Fail | The current implementation does not strictly compare error strings; it focuses primarily on whether an error occurred. ### Diagnostic Output on Failure When a test fails, the following information is provided: * Full EVM execution trace for the failing test * Step-by-step operation logs in JSON format * Gas-limit-based constraints to prevent excessive output This enables precise analysis of protocol behavior issues. # EVM Testing Tools Source: https://docs.stablenet.network/en/development-tools/10.5-evm-testing-tools ## Purpose and Scope This page describes the testing and debugging tools provided by StableNet for EVM bytecode execution, state transitions, and transaction validation.\ These tools are essential for developers performing smart contract development, consensus rule verification, and transaction execution debugging. The core tool is the `cmd/evm` utility, which provides multiple subcommands supporting a wide range of testing scenarios.\ This document covers both command-line tools and programmatic testing interfaces. For more comprehensive testing infrastructure and JSON test fixtures, see\ [Test Framework](/en/development-tools/10.4-testing-framework). ## Command-Line Tool Overview The `evm` command-line tool provides an isolated execution environment for testing EVM bytecode, transactions, and state transitions without running a full node.\ All commands support various tracing and debugging options. ### Available Commands * `evm run` * `evm transition` (`t8n`) * `evm transaction` (`t9n`) * `evm block-builder` (`b11r`) * `evm blocktest` ## evm run Command The `run` command executes arbitrary EVM bytecode in an isolated environment with configurable state and block context. ### Key Flags | Flag | Type | Default | Description | | ------------- | ------- | ----------- | ------------------------------------- | | `--code` | string | - | Hex-encoded EVM bytecode | | `--codefile` | string | - | Bytecode file (`-` for stdin) | | `--input` | string | - | Call data (hex) | | `--inputfile` | string | - | Call data file | | `--gas` | uint64 | 10000000000 | Gas limit | | `--price` | big.Int | 0 | Gas price | | `--value` | big.Int | 0 | Transferred value | | `--sender` | address | default | Sender address | | `--receiver` | address | default | Receiver address | | `--create` | bool | false | Use CREATE instead of CALL | | `--prestate` | string | - | Genesis JSON for state initialization | | `--debug` | bool | false | Full trace output | | `--json` | bool | false | JSON output | | `--dump` | bool | false | Dump state after execution | | `--bench` | bool | false | Run benchmark | ### Execution Process `runCmd` orchestrates execution in the following order: 1. Initialize StateDB with genesis or an empty state 2. Load bytecode (`--code`, `--codefile`, or positional argument) 3. Set up sender and receiver accounts 4. Configure `runtime.Config` with gas, price, and block context 5. Execute one of `Execute`, `Call`, or `Create` 6. Output execution result, gas usage, and optional traces ## evm transition (t8n) Command The `transition` command implements the Ethereum state transition function, applying a set of transactions to a pre-state and producing a post-state.\ It is a core tool for validating consensus-level transaction processing. ### Input Formats `t8n` requires the following three inputs: * **alloc.json**: Pre-state account allocation * **env.json**: Block environment information * **txs.json** or `txs.rlp`: Transaction list ### Output Formats * **alloc.json**: Post-state * **result.json**: Execution results * **body.rlp**: Block body (optional) ### Key Flags | Flag | Default | Description | | ------------------ | ----------- | -------------------- | | `--input.alloc` | stdin | Pre-state allocation | | `--input.env` | stdin | Block environment | | `--input.txs` | stdin | Transactions | | `--output.basedir` | - | Output directory | | `--output.alloc` | alloc.json | Post-state | | `--output.result` | result.json | Execution result | | `--output.body` | body.rlp | Block body | | `--state.fork` | - | Fork name | | `--state.chainid` | 1 | Chain ID | | `--state.reward` | -1 | Mining reward | | `--trace` | false | JSON trace | | `--trace.tracer` | - | Custom tracer | ### Fork Configuration `--state.fork` specifies the consensus rules to apply. * `Frontier`, `Homestead`, `EIP150`, `EIP158` * `Byzantium`, `Constantinople`, `Istanbul` * `Berlin`, `London`, `Shanghai`, `Cancun` * `Anzeon` (StableNet-specific) Additional EIPs can be specified in the form `London+3855+3860`. ### Environment Validation Rules Required fields are validated depending on the active fork. * London: `currentBaseFee` or `parentBaseFee` required * Shanghai: `withdrawals` required * Merge: `currentRandom` required, difficulty must be 0 * Cancun: `parentBeaconBlockRoot` required ## evm transaction (t9n) Command The `t9n` command validates transaction encoding and signature recovery without executing the transaction. ### Validation Items 1. Whether RLP decoding succeeds 2. Sender recovery via ECDSA signature 3. Compliance with fork-specific validation rules ### Key Flags | Flag | Default | Description | | ----------------- | ------- | ----------------- | | `--input.txs` | stdin | Transaction input | | `--state.fork` | - | Fork rules | | `--state.chainid` | 1 | Chain ID | ## evm block-builder (b11r) Command The `block-builder` command constructs a complete block from transactions, ommers, and withdrawals. ### Key Flags | Flag | Default | Description | | --------------------- | ------- | ------------------ | | `--input.header` | - | Header template | | `--input.txs` | - | Transaction RLP | | `--input.ommers` | - | Uncle headers | | `--input.withdrawals` | - | Withdrawal list | | `--output.block` | - | Output block RLP | | `--seal.clique` | - | Clique signing key | ## evm blocktest Command `blocktest` executes blockchain tests in JSON format to validate block validity and state transitions.\ The test structure and execution logic follow the same rules as the test framework. ## Integration with the Test Framework The `evm` tool internally reuses the execution logic from the `tests` package. ### Key Test Functions | Function | Purpose | | ------------------------- | ---------------------------- | | `StateTest.Run()` | Execute State tests | | `StateTest.RunNoVerify()` | Execute without verification | | `BlockTest.Run()` | Execute Block tests | | `TransactionTest.Run()` | Validate transactions | | `MakePreState()` | Create pre-state | | `GetChainConfig()` | Parse fork configuration | ## EVM Runtime Package The `core/vm/runtime` package provides a programmatic interface for executing the EVM without blockchain infrastructure. ### Default Behavior `runtime.Config` provides reasonable defaults. * All hard forks enabled * Difficulty 0 (post-merge) * Maximum GasLimit * BaseFee 1 gwei * BlobBaseFee 1 wei ### State Preparation Steps Before execution, the following steps are performed: 1. Access list warm-up (post-Berlin) 2. Transient storage initialization (EIP-1153) 3. Precompile address warm-up 4. Transaction-related address warm-up ## Test Workflow Summary EVM testing tools are typically used in the following workflow: 1. Single bytecode testing (`evm run`) 2. Consensus rule validation (`evm transition`) 3. Transaction format validation (`evm transaction`) 4. Block construction and validation (`evm block-builder`, `evm blocktest`) This allows precise validation of EVM and consensus logic without running a full node. # Development Tools Source: https://docs.stablenet.network/en/development-tools/index ## Purpose and Scope This document provides an **overview of all development tools** available in the go-stablenet codebase.\ The tools covered here support the entire lifecycle of **building, testing, debugging, operating, and maintaining** StableNet nodes and networks. The development tools are organized into four major categories, each of which is described in detail in its own subdocument. * **Building and CI/CD**\ Build system, cross-compilation, and CI/CD pipeline * **devp2p CLI Tools**\ DNS-based discovery, P2P network diagnostics, and testing tools * **Data Import and Export Utilities**\ Blockchain data management tools (chain, history, snapshots) * **Testing and Debugging**\ Test frameworks, protocol validation, and static analysis tools Rather than describing individual commands in detail, this document serves as a **high-level guide to understanding the overall tool ecosystem and how the tools relate to each other**. ## Tool Categories Development tools are distributed across the codebase, with the following primary entry points. | Category | Entry Point | Primary Use Cases | | ---------------- | --------------------------------------------------- | ------------------------------------------------------- | | Build Automation | `build/ci.go`, `Makefile` | Executable builds, cross-compilation, release packaging | | CI/CD Pipelines | `.travis.yml`, `appveyor.yml` | Automated testing, builds, deployment | | Network Tools | `cmd/devp2p/` | P2P network diagnostics, DNS discovery management | | Chain Management | `cmd/utils/cmd.go` | Chain import/export, Era1, snapshot management | | Code Quality | `.golangci.yml`, `build/ci.go` | Static analysis, linting | | Testing | `internal/utesting/`, `cmd/devp2p/internal/v4test/` | Unit tests, P2P protocol tests | ## Build System Architecture The core of the build system is `build/ci.go`, which acts as the **single control point for all build, test, and release tasks**. ### Key Components * `build/ci.go`\ Main orchestrator for building, testing, archiving, and uploading * `build.GoToolchain`\ Manages Go compiler configuration, including cross-compilation * `build.Environment`\ Collects commit, date, branch, and tag metadata from CI or local Git environments * `build.ChecksumDB`\ Verifies external dependency integrity using `build/checksums.txt` This build system supports the following via `-arch` and `-cc` flags: * Architectures: `amd64`, `386`, `arm`, `arm64` * Platforms: `linux`, `darwin`, `windows`, `freebsd` ## CI/CD Pipeline Architecture Continuous Integration (CI) is **split by platform characteristics**. * **Travis CI**: Linux / macOS * **AppVeyor**: Windows This separation ensures consistent multi-platform release quality from a single codebase. ### Pipeline Stages 1. **Code Push Trigger**\ Triggered on pushes to the master branch or version tags 2. **Parallel Builds**\ Parallel jobs per platform and architecture 3. **Test Execution**\ Basic tests on all builds, race detection in scheduled jobs 4. **Artifact Generation**\ Creation of signed binary archives in zip / tar.gz formats ## Development Tool Invocation Flow The following shows how developers typically interact with tools locally and in CI environments. | Command | Purpose | Implementation | | ------------------------ | ----------------------- | ---------------------------------------------------- | | `make gstable` | Build main node | `go run build/ci.go install ./cmd/gstable` | | `make genesis_generator` | Build genesis generator | `go run build/ci.go install ./cmd/genesis_generator` | | `make all` | Build all executables | `go run build/ci.go install` | | `make test` | Run tests | `go run build/ci.go test` | | `make lint` | Static analysis | Runs `golangci-lint` | | `make devtools` | Install dev tools | stringer, gencodec, abigen, etc. | ## Quick Reference: Available Tools ### Build and Release Tools | Tool | Location | Command | Description | | ----------------- | ------------- | -------------------------- | ----------------------------- | | Main build script | `build/ci.go` | `go run build/ci.go ` | Build orchestration | | Makefile | `Makefile` | `make ` | Developer convenience wrapper | ### Network and Discovery Tools | Tool | Location | Description | | --------------- | ----------------------------------------- | ------------------------------------ | | devp2p | `cmd/devp2p/` | P2P network diagnostics | | DNS discovery | `cmd/devp2p/dnscmd.go` | DNS-based node discovery management | | Discovery v4/v5 | `cmd/devp2p/discv4cmd.go`, `discv5cmd.go` | DHT-based discovery protocol testing | | Node crawler | `cmd/devp2p/crawl.go` | Network topology collection | ### Chain Management Tools | Tool | Location | Description | | ------------------- | ------------------ | --------------------------- | | Chain import/export | `cmd/utils/cmd.go` | Chain data migration | | Era1 archive | `cmd/utils/cmd.go` | Historical block management | | Preimage tools | `cmd/utils/cmd.go` | Hash preimage management | | Snapshot export | `cmd/utils/cmd.go` | State snapshot preimages | ### Testing and Verification Tools | Tool | Location | Description | | ------------------ | ----------------------------- | ----------------------------------- | | Unit tests | Entire codebase | Go standard tests | | P2P protocol tests | `cmd/devp2p/internal/v4test/` | Discovery v4 compliance tests | | Test utilities | `internal/utesting/` | TAP-compatible test runner | | Linter | `.golangci.yml` | golangci-lint-based static analysis | ## Build Flags and Configuration ### Cross-Compilation Flags | Flag | Description | | --------- | ----------------------------- | | `-arch` | Target architecture | | `-cc` | C compiler for cgo | | `-static` | Static binary linking | | `-dlgo` | Download specified Go version | ### CI Environment Variables In CI environments, commit metadata, signing keys, and upload tokens are injected via environment variables. * `TRAVIS_COMMIT`, `APPVEYOR_REPO_COMMIT` * `AZURE_BLOBSTORE_TOKEN` * `LINUX_SIGNING_KEY`, `OSX_SIGNING_KEY` * `AWS_ACCESS_KEY_ID` (for DNS management) ## Tool Dependencies and Versions All external tool dependencies have **pinned versions and SHA256 checksums** in `build/checksums.txt`. | Tool | Version | Purpose | | -------------------- | ------- | -------------------- | | Go compiler | 1.21.6 | Build toolchain | | golangci-lint | 1.55.2 | Linting | | execution-spec-tests | 2.1.0 | Execution spec tests | When required, tools are automatically downloaded and verified via `build.ChecksumDB`. *** For practical usage examples and detailed instructions, refer to the following subdocuments: * Building and CI/CD * devp2p CLI Tools * Data Import and Export Utilities * Testing and Debugging # Installation and Building Source: https://docs.stablenet.network/en/getting-started/2.1-installation-and-building ## Purpose and Scope This document provides detailed instructions for building StableNet from source. It covers the build system architecture, available build targets, and cross-compilation options. For information on configuring a built node, see [Node Configuration](/en/getting-started/2.2-node-configuration).\ For initializing a new network with a genesis file, see [Genesis Setup and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization). ## Prerequisites Building StableNet from source requires **Go 1.22 or later**. Additional dependencies required for building: * **C compiler** (gcc or clang) — required for CGO-enabled packages * **Git** — required for embedding version metadata * **Make** (optional, for convenience targets) ## Build System Architecture The StableNet build system is centered around Go-based build scripts that generate node executables, handle build environment detection, and apply shared build logic. ### Build System Components | File Path | Purpose | | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | [`build/ci.go`](https://github.com/stable-net/go-stablenet/blob/master/build/ci.go) | Main build orchestrator with subcommands | | [`Makefile`](https://github.com/stable-net/go-stablenet/blob/master/Makefile) | Convenience wrapper for common tasks | | [`internal/build/util.go`](https://github.com/stable-net/go-stablenet/blob/master/internal/build/util.go) | Build utility functions | | [`internal/build/gotool.go`](https://github.com/stable-net/go-stablenet/blob/master/internal/build/gotool.go) | Go toolchain management | | [`internal/build/env.go`](https://github.com/stable-net/go-stablenet/blob/master/internal/build/env.go) | Environment detection (CI/local) | | [`build/checksums.txt`](https://github.com/stable-net/go-stablenet/blob/master/build/checksums.txt) | Dependency checksums for verification | ## Building from Source ### Using Make StableNet can be built easily using Makefile targets. ```bash theme={null} git clone https://github.com/stable-net/go-stablenet cd go-stablenet # Build only the gstable client make gstable # Build only genesis_generator make genesis_generator # Build all executables (gstable, abigen, bootnode, evm, rlpdump, clef, genesis_generator, etc.) make all # Verify the build ./build/bin/gstable version ``` All built binaries are created in the `build/bin/` directory. ### Using build/ci.go Directly For finer-grained control, you can invoke the build script directly: ```bash theme={null} # Build only gstable go run build/ci.go install ./cmd/gstable # Build for a specific architecture (e.g. ARM64) go run build/ci.go install -arch arm64 ./cmd/gstable # Create a statically linked binary (Linux) go run build/ci.go install -static ./cmd/gstable # Automatically download the Go version specified in checksums.txt and build go run build/ci.go install -dlgo ./cmd/gstable # Build all executables go run build/ci.go install ``` Flags available for the `install` command: | Flag | Description | | --------- | --------------------------------------------------------- | | `-dlgo` | Download and use a specific Go version from checksums.txt | | `-arch` | Target architecture (amd64, 386, arm, arm64) | | `-cc` | C compiler for cross-compilation | | `-static` | Create a statically linked executable (Linux) | ### Available Build Targets All executables are built into `build/bin/`: | Executable | Purpose | Source Path | | ------------------- | ------------------------------------ | ------------------------ | | `gstable` | Main StableNet client | `cmd/gstable/` | | `genesis_generator` | Genesis file generator | `cmd/genesis_generator/` | | `abigen` | Solidity ABI to Go binding generator | `cmd/abigen/` | | `bootnode` | Lightweight bootstrap node | `cmd/bootnode/` | | `evm` | EVM testing tool | `cmd/evm/` | | `rlpdump` | RLP data structure inspector | `cmd/rlpdump/` | | `clef` | External account signer | `cmd/clef/` | | `devp2p` | P2P network utilities | `cmd/devp2p/` | ## Cross-Compilation The build system supports cross-compilation for multiple architectures and operating systems using Go’s built-in cross-compilation features and external C toolchains. ### Supported Platforms The CI system builds for the following platforms: | Platform | Architecture | Notes | | -------- | ------------ | ------------------------------------ | | Linux | amd64 | Default, full support | | Linux | 386 | 32-bit Intel/AMD | | Linux | arm | ARMv5, ARMv6, ARMv7 (GOARM variants) | | Linux | arm64 | 64-bit ARM | | macOS | amd64 | Intel Macs | | macOS | arm64 | Apple Silicon (M1/M2) | | Windows | amd64 | 64-bit Windows | | Windows | 386 | 32-bit Windows | ## Build Verification After building, run tests to verify correct operation: ```bash theme={null} # Run quick tests make test-short # Run full test suite make test # Run lint checks make lint ``` The `build/ci.go test` command supports the following options: ```bash theme={null} # Coverage report go run build/ci.go test -coverage ./... # Race detection go run build/ci.go test -race ./... # Verbose output go run build/ci.go test -v ./... ``` # Node Configuration Source: https://docs.stablenet.network/en/getting-started/2.2-node-configuration ## Purpose and Scope This document explains how to configure a StableNet node using command-line flags, configuration files, and deployment patterns. For information on building the node binary, see [Installation and Building](/en/getting-started/2.1-installation-and-building).\ For genesis block setup and network initialization, see [Genesis Setup and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization). ## Configuration System Overview StableNet node configuration uses a hierarchical system that converts command-line flags into structured configuration objects, which are then used to initialize each component. **Configuration precedence**: Command-line flags > TOML configuration file > Defaults ## Command-Line Flags All configuration flags are defined in `cmd/utils/flags.go` and are grouped by category. ### Core Flag Categories | Category | Purpose | Key Flags | | ---------------- | ---------------------------------- | ------------------------------------------------------------------ | | Chain / Sync | Chain and synchronization settings | `--datadir`, `--networkid`, `--syncmode`, `--mainnet`, `--testnet` | | Accounts | Key management | `--keystore`, `--unlock`, `--password` | | Mining | Block production | `--mine`, `--miner.etherbase`, `--miner.gaslimit` | | Networking | P2P configuration | `--port`, `--maxpeers`, `--bootnodes`, `--nat` | | API | RPC endpoints | `--http`, `--http.port`, `--ws`, `--http.api` | | Transaction Pool | Transaction pool tuning | `--txpool.pricelimit`, `--txpool.globalslots` | | Performance | Performance tuning | `--cache`, `--cache.database`, `--cache.trie` | | State | State management | `--state.scheme`, `--gcmode` | ### Network Selection Flags StableNet provides flags for selecting predefined networks: * `--mainnet`: Connect to StableNet mainnet (ChainID 8282) * `--testnet`: Connect to StableNet testnet (ChainID 8283) * `--networkid`: Override the automatic network ID (defaults to ChainID) * Bootstrap nodes are automatically selected based on the network flag ### Data Directory The `--datadir` flag specifies the root directory where the node stores blockchain data and state.\ Some sub-paths, such as the keystore, can be overridden with separate flags. If not specified, internal defaults are used. | Flag | Purpose | Default | | ----------------------- | ------------------------------------------ | --------------------------------------------------- | | `--datadir` | Root directory for all data | Linux: `~/.stablenet`, macOS: `~/Library/StableNet` | | `--datadir.ancient` | Separate location for ancient/freezer data | `/gstable/ancient` | | `--keystore` | Override keystore location | `/keystore` | | `--datadir.minfreedisk` | Auto-shutdown disk threshold (MB) | 0 (disabled) | ## Database Configuration This setting controls the type of database engine used by the node.\ It determines how state and chain data are stored and accessed internally, affecting performance and resource usage. | Flag | Description | Default | | ------------- | -------------------------------------- | -------- | | `--db.engine` | Select state and chain database engine | `pebble` | ## Synchronization Mode The `--syncmode` flag controls how the blockchain is synchronized: | Mode | Value | Description | Use Case | | --------- | ------- | ------------------------------------------------------------------------------ | ------------------------------------ | | **Full** | `full` | Download all blocks and execute all transactions and state transitions locally | Validator nodes, standard full nodes | | **Snap** | `snap` | Download state snapshots first, then sync blocks to quickly build full state | Fast initial sync | | **Light** | `light` | Keep only block headers; request state/data on demand from peers | Low-resource environments | ## State Scheme The `--state.scheme` flag selects the state storage layout: * `hash`: Legacy hash-based scheme (default, stable) * `path`: Path-based scheme with Verkle trie support (experimental) If not specified, the node automatically selects the scheme matching the existing database. ## Mining and Validator Configuration Flags controlling block production for StableNet validators (Anzeon-enabled networks). ### Mining Flags | Flag | Purpose | Default | Notes | | ------------------- | ------------------------ | ---------------- | ----------------------- | | `--mine` | Enable mining/validation | false | Required for validators | | `--miner.etherbase` | Block reward address | Node key address | Auto-set in Anzeon | | `--miner.gaslimit` | Block gas ceiling | 105,000,000 | Target block gas limit | | `--miner.extradata` | Extra block data | Client version | Custom identifier | ## Anzeon Network Design Characteristics * `etherbase` is automatically derived from `--nodekey` and cannot be manually overridden * `GasTip` (priority fee) is enforced as a network-wide value via GovValidator governance (except for authorized accounts) * `BaseFee` uses a StableNet-customized calculation logic, with increase/decrease rates and min/max bounds controlled by chain parameters * `BaseFee` is not burned; it is distributed to validators For detailed gas fee policy, see [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy).\ For governance-based gas tip management, see [Validator Governance](/en/governance-system/5.3-validator-governance-\(govvalidator\)). ## P2P Network Configuration P2P networking flags control peer discovery and connection management. ### P2P Configuration Flags | Flag | Purpose | Default | | --------------- | ------------------------------------------- | ------------------------- | | `--port` | P2P listening port | 30303 | | `--maxpeers` | Maximum peer connections | 50 | | `--nat` | NAT port mapping method | `any` | | `--bootnodes` | Bootstrap node enode URLs (comma-separated) | Auto-selected per network | | `--nodiscover` | Disable peer discovery | false | | `--nodekey` | P2P node key file path | Auto-generated | | `--netrestrict` | Allowed network CIDR mask | None (allow all) | ### Bootstrap Node Selection Bootstrap nodes are selected in the following order: 1. Use `--bootnodes` if explicitly specified 2. Use bootstrap nodes defined in the config file 3. If `--mainnet`, use StableNet mainnet bootstrap nodes 4. If `--testnet`, use StableNet testnet bootstrap nodes ### Static and Trusted Peers Static and trusted peers can be configured in the `[Node.P2P]` section of a TOML configuration file: ```toml theme={null} [Node.P2P] StaticNodes = [ "enode://pubkey1@ip1:port1", "enode://pubkey2@ip2:port2" ] TrustedNodes = [ "enode://pubkey3@ip3:port3" ] ``` * **StaticNodes**: Peers the node always tries to maintain connections with * **TrustedNodes**: Peers exempt from peer count limits ## RPC API Configuration RPC APIs expose node functionality to external clients. StableNet supports HTTP, WebSocket, and IPC transports. ### HTTP Configuration | Flag | Purpose | Default | | ------------------- | ---------------------- | -------------- | | `--http` | Enable HTTP-RPC server | Disabled | | `--http.addr` | Listening interface | `localhost` | | `--http.port` | Listening port | 8545 | | `--http.api` | Exposed API modules | `eth,net,web3` | | `--http.corsdomain` | Allowed CORS domains | None | | `--http.vhosts` | Allowed virtual hosts | `localhost` | ### WebSocket Configuration | Flag | Purpose | Default | | -------------- | ----------------------- | -------------- | | `--ws` | Enable WebSocket server | Disabled | | `--ws.addr` | Listening interface | `localhost` | | `--ws.port` | Listening port | 8546 | | `--ws.api` | Exposed API modules | `eth,net,web3` | | `--ws.origins` | Allowed origins | None | ### IPC Configuration IPC is enabled by default, creating a socket at `/gstable.ipc`. | Flag | Purpose | Default | | -------------- | --------------- | ------------- | | `--ipcdisable` | Disable IPC | false | | `--ipcpath` | IPC socket path | `gstable.ipc` | ### API Namespace Security Do not expose all API namespaces publicly. Recommended configurations: | Deployment Type | HTTP APIs | WebSocket APIs | Notes | | ---------------- | ----------------------------------- | -------------- | ------------------------------ | | Public RPC node | `eth,net,web3` | `eth,net,web3` | Read-only, safe for public use | | Validator node | None or localhost only | None | Minimize attack surface | | Development node | `eth,net,web3,personal,debug,admin` | Same | Full access for testing | | Archive node | `eth,net,web3,txpool,debug` | Same | Debug APIs for analysis | **Warning**: `personal`, `admin`, and `debug` namespaces provide privileged operations. Never expose them on public interfaces without authentication. ### RPC Limiting Flags | Flag | Purpose | Default | | ------------------------------- | ------------------------------------------ | ------------- | | `--rpc.gascap` | Max gas for `eth_call` / `eth_estimateGas` | 50,000,000 | | `--rpc.evmtimeout` | Timeout for `eth_call` | 5 seconds | | `--rpc.txfeecap` | Max fee for `eth_sendTransaction` | 0 (unlimited) | | `--rpc.batch-request-limit` | Max requests per batch | 1000 | | `--rpc.batch-response-max-size` | Max batch response size | 25MB | These limits protect the node from resource exhaustion by malicious or misconfigured clients. ## Performance Tuning Cache and database settings have a major impact on node performance and resource usage. ### Cache Configuration The `--cache` flag sets total memory allocation, which is split across subsystems. Default allocation: ```text theme={null} Total cache: 1024 MB ├─ Database: 512 MB (50%) ├─ Trie Clean: 154 MB (15%) ├─ Snapshot: 102 MB (10%) └─ Trie Dirty (GC): 256 MB (25%) ``` For archive nodes (`--gcmode archive`), Trie Dirty cache is disabled and reallocated to Trie Clean and Snapshot. **Recommended settings by node type:** | Node Type | `--cache` | `--gcmode` | Notes | | ------------------------ | --------- | ---------- | ------------------------------- | | Validator (synced) | 4096+ | `full` | Fast state access | | Validator (initial sync) | 8192+ | `full` | Faster initial sync | | Full node | 2048 | `full` | Balanced performance | | Archive node | 8192+ | `archive` | No pruning, large disk required | ### Database Engine Selection The `--db.engine` flag selects the underlying key-value store: * **`pebble`** (default): Modern, fast, better compression * **`leveldb`**: Legacy, stable, compatible with older databases Pebble is recommended for new deployments. ### Garbage Collection and Pruning The `--gcmode` flag controls state pruning behavior: * **`full`** (default): Prunes old state tries, keeps recent state only * **`archive`**: Keeps all historical state without pruning (requires TBs of disk) ## Common Configuration Patterns ### Validator Node ```bash theme={null} gstable --mainnet \ --mine \ --nodekey /path/to/nodekey \ --syncmode full \ --datadir /data/gstable \ --cache 4096 \ --http \ --http.addr 127.0.0.1 \ --http.port 8545 \ --http.api eth,net,web3 \ --port 30303 \ --maxpeers 50 ``` * `--mine` enables block production * `--nodekey` specifies the validator’s operational key (also used as etherbase in Anzeon) * RPC is bound to localhost for security * Validators must use `--syncmode full` ### Public RPC Node ```bash theme={null} gstable --mainnet \ --syncmode snap \ --datadir /data/gstable \ --cache 2048 \ --http \ --http.addr 0.0.0.0 \ --http.port 8545 \ --http.api eth,net,web3 \ --http.corsdomain "*" \ --http.vhosts "*" \ --ws \ --ws.addr 0.0.0.0 \ --ws.port 8546 \ --ws.api eth,net,web3 \ --maxpeers 100 ``` * `--syncmode snap` allowed since this is not a validator * Bound to `0.0.0.0` for public access * Only safe APIs exposed (`eth`, `net`, `web3`) ### Development Node ```bash theme={null} gstable --dev \ --dev.period 1 \ --datadir /tmp/gstable-dev \ --http \ --http.addr 127.0.0.1 \ --http.api eth,net,web3,personal,debug,admin \ --allow-insecure-unlock ``` * `--dev` creates a temporary development network with pre-funded accounts * `--dev.period 1` produces a block every second * All APIs enabled for debugging * `--allow-insecure-unlock` allows HTTP account unlocking (development only) ### Archive Node ```bash theme={null} gstable --mainnet \ --syncmode full \ --gcmode archive \ --datadir /data/gstable-archive \ --cache 8192 \ --http \ --http.addr 127.0.0.1 \ --http.api eth,net,web3,debug,trace \ --maxpeers 50 ``` * `--gcmode archive` disables state pruning * `debug` and `trace` APIs are useful for analysis * Requires significant disk space (multiple TBs) ## Configuration Files While command-line flags are the primary configuration method, TOML configuration files are useful for managing complex deployments. ### TOML Configuration Files To export the current node configuration to a TOML file: ```bash theme={null} gstable dumpconfig > config.toml ``` Edit the generated file and load it with the `--config` flag: ```bash theme={null} gstable --config config.toml ``` Example TOML sections: ```toml theme={null} [Eth] NetworkId = 8282 SyncMode = "full" NoPruning = false [Eth.Miner] GasCeil = 105000000 [Node] DataDir = "/data/gstable" HTTPHost = "0.0.0.0" HTTPPort = 8545 HTTPModules = ["eth", "net", "web3"] WSHost = "0.0.0.0" WSPort = 8546 WSModules = ["eth", "net", "web3"] IPCPath = "gstable.ipc" [Node.P2P] MaxPeers = 100 ListenAddr = ":30303" StaticNodes = [] TrustedNodes = [] ``` **Configuration precedence**: Command-line flags > TOML file settings > Defaults ### Genesis Configuration For custom networks, the genesis configuration is provided as JSON and loaded using the `gstable init` command: ```bash theme={null} gstable init /path/to/genesis.json --datadir /path/to/datadir ``` For detailed information on the genesis file structure, see [Genesis Setup and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization). # Genesis Configuration and Network Initialization Source: https://docs.stablenet.network/en/getting-started/2.3-genesis-setup-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://@: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. # Getting Started Source: https://docs.stablenet.network/en/getting-started/index ## Purpose and Scope This document guides you through installing StableNet, configuring a node, and performing the initial startup. It covers the essential steps required to bring a node into an operational state, from system requirements to first execution. For more detailed information, refer to the following documents: * [Core Architecture](/en/core-architecture/index) * [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol) * [Installation and Build](/en/getting-started/2.1-installation-and-building) * [Node Configuration](/en/getting-started/2.2-node-configuration) * [Genesis Configuration and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization) ## Prerequisites StableNet is built with Go and requires the following: | Requirement | Minimum Version | Notes | | ----------- | --------------- | ------------------------------------------------------------ | | Go | 1.22.x | Required for source builds | | Disk | 200+ GB | Based on Full Sync; varies by network | | RAM | 8 GB | 16 GB recommended for validator nodes | | CPU | 2 cores | 4 cores or more recommended | | Network | 25 Mbps+ | Required for P2P sync; 50 Mbps+ recommended for initial sync | ## Installation Overview StableNet can be installed in multiple ways: ### Build from Source The primary build method uses the CI build script: ```bash theme={null} git clone https://github.com/stable-net/go-stablenet cd go-stablenet # Build the gstable binary go run build/ci.go install ./cmd/gstable # The binary will be located at build/bin/gstable ./build/bin/gstable version ``` The build system supports cross-compilation and static linking via the `build/ci.go` script, handling all build flags and dependencies. ### Use Release Binaries Prebuilt binaries can be downloaded from [GitHub Releases](https://github.com/stable-net/go-stablenet/releases): ```bash theme={null} # Download from the release page tar -xzf gstable-linux-amd64-.tar.gz # Add the binary to PATH sudo mv gstable /usr/local/bin/ # Verify installation gstable version ``` For platform-specific installation instructions, see [Installation and Build](/en/getting-started/2.1-installation-and-building). ## Network Selection StableNet supports multiple network configurations: | Network | Flag | ChainID | | ------- | -------------------------------------------------- | ------------ | | Mainnet | `--mainnet` | 8282 | | Testnet | `--testnet` | 8283 | | Custom | `--genesis /path/to/genesis.json --networkid ` | User-defined | For custom network setup, see [Genesis Configuration and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization). ## Basic Configuration Nodes can be configured using command-line flags and TOML configuration files. For key options such as `--datadir`, `--http`, and `--port`, see [Node Configuration](/en/getting-started/2.2-node-configuration). ## Running Your First Node 1. **Data Initialization**: On first launch, if no network flag is specified, the node initializes as Mainnet by default. For custom networks, see [Genesis Configuration and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization). 2. **Start the Node**: By default, the node starts as a non-consensus participant. To participate in consensus as a validator, specify the `--mine` option. For commands and flags, see [Node Configuration](/en/getting-started/2.2-node-configuration). 3. **Verify Operation**: Methods for checking RPC access, the JavaScript console, and peer connections are described in [Node Configuration](/en/getting-started/2.2-node-configuration). If issues occur, refer to [Node Configuration](/en/getting-started/2.2-node-configuration) and [Node Monitoring and Maintenance](/en/operations-guide/11.3-node-monitoring-and-maintenance). ## Next Steps After successfully running your first node: * [Node Configuration](/en/getting-started/2.2-node-configuration) — production configuration options * [Validator Operations](/en/operations-guide/11.2-validator-operations) — operating validator nodes * [Genesis Configuration and Network Initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization) — creating custom networks * [Node Monitoring and Maintenance](/en/operations-guide/11.3-node-monitoring-and-maintenance) — monitoring and logging * [Core Architecture](/en/core-architecture/index) — overview of StableNet components * [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol) — detailed consensus protocol # System Contracts Overview Source: https://docs.stablenet.network/en/governance-system/5.1-system-contracts-overview ## Purpose and Scope This page provides an overview of the five system contracts in StableNet, their fixed addresses, and the genesis deployment and initialization model.\ These contracts implement the core governance mechanisms for validator management, mint/burn authorization, and ERC-20 compatibility for the native stablecoin. For detailed documentation of each contract, refer to the following pages: * [NativeCoinAdapter Contract](/en/governance-system/5.2-nativecoinadapter-contract) – ERC-20 wrapper for native balances * [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)) – Validator set management * [Minting Governance (GovMasterMinter and GovMinter)](/en/governance-system/5.4-minting-governance-\(govmasterminter-and-govminter\)) – Minter registration and proposals * [Council Governance (GovCouncil)](/en/governance-system/5.5-council-governance-\(govcouncil\)) – Blacklist and Authorized account policies * [Mint and Burn Protocol](/en/governance-system/5.6-mint-and-burn-protocol) – End-to-end mint/burn workflow ## The Five System Contracts StableNet deploys five system contracts directly at predefined addresses during genesis block creation.\ These contracts are deployed without owners and do not use common upgrade patterns (such as proxies); they can be replaced **only via hard forks**. | Contract Name | Address | Primary Purpose | Version | | --------------------- | -------------------------------------------- | -------------------------------------------------------------------------------- | ------- | | **NativeCoinAdapter** | `0x0000000000000000000000000000000000001000` | ERC-20 wrapper for native stablecoin balances; entry point for mint/burn | v1 | | **GovValidator** | `0x0000000000000000000000000000000000001001` | Validator set management, BLS key registration, gas tip (`gasTip`) governance | v1 | | **GovMasterMinter** | `0x0000000000000000000000000000000000001002` | Registry of approved minters and global maximum mint allowance caps | v1 | | **GovMinter** | `0x0000000000000000000000000000000000001003` | Creation, voting, and execution of proof-based mint/burn proposals | v1 | | **GovCouncil** | `0x0000000000000000000000000000000000001004` | Management of blacklists and Authorized account sets; AccountManager integration | v1 | ## Contract Deployment Architecture System contracts are deployed during genesis block creation via a state transition mechanism that writes both bytecode and initialized storage directly into the genesis state. ## Genesis Configuration Structure System contracts are defined in the genesis file under the `config.anzeon.systemContracts` section, where the address, version, and initialization parameters for each contract are specified. ## Versioning and Bytecode Storage Contract bytecode is embedded into the node binary at compile time and indexed by contract name and version.\ The `SystemContractCodes` map provides version-controlled access to the deployable bytecode. The version validation process ensures that only supported contract versions can be deployed. ## Contract Initialization Parameters Each system contract requires specific initialization parameters to construct its storage state at genesis.\ These parameters are interpreted and validated by the contract-specific initialization functions. ## Contract Dependency Graph System contracts form a dependency hierarchy in which some contracts reference others.\ Understanding these dependencies is essential for correct configuration. ## Storage Initialization Process Each contract’s initialization function writes values to predefined storage slots.\ Initialization follows Solidity storage layout rules to compute slot addresses for mappings and dynamic arrays. ## Contract Upgrade Mechanism System contracts are deployed without owners and cannot be upgraded through standard contract mechanisms.\ The only supported upgrade path is via a hard fork. # NativeCoinAdapter Contract Source: https://docs.stablenet.network/en/governance-system/5.2-nativecoinadapter-contract ## Purpose and Scope This document provides technical documentation for the NativeCoinAdapter system contract in StableNet.\ NativeCoinAdapter exposes the chain’s native coin (used for gas fees) through the standard ERC-20 interface, enabling seamless integration with existing DApps and services that expect ERC-20 tokens. For an overview of the governance system and mint/burn control mechanisms, see [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview).\ For validator management and consensus details, refer to the [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol). ## Contract Deployment and Identification NativeCoinAdapter is a genesis system contract deployed at a fixed address and initialized during chain bootstrap.\ Unlike user-deployed contracts, it has no owner and can only be upgraded via a hard fork, preserving decentralization guarantees. | Property | Value | | ------------------- | -------------------------------------------- | | Contract Address | `0x0000000000000000000000000000000000001000` | | Deployment Method | Genesis injection via `InjectContracts` | | Upgrade Mechanism | Hard fork only | | Owner | None (system contract) | | Standard Compliance | ERC20, FiatTokenV2\_2 | The contract is initialized during genesis block creation with parameters including currency name, symbol, decimals, and the initial master minter configuration. ## Architecture and Design Principles ### Dual-Nature Balance Model NativeCoinAdapter implements a unique dual-nature balance model with the following properties: 1. **No Redundant Storage**: The adapter does not store balances in its own storage slots. All balance queries directly reference the native balance field in account state. 2. **Direct State Mutation**: Transfers executed via the adapter modify the same native balances that are affected by gas fee payments, ensuring consistency across all balance mutation paths. 3. **Allowance Isolation**: Only allowance mappings (used by `approve()` / `transferFrom()`) are stored in the contract storage trie. 4. **Unified Balance View**: `NativeCoinAdapter.balanceOf(address)` always returns exactly the same value as the account’s native balance used for gas accounting. ## Storage Layout and State Management ### Contract Storage Slots NativeCoinAdapter maintains minimal storage, tracking only data that cannot be derived from native account state: | Slot Type | Purpose | Storage Location | | ----------------- | --------------------------------------------------- | --------------------- | | Allowances | `mapping(address => mapping(address => uint256))` | Contract storage trie | | Minter Allowances | Per-minter mint/burn limits | Contract storage trie | | Metadata | Currency name, symbol, decimals | Contract storage trie | | Balances | **NOT STORED** – directly references native balance | Account state | By limiting storage to mappings that cannot be inferred from native state, the adapter minimizes storage overhead while preserving full ERC20 functionality. ## Core Transfer Operations ### Direct Transfer Flow Transfers via NativeCoinAdapter are processed in the following order: 1. **Blacklist Validation**: Check blacklist flags for both sender and recipient in the account Extra field. 2. **Balance Check**: Read the sender’s native balance. 3. **Balance Mutation**: Atomically update the native balances of both accounts. 4. **Journaling**: All state changes are journaled to support reversion. 5. **Event Emission**: Emit the `Transfer(from, to, amount)` event. ### Allowance-Based transferFrom `transferFrom()` follows the standard ERC20 delegated transfer pattern: 1. Read the allowance from contract storage. 2. Decrease the allowance if sufficient. 3. Perform the actual balance transfer by directly mutating native balances. 4. Emit a `Transfer` event. ## Allowance System Implementation Allowances cannot be derived from native state and therefore require dedicated contract storage. | Operation | Storage Access | State Modification | | ------------------- | -------------- | ----------------------------- | | `approve` | WRITE | Set allowance | | `increaseAllowance` | READ → WRITE | Increase allowance | | `decreaseAllowance` | READ → WRITE | Decrease allowance | | `transferFrom` | READ (+ WRITE) | Deduct allowance and transfer | | `allowance` | READ | Read-only | Allowance storage follows the Solidity nested mapping layout and uses keccak256-based slot computation. ## Minting and Burning Integration NativeCoinAdapter is the **sole minting and burning interface** for the native coin.\ These operations are restricted to addresses approved by GovMinter and GovMasterMinter. ### Mint/Burn Constraints 1. All minting and burning must occur via `mint()` / `burn()`. 2. Only approved minters may call these functions. 3. Per-minter maximum allowances are enforced. 4. Standard `Transfer` events and dedicated `Mint` / `Burn` events are emitted. 5. Native balances are modified directly. ## Event Emission and Auditability NativeCoinAdapter emits events for all native coin movements, providing full traceability. | Event | Trigger | | ---------- | -------------------- | | `Transfer` | Any balance movement | | `Approval` | Allowance change | | `Mint` | Minting | | `Burn` | Burning | This ensures that all base coin movements can be indexed, audited, and displayed in frontends. ## Blacklist and Authorization Flags NativeCoinAdapter integrates with flags stored in the account Extra field. | Account State | Extra Flag | Effect | | ---------------- | -------------------- | -------------------------------------- | | Blacklisted | `0x8000000000000000` | Transfers and receipts blocked | | Authorized | `0x4000000000000000` | Exempt from governance-enforced gasTip | | Normal (default) | `0x0` | Governance gasTip enforcement applies | ## ERC20 and FiatToken Extension Compliance NativeCoinAdapter implements both the standard ERC20 interface and the FiatTokenV2\_2 extensions, ensuring compatibility with existing USDC-based stablecoin infrastructure. ## StateDB Integration NativeCoinAdapter integrates directly with StateDB: 1. Balance reads → direct native balance access 2. Balance updates → `AddBalance` / `SubBalance` 3. Journaling → supports transaction reversion 4. Flag checks → Extra field access 5. Event logging → included in receipts ### StateObject Structure ```text theme={null} stateObject { address data { Nonce Balance // native balance CodeHash Root Extra // blacklist / authorized flags } trie // contract storage } ``` ## Genesis Initialization NativeCoinAdapter is initialized at genesis with the following parameters: ```json theme={null} { "currency": "KRW", "decimals": "18", "name": "WKRC", "symbol": "WKRC", "masterMinter": "0x...1002", "minterAllowed": "10000000000000000000000000000", "minters": "0x...1003" } ``` Initialization results: * Contract exists at genesis block * Initial minters and allowances configured * Token metadata finalized * Any future changes require a hard fork ## Summary NativeCoinAdapter achieves the following: 1. **Zero-storage-overhead ERC20** 2. **Event-level traceability for all native coin movements** 3. **Governance-controlled minting and burning** 4. **Full compatibility with existing stablecoin ecosystems** 5. **Protocol-level security and policy enforcement** Through this design, StableNet naturally exposes its native gas token as a standard ERC20 stablecoin. # Validator Governance (GovValidator) Source: https://docs.stablenet.network/en/governance-system/5.3-validator-governance-(govvalidator) ## Purpose and Scope This document describes the **GovValidator** system contract, which manages validator set governance on the StableNet blockchain.\ GovValidator is responsible for validator registration and removal, BLS key management, and network-wide gas tip policy. For an overview of all system contracts, see [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview).\ For minting governance, refer to [Minting Governance (GovMasterMinter and GovMinter)](/en/governance-system/5.4-minting-governance-\(govmasterminter-and-govminter\)). ## Overview GovValidator (`0x0000000000000000000000000000000000001001`) is a genesis-deployed system contract that implements on-chain governance for the validator set.\ Unlike traditional staking-based validator systems, StableNet uses a **Proof-of-Authority (PoA)** model in which validators are managed through collective voting by existing governance members. Key responsibilities: * **Validator set management**: Registering and removing validators through governance voting * **Key management**: Managing operator keys, validator keys, and BLS public keys for each validator * **Gas tip policy**: Setting and enforcing a mandatory network-wide gas tip * **Quorum-based decisions**: All governance actions require member votes that meet a quorum threshold ## Architecture Overview The GovValidator contract interacts with the WBFT consensus engine to apply validator set changes and gas tip policies. ## Validator Key Structure StableNet validators use three types of keys: **Operator key**, **Validator key**, and **BLS key**.\ For detailed roles, generation/derivation procedures, and genesis configuration examples, see [Validator Operations](/en/operations-guide/11.2-validator-operations). ## Genesis Configuration GovValidator is initialized at genesis with the following parameters: | Parameter | Type | Description | | --------------- | ----------- | ----------------------------------------------------------- | | `members` | `address[]` | List of operator key addresses | | `validators` | `address[]` | List of validator key addresses | | `blsPublicKeys` | `bytes[]` | List of BLS public keys | | `quorum` | `uint256` | Minimum number of approvals required for governance actions | | `expiry` | `uint256` | Proposal expiration time (seconds) | | `memberVersion` | `uint256` | Version of the member/validator set | | `gasTip` | `uint256` | Initial network-wide gas tip | **Important:**\ `init.validators` / `init.blsPublicKeys` are used **only for the first epoch**.\ From the second epoch onward, the values stored in the GovValidator contract are authoritative. ## Validator Governance Flow ### Adding a Validator Validator addition follows these steps: 1. A governance member creates a proposal containing the new validator information 2. Other members cast votes 3. Once approvals reach the quorum, the proposal is executed 4. `memberVersion` is incremented 5. The new validator becomes active from the next epoch ### Removing a Validator Validator removal follows the same quorum-based proposal, voting, and execution flow.\ Removed validators stop participating in consensus and block signing starting from the next epoch. ## Gas Tip Policy Management GovValidator manages the **mandatory gas tip** applied network-wide.\ Normal accounts must comply with this value, while Authorized accounts are allowed to specify a custom tip. ### Gas Tip Lifecycle 1. A governance member proposes `setGasTip(newTip)` 2. Quorum approval is reached 3. The `gasTip` value in contract storage is updated 4. The new value is reflected in the next block header 5. Workers and the TxPool synchronize to the new minimum value ### Application During Transaction Selection | Transaction Type | Gas Tip Rule | | ------------------ | ---------------------------- | | Normal Account | Governance `gasTip` enforced | | Authorized Account | User-defined tip allowed | | Below Minimum | Rejected by TxPool | ## Integration with WBFT Consensus GovValidator supplies the active validator set to the WBFT consensus engine at every epoch block. At epoch transition: 1. The consensus engine detects the epoch block 2. Reads `validators[]` and `blsPublicKeys[]` from GovValidator storage 3. Constructs `EpochInfo` 4. Encodes it into the block header Extra data 5. Activates the new set in the next epoch ## Contract Storage Layout | Variable | Type | Description | | --------------- | ----------- | ------------------------- | | `members` | `address[]` | Governance operator keys | | `validators` | `address[]` | Validator keys | | `blsPublicKeys` | `bytes[]` | BLS public keys | | `memberVersion` | `uint256` | Set change version | | `quorum` | `uint256` | Minimum approval count | | `expiry` | `uint256` | Proposal expiration time | | `gasTip` | `uint256` | Mandatory network gas tip | ## Governance Member Operations | Operation | Effect | | ---------------- | ----------------------------------------------- | | Add Validator | Add a validator starting from the next epoch | | Remove Validator | Remove a validator starting from the next epoch | | Set Gas Tip | Change the network minimum priority fee | | Query Validators | Retrieve the current validator list | | Query Gas Tip | Retrieve the current gas tip | All state-changing operations are executed exclusively through quorum-based voting. ## Relationship with Other Contracts GovValidator is part of the StableNet governance system,\ with clearly separated responsibilities from minting policy (GovMasterMinter/GovMinter) and account policy (GovCouncil). This separation allows consensus and validator operations to be managed independently from monetary policy. # Minting Governance (GovMasterMinter and GovMinter) Source: https://docs.stablenet.network/en/governance-system/5.4-minting-governance-(govmasterminter-and-govminter) ## Purpose and Scope StableNet implements a two-layer governance system for minting and burning of the native stablecoin.\ This architecture clearly separates **authorization** (who is allowed to be a minter) from **execution** (who can actually perform mint/burn operations): * **GovMasterMinter**: Approves and manages minter entities * **GovMinter**: Executes mint and burn operations through collective voting This document explains the architecture, responsibilities, storage interactions, and execution flows between the two governance contracts.\ For the operational protocol followed by minters when performing mint/burn operations, see [Mint and Burn Protocol](/en/governance-system/5.6-mint-and-burn-protocol).\ For how minted tokens are represented on-chain, see [NativeCoinAdapter Contract](/en/governance-system/5.2-nativecoinadapter-contract).\ For an overview of all system contracts, see [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview). ## Two-Layer Minting Architecture Minting governance uses a **hierarchical authorization model** to balance flexibility and security.\ This architecture is implemented through two fixed-address system contracts and storage slots in `NativeCoinAdapter`. **Key design principles**: | Layer | Contract Address | Members | Operations | | ------------- | ---------------- | --------------------- | --------------------------------------------- | | Authorization | `0x0000...1002` | Master minter members | `configureMinter()`, `removeMinter()` | | Execution | `0x0000...1003` | Minter members | `mint()`, `burn()` (quorum approval required) | This separation is enforced by access control modifiers in the `NativeCoinAdapter` contract: * `onlyMasterMinter`: checks `msg.sender == masterMinter` (slot 0x0) * `onlyMinters`: checks `_minters[msg.sender] == true` (slot 0x1) * Allowance check: `_minterAllowed[msg.sender] >= amount` (slot 0x2) ## GovMasterMinter Contract ### Contract Identification and Deployment GovMasterMinter is deployed as a system contract at genesis: * **Address**: `0x0000000000000000000000000000000000001002` * **Deployment method**: Direct injection into the genesis block (no owner) * **Upgrade mechanism**: Replacement only via hard fork * **Version**: Specified in the genesis configuration (e.g. `"v1"`) ### Responsibilities GovMasterMinter acts as the **authorization layer** for minting operations: 1. **Minter registration**: Approves specific addresses as minters 2. **Minter removal**: Revokes existing minter permissions 3. **Allowance management**: Sets per-minter mint/burn limits 4. **Extensibility**: Enables approval of various minter types such as bridge-based or system minters This structure generalizes the `masterMinter` concept used in Circle’s FiatToken contracts into an on-chain governance model. ### Genesis Parameters GovMasterMinter is initialized at genesis via `params.ChainConfig.Anzeon.SystemContracts.GovMasterMinter`: | Parameter | Type | Purpose | Example Value | Genesis Location | | -------------------- | ------------ | ---------------------------------- | --------------------------------- | ----------------------------------------------------- | | `members` | address list | Master minter governance members | `"0xaa5f...4697"` | `params.GovMasterMinter.Params["members"]` | | `quorum` | uint | Minimum approvals required | `"1"` | `params.GovMasterMinter.Params["quorum"]` | | `expiry` | uint | Proposal expiration time (seconds) | `"604800"` | `params.GovMasterMinter.Params["expiry"]` | | `memberVersion` | uint | Membership version | `"1"` | `params.GovMasterMinter.Params["memberVersion"]` | | `fiatToken` | address | NativeCoinAdapter address | `"0x0000...1000"` | `params.GovMasterMinter.Params["fiatToken"]` | | `minters` | address list | Initially approved minters | `"0x0000...1003"` | `params.GovMasterMinter.Params["minters"]` | | `maxMinterAllowance` | uint256 | Maximum allowance per minter | `"10000000000000000000000000000"` | `params.GovMasterMinter.Params["maxMinterAllowance"]` | | `maxProposals` | uint | Maximum concurrent proposals | `"3"` | `params.GovMasterMinter.Params["maxProposals"]` | ### Initialization Sequence 1. `core.SetupGenesisBlock()` calls `core.InjectContracts()` 2. `InjectContracts()` calls `systemcontracts.InjectGovMasterMinter()` 3. `InjectGovMasterMinter()` directly initializes `NativeCoinAdapter` storage: * Slot 0x0: `masterMinter = 0x0000...1002` * Slot 0x1: `_minters[address] = true` for each approved minter * Slot 0x2: `_minterAllowed[address] = maxMinterAllowance` for each minter ### Storage Layout GovMasterMinter does not maintain its own storage.\ Instead, it manages state via storage slots in `NativeCoinAdapter`, defined as constants in `systemcontracts/coin_adapter.go`: ``` SLOT_COIN_ADAPTER_MASTER_MINTER = "0x0" // address masterMinter SLOT_COIN_ADAPTER_MINTERS = "0x1" // mapping(address => bool) _minters SLOT_COIN_ADAPTER_MINTER_ALLOWED = "0x2" // mapping(address => uint256) _minterAllowed ``` **Storage access patterns**: | Operation | Slot | Key Derivation | Value Type | | | | ------------------ | ---- | ------------------- | ---------- | ------- | --------- | | Read master minter | 0x0 | Direct slot access | `address` | | | | Check minter | 0x1 | \`keccak256(address | | slot)\` | `bool` | | Read allowance | 0x2 | \`keccak256(address | | slot)\` | `uint256` | Mapping slot calculation follows standard Solidity storage layout rules. ### Interaction with NativeCoinAdapter GovMasterMinter can only call **permission management functions** on `NativeCoinAdapter`, protected by the `onlyMasterMinter` modifier. **Function signatures**: * `configureMinter(address minter, uint256 minterAllowedAmount) external onlyMasterMinter` * `removeMinter(address minter) external onlyMasterMinter` **Access control flow**: 1. A governance proposal reaches quorum and enters execution 2. The transaction is sent from the GovMasterMinter contract 3. `NativeCoinAdapter` compares `msg.sender` with `masterMinter` in slot 0x0 4. On match, slots 0x1 and 0x2 are updated and events are emitted ## GovMinter Contract ### Contract Identification and Deployment GovMinter is deployed as a system contract at genesis: * **Address**: `0x0000000000000000000000000000000000001003` * **Deployment method**: Direct injection into the genesis block * **Upgrade mechanism**: Hard fork only * **Version**: Specified in the genesis configuration ### Responsibilities GovMinter acts as the **execution layer** for minting operations: 1. **Mint execution**: Issues native stablecoins 2. **Burn execution**: Burns native stablecoins 3. **Oracle role**: Verifies off-chain fiat deposits and withdrawals 4. **Member governance**: Manages its own member set 5. **Multi-approval coordination**: Collects quorum approvals for mint/burn proposals No single member can ever mint or burn unilaterally. ### Genesis Parameters GovMinter is configured at genesis via `params.ChainConfig.Anzeon.SystemContracts.GovMinter`: | Parameter | Type | Purpose | Example Value | Genesis Location | | --------------- | ------------ | ------------------------------- | ----------------- | ------------------------------------------ | | `members` | address list | Minter operator members | `"0xaa5f...4697"` | `params.GovMinter.Params["members"]` | | `quorum` | uint | Minimum approvals for mint/burn | `"1"` | `params.GovMinter.Params["quorum"]` | | `expiry` | uint | Proposal expiration time | `"604800"` | `params.GovMinter.Params["expiry"]` | | `memberVersion` | uint | Member version | `"1"` | `params.GovMinter.Params["memberVersion"]` | | `fiatToken` | address | NativeCoinAdapter address | `"0x0000...1000"` | `params.GovMinter.Params["fiatToken"]` | | `maxProposals` | uint | Maximum concurrent proposals | `"3"` | `params.GovMinter.Params["maxProposals"]` | ### Initialization Prerequisites GovMinter must be **approved as a minter** before it can operate: 1. GovMinter address must be included in GovMasterMinter’s `minters` list 2. GovMasterMinter must assign an allowance to GovMinter 3. During genesis, `InjectGovMasterMinter()` writes this into NativeCoinAdapter slots 0x1 and 0x2 If these conditions are not met, all `mint()` / `burn()` calls will be rejected at the `onlyMinters` check. ### Mint and Burn Workflow Before any balance change, mint and burn operations must pass the following validation chain: **Access control validation chain**: 1. **Minter approval check**: `_minters[msg.sender] == true` 2. **Allowance check**: `_minterAllowed[msg.sender] >= amount` 3. **Balance update**: Direct native balance modification via StateDB 4. **Allowance deduction**: `_minterAllowed[msg.sender] -= amount` **Function signatures**: * `mint(address to, uint256 amount) external onlyMinters` * `burn(uint256 amount) external onlyMinters` ### Self-Governance of Members GovMinter can manage its own membership.\ However, if GovMasterMinter revokes GovMinter’s minter approval, GovMinter’s entire execution authority is immediately disabled. ## Governance Mechanism GovMasterMinter and GovMinter share a common GovBase pattern. ### Voting Process **Proposal lifecycle**: 1. **Creation**: A member creates a proposal 2. **Voting**: Members vote to approve or reject 3. **Quorum reached**: Approvals meet or exceed `quorum` 4. **Execution**: Executed before expiry 5. **Expiration**: Automatically discarded if quorum is not reached ### Quorum Requirements | Network Size | Recommended Quorum | Rationale | | ------------ | ------------------ | ----------------------- | | 1 member | 1 | Development and testing | | 2–4 members | 2 | Simple majority | | 5+ members | ⌈(n/2) + 1⌉ | BFT-oriented safety | In production environments, a majority or ≥2/3 quorum is recommended. ### Member Versioning `memberVersion` is incremented on membership changes and prevents execution of proposals created under older versions, mitigating replay attacks. ### Proposal Limits `maxProposals` limits the number of concurrent proposals to prevent governance-level DoS attacks. ## Integration with System Contracts | Relationship | Storage/Code Location | Purpose | | ------------------------------ | ---------------------------- | -------------------------- | | GovMasterMinter → Slot 0x0 | `statedb.GetState(nca, 0x0)` | Master minter verification | | GovMinter → Slot 0x1 | `_minters[address]` | Minter approval check | | GovMinter → Slot 0x2 | `_minterAllowed[address]` | Allowance check | | NativeCoinAdapter → Precompile | Native balance update | Balance modification | | Genesis → Storage | `InjectGovMasterMinter()` | Initial state setup | ## Summary The two-layer minting governance architecture guarantees: | Feature | Benefit | | ----------------------------------------- | ------------------------------- | | Separation of authorization and execution | Prevents concentration of power | | Multi-approval | Blocks unilateral abuse | | Extensibility | Supports diverse minter types | | Transparency | All actions recorded on-chain | | Security | Allowance-based issuance limits | This design enables StableNet to maintain a **1:1 fiat peg** while achieving protocol-level decentralization and strong operational control. # Council Governance (GovCouncil) Source: https://docs.stablenet.network/en/governance-system/5.5-council-governance-(govcouncil) ## Purpose and Scope This document describes the role of the `GovCouncil` system contract within the StableNet governance architecture.\ GovCouncil manages the network-wide **blacklist** and **authorized account set**, and enforces account-level restrictions consistently by integrating with the on-chain `AccountManager` native precompile. For an overview of all system contracts and their addresses, see [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview).\ For how blacklist and authorized accounts affect transaction processing and state transitions, refer to: * [State Transitions and Gas](/en/transaction-processing/6.2-state-transitions-and-gas) * [Fee Delegation](/en/transaction-processing/6.5-fee-delegation) ## Contract Overview GovCouncil is deployed at the following fixed address: * **GovCouncil**: `0x0000000000000000000000000000000000001004` Like other governance contracts (`GovValidator`, `GovMasterMinter`, `GovMinter`), GovCouncil inherits from the common base contract `GovBase`, and extends it with Council-specific state and actions. Its responsibilities include: * Managing the network-wide **blacklist** set * Managing the **authorized account** set for privileged or priority operations * Bridging these sets to the `AccountManager` native precompile, enabling fast and consistent checks during EVM execution and precompile handling In summary: * **GovBase** provides membership management, quorum calculation, proposal lifecycle, and execution-safety logic. * **GovCouncil** defines domain-specific governance actions for modifying blacklist and authorized account sets. * **AccountManager** and the EVM query these sets to enforce Anzeon-specific policies during transaction processing. ## Governance Responsibilities The primary responsibilities of GovCouncil are: * Adding or removing accounts from the **blacklist** when they must be restricted from sending or receiving transactions * Defining and updating the set of **authorized accounts** allowed to perform privileged management actions or priority transactions * Ensuring that all such changes are applied **only** through the quorum-based proposal and voting model provided by `GovBase` ### Example Governance Actions While concrete Solidity action types are defined in the GovCouncil contract, conceptually they include: * **Add to blacklist**: Add one or more addresses to the blacklist set * **Remove from blacklist**: Remove existing addresses from the blacklist set * **Add authorized account**: Grant authorized status to a specific account * **Remove authorized account**: Revoke authorized status from an account All actions are created as proposals, and no on-chain state change can occur without quorum approval by Council members. ## Storage Model GovCouncil extends `GovBase` and defines additional storage slots for Council-specific state.\ The storage layout is implemented in `systemcontracts/gov_council.go` and is conceptually organized as follows: * Slots `0x00–0x31`: Common `GovBase` storage\ (member list, quorum, proposal data, execution state, reentrancy protection, etc.) * Slots `0x32–0x35`: GovCouncil-specific storage * `0x32`: `_currentBlacklist` values slot (AddressSet) * `0x33`: `_currentBlacklist` positions mapping slot * `0x34`: `_currentAuthorizedAccounts` values slot (AddressSet) * `0x35`: `_currentAuthorizedAccounts` positions mapping slot * Slot `0x36`: `__accountManager` address (`AccountManager` native precompile) ### AddressSet Encoding Both `blacklist` and `authorizedAccounts` use the **AddressSet** structure defined in the shared `AddressSetLib` library. * Each AddressSet consists of **two slots**: * **values slot**: Stores the array length at the base slot; actual elements are stored at `keccak256(valuesSlot) + index` * **positions slot**: Stores a mapping `address → index + 1`; a value of `0` means the address is not in the set This structure enables: * Near O(1) membership checks for `IsBlacklisted` and `IsAuthorizedAccount` * Full enumeration via `GetAllBlacklisted` and `GetAllAuthorizedAccounts` * Safe initialization with zero-address checks and duplicate elimination ### Genesis Initialization Parameters GovCouncil is initialized at genesis via the `initializeGovCouncil` logic with the following parameters: | Parameter | Type | Description | | -------------------- | ------------ | -------------------------------------------------- | | `members` | address list | Council governance members (GovBase) | | `quorum` | uint | Minimum approvals required for execution (GovBase) | | `expiry` | uint | Proposal expiration time in seconds (GovBase) | | `memberVersion` | uint | Member list version (GovBase) | | `blacklist` | address list | Initial blacklist addresses | | `authorizedAccounts` | address list | Initial authorized account addresses | During initialization, the following steps are performed: * Validation against the zero address * Duplicate address removal * Encoding of `blacklist` and `authorizedAccounts` into AddressSet form in slots `0x32–0x35` * Writing the `AccountManager` precompile address into slot `0x36` to link the account-policy layer ## Integration with AccountManager and the EVM GovCouncil does not directly check blacklist or authorization status during transaction execution.\ Instead, it acts as the **single source of truth** for these sets. Other components query GovCouncil state via helper functions defined in `gov_council.go`: * `IsBlacklisted(govCouncilAddress, state, addr)` * Returns `true` if the address is in the blacklist * `GetBlacklistCount`, `GetBlacklistedAddress`, `GetAllBlacklisted` * Used for enumeration and monitoring * `IsAuthorizedAccount(govCouncilAddress, state, addr)` * Returns `true` if the address is an authorized account * `GetAuthorizedAccountCount`, `GetAuthorizedAccountAddress`, `GetAllAuthorizedAccounts` * Used to enumerate authorized accounts The `AccountManager` precompile and the EVM use this information to enforce policies such as: * Rejecting transactions where the sender is blacklisted * Blocking transfers or calls targeting blacklisted accounts * Restricting certain management functions or special transactions to authorized accounts only ## Proposal and Voting Model GovCouncil inherits the **proposal lifecycle and quorum-based voting model** directly from `GovBase`.\ As a result, its operational pattern is identical to other Gov\* contracts. * **Members**: The set of Council members who can create proposals and vote * **Quorum**: Minimum number of approvals required before execution * **Expiry**: Proposal validity period; expired proposals cannot be executed * **Member Versioning**: `memberVersion` increments on membership changes, invalidating older proposals The conceptual proposal flow is as follows: 1. A member creates a proposal to modify the blacklist or authorized account set. 2. Other members review the proposal and vote to approve or reject it. 3. Once approvals reach quorum and the proposal has not expired, it becomes executable. 4. Upon execution, the AddressSet is updated and corresponding events are emitted. Concrete action types and events are defined in the Solidity implementation of GovCouncil,\ but the high-level behavior is consistent across all governance contracts using GovBase. ## Operational Considerations When configuring and operating GovCouncil, consider the following: * **Initial blacklist and authorized accounts** * These can be set at genesis via `systemContracts.govCouncil.params.*`. * They take effect immediately from the first block, so careful review before deployment is essential. * **Balance between quorum and member count** * A quorum that is too low may allow overly easy policy changes. * A quorum that is too high may delay emergency blacklist actions. * A balanced configuration aligned with network characteristics is required. * **Monitoring** * Off-chain services can periodically query `GetAllBlacklisted` and `GetAllAuthorizedAccounts` to track changes. * Wallets or explorers can display blacklist or authorized status on account detail pages. * **Integration with transaction processing** * During transaction validation and state transition, AccountManager or GovCouncil helpers can enforce: * Rejection of transactions from blacklisted accounts * Blocking calls targeting blacklisted accounts * Restricting specific management functions to authorized accounts Together with `GovValidator`, `GovMasterMinter`, and `GovMinter`, GovCouncil forms StableNet’s **policy layer**.\ It defines which accounts are restricted or privileged, and ensures these decisions are applied consistently across the entire network. # Mint and Burn Protocol Source: https://docs.stablenet.network/en/governance-system/5.6-mint-and-burn-protocol ## Purpose and Scope This document describes the **end-to-end protocol** for minting and burning the native stablecoin on StableNet.\ It covers off-chain coordination between minter members and financial institutions, the proof structures used to verify fiat movements, and the **GovMinter governance contract with quorum-based approval procedures**. For detailed information on the governance contracts implementing this protocol, see [Minting Governance (GovMasterMinter and GovMinter)](/en/governance-system/5.4-minting-governance-\(govmasterminter-and-govminter\)).\ For the token layer where minting and burning are actually executed, see the [NativeCoinAdapter Contract](/en/governance-system/5.2-nativecoinadapter-contract).\ The overall governance architecture is described in [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview). ## Protocol Overview The mint and burn protocol aims to issue stablecoins **backed by verifiable fiat deposits and withdrawals**.\ The protocol follows three core principles: 1. **No unilateral execution without quorum**: Mint and burn operations are executed only after a GovMinter proposal and quorum-based approval. 2. **Proof-based verification**: Every mint and burn is proposed together with a proof referencing an off-chain fiat movement. 3. **Quorum-based consensus**: Operations are executed only when the minter quorum defined at GovMinter genesis is reached. The protocol assumes cooperation among the following participants: * **Minter members**: Governance participants who verify proofs and vote on mint/burn proposals * **Collateral accounts**: Bank accounts where fiat deposits and withdrawals actually occur * **GovMinter contract**: On-chain governance contract managing mint/burn proposals and voting\ (`0x0000000000000000000000000000000000001003`) * **NativeCoinAdapter contract**: System contract that executes approved mint/burn operations by modifying native balances\ (`0x0000000000000000000000000000000000001000`) ## System Architecture The mint and burn protocol consists of three layers: **off-chain verification + on-chain consensus + native balance modification**.\ The off-chain layer verifies fiat movements, the on-chain layer validates them via collective consensus, and the execution layer updates balances and total supply consistently through the NativeCoinAdapter. ## Minting Protocol ### Minting Workflow The minting protocol follows the four-step flow below: 1. **Deposit detection**: A fiat deposit into a collateral account is detected 2. **Proof construction**: A mint proof containing deposit information is created 3. **Proposal and verification**: A proposal is submitted to GovMinter and independently verified by minters 4. **On-chain execution**: Once quorum is reached, minting is executed via the NativeCoinAdapter ### Mint Proof Structure A mint proof is a data structure that binds a token issuance request to a specific fiat deposit.\ On-chain, it is represented by the `MintProof` struct in GovMinter. | Field | Type | Description | | --------------- | ------- | ------------------------------------------------------ | | `beneficiary` | address | Address that will receive the minted tokens | | `amount` | uint256 | Amount of tokens to mint (in smallest units) | | `timestamp` | uint256 | Unix timestamp when the deposit occurred | | `depositId` | string | Unique identifier of the deposit in the banking system | | `bankReference` | string | Bank transaction reference (1:1 with deposit record) | | `memo` | string | Optional memo for internal accounting and auditing | This structure, together with GovMinter state (`usedProofHashes`, `depositIdToProposalId`, `executedDepositIds`), ensures: * **Uniqueness**: Each `depositId` can be used only once, preventing double minting * **Traceability**: On-chain issuance is linked to a specific off-chain deposit * **Timeliness**: Old proofs can be rejected based on timestamps ### Minter Responsibilities During Minting Minter members have the following responsibilities during minting: 1. **Collateral account association**: Minters must be associated with predefined collateral accounts, managed via GovMasterMinter 2. **Deposit monitoring**: Continuously monitor fiat deposits in collateral accounts off-chain 3. **Proof creation**: Generate a mint proof when a deposit is detected 4. **Proposal submission**: One minter submits a mint proposal to GovMinter\ Duplicate proposals for the same `depositId` are rejected 5. **Independent verification**: Other minters independently verify the proof: * Whether the deposit occurred * Whether the amount matches * Whether the beneficiary address is correct * Whether the deposit has already been used 6. **Approval voting**: Approve after successful verification; otherwise reject or abstain ### On-Chain Execution Once a mint proposal reaches quorum, `GovBase.executeProposal()` calls GovMinter’s `_executeMint()`, which internally issues tokens via `fiatToken.mint(beneficiary, amount)`.\ In typical networks, this `fiatToken` is the `NativeCoinAdapter`. Execution steps: 1. **Quorum check**: GovBase verifies that sufficient approvals have been collected 2. **Allowance verification**: Confirms that `fiatToken.minterAllowance(GovMinter)` is sufficient 3. **Mint execution**: Calls `fiatToken.mint(beneficiary, amount)`\ For NativeCoinAdapter, native balances are increased via the internal `ICoinManager.mint()` 4. **Proof consumption**: Records `executedDepositIds[depositId] = true` to prevent reuse 5. **Total supply update**: Increases the fiat token total supply 6. **Event emission**: Emits `Mint` and `Transfer(address(0), beneficiary, amount)` events ## Burn Protocol ### Burn Workflow The burn protocol operates as the reverse of minting.\ After tokens are burned on-chain, an equivalent amount of fiat is returned off-chain. ### Burn Proof Structure A burn proof represents a valid withdrawal request corresponding to a token burn.\ On-chain, it is represented by the `BurnProof` struct in GovMinter. | Field | Type | Description | | -------------- | ------- | -------------------------------------------------- | | `from` | address | Address holding the tokens to be burned | | `amount` | uint256 | Amount of tokens to burn | | `timestamp` | uint256 | Time when the withdrawal request was received | | `withdrawalId` | string | Unique identifier of the withdrawal request | | `referenceId` | string | External settlement system reference ID | | `memo` | string | Optional memo for internal accounting and auditing | GovMinter uses `withdrawalIdToProposalId`, `executedWithdrawalIds`, and `usedProofHashes` to ensure: * **ID uniqueness**: Each `withdrawalId` can be used only once * **User specificity**: Burns are executed for a specific `from` address * **Idempotency**: Duplicate burns for the same withdrawal request are prevented ### Minter Responsibilities During Burning 1. **Receive withdrawal request** 2. **Generate withdrawal ID** 3. **Share off-chain** 4. **Create burn proof** 5. **Submit proposal and escrow**: Call `proposeBurn{value: amount}` to escrow the same amount of native coin 6. **Independent verification** 7. **Approval voting** 8. **Fiat return** ### On-Chain Burn Execution When quorum is reached, `GovBase.executeProposal()` calls GovMinter’s `_safeBurn()`. Execution steps: 1. **Quorum verification** 2. **Emergency pause check** 3. **Escrow balance deduction** 4. **Burn execution**: `fiatToken.burn(amount)` 5. **Withdrawal ID consumption** 6. **Event emission** ## Quorum Requirements and Governance ### Quorum Configuration The quorum required for mint and burn operations is set via GovMinter genesis parameters. ``` systemContracts.govMinter.params: - members: "comma-separated list of minter addresses" - quorum: "minimum approvals required" - expiry: "proposal expiration time in seconds" - memberVersion: "version identifier" - fiatToken: "0x0000000000000000000000000000000000001000" ``` Recommended guidelines: * **Minimum**: 1 * **Maximum**: Number of minters * **Typical**: `ceil((members.length * 2) / 3)` ### Proposal Lifecycle 1. **Proposed** 2. **Voting** 3. **Quorum reached** 4. **Executed** 5. **Expired** ## Security Considerations ### Byzantine Fault Tolerance With quorum set to `ceil((N * 2) / 3)`, up to `floor((N - 1) / 3)` malicious minters can be tolerated. ### Off-Chain Dependencies Failures in off-chain coordination may cause delays or rejections, but are mitigated by the multi-minter structure and on-chain event auditing. ### Proposal Expiry The expiry mechanism prevents execution of stale proofs, governance griefing, and unbounded proposal accumulation. ## Integration with NativeCoinAdapter ### Mint Execution Path ``` GovBase.executeProposal() → GovMinter._executeMint(...) → fiatToken.mint(...) → CoinManager.mint(...) precompile → Transfer(0x0, beneficiary, amount) ``` ### Burn Execution Path ``` GovBase.executeProposal() → GovMinter._safeBurn(...) → fiatToken.burn(...) → CoinManager.burn(...) precompile → Transfer(from, 0x0, amount) ``` Through these execution paths, native balances, fiat tokens, and event logs remain consistent, enabling both on-chain and off-chain auditing. # Governance System Source: https://docs.stablenet.network/en/governance-system/index ## Purpose and Scope This document provides an overview of the StableNet governance system, which implements a **protocol-native, three-layer governance architecture**.\ The governance system manages validator operations, token mint/burn authority, and protocol-level decisions through a set of **genesis-deployed system contracts**. For detailed information on specific components, refer to: * System contract deployment and initialization: [System Contracts Overview](/en/governance-system/5.1-system-contracts-overview) * Native stablecoin ERC-20 wrapper: [NativeCoinAdapter Contract](/en/governance-system/5.2-nativecoinadapter-contract) * Validator management and gas policy: [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)) * Minting authority hierarchy: [Minting Governance (GovMasterMinter and GovMinter)](/en/governance-system/5.4-minting-governance-\(govmasterminter-and-govminter\)) * Account policy (Blacklist / Authorized): [Council Governance (GovCouncil)](/en/governance-system/5.5-council-governance-\(govcouncil\)) * Proof-based mint and burn protocol: [Mint and Burn Protocol](/en/governance-system/5.6-mint-and-burn-protocol) For consensus and validator operations, see\ [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol) and\ [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)). *** ## Three-Layer Governance Architecture StableNet implements a **three-layer governance model**, where each layer has clearly separated responsibilities and is operated through **quorum-based voting among its members**. Unlike public blockchains where governance is driven by token holders, StableNet governance is distributed across **professional operators, financial institutions, and protocol administrators**, reflecting its stablecoin-centric design. ### Governance Layers | Governance Layer | Contract | Address | Primary Responsibility | | ------------------------ | --------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------- | | Validator Governance | GovValidator | `0x0000000000000000000000000000000000001001` | Validator set management, gasTip policy, providing validators/BLS keys at epoch transitions | | Master Minter Governance | GovMasterMinter | `0x0000000000000000000000000000000000001002` | Approved minter registry, minter list and per-minter allowance caps | | Minter Governance | GovMinter | `0x0000000000000000000000000000000000001003` | Proof-based mint/burn execution, actual issuance and burning via NativeCoinAdapter | | Council Governance | GovCouncil | `0x0000000000000000000000000000000000001004` | Global blacklist and authorized account sets, integration with AccountManager | The **NativeCoinAdapter**, deployed at\ `0x0000000000000000000000000000000000001000`,\ provides an ERC-20 interface for the native stablecoin. Decisions made by GovValidator, GovMasterMinter, GovMinter, and GovCouncil are ultimately reflected as **actual balance changes** through this adapter. *** ## Validator Governance **Purpose:**\ Manage the validator set that operates the blockchain and participates in consensus. **Key Responsibilities:** * Registering and removing validators through collective approval * Managing operator keys, validator keys, and BLS keys * Defining the network-wide mandatory gas tip (`gasTip`) * Handling epoch transitions and validator set rotation *** ## Minter Governance **Purpose:**\ Control the issuance and destruction of the native stablecoin. **Key Responsibilities:** * Proof-based minting and burning tied to fiat deposits and withdrawals * Quorum-based approval and execution * Preventing arbitrary issuance by a single entity *** ## Master Minter Governance **Purpose:**\ Manage the registry of entities allowed to participate in mint/burn operations. **Key Responsibilities:** * Adding and removing minters * Enforcing per-minter maximum allowance limits * Supporting future extensible minter types (e.g., bridges, system minters) *** ## Council Governance **Purpose:**\ Manage **global account-level policies** across the network. **Key Responsibilities:** * Defining and updating the blacklist account set * Defining and updating the authorized account set * Enforcing Anzeon-specific policies during transaction validation and state transitions via integration with the `AccountManager` precompile *** ## Immutability and Upgrade Model All governance contracts are deployed at genesis with **immutable code**.\ They cannot be upgraded through on-chain permissions or proxy mechanisms. Any change to governance logic requires a **protocol upgrade (hard fork)**, ensuring predictability and resistance to governance capture. *** ## Quorum-Based Voting Mechanism All governance contracts share a common governance base (`GovBase`) and therefore follow the same proposal lifecycle: * Membership snapshot–based proposal creation * Bitmap-based vote tracking * Transition to executable state upon quorum reach * Automatic invalidation via expiry, cancellation, or member version changes *** ## Integration with Consensus The governance system is directly integrated with **Anzeon WBFT consensus**: * Validator sets are loaded from GovValidator at epoch blocks * BLS keys are included in consensus message signing * Validator additions and removals take effect starting from the next epoch *** ## Relationship with Other Components The governance system coordinates and constrains StableNet’s: * Consensus and validator operation * Transaction pool admission rules * Block production * State transition rules * Gas fee and priority policies Together, these governance layers form the **policy backbone** of StableNet, ensuring that operational authority, monetary control, and account-level restrictions are applied consistently and transparently across the protocol. # Home Source: https://docs.stablenet.network/en/index ## Check RPC Connection Status ```shellscript bash theme={null} curl -X POST https://api.test.stablenet.network \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ```shellscript theme={null} {"jsonrpc":"2.0","id":1,"result":"0x132d3"} ``` This is the fastest way to verify that the StableNet RPC endpoint is operating correctly.\ By running this command, you send a JSON-RPC request directly to the StableNet network and receive the latest block number in response. If a block number (in hexadecimal) is returned successfully, your RPC connection is correctly configured and communication with the StableNet network is working.\ **Always try this first** before proceeding with node configuration, transaction submission, or wallet integration. *** ## Getting Started Choose a path based on what you want to do. * **StableNet Overview**\ Explains what StableNet is, how it differs, and how the system is structured.\ → /en/stablenet-overview/index * **Getting Started**\ Install and configure a node, and initialize genesis and network settings.\ → /en/getting-started/index *** ## Getting Started Checklist * **Installation and Build**\ Set up the environment and build the client.\ → /en/getting-started/2.1-installation-and-building * **Node Configuration**\ Configure the node and adjust key runtime settings.\ → /en/getting-started/2.2-node-configuration * **Genesis and Network Initialization**\ Initialize genesis and bootstrap the network.\ → /en/getting-started/2.3-genesis-setup-and-network-initialization *** ## Operations and Interaction * **Operations Guide**\ Deploy, operate, monitor validators, and maintain nodes.\ → /en/operations-guide/index * **RPC and APIs**\ RPC namespaces, filtering/subscriptions, and transaction submission.\ → /en/rpc-and-apis/index *** ## Deep Dive into the Protocol * **Core Architecture**\ Node lifecycle, core management flows, transaction pool, and encoding formats.\ → /en/core-architecture/index * **Consensus and Block Production**\ WBFT consensus, validator management, and block production.\ → /en/consensus-and-block-production/index * **Governance System**\ System contracts and protocol behavior controlled by governance.\ → /en/governance-system/index * **Storage Architecture**\ Trie/storage internals, caching, snapshots, and data lifecycle.\ → /en/storage-architecture/index * **Transaction Processing**\ End-to-end transaction flow: validation, execution, and inclusion.\ → /en/transaction-processing/index * **Networking**\ P2P, discovery, protocol handlers, and chain synchronization.\ → /en/networking/index *** ## Tools * **Development Tools**\ Utilities for building, CI/CD, testing, debugging, and operations.\ → /en/development-tools/index * **Explorer**\ Browse on-chain data such as blocks, transactions, and accounts on the StableNet network.\ → [https://explorer.stablenet.network](https://explorer.stablenet.network) # P2P Server and Peer Management Source: https://docs.stablenet.network/en/networking/7.1-p2p-server-and-peer-management This document covers the peer-to-peer networking layer that manages connections between StableNet nodes.\ It focuses on the `p2p.Server` architecture, peer lifecycle management, connection types, and protocol multiplexing. For peer discovery mechanisms, see [Discovery Mechanisms](/en/networking/7.2-discovery-mechanisms).\ For blockchain synchronization protocols, see [Chain Synchronization](/en/networking/7.3-chain-synchronization).\ For protocol handler implementations, see [Protocol Handlers](/en/networking/7.4-protocol-handlers). ## Server Architecture The P2P layer is centered around the `p2p.Server` structure, which manages all peer connections and implements the core networking functionality of a StableNet node.\ It unifies inbound and outbound connections and acts as an intermediary between discovery protocols and protocol handlers. ### Server Structure The `Server` structure maintains the following core components: | Component | Type | Purpose | | ----------- | ------------------ | ---------------------------------------------------------------------------------- | | `Config` | `p2p.Config` | Network configuration such as maximum peers, listen address, and enabled protocols | | `localnode` | `*enode.LocalNode` | Local node identity and ENR management | | `listener` | `net.Listener` | Accepts inbound TCP connections | | `dialsched` | `*dialScheduler` | Schedules outbound connection attempts | | `discmix` | `*enode.FairMix` | Aggregates multiple discovery sources | | `ntab` | `*discover.UDPv4` | Discovery v4 protocol handler | | `DiscV5` | `*discover.UDPv5` | Discovery v5 protocol handler | | `nodedb` | `*enode.DB` | Persistent node database | ### Server Configuration and Initialization Server initialization proceeds through the following steps: 1. **`setupLocalNode()`**\ Generates the local node ID and ENR from the private key and initializes the node database. 2. **`setupListening()`**\ Starts the TCP listener on the configured network address. 3. **`setupDiscovery()`**\ Initializes Discovery v4/v5 and configures the discovery mixer. 4. **`setupDialScheduler()`**\ Creates the dial scheduler for static and discovered nodes. 5. **`run()`**\ Starts the server’s main event loop for peer event handling. 6. **`listenLoop()`**\ Continuously accepts inbound connections. ### Server Main Loop The server’s main event loop performs the following tasks: * Handles peer addition and removal events * Processes connection requests from the dial scheduler * Gracefully shuts down all peers on termination signals * Broadcasts peer state changes via the event feed ## Peer Lifecycle Each connected peer is represented by a `Peer` structure that encapsulates connection state, protocol handlers, and lifecycle metadata. ### Connection Establishment Flow Peer connections follow this sequence: 1. TCP connection establishment 2. Encrypted handshake 3. Protocol handshake and capability negotiation 4. Protocol multiplexing setup 5. Peer registration and event emission ### Handshake Protocols Connection setup consists of two handshake phases: 1. **Encryption Handshake** (`doEncHandshake`)\ Establishes an RLPx-encrypted communication channel. 2. **Protocol Handshake** (`doProtoHandshake`)\ Negotiates supported protocols and versions. The `protoHandshake` structure includes: | Field | Type | Description | | ------------ | -------- | --------------------------------------- | | `Version` | `uint64` | P2P protocol version | | `Name` | `string` | Client identification string | | `Caps` | `[]Cap` | List of supported protocol capabilities | | `ListenPort` | `uint64` | Listening port | | `ID` | `[]byte` | Node public key | ### Protocol Multiplexing After the handshake, the server matches commonly supported protocols and assigns message code ranges to each protocol. * Base P2P messages: codes 0–15 * First matched subprotocol: starting at code 16 * Subsequent protocols: offset increased by the previous protocol’s length This design allows multiple protocols to be safely multiplexed over a single connection. ## Connection Types and Management The P2P server uses `connFlag` values to distinguish connection types: | Flag | Value | Description | | ------------------ | -------- | ------------------------------------------ | | `dynDialedConn` | `1 << 0` | Outbound connection created via discovery | | `staticDialedConn` | `1 << 1` | Outbound connection to a static node | | `inboundConn` | `1 << 2` | Inbound connection initiated externally | | `trustedConn` | `1 << 3` | Trusted peer (may exceed `MaxPeers` limit) | ### Peer Limits and Capacity Default peer capacity control policies include: * `MaxPeers`: total peer count limit * `MaxPendingPeers`: limit on pending connection attempts (default 50 per direction) * `DialRatio`: outbound peer ratio (default 1/3) ### Dial Scheduler The `dialScheduler` manages outbound connection attempts: * Tracks recent dial history to avoid excessive retries * Prioritizes static nodes over discovered nodes * Enforces maximum concurrent dial limits * Uses exponential backoff to throttle retries for failed endpoints ## Peer Operations and Lifecycle ### Adding and Removing Peers The server manages its peer set using the following methods: | Method | Purpose | | ------------------------- | --------------------------------------------- | | `AddPeer(node)` | Add a static peer with automatic reconnection | | `RemovePeer(node)` | Remove a static peer and disconnect | | `AddTrustedPeer(node)` | Add a trusted peer | | `RemoveTrustedPeer(node)` | Remove a trusted peer | ### Disconnect Reasons Disconnect reasons are recorded using `DiscReason` codes: | Reason | Code | Description | | ------------------------- | ---- | ------------------------- | | `DiscRequested` | 0x00 | Graceful shutdown | | `DiscNetworkError` | 0x01 | Network error | | `DiscProtocolError` | 0x02 | Protocol violation | | `DiscUselessPeer` | 0x03 | Invalid or unhelpful peer | | `DiscTooManyPeers` | 0x04 | Peer limit exceeded | | `DiscAlreadyConnected` | 0x05 | Duplicate connection | | `DiscIncompatibleVersion` | 0x06 | Version mismatch | | `DiscInvalidIdentity` | 0x07 | Invalid node identity | | `DiscQuitting` | 0x08 | Server shutting down | | `DiscSubprotocolError` | 0x10 | Subprotocol error | ### Peer Event Feed The server emits peer state changes via `PeerEvent` notifications: | Event Type | Description | | ---------------------- | ----------------------------- | | `PeerEventTypeAdd` | Peer connected and registered | | `PeerEventTypeDrop` | Peer disconnected | | `PeerEventTypeMsgSend` | Message sent | | `PeerEventTypeMsgRecv` | Message received | ## Integration with the Ethereum Backend The Ethereum backend integrates with the P2P server through protocol registration. Integration flow: 1. `eth.Ethereum.Protocols()` – returns protocol definitions 2. `eth.MakeProtocols()` – creates `eth` subprotocol handlers 3. `snap.MakeProtocols()` – creates `snap` protocol handlers (if enabled) 4. `node.Stack.RegisterProtocols()` – registers protocols with the P2P server 5. `handler.Start()` – begins protocol message processing ### Backend Access to the P2P Server The backend maintains a reference to the P2P server for RPC services, used for: * `NetAPI` – network information queries * `AdminAPI` – peer management RPCs * Dynamic ENR updates ## Configuration Flags Key flags used to configure the P2P network include: | Flag | Type | Default | Description | | ---------------- | ------ | -------------------------- | ------------------------------ | | `--maxpeers` | int | DefaultConfig.P2P.MaxPeers | Maximum number of peers | | `--maxpendpeers` | int | 0 | Pending peer limit | | `--port` | int | 30303 | Network listening port | | `--bootnodes` | string | Network-specific | Bootstrap nodes | | `--nodekey` | string | - | P2P node key file path | | `--nodekeyhex` | string | - | Test node key (hex) | | `--nodiscover` | bool | false | Disable peer discovery | | `--netrestrict` | string | - | CIDR-based network restriction | These configuration values are applied during node initialization via `SetP2PConfig()` and `setNodeKey()`. # Discovery Mechanisms Source: https://docs.stablenet.network/en/networking/7.2-discovery-mechanisms ## Purpose and Scope This page explains the peer discovery mechanisms used in the P2P networking layer of StableNet.\ Peer discovery is the process by which a node identifies other nodes in the network and obtains candidates for connection, which are then passed to the P2P server’s connection management logic.\ This document covers the Discovery v4 and Discovery v5 protocols, Ethereum Node Records (ENR), bootstrap nodes, and DNS-based discovery. For connection management after discovery, see [P2P Server and Peer Management](/en/networking/7.1-p2p-server-and-peer-management).\ For data exchange and synchronization with discovered peers, see [Chain Synchronization](/en/networking/7.3-chain-synchronization). ## Discovery Architecture Overview StableNet does not rely on a single method, but instead uses multiple discovery mechanisms in parallel to build a pool of peer candidates. **Discovery mechanisms:** * **Discovery V4**: Basic peer discovery using a Kademlia-based DHT * **Discovery V5**: An extended protocol with topic advertisements and enhanced cryptography * **DNS Discovery**: Tree-based discovery using DNS TXT records * **Bootstrap Nodes**: Static seed nodes for initial connectivity * **Protocol-specific sources**: Custom iterators provided by specific protocols **Discovery mixer:** `enode.FairMix` fairly mixes node candidates collected from multiple discovery sources.\ It iterates over each source in a round-robin manner to prevent any single source from monopolizing the candidate pool, and applies per-source timeouts. ## Discovery V4 Protocol Discovery V4 is a UDP-based Kademlia DHT protocol that maintains a routing table using an XOR distance metric.\ Nodes explore the network by issuing iterative queries to discover arbitrary peers. ### V4 Protocol Operations | Operation | Packet Type | Purpose | | --------------- | ----------- | ------------------------------------------ | | **PING** | 0x01 | Check node liveness and exchange endpoints | | **PONG** | 0x02 | Respond to PING and confirm endpoint | | **FINDNODE** | 0x03 | Request nodes close to a target ID | | **NEIGHBORS** | 0x04 | Return up to 16 node records | | **ENRREQUEST** | 0x05 | Request the latest ENR (EIP-868) | | **ENRRESPONSE** | 0x06 | Respond with an ENR | ### V4 Configuration and Setup The Discovery V4 service is configured via `p2p.Config` and started during the server initialization phase in `setupDiscovery()`. **Initialization process:** 1. Create a UDP socket 2. Build a `discover.Config` including the private key, network restrictions, and bootstrap nodes 3. Call `discover.ListenV4()` to start the V4 service 4. Register the `ntab.RandomNodes()` iterator with the discovery mixer ## Discovery V5 Protocol Discovery V5 is an extension of V4 that provides topic-based discovery and stronger cryptography.\ It supports both random node discovery and searching for peers interested in specific topics. ### V5 Enhancements * **Topic advertisements**: Nodes can advertise and search for interest-based topics * **Session keys**: Reduced handshake cost for repeated communication * **ENR updates**: More efficient ENR refresh mechanisms * **Improved NAT handling**: Better external endpoint estimation * **Packet encryption**: Authenticated encryption applied to all packets ### V5 Configuration Discovery V5 uses a separate list of bootstrap nodes and can be enabled alongside V4. **Shared UDP socket:** When V4 and V5 are both enabled, they share the same UDP port.\ Packets not handled by V4 are forwarded to V5, preventing conflicts. ## Ethereum Node Records (ENR) ENR is a signed data structure that contains a node’s identity and connectivity information.\ Both Discovery V4 and V5 use ENRs to exchange node metadata. ### ENR Structure **Core fields:** * **Node ID**: Identifier derived from the public key * **Sequence Number**: Incremented on each ENR update * **Signature**: Verifies record ownership * **Key-Value Pairs**: Extensible set of attributes **Common key-value entries:** | Key | Type | Description | | ----------- | ------------------------------ | ---------------------------- | | `id` | string | Identity scheme (usually v4) | | `secp256k1` | bytes | Compressed public key | | `ip` | bytes | IPv4 address | | `ip6` | bytes | IPv6 address | | `tcp` | uint16 | RLPx TCP port | | `udp` | uint16 | UDP discovery port | | `eth` | \[chainID, forkHash, forkNext] | Chain information | `enode.LocalNode` manages the local node’s ENR and automatically updates it when network conditions change. ## Bootstrap Nodes Bootstrap nodes are seed nodes used to initiate peer discovery when joining the network.\ They provide the first entry point when a local node has no knowledge of other peers. ### Bootstrap Configuration * Static specification via configuration files * Specification via command-line flags * `--bootnodes` for V4 bootstrap nodes * `--bootnodesv5` for V5 bootstrap nodes **Requirements:** * Publicly reachable endpoints * High availability * Typically operated by the network maintainers ## DNS Discovery DNS Discovery distributes ENR information encoded in DNS TXT records.\ This allows bootstrap lists to be updated dynamically without changing node software. ### DNS Discovery Tree Structure DNS-based discovery is organized as a Merkle tree. | Record Type | Description | | ----------- | ------------------------------------------ | | Root | Tree entry point and signature information | | Branch | Links to child nodes | | ENR | Actual node records | | Link | References to external trees | The DNS client traverses the tree, extracts ENR records, and passes them to the discovery mixer. ## Integration with the P2P Server All discovery mechanisms are initialized in `setupDiscovery()` and integrated via `enode.FairMix`.\ Discovered node candidates are forwarded to the dial scheduler, which attempts actual connections. ### Fair Mixing Algorithm `FairMix` follows these rules: 1. Iterate over active sources in round-robin order 2. Apply a maximum wait time per source 3. Skip unresponsive sources and move to the next 4. Periodically retry failed sources ## Discovery Metrics The discovery subsystem maintains the following state: * Discovery V4 routing table * Discovery V5 service state * Discovery mixer state * Local ENR * Persistent node database Discovery results are passed to the dial scheduler, which limits connection attempts and tracks failures to prevent retry storms. ## Summary StableNet’s peer discovery system is designed as a multi-layered architecture resilient to network changes. 1. **Discovery V4** provides stable, DHT-based random discovery 2. **Discovery V5** adds topic-based search and enhanced security 3. **ENR** enables extensible, signed node information exchange 4. **Bootstrap Nodes** provide initial network entry points 5. **DNS Discovery** enables dynamic and flexible bootstrapping All of these mechanisms are combined through `FairMix` to continuously supply a balanced set of peer candidates to the dial scheduler. # Chain Synchronization Source: https://docs.stablenet.network/en/networking/7.3-chain-synchronization ## Purpose and Scope Chain synchronization is the process of downloading and validating blockchain data (blocks, headers, receipts, and state) from network peers in order to bring a node up to the latest chain head.\ This document explains the synchronization architecture and internal workflow used in StableNet. Core components: * **`downloader.Downloader`** – Main synchronization engine * **`chainSyncer`** – Orchestrates synchronization tasks * **`queue`** – Schedules parallel downloads and caches results * **`peerSet`** – Manages peers participating in synchronization This document covers synchronization modes, common ancestor discovery, parallel download of headers/bodies/receipts, Snap-based state synchronization, queue limits, and peer management flows. For peer discovery, see [Discovery Mechanisms](/en/networking/7.2-discovery-mechanisms).\ For block insertion and chain management logic, see [Blockchain Management](/en/core-architecture/3.2-blockchain-management). ## Synchronization Modes StableNet supports three `SyncMode` values. | Mode | Value | Behavior | | ----------- | ----- | ------------------------------------------------------------------- | | `FullSync` | 0 | Download all blocks and execute all transactions | | `SnapSync` | 1 | Download headers and a recent state snapshot, then backfill history | | `LightSync` | 2 | Download headers only, minimal validation | The current mode is stored atomically in `Downloader.mode`. ### Mode Selection Logic `chainSyncer.modeAndLocalHead()` determines the synchronization mode using the following rules: * If the SnapSync flag is enabled, select SnapSync * If there is no local head state, force SnapSync * If the chain has rewound below the SnapSync pivot, re-enable SnapSync * Otherwise, use FullSync ## Downloader Architecture `Downloader` is the central component of the synchronization pipeline. | Field | Type | Purpose | | ------------ | --------------- | ------------------------------ | | `mode` | `atomic.Uint32` | Current synchronization mode | | `queue` | `*queue` | Download task scheduler | | `peers` | `*peerSet` | Peer tracking and selection | | `blockchain` | `BlockChain` | Target for FullSync | | `lightchain` | `LightChain` | Target for LightSync | | `SnapSyncer` | `*snap.Syncer` | State snapshot synchronization | | `skeleton` | `*skeleton` | Beacon header backfill | | `cancelCh` | `chan struct{}` | Cancellation signal | `Downloader` is created by the `eth` protocol handler and controlled by `chainSyncer`. ## Synchronization Orchestration ### chainSyncer Control Loop `chainSyncer.loop()` operates as a state machine and repeatedly performs the following: * Evaluate the current local head and remote peer states * Decide the next synchronization action * Execute synchronization and process results * Retry or switch modes on errors ### Synchronization Execution `doSync()` executes one of the following based on the selected mode: * FullSync – Full header, body, and receipt download * SnapSync – State snapshot download followed by history backfill ## Finding the Common Ancestor Synchronization begins by finding the common ancestor between the local chain and the remote chain. ### Two-Phase Ancestor Search 1. **Span Search**\ Request headers at intervals to quickly narrow down the fork range. 2. **Binary Search**\ Perform a binary search within the candidate range to find the exact common ancestor. ### Fork Protection To prevent deep chain reorganizations, a protective floor is applied, limiting ancestor searches below a certain depth. ## Header Synchronization Headers are synchronized before bodies and receipts. ### Header Fetch Modes * **Legacy mode** – Request headers directly from network peers ### Header Processing Downloaded headers are verified and ordered in parallel across multiple goroutines, while reorganization protection constants ensure chain stability. ## Downloading Bodies and Receipts Once headers are ready, bodies and receipts are downloaded in parallel via the `queue`. * Bodies and receipts maintain independent task queues and pending pools * Tasks are dynamically assigned based on peer capacity * Peers that fail validation are penalized or dropped ## State Synchronization (Snap Sync) Snap synchronization accelerates initial sync by skipping full transaction execution and downloading a state snapshot. ### Snap Sync Stages 1. Select a pivot block 2. Download the state snapshot 3. Fill missing trie nodes and code 4. Commit the pivot 5. Process subsequent blocks using FullSync ### Pivot Block The pivot block serves as the state root reference point. * Legacy mode – Request the latest head from peers The pivot number is persisted in the database. ### SnapSyncer Responsibilities SnapSyncer downloads the following data: * Account trie segments * Contract storage data * Contract bytecode * Missing trie nodes ### Ancient Store Handling During SnapSync, older blocks may be moved directly into the ancient store. * Threshold is finalized blocks or `head - 90000` * Blocks below the threshold are immediately frozen * Recent blocks remain in the active database ## Queue Task Scheduling `queue` controls parallel downloads and caches results. | Field | Purpose | | ------------------ | -------------------------------- | | `blockTaskPool` | Pending body tasks | | `blockTaskQueue` | Priority queue for body tasks | | `blockPendPool` | In-progress body requests | | `receiptTaskPool` | Pending receipt tasks | | `receiptTaskQueue` | Priority queue for receipt tasks | | `resultCache` | Completed result cache | ### Cache Limits The result cache is throttled when any of the following conditions are exceeded: * Item count limit * Total memory usage limit In this case, fetchers wait until processors consume cached results. ## Peer Management ### peerConnection Each peer tracks throughput and response latency. * Capacity estimates for headers, bodies, and receipts * Performance estimation based on exponential moving averages ### peerSet `peerSet` manages the set of peers eligible for synchronization. ### Peer Registration New peers are registered via `RegisterPeer()` after completing the synchronization handshake. ### Error Handling and Dropping * Missing data is marked via `MarkLacking()` * Repeated errors, timeouts, or invalid responses result in peer drops * In legacy sync paths, errors may cause immediate drops ## Synchronization Workflow Summary 1. Select peers and determine synchronization mode 2. Find the common ancestor 3. Download and validate headers 4. Download bodies and receipts in parallel 5. Perform SnapSync state synchronization if required 6. Commit the pivot and switch to FullSync 7. Reach the chain head and enter normal operation This workflow represents the full synchronization lifecycle from the moment a node joins the network until it reaches the latest chain state. # Protocol Handlers Source: https://docs.stablenet.network/en/networking/7.4-protocol-handlers ## Purpose and Scope This document describes the Ethereum protocol handlers in go-stablenet that manage message routing, peer protocol lifecycles, and data propagation.\ Protocol handlers act as a bridge between the P2P networking layer and higher-level blockchain components such as the downloader, block fetcher, and transaction pool. For basic P2P server and peer connection management, see [P2P Server and Peer Management](/en/networking/7.1-p2p-server-and-peer-management).\ For details on chain synchronization mechanisms, see [Chain Synchronization](/en/networking/7.3-chain-synchronization). ## Handler Architecture The protocol handler system is composed of multiple layers. ### Core Handler Structure The main `handler` struct coordinates all protocol-related activities. The `handler` struct includes: * **networkID**: Network identifier (mainnet, testnet, etc.) * **forkFilter**: Fork ID validation filter * **downloader**: Full chain synchronization component * **blockFetcher**: Short-range block announcement handler * **txFetcher**: Transaction propagation handler * **peers**: Active peer set * **chainSync**: Chain synchronization coordinator ## Protocol Registration and Lifecycle ### Handler Initialization During handler initialization, the following steps are performed: * Creation of the fork ID filter * Initialization of the downloader, fetchers, and peerSet * Registration of supported protocols (`eth`, `snap`) * Setup of broadcast loops and event subscriptions ### Peer Protocol Lifecycle When a peer connects, the handler operates in the following order: 1. Completion of the P2P handshake 2. Execution of the `eth` protocol handshake 3. Optional `snap` protocol handshake if required 4. Atomic registration in the peerSet 5. Start of the message handling loop This flow is managed by the `runEthPeer` function. ### Snap Protocol Extension The `snap` protocol operates as an extension layered on top of the `eth` protocol. * Successful `eth` handshake is a prerequisite * Handles messages dedicated to state snapshots and trie data requests * Directly integrated with the downloader’s SnapSync path ## Message Routing ### Protocol Message Dispatch The protocol handler forwards incoming messages to appropriate subsystems based on their type: * Synchronization-related messages → downloader * Block announcements → blockFetcher * Transactions → txFetcher / txpool * State snapshot requests → SnapSyncer The handler maintains two primary broadcast loops: 1. **Transaction Broadcast Loop**\ Listens for new transaction events and propagates them to peers. 2. **Mining Block Broadcast Loop**\ Listens for new block events and propagates blocks across the network. ### Peer Message Handlers Each protocol processes messages in a dedicated Run function. | Protocol | Handler Function | Message Types | | -------- | ----------------------------- | ------------------------------------------------------------ | | `eth/68` | `eth.MakeProtocols()[0].Run` | Headers, bodies, receipts, transactions, block announcements | | `snap/1` | `snap.MakeProtocols()[0].Run` | Account ranges, storage ranges, code, trie nodes | ## Block and Transaction Broadcasting ### Block Broadcasting Strategy Block propagation is performed in two phases: 1. Send the full block to √n peers 2. Send block hash announcements to all remaining peers This approach balances bandwidth usage and propagation latency. ### Transaction Broadcasting Strategy Transaction propagation varies by transaction size: * **Large transactions** (> 4096 bytes): Hash announcements only * **Normal transactions**: Direct send to √n peers, announcements to the rest ## Protocol Versioning and Capabilities ### Supported Protocols | Protocol | Version | Purpose | | -------- | ------- | ----------------------------------------------------- | | `eth` | 68 | Block and transaction synchronization and propagation | | `snap` | 1 | State snapshot and trie data synchronization | During the handshake, peers exchange capabilities and negotiate a common supported version. ### Fork ID Validation Fork ID validation based on EIP-2124 ensures chain compatibility using: * Genesis hash * Fork block information * Next scheduled fork Peers with incompatible fork IDs are immediately disconnected. ## Peer Set Management ### Role of peerSet `peerSet` centrally manages active peers: * Atomically registers eth / snap protocols * Tracks per-peer block and transaction reception status * Used for synchronization and broadcast target selection ## Handler Lifecycle ### Start and Stop * **`Start()`**\ Starts broadcast loops and event subscriptions. * **`Stop()`**\ Terminates all goroutines and cleans up peers. ## Integration with Subsystems ### Downloader Integration The handler provides the downloader with: * Peer registration and removal notifications * Synchronization start triggers * Control over snap / full synchronization transitions ### Fetcher Integration * **blockFetcher**: Handles fast block announcements * **txFetcher**: Prevents transaction duplication and optimizes propagation ## Error Handling and Peer Removal ### Peer Removal Flow Peers are removed under the following conditions: * Protocol violations * Fork ID mismatch * Repeated invalid responses * Timeouts or resource abuse Upon removal, cleanup is performed consistently across the peerSet, downloader, and fetchers. ## Summary The go-stablenet protocol handlers are responsible for: 1. Negotiation and management of multiple protocols (`eth`, `snap`) 2. Message routing and integration with subsystems 3. Efficient block and transaction broadcasting 4. Peer lifecycle management and error handling 5. Bridging P2P networking with the blockchain core Protocol handlers are a central component that orchestrates all protocol-level network operations in the Ethereum backend. # Networking Source: https://docs.stablenet.network/en/networking/index ## Purpose and Scope This document provides an overview of StableNet’s peer-to-peer networking subsystem, which handles node discovery, peer connection management, blockchain synchronization, and message propagation.\ The networking layer is built on Ethereum’s DevP2P protocol stack and implements the `eth` protocol for block and transaction exchange. For detailed information on specific networking components, refer to the following documents: * Connection lifecycle and peer tracking: [P2P Server and Peer Management](/en/networking/7.1-p2p-server-and-peer-management) * Node discovery mechanisms and peer compatibility: [Discovery and Fork ID](/en/networking/7.2-discovery-mechanisms) * Blockchain download and synchronization strategies: [Chain Synchronization](/en/networking/7.3-chain-synchronization) * Message routing and protocol version management: [Protocol Handlers](/en/networking/7.4-protocol-handlers) For transaction propagation details, see [Transaction Lifecycle](/en/transaction-processing/6.1-transaction-lifecycle).\ For block production and broadcasting, see [Block Production and Mining](/en/consensus-and-block-production/4.2-block-production-and-mining). ## Networking Architecture Overview StableNet’s networking layer consists of four major subsystems that work together to maintain network connectivity and synchronize blockchain state. ## P2P Server `p2p.Server` is the foundation of the networking stack and manages the lifecycle of all peer connections.\ It coordinates peer discovery, connection establishment, protocol negotiation, and graceful disconnection. The server maintains different categories of peers: * Dynamic peers: Discovered through DHT mechanisms and subject to connection limits * Static peers: Preconfigured nodes that are always reconnected upon disconnection * Trusted peers: Nodes that bypass `MaxPeers` limits and receive priority treatment **Key components:** | Component | Type | Purpose | | ------------------ | -------------------- | ---------------------------------- | | `Server.localnode` | `*enode.LocalNode` | Local node ENR record and identity | | `Server.ntab` | `*discover.UDPv4` | Discovery v4 table | | `Server.DiscV5` | `*discover.UDPv5` | Discovery v5 table | | `Server.dialsched` | `*dialScheduler` | Outbound connection scheduling | | `Server.peers` | `map[enode.ID]*Peer` | Currently connected peer set | The server runs a main event loop that handles: * Peer connection setup stages * Peer disconnection processing * Dynamic updates to the trusted peer list * Thread-safe access to the peer set ## Peer Discovery StableNet supports multiple peer discovery mechanisms that can operate simultaneously: | Mechanism | Protocol | Use Case | | ------------- | ------------------ | -------------------------------------- | | Discovery v4 | UDP / Kademlia DHT | Default discovery for public networks | | Discovery v5 | UDP / Topic-based | Advanced discovery and topic filtering | | DNS Discovery | DNS TXT | Bootstrapping and known nodes | | Static Nodes | Configuration file | Persistent peer relationships | | Trusted Nodes | Configuration file | Priority peers | Discovery services forward candidate peers to the `dialScheduler` and apply the following policies: * Maintain inbound/outbound connection ratios * Prevent duplicate dials * Apply exponential backoff for failed connections * Relax limits for trusted peers ### Fork ID Validation Before establishing full peer relationships, nodes exchange fork IDs (EIP-2124) to verify chain compatibility.\ The fork ID is computed based on the genesis hash and upcoming fork block numbers: ```text theme={null} ForkID = CRC32(genesisHash + fork1Block + fork2Block + ...) ``` Peers with incompatible fork IDs are rejected during the handshake phase, preventing network splits. ## Chain Synchronization The chain synchronization subsystem downloads and verifies blockchain data from peers.\ This system operates through the collaboration of multiple components. **Diagram: Synchronization component interaction** ### Synchronization Modes StableNet supports the following synchronization modes depending on node state: | Mode | Description | Use Case | | --------- | ---------------------------------- | ---------------------------- | | FullSync | Download and execute all blocks | Archive nodes | | SnapSync | State snapshot + recent blocks | Fast initial synchronization | | LightSync | Header-only and request-based data | Lightweight clients | ### Downloader The downloader performs the following tasks: * Common ancestor block discovery * Skeleton chain construction * Parallel data downloads * Memory-based queue limiting * Chain insertion after verification ## Protocol Handlers Protocol handlers bridge the P2P layer and blockchain logic and are responsible for routing messages. **Diagram: Protocol handler message flow** ### Protocol Version Management StableNet implements the `eth/68` protocol.\ During the handshake, protocol version and chain information are exchanged: ```text theme={null} Handshake { ProtocolVersion: 68 NetworkID: TD: Head: Genesis: ForkID: } ``` Peers must share the same genesis hash and a compatible fork ID to establish a connection. ### Message Handling **Request/response messages:** * GetBlockHeaders / BlockHeaders * GetBlockBodies / BlockBodies * GetReceipts / Receipts * GetPooledTransactions / PooledTransactions **Broadcast messages:** * NewBlock * NewBlockHashes * Transactions * NewPooledTransactionHashes Smart propagation strategies are used to balance bandwidth usage and propagation latency. ## Peer Management Each peer goes through the following lifecycle: 1. Discovery 2. Dialing 3. Encryption handshake 4. Protocol handshake 5. Registration 6. Message exchange 7. Disconnection The P2P layer is responsible for transport and encryption, while the `eth` layer handles blockchain logic. ### Peer Reputation The downloader continuously tracks peer performance: * Header processing capacity * Body processing capacity * Receipt processing capacity * Round-trip latency This reputation data is used to select peers for synchronization requests. ## Network Security The networking layer includes the following security mechanisms: | Mechanism | Purpose | | ------------------------- | ------------------------------ | | Connection limits | Prevent resource exhaustion | | Inbound limits | Defend against connection spam | | Fork ID validation | Prevent chain splits | | Reputation-based eviction | Block malicious peers | | Message size limits | Prevent memory attacks | | Request rate limits | Protect I/O and bandwidth | Peers may be disconnected due to protocol violations, excessive resource usage, or compatibility issues. # Network Deployment Source: https://docs.stablenet.network/en/operations-guide/11.1-network-deployment ## Purpose and Scope This document explains the procedure for **deploying a private StableNet network from scratch**.\ It covers the **initial network setup phase**, including genesis file generation, nodekey management, and bootnode configuration. Deployment is performed by building from source in the StableNet repository. Required binaries such as `gstable`, `bootnode`, and `genesis_generator` are built via the Makefile or `build/ci.go`. For detailed instructions, refer to [Installation and Building](/en/getting-started/2.1-installation-and-building). The following topics are **out of scope** for this document and are covered elsewhere: * Per-node configuration and runtime options:\ [/en/getting-started/2.2-node-configuration](/en/getting-started/2.2-node-configuration) * Genesis structure and system contract initialization:\ [/en/getting-started/2.3-genesis-setup-and-network-initialization](/en/getting-started/2.3-genesis-setup-and-network-initialization) * Validator operations after network deployment:\ [/en/operations-guide/11.2-validator-operations](/en/operations-guide/11.2-validator-operations) ## Generating a Genesis File with genesis\_generator `genesis_generator` is a **dedicated CLI tool for genesis creation** provided to initialize a StableNet network.\ It generates a genesis file and a base configuration file tailored to the selected consensus engine, validator setup, and network topology. ### Tool Overview `genesis_generator` automatically performs the following tasks: * Extracts validator information from nodekeys * Generates a genesis structure compatible with the consensus engine * Computes the initial validator set and quorum * Generates `genesis.json` and `config.toml` ### Single-Node Network Configuration For development and testing purposes, a **single-node network configuration** can be generated.\ This setup is intended **only for network initialization and functional validation** and is not suitable for real deployments or production environments. **Process Flow:** 1. **Load nodekey** * Input the nodekey file path * Default path: `./nodekey` 2. **Derive validator keys** * Derive the following from the nodekey (ECDSA private key): * Validator account address * BLS public key for QBFT consensus 3. **Automatically configure validator set** * Number of validators: `1` * Quorum: `1` 4. **Generate genesis.json** * Register the single validator in the validator set * Allocate an initial balance to the validator account * Apply the selected consensus engine configuration 5. **Generate config.toml** * `StaticNodes` is generated as an empty list * Includes only the minimum settings required to run a single node ### Generated Artifacts * `genesis.json`\ Contains network ID, consensus configuration, validator information, and initial state * `config.toml`\ Base configuration file for node execution (`StaticNodes` is an empty array in single-node mode) ### Multi-Node Network Configuration For development, testing, or production networks, a **multi-node network configuration** can be generated.\ This setup supports validator sets with governance quorum and collects validator, quorum, and static node information interactively. **Process Flow:** 1. **Input validators** * Enter validator addresses and their corresponding BLS public keys (empty input terminates) * For each validator, a BLS public key is requested (0x-prefixed, 96 hex characters) 2. **Configure quorum** * Enter the governance quorum value * Minimum: 2, Maximum: number of validators 3. **Static nodes** * Optionally input enode URLs to populate `config.toml` * If skipped, static nodes must be managed manually 4. **Generate genesis.json** * Apply Anzeon configuration using the provided validators, BLS keys, and quorum * System contract parameters are set via `setAnzeonConfig()` 5. **Save** * Specify output paths and generate the genesis and configuration files ### Generated Artifacts * `genesis.json`\ Includes network ID, consensus configuration, validator list, BLS public keys, quorum, and system contract parameters (e.g., GovValidator) * `config.toml`\ Base configuration file for node execution\ (`StaticNodes` populated with provided enode URLs if selected, otherwise an empty array) ## Nodekey Generation and Management Before deploying validators, each node requires a unique nodekey used for multiple purposes. ### Data Derived from a Nodekey Each node’s nodekey (ECDSA private key) is used to derive the **validator address** (block signing / coinbase) and the **BLS key pair** (consensus signing).\ This derivation is used by `genesis_generator` (`deriveAccount()`), `bootnode`, and node networking configuration (static nodes, enode URLs, etc.). ### Generating a Nodekey The `bootnode` utility can be used to generate a nodekey and inspect its public key (for enode URLs). Common flags include: | Flag | Description | | --------------- | -------------------------------------------------------------------- | | `-genkey` | Generate a nodekey and store it in the specified file | | `-nodekey` | Specify the private key file path | | `-writeaddress` | Print the node public key and exit (used for enode URL construction) | ```bash theme={null} # Generate a nodekey (stored in the specified file) bootnode -genkey nodekey # Print the public key from an existing key (used in enode URLs) bootnode -nodekey nodekey -writeaddress ``` ## Network Initialization Workflow ### Genesis Initialization Process 1. **Generate genesis and config**: Use `genesis_generator` to create `genesis.json` (and optionally `config.toml`) 2. **Distribute files**: Copy the same `genesis.json` to the intended data directory location on every node 3. **Initialize data directories**: Run `gstable init` on each node to write the genesis block, then start the node using that directory `init` **overwrites existing data**, so the target directory must not contain an active chain.\ For Anzeon genesis files, consensus and system contract settings are validated during initialization. ### Initialization Command `gstable init` accepts a single argument: the path to the genesis file.\ The data directory is specified with `--datadir`. ```bash theme={null} gstable --datadir /path/to/datadir init /path/to/genesis.json ``` * **`--datadir`**: Data directory to initialize (defaults if omitted) * **``**: Path to the `genesis.json` file When running the node, use the same `--datadir`, and specify `--networkid` to match `config.chainId` in the genesis file. ### Network Presets (--mainnet, --testnet) When joining an **already configured public StableNet network**, network preset flags can be used.\ These presets include built-in genesis and bootnodes, allowing nodes to run without a custom `genesis.json`. | Flag | Description | Network ID | Use Case | | ----------- | ----------------- | ---------- | --------------------------------------------------- | | `--mainnet` | StableNet mainnet | 8282 | Connect to StableNet mainnet | | `--testnet` | StableNet testnet | 8283 | Connect to the preconfigured StableNet test network | * These flags are mutually exclusive. * When using `--mainnet` or `--testnet`, the corresponding genesis and bootnode list are applied automatically, and the default network ID is used unless overridden. Example: running a StableNet testnet node ```bash theme={null} gstable --testnet --datadir /path/to/datadir ``` ## Bootnode Configuration and Peer Connectivity ### Static Node Configuration Static nodes are peers that a node attempts to connect to on startup.\ They are defined in the `[Node.P2P]` section of `config.toml` generated by `genesis_generator`. * **Single-node**: `StaticNodes` is generated as an empty array (`[]`) * **Multi-node**: When enode URLs are provided interactively, `StaticNodes` is populated accordingly, simplifying peer connectivity among validator nodes Example `config.toml` for a multi-node setup: ```toml theme={null} [Node.P2P] StaticNodes = [ "enode://<128_hex_public_key>@:", "enode://<128_hex_public_key>@:" ] ``` ### Enode URL Structure An enode URL uniquely identifies a node in the P2P network and is used for static nodes and bootnodes. **Format:** `enode://@:` * Public key: 64-byte ECDSA public key encoded as 128 hex characters * Host and port: IP address (or hostname) and listening port `genesis_generator.validateEnodeURL()` verifies that each enode URL satisfies: 1. Starts with the `enode://` prefix 2. Public key is exactly 128 hexadecimal characters 3. Host is a valid IPv4 or IPv6 address 4. Port is an integer in the range 1–65535 ### Deploying a Bootnode for Peer Discovery For production networks, it is recommended to deploy a dedicated bootnode to facilitate peer discovery.\ A bootnode provides discovery services only and does not maintain the full chain. **1. Key generation and execution** ```bash theme={null} # Generate a bootnode key bootnode -genkey boot.key # Run the bootnode (configure listen address, network restriction, log level) bootnode \ -nodekey boot.key \ -addr :30303 \ -netrestrict 0.0.0.0/0 \ -verbosity 3 # Print the public key (for constructing the enode URL) bootnode -nodekey boot.key -writeaddress ``` **2. Client usage** When running each node, include the bootnode enode URL via `-bootnodes` to enable peer discovery. ```bash theme={null} gstable -bootnodes enode://@:30303 -datadir /path/to/datadir ``` ## Production Network Deployment Checklist ### Pre-Deployment Preparation | Task | Details | Verification | | -------------------------- | ----------------------------------------------------------------- | ---------------------------------------- | | **Generate nodekeys** | Use `bootnode -genkey`, one per validator | Verify derived addresses and BLS keys | | **Create genesis file** | Use `genesis_generator` with all validator addresses and BLS keys | Validate JSON structure and quorum | | **Configure static nodes** | Build `config.toml` with all validator enode URLs | Test enode connectivity | | **Set chain parameters** | Choose a unique chainId, gas limits, system contracts | Review gas tip policy, mint/burn quorum | | **Pre-fund accounts** | Allocate initial balances in genesis `alloc` | Verify total supply matches expectations | ### Initialization Sequence 1. Copy the same `genesis.json` to all nodes 2. Run `gstable -datadir init ` on each node 3. Start each node with\ `gstable -datadir -networkid ` (and `-bootnodes`, `-config` if needed) **Common runtime flags:** | Flag | Description | | ------------ | ------------------------------------------ | | `-datadir` | Data directory (must match initialization) | | `-networkid` | Must match the genesis chainId | | `-bootnodes` | Bootnode enode URLs (comma-separated) | | `-config` | Path to config.toml (static nodes, etc.) | ### Post-Deployment Verification After nodes are running, verify the following: 1. **Peer count**: Attach via `gstable attach` and check `admin.peers.length` 2. **Consensus**: Monitor block production and finalization 3. **Transactions**: Send test transactions and verify propagation and execution 4. **Gas tip**: Confirm that the governance-defined gas tip is enforced 5. **System contracts**: Call `GovValidator.getValidators()` and verify the validator set matches genesis ## System Contract Deployment Verification After network initialization, you can verify that system contracts defined in the genesis file were deployed correctly.\ During genesis application, `GetSystemContractsTransition()` is invoked to install contract code and initialize storage using genesis parameters.\ By querying code and storage at system contract addresses via RPC, you can confirm successful deployment. # Validator Operations Source: https://docs.stablenet.network/en/operations-guide/11.2-validator-operations ## Purpose and Scope This document provides a **guide for operating validator nodes** in the StableNet network.\ It covers validator key management, node configuration, block production (mining), governance participation, monitoring practices, and common failure-handling scenarios. Validators are the core operators of the StableNet blockchain, responsible for block production, consensus participation, and network governance. Related documents: * [Network Deployment](/en/operations-guide/11.1-network-deployment) * [Node Monitoring and Maintenance](/en/operations-guide/11.3-node-monitoring-and-maintenance) * [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol) * [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)) ## Validator Architecture Overview ### Validator Key Structure StableNet validators use **three types of keys**, each serving a distinct purpose. | Key Type | Purpose | Storage | Usage Frequency | | ----------------- | ------------------------------------------------- | --------------------------- | ----------------------------- | | **Operator Key** | Governance voting, validator add/remove | External wallet or multisig | Low (governance actions only) | | **Validator Key** | Consensus message signing, coinbase address | Node `nodekey` file | High (every block) | | **BLS Key** | Derived from Validator Key, aggregated signatures | Derived internally | High (every block) | * The **Operator Key** can be a standard EOA (Externally Owned Account) or a multisig contract address for enhanced security. * The **Validator Key** and **BLS Key** must always be accessible to the node process for consensus participation. * StableNet nodes automatically derive the validator address from the `nodekey` and use it consistently across the Anzeon chain. ### Genesis Configuration for Validators Validators are defined in **two locations** within the genesis file. 1. **`anzeon.init` section** * Used to construct `EpochInfo` in the genesis block (block 0) * Defines the active validator set for the **first epoch** (from block 0 up to the first epoch block) 2. **`anzeon.systemContracts.govValidator` section** * Defines the **initial state** of the GovValidator contract (storage initialized at genesis) * From the **second epoch onward**, validator BLS keys are read from this contract when creating new `EpochInfo` at epoch blocks * After genesis, validator additions and removals are only possible via governance (GovValidator proposals, voting, and execution) The `govValidator.params` object contains three parallel lists: * `members` * `validators` * `blsPublicKeys` These lists must have **identical lengths and ordering**.\ Entries at the same index across all lists together represent a single validator identity. * **Operator address** (`members`): Used for governance voting and validator management * **Validator address** (`validators`): Used for consensus message signing and as the coinbase address; derived from the node’s `nodekey` * **BLS public key** (`blsPublicKeys`): Derived from the validator key; used for WBFT PREPARE/COMMIT aggregated signatures ## Node Configuration ### Initial Setup #### 1. Validator Key Generation The validator address and BLS key are derived from the node’s **nodekey**.\ The nodekey is generated using `bootnode -genkey` as described in [Network Deployment](/en/operations-guide/11.1-network-deployment). The BLS public key can be prepared in one of the following ways: * Automatically derived from the nodekey by `genesis_generator` * Generated via bootnode tooling and registered in genesis and GovValidator #### 2. Configuration File Setup Each validator node uses a `config.toml` file to configure data directories, RPC, P2P, static nodes, and bootnode settings.\ For multi-node deployments, you may directly use the `config.toml` generated by `genesis_generator` or customize it for the operational environment. #### 3. Network Configuration Mainnet and testnet validators can use network presets (`-mainnet`, `-testnet`) or specify bootnodes using `-bootnodes`.\ For private networks, follow the static node and bootnode configuration described in\ [11.1 Network Deployment](/en/operations-guide/11.1-network-deployment). ### Important Configuration Parameters #### Mining Configuration In Anzeon/WBFT chains, the etherbase is **automatically** set to the address derived from the node’s nodekey, regardless of `-miner.etherbase`.\ This guarantees that the validator key and block coinbase always match.\ The code (e.g., `eth/backend.go`) consistently derives the validator address from the P2P node key. ## Starting Validator Operations ### Node Startup Run the node using a data directory initialized with the genesis file.\ To enable mining (block production), specify the `-mine` flag. Example: `gstable -datadir -networkid -mine -config config.toml` If required, add the `-bootnodes` option to specify bootnodes. ### Mining Lifecycle Mining begins once the node is synchronized with the network.\ Under WBFT consensus, **only the proposer selected for the current round** proposes a block, while other validators participate via prepare and commit messages. ### WBFT-Specific Mining Loop In WBFT, mining is **event-driven rather than timer-based**.\ When the consensus engine starts a new round, it signals the worker to generate and submit a block. **Execution flow summary:** * **Trigger**\ When WBFT core starts a new round (`startNewRound`), `NotifyNewRound` is invoked in the backend and forwarded to the worker’s `readyToCommit` channel.\ An optional delay until the next block time may also be included. * **Worker**\ Upon receiving a signal on `readyToCommitCh`, the worker creates new sealing work.\ Any in-progress block build is aborted and retried using the new round context.\ When WBFT is enabled, block creation is triggered *only* by this channel signal; simple chain head updates do not trigger new work. * **Proposer**\ A proposer is selected for each round.\ Although all validators may build blocks, only the proposer’s PRE-PREPARE block is used for consensus. This integration is achieved by registering a `readyToCommit` callback with the WBFT engine during backend startup, linking the consensus engine and execution backend (worker). ## Governance Participation ### Proposal Voting Governance members participate via the GovValidator contract.\ Using the **Operator Key**, they can create proposals (`propose`), vote (`vote`), and execute (`execute`).\ Refer to [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)) for details. ### Gas Tip Governance Governance members determine the gas tip (priority fee) for non-authorized accounts via GovValidator governance.\ The selected gas tip is queried from GovValidator on every block and automatically applied to both the worker and transaction pool. ## Key Management Best Practices ### Security Considerations | Key Type | Security Level | Backup Strategy | Access Pattern | | ----------------- | -------------- | ------------------------------------ | -------------- | | **Operator Key** | Highest | Offline backup, multisig recommended | Rare | | **Validator Key** | High | Encrypted backup | Continuous | | **BLS Key** | High | Encrypted backup | Continuous | ### Protecting the Operator Key Because the operator key controls governance actions, it carries the highest privilege. Recommended practices: 1. **Use multisig contracts**\ Use a multisig contract address instead of a plain EOA 2. **Cold storage**\ Keep the operator key offline except during voting 3. **Hardware wallets**\ Use hardware wallets for operator key signing 4. **Isolated signing services**\ Operate a dedicated signing service for operator actions ### BLS Key Management BLS keys are mandatory for WBFT participation. The following must be strictly observed. 1. **Registration consistency**\ The BLS public key registered in GovValidator (or genesis `init`) must match the BLS public key derived from the node’s nodekey.\ The consensus engine verifies signatures using the registered key; mismatches prevent participation. 2. **Derivation during initialization**\ During initialization, the WBFT backend derives the BLS secret key by calling `bls.DeriveFromECDSA` on the node’s ECDSA private key (nodekey).\ There is no separate BLS key file loading path. 3. **Secure backups**\ Losing the nodekey makes it impossible to recover the same BLS key pair.\ In such cases, governance must be used to register a new validator with a new nodekey and BLS key. To obtain the BLS public key for genesis or GovValidator registration: * Derivation logic: `genesis_generator.deriveAccount()` * Reference: *Data derived from a Nodekey* in\ [Network Deployment](/en/operations-guide/11.1-network-deployment) In production, either generate validator and BLS keys via `genesis_generator` or use a BLS12-381–capable utility, ensuring the same key pair is used by the node. ### Validator Rotation Active validators and BLS keys can be changed **only via governance**, allowing zero-downtime rotation. 1. **Preparation**\ Generate a new nodekey and BLS key pair and obtain the validator address and BLS public key. 2. **Propose addition**\ Submit a proposal to add the new validator using the operator key. 3. **Propose removal**\ After approval, submit a proposal to remove the old validator. 4. **Zero-downtime transition**\ Run both validator nodes concurrently during the transition period. Governance process: * Call `GovValidator.propose()` with the operator key * Members vote via `GovValidator.vote()` * Execute via `GovValidator.execute()` once quorum is reached * Changes take effect at the next epoch block ### Key Storage Restrict file permissions so sensitive key files (e.g., `nodekey`) are readable **only by the validator node**.\ Example: `chmod 600 nodekey`\ Ensure the directory containing key files also has restricted permissions. ## Validator Status Monitoring ### Key Metrics to Monitor Regularly monitor block production rate, peer count, sync lag, disk and memory usage, and BLS/consensus-related errors.\ See [Node Monitoring and Maintenance](/en/operations-guide/11.3-node-monitoring-and-maintenance) for details. ### Monitoring Commands After attaching to the node console using `gstable attach`, use: * `eth.mining` : Mining (block production) status * `eth.blockNumber` : Current block height * `admin.peers.length` : Number of connected peers * `admin.peers` : Detailed peer information Validator lists can be queried via GovValidator contract calls. ### Log Monitoring Inspect logs for: * Block proposal and commit flow * BLS signature failures and consensus errors * Peer connections and disconnections * Gas tip updates * Governance-related events Investigate and address warnings or errors promptly. ### Log Levels The default `-verbosity` is often sufficient.\ For deeper inspection of consensus, P2P, or worker behavior, increase `-verbosity` or use `-vmodule` to enable detailed logs for specific packages. ### Metrics Export Enable Prometheus-compatible metrics using the `-metrics` flag.\ Default endpoint: * `http://localhost:6060/debug/metrics` The metrics port and path can be customized via flags. ## Common Troubleshooting ### Issue: Mining Does Not Start **Symptoms**: `eth.mining` returns `false` and no blocks are produced. **Diagnostics**: 1. Attach to the node and check `eth.mining` and `eth.coinbase` 2. Verify the node was started with the `-mine` flag 3. Check `eth.syncing` (mining may be delayed while syncing) **Resolution**: * Restart the node with `-mine` * Ensure the nodekey file exists in `-datadir` (or default data directory) * Recheck mining status after synchronization completes ### Issue: Block Production Stops **Symptoms**\ The validator no longer produces blocks. **Diagnostics**: 1. Query GovValidator to confirm the node’s address is still in the validator set 2. Inspect logs for WBFT proposal/commit messages or errors 3. Check peer connectivity via `admin.peers.length` and `admin.peers` **Resolution**: * Verify validator address and BLS public key registration * Ensure the node’s BLS key matches the registered public key * Increase peer connectivity (20–30 peers recommended for stability) * Check firewall and network access for the P2P port (default 30303) ### Issue: Gas Tip Mismatch **Symptoms**\ Transactions fail with `"gas tip too low"` errors. **Diagnostics**: 1. Check the current required gas tip via `GovValidator.gasTip()` or `eth.maxPriorityFeePerGas` 2. Verify the transaction’s `maxPriorityFeePerGas` meets or exceeds the required value 3. Confirm the node is fully synchronized and recent governance changes are applied **Resolution**: * Ensure the node is synced (gas tip is fetched automatically by the worker) * Allow time for block propagation after governance changes * Submit transactions with `maxPriorityFeePerGas` ≥ required network gas tip ### Issue: Node Crash or Restart **Symptoms**\ The node process exits unexpectedly. **Diagnostics**: 1. Check available disk space on `-datadir` 2. Inspect logs for database errors after restart 3. Review system and kernel logs for OOM kills or I/O errors **Resolution**: * Free disk space (≥500GB recommended for production)\ Optionally configure `-datadir.minfreedisk` * Increase RAM or adjust `-cache` if memory pressure occurs * If DB corruption is suspected, back up data, clear `-datadir`, and resync * Use SIGINT or SIGTERM for graceful shutdown and verify shutdown logs ### Issue: Validator Removed from Set **Symptoms**\ The node stops producing blocks and is no longer in the validator set. **Diagnostics**: 1. Query `GovValidator.getValidators()` to confirm removal 2. Check recent governance proposals, votes, and executions 3. Investigate potential operator key compromise or misuse **Resolution**: * If key compromise is suspected, immediately prepare key rotation * Coordinate with governance members to propose re-adding the validator * Review proposal history and logs to determine the cause * Protect operator keys using multisig and cold storage ## Performance Optimization ### Resource Requirements | Resource | Minimum | Recommended | Notes | | -------- | ---------- | ------------- | ----------------------------------------- | | CPU | 4 cores | 8+ cores | More cores improve parallel tx processing | | RAM | 8 GB | 16+ GB | More RAM reduces disk I/O | | Disk | 500 GB SSD | 1 TB NVMe SSD | Disk speed affects state access | | Network | 10 Mbps | 100+ Mbps | Low-latency, stable network recommended | ### Cache Configuration Use the `-cache` option to allocate memory (MB) to the node.\ Validators are recommended to use **at least 4096MB**, considering full sync and block production load.\ Increasing the value reduces disk I/O if memory is available. ### Network Optimization Set an appropriate `-maxpeers` value and maintain connections to trusted peers using `-bootnodes` and static nodes.\ Ensure the P2P port (default 30303) is open and the network environment has low latency and packet loss. ## Epoch Transitions and Validator Set Updates ### Epoch Structure WBFT manages blocks in epochs, and validator set changes apply **only at epoch blocks**. The epoch length is defined by `config.anzeon.epochLength` in genesis\ (e.g., `epochLength = 10`). At the last block of each epoch (`blockNumber % epochLength == 0`), the WBFT engine: 1. Reads the current validator list from GovValidator 2. Reads the BLS public key list from GovValidator 3. Updates `WBFTExtra.EpochInfo` in the next block header 4. Activates the updated validator set starting from the next block ### Validator Set Synchronization New or restarting nodes read the validator set from the latest block’s `WBFTExtra.EpochInfo` during chain synchronization. Because GovValidator updates are applied at epoch blocks, once synchronization completes, the node’s active validator set automatically matches the network’s current state. ## Validator Rewards and Economics StableNet validators are rewarded through the following structure. ### Validator Reward Model **Transaction Fees** * Both Base Fee and Gas Tip are paid to validators * **Base Fee is not burned**\ (Unlike Ethereum, no burn mechanism is used to preserve 1:1 fiat backing) * **Gas Tip** is paid directly to the block producer\ (credited via `Header.Coinbase`) * **No block rewards**\ There is no inflationary block subsidy by design ### Gas Fee Policy StableNet uses a gas fee policy optimized for a stablecoin environment. #### Gas Tip Policy Gas Tip application depends on account type. 1. Authorized Accounts * Same as Ethereum: **user-specified Gas Tip per transaction** * `maxPriorityFeePerGas` is applied as provided 2. Non-Authorized Accounts * **Fixed Gas Tip value set by governance** * Gas Tip is adjustable via GovValidator governance * Even if a higher `maxPriorityFeePerGas` is specified, the **governance-defined fixed Gas Tip is enforced** #### Base Fee Policy Unlike Ethereum EIP-1559, StableNet uses a **dual-threshold fixed-rate adjustment model**. **Base Fee Parameters** | Parameter | Value | Description | | ------------------- | --------------- | --------------------------- | | IncreasingThreshold | 20 | Increase if gas usage > 20% | | DecreasingThreshold | 6 | Decrease if gas usage \< 6% | | BaseFeeChangeRate | 2 | Adjustment rate (2%) | | MinBaseFee | 20,000 gwei | Minimum Base Fee | | MaxBaseFee | 20,000,000 gwei | Maximum Base Fee | **Base Fee Adjustment Rules** Base Fee is adjusted based on the **parent block’s gas usage**. 1. **Gas usage > 20%** * Increase Base Fee by **2%** * Roughly corresponds to >1,000 simple transfers per block 2. **6% ≤ Gas usage ≤ 20%** * **No change** to Base Fee 3. **Gas usage \< 6%** * Decrease Base Fee by **2%** * Roughly corresponds to \< 300 simple transfers per block Base Fee is always clamped within `MinBaseFee` and `MaxBaseFee`. ## Validator Summary Checklist **Setup** * Generate and securely store operator, validator, and BLS keys * Configure `config.toml` for the operational environment * Register the validator via governance * Set up monitoring and alerting **Operations** * Run validator nodes with `-mine` * Verify mining and block production * Monitor peer count and sync status * Track gas tip governance changes * Participate in governance proposals and voting **Maintenance** * Regularly back up configuration files and keys * Monitor disk space and system resources * Review logs for errors and warnings * Test upgrades on testnet before production rollout * Coordinate changes with other validators and governance members **Security** * Protect operator keys with multisig or cold storage * Encrypt validator and BLS keys * Enforce correct file permissions (`chmod 600`) * Restrict unnecessary network access via firewall rules * Conduct regular security reviews of access control and key management # Node Monitoring and Maintenance Source: https://docs.stablenet.network/en/operations-guide/11.3-node-monitoring-and-maintenance This document provides a practical guide for operating StableNet nodes, including metric collection, logging, disk space management, database maintenance, and common troubleshooting scenarios.\ The tools and procedures described here are intended to maintain node stability and to diagnose issues that arise in production environments. For validator-specific operations, refer to [Validator Operations](/en/operations-guide/11.2-validator-operations). For initial network deployment and configuration, refer to [Network Deployment](/en/operations-guide/11.1-network-deployment). ## Metrics Collection StableNet nodes expose a wide range of internal metrics to observe performance and operational status.\ The metrics system is implemented using the `go-metrics` library and provides real-time indicators for consensus processing, transaction handling, network status, and database behavior. In production environments, metric collection enables operators to monitor: * Block production and consensus latency * Transaction pool congestion * Peer connection stability * Database and state processing performance * Resource bottlenecks (CPU, memory, disk I/O) ### Enabling Metrics Metrics collection is controlled via command-line flags. | Flag | Description | Default | | --------------------- | -------------------------------------------------------- | -------- | | `--metrics` | Enable metric collection and exposure | Disabled | | `--metrics.expensive` | Enable expensive metrics (not recommended in production) | Disabled | | `--metrics.addr` | Metrics HTTP server bind address | None | | `--metrics.port` | Metrics HTTP server port | 6060 | **Example: running the default metrics server** ```bash theme={null} gstable --metrics --metrics.addr 0.0.0.0 --metrics.port 6060 ``` The metrics HTTP endpoint exposes Prometheus-compatible data at: `http://:/debug/metrics` In production environments, it is recommended not to expose the metrics server directly to the public network.\ Instead, restrict access via an internal network or a proxy. ### Exporting to InfluxDB Metrics can be exported to InfluxDB for long-term storage and time-series analysis.\ StableNet supports both InfluxDB v1 and v2. #### InfluxDB v1 Configuration | Flag | Description | | ----------------------------- | ------------------------------ | | `--metrics.influxdb` | Enable InfluxDB v1 export | | `--metrics.influxdb.endpoint` | InfluxDB API endpoint | | `--metrics.influxdb.database` | Database name | | `--metrics.influxdb.username` | Authentication username | | `--metrics.influxdb.password` | Authentication password | | `--metrics.influxdb.tags` | Comma-separated key/value tags | #### InfluxDB v2 Configuration | Flag | Description | | --------------------------------- | ------------------------- | | `--metrics.influxdbv2` | Enable InfluxDB v2 export | | `--metrics.influxdb.token` | Authentication token | | `--metrics.influxdb.bucket` | Bucket name | | `--metrics.influxdb.organization` | Organization name | **Examples:** ```bash theme={null} # InfluxDB v1 gstable --metrics --metrics.influxdb \ --metrics.influxdb.endpoint "http://localhost:8086" \ --metrics.influxdb.database "gstable_metrics" \ --metrics.influxdb.username "admin" \ --metrics.influxdb.password "secret" \ --metrics.influxdb.tags "host=node01,network=mainnet" # InfluxDB v2 gstable --metrics --metrics.influxdbv2 \ --metrics.influxdb.endpoint "http://localhost:8086" \ --metrics.influxdb.token "my-token" \ --metrics.influxdb.bucket "gstable" \ --metrics.influxdb.organization "my-org" ``` ### Available Metrics #### Key Metrics by Category | Category | Metric Name | Type | Description | Source | | -------------- | -------------------------------- | ------- | --------------------------------------------- | ---------------------- | | WBFT Consensus | `consensus/wbft/core/commitwork` | Timer | Block commit processing time | miner/worker.go | | Worker | `miner.newTxs` | Counter | Number of incoming transactions | miner/worker.go | | Worker | `miner.running` | Bool | Whether the block production worker is active | miner/worker.go | | Worker | `miner.syncing` | Bool | Whether the node is syncing | miner/worker.go | | Chain | Block insertion rate | Meter | Block insertion throughput | core/blockchain.go | | Chain | Reorg depth | Counter | Chain reorganization depth | core/blockchain.go | | TxPool | Pending transactions | Gauge | Executable transactions | core/txpool/legacypool | | TxPool | Queued transactions | Gauge | Queued (non-executable) transactions | core/txpool/legacypool | | P2P | Peer count | Gauge | Number of connected peers | p2p/server.go | | P2P | Ingress / Egress | Meter | Network traffic | p2p/server.go | | State | Trie cache hits | Counter | State cache hit count | core/state/statedb.go | | State | Commit time | Timer | State commit duration | core/state/statedb.go | #### StableNet / Anzeon-Specific Metrics In Anzeon (WBFT)-based networks, additional consensus-specific metrics are available: * Gas tip change events via governance * Epoch-based validator set changes * BLS signature verification latency * Round changes and timeout occurrences #### Worker State Monitoring The `worker` structure exposes several atomic variables that reflect block production and consensus processing state.\ These are critical for diagnosing why block production may have stalled on validator nodes. ## Logging StableNet uses a structured logging system, with configurable verbosity levels to control output detail. ### Log Levels | Level | Value | Description | | -------- | ----- | ----------------------------------------- | | Critical | 1 | Fatal errors requiring immediate action | | Error | 2 | Errors that may cause functional failure | | Warn | 3 | Warning conditions | | Info | 4 | General operational information (default) | | Debug | 5 | Detailed debugging logs | | Trace | 6 | Very detailed trace logs | ### Log Output Examples **Node startup logs:** ```text theme={null} INFO Starting Gstable on StableNet INFO Maximum peer count total=50 INFO Set global gas cap cap=50,000,000 ``` **Disk space warning logs:** ```text theme={null} WARN Disk space is running low available=50GiB ERROR Low disk space. Shutting down to prevent database corruption ``` ## Disk Space Management StableNet includes automatic disk space monitoring to prevent database corruption caused by insufficient disk space. ### Disk Space Thresholds The effective threshold is determined by one of the following: * Default: `2 * TrieDirtyCache` * Cache-based: `2 * --cache * --cache.gc / 100` * Explicit configuration: `--datadir.minfreedisk` ### Behavior 1. Free space ≥ 2× threshold: normal operation 2. Between 1× and 2×: periodic warning logs 3. \< 1×: node shutdown is triggered ### Platform-Specific Implementations | Platform | Implementation | System Call | | ------------ | -------------------------------- | ---------------------- | | Linux / Unix | `cmd/utils/diskusage.go` | `syscall.Statfs()` | | Windows | `cmd/utils/diskusage_windows.go` | `GetDiskFreeSpaceEx()` | | OpenBSD | `cmd/utils/diskusage_openbsd.go` | `syscall.Statfs()` | ## Database Maintenance ### Database Backends StableNet supports the following database backends: * LevelDB * Pebble ### Compaction * Automatic compaction runs in the background during normal operation. * Completion is logged. ```text theme={null} INFO Database compaction finished elapsed=5m30s ``` ### State Pruning * Offline pruning is supported only for the hash-based state schema * Requires the node to be stopped * If interrupted, recovery is attempted on the next startup ### Ancient Data (Freezer) * Data older than a certain block height is moved to ancient storage * Read-only with high compression efficiency * Grows continuously as the chain advances ## Node Health Monitoring StableNet tracks abnormal shutdowns. * A clean marker is written on normal shutdown * A warning log is emitted on restart after an abnormal shutdown ### Monitoring Checklist **Daily** * Synchronization completed * Peer count ≥ 10 * Available disk space check **Weekly** * Database size growth trend * Occurrence of abnormal shutdowns **Monthly** * Review log retention policies * Manage ancient data growth * Evaluate version upgrades ## Troubleshooting ### Node Synchronization Failure * Verify peer connectivity * Check firewall configuration * Confirm network ID and bootnode settings ### High Memory Usage * Review cache configuration * Check whether archive mode is enabled * Inspect system OOM logs ### Slow Block Processing * Check disk I/O bottlenecks * Inspect the `commitwork` metric * Review cache settings and CPU core availability ### Database Corruption * Stop the node immediately * Restore from backup or resynchronize * Consider switching to the Pebble backend for long-term stability By following these monitoring and maintenance practices, StableNet nodes can be operated reliably, and production issues can be diagnosed and resolved efficiently. # Operations Guide Source: https://docs.stablenet.network/en/operations-guide/index ## Purpose and Scope This guide provides operational guidelines for deploying, operating, and maintaining StableNet nodes and validator infrastructure.\ It covers network deployment procedures, validator operations, and overall node maintenance. For system architecture and component design, refer to the Core Architecture documentation.\ For detailed consensus behavior, see the Anzeon WBFT Consensus Protocol.\ For governance contract usage, refer to the Governance System documentation. ## Network Deployment ### Genesis File Creation The StableNet network is initialized using a genesis file generated by the `genesis_generator` tool.\ This tool creates the genesis block including Anzeon consensus parameters and system contracts. ```text theme={null} ``` ### Genesis Configuration Parameters StableNet genesis configuration defines consensus- and governance-specific parameters under the `anzeon` section. | Parameter | Location | Description | | ---------------------------- | ----------------------------------- | ----------------------------------------------- | | `wbft.epochLength` | `anzeon.wbft.epochLength` | Number of blocks per epoch (default: 10) | | `wbft.blockPeriodSeconds` | `anzeon.wbft.blockPeriodSeconds` | Target block time in seconds (default: 1) | | `wbft.requestTimeoutSeconds` | `anzeon.wbft.requestTimeoutSeconds` | Consensus timeout in seconds (default: 2) | | `wbft.proposerPolicy` | `anzeon.wbft.proposerPolicy` | Proposer selection policy (0 = round-robin) | | `init.validators` | `anzeon.init.validators` | Initial validator addresses for the first epoch | | `init.blsPublicKeys` | `anzeon.init.blsPublicKeys` | BLS public keys for each validator | | `systemContracts` | `anzeon.systemContracts` | System contract configuration | ### System Contract Initialization Each system contract is configured via initialization parameters at genesis.\ Below is a list of key system contracts and their initialization parameters. **GovValidator** (Address: `0x0000000000000000000000000000000000001001`) * `members`: Comma-separated list of operator addresses * `validators`: Comma-separated list of validator addresses * `blsPublicKeys`: List of validator BLS public keys (same order as `validators`) * `quorum`: Minimum number of votes required to approve governance actions * `expiry`: Governance proposal expiration time (seconds, default: 604800 = 7 days) * `gasTip`: Gas tip applied to transactions from non-authorized accounts (wei) **NativeCoinAdapter** (Address: `0x0000000000000000000000000000000000001000`) * `name`: Native token name (e.g. `"WKRC"`) * `symbol`: Native token symbol (e.g. `"WKRC"`) * `decimals`: Token decimals (typically `18`) * `currency`: Pegged fiat currency code (e.g. `"KRW"`) * `masterMinter`: GovMasterMinter contract address * `minters`: Comma-separated list of contracts with minting authority ### Bootnode Configuration StableNet networks use bootnodes for peer discovery.\ Bootnodes can be specified via the `--bootnodes` flag at runtime or via configuration files. **Bootnode example (`--bootnodes` flag)** ```text theme={null} --bootnodes enode://722f1f35c6fe2ac829aa9e0d7ef55bbe782ef3cea1e2354eefbe1584057a01b7@127.0.0.1:8589,enode://aa46e4a40781022e480bb05d1fd578fff164dc2ad379dc00370456c5ce9c2479@127.0.0.1:8589 ``` Bootnodes are selected in the following priority order: 1. Explicitly specified via the `--bootnodes` flag 2. `BootstrapNodes` defined in the configuration file 3. Network preset flags (`--mainnet`, `--testnet`) 4. Default mainnet bootnode configuration ### Network Flags and Configuration The following command-line flags are commonly used to deploy and run StableNet networks. | Flag | Purpose | Default | | -------------- | --------------------------------------------- | ---------------- | | `--datadir` | Data directory for databases and keystore | `~/.stable` | | `--mainnet` | StableNet mainnet | - | | `--testnet` | StableNet test network | - | | `--networkid` | Network ID (auto-detected from chain ID if 0) | 0 | | `--port` | P2P listening port | 30303 | | `--bootnodes` | Comma-separated enode URLs for bootstrap | Network-specific | | `--maxpeers` | Maximum number of peers | 50 | | `--nodiscover` | Disable peer discovery | false | | `--nat` | NAT port mapping mechanism | "any" | ## Validator Operations ### Validator Key Structure StableNet validators use three distinct cryptographic keys, each serving a different role in the consensus and governance systems. ### Key Generation and Management #### ECDSA Keys ECDSA keys are generated and managed using the standard Ethereum keystore format. ```bash theme={null} # Generate operator key (for governance) gstable account new --datadir /data/validator1 # Generate validator key (for block signing) gstable account new --datadir /data/validator1 --keystore /data/validator1/validator-keystore # Import an existing private key gstable account import private.key --datadir /data/validator1 ``` The derived public address is used as the node’s etherbase (coinbase) and must exactly match the address registered in `GovValidator.validators`. #### BLS Key Derivation BLS keys are deterministically derived from the validator’s ECDSA private key.\ This guarantees that the same ECDSA key always produces the same BLS key pair. ```go theme={null} // Derive a BLS key from an ECDSA private key blsKey, err := bls.DeriveFromECDSA(ecdsaPrivateKey) if err != nil { log.Fatal("Failed to derive BLS key", "err", err) } blsPublicKey := blsKey.PublicKey() ``` The derived BLS public key must be registered in `GovValidator.blsPublicKeys` at the same index as the corresponding validator address. ### Validator Registration Validators are registered in the `GovValidator` contract through governance proposals.\ Only registered validators can participate in consensus and block proposal. ### Starting a Validator Node The following example starts a validator node with mining enabled. ```bash theme={null} gstable \ --datadir /data/validator1 \ --networkid 8282 \ --mine \ --miner.etherbase 0xYOUR_VALIDATOR_ADDRESS ``` **Key validator flags:** | Flag | Purpose | | ------------------- | ---------------------------- | | `--mine` | Enable block production | | `--miner.etherbase` | Validator address (coinbase) | ### Validator Mining Process When a validator node starts mining, the following initialization sequence occurs: 1. **Load validator state** * Load the registered validator set from genesis and the latest chain state via `GovValidator`. * Verify that the node’s etherbase is part of the active validator set. 2. **Validate validator keys** * Ensure the address derived from the signing key matches the etherbase address. * Verify that the corresponding BLS public key is correctly registered in `GovValidator.blsPublicKeys`. 3. **Initialize the WBFT consensus engine** * Load Anzeon WBFT parameters (epoch length, block period, timeout, etc.) from genesis. * Apply the WBFT configuration for the current block height. 4. **Determine validator role** * Decide whether the node is the proposer for the current round based on the proposer policy. * If selected as proposer, prepare a block proposal. 5. **Start consensus message handling** * Activate network handlers for consensus messages. * Initialize signing and verification logic for each consensus phase, including BLS signature aggregation. 6. **Block production and consensus participation** * If proposer, propose a block including `WBFTExtra`. * If not proposer, validate the proposed block and broadcast signed messages according to the consensus phase. ### Gas Tip Policy In StableNet, the gas tip (priority fee) for non-authorized accounts is governed via on-chain governance and stored in the `GovValidator` contract.\ Gas tip application differs by account type. #### Authorized Accounts Authorized accounts follow the standard Ethereum model and directly specify `maxPriorityFeePerGas` per transaction. * Per-transaction gas tip configuration * The specified `maxPriorityFeePerGas` is applied as-is * Competitive prioritization during congestion * Not subject to the fixed gas tip policy defined by governance #### Non-Authorized Accounts Non-authorized accounts may also specify `maxPriorityFeePerGas`, but the value is **not used to determine the actual gas tip**. * Regardless of the transaction’s `maxPriorityFeePerGas`, the **fixed gas tip defined by governance** is applied * The transaction-specified gas tip is used **only for transaction replacement logic** * Transactions below the fixed gas tip are filtered out by the transaction pool #### Gas Tip Updates * Validators may propose updates to the fixed gas tip via governance proposals * Proposals require quorum approval and are applied immediately upon execution ### Epoch Transitions StableNet operates on epoch-based cycles, and validator set changes are applied only at epoch blocks. **Key points:** * Epoch length is configured via `anzeon.wbft.epochLength` (default: 10 blocks) * Validator set changes approved during epoch N become active at the start of epoch N+1 * The first epoch uses the validator set defined in `anzeon.init.validators` * Subsequent epochs load validator sets from `GovValidator.validators` ### Governance Participation Validators participate in governance using their operator keys.\ Governance manages network configuration and validator sets through proposals and voting. #### Proposal Types * `ADD_VALIDATOR`: Add a new validator to the set * `REMOVE_VALIDATOR`: Remove an existing validator * `SET_GAS_TIP`: Update the mandatory gas tip value * `CONFIGURE_SYSTEM`: Update system parameters and configuration #### Voting Process * Any governance member can submit a proposal via a contract call * Other members vote using `vote(proposalId, approve)` * Proposals are executed automatically upon reaching quorum * Proposals expire after the configured expiry period (default: 7 days) ## Node Monitoring and Maintenance ### Logging Configuration StableNet nodes use a structured logging system with configurable verbosity levels.\ Operators can configure global log levels, module-specific levels, and output formats. ```bash theme={null} # Set global log level gstable --verbosity 3 # 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=trace # Module-specific log levels gstable --vmodule "consensus/*=5,miner=4,eth/*=3" # File logging and rotation gstable --log.file /var/log/gstable/node.log --log.rotate # JSON-formatted logs for log aggregation gstable --log.json ``` **Key log modules to monitor:** | Module | Purpose | Important Events | | ----------------- | ---------------- | ----------------------------------------------------- | | `consensus/wbft` | WBFT consensus | Round changes, validator proposals, commit messages | | `miner` | Block production | Block sealing, transaction inclusion, gas tip updates | | `eth/handler` | Chain sync | Peer connections, block propagation, sync progress | | `core/blockchain` | Chain processing | Block insertion, reorgs, state root mismatches | | `eth/downloader` | Sync progress | Sync mode, peer selection, download rates | ### Metrics and Monitoring StableNet supports metrics collection and integration with external monitoring systems to ensure operational visibility. ```bash theme={null} # Enable metrics server gstable --metrics --metrics.addr 0.0.0.0 --metrics.port 6060 # Enable InfluxDB metrics export gstable \ --metrics.influxdb \ --metrics.influxdb.endpoint http://influxdb:8086 \ --metrics.influxdb.database gstable \ --metrics.influxdb.username monitor \ --metrics.influxdb.password secret ``` ### Disk Space Management StableNet nodes consume significant disk space to store blockchain data.\ Continuous monitoring and protective shutdown mechanisms are recommended for stable operation. #### Minimum Free Disk Space To prevent data corruption due to low disk space, a minimum free disk threshold can be configured.\ If available disk space falls below this threshold, the node shuts down automatically. ```bash theme={null} # Set minimum free disk space (in MB) gstable --datadir.minfreedisk 50000 # Shutdown if free space drops below 50 GB ``` The node periodically checks available disk space and performs a graceful shutdown when the threshold is reached. #### Database Size Monitoring Database usage varies by sync mode and pruning configuration.\ The table below shows typical database sizes and expected monthly growth. | Configuration | Approximate Size | Growth Rate | | ------------------- | ---------------- | ------------- | | Full node (archive) | 500+ GB | \~30 GB/month | | Full node (pruned) | 150–200 GB | \~10 GB/month | | Snap sync | 100–150 GB | \~8 GB/month | The following directories should be continuously monitored: * `chaindata/`: Main blockchain state and block database * `ancient/`: Freezer directory for old blocks (if configured separately) * `blobpool/`: Blob transaction pool data * `ethash/`: DAG storage (if Ethash consensus is used) #### Pruning and Garbage Collection When using the hash-based state scheme, pruning and garbage collection can be configured. ```bash theme={null} # Archive mode (no pruning) gstable --gcmode archive --cache.gc 0 # Full mode (pruning enabled) gstable --gcmode full --cache.gc 25 # Use 25% of cache for GC ``` Note: Path-based state databases use automatic pruning and do not support manual GC configuration. ### Database Maintenance #### State Scheme Selection StableNet supports two state storage schemes. Operators should select the appropriate scheme based on operational requirements. ```bash theme={null} # Hash-based scheme (traditional) gstable --state.scheme hash # Path-based scheme (recommended for new nodes) gstable --state.scheme path ``` **Advantages of the path-based scheme:** * Automatic state pruning * Lower disk usage * Improved synchronization performance **Advantages of the hash-based scheme:** * Mature and well-tested * Manual control over pruning and garbage collection * Suitable for environments requiring offline pruning tools #### Offline Pruning Recovery Nodes using the hash-based scheme automatically attempt recovery at startup if an interrupted pruning operation is detected. ```go theme={null} // Automatic recovery at startup if scheme == rawdb.HashScheme { if err := pruner.RecoverPruning(stack.ResolvePath(""), chainDb); err != nil { log.Error("Failed to recover state", "error", err) } } ``` This recovery process runs automatically during startup and restores database consistency after abnormal pruning interruptions. ### Chain Recovery and SetHead If blockchain state is corrupted or needs to be rolled back to a specific point, the `debug_setHead` RPC method can be used. ```bash theme={null} # Roll back to a specific block number gstable attach /data/gstable.ipc --exec 'debug.setHead("0x10000")' # Move to block 65536 # Roll back by number of blocks gstable attach /data/gstable.ipc --exec 'debug.setHead("0x-100")' # Move back 256 blocks ``` **Use cases:** * Recovery from corrupted block data * Rolling back after detecting chain anomalies * Rebuilding the chain on the correct fork after a network split **Warning:** `setHead` deletes all blocks and state data after the specified point.\ Always ensure a backup exists and fully understand the impact before use. ### Node Upgrade Procedure Node upgrades should be performed sequentially using the following steps: 1. **Stop the node** * Gracefully shut down the running `gstable` process. 2. **Replace binaries** * Back up the existing binary and replace it with the new version. * Verify execution permissions and binary paths. 3. **Review configuration files** * Check for new or modified configuration options in the new version. * Ensure compatibility with existing configuration files. 4. **Restart the node** * Restart the node with the same options. * For validator nodes, ensure the `--mine` flag is included. 5. **Inspect initial logs** * Review startup logs for database migrations, consensus initialization, and network connectivity issues. **Pre-upgrade checklist:** * Review release notes for breaking changes * Back up the database (`chaindata/` directory) * Test the upgrade on non-critical nodes first * For validator nodes, announce planned downtime to peers in advance **Post-upgrade verification:** ```bash theme={null} # Check node version gstable version # Check database version gstable --datadir /data version-check # Check synchronization status gstable attach --exec 'eth.syncing' # Check peer connectivity gstable attach --exec 'admin.peers.length' # For validator nodes, check mining status gstable attach --exec 'eth.mining' ``` ### Abnormal Shutdown Detection StableNet nodes detect abnormal shutdowns indirectly via database state and automatically run recovery mechanisms on startup. #### Abnormal Shutdown Handling * On startup, LevelDB WAL (Write-Ahead Log) is used to recover incomplete writes * Consistency between state database, snapshots, and ancient data is verified * If consistency cannot be restored automatically, resynchronization or state reconstruction may be triggered **Manual recovery after abnormal shutdowns:** ```bash theme={null} # Verify database integrity gstable --datadir /data verify-db # Rebuild indexes if necessary gstable --datadir /data rebuild-indexes ``` ### Bootnode Operations Dedicated bootnodes can be deployed to support peer discovery in StableNet networks. ```bash theme={null} # Generate bootnode key bootnode --genkey=boot.key # Run the bootnode bootnode \ --nodekey=boot.key \ --addr=:30303 \ --netrestrict=0.0.0.0/0 \ --verbosity=3 # Print enode URL bootnode --nodekey=boot.key --writeaddress ``` Bootnodes provide lightweight peer discovery services without maintaining full blockchain state.\ Clients can reference the bootnode as follows: ```bash theme={null} gstable --bootnodes enode://[nodekey-pubkey]@[ip]:30303 ``` ### Network Monitoring Dashboard For stable validator operations, it is recommended to configure dashboards with the following key metrics. **Validator Key Performance Indicators (KPIs)** | Metric | Target | Alert Threshold | | --------------------- | ---------------- | ------------------ | | Block production rate | \~1 block/second | \< 0.9 blocks/sec | | Missed blocks | 0% | > 1% | | Peer count | 10–50 | \< 5 peers | | Sync delay | \< 2 blocks | > 10 blocks behind | | Disk free space | > 100 GB | \< 50 GB | | Memory usage | \< 80% | > 90% | | CPU usage | \< 50% | > 80% sustained | # API Services and Namespaces Source: https://docs.stablenet.network/en/rpc-and-apis/8.1-api-services-and-namespaces ## Purpose and Scope This document describes the JSON-RPC API architecture of StableNet, including available API namespaces, service implementations, and the backend abstraction layer that connects API services to core blockchain components.\ The API system provides external access to node functionality via HTTP, WebSocket, and IPC transports. For information on event filtering and subscriptions, refer to [Event Filtering and Subscriptions](/en/rpc-and-apis/8.2-event-filtering-and-subscriptions). ## API Architecture Overview The StableNet RPC API follows a layered architecture in which API service implementations depend on a `Backend` interface.\ This design enables access to core blockchain functionality without tight coupling to the Ethereum backend. ## API Namespace Structure StableNet organizes its APIs into multiple namespaces, each with a clearly defined responsibility and purpose.\ Namespaces are registered via `internal/ethapi.GetAPIs`, `eth.Ethereum.APIs()`, node-level `apis()`, and the consensus engine (WBFT) `APIs()`, and are exposed externally through the RPC handler. ### API Namespace Mapping | Namespace | Service Implementation | Purpose | | ---------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `eth` | `EthereumAPI`, `BlockChainAPI`, `TransactionAPI`, `EthereumAccountAPI`, `DownloaderAPI` | Core protocol, blocks, transactions, synchronization | | `txpool` | `TxPoolAPI` | Transaction pool inspection | | `personal` | `PersonalAccountAPI` | Password-based account management and fee-delegated signing | | `debug` | `DebugAPI` (ethapi·eth·node) | Debugging and diagnostics | | `admin` | `AdminAPI` (node·eth) | Node and peer management | | `miner` | `MinerAPI` | Block production control | | `net` | `NetAPI` | Network information | | `web3` | `web3API` | Web3 utilities | | `istanbul` | `WBFT API` | WBFT consensus validators, signers, and status | ## eth Namespace The `eth` namespace provides core Ethereum protocol functionality and is composed of multiple API service classes. ### EthereumAPI Service `EthereumAPI` handles network state and fee-related queries. | Method | Description | | ------------------------ | ---------------------------------------------- | | `GasPrice()` | Returns gas price for legacy transactions | | `MaxPriorityFeePerGas()` | Returns priority fee for EIP-1559 transactions | | `FeeHistory()` | Returns historical fee data | | `Syncing()` | Returns node synchronization status | In StableNet with Anzeon enabled, `MaxPriorityFeePerGas` does not use a gas price oracle and instead returns the gas tip value enforced by the `GovValidator` contract. ### BlockChainAPI Service `BlockChainAPI` provides interfaces for querying blockchain state and data. | Method | Description | RPC Method | | ------------------------- | ---------------------------- | --------------------------- | | `ChainId()` | Returns chain ID | `eth_chainId` | | `BlockNumber()` | Returns current block number | `eth_blockNumber` | | `GetBalance()` | Queries account balance | `eth_getBalance` | | `GetCode()` | Queries contract code | `eth_getCode` | | `GetStorageAt()` | Queries a storage slot | `eth_getStorageAt` | | `GetProof()` | Returns Merkle proof | `eth_getProof` | | `GetBlockByNumber()` | Fetch block by number | `eth_getBlockByNumber` | | `GetBlockByHash()` | Fetch block by hash | `eth_getBlockByHash` | | `GetTransactionByHash()` | Fetch transaction | `eth_getTransactionByHash` | | `GetTransactionReceipt()` | Fetch transaction receipt | `eth_getTransactionReceipt` | ### TransactionAPI Service `TransactionAPI` is responsible for transaction creation, signing, and submission. | Method | Description | RPC Method | | ---------------------- | ------------------------------------- | ------------------------ | | `SendTransaction()` | Signs and submits a transaction | `eth_sendTransaction` | | `SendRawTransaction()` | Submits a signed transaction | `eth_sendRawTransaction` | | `SignTransaction()` | Signs a transaction only | `eth_signTransaction` | | `FillTransaction()` | Fills default transaction fields | `eth_fillTransaction` | | `EstimateGas()` | Estimates gas usage | `eth_estimateGas` | | `Call()` | Executes a call without state changes | `eth_call` | ## txpool Namespace `TxPoolAPI` provides read-only access to transaction pool state. | Method | Description | RPC Method | | --------------- | ----------------------------------------- | -------------------- | | `Content()` | Lists all transactions in the pool | `txpool_content` | | `ContentFrom()` | Lists transactions for a specific address | `txpool_contentFrom` | | `Status()` | Returns pending/queued counts | `txpool_status` | | `Inspect()` | Human-readable summary | `txpool_inspect` | Transactions are classified into two states: * **pending**: Eligible for inclusion in the next block * **queued**: Waiting due to nonce gaps or insufficient balance ## personal Namespace `PersonalAccountAPI` provides password-based account management.\ For security reasons, it is typically disabled on external RPC endpoints. | Method | Description | RPC Method | | ------------------- | ---------------------------------- | -------------------------- | | `NewAccount()` | Create a new account | `personal_newAccount` | | `ListAccounts()` | List accounts | `personal_listAccounts` | | `UnlockAccount()` | Unlock an account | `personal_unlockAccount` | | `LockAccount()` | Lock an account | `personal_lockAccount` | | `SendTransaction()` | Password-based transaction sending | `personal_sendTransaction` | | `SignTransaction()` | Password-based signing | `personal_signTransaction` | | `Sign()` | Sign arbitrary data | `personal_sign` | | `ImportRawKey()` | Import a private key | `personal_importRawKey` | ## debug Namespace `DebugAPI` provides advanced functionality for development and operational diagnostics. ### Major Feature Categories **Transaction and Block Tracing** * `TraceTransaction()` * `TraceBlock()` * `TraceBlockByNumber()` * `TraceBlockByHash()` * `TraceCall()` **State Inspection** * `DumpBlock()` * `AccountRange()` * `StorageRangeAt()` **Database Management** * `DbGet()` * `DbAncient()` * `ChaindbProperty()` * `ChaindbCompact()` **Profiling** * `CpuProfile()` * `BlockProfile()` * `MemStats()` * `GcStats()` ## web3 Namespace `web3API` provides basic Web3 utility functions. | Method | Description | RPC Method | | ----------------- | ------------------------ | -------------------- | | `ClientVersion()` | Returns client version | `web3_clientVersion` | | `Sha3()` | Computes Keccak-256 hash | `web3_sha3` | ## istanbul Namespace Exposed only when WBFT consensus is enabled. | Method | Description | RPC Method | | ----------------------------------- | ----------------------------------- | ------------------------------------------ | | `NodeAddress()` | Returns signer node address | `istanbul_nodeAddress` | | `GetCommitSignersFromBlock()` | Returns proposer and commit signers | `istanbul_getCommitSignersFromBlock` | | `GetCommitSignersFromBlockByHash()` | Query by block hash | `istanbul_getCommitSignersFromBlockByHash` | | `GetValidators()` | Returns validator list | `istanbul_getValidators` | | `GetValidatorsAtHash()` | Validators at a given hash | `istanbul_getValidatorsAtHash` | | `Status()` | Round and sealer statistics | `istanbul_status` | ## StableNet Fee Delegation Extensions For fee-delegated transactions, StableNet provides the following extended APIs in the `personal` and `eth` namespaces. | RPC Method | Description | | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `personal_signRawFeeDelegateTransaction` | Authenticates the fee payer using a password and appends a fee-payer signature to an already signed transaction, returning RLP-encoded bytes. | | `eth_signRawFeeDelegateTransaction` | Performs the same fee-delegation signing using an already unlocked fee-payer account. | The resulting signed transaction is submitted via `eth_sendRawTransaction`, and gas costs are paid by the fee payer. ## API Test Infrastructure The codebase includes the following test infrastructure: * Unit tests based on a mock backend * Genesis- and key-based integration tests * RPC serialization and response validation tests # Event Filtering and Subscriptions Source: https://docs.stablenet.network/en/rpc-and-apis/8.2-event-filtering-and-subscriptions ## Purpose and Scope This document describes the event filtering and subscription system designed to allow clients to efficiently query blockchain data and receive real-time notifications for new blocks, transactions, and logs.\ The system provides both traditional polling-based filters and WebSocket-based subscription mechanisms, supporting a wide range of client environments and usage patterns. For information on the general RPC API structure and namespaces, refer to [API Services and Namespaces](/en/rpc-and-apis/8.1-api-services-and-namespaces). ## Overview Through the filtering and subscription system, clients can use the following features: * Query historical logs that match specific conditions (contract addresses, topics, block ranges) * Receive real-time events for new blocks, pending transactions, and logs * Efficiently match logs over large block ranges using Bloom filters * Poll for changes using filter IDs * Use server-push–based subscriptions via WebSocket The implementation is primarily located in the `eth/filters` package and is tightly integrated with the blockchain event feed system. ## Filter API Methods `FilterAPI` provides RPC endpoints for creating, querying, and removing filters.\ This API supports both polling-based filters and WebSocket-based subscriptions. ### Core RPC Methods | Method | Description | Return Type | | --------------------------------- | ---------------------------------------------- | ------------- | | `eth_newFilter` | Create a condition-based log filter | Filter ID | | `eth_newBlockFilter` | Create a new block hash filter | Filter ID | | `eth_newPendingTransactionFilter` | Create a pending transaction filter | Filter ID | | `eth_getFilterChanges` | Retrieve changes since the last call | Logs / Hashes | | `eth_getFilterLogs` | Retrieve all logs matching the filter criteria | Logs array | | `eth_getLogs` | One-off log query | Logs array | | `eth_uninstallFilter` | Remove a filter | Boolean | ### Subscription Methods (WebSocket) | Method | Description | Event Type | | ----------------------------------------- | ----------------------------------- | ---------------- | | `eth_subscribe("newHeads")` | Subscribe to new block headers | Header | | `eth_subscribe("logs", criteria)` | Subscribe to logs matching criteria | Log | | `eth_subscribe("newPendingTransactions")` | Subscribe to pending transactions | Tx hash / object | | `eth_unsubscribe` | Unsubscribe | Boolean | ## System Architecture ### Component Overview The event filtering system is composed of two main components: `FilterSystem` and `EventSystem`. ### FilterSystem `FilterSystem` manages resources shared by all filter instances and serves as the entry point for filter creation. **Key Fields:** * `backend Backend` – Interface for accessing blockchain data * `logsCache *lru.Cache[common.Hash, *logCacheElem]` – Cache of recent block logs * `cfg *Config` – Cache size and timeout configuration The log cache stores logs from recently accessed blocks, reducing repeated database access and minimizing response latency. ### EventSystem `EventSystem` is a central event dispatcher that manages all active subscriptions and delivers blockchain events to the appropriate subscribers.\ It receives events from multiple event feeds and filters them according to subscription criteria before delivery. ## Filter Types and Execution ### Log Filters Log filters search for log events that match specified criteria within a given block range or within a single block. **FilterCriteria Structure:** | Field | Type | Description | | ----------- | ------------------ | --------------------------------- | | `FromBlock` | `*big.Int` | Starting block (nil means latest) | | `ToBlock` | `*big.Int` | Ending block (nil means latest) | | `BlockHash` | `*common.Hash` | Target a single block | | `Addresses` | `[]common.Address` | List of contract addresses | | `Topics` | `[][]common.Hash` | Topic filters | **Topic Matching Rules:** * Each position may contain multiple topics (OR condition) * If a position is nil, it always matches * AND conditions apply across positions * A maximum of 4 topic positions is supported ### Bloom Filter Optimization To improve performance when searching large log ranges, a two-stage Bloom filtering approach is used. 1. **Block Header Bloom** – A 2048-bit Bloom filter included in each block header 2. **Section Bloom Index** – Groups blocks into sections to support bit-level searching **Bloom Filter Algorithm Overview:** ```text theme={null} Hash = Keccak256(data) For i in [0, 2, 4]: BitIndex = (Uint16(Hash[i:i+2]) & 0x7FF) >> 3 BitOffset = Hash[i+1] & 0x7 Bloom[BitIndex] |= (1 << BitOffset) ``` ## Subscription Lifecycle ### Polling-Based Filters In environments where WebSocket is not available, the server maintains filter state and clients periodically poll for changes. **Filter Timeout Management:** * The default timeout is 5 minutes * The timer is refreshed on each `eth_getFilterChanges` call * Filters are automatically removed after a period of inactivity This mechanism prevents resource leaks caused by long-abandoned filters. ## Event Delivery and Filtering ### Chain Reorganization Handling When a chain reorganization occurs, the system generates a `RemovedLogsEvent` and delivers it to subscribers. The processing flow is as follows: 1. Detect a chain reorganization during block insertion 2. Generate events with logs from removed blocks 3. Set the `Removed: true` flag on log objects 4. Clients adjust their state based on the removed logs ## Backend Integration The filter system abstracts blockchain data access through the `Backend` interface.\ This allows the same filter logic to be reused without being tightly coupled to a specific full node implementation. Key backend implementations delegate responsibilities to the following components: * Historical block data – `BlockChain` * Pending transactions – `TxPool` * Pending block construction – `Miner` * Bloom bit searching – `BloomIndexer` ## Error Handling and Edge Cases | Error | Cause | Handling | | ---------------------- | ------------------------------------- | ---------------------- | | `errInvalidBlockRange` | Start block is greater than end block | Reject filter creation | | `errFilterNotFound` | Filter ID does not exist | Return empty result | | `errExceedMaxTopics` | Exceeded maximum topic positions | Reject filter creation | | `unknown block` | Block hash not found | Return error | | Context cancel | Connection closed | Abort query | Through this error-handling logic, the system ensures stable and reliable event delivery. # RPC and APIs Source: https://docs.stablenet.network/en/rpc-and-apis/index ## Purpose and Scope This document describes the RPC (Remote Procedure Call) server architecture and API layer of go-stablenet. It covers RPC endpoint configuration, available API namespaces, the backend abstraction layer, event filtering and subscriptions, and transaction submission mechanisms. The RPC layer provides an external interface for interacting with blockchain nodes via JSON-RPC over HTTP, WebSocket, or IPC transports. For information on P2P networking and protocol handlers, refer to [Networking](/en/networking/index). For details on node initialization and lifecycle management, refer to [Node Initialization and Lifecycle](/en/core-architecture/3.1-node-initialization-and-lifecycle). ## RPC Server Configuration The node supports three RPC transport mechanisms: HTTP, WebSocket (WS), and Inter-Process Communication (IPC). Each transport can be independently enabled and configured via command-line flags or configuration files. ### Transport Configuration | Transport | Enable Flag | Address Flag | Port Flag | Default Port | | --------- | -------------------- | ------------- | ------------- | ------------- | | HTTP | `--http` | `--http.addr` | `--http.port` | 8545 | | WebSocket | `--ws` | `--ws.addr` | `--ws.port` | 8546 | | IPC | (enabled by default) | `--ipcpath` | N/A | `gstable.ipc` | **Key Configuration Flags:** * `--http.api`: Comma-separated list of API namespaces exposed over HTTP (e.g., "eth,net,web3") * `--ws.api`: API namespaces for the WebSocket interface * `--http.corsdomain`: CORS domains for HTTP requests * `--ws.origins`: Allowed origins for WebSocket connections * `--http.vhosts`: Virtual hostnames allowed by the HTTP server * `--ipcdisable`: Disable the IPC-RPC server **Security and Limits:** * `--rpc.gascap`: Gas cap for `eth_call` and `eth_estimateGas` (default: 50,000,000) * `--rpc.evmtimeout`: Execution timeout for `eth_call` (default: 5 seconds) * `--rpc.txfeecap`: Transaction fee cap in ether (default: 0, no cap) * `--rpc.batch-request-limit`: Maximum number of requests in a batch * `--rpc.batch-response-max-size`: Maximum response size in bytes for batch responses * `--allow-insecure-unlock`: Allow account unlocking over HTTP (disabled by default for security reasons) ## RPC Server Initialization Flow During node initialization, the RPC server follows these steps: parsing transport configuration, determining API namespaces, creating the Backend instance, initializing the RPC server, binding transport-specific listeners, and registering APIs. ## Core API Namespaces ### eth Namespace The `eth` namespace provides the primary interface for blockchain state queries, transaction submission, and gas estimation. | Method | Description | | -------------------------- | ------------------------------------------ | | `eth_chainId` | Returns the chain ID | | `eth_blockNumber` | Returns the current block number | | `eth_getBalance` | Retrieves account balance | | `eth_getStorageAt` | Retrieves a storage slot value | | `eth_getCode` | Retrieves contract code | | `eth_getTransactionCount` | Retrieves account nonce | | `eth_call` | Executes an EVM call without state changes | | `eth_estimateGas` | Estimates gas for a transaction | | `eth_sendRawTransaction` | Submits a signed transaction | | `eth_gasPrice` | Returns a suggested legacy gas price | | `eth_maxPriorityFeePerGas` | Returns the EIP-1559 priority fee | | `eth_feeHistory` | Returns fee history | ### txpool Namespace The `txpool` namespace provides diagnostic APIs for inspecting the internal state of the transaction pool. ### admin Namespace The `admin` namespace provides node management functions, including peer management and RPC server control. This namespace should never be exposed on public RPC endpoints. ### debug Namespace The `debug` namespace provides advanced debugging features such as transaction tracing, state dumps, chain rewinding, and database diagnostics. ### personal Namespace The `personal` namespace provides local account-based signing functionality and is disabled by default for security reasons. ### miner Namespace The `miner` namespace provides block production, sealing control, and gas policy configuration functions. ### net Namespace The `net` namespace provides basic network information such as the network ID and peer connectivity status. ### web3 Namespace The `web3` namespace provides auxiliary utility APIs such as client version (`web3_clientVersion`) and SHA3 hashing (`web3_sha3`). ### istanbul Namespace The `istanbul` namespace exposes RPCs from the Anzeon/WBFT consensus engine, providing consensus-related queries such as validators, block signers, and round statistics. ## Event System and Filtering The RPC filter system provides new block, log, and pending transaction events via polling-based filters or WebSocket-based subscriptions. ### Log Filter Criteria Structure ```go theme={null} type FilterCriteria struct { BlockHash *common.Hash FromBlock *big.Int ToBlock *big.Int Addresses []common.Address Topics [][]common.Hash } ``` ## Summary The go-stablenet RPC and API layer provides multi-transport support, a comprehensive set of namespaces, an efficient event system, flexible transaction submission mechanisms, and strong security controls. It maintains compatibility with the standard Ethereum JSON-RPC while integrating StableNet-specific features. # StableNet Overview Source: https://docs.stablenet.network/en/stablenet-overview/index ## Purpose and Scope This document provides an overview of the StableNet blockchain protocol, its relationship with go-ethereum, and the key features added to support stablecoin operations. It includes the Anzeon WBFT consensus mechanism architecture, as well as system contracts that implement governance and stablecoin functionality. For detailed information on each subsystem, refer to the following documents: * Node configuration and startup: [Getting Started](/en/getting-started/index) * Consensus protocol details: [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol) * System contract specifications: [Governance System](/en/governance-system/index) * Gas fee mechanism: [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy) ## StableNet Overview StableNet is an EVM-compatible blockchain built as a fork of the WBFT protocol (originally derived from go-wbft). WBFT is an enhanced version of QBFT, and StableNet is designed for stablecoin operations using a Proof-of-Authority (PoA) architecture with Byzantine Fault Tolerance (BFT) consensus. The codebase extends go-ethereum in the following ways: * **Anzeon WBFT Consensus Engine** – Performs BFT consensus based on a validator set determined through governance, leveraging BLS signature aggregation to improve the efficiency of consensus message verification. * **Five system contracts** — Deployed at genesis and composed of NativeCoinAdapter (an ERC-20 wrapper for the native coin), GovValidator, GovMasterMinter, GovMinter, and GovCouncil. These contracts manage validator and minting governance while ensuring compatibility with stablecoin services by exposing an USDC-compatible interface. * **Stablecoin-Optimized Gas Policy** – Provides governance-controlled priority fees and a stable base fee mechanism. ## Architecture Foundation StableNet preserves the core go-ethereum architecture while adding StableNet-specific consensus and governance layers. ### Diagram: StableNet Component Stack Image Core Ethereum components (BlockChain, StateDB, EVM, TxPool) are retained, while Anzeon WBFT acts as the consensus engine. System contracts are deployed at genesis and can only be upgraded via hard forks. ## Core Components ### Consensus Engine: Anzeon WBFT Anzeon WBFT is a Byzantine Fault Tolerant consensus protocol tailored to StableNet’s stablecoin-centric requirements. Unlike WBFT for public blockchains, it is optimized as follows: * **No staking** – Validators are managed through governance. * **No block rewards** – Maintains a non-inflationary token supply. * **Governance-based validator selection** – Determined by voting in the GovValidator contract. * **Genesis-based activation** – Not activated via mid-chain forks. Consensus proceeds through the PREPARE → COMMIT → FINALIZATION stages, with BLS signature aggregation improving message verification efficiency. For detailed protocol behavior, refer to [Anzeon WBFT Consensus Protocol](/en/consensus-and-block-production/4.1-anzeon-wbft-consensus-protocol). ### System Contract Architecture Five system contracts are deployed at fixed addresses at genesis to manage the protocol: Image #### Contract Responsibilities * **NativeCoinAdapter** – Native ERC20 wrapper * **GovValidator** – Gas tip and validator management * **GovMasterMinter** – Minter registration * **GovMinter** – Mint/burn voting * **GovCouncil** – Blacklist and authorized account management For details, refer to [Governance System](/en/governance-system/index). For NativeCoinAdapter specifics, see the “NativeCoinAdapter” section below. ### NativeCoinAdapter (Bridging Native Coin and ERC20) NativeCoinAdapter provides an ERC20 interface over native balances without separate storage. It is compatible with the FiatTokenV2\_2 specification (Circle USDC), allowing existing dApps to use the stablecoin without modification. ## Stablecoin-Specific Features ### Base Coin Policy Unlike traditional blockchains that pre-mint the base coin at genesis, StableNet implements dynamic supply management: * **Minimal genesis issuance** – Only the funds required for initial operations are issued. * **Minter-controlled supply** – Approved minters can mint and burn tokens throughout operation. * **Oracle role** – Minters verify fiat deposits and withdrawals in traditional financial systems. * **No inflation** – There are no block rewards; total supply changes only via minting and burning. * **Auditable supply** – Total issuance always matches on-chain balances, with no hidden inflation. ### Mint/Burn Protocol Minting and burning are executed via quorum-based voting, preventing unilateral actions by a single minter and maintaining 1:1 fiat backing. ### Gas Fee Policy StableNet modifies EIP-1559 to preserve stablecoin stability. The Base Fee adjusts based on network utilization and is paid to validators instead of being burned. The Priority Fee is determined through GovValidator governance, and regular accounts must follow a mandatory tip. For details, refer to [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy). ## Genesis Configuration The genesis block initializes consensus timing (`anzeon.wbft`), initial validators (`anzeon.init`), and the configuration of the five system contracts. The `genesis_generator` CLI can be used to generate an appropriate genesis file. For detailed configuration, refer to [Getting Started](/en/getting-started/index). ## Node Architecture Nodes initialize in the following order: load configuration → initialize genesis → set up P2P, blockchain, and consensus backends → start services. For detailed configuration and execution instructions, refer to [Getting Started](/en/getting-started/index). ## Development Tools Key tools for working with StableNet include: * **gstable** – Main client binary (equivalent to geth functionality) * **genesis\_generator** – Interactive genesis file generation tool * **bootnode** – Lightweight discovery node for private networks * **devp2p** – P2P network testing and DNS discovery deployment * **clef** – External signer for secure key management # Database Layer and Merkle Patricia Trie Source: https://docs.stablenet.network/en/storage-architecture/9.1-database-layer-and-merkle-patricia-tries ## Purpose and Scope This document explains the Merkle Patricia Trie data structure used to store trie nodes in StableNet and the underlying database layer.\ The trie provides a cryptographically authenticated key-value store with efficient lookups, proof generation, and deterministic root hash computation. Main topics covered: * **Trie Structure**: Node types (shortNode, fullNode, valueNode, hashNode) and tree composition * **Node Encoding**: Key encoding schemes (keybytes, hex, compact) and RLP serialization * **Trie Database**: Storage schemas (hash-based, path-based) and node persistence * **Merkle Proofs**: Proof generation, verification, and use cases For how StateDB uses these tries for state management, see [State Management](/en/core-architecture/3.3-state-management).\ For snapshot-based optimizations, see [Caching and Snapshots](/en/storage-architecture/9.2-caching-and-snapshots).\ For the ancient store handling historical block data, see [Ancient Store and Data Lifecycle](/en/storage-architecture/9.3-ancient-store-and-data-lifecycle). ## Merkle Patricia Trie Overview The Merkle Patricia Trie is a cryptographically authenticated data structure that combines properties of Merkle trees and Patricia tries (radix trees). It enables: * **Efficient key-value storage and lookup** with O(log n) complexity * **State commitment** via Merkle root hashing * **State proof generation** without holding the entire state * **Deterministic root computation** where all nodes derive the same result StableNet uses tries for two purposes: 1. **Account Trie**\ Maps account addresses to account state (balance, nonce, storage root, code hash). 2. **Storage Trie**\ Each contract account has an independent storage trie mapping storage slots to values. ## Trie Node Types ### Node Type Description | Node Type | Purpose | Structure | Usage | | ------------- | ------------------------------ | ---------------------- | ------------------------------------ | | **shortNode** | Common prefix path compression | `Key []byte, Val node` | When multiple keys share a prefix | | **fullNode** | Branch node | `Children [17]node` | 16 nibble branches + value slot | | **valueNode** | Leaf value | `[]byte` | Stores the actual RLP-encoded value | | **hashNode** | Compact reference | 32-byte hash | References a sub-trie stored on disk | The `nodeFlag` structure manages the cache state of a node: ```text theme={null} type nodeFlag struct { hash hashNode // cached hash of the node dirty bool // whether the node has been modified } ``` ## Key Encoding Schemes The trie uses three key encoding formats for different purposes. ### Encoding Formats | Format | Description | Usage | Example (key = 0x123) | | ------------ | ------------------------- | ------------------------ | --------------------- | | **keybytes** | Raw bytes | External APIs | `[0x12, 0x03]` | | **hex** | Nibble array + terminator | Internal trie operations | `[1, 2, 3, 16]` | | **compact** | Compressed nibble format | Serialization / proofs | nibbles + flag bits | The hex format represents each 4-bit nibble as a byte, where the value `16` indicates the end of the path.\ The compact format compresses nibbles and encodes leaf/extension information and length in flag bits. ## 2-Trie Architecture ### Account Trie The account trie uses the **Keccak256-hashed address** as the key.\ The value is the RLP-encoded `types.StateAccount` structure. ### Storage Trie Each contract has its own storage trie, structured as follows: * **Owner**: Keccak256 hash of the account address * **Key**: Keccak256 hash of the storage slot * **Value**: RLP-encoded storage value (leading zeros removed) ## Trie Operations ### Get Operation `Trie.get()` recursively traverses nodes from the root.\ When encountering a `hashNode`, it loads the referenced node from the database. ### Update Operation Updates do not immediately compute hashes. Nodes are marked dirty instead.\ Actual hashing occurs during the commit phase, and the `unhashed` counter tracks the number of unhashed leaves. ### Delete Operation Delete removes a key-value pair.\ Branch nodes with only a single remaining child are collapsed into a shortNode. ## Hashing and Commit ### Hasher Component The `hasher` performs top-down hash computation: 1. Recursively hash child nodes 2. Collapse nodes into `hashNode` if the RLP-encoded size is ≥ 32 bytes 3. Serialize the node structure with RLP 4. Compute the Keccak256 hash 5. Cache the result in `nodeFlag.hash` ### Committer Component The `committer` traverses the fully hashed trie and collects dirty nodes. **Output:**\ `trienode.NodeSet` – a set mapping paths to node data, used for database writes. ## State Root Calculation The state root is calculated through the following steps: 1. **Finalise**\ Move dirty storage to pending and update storage roots 2. **updateRoot()**\ Apply per-account storage trie roots 3. **updateStateObject()**\ Write account data into the account trie 4. **IntermediateRoot()**\ Hash the account trie 5. **Commit()**\ Commit all tries and generate the NodeSet ## Proof Generation and Verification ### Proof Structure A Merkle proof consists of a sequence of RLP-encoded nodes from the root to a specific leaf. * **Proof size:** O(log n)\ Approximately 500–2000 bytes for Ethereum state **Use Cases:** * Light client state verification * State synchronization * Storage proofs for cross-chain bridges ## Trie Database Layer The trie database layer persists trie nodes to disk and resolves `hashNode` or path-based references into actual nodes. StableNet supports two storage schemas. ### Hash-Based Schema (Legacy) **Node key:** `Keccak256(RLP(node))` ```text theme={null} Key: 32-byte hash Value: RLP-encoded node ``` **Characteristics:** * Simple key-value structure * No path information retained * Requires garbage collection * Inefficient for historical state access ### Path-Based Schema (Modern) **Node key:** `owner_hash + path_from_root` ```text theme={null} Key: owner (32 bytes) + path Value: RLP-encoded node ``` **Characteristics:** * Path-based addressing * Supports state history and fast rollbacks * Change tracking via diff layers * Suitable for archive nodes ## Integration with State Management ### Operation Flow **Account Access:** 1. Check StateDB cache 2. Load from snapshot or account trie 3. Decode `types.StateAccount` 4. Create `stateObject` **Storage Access:** 1. Lookup in dirty → pending → origin order 2. Fallback to storage trie on miss 3. RLP decoding **Commit Flow:** 1. `Finalise()` 2. `updateRoot()` 3. `updateStateObject()` 4. `Commit()` 5. `triedb.Update()` ## Key Implementation Details ### Trie Prefetching `triePrefetcher` asynchronously preloads nodes likely to be accessed during transaction execution to reduce latency. ```text theme={null} - Spawn goroutines per storage trie - Prefetch based on expected access paths - Improves transaction execution performance ``` ### Node Iterator `nodeIterator` traverses all trie nodes using a pre-order traversal. ```text theme={null} - Used for state synchronization - Used for proof generation - Lazily loads hashNodes - Maintains path and stack ``` ### Tracer `tracer` tracks trie modifications for use in path-based schemas and debugging. ```text theme={null} - Records insertions and deletions - Maps access paths - Essential component for path-based DB ``` **Summary:**\ The Merkle Patricia Trie is the core cryptographic structure of the StableNet state store.\ Through the dual account/storage trie design and flexible storage schemas, StableNet efficiently and securely supports historical state access and light client verification. # Caching and Snapshots Source: https://docs.stablenet.network/en/storage-architecture/9.2-caching-and-snapshots ## Purpose and Scope This document describes the multi-layer caching mechanisms and snapshot system used in StableNet to optimize state access.\ The caching architecture ranges from in-memory LRU caches for frequently accessed data to a state snapshot system that provides fast access to account and storage data without traversing the trie. For the underlying Merkle Patricia Trie data structure and database interfaces, see [Database Layer and Merkle Patricia Trie](/en/storage-architecture/9.1-database-layer-and-merkle-patricia-tries).\ For historical data management and archive strategies, see [Ancient Store and Data Lifecycle](/en/storage-architecture/9.3-ancient-store-and-data-lifecycle). ## StateDB Caching Architecture StateDB acts as the top-level caching layer for all blockchain state and maintains multiple in-memory data structures to minimize repeated and expensive trie and database accesses during transaction execution. ### Account and Storage Cache Maps StateDB maintains the following cache maps to track state changes during block execution: | Cache Map | Type | Purpose | | ---------------------- | ------------------------------------------- | ----------------------------------------------- | | `stateObjects` | `map[common.Address]*stateObject` | Live account objects modified during execution | | `accounts` | `map[common.Hash][]byte` | Slim RLP-encoded account data for commit | | `storages` | `map[common.Hash]map[common.Hash][]byte` | Storage slot changes to be committed | | `accountsOrigin` | `map[common.Address][]byte` | Pre-change account state (for diff computation) | | `storagesOrigin` | `map[common.Address]map[common.Hash][]byte` | Pre-change storage state (for diff computation) | | `stateObjectsPending` | `map[common.Address]struct{}` | Objects finalised but not yet applied to trie | | `stateObjectsDirty` | `map[common.Address]struct{}` | Objects modified in the current execution | | `stateObjectsDestruct` | `map[common.Address]*types.StateAccount` | Accounts self-destructed within the block | `stateObjects` is the **live state object cache** maintained during execution of the current block.\ Each account is loaded only once on first access and reused thereafter. **Account loading flow summary:** 1. Check the `stateObjects` cache 2. If missing, attempt to load from snapshot 3. If snapshot is unavailable or misses, load from trie 4. Create a `stateObject` wrapper 5. Cache in `stateObjects` and return ### State Object Storage Caching Each `stateObject` maintains a **three-tier storage cache** for storage slot access. Storage tiers and their roles: * **dirtyStorage**\ Slots modified in the current transaction. Cleared at transaction end. * **pendingStorage**\ Changes that are finalised but not yet committed to the trie. * **originStorage**\ Baseline state loaded from snapshot or trie. This structure guarantees: * Transaction-level rollback capability * Avoidance of duplicate trie writes for the same slot * Accurate diff computation of state changes ## State Snapshot System The snapshot system provides a **flat state representation** that allows account and storage data to be queried without directly traversing the Merkle Patricia Trie.\ It plays a critical role in both snap synchronization and normal block execution performance. ### Snapshot Architecture The snapshot system consists of three components: 1. **Disk Layer**\ A persistent snapshot at a specific block height, holding flat mappings of\ account hash → account data, and storage hash → storage value. 2. **Diff Layers**\ In-memory chained layers that store per-block state changes.\ Only modified accounts and storage slots are stored. 3. **Snapshot Tree**\ Manages snapshots per state root and provides the `Snapshot(root)` interface. ### Snapshot-Based State Access When snapshots are enabled, StateDB queries state in the following order: * Account lookup: `snap.Account(hash)` * Storage lookup: `snap.Storage(addrHash, slotHash)` * Fallback to trie only on miss Performance benefits of this approach: * No trie node decoding * No hash verification * Direct access to flat structures * Typically **10–100× faster** account lookups ## Trie Prefetcher The trie prefetcher proactively loads trie nodes that are likely to be accessed during transaction execution, reducing commit latency. Execution flow: 1. `StartPrefetcher()` is called at block execution start 2. Modified storage slot information is collected during `finalise()` 3. Worker goroutines asynchronously load trie nodes along those paths 4. Cached tries are reused during `IntermediateRoot()` or commit 5. `StopPrefetcher()` is called at block end for cleanup The prefetcher operates **in parallel with execution** and does not increase transaction latency. ## Journal and Snapshot Rollback StateDB supports rolling back to previous states at any point during transaction execution via journal-based change tracking. Each state change is recorded as a `journalEntry`, including: * Balance changes * Nonce changes * Code changes * Storage updates * Selfdestruct operations * Account creation When `Snapshot()` is called, the current journal length is recorded.\ Calling `RevertToSnapshot()` replays the journal in reverse to restore state. This mechanism is essential for: * EVM `REVERT` * Out-of-gas handling * Exception recovery * Speculative execution ## State Commit and Cache Management State commit proceeds in three stages. ### Stage 1: Finalise * Clean up dirty objects * Process selfdestructs * Move `dirtyStorage` → `pendingStorage` * Clear the journal ### Stage 2: IntermediateRoot * Hash storage tries of all pending objects * Update the account trie * Compute the intermediate state root ### Stage 3: Commit * Commit all storage tries * Commit the account trie * Generate a `NodeSet` for modified nodes * Persist changes in batch via `triedb.Update()` ## Fast Storage Deletion Deleting large storage tries via full traversal is inefficient.\ StateDB provides a **fast deletion path** using snapshots. How it works: 1. Iterate flat storage slots from the snapshot 2. Build an in-memory StackTrie 3. Generate delete markers for each node 4. Fallback to the slow path if size limits are exceeded 5. Return a `NodeSet` containing delete markers This approach operates entirely in memory without disk access. ## StateDB Copy Semantics `StateDB.Copy()` is used for parallel execution and speculative state creation. **Shared (read-only):** * Database interface * Snapshot tree * Base tries **Deep-copied (writable):** * State object maps * Change-tracking maps * Journal * Logs and preimages * Access lists and transient storage This design enables: * Parallel transaction execution * Minimal memory duplication * Complete isolation between state instances ## Performance Metrics and Instrumentation StateDB collects detailed metrics across state processing. Example metrics include: * Account and storage read latency * Trie hashing time * Commit time * Snapshot access time * Number of updates and deletions These metrics are used for: * Bottleneck identification * Cache hit-rate analysis * Snapshot effectiveness validation * Performance regression detection ## Cleanup and Cache Eviction ### Snapshot-Based Cleanup * Merge old diff layers * Refresh the disk layer * Optionally remove obsolete trie nodes ### Cache Eviction Strategies * Trie node LRU caches * Separation of clean and dirty caches * Dirty caches evicted after commit ### Memory Management * Journal cleanup at transaction end * Reset pending objects * Stop prefetcher * Structure sharing during StateDB copies These mechanisms ensure that memory usage remains bounded even in long-running environments. # Ancient Store and Data Lifecycle Source: https://docs.stablenet.network/en/storage-architecture/9.3-ancient-store-and-data-lifecycle ## Purpose and Scope This document describes the ancient store subsystem (commonly referred to as the “freezer”) in go-stablenet and how it manages the storage lifecycle of historical blockchain data. The ancient store is an **append-only archive storage layer** that separates and preserves old block data in order to optimize performance and disk usage of the active database. This page covers: * Ancient store architecture and its separation of roles from the active database * Data migration flow from the active store to the ancient store * Ancient store operations (read, write, truncate) * Chain rewind handling when frozen data exists * Importing and exporting historical data using the Era1 format For the active database layer and trie storage, see [Database Layer and Merkle Patricia Trie](/en/storage-architecture/9.1-database-layer-and-merkle-patricia-tries).\ For caching and snapshots, see [Caching and Snapshots](/en/storage-architecture/9.2-caching-and-snapshots). ## Ancient Store Architecture The ancient store is a dedicated storage for historical blockchain data that has become **immutable**.\ This layer is designed to improve performance and disk efficiency with the following characteristics: * Append-only write model * Sequential access by block number * Physical and logical separation from the active key-value database * Minimized random-access cost for old data ### Storage Layers Blockchain data is divided into two main layers: * **Active Database**\ Recent blocks, state (tries), headers, transaction indices, and other data\ that require frequent random access and writes * **Ancient Store**\ Blocks, receipts, and total difficulty data that are sufficiently old and no longer mutable ### Database Interface The `ethdb.Database` interface provides a unified access point for both the active and ancient stores: | Method | Description | Storage Layer | | ---------------------------- | ------------------------------------ | --------------- | | `Ancients()` | Returns the number of frozen blocks | Ancient store | | `TruncateHead(n)` | Removes ancient data after block `n` | Ancient store | | `Get(key)` / `Put(key, val)` | Key-value read/write | Active database | | `NewBatch()` | Create a batch write | Active database | Although accessed via the same DB handle, the ancient store uses a separate internal implementation optimized for **sequential, immutable data**. ## Data Lifecycle and Migration ### Block Data States Blockchain data transitions through the following stages depending on block age and state availability: 1. **Active State**\ Recent blocks that must support state (trie) access and rewinds 2. **Transitional State**\ State is no longer needed, but data has not yet moved to the ancient store 3. **Frozen State**\ State access is no longer required; data is considered immutable and stored in the ancient store ### Freezer Threshold The freezer threshold defines the point at which blocks are migrated to the ancient store.\ Blocks below this threshold are considered **ineligible for state recovery during rewinds**. Key considerations: * **State availability**\ Blocks requiring state (tries) must remain in the active database * **`TriesInMemory` constant**\ Typically, the most recent \~128 blocks are kept in the active DB * **Snap synchronization**\ During snap sync, the pivot block may affect the freezer boundary * **Full synchronization**\ Once state is no longer required, old blocks are migrated sequentially ## Ancient Store Operations ### Reading Ancient Data When accessing old blocks, the BlockChain logic transparently reads data from the ancient store. From the perspective of higher layers, there is no need to explicitly distinguish whether data resides in the active DB or the ancient store. ### Writing and Truncation Modifications to the ancient store occur only in limited scenarios: 1. **Chain rewind (`SetHead`)**\ When rewinding below the frozen threshold 2. **Historical data import**\ When injecting past data via Era1 archives `TruncateHead` removes data **after a given block number** from the ancient store. ## Chain Rewind with Ancient Data ### Rewind Process When rewinding the chain (`SetHead`, `SetHeadWithTimestamp`),\ special handling is required for frozen data. | Scenario | Active DB Action | Ancient Store Action | | ------------------------------ | ---------------------------- | ----------------------- | | Target above freezer threshold | Delete active blocks/headers | None | | Target below freezer threshold | Delete all active blocks | Truncate ancient store | | Rewind to genesis | Reset active DB | Remove all ancient data | This logic is implemented in the `setHeadBeyondRoot` flow. ### Handling Missing State During rewind, the system must locate a block **with available state**: 1. Check `HasState(root)` or `stateRecoverable(root)` 2. If state is missing, move to the parent block 3. Rewinds below the snap pivot are prohibited 4. If recoverable, attempt `triedb.Recover(root)` ### Safety of Ancient Truncation Ancient truncation follows strict safety rules: * Executed via a single `TruncateHead` call * Active DB cleanup performed first * Hash/number mappings of removed blocks deleted * Chain head markers updated atomically ## Importing and Exporting Historical Data ### Era1 Archive Format go-stablenet uses the Era1 format to bundle historical blockchain data. | Component | Content | Purpose | | ---------------- | --------------------- | ----------------------------- | | Era Archive | \~8192 blocks | Sequential storage unit | | Block Data | Header, Body, Tx | Block reconstruction | | Receipts | Transaction receipts | Execution result verification | | Total Difficulty | Cumulative difficulty | Chain weight calculation | | Root Hash | Era Merkle root | Integrity verification | ### Import Process `ImportHistory` writes Era1 archives **directly into the ancient store**.\ Since the active DB is bypassed, this enables fast bootstrapping. ### Export Process `ExportHistory` packages existing chain data into the Era1 format for external storage or distribution. ### Direct Ancient Store Initialization When attaching an external ancient store to an empty node, automatic initialization is performed at startup. This is useful for: * Fast initialization from a trusted archive * Physical separation of ancient and active data * Disaster recovery setups ## Integration with BlockChain ### BlockChain Structure Fields ```text theme={null} type BlockChain struct { db ethdb.Database triedb *triedb.Database stateCache state.Database currentBlock atomic.Pointer[types.Header] currentSnapBlock atomic.Pointer[types.Header] bodyCache *lru.Cache[common.Hash, *types.Body] receiptsCache *lru.Cache[common.Hash, []*types.Receipt] blockCache *lru.Cache[common.Hash, *types.Block] } ``` ### Ancient Store Query Patterns | Operation | Implementation | Ancient Check | | ------------------------ | ---------------------------- | ------------- | | Get block by number | Branch on `Ancients()` | Yes | | Header lookup | Active → ancient fallback | Implicit | | Chain continuity check | Verify ancient boundary | Yes | | State availability check | Ancient blocks have no state | Yes | ### Interaction with Snap Synchronization * Snap pivot block may lie at the ancient boundary * Receipt chains are filled via `InsertReceiptChain` * `currentSnapBlock` and `currentBlock` may diverge * Snap insertion below the boundary is prohibited ## Maintenance Operations ### Disk Space Management Because the ancient store can occupy a large portion of disk space, block count and disk usage should be continuously monitored. ### Database Corruption Recovery Possible causes: * Abnormal shutdown during truncation * Filesystem errors * Manual file modification Recovery procedure: 1. Verify ancient count and head at startup 2. Automatically truncate on mismatch 3. Manually recover using `SetHead` if necessary ## Best Practices ### Operational Guidelines 1. The ancient store can be backed up while running 2. Consider placing it on a separate disk for I/O isolation 3. Monitor ancient block count and disk usage separately 4. Ancient data is immutable and removed only via truncation ### Performance Considerations | Aspect | Recommendation | Rationale | | ---------------- | -------------------------------------------- | ------------------------------- | | Ancient location | Disk with strong sequential read performance | Append-only access pattern | | Active DB | Disk with strong random I/O performance | Frequent reads/writes | | Memory | Minimal caching | Low access frequency | | Synchronization | Full sync fills naturally | Snap requires separate receipts | # Storage Architecture Source: https://docs.stablenet.network/en/storage-architecture/index ## Purpose and Scope This document describes the persistent and in-memory storage architecture used by StableNet to maintain blockchain state, blocks, and receipts.\ It covers the layered storage structure from the high-level StateDB caching layer down to the raw database backends, including the Merkle Patricia Trie, caching strategies, and the snapshot system. For state transitions and EVM execution, see *State Transitions and Gas*.\ For blockchain management and canonical chain maintenance, see *Blockchain Management*.\ For detailed information on the ancient store and data lifecycle, see *Ancient Store and Data Lifecycle*. ## Storage Layer Hierarchy StableNet’s storage architecture is composed of multiple layers, each providing a different level of abstraction and performance optimization. ## StateDB: State Caching Layer StateDB is the core interface for reading and modifying blockchain state.\ It is an advanced caching layer that provides journaling-based atomicity guarantees and snapshot-based rollback capabilities. ### StateDB Structure | Component | Type | Purpose | | ---------------------- | ------------------------------------------- | --------------------------------- | | `db` | `Database` | Trie database interface | | `trie` | `Trie` | Account trie root | | `snaps` | `*snapshot.Tree` | Snapshot tree for fast access | | `snap` | `snapshot.Snapshot` | Currently active snapshot | | `stateObjects` | `map[common.Address]*stateObject` | Active account objects | | `stateObjectsPending` | `map[common.Address]struct{}` | Finalized but uncommitted objects | | `stateObjectsDirty` | `map[common.Address]struct{}` | Objects modified during execution | | `stateObjectsDestruct` | `map[common.Address]*types.StateAccount` | Destructed objects | | `accounts` | `map[common.Hash][]byte` | Modified account data | | `storages` | `map[common.Hash]map[common.Hash][]byte` | Modified storage slots | | `accountsOrigin` | `map[common.Address][]byte` | Original account values | | `storagesOrigin` | `map[common.Address]map[common.Hash][]byte` | Original storage values | | `journal` | `*journal` | State change log | | `validRevisions` | `[]revision` | Snapshot revisions | | `refund` | `uint64` | Gas refund counter | ### State Object Management Each account is managed as a `stateObject`, which wraps the base `types.StateAccount` and tracks execution-time changes. | Field | Type | Purpose | | ---------------- | --------------------- | --------------------------------- | | `address` | `common.Address` | Account address | | `addrHash` | `common.Hash` | Keccak256(address) | | `origin` | `*types.StateAccount` | Original account data | | `data` | `types.StateAccount` | Current account data | | `trie` | `Trie` | Storage trie | | `code` | `Code` | Contract bytecode | | `originStorage` | `Storage` | Original storage | | `pendingStorage` | `Storage` | Pending storage (awaiting commit) | | `dirtyStorage` | `Storage` | Modified storage during execution | | `dirtyCode` | `bool` | Code modification flag | | `selfDestructed` | `bool` | Self-destruct marker | | `deleted` | `bool` | Deletion marker | | `created` | `bool` | Created in current transaction | ### Journaling and Snapshots StateDB records all state changes in a journal to guarantee rollback capability.\ Each journal entry implements a `revert()` method and includes the following change types: * `balanceChange` * `nonceChange` * `storageChange` * `codeChange` * `extraChange` * `createObjectChange` * `selfDestructChange` * `touchChange` * `addLogChange` ## Merkle Patricia Trie Implementation The Merkle Patricia Trie (MPT) is the core cryptographic data structure used to store state.\ StableNet supports both hash-based and path-based storage schemes. ### Trie Node Types | Node Type | Purpose | Structure | | ----------- | ---------------- | ------------------------ | | `fullNode` | 16-way branching | `Children [17]node` | | `shortNode` | Path compression | `Key []byte`, `Val node` | | `valueNode` | Leaf value | `[]byte` | | `hashNode` | Hash reference | `[]byte` | ## Storage Schemes: Hash vs Path StableNet supports two trie storage schemes. | Scheme | Key Format | Purpose | | ----------- | ---------- | --------------------------- | | Hash Scheme | Node hash | Content-addressed storage | | Path Scheme | Trie path | History and pruning support | The path scheme enables state history, efficient pruning, and historical state queries.\ The hash scheme is simpler but does not embed history. ## BlockChain Caching Strategy BlockChain minimizes database access by using multiple LRU caches. | Cache | Size | Purpose | | ------------- | ---- | ------------------- | | bodyCache | 256 | Block bodies | | blockCache | 256 | Full blocks | | receiptsCache | 32 | Receipts | | txLookupCache | 1024 | Transaction lookup | | headerCache | 512 | Block headers | | tdCache | 1024 | Total difficulty | | numberCache | 2048 | Hash → block number | ## Snapshot System Snapshots provide a flattened view of state, enabling fast access to accounts and storage without traversing the state trie. ### Snapshot Layers | Layer | Purpose | Storage | | ----------- | -------------- | ------- | | `difflayer` | Recent changes | Memory | | `disklayer` | Base state | Disk | Snapshot access order is diff → disk → trie fallback. ### Snapshot Configuration | Field | Default | Purpose | | ----------------- | ------- | --------------------------- | | `SnapshotLimit` | 256MB | Snapshot cache size | | `SnapshotNoBuild` | false | Disable background building | | `SnapshotWait` | true | Wait on startup | ## State Commit and Finalization State changes proceed through modification → finalization → trie update → commit stages.\ The final result is returned as a new state root hash. ## Raw Database and Ancient Store At the lowest level, a key-value database is used, and old data is migrated to the ancient store. ### Ancient Store Characteristics * Reduced active database size * Fast sequential access to historical data * Enables pruning of the active database * Supports Era1 archive generation ## Cache Configuration Summary | Configuration | Default | Purpose | | -------------------- | --------- | ------------------ | | `TrieCleanLimit` | 256MB | Clean trie cache | | `TrieDirtyLimit` | 256MB | Dirty trie cache | | `TrieTimeLimit` | 5 minutes | Flush delay | | `SnapshotLimit` | 256MB | Snapshot cache | | `StateHistory` | 0 | State history | | `bodyCacheLimit` | 256 | Block bodies | | `blockCacheLimit` | 256 | Full blocks | | `receiptsCacheLimit` | 32 | Receipts | | `txLookupCacheLimit` | 1024 | Transaction lookup | # Transaction Lifecycle Source: https://docs.stablenet.network/en/transaction-processing/6.1-transaction-lifecycle ## Purpose and Scope This document describes the complete lifecycle of a transaction in StableNet, from the moment it is submitted to the system until it is **finally included (finalized)** on the blockchain.\ It covers the entire process, including submission via RPC or P2P, transaction pool validation and acceptance, mining candidate selection, state transition (EVM execution), block sealing, and consensus-based finalization. For details on transaction types and encoding, see [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding).\ For transaction pool management policies, see [Transaction Pool](/en/core-architecture/3.4-transaction-pool).\ For internal EVM execution behavior, see [EVM Execution](/en/transaction-processing/6.3-evm-execution).\ For gas fees and tip policies, see [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy). ## Transaction Lifecycle Overview Transactions in StableNet go through the following **7-stage lifecycle** in sequence. **Transaction Lifecycle Stages** 1. Transaction submission 2. Pool-level validation and acceptance 3. Mining candidate selection 4. Transaction execution (state transition) 5. Block sealing and propagation 6. Block verification and chain insertion 7. Consensus-based finality ## Stage 1: Transaction Submission Transactions enter a StableNet node through two main paths. ### Entry Points | Path | Entry Point | Description | | --------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **RPC API** | `internal/ethapi/api.go` (`TransactionAPI`) | Transactions are submitted via JSON-RPC calls such as `eth_sendTransaction` or `eth_sendRawTransaction`. Internally, they pass through `SubmitTransaction` → backend `SendTx` and are forwarded to the txpool | | **P2P Network** | `eth/handler.go` (`txFetcher`) | Transactions broadcast by peers are received and added to the pool via `txpool.Add(tx, remote)` | On the RPC path, `TransactionArgs.setDefaults` fills in fields such as nonce, gas limit, and fee parameters.\ After wallet- or keystore-based signing (`SignTx`), a **fully signed transaction** is delivered to the txpool. ## Stage 2: Pool-Level Validation and Acceptance The txpool does not execute submitted transactions immediately. Instead, it applies a **pool-level validation pipeline** to filter them. Key validation checks include: * Transaction type validity (including fork activation checks) * Gas limit and minimum gas price requirements * Consistency of EIP-1559 fee fields (`maxFeePerGas`, `maxPriorityFeePerGas`) * Nonce ordering and detection of per-account nonce gaps * Replacement rules (price bump requirements for resubmission with the same nonce) * Per-account queue / pending slot limits * Whether fee-delegated transaction types are allowed Only transactions that pass validation are stored in the `pending` or `queued` sub-pools.\ Transactions that fail validation are either rejected immediately or retained in the queue until conditions are met. ## Stage 3: Mining Candidate Selection The mining worker (`miner/worker.go`) selects transactions as block candidates at the following times: * Upon receiving a `NewTxsEvent` * When starting a new block-building work loop The selection process follows this flow: * A `txpool.PendingFilter` is constructed based on the current block’s `baseFee`, the **governance-defined gas tip** retrieved from `GovValidator`, and blob fees (EIP-4844). * `TxPool().Pending(filter)` is called to retrieve transactions that satisfy the conditions. * **Local transactions are prioritized**, followed by remote transactions. * Transactions are ordered via `newTransactionsByPriceAndNonce` using the following criteria: * Effective gas tip and fee level * Per-account nonce continuity * Authorized account status in the Anzeon environment * `commitTransactions` greedily selects transactions until the block gas limit is reached. At this stage, only **pre-execution filtering** is performed; no state changes occur yet. ## Stage 4: Transaction Execution (State Transition) Each selected transaction is executed sequentially via `core.StateTransition`. The execution flow is as follows: * Create `NewStateTransition(evm, msg, gasPool)` * Call `TransitionDb()` to start the state transition * Perform pre-execution checks in `preCheck()`: * Nonce correctness (TooLow / TooHigh / Max) * Whether the sender is an EOA (contract accounts are rejected, except for EIP-7702 delegated code) * Relationship between `gasFeeCap`, `gasTipCap`, and the block `baseFee` * Validation of blob fees (EIP-4844) and authorization formats (EIP-7702) * Perform upfront gas deduction in `buyGas()`: * Deduct from the sender’s balance if no fee delegation is used * Deduct from the FeePayer’s balance if fee delegation is applied * Execute contract calls or creations via the EVM * Compute gas usage, gas refunds, execution results, and logs EVM errors (such as revert or out-of-gas) are **recorded as transaction failures but do not invalidate the block**.\ Consensus-level errors (such as preCheck failures) cause the transaction to be excluded from the block. ## Stage 5: Block Sealing and Propagation After all selected transactions have been executed, the worker performs the following steps: * Finalizes the block header by computing the state root, receipt root, and log bloom * Seals the block according to WBFT consensus rules (including BLS signature aggregation) * Writes the sealed block to the local chain and broadcasts it to the network via\ `eth/handler` and P2P subprotocols At this point, the block is propagated to the network in a **proposed** state. ## Stage 6: Block Verification and Chain Insertion Other nodes that receive the block perform the following validations: * Header validation (parent hash, timestamp, gas limit, extra data) * Verification of the transaction Merkle root and receipt root * Re-execution of transactions to verify the state root * Validation of WBFT consensus signatures If all checks pass, the block is inserted into the chain, and the canonical chain may be updated. ## Stage 7: Finality and Confirmation When the conditions required by WBFT consensus (signatures from at least 2/3 of validators) are met, the block is marked as **finalized**. * Finalized blocks cannot be reverted. * Clients and applications treat transactions in finalized blocks as **confirmed**. * Safe and Final header concepts can be used in UIs and APIs to distinguish trust levels. With this, a transaction completes its full lifecycle on StableNet. # State Transition and Gas Source: https://docs.stablenet.network/en/transaction-processing/6.2-state-transitions-and-gas ## Purpose and Scope This page documents the state transition process in StableNet, which defines how a transaction modifies the blockchain state.\ It covers gas mechanics, transaction validation, execution flow, fee delegation, and StableNet-specific features, including the gas policy of the Anzeon network. For details on internal EVM execution, see [EVM Execution](/en/transaction-processing/6.3-evm-execution).\ For gas fee policy and pricing, see [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy).\ For transaction types and encoding, see [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding). ## Overview A state transition refers to **the process of applying a single transaction to the current chain state (StateDB)**.\ The `StateTransition` type in `core/state_transition.go` orchestrates this process, handling nonce validation, gas purchase, value transfer, EVM execution, and gas refunds.\ This process is tightly integrated with the EVM to execute contract code and update account balances and storage. ## Core Data Structures ### Message The `Message` structure represents transaction data prepared for state processing.\ It is derived from a signed transaction and includes execution-time computed fields such as the effective gas price. ``` Message Structure (core/state_transition.go): - To: recipient address (nil for contract creation) - From: sender address - Nonce: transaction nonce - Value: wei amount to transfer - GasLimit: maximum gas available - GasPrice: effective gas price paid (result after baseFee and tip) - GasFeeCap: max fee per gas (EIP-1559) - GasTipCap: priority fee per gas (EIP-1559) - Data: call data or init code - AccessList: EIP-2930 access list - SetCodeAuthorizations: EIP-7702 code delegation list - FeePayer: optional fee payer address (StableNet fee delegation) - BlobGasFeeCap, BlobHashes: EIP-4844 blob fields - SkipAccountChecks: bypass validation (for eth_call) ``` ### StateTransition The `StateTransition` structure manages the lifecycle of a single transaction and tracks gas consumption. | Field | Type | Purpose | | -------------- | ------------ | ----------------------------------- | | `gp` | `*GasPool` | Block-level gas limit tracker | | `msg` | `*Message` | Transaction message being processed | | `gasRemaining` | `uint64` | Unspent gas during execution | | `initialGas` | `uint64` | Starting gas limit | | `state` | `vm.StateDB` | State database interface | | `evm` | `*vm.EVM` | EVM instance for execution | ## State Transition Flow **Diagram: Complete State Transition Flow** ## Converting a Transaction to a Message Before execution, a transaction is converted into a `Message` via `TransactionToMessage()`.\ At this stage, the effective gas price is calculated, and the governance-based gas tip policy of the Anzeon network is applied. ### Gas Tip Override (Anzeon) In the Anzeon network, a network-enforced gas tip included in the block header is applied to unauthorized accounts, while only authorized accounts may use the tip specified in the transaction itself. ``` if headerGasTip != nil: if !statedb.IsAuthorized(sender): gasTipCap = headerGasTip // Override with mandatory tip else: gasTipCap = tx.GasTipCap() // Use transaction's tip ``` For EIP-1559 transactions, the effective gas price is calculated as\ `min(gasTipCap + baseFee, gasFeeCap)`. ## Pre-Execution Validation ### preCheck() Method The `preCheck()` method validates whether a transaction satisfies consensus rules before any state changes occur. | Check | Error | Description | | ----------------- | ------------------------------------ | ----------------------------------------- | | Nonce correctness | `ErrNonceTooLow` / `ErrNonceTooHigh` | Nonce must exactly match the state nonce | | Nonce overflow | `ErrNonceMax` | Nonce cannot be `uint64` max value | | Sender is EOA | `ErrSenderNoEOA` | Sender must not have contract code | | Gas fee cap | `ErrFeeCapTooLow` | Fee cap must exceed the base fee | | Tip sanity | `ErrTipVeryHigh` | Tip cannot exceed 256 bits | | Fee cap sanity | `ErrFeeCapVeryHigh` | Fee cap cannot exceed 256 bits | | Tip vs cap | `ErrTipAboveFeeCap` | Tip cannot exceed the fee cap | | Blob validity | `ErrBlobTxCreate` | Blob transactions cannot create contracts | | Blob fee cap | `ErrBlobFeeCapTooLow` | Blob fee cap must meet the minimum | ### Gas Purchase (buyGas) After validation, `buyGas()` deducts gas costs upfront.\ The paying account depends on whether fee delegation is used. **Diagram: Gas Purchase Flow with Fee Delegation** * **Without delegation:** The sender pays both gas costs and value transfer * **With delegation:** The FeePayer pays for gas, while the sender pays only for value transfer ## Intrinsic Gas Calculation Intrinsic gas is the minimum gas required for a transaction to be executed. | Component | Cost | Condition | | ------------------ | -------------------------------- | ----------------------------- | | Base transaction | 21,000 gas | All transactions | | Contract creation | +32,000 gas | `to == nil` and Homestead+ | | Zero byte data | 4 gas/byte | Each zero byte | | Non-zero byte data | 16 gas/byte (Istanbul+) | Each non-zero byte | | | 68 gas/byte (Frontier–Byzantium) | | | Access list | 2,400 gas/address | Per address | | | 1,900 gas/key | Per storage key | | Init code size | 2 gas/word | Contract creation (Shanghai+) | If `gasRemaining < intrinsicGas`, the transaction is immediately rejected with `ErrIntrinsicGas`. ## EVM Execution Integration After intrinsic gas is deducted, the remaining gas is used for EVM execution. ### Contract Calls ``` state.SetNonce(sender, nonce + 1) ret, gasRemaining, err = evm.Call( sender, *msg.To, msg.Data, gasRemaining, value ) ``` For call transactions, the nonce is incremented before execution. ## Blacklist Validation (Anzeon) In the Anzeon network, a blacklist managed by `GovValidator` is checked before execution. ``` if rules.IsAnzeon: if state.IsBlacklisted(msg.From): return ErrBlacklistedAccount{msg.From} if msg.To != nil && state.IsBlacklisted(*msg.To): return ErrBlacklistedAccount{*msg.To} ``` When fee delegation is enabled, the FeePayer is also subject to blacklist checks. ``` if msg.FeePayer != nil && rules.IsAnzeon: if state.IsBlacklisted(*msg.FeePayer): return ErrBlacklistedAccount{*msg.FeePayer} ``` ## Gas Refunds and Fee Distribution ### Gas Refund Calculation | Fork | Refund Cap | Constant | | ---------- | ------------- | ------------------------------ | | Pre-London | `gasUsed / 2` | `params.RefundQuotient` | | London+ | `gasUsed / 5` | `params.RefundQuotientEIP3529` | Refunds are returned to the account that actually paid for gas (either the FeePayer or the sender). ### Fee Distribution In StableNet’s Anzeon network, validators receive the full fee corresponding to the effective gas price. ``` effectivePrice := msg.GasPrice fee := gasUsed * effectivePrice state.AddBalance(coinbase, fee) ``` * `msg.GasPrice` is the final effective gas price computed during `TransactionToMessage` * Unlike Ethereum London, there is no baseFee burn * This design preserves the 1:1 fiat backing principle of the stablecoin ## Fee Delegation Details ### Balance Validation With fee delegation, balance checks are clearly separated between sender and FeePayer. ### Gas Cost Calculation ``` feeCheck = gasLimit * gasFeeCap actualDebit = gasLimit * gasPrice if Anzeon && isFeeDelegation: feeCheck = gasLimit * gasPrice ``` ### Transfer Log Generation In Anzeon, explicit Transfer logs are generated for native coin movements. ``` func (evm *EVM) AddTransferLog(sender, recipient common.Address, amount *uint256.Int) { if !evm.chainConfig.AnzeonEnabled() { return } // Record Transfer log } ``` ## Execution Result `ExecutionResult` represents the outcome of a state transition. | Field | Type | Description | | ------------- | -------- | ------------------------------ | | `UsedGas` | `uint64` | Gas consumed excluding refunds | | `RefundedGas` | `uint64` | Refunded gas | | `Err` | `error` | EVM execution error | | `ReturnData` | `[]byte` | EVM return data | * **Consensus errors:** The transaction itself is rejected * **EVM errors:** The transaction is included but recorded as failed ## Integration with Block Processing State transitions are invoked sequentially by the `StateProcessor` during block processing. **Diagram: Block Processing Loop** `applyTransaction()` coordinates EVM context creation, execution, and receipt generation. ## Error Handling | Error | Code Location | Meaning | | ----------------------- | -------------------- | ------------------- | | `ErrNonceTooLow` | state\_transition.go | Already executed | | `ErrNonceTooHigh` | state\_transition.go | Nonce gap | | `ErrInsufficientFunds` | state\_transition.go | Cannot afford cost | | `ErrIntrinsicGas` | state\_transition.go | Gas limit too low | | `ErrGasLimitReached` | gas\_pool.go | Block gas exhausted | | `ErrBlacklistedAccount` | state\_transition.go | Blacklisted | | `ErrTxTypeNotSupported` | types/transaction.go | Fork not active | These errors may cause a block to be considered invalid during block verification. ## State Transition Testing StableNet includes the `t8n` state transition testing tool. ``` evm t8n --input.alloc=alloc.json \ --input.txs=txs.json \ --input.env=env.json \ --state.fork=Shanghai ``` This tool outputs the pre-state, post-state root, and receipts for deterministic verification of state transitions. # EVM Execution Source: https://docs.stablenet.network/en/transaction-processing/6.3-evm-execution ## Purpose and Scope This page provides detailed information about the Ethereum Virtual Machine (EVM) execution layer in StableNet, focusing on the interpreter architecture, opcode execution mechanics, jump tables, gas metering, and contract call handling.\ For details on how transactions enter the execution pipeline, see [Transaction Lifecycle](/en/transaction-processing/6.1-transaction-lifecycle).\ For the state transition model that wraps EVM execution, see [State Transitions and Gas](/en/transaction-processing/6.2-state-transitions-and-gas).\ For StableNet-specific gas pricing policies, see [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy). ## EVM Architecture The EVM is implemented as a stack-based virtual machine that executes bytecode and manages state changes.\ Its core consists of several major structures. **Architecture Overview: EVM Component Hierarchy** ## EVM Structure The `EVM` struct contains all context required for execution. | Field | Type | Purpose | | ------------- | --------------------- | ---------------------------------------------------------------------------- | | `Context` | `BlockContext` | Block-level information (coinbase, gas limit, block number, timestamp, etc.) | | `TxContext` | `TxContext` | Transaction-level information (origin, gas price, blob hashes) | | `StateDB` | `StateDB` | Interface for account and storage state | | `depth` | `int` | Current call stack depth (max 1024) | | `chainConfig` | `*params.ChainConfig` | Chain configuration | | `chainRules` | `params.Rules` | Fork rules for the current block | | `Config` | `Config` | VM configuration (tracer, ExtraEips, NoBaseFee, etc.) | | `interpreter` | `*EVMInterpreter` | Bytecode interpreter | | `abort` | `atomic.Bool` | Asynchronous abort flag | | `callGasTemp` | `uint64` | Temporary gas calculation space for CALL-family opcodes | ## EVMInterpreter Structure The interpreter executes bytecode using a jump table. | Field | Type | Purpose | | ------------ | -------------------- | ------------------------------------- | | `evm` | `*EVM` | Reference to the parent EVM | | `table` | `*JumpTable` | Array defining 256 opcodes | | `hasher` | `crypto.KeccakState` | Hash instance for KECCAK256 opcode | | `hasherBuf` | `common.Hash` | Hash output buffer | | `readOnly` | `bool` | STATICCALL mode flag | | `returnData` | `[]byte` | Return data from the most recent call | ## ScopeContext Structure `ScopeContext` holds execution resources scoped to a single call.\ It is created per contract execution and passed to all opcode execution functions, providing access to the stack and memory. ## Interpreter Loop The core execution loop of `EVMInterpreter.Run()` processes bytecode instructions one by one. **Interpreter Loop Execution Flow** ## Stack and Memory Management The EVM uses a stack for operands during execution and an expandable memory for data storage. ### Stack Implementation The `Stack` is a bounded array of 256-bit integers. | Component | Description | | ---------- | ------------------------------------ | | Structure | `[]uint256.Int`, maximum size 1024 | | Pool | `sync.Pool` for reuse across calls | | Operations | `push`, `pop`, `peek`, `swap`, `dup` | | Validation | Checked before each opcode execution | Before executing each opcode, the stack guarantees: * `stack.len() >= operation.minStack` * `stack.len() <= operation.maxStack` ### Memory Implementation `Memory` is a byte array that expands in 32-byte words. | Component | Description | | ------------ | --------------------------------------------------- | | Storage | `[]byte` | | Gas Tracking | Cumulative expansion cost tracked via `lastGasCost` | | Operations | `Set`, `Set32`, `Resize`, `GetPtr`, `GetCopy` | | Cost Model | `3 * words + words² / 512` | Memory expansion gas calculation: ``` newMemSizeWords = (newMemSize + 31) / 32 newTotalFee = 3 * newMemSizeWords + newMemSizeWords² / 512 expansionCost = newTotalFee - lastGasCost ``` ## Major Execution Steps 1. **Initialization** * Increase call depth * Set `readOnly` if STATICCALL * Reset `returnData` * Create new `Stack` and `Memory` * Construct `ScopeContext` 2. **Fetch Opcode** * Load opcode at the program counter 3. **Stack Validation** * Check for underflow and overflow 4. **Gas Consumption** * Deduct fixed gas * Compute dynamic gas if required * Apply memory expansion gas 5. **Execution** * Invoke the opcode execution function 6. **Program Counter Update** * Increment `pc` unless a JUMP-family opcode is executed ## Jump Table and Opcodes The jump table maps 256 opcodes to execution functions, gas costs, and stack requirements.\ Different instruction sets are selected depending on the active fork. ### Instruction Sets by Fork | Instruction Set | Fork | Features | | --------------- | -------------- | ------------------------------------------------------ | | frontier | Frontier | Base opcodes | | homestead | Homestead | DELEGATECALL | | byzantium | Byzantium | STATICCALL, REVERT | | constantinople | Constantinople | CREATE2 | | istanbul | Istanbul | Gas repricing | | berlin | Berlin | EIP-2929 | | london | London | BASEFEE | | shanghai | Shanghai | PUSH0 | | cancun | Cancun | BLOB-related opcodes | | **anzeon** | **Anzeon** | **London + Shanghai + partial Cancun (blob excluded)** | The jump table is selected in `NewEVMInterpreter()` based on chain rules. ## Contract Calls The EVM supports CALL, DELEGATECALL, STATICCALL, CREATE, and CREATE2. ### Key Handling During Calls * Maximum call depth: 1024 * Anzeon: value transfer destination restrictions * Blacklist checks * State snapshot creation and rollback on error * Tracer event invocation ## Precompiled Contracts | Address | Contract | Purpose | | ------------ | ---------- | ---------------------------------- | | 0x01 | ecrecover | ECDSA recovery | | 0x02 | sha256 | Hashing | | 0x03 | ripemd160 | Hashing | | 0x04 | identity | Data copy | | 0x05 | modexp | Modular exponentiation | | 0x06–0x08 | bn256 | Pairing operations | | 0x09 | blake2F | Compression | | **0xb00001** | **blsPoP** | **Anzeon BLS Proof-of-Possession** | ## Native Manager Contracts (Anzeon) StableNet provides native Go-implemented contracts for system-level operations. | Address | Contract | Purpose | | -------- | ----------------- | ----------------------------- | | 0xb00002 | NativeCoinManager | Direct balance manipulation | | 0xb00003 | AccountManager | Account extra-data management | These are integrated into the normal CALL flow and interact directly with StateDB. ## Gas Metering Gas is calculated across the following stages: * Intrinsic gas * Memory expansion gas * Opcode dynamic gas * Post-execution refunds Refund caps: * Pre-London: `gasUsed / 2` * London+: `gasUsed / 5` ## Error Handling | Error Type | Behavior | Example | | ---------- | ----------------------------------- | -------------------- | | Consensus | Transaction invalid | ErrNonceTooLow | | Execution | Consume all gas | ErrOutOfGas | | Revert | Roll back state, partial gas refund | ErrExecutionReverted | | Internal | Should not occur | ErrGasUintOverflow | The REVERT opcode rolls back state changes while preserving return data. # Gas Fee Policy Source: https://docs.stablenet.network/en/transaction-processing/6.4-gas-fee-policy ## Purpose and Scope This document describes the gas fee policy of StableNet.\ StableNet applies a **modified version of Ethereum’s EIP-1559 fee mechanism** to support a stablecoin-based transaction environment.\ This document covers the dual-component fee structure (base fee and priority fee), governance-controlled gas tips, and the fee delegation mechanism.\ For information on the governance system that controls gas tips, refer to [Validator Governance (GovValidator)](/en/governance-system/5.3-validator-governance-\(govvalidator\)).\ For details on transaction types and encoding, refer to [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding). ## Overview StableNet implements a modified version of Ethereum’s EIP-1559 fee mechanism, tailored for a **1:1 fiat-backed stablecoin environment**.\ The primary design goals are to minimize fee volatility, provide a predictable cost structure, and enable governance-based control. The following key modifications are applied. 1. **No Burning of the Base Fee**\ Unlike Ethereum, the base fee is not burned but instead distributed to validators.\ This follows the design principle that stablecoins should only be burned at the point of fiat redemption. 2. **Governance-Controlled Priority Fee**\ Gas tips are determined through validator governance rather than market competition. 3. **Dual-Threshold-Based Base Fee Adjustment**\ Clear rules are defined for increasing, maintaining, or decreasing the base fee based on gas utilization ranges. 4. **Priority Allowance for Authorized Accounts**\ Authorized (certified) accounts may specify custom priority fees. 5. **Fiat-Denominated Cost Design**\ All gas fees are designed in terms of the base stablecoin unit (e.g., KRW). ## Fee Components ### Base Fee and Priority Fee Structure Gas fees in StableNet consist of the following two components. * **Base Fee**\ The minimum fee determined by the protocol based on network congestion * **Priority Fee (Gas Tip)**\ An additional fee to compensate validators and determine transaction processing priority ### Transaction Fee Fields | Field | Description | Set By | Applies To | | ---------------------- | --------------------------------------------- | ----------------- | ---------------- | | `gasLimit` | Maximum gas allowed for transaction execution | User | All transactions | | `baseFeePerGas` | Minimum gas cost included in the block header | Protocol | London and later | | `maxFeePerGas` | Maximum gas cost the user is willing to pay | User | DynamicFeeTx | | `maxPriorityFeePerGas` | Maximum priority fee | User / Governance | DynamicFeeTx | | `gasPrice` | Fixed gas price | User | LegacyTx | On the Anzeon chain, for **general accounts**, the `maxPriorityFeePerGas` specified in the transaction is overridden by the governance-enforced gas tip. ## Base Fee Policy ### Adjustment Mechanism StableNet modifies the EIP-1559 base fee adjustment mechanism to be more gradual and predictable. **Standard Ethereum** * Target utilization: 50% * Adjustment rate: ±12.5% per block **StableNet Dual-Threshold System** StableNet applies the following rules based on the parent block’s gas utilization. 1. **Gas utilization > 20%** * Base fee increases by 2% * Enters this range at approximately 1,000 or more simple transfers per block 2. **6% ≤ Gas utilization ≤ 20%** * Base fee remains unchanged * Stable network operating range 3. **Gas utilization \< 6%** * Base fee decreases by 2% * Enters this range at fewer than approximately 300 simple transfers per block Additional constraints are as follows. * Adjustment rate: ±2% per block * Minimum base fee: 20,000 gwei * Maximum base fee: 20,000,000 gwei Protocol constant definitions: ``` IncreasingThreshold = 20 DecreasingThreshold = 6 BaseFeeChangeRate = 2 MinBaseFee = 20_000_000_000_000 MaxBaseFee = 20_000_000_000_000_000 ``` ### Base Fee Distribution In StableNet, the base fee is handled as follows. 1. The base fee is not burned and is distributed as rewards to all validators. 2. The priority fee is paid to the block producer. This structure ensures that the stablecoin supply decreases only through explicit, governance-approved burn operations. ## Priority Fee (Gas Tip) Policy ### Governance-Controlled Gas Tip In the Anzeon configuration, gas tips are determined through validator consensus via the GovValidator contract, rather than by individual users.\ This removes gas price competition and provides a predictable cost environment. ### Gas Tip Update Mechanism The governance-controlled gas tip is updated at the following times. **At Initialization** ``` - Retrieve the initial gasTip from the GovValidator contract - Set it based on the current block state - Register callbacks for future updates ``` **After Block Production** ``` - After block production completes - Re-fetch the gasTip from the new block state - Apply it to the worker and TxPool ``` ### General Accounts vs. Authorized Accounts **General Accounts** * Use the fixed gas tip set by governance * Higher user-specified tips are ignored * Transactions below the minimum gas tip are rejected * No execution priority competition **Authorized Accounts** * May specify a per-transaction gas tip * Priority is determined based on the actual tip value * Intended for operational and system accounts This design provides cost stability for general users while allowing flexibility for operational accounts. ## Transaction Fee Calculation ### Effective Gas Price For EIP-1559 transactions, the effective gas price is calculated as follows. ``` effectiveGasPrice = baseFee + effectivePriorityFee ``` In Anzeon: ``` effectivePriorityFee = min(governanceTip, maxFeePerGas - baseFee) ``` ### Total Cost ``` Total Cost = (gasUsed × effectiveGasPrice) + value ``` For blob transactions (EIP-4844), additional blob gas costs apply. ## Fee Delegation StableNet supports fee delegation through `FeeDelegateDynamicFeeTxType` (0x16). Key characteristics: * Dual signatures from the sender and the fee payer * Gas costs are charged to the fee payer * Transaction value is deducted from the sender’s balance * The transaction hash includes both signatures ## Protocol Parameters ### Gas Fee Constants | Constant | Value | Description | | ------------------- | --------------- | ------------------------------- | | IncreasingThreshold | 20 | Base fee increase threshold (%) | | DecreasingThreshold | 6 | Base fee decrease threshold (%) | | BaseFeeChangeRate | 2 | Adjustment rate per block (%) | | MinBaseFee | 20,000 gwei | Minimum base fee | | MaxBaseFee | 20,000,000 gwei | Maximum base fee | ### Maximum Block Gas Limit ``` Maximum Block Gas Limit = 105_000_000 ``` This is designed to process approximately 5,000 basic transfer transactions per block. ## Fee Query APIs | API | Description | | -------------------------- | ------------------------------------------- | | `eth.maxPriorityFeePerGas` | Query the governance-configured gasTip | | `eth.gasPrice` | Recommended price based on baseFee + gasTip | ## Comparison with Standard Ethereum | Aspect | Ethereum | StableNet | | ---------------- | ------------------ | --------------------- | | Base Fee | Burned | Paid to validators | | Adjustment Model | 50% target, ±12.5% | Dual thresholds, ±2% | | Priority Fee | User competition | Governance-controlled | | Fee Volatility | High | Low | | Fee Delegation | Not supported | Supported | | Block Gas Limit | \~60M | 105M | | Currency Basis | Non-pegged | Fiat-pegged | # Fee Delegation Source: https://docs.stablenet.network/en/transaction-processing/6.5-fee-delegation This page documents StableNet’s **WEMIX-style fee delegation mechanism**.\ Fee delegation allows a separate account (`FeePayer`) to pay the transaction gas costs, while the transaction sender (`From`) only provides the value transfer.\ This feature enables use cases where application operators subsidize transaction fees for users. For gas fee policies and tip requirements, refer to [Gas Fee Policy](/en/transaction-processing/6.4-gas-fee-policy).\ For the general transaction processing flow, refer to [Transaction Lifecycle](/en/transaction-processing/6.1-transaction-lifecycle). ## Purpose and Scope Fee delegation clearly separates the financial responsibilities of a transaction between two parties. * **Sender (`From`)**\ Signs the transaction intent, provides the `Value` to be transferred, and must hold a valid nonce. * **Fee Payer (`FeePayer`)**\ Separately signs to approve gas payment and must hold sufficient balance to cover gas costs. This mechanism is implemented via a dedicated transaction type, `FeeDelegateDynamicFeeTxType = 0x16`, and requires the **Applepie fork** to be active. ## Transaction Type and Structure ### Transaction Type Definition Fee delegation uses transaction type `0x16` (decimal 22). | Constant | Value | Description | | ----------------------------- | ------ | ---------------------------------------- | | `FeeDelegateDynamicFeeTxType` | `0x16` | Fee-delegated EIP-1559 style transaction | ### Core Data Structures The `Message` structure includes fee delegation fields. ``` Message { From common.Address // Transaction sender (signs transaction intent) To *common.Address // Recipient Value *big.Int // Value to transfer from sender GasLimit uint64 GasPrice *big.Int GasFeeCap *big.Int GasTipCap *big.Int FeePayer *common.Address // Account paying for gas (optional) ... } ``` The `TxData` interface includes fee delegation–related methods. ``` type TxData interface { feePayer() *common.Address rawFeePayerSignatureValues() (v, r, s *big.Int) ... } ``` ## Dual Signature Requirement Fee-delegated transactions require **two independent signatures**. ### Signature 1: Transaction Sender * Signs the transaction data (to, value, data, gas parameters, nonce). * Signature values: `V`, `R`, `S` * Proves transaction intent and authorization. ### Signature 2: Fee Payer * Signs consent to pay gas for the transaction. * Signature values: `FV`, `FR`, `FS` * Retrieved via the `rawFeePayerSignatureValues()` method. This dual-signature structure guarantees that both the sender and the fee payer explicitly agree to their respective responsibilities. ## State Transition Process ### Transaction-to-Message Conversion A fee-delegated transaction is converted into a `Message` upon entering the state transition. ``` FeeDelegateDynamicFeeTx Message +--------------------------+ +---------------------------+ | SenderTx.Nonce | ----> | Nonce | | SenderTx.GasFeeCap | ----> | GasFeeCap | | SenderTx.GasTipCap | ----> | GasTipCap | | SenderTx.Gas | ----> | GasLimit | | SenderTx.To | ----> | To | | SenderTx.Value | ----> | Value | | SenderTx.Data | ----> | Data | | SenderTx.AccessList | ----> | AccessList | | FeePayer | ----> | FeePayer | +--------------------------+ +---------------------------+ | From = recovered sender | | GasPrice = effectivePrice | +---------------------------+ ``` `TransactionToMessage` recovers the `From` address from the sender’s signature (`V/R/S`) and sets the `FeePayer` field via `tx.FeePayer()`.\ The fee payer’s signature is used only to authorize gas payment and is **not** used to derive the `From` address. ### Gas Purchase (`buyGas`) When fee delegation is active, `buyGas` performs separated balance checks and deductions. #### Balance Validation Rules | Scenario | FeePayer Balance Check | Sender Balance Check | | --------------------- | ----------------------------------- | --------------------------------------------- | | Fee Delegation Active | ≥ `gasLimit × gasPrice` + blob fees | ≥ `value` | | Standard Transaction | N/A | ≥ `gasLimit × gasPrice` + `value` + blob fees | ## EVM Execution Context Fee delegation does not alter EVM execution semantics. * **tx.origin**: Always the transaction sender (`From`) * **Top-level caller**: Transaction sender * **FeePayer**: Not exposed to the EVM context As a result, smart contracts cannot directly distinguish whether fee delegation was used. ## Gas Refund Process After execution, unused gas is refunded to the account that actually paid for gas. ``` func (st *StateTransition) refundGas(refundQuotient uint64) uint64 { refund := st.gasUsed() / refundQuotient if refund > st.state.GetRefund() { refund = st.state.GetRefund() } st.gasRemaining += refund remaining := uint256.NewInt(st.gasRemaining) remaining = remaining.Mul(remaining, uint256.MustFromBig(st.msg.GasPrice)) if st.msg.FeePayer != nil { st.state.AddBalance(*st.msg.FeePayer, remaining) } else { st.state.AddBalance(st.msg.From, remaining) } st.gp.AddGas(st.gasRemaining) return refund } ``` ## Fee Payment to Coinbase Validators receive fees based on actual gas usage.\ Fee payment is processed in the later stages of state transition and includes blacklist checks for the fee payer. ## Fork Activation Requirement Fee delegation is **only permitted after the Applepie fork**. ``` if isFeeDelegation && !st.evm.ChainConfig().IsApplepie(st.evm.Context.BlockNumber) { return ErrTxTypeNotSupported } ``` For blocks prior to Applepie, fee-delegated transactions are immediately rejected during the `preCheck` stage. ## Transaction Construction via RPC ### TransactionArgs Fields | Field | Type | Purpose | | -------------- | ----------------- | ------------------ | | `From` | `*common.Address` | Transaction sender | | `FeePayer` | `*common.Address` | Optional fee payer | | `V`,`R`,`S` | `*hexutil.Big` | Sender signature | | `FV`,`FR`,`FS` | raw tx only | FeePayer signature | ### JSON Representation ``` { "type": "0x16", "chainId": "0x2052", "nonce": "0x1", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "maxFeePerGas": "0x9184e72a000", "maxPriorityFeePerGas": "0x5f5e100", "value": "0xde0b6b3a7640000", "input": "0x", "accessList": [], "v": "0x0", "r": "0x...", "s": "0x...", "feePayer": "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "fv": "0x0", "fr": "0x...", "fs": "0x..." } ``` ## Key Invariants 1. **Balance Isolation**\ The fee payer covers gas only, while the sender covers value only. 2. **Origin Preservation**\ `tx.origin` is always the sender. 3. **Dual Consent**\ Both accounts must sign for the transaction to be valid. 4. **Fork Gate**\ Available only after Applepie activation. 5. **Refund Consistency**\ Unused gas is refunded to the actual payer. # Transaction Processing Source: https://docs.stablenet.network/en/transaction-processing/index ## Purpose and Scope This document provides a comprehensive overview of transaction execution in **go-stablenet**, covering the entire pipeline from RPC submission to validation, EVM execution, and finalization.\ It introduces the major components (StateProcessor, StateTransition, EVM) and their interactions, while delegating detailed explanations of specific aspects to subpages. **Detailed Topics (See Subpages):** * Transaction Lifecycle – End-to-end flow from RPC submission to block inclusion * State Transitions and Gas – StateTransition process, pre-checks, gas purchase, intrinsic gas, refunds * EVM Execution – EVM instantiation, bytecode interpretation, state mutation * Gas Fee Policy – Governance-based gas tip application in StableNet * Fee Delegation – Third-party gas payment mechanism **Related Pages:** * Transaction pool management and validation: [Transaction Pool](/en/core-architecture/3.4-transaction-pool) * Transaction structure and serialization: [Transaction Types and Encoding](/en/core-architecture/3.5-transaction-types-and-encoding) * Transaction selection during block production: [Block Production and Mining](/en/consensus-and-block-production/4.2-block-production-and-mining) * StateDB architecture and journaling: [State Management](/en/core-architecture/3.3-state-management) ## Transaction Processing Overview Transaction processing in go-stablenet follows a multi-stage pipeline that transforms messages into state changes and receipts.\ The process is orchestrated by the **StateProcessor** for block-level handling and **StateTransition** for individual transaction execution. ### High-Level Processing Flow **Diagram: Transaction execution pipeline with code entities** ## Core Components ### StateProcessor StateProcessor handles block-level transaction processing. It iterates over all transactions in a block, applies them sequentially, and coordinates with the consensus engine for finalization. | Component | Type | Purpose | | --------- | --------------------- | --------------------------------------------- | | `config` | `*params.ChainConfig` | Chain configuration for fork rules | | `bc` | `*BlockChain` | Access to canonical chain state | | `engine` | `consensus.Engine` | Consensus engine for rewards and finalization | **Key Method:** `Process(block, statedb, cfg) -> (receipts, logs, gasUsed, error)` This method performs the following steps: * Creates the EVM block context using header information * Iterates over transactions and converts each to a Message * Invokes `applyTransaction()` for each transaction * Calls `engine.Finalize()` for consensus-specific logic ### StateTransition The StateTransition structure encapsulates the logic for executing a single transaction against the current state.\ It manages gas accounting, pre-checks, EVM invocation, and error handling. ## Transaction Validation and Pre-Checks Before execution, transactions undergo extensive validation in the `StateTransition.preCheck()` method.\ This ensures all consensus rules are satisfied before any state changes occur. ### Key Validation Checks | Check | Method | Purpose | Errors | | ------------------ | ----------------------------------- | ------------------------------ | -------------------------------------- | | Nonce | `state.GetNonce(msg.From)` | Ensures transaction ordering | `ErrNonceTooLow`, `ErrNonceTooHigh` | | Sender Account | `state.GetCode(msg.From)` | Verifies sender is an EOA | `ErrSenderNoEOA` | | Gas Pricing | `GasFeeCap >= GasTipCap >= BaseFee` | Validates EIP-1559 constraints | `ErrFeeCapTooLow`, `ErrTipAboveFeeCap` | | Authorization List | Validate EIP-7702 | Verifies signatures | `ErrAuthorizationInvalidSignature` | | Gas Purchase | `buyGas()` | Reserves gas upfront | `ErrInsufficientFunds` | ## Gas Management Gas handling in StableNet consists of three phases: upfront purchase, intrinsic gas deduction, and post-execution refunds. ### Gas Purchase `StateTransition.buyGas()` handles upfront gas payment, including optional fee delegation. ### Intrinsic Gas `IntrinsicGas()` computes the minimum gas required before execution begins. ### Gas Refunds `StateTransition.refundGas()` refunds unused gas after execution. ## EVM Execution After validation and gas purchase, `StateTransition.TransitionDb()` invokes the EVM to execute the transaction. ### EVM Structure | Field | Type | Purpose | | ------------- | ----------------- | -------------------- | | `Context` | `vm.BlockContext` | Block metadata | | `TxContext` | `vm.TxContext` | Transaction metadata | | `StateDB` | `vm.StateDB` | State interface | | `interpreter` | `*EVMInterpreter` | Bytecode interpreter | ## StableNet-Specific Features ### Blacklist Enforcement When Anzeon is active, blacklisted addresses are blocked before and during execution. ### Governance-Based Gas Tips For non-authorized accounts, a governance-mandated minimum gas tip is enforced. ### Fee Delegation A third-party account can pay gas fees, and refunds are issued to that account accordingly. ## Error Handling Errors are categorized into pre-execution consensus errors and execution-time EVM errors. ## Performance Considerations * Use of stack and memory pools * Snapshot-based rollback in StateDB * Optimized gas calculation paths ## Summary Transaction processing in StableNet follows the flow:\ **validation → gas purchase → EVM execution → state application → refunds → receipt generation**, and incorporates governance-based gas policies, fee delegation, and extended features such as EIP-7702.