# Network Architecture

### Overview

OPN Chain is built on a carefully designed architecture that optimizes for EVM compatibility while leveraging the proven security and consensus mechanisms of the Cosmos ecosystem. This unique approach provides developers with a familiar Ethereum environment backed by enterprise-grade infrastructure.

### Architecture Layers

```
┌─────────────────────────────────────────────┐
│          Application Layer                   │
│   • Smart Contracts (Solidity/Vyper)        │
│   • DApps & Web3 Applications               │
│   • Developer Tools & SDKs                  │
├─────────────────────────────────────────────┤
│          EVM Execution Layer                 │
│   • Ethereum Virtual Machine                 │
│   • Pectra Upgrade Support                  │
│   • Gas Metering & Optimization            │
├─────────────────────────────────────────────┤
│          State Management Layer              │
│   • Account State (EOA & Contracts)         │
│   • Storage Tries                           │
│   • State Transitions                       │
├─────────────────────────────────────────────┤
│          Core Blockchain Layer               │
│   • Cosmos SDK Modules                      │
│   • Bank, Staking, Governance              │
│   • Transaction Processing                  │
├─────────────────────────────────────────────┤
│          Consensus Layer                     │
│   • Tendermint BFT                         │
│   • Block Production                        │
│   • Finality Guarantees                     │
├─────────────────────────────────────────────┤
│          Network Layer                       │
│   • P2P Communication                       │
│   • Node Discovery                          │
│   • Data Propagation                        │
└─────────────────────────────────────────────┘
```

### Core Components

#### 1. EVM Module

The EVM module is the heart of OPN Chain's Ethereum compatibility.

**Key Features:**

* Full opcode compatibility with Ethereum
* Support for latest EIPs including Pectra
* Optimized gas consumption
* Native integration with Cosmos SDK

**Architecture:**

```go
type EVMKeeper struct {
    storeKey      sdk.StoreKey
    cdc           codec.BinaryCodec
    stateDB       *statedb.StateDB
    accountKeeper types.AccountKeeper
    bankKeeper    types.BankKeeper
}
```

**State Management:**

* Merkle Patricia Tries for accounts and storage
* Efficient state pruning
* Fast state synchronization
* Snapshot capabilities

#### 2. Consensus Engine

OPN Chain uses Tendermint BFT (Byzantine Fault Tolerant) consensus.

**Properties:**

* **Instant Finality**: Blocks are final once committed
* **High Throughput**: \~1 second block times
* **Byzantine Fault Tolerance**: Secure with up to 1/3 malicious validators
* **Deterministic**: No forks or reorganizations

**Consensus Flow:**

```
1. Proposal Phase
   └─> Designated proposer creates block
   
2. Prevote Phase
   └─> Validators vote on proposed block
   
3. Precommit Phase
   └─> Validators commit to block if 2/3+ prevotes
   
4. Commit Phase
   └─> Block is finalized and added to chain
```

#### 3. Transaction Processing

**Transaction Lifecycle:**

```
User Transaction
      ↓
JSON-RPC Endpoint
      ↓
Transaction Pool (Mempool)
      ↓
Block Proposer Selection
      ↓
Transaction Execution
      ↓
State Updates
      ↓
Block Commitment
      ↓
Event Emission
```

**Transaction Types:**

* **Ethereum Transactions**: Standard ETH transfers and contract calls
* **Cosmos Transactions**: Staking, governance, IBC (future)

#### 4. State Management

**Account Model:**

```typescript
interface Account {
  address: string;        // 20-byte Ethereum address
  balance: BigNumber;     // Native token balance
  nonce: number;         // Transaction counter
  codeHash: string;      // Contract code hash (if contract)
  storageRoot: string;   // Root of storage trie (if contract)
}
```

**Storage Model:**

* Key-value storage per contract
* 256-bit keys and values
* Sparse Merkle Patricia Trie
* Efficient proof generation

#### 5. Networking Layer

**P2P Network:**

* Gossip-based message propagation
* Peer discovery via seed nodes
* DDoS protection mechanisms
* Configurable peer limits

**Network Topology:**

```
              Seed Nodes
                  │
        ┌─────────┴─────────┐
        │                   │
    Validator           Validator
      Nodes              Nodes
        │                   │
    ┌───┴───┐          ┌───┴───┐
    │       │          │       │
  Full    Full      Full     Full
  Nodes   Nodes    Nodes    Nodes
    │                         │
    └─────── RPC Nodes ───────┘
              │
          End Users
```

### Network Parameters

#### Block Production

| Parameter       | Value      | Description                 |
| --------------- | ---------- | --------------------------- |
| Block Time      | \~1 second | Average time between blocks |
| Block Size      | 30M gas    | Maximum gas per block       |
| Timeout Commit  | 1 second   | Time to wait after commit   |
| Timeout Propose | 3 seconds  | Maximum proposal time       |

#### Transaction Limits

| Parameter     | Value     | Description                |
| ------------- | --------- | -------------------------- |
| Max TX Size   | 1 MB      | Maximum transaction size   |
| Min Gas Price | 7 Gwei    | Minimum accepted gas price |
| Gas Limit     | 30M       | Maximum gas per block      |
| TX Timeout    | 20 blocks | Transaction expiration     |

#### Network Limits

| Parameter       | Value | Description              |
| --------------- | ----- | ------------------------ |
| Max Peers       | 50    | Maximum peer connections |
| Max Pending TXs | 5000  | Mempool size limit       |
| Sync Timeout    | 60s   | State sync timeout       |
| Keep-Alive      | 60s   | Connection timeout       |

### Security Architecture

#### Validator Security

**Slashing Conditions:**

1. **Double Signing**: Signing two different blocks at same height
2. **Downtime**: Missing too many blocks
3. **Invalid Proposals**: Proposing invalid blocks

**Security Measures:**

* Hardware security module (HSM) support
* Key rotation capabilities
* Automated backup systems
* DDoS protection

#### Network Security

**Protection Mechanisms:**

```
┌─────────────────────────┐
│   Rate Limiting         │
│   • RPC rate limits     │
│   • P2P message limits  │
│   • TX spam prevention  │
├─────────────────────────┤
│   Access Control        │
│   • IP whitelisting     │
│   • Peer authentication │
│   • API key management  │
├─────────────────────────┤
│   Consensus Security    │
│   • BFT guarantees      │
│   • Slashing penalties  │
│   • Validator bonds     │
└─────────────────────────┘
```

#### Smart Contract Security

**Built-in Protections:**

* Gas limits prevent infinite loops
* Reentrancy protection patterns
* Access control mechanisms
* Upgrade safety checks

### Performance Optimization

#### State Storage

**Optimization Techniques:**

1. **Pruning**: Remove old state data
2. **Compression**: Compress historical data
3. **Indexing**: Fast lookups via indexes
4. **Caching**: In-memory state cache

#### Transaction Processing

**Parallel Execution:**

```
Block N
├── TX Group 1 (Independent)
│   ├── TX 1.1
│   ├── TX 1.2
│   └── TX 1.3
├── TX Group 2 (Independent)
│   ├── TX 2.1
│   └── TX 2.2
└── TX Group 3 (Dependent)
    └── TX 3.1 (Sequential)
```

#### Network Optimization

**Efficiency Features:**

* Block compression
* Efficient encoding (Protobuf)
* Connection pooling
* Adaptive peer selection

### Scalability Design

#### Horizontal Scaling

**Sharding (Future):**

* Data sharding for storage
* Computation sharding for execution
* Cross-shard communication
* Unified security model

#### Vertical Scaling

**Node Types:**

1. **Archive Nodes**: Full history (3TB+)
2. **Full Nodes**: Recent history (1.5TB)
3. **Light Nodes**: Headers only (25GB)
4. **RPC Nodes**: API service only

### Monitoring & Metrics

#### Key Metrics

**System Health:**

```javascript
{
  "blockHeight": 1234567,
  "blockTime": 1.2,
  "peerCount": 45,
  "txPoolSize": 234,
  "gasPrice": 7000000000,
  "networkLoad": 0.67
}
```

**Performance Metrics:**

* Transactions per second (TPS)
* Block propagation time
* Consensus round duration
* State sync speed

#### Monitoring Tools

**Prometheus Metrics:**

```yaml
# Key metrics to monitor
- tendermint_consensus_height
- tendermint_consensus_block_interval_seconds
- tendermint_p2p_peers
- tendermint_mempool_size
- cosmos_tx_count
- evm_gas_used
```

### Comparison with Other Architectures

#### vs Ethereum

| Aspect       | OPN Chain      | Other L1's     |
| ------------ | -------------- | -------------- |
| Consensus    | Tendermint BFT | Proof of Stake |
| Finality     | Instant        | Probabilistic  |
| Block Time   | \~1s           | \~10s          |
| Architecture | Modular        | Monolithic     |

#### vs Layer 2 Solutions

| Aspect           | OPN Chain   | L2 Rollups       |
| ---------------- | ----------- | ---------------- |
| Security         | Independent | Inherits from L1 |
| Finality         | \~1s        | Hours/Days       |
| Complexity       | Simple      | Complex          |
| Decentralization | Full        | Varies           |

### Future Architecture Evolution

#### Planned Enhancements

1. **IBC Integration**
   * Cross-chain communication
   * Asset transfers
   * Interchain accounts
2. **Zero-Knowledge Integration**
   * Privacy preserving transactions
   * Scalability via ZK-rollups
   * Efficient proof verification

#### Research Areas

* Quantum resistant cryptography
* Advanced consensus mechanisms
* Novel scaling solutions
* Enhanced privacy features

### Developer Implications

#### Building on OPN

**Advantages:**

* Familiar EVM environment
* Fast transaction finality
* Predictable costs
* Rich tooling ecosystem

**Considerations:**

* Block time assumptions
* Finality model differences
* Gas price stability
* Network-specific features

#### Best Practices

1. **Design for 1s blocks**

   ```solidity
   // Good: Account for fast blocks
   uint256 constant BLOCKS_PER_DAY = 86400;

   // Bad: Ethereum assumptions
   uint256 constant BLOCKS_PER_DAY = 7200;
   ```
2. **Leverage instant finality**

   ```javascript
   // No need for confirmations
   const receipt = await tx.wait(1);
   // Transaction is final!
   ```
3. **Optimize for consistency**
   * No chain reorganizations
   * Simplified event handling
   * Reliable state queries

### Conclusion

OPN Chain's architecture represents a thoughtful balance between compatibility and innovation. By building on proven technologies while optimizing for modern use cases, we provide a platform that's both familiar to developers and powerful enough for next-generation applications.

The modular design allows for future enhancements without disrupting existing applications, ensuring that OPN Chain can evolve with the rapidly changing blockchain landscape while maintaining its core strengths of speed, reliability, and developer friendliness.

***
