bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 23쪽 중 16쪽
).
// This associates the execution phase results with the commit phase confirmation.
// Step 3: Atomically persist the block data and state changes
// to the underlying storage (e.g., RocksDB, Sled).
// This is the first time the transaction lifecycle data
// is permanently written to disk.
Self::persist_block(block_info.num, &pending_blocks, storage.as_ref()).await;
// (Optional) Step 4: Cleanup.
// After persistence, remove the committed block data
// from in-memory caches (pending_blocks) to free resources.
}
}
}
```
At this point, a transaction’s full lifecycle—from submission, to consensus on ordering, to execution, and finally to durable persistence—has been fully completed and permanently recorded on-chain.
### **5. Step 4: Assembly & Startup**
The final step is to integrate all implemented modules (TxPool, Executor, Committer, Storage, etc.) and launch the blockchain node.
A typical startup workflow is as follows:
1. **Initialize Core Modules**: Load node configuration, initialize storage, load the genesis block to establish the initial state, and create the transaction pool (Mempool) instance.
2. **Start the Consensus Engine**: Using the node configuration and the TxPool instance, initialize and start the `ConsensusEngine`. This is the heart of Gravity SDK.
3. **Launch Background Tasks**: Use an asynchronous runtime (e.g., `tokio::spawn`) to start the previously defined `execute_task` and `commit_task` as independent background services.
4. **Start RPC Service** (not detailed in the example): Launch an RPC server to listen for external requests and inject transactions into the TxPool.
5. **Block the Main Thread**: Keep the main thread alive to ensure the node runs continuously.
***
#### **Example: KvStore Startup Code**
```rust
fn main() -> Result<()> {
// 1. Initialize storage, genesis state, etc.
let storage = Arc::new(SledStorage::new("blockchain_db")?);
let blockchain = Blockchain::new(storage.clone(), "genesis.json");
let state = blockchain.get_latest_state();
let mempool = KvStoreTxPool::new();
let pending_blocks = Arc::new(DashMap::new()); // Shared data between execution and commit tasks
// 2. Initialize and start the Gravity SDK Consensus Engine
// Pass configuration, networking components, and our TxPool implementation
let _consensus_engine = ConsensusEngine::init(
ConsensusEngineArgs { ... },
Box::new(mempool), // Instance implementing the TxPool Trait
).await;
// 3. Launch execution task
let state_clone = state.clone();
let pending_blocks_clone = pending_blocks.clone();
tokio::spawn(async move {
PipelineExecutor::execute_task(start_num, None, state_clone, pending_blocks_clone).await;
});
// 4. Launch commit task
let pending_blocks_clone2 = pending_blocks.clone();
tokio::spawn(async move {
PipelineExecutor::commit_task(start_num, None, storage, pending_blocks_clone2).await;
});
// 5. Block the main thread to keep the node running
// Typically, the RPC service would be launched here and wait for termination signals
// ...
Ok(())
}
```
***
> **Multi-Node Cluster Configuration**
>
> When deploying a multi-node network, each validator node requires its own configuration file (`validator.yaml`), private keys, and an initial waypoint to ensure that all nodes boot from the same trusted genesis state. Refer to Gravity SDK’s official documentation for details.
### **6. Data Flow Recap: The Complete Lifecycle of a Transaction**
Let’s use a simple key-value transaction to illustrate the full process:
1. **Submission**: The user calls the RPC interface to submit a transaction `Set("key", "value")`.
2. **Pooling**: The RPC service receives the request, wraps it into the application’s native transaction object, and inserts it into the implemented `KvStoreTxPool` for processing.
3. **Ordering Consensus**: The Gravity SDK `ConsensusEngine` pulls this transaction from the `KvStoreTxPool` (via the `best_txns` method), packages it together with other transactions into an **ordered block**, and reaches consensus across the network on its contents and order.
4. **Execution**: The `execute_task` retrieves the ordered block from the `BlockBufferManager`. It deserializes the `Set("key", "value")` transaction, updates the key-value state **in memory**, and computes the new global `StateRoot`. This execution result is then reported back to the `BlockBufferManager`.
5. **Result Consensus**: The `ConsensusEngine` runs a second round of consensus on the block’s execution result (`StateRoot`), ensuring that all nodes agree on the outcome.
6. **Committing**: Once result consensus is achieved, the `commit_task` fetches this block from the `BlockBufferManager` and **persists** the state changes (the updated `"key"` value) together with the block information to the disk database.
At this point, the transaction is finalized, and the state update is permanently recorded.
Through this lifecycle, we show how Gravity SDK lets developers leverage its robust consensus framework while seamlessly integrating their custom application logic to build a simple yet fully functional blockchain application.
# Validator Cluster Deployment Guide
Deploy a local multi-validator Gravity EVM cluster using Gravity SDK in minutes — the fastest way to run a high-performance, EVM-compatible chain from scratch.
Gravity SDK makes it straightforward to spin up your own EVM-compatible chain with the same [AptosBFT](https://aptos.dev/en/network/blockchain/bft-consensus) consensus and parallel execution engine that powers the Gravity L1. Whether you want to run a local devnet for development, benchmark raw throughput, or evaluate the technology, this guide walks you through a complete cluster deployment in five steps.
> For a deeper dive into the SDK architecture and how to build production-grade chains, see [Build Your Own 100k+ TPS Chain Using Gravity SDK](/research-and-development/gravity-sdk-tutorial).
***
## Prerequisites
Ensure you have the following installed:
* **Rust**: `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh`
* **Foundry** (for genesis contract deployment): `curl -L https://foundry.paradigm.xyz | bash` then `foundryup`
* **Python 3**: For parsing configurations.
* **envsubst**: Usually part of the `gettext` package (`sudo apt install gettext` on Ubuntu).
## Quick Start (4-Node Cluster)
### 1. Clone the Repository
```bash
git clone https://github.com/Galxe/gravity-sdk.git
cd gravity-sdk
```
### 2. Build the Node Binary
Benchmark results are only meaningful when the node is compiled with optimizations:
```bash
make BINARY=gravity_node MODE=quick-release
```
Refer to [gravity-sdk/readme.md](https://github.com/Galxe/gravity-sdk/blob/main/readme.md) for full build options.
### 3. Setup Configuration
```bash
cd cluster
cp genesis.toml.example genesis.toml # Genesis / validator config
cp cluster.toml.example cluster.toml # Node deployment config
```
The default configuration sets up 4 nodes on localhost. Edit `genesis.toml` to customize validators, stake amounts, and network parameters. Edit `cluster.toml` to adjust ports or the path to your binary.
### 4. Initialize Node Keys
```bash
make init
```
This generates `identity.yaml` for each validator node.
### 5. Generate Genesis (New Networks Only)
```bash
make genesis
```
Outputs `./output/genesis.json` and `./output/waypoint.txt`.
> **Note**: `genesis.sh` clones `gravity_chain_core_contracts` into `external/` on first run but does **not** auto-update it. To update manually: `cd external/gravity_chain_core_contracts && git pull origin main`
### 6. Deploy and Start
```bash
make deploy_start
```
Your cluster is now running. Useful commands:
```bash
make status # Show PID, status, and current block number
make stop # Gracefully stop all nodes
```
***
## Configuration Reference
### `genesis.toml` (New Networks Only)
| Section | Description |
| ---------------------------- | -------------------------------------------------------- |
| `[genesis]` | Core genesis parameters (chain ID, epoch interval, etc.) |
| `[genesis.faucet]` | Pre-funded faucet account for testing |
| `[genesis.validator_config]` | Validator bond limits and restrictions |
| `[[genesis_validators]]` | Genesis validator list with addresses and stake |
**Key validator fields:**
* `address` — Validator's ETH address (required)
* `stake_amount` — Initial stake in Wei (required)
* `voting_power` — Initial voting power (must be ≥ stake\_amount)
### `cluster.toml` (Node Deployment)
| Section | Description |
| ------------------ | ------------------------------------------ |
| `[cluster]` | Cluster name and base directory |
| `[build]` | Path to the `gravity_node` binary |
| `[genesis_source]` | Paths to `genesis.json` and `waypoint.txt` |
| `[[nodes]]` | Node definitions with ports and roles |
| `[faucet_init]` | Optional faucet initialization config |
**Node roles:**
* `genesis` — Included in the genesis validator set
* `validator` — Validator that joins via on-chain transaction
* `vfn` — Full node using on-chain discovery
***
## Makefile Reference
| Target | Description |
| ------------------- | ----------------------------------------- |
| `make genesis` | Generate `genesis.json` + `waypoint.txt` |
| `make init` | Generate node identity keys |
| `make deploy` | Prepare runtime environment for each node |
| `make start` | Start all nodes |
| `make stop` | Stop all nodes |
| `make status` | Check cluster status |
| `make faucet` | Initialize faucet accounts |
| `make clean` | Remove generated artifacts |
| `make deploy_start` | Deploy and start (convenience) |
| `make restart` | Stop, deploy, and start |
***
## Next Steps
Once your cluster is running, follow the [Benchmark Reproduction Guide](/research-and-development/benchmark-guide) to benchmark throughput and latency using `gravity_bench`.
# Benchmark Reproduction Guide
Step-by-step guide to reproducing the Gravity EVM benchmark and collecting throughput and latency data using gravity\_bench.
### Overview
* **Goal**: Continuously stress Gravity's RPC endpoints and measure throughput (TPS) and latency.
* **Repository**: `https://github.com/Galxe/gravity_bench`
* **What the tool does**:
* Deploys the required ERC20 contracts.
* Prepares a large pool of accounts/addresses.
* Concurrently sends transactions to one or more RPC endpoints.
### Prerequisites
1. **A `gravity_node` binary built in release mode** — benchmark results are only meaningful when the node is compiled with optimizations. Refer to [gravity-sdk/readme.md](https://github.com/Galxe/gravity-sdk/blob/main/readme.md) for full build instructions. The recommended command is:
```bash
make BINARY=gravity_node MODE=quick-release
```
2. **A running Gravity EVM cluster** (refer to: [Validator Cluster Deployment Guide](/research-and-development/cluster-deployment)):
* Code: <https://github.com/Galxe/gravity-sdk> (see [releases](https://github.com/Galxe/gravity-sdk/releases) for tagged versions)
* Note: example cluster configurations are available at: <https://github.com/Galxe/gravity-sdk/tree/main/cluster/example>
* `chain_id`: `1337 (example)`
* `nodes1`: `http://127.0.0.1:8545 (example Validator1)`
* `nodes2`: `http://127.0.0.1:8546 (example Validator2)`
* `nodes3`: `http://127.0.0.1:8547 (example Validator3)`
3. **A funded EOA** for use as **faucet + deployer**:
* You must provide this account's private key in the config file.
* The account needs sufficient native token balance to:
* Fund a large number of test accounts (directly or via cascading faucet mode).
* Pay gas for contract deployment.
A test faucet account is pre-funded in genesis.toml, with private key\
`0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80`,\
corresponding to address `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266`.\
The following configuration must be present in genesis.toml to give this address a balance:
```toml
[genesis.faucet]
address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
private_key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
balance = "1000000000000000000000000" # 1M ETH
```
### System Dependencies (Ubuntu)
Install all required build and runtime packages in one step:
```bash
sudo apt update && sudo apt install -y \
build-essential clang pkg-config libssl-dev git curl \
libudev-dev libusb-1.0-0-dev \
python3 python-is-python3 python3-pip python3-venv \
nodejs npm
```
> `python-is-python3` creates the `python` command alias required by gravity\_bench's internal scripts. `libudev-dev` / `libusb-1.0-0-dev` prevent common build errors when compiling `hidapi`.
### Environment Setup
1. **Clone the repository**
```bash
git clone https://github.com/Galxe/gravity_bench.git
cd gravity_bench
```
2. **Run the initialization script**
The script will:
* Check and install missing tools (Rust, Node.js, Python)
* Create a Python virtual environment
* Install Python and Node dependencies
* Clone the contract repositories required for benchmarking
**Recommended (keep the environment active in the current shell):**
```bash
source setup.sh
```
> ⚠️ On Ubuntu, if you see `Failed to create Python virtual environment`, first run:
>
> ```bash
> sudo apt install python3-venv
> ```
>
> Then re-run `source setup.sh`.
**Alternative (requires manual environment activation):**
```bash
bash setup.sh
# Then manually activate the environment:
source venv/bin/activate
source ~/.cargo/env # only needed if the script installed Rust
```
### Configuration
1. **Create a local config file**
```bash
cp bench_config.template bench_config.toml
```
2. **Edit `bench_config.toml`**
Key fields to review:
* `nodes`: one or more RPC endpoints
* `target_tps`: target benchmark TPS; recommended not to exceed 9k on a 3-node cluster
* `[faucet].private_key`: **private key of the funded faucet/deployer account**
* `[accounts].num_accounts`: number of benchmark accounts; 100k recommended
* `[performance]`: concurrency and pool configuration
**Configuration constraints** — violating these will cause an assertion failure on startup:
* `accounts.num_accounts` ≥ `target_tps`
* `performance.num_senders` ≤ `accounts.num_accounts`
Example (abbreviated):
```toml
# Gravity Bench Configuration File
# Uniswap configuration file path (generated by deployment)
contract_config_path = "deploy.json"
# Target sending rate
target_tps = 9000
# RPC endpoints, replace with your chain_id and addresses
nodes = [
{ rpc_url = "http://127.0.0.1:8545", chain_id = 1337 },
{ rpc_url = "http://127.0.0.1:8546", chain_id = 1337 },
{ rpc_url = "http://127.0.0.1:8547", chain_id = 1337 },
]
num_tokens = 1
enable_swap_token = false
# Address pool type: "random" (default) or "weighted" (hot/normal/long-tail distribution)
address_pool_type = "random"
[faucet]
# Private key (replace with your real key)
private_key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
# Faucet Level:
# - 10 enables cascade mode: 1 -> 10 -> 100 (amplification chain)
# - 0 disables cascading
faucet_level = 10
# Wait between faucet distribution levels (increase if you see insufficient funds)
wait_duration_secs = 1
# Target ETH balance per funded account (in wei)
fauce_eth_balance = "1000000000000000000000"
[accounts]
num_accounts = 100000
[performance]
# Number of concurrent transaction sending tasks inside TxnConsumer
num_senders = 600
# Max in-memory pool size inside the consumer
max_pool_size = 100000
# Benchmark duration in seconds (0 = run indefinitely)
duration_secs = 0
# Sampling strategy: integer = sample every N txns, or "full" to check all pending
sampling = 20
```
### Running the Benchmark
#### First Run (includes faucet distribution + contract deployment)
For the first run (or when you want to re-initialize accounts/contracts):
```bash
cargo run --release -- --config bench_config.toml
```
This step will:
* Distribute funds to test accounts using the faucet private key.
* Deploy the required contracts.
* Generate (or update) `deploy.json`, referenced by `contract_config_path`.
#### Subsequent Runs (reuse existing state)
Once contracts are deployed and `deploy.json` exists, use recovery mode:
```bash
cargo run --release -- --config bench_config.toml --recover
```
### Diagnostics
**Verify an RPC endpoint is reachable and get its `chain_id`:**
```bash
curl -s http://127.0.0.1:8545 \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}'
# expect 0x539 for chainId 1337
```
**Check a faucet account balance:**
```bash
curl -s http://127.0.0.1:8545 \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_getBalance","params":["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","latest"]}'
```
### Troubleshooting
| Symptom | Fix |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Build error: `libudev.pc` / `hidapi` / `pkg-config` not found | `sudo apt install -y libudev-dev libusb-1.0-0-dev pkg-config` |
| `python: command not found` | `sudo apt install -y python-is-python3` |
| `ModuleNotFoundError: No module named 'web3'` | Ensure you're in the `gravity_bench` directory and run `source setup.sh` again |
| `SolcError` or missing Uniswap/OpenZeppelin contracts | Remove `contracts/` and `node_modules/` then re-run `source setup.sh` |
| `insufficient funds for gas * price + value` | Increase `faucet.wait_duration_secs` in `bench_config.toml`; for a local cluster, restart all nodes to reset state |
| `assertion failed: accounts.num_accounts >= target_tps` | Increase `accounts.num_accounts` to be ≥ `target_tps` |
| `Connection refused` / wrong network | Verify `rpc_url` is correct and the cluster is running; confirm `chain_id` matches the value returned by `eth_chainId` |
### Visualization
For Grafana / Prometheus deployment and dashboard import, refer to:
* Grafana / Prometheus deployment guide coming soon.
# 3-Validator Cluster Benchmark Results
3-validator cluster benchmark results from 2026-02-28, covering TPS benchmarks and bottleneck analysis across CPU, memory, and I/O.
### Test Environment
| Parameter | Value |
| ---------------- | ------------------------------- |
| **Topology** | 3 validators + 1 VFN |
| **Machine spec** | 8 vCPU / 16 GB RAM |
| **Disk** | 200 GB pd-balanced (4,200 IOPS) |
| **Accounts** | 100k accounts |
### Load Test Results (transaction removal rate)
* **Before write buffer is full**: \~**11k TPS** ERC20 transfer
* **After write buffer is full**: \~**9.5k TPS** ERC20 transfer
<figure><img src="https://1664081133-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZtdkwV6IW7ZSjaMZNmkU%2Fuploads%2Fgit-blob-ba5ed8a690742400f0ce24df278f733559cd6b2d%2Fload-test-results-tps.png?alt=media" alt="TPS chart before and after write buffer saturation"><figcaption><p>TPS over time</p></figcaption></figure>
<figure><img src="https://1664081133-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZtdkwV6IW7ZSjaMZNmkU%2Fuploads%2Fgit-blob-c17166b05a29ffa5285d81f217a797db50c6a268%2Fload-test-results-tps2.png?alt=media" alt="TPS detail chart"><figcaption><p>TPS detail</p></figcaption></figure>
***
### Bottleneck Analysis
#### Resource Utilization
**1. CPU**
* CPU was **not** the bottleneck (usage \~**800%** on a 16-core machine)
* Execution, Merkle computation, and other pipeline stages all completed within the block time (\~**200 ms**)
<figure><img src="https://1664081133-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZtdkwV6IW7ZSjaMZNmkU%2Fuploads%2Fgit-blob-e1d4c1fc6c384f9fc175a8dde50c098dc4a2b408%2Fload-test-results-cpu.png?alt=media" alt="CPU utilization chart"><figcaption><p>CPU utilization during load test</p></figcaption></figure>
**2. Memory**
* Memory grew continuously during the block cac프로젝트로 돌아가기