# vechain/thor architecture

> Architecture diagram of the GitHub repository vechain/thor, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/vechain/thor
- Repository: https://github.com/vechain/thor

## Overview

##### Project Type and Purpose
- This is a Go-based Layer-1 blockchain node implementation (VeChainThor). It provides:
- A command-line interface (cmd/thor) to start and configure a node
- A P2P network layer to discover, connect and synchronize peers
- A consensus engine (PoA/BFT styles) to agree on and produce blocks
- A transaction pool, block builder and state machine (EVM compatible)
- REST/JSON-RPC APIs to serve clients and expose metrics

##### High-Level Architecture Analysis
- Top-level directories map to core subsystems:
- cmd/…: CLI entry points (“thor”, “disco”)
- api/: HTTP/JSON RPC API handlers and documentation
- p2psrv/, comm/: Peer discovery, RPC, gossip, sync logic
- consensus/, bft/, poa/: Consensus algorithms and forking logic
- txpool/: Pending transactions management and validation
- block/, chain/: Block assembly, chain persistence, forks
- runtime/, vm/: Smart‐contract execution environment (EVM)
- state/, logdb/: State trie, historical lookup, event logs
- builtin/: Native smart contracts preloaded at genesis
- metrics/: Prometheus, telemetry instrumentation
- tracers/: Transaction tracing and profiling tools
- Test and bench directories alongside each module confirm clear module boundaries.

##### Key Components
a. **Node CLI** (“thor” executable)
- Initialises configuration, bootstraps subsystems, launches services
b. **P2P Network Layer** (p2psrv + comm)
- Peer discovery (bootstrap nodes), secure RPC, gossip protocols
c. **Consensus Engine** (consensus/, bft/, poa/)
- Receives blocks, validates, participates in block production
- Fork-handling, justifier, metrics
d. **Transaction Pool** (txpool/)
- Accepts inbound transactions via API or peer
- Validates, prioritizes, caches for inclusion in blocks
e. **Block Assembler** (block/, packer/)
- Gathers transactions, builds header, computes roots
f. **Chain Manager** (chain/)
- Validates blocks, applies to state, persists in logdb and state trie
g. **State Database** (state/, runtime/statedb/, muxdb/, trie/)
- Ethereum-style Merkle-Patricia trie, backing key-value store
- Journal, snapshots, cache layers
h. **EVM Runtime** (vm/, runtime/)
- Executes smart contracts, built-in natives, energy metering
i. **API Server** (api/)
- JSON/REST endpoints for blocks, transactions, accounts, events, metrics
j. **Instrumentation** (metrics/, log/, tracers/)
- Exposes Prometheus metrics, structured logging, execution traces

##### Component Interactions and Data Flows
- **Startup**: CLI → load config → init modules in order: metrics → storage → trie → state → txpool → P2P → consensus → API
- **Peer Sync**: P2P ←→ comm RPCs → fetch block headers/bodies → chain manager → state DB
- **Tx Propagation**: API or P2P → txpool → broadcast to peers → block assembler
- **Block Production**: consensus engine triggers packer → build block → broadcast via P2P
- **Block Finalization**: receive block → consensus validation → chain.ApplyBlock → state.Update → logdb.Store
- **Contract Execution**: chain.ApplyBlock calls vm.InterpretTransaction → runtime(statedb) updates → emit events
- **API Responses**: chain, state, trx data → JSON serialization → client
- **Metrics & Logging**: hook into each module for counters, histograms, logs

##### Architectural Patterns and Principles
- Modular package per subsystem – clear separation of concerns
- Layered architecture: CLI → API → Consensus → Core Chain → State → Storage
- Interface‐based abstractions for networking, database (muxdb), VM
- Dependency injection for testing: modules expose interfaces and tests use mocks
- Event-driven flows: blocks, transactions, state changes produce events for subscriptions

## Diagram (Mermaid)

```mermaid
graph TB
    %% Swimlanes
    subgraph "Node CLI"
        CLI["CLI\ncmd/thor/main.go"]:::cli
    end

    subgraph "Networking"
        P2PSRV["P2P Layer\np2psrv/server.go"]:::network
        COMM["Comm\ncomm/communicator.go"]:::network
    end

    subgraph "Consensus"
        CONS["Consensus Engine\nconsensus/consensus.go"]:::consensus
        BFT["BFT Engine\nbft/engine.go"]:::consensus
        POA["PoA Proposer\npoa/proposer.go"]:::consensus
    end

    subgraph "Transaction Pool"
        TXPOOL["Tx Pool\ntxpool/tx_pool.go"]:::txpool
    end

    subgraph "Block Assembler"
        PACKER["Packer\npacker/packer.go"]:::storage
        BUILDER["Builder\nblock/builder.go"]:::storage
    end

    subgraph "Chain Manager"
        CHAIN["Chain Manager\nchain/chain.go"]:::storage
        READER["Block Reader\nchain/block_reader.go"]:::storage
    end

    subgraph "State & Database"
        STATE["State DB\nstate/state.go"]:::state
        STATEDB["StateDB\nruntime/statedb/statedb.go"]:::state
        MUXDB["MuxDB\nmuxdb/muxdb.go"]:::state
        TRIE["Trie\ntrie/trie.go"]:::state
    end

    subgraph "EVM & Runtime"
        VM["EVM Interpreter\nvm/interpreter.go"]:::execution
        RUNTIME["Runtime\nruntime/runtime.go"]:::execution
    end

    subgraph "API Server"
        API["API Server\napi/api.go"]:::api
        ADMIN["Admin API\napi/admin_server.go"]:::api
    end

    subgraph "Instrumentation"
        METRICS["Prometheus\nmetrics/prometheus.go"]:::instr
        LOG["Logger\nlog/logger.go"]:::instr
        TRACERS["Tracers\ntracers/tracers.go"]:::instr
    end

    %% Startup Initialization Flow
    CLI -->|"init Metrics"| METRICS
    METRICS -->|"init Storage"| STATE
    STATE -->|"init Trie"| TRIE
    TRIE -->|"init StateDB"| STATEDB
    STATEDB -->|"init TxPool"| TXPOOL
    TXPOOL -->|"init P2P"| P2PSRV
    P2PSRV -->|"init Consensus"| CONS
    CONS -->|"init API"| API

    %% API interactions
    API -->|"SubmitTx"| TXPOOL
    API -->|"QueryChain"| CHAIN
    API -->|"GetState"| STATE

    %% P2P Data Flows
    P2PSRV <-->|"ConsensusRPC"| CONS
    P2PSRV <-->|"PropagateTx"| TXPOOL
    P2PSRV <-->|"FetchBlock"| CHAIN

    %% Transaction & Block Production
    CONS -->|"ProduceBlock"| PACKER
    PACKER -->|"BuildBlock"| BUILDER
    BUILDER -->|"DeliverBlock"| CHAIN
    PACKER -->|"BroadcastBlock"| P2PSRV

    %% Block Finalization & Persistence
    CHAIN -->|"ApplyBlock"| STATE
    CHAIN -->|"ReadBlock"| READER
    CHAIN -->|"PersistKV"| MUXDB
    CHAIN -->|"UpdateTrie"| TRIE
    CHAIN -->|"UpdateStateDB"| STATEDB
    CHAIN -->|"EmitEvent"| TRACERS

    %% Contract Execution
    CHAIN -->|"InterpretTx"| VM
    VM -->|"StateUpdate"| RUNTIME
    RUNTIME -->|"WriteState"| STATE

    %% Click Events
    click CLI "https://github.com/vechain/thor/blob/master/cmd/thor/main.go"
    click P2PSRV "https://github.com/vechain/thor/blob/master/p2psrv/server.go"
    click COMM "https://github.com/vechain/thor/blob/master/comm/communicator.go"
    click CONS "https://github.com/vechain/thor/blob/master/consensus/consensus.go"
    click BFT "https://github.com/vechain/thor/blob/master/bft/engine.go"
    click POA "https://github.com/vechain/thor/blob/master/poa/proposer.go"
    click TXPOOL "https://github.com/vechain/thor/blob/master/txpool/tx_pool.go"
    click BUILDER "https://github.com/vechain/thor/blob/master/block/builder.go"
    click PACKER "https://github.com/vechain/thor/blob/master/packer/packer.go"
    click CHAIN "https://github.com/vechain/thor/blob/master/chain/chain.go"
    click READER "https://github.com/vechain/thor/blob/master/chain/block_reader.go"
    click STATE "https://github.com/vechain/thor/blob/master/state/state.go"
    click STATEDB "https://github.com/vechain/thor/blob/master/runtime/statedb/statedb.go"
    click MUXDB "https://github.com/vechain/thor/blob/master/muxdb/muxdb.go"
    click TRIE "https://github.com/vechain/thor/blob/master/trie/trie.go"
    click VM "https://github.com/vechain/thor/blob/master/vm/interpreter.go"
    click RUNTIME "https://github.com/vechain/thor/blob/master/runtime/runtime.go"
    click API "https://github.com/vechain/thor/blob/master/api/api.go"
    click ADMIN "https://github.com/vechain/thor/blob/master/api/admin_server.go"
    click METRICS "https://github.com/vechain/thor/blob/master/metrics/prometheus.go"
    click LOG "https://github.com/vechain/thor/blob/master/log/logger.go"
    click TRACERS "https://github.com/vechain/thor/blob/master/tracers/tracers.go"

    %% Styles
    classDef cli fill:#f9f,stroke:#333,stroke-width:1px
    classDef network fill:#ccf,stroke:#333,stroke-width:1px
    classDef consensus fill:#fc9,stroke:#333,stroke-width:1px
    classDef txpool fill:#cff,stroke:#333,stroke-width:1px
    classDef storage fill:#d9c,stroke:#333,stroke-width:1px
    classDef state fill:#9f9,stroke:#333,stroke-width:1px
    classDef execution fill:#9cf,stroke:#333,stroke-width:1px
    classDef api fill:#c9f,stroke:#333,stroke-width:1px
    classDef instr fill:#fcf,stroke:#333,stroke-width:1px
```
