> For the complete documentation index, see [llms.txt](https://quantumwing.gitbook.io/quantumwing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://quantumwing.gitbook.io/quantumwing/architecture/trust-boundaries.md).

# Trust Boundaries

The trust boundary architecture in QuantumWing establishes clear security domains between the beacon layer (consensus) and execution layer (state management), using **defense-in-depth validation** where both layers independently verify cryptographic proofs.

## Overview

QuantumWing implements **defense-in-depth security** between the beacon chain and execution layer:

* **Beacon Layer**: Performs full Dilithium Mode 3 signature verification + VRF proof validation
* **Execution Layer**: **Also performs full verification** (Dilithium + VRF) as defense-in-depth
* **Result**: Double verification protects against compromised beacon, P2P attacks, MITM attacks

**Current Status** (June 2026): Execution layer performs **full cryptographic verification**, NOT trust-based acceptance. This is a **security-first approach** that prioritizes safety over performance optimization.

***

## The Problem: Canonical Encoding for Dilithium Signatures

### Root Cause

Dilithium Mode 3 signatures are computed over **canonical block headers**, but block transmission uses **wire format** (JSON/protobuf):

1. **Validator creates block** with canonical header hash
2. **Beacon receives via REST API** → JSON unmarshaling changes structure
3. **Execution receives via REST API** → JSON unmarshaling changes structure again
4. **Each layer must recompute canonical hash** to verify signature

### Wire Format vs Canonical Format

**Wire Format** (JSON transmission):

```json
{
  "header": {
    "index": 7,
    "timestamp": 1759253906612,
    "parent_hash": "0x1234...",
    "merkle_root": "0x5678...",
    "validator_id": "0x8258...",
    "vrf_proof": "0x9abc...",
    "vrf_seed": "0xdef0..."
  },
  "transactions": [...],
  "signature": "0x7a4b..."
}
```

**Canonical Format** (for Dilithium signing):

```go
SignedHeader{
  ChainID: "quantum-production-1",
  Index: 7,
  Timestamp: 1759253906,  // Unix seconds (not milliseconds)
  ParentHash: [32]byte{0x12, 0x34, ...},
  MerkleRoot: [32]byte{0x56, 0x78, ...},
  ValidatorIndex: 0,  // Not validator_id string
}
```

### Solution: Canonical Hash Recomputation

Each layer **reconstructs canonical header** before verification:

```go
// 1. Extract SignedHeader from wire format BlockHeader
signedHeader := &types.SignedHeader{}
signedHeader.FromBlockHeader(&block.Header, validatorIndex)

// 2. Calculate canonical hash with domain separation
canonicalHash := signedHeader.Hash(chainID)

// 3. Verify Dilithium signature using canonical hash
dilithium.Verify(publicKey, canonicalHash, signature)
```

This ensures **deterministic hashing** across network transmission.

***

## Solution: Defense-in-Depth Validation

### Design Principles

1. **Zero Trust Between Layers**: Each layer independently verifies all cryptographic proofs
2. **Defense-in-Depth**: Multiple layers of verification catch attacks at different points
3. **Canonical Encoding**: Deterministic hashing using SignedHeader format
4. **Attack Resistance**: Protects against compromised beacon, P2P attacks, MITM

### Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────┐
│                       Validator Layer                            │
│  - Proposes blocks with Dilithium Mode 3 signatures             │
│  - Signs canonical SignedHeader (not wire format BlockHeader)   │
│  - 1,952-byte public key, 3,293-byte signature                  │
└───────────────────────────┬─────────────────────────────────────┘
                            │ POST /api/v1/beacon/block/proposal
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                       Beacon Layer (Port 8080)                   │
│  ✅ VERIFICATION #1: FULL DILITHIUM SIGNATURE VERIFICATION      │
│  - Reconstructs canonical SignedHeader from wire format         │
│  - Verifies 3,293-byte signature with 1,952-byte public key     │
│  - Validates VRF randomness proof                               │
│  - Confirms validator is active and has stake                   │
│  - Validates PoR consensus rules (slot timing, epoch)           │
└───────────────────────────┬─────────────────────────────────────┘
                            │ POST /api/v1/blocks
                            │ (Forwards verified block)
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Execution Layer (Port 8546)                  │
│  ✅ VERIFICATION #2: DEFENSE-IN-DEPTH (FULL RE-VERIFICATION)    │
│  - Reconstructs canonical SignedHeader from wire format         │
│  - RE-VERIFIES Dilithium signature (same as beacon)             │
│  - RE-VERIFIES VRF proof (same as beacon)                       │
│  - VALIDATES Merkle root of transactions                        │
│  - VALIDATES all transaction signatures (user signatures)       │
│  - VALIDATES state transitions (nonces, balances, gas)          │
│  - VALIDATES smart contract execution correctness               │
│                                                                  │
│  🛡️ PROTECTION AGAINST:                                         │
│  - Compromised beacon node (malicious block forwarding)         │
│  - P2P network attacks (fake blocks from peers)                 │
│  - MITM attacks (block tampering in transit)                    │
│  - Validator key compromise (invalid blocks with valid sigs)    │
└─────────────────────────────────────────────────────────────────┘
```

### Key Implementation: isValidBlockFromBeacon()

**Location**: `blockchain/core/blockchain.go:686-783`

```go
func (bc *Blockchain) isValidBlockFromBeacon(block *types.Block) bool {
    // ✅ Step 1: Verify Merkle root
    if block.Header.MerkleRoot != block.CalculateMerkleRoot() {
        logger.Error("Block Merkle root mismatch")
        return false
    }
    
    // ✅ Step 2: Verify all transaction signatures
    for _, tx := range block.Transactions {
        if !tx.Verify() {
            logger.Error("Transaction verification failed")
            return false
        }
    }
    
    // ✅ Step 3: Get validator public key and index
    validatorPubKey, exists := bc.validators[block.Header.ValidatorID]
    if !exists {
        logger.Error("Unknown validator")
        return false
    }
    
    validatorIndex := bc.validatorIndices[block.Header.ValidatorID]
    
    // ✅ Step 4: CRITICAL SECURITY - Verify Dilithium Mode 3 signature
    // This prevents: (1) Compromised beacon, (2) P2P attacks, (3) MITM
    if len(block.Signature) == 0 {
        logger.Error("Block missing Dilithium signature")
        return false
    }
    
    // 4a. Reconstruct canonical SignedHeader from wire format
    signedHeader := &types.SignedHeader{}
    if err := signedHeader.FromBlockHeader(&block.Header, validatorIndex); err != nil {
        logger.Error("Failed to create SignedHeader")
        return false
    }
    
    // 4b. Calculate canonical hash with domain separation
    canonicalHash := signedHeader.Hash(bc.chainID)
    
    // 4c. Verify Dilithium Mode 3 signature
    verifier := verify.NewVerifier([]dilithium.Mode{dilithium.Mode3})
    result := verifier.VerifyWithPublicKey(
        canonicalHash[:], 
        block.Signature, 
        validatorPubKey, 
        dilithium.Mode3,
    )
    
    if !result.Valid {
        logger.Error("❌ DILITHIUM SIGNATURE VERIFICATION FAILED",
            zap.String("validator_id", block.Header.ValidatorID),
            zap.String("error", result.Error))
        return false
    }
    
    logger.Debug("✅ Dilithium signature verified")
    
    // ✅ Step 5: DEFENSE-IN-DEPTH - Verify VRF proof independently
    // Even though beacon already verified, execution re-validates
    if len(block.Header.VRFProof) == 0 {
        logger.Error("Block missing VRF proof")
        return false
    }
    
    _, err := vrf.VerifyVRFProof(
        validatorPubKey, 
        block.Header.VRFSeed, 
        block.Header.VRFProof,
    )
    if err != nil {
        logger.Error("VRF proof verification failed")
        return false
    }
    
    logger.Info("✅ Block validated (Dilithium + VRF proofs verified)")
    return true
}
```

***

## What Execution Layer Validates (Defense-in-Depth)

The execution layer performs **complete independent verification**, not trust-based acceptance:

### 1. Dilithium Signature Re-Verification ✅

**Why**: Protects against compromised beacon node or P2P network attacks

```go
// Reconstruct canonical SignedHeader
signedHeader := &types.SignedHeader{}
signedHeader.FromBlockHeader(&block.Header, validatorIndex)

// Calculate canonical hash
canonicalHash := signedHeader.Hash(bc.chainID)

// Verify Dilithium Mode 3 signature
verifier := verify.NewVerifier([]dilithium.Mode{dilithium.Mode3})
result := verifier.VerifyWithPublicKey(canonicalHash[:], block.Signature, validatorPubKey, dilithium.Mode3)

if !result.Valid {
    return false  // Reject block
}
```

**Protection**: Even if beacon is compromised and forwards invalid block, execution rejects it.

### 2. VRF Proof Re-Verification ✅

**Why**: Ensures validator was legitimately selected by randomness

```go
_, err := vrf.VerifyVRFProof(validatorPubKey, block.Header.VRFSeed, block.Header.VRFProof)
if err != nil {
    return false  // Reject block
}
```

**Protection**: Prevents unauthorized validators from creating blocks (even with stolen signatures).

### 3. Merkle Root Verification ✅

Ensures all transactions in the block are authentic and unmodified:

```go
calculatedRoot := block.CalculateMerkleRoot()
if block.Header.MerkleRoot != calculatedRoot {
    return false  // Merkle root mismatch
}
```

**Protection**: Detects if transactions were added/removed/modified after beacon verification.

### 4. Transaction Signature Verification ✅

Every transaction has its own Dilithium signature from the user:

```go
for _, tx := range block.Transactions {
    if !tx.Verify() {  // Verifies user's Dilithium signature
        return false
    }
}
```

**Protection**: Prevents execution of unauthorized transactions even if beacon and block signatures are valid.

### 5. State Transition Validation ✅

Ensures block follows state machine rules:

```go
// Verify nonces (prevent replay)
if tx.Nonce != account.Nonce {
    return errors.New("invalid nonce")
}

// Verify balances (prevent overspending)
if account.Balance < tx.Value + tx.GasPrice * tx.GasLimit {
    return errors.New("insufficient balance")
}

// Verify gas limits
if tx.GasLimit > MaxGasPerBlock {
    return errors.New("gas limit exceeded")
}
```

**Protection**: Prevents invalid state changes (e.g., double spends, negative balances).

### 6. Smart Contract Execution ✅

QWVM executes contracts and validates results:

```go
result := qwvm.Execute(contract, input, gas)
if result.Error != nil {
    return errors.New("contract execution failed")
}
```

**Protection**: Ensures contract logic executes correctly and deterministically.

***

## Security Model: Defense-in-Depth

### Trust Assumptions

**What We Verify at BOTH Layers**:

* ✅ Dilithium Mode 3 block signatures (3,293 bytes)
* ✅ VRF randomness proofs
* ✅ Validator existence and stake
* ✅ Consensus rules (slot timing, epoch progression)

**What We Trust**:

* Network reliability between beacon and execution (localhost in single-node setup)
* Deterministic canonical encoding (SignedHeader format)
* Dilithium Mode 3 cryptographic security (NIST standardized)

**What We Don't Trust (Validated at Execution)**:

* Beacon node integrity (assume compromised)
* P2P network integrity (assume MITM attacks)
* Block transactions (independently verified)
* State transitions (independently validated)
* Merkle roots (independently computed)

### Attack Scenarios & Defense-in-Depth Protection

#### 1. Compromised Beacon Node

**Scenario**: Attacker gains control of beacon node, forwards invalid block to execution.

**Attack Vector**:

```
Attacker-Controlled Beacon → Execution Layer
         POST /api/v1/blocks
         {block with fake signature OR invalid VRF}
```

**Defense-in-Depth Protection**:

* ✅ **Execution re-verifies Dilithium signature** → Invalid signature detected, block rejected
* ✅ **Execution re-verifies VRF proof** → Invalid VRF detected, unauthorized validator rejected
* ✅ **Execution validates Merkle root** → Transaction tampering detected
* ✅ **Execution verifies all transaction signatures** → Forged transactions rejected
* ✅ **Execution validates state transitions** → Invalid state changes rejected

**Result**: Compromised beacon **cannot corrupt execution state**. All invalid blocks rejected at execution layer.

#### 2. Network Man-in-the-Middle (MITM)

**Scenario**: Attacker intercepts beacon→execution traffic, modifies block in transit.

**Attack Vector**:

```
Beacon → [Attacker Proxy] → Execution
         (tampers with transactions/signature)
```

**Defense-in-Depth Protection**:

* ✅ **Execution re-verifies Dilithium signature** → Signature no longer matches tampered block, rejected
* ✅ **Execution validates Merkle root** → Modified transactions cause Merkle mismatch, rejected
* ✅ **TLS encryption** (production deployments) → Prevents traffic inspection and tampering
* ✅ **Canonical hash recomputation** → Tampering changes hash, signature verification fails

**Result**: Tampered block **detected and rejected** during cryptographic verification.

#### 3. Validator Private Key Compromise

**Scenario**: Attacker steals validator's Dilithium private key, creates malicious blocks.

**Attack Vector**:

```
Attacker → Beacon (with stolen key)
         POST /api/v1/beacon/block/proposal
         {block with VALID signature but INVALID state transitions}
```

**Defense-in-Depth Protection**:

* ✅ **Beacon validates consensus rules** → Block must satisfy PoR timing, VRF selection
* ✅ **Beacon validates parent hash** → Block must extend valid chain
* ✅ **Execution validates state transitions** → Invalid nonces, negative balances detected
* ✅ **Execution validates transaction signatures** → Forged user transactions rejected
* ✅ **Slashing mechanism** → Validator loses stake for invalid blocks
* ✅ **RANDAO prevents selection prediction** → Attacker cannot predict when to propose

**Result**: Invalid blocks **rejected by consensus validation**. Valid but malicious blocks **rejected by state validation**. Validator **slashed for misbehavior**.

#### 4. Double-Spend Attempt

**Scenario**: Attacker controls beacon, tries to include transaction with invalid nonce.

**Attack Vector**:

```
Beacon (Compromised) → Execution
       Block with tx.Nonce = 5 (but account.Nonce = 7)
```

**Defense-in-Depth Protection**:

* ✅ **Execution validates every transaction nonce** against account state
* ✅ **Execution maintains independent BadgerDB state**
* ✅ **State root commitment in block header** (verified against local computation)
* ✅ **Merkle tree integrity** ensures transaction authenticity

**Result**: Block **rejected during transaction processing**, state remains consistent, double-spend prevented.

#### 5. P2P Network Attack (Fake Block Gossip)

**Scenario**: Attacker sends fake block directly to execution P2P network (bypassing beacon).

**Attack Vector**:

```
Attacker → Execution P2P (port 9000)
         GossipSub: FakeBlock{signature: invalid}
```

**Defense-in-Depth Protection**:

* ✅ **Execution re-verifies Dilithium signature on ALL blocks** (beacon + P2P sources)
* ✅ **Execution validates VRF proof** → Unauthorized validator detected
* ✅ **Validator registry check** → Unknown validator ID rejected
* ✅ **Canonical hash recomputation** → Invalid signature causes rejection

**Result**: Fake block **immediately rejected** during cryptographic verification, never reaches state machine.

***

## Comparison with Other Blockchains

### Ethereum 2.0

* **Architecture**: Beacon chain (consensus) + Execution layer (EVM)
* **Verification Model**: Execution trusts beacon's finality (minimal re-verification)
* **Rationale**: Beacon and execution tightly coupled, assume same operator
* **QuantumWing Difference**: **Defense-in-depth - Execution independently verifies ALL Dilithium signatures + VRF proofs**

### Bitcoin

* **Architecture**: Single layer, every node verifies everything
* **Verification Model**: Full verification at every node (no trust)
* **Rationale**: Decentralized security, no layer separation
* **QuantumWing Similarity**: **Same philosophy - both layers verify cryptographic proofs**

### Polkadot

* **Architecture**: Relay chain (consensus) + Parachains (execution)
* **Verification Model**: Parachains trust relay chain's GRANDPA finality
* **Rationale**: Parachain collators trust relay security
* **QuantumWing Difference**: **Execution doesn't blindly trust beacon - independently verifies all signatures**

### Cosmos

* **Architecture**: Hub (consensus) + Zones (execution)
* **Verification Model**: Zones trust Tendermint consensus of hub
* **Rationale**: IBC relayers trust source chain finality
* **QuantumWing Difference**: **Zero trust between layers**

**QuantumWing's Approach**: Prioritizes **security over performance**, using defense-in-depth to protect against quantum-era attacks. The \~2-5ms overhead of double verification is acceptable for quantum-safe guarantees.

***

## Performance Considerations

### Defense-in-Depth Overhead

```
Beacon Layer:
  - Dilithium.Verify() → 2-5ms per block
  - VRF.Verify() → 1-2ms per block
  - Forward to execution

Execution Layer:
  - Dilithium.Verify() → 2-5ms per block (RE-VERIFICATION)
  - VRF.Verify() → 1-2ms per block (RE-VERIFICATION)
  - Merkle root validation → 0.5ms
  - Transaction verification → variable (depends on tx count)
  - State transitions → variable

Total Cryptographic Overhead: 6-14ms per block (double verification)
```

### Performance vs Security Trade-off

**Current Choice**: **Security-first** (defense-in-depth)

* ✅ Protects against compromised beacon, P2P attacks, MITM
* ✅ Zero trust between layers (defense-in-depth)
* ⚠️ 6-14ms overhead per block (\~0.1% of 12-second slot time)

**Alternative (NOT IMPLEMENTED)**: **Performance-first** (trust boundary)

* ⚠️ Execution trusts beacon verification (skips Dilithium + VRF)
* ⚠️ Vulnerable to compromised beacon node
* ✅ 3-7ms saved per block (\~0.06% performance gain)

**Decision**: QuantumWing implements **security-first** model. For quantum-safe blockchain, **security > 0.06% performance gain**. The cryptographic overhead is negligible compared to 12-second slot time.

**Current Implementation**: `blockchain/core/blockchain.go:isValidBlockFromBeacon()` verifies ALL signatures.

### Optimization Opportunities (Future)

1. **Finality Gadget** (Phase 5, 2027):
   * Only forward finalized blocks (2+ epoch confirmations)
   * Execution MAY skip verification for finalized blocks (optional optimization)
   * Trade-off: 12-minute finality delay vs immediate propagation
2. **ZK-SNARKs** (Phase 6, 2027):
   * Beacon proves block validity with ZK-SNARK
   * Execution verifies tiny proof (\~10ms) instead of full Dilithium (\~5ms)
   * Benefit: Smaller proof size, faster verification
3. **Aggregate Signatures** (Phase 7, 2028):
   * Aggregate multiple block signatures into one
   * Verify N blocks with single Dilithium verification
   * Benefit: Amortized verification cost for batch sync

***

## Production Deployment Considerations

### Single-Node Setup (Development/Testnet)

**Security Model**: Beacon and execution on same machine, defense-in-depth verification.

```bash
# Start beacon and execution with local communication
./scripts/secure-three-layer.sh

# Beacon listens on 8080, execution on 8546
# Communication via http://localhost:8080 → http://localhost:8546
# Both layers perform FULL verification
```

**Security**: Minimal attack surface (localhost), defense-in-depth protects against software bugs.

### Distributed Setup (Production/Mainnet)

**Security Model**: Beacon and execution on separate machines, both perform full verification + TLS.

#### Step 1: Add Mutual TLS

**Beacon Configuration**:

```yaml
execution_endpoint: https://execution.quantumwing.net:8546
tls_cert: /etc/beacon/tls.crt
tls_key: /etc/beacon/tls.key
tls_ca: /etc/beacon/ca.crt  # Verify execution's certificate
```

**Execution Configuration**:

```yaml
beacon_endpoint: https://beacon.quantumwing.net:8080
tls_cert: /etc/execution/tls.crt
tls_key: /etc/execution/tls.key
tls_ca: /etc/execution/ca.crt  # Verify beacon's certificate
```

**Note**: TLS prevents MITM attacks, but execution **still re-verifies Dilithium signatures** for defense-in-depth.

#### Step 2: Monitoring & Alerting

**Metrics to Monitor**:

* Block hash divergence between nodes
* Dilithium signature verification failures (execution layer)
* VRF proof verification failures
* Merkle root validation failures
* Transaction signature failures
* State transition errors
* Beacon→Execution latency

**Alert Triggers**:

* Signature verification failure rate > 0% (possible attack)
* Block hash mismatch across 2+ nodes (possible fork)
* Merkle root failures > 0.1% (possible tampering)
* State transition errors > 0.1% (possible consensus bug)

**Example Prometheus Alerts**:

```yaml
- alert: DilithiumSignatureFailure
  expr: rate(dilithium_signature_failures[5m]) > 0
  annotations:
    summary: "Dilithium signature verification failures detected"
    description: "Execution layer rejecting blocks due to invalid signatures"

- alert: BlockHashDivergence
  expr: count(block_hash{height="latest"}) > 1
  annotations:
    summary: "Block hash divergence across nodes"
    description: "Possible chain fork or consensus bug"
```

***

## Future Enhancements

### 1. Finality Gadget (Phase 5, 2027)

Only forward finalized blocks to execution (2+ epoch confirmations):

```go
func (b *Beacon) OnBlockFinalized(block *types.Block) {
    // Wait for 2 epochs of attestations
    if block.Epoch + 2 <= b.CurrentEpoch {
        b.sendToExecution(block)  // Only send finalized blocks
    }
}
```

**Benefit**: Execution layer can OPTIONALLY trust finalized blocks (skip verification for performance).

**Current**: Execution verifies ALL blocks regardless of finality (maximum security).

**Trade-off**: 12-minute finality delay vs immediate propagation.

### 2. Zero-Knowledge Proofs (Phase 6, 2027)

Beacon proves block validity with ZK-SNARK:

```go
// Beacon generates ZK proof of Dilithium verification
proof := zksnark.Prove(block, dilithiumSignature, validatorPublicKey)
b.sendToExecution(block, proof)

// Execution verifies tiny ZK proof (10ms) instead of Dilithium (~5ms)
if !zksnark.Verify(proof, block.Hash()) {
    return errors.New("invalid ZK proof")
}
```

**Benefit**: Smaller proof size (\~200 bytes vs 3,293 bytes), faster verification (\~10ms vs \~5ms).

**Note**: Still provides cryptographic proof, not trust-based.

### 3. Checkpoint Verification (Phase 4, 2026)

Execution periodically cross-validates block hashes with beacon:

```go
func (bc *Blockchain) ValidateCheckpoint(height uint64) error {
    localHash := bc.GetBlockHash(height)
    beaconHash := bc.fetchBeaconBlockHash(height)
    
    if localHash != beaconHash {
        log.Error("⚠️ Checkpoint mismatch: possible fork or attack")
        bc.EmergencyPause("checkpoint divergence")
        return errors.New("checkpoint mismatch")
    }
    
    log.Info("✅ Checkpoint validated", "height", height)
}
```

**Benefit**: Detects long-range attacks or subtle consensus bugs.

### 4. Aggregate Signatures (Phase 7, 2028)

Aggregate multiple block signatures for batch verification:

```go
// Aggregate N block signatures into one
aggSignature := dilithium.Aggregate(sig1, sig2, ..., sigN)

// Verify N blocks with single Dilithium verification
if dilithium.VerifyAggregate(aggSignature, [block1.Hash(), ..., blockN.Hash()]) {
    // All N blocks valid
}
```

**Benefit**: Amortized verification cost for fast sync (verify 100 blocks in \~5ms instead of 500ms).

***

## Verification Logs

### Beacon Layer Logs (Full Verification)

```json
{"level":"info","ts":1759253906.612,"msg":"✅ Dilithium signature verified for block 7"}
{"level":"info","ts":1759253906.612,"msg":"✅ VRF proof verified for block 7"}
{"level":"info","ts":1759253906.612,"msg":"🔷 NEW BLOCK #7","validator":"0x8258...1ea8","txs":0}
```

### Execution Layer Logs (Defense-in-Depth Re-Verification)

```json
{"level":"debug","ts":1759253906.613,"msg":"✅ Dilithium signature verified","index":7,"validator":"0x8258782Ed32d4..."}
{"level":"info","ts":1759253906.613,"msg":"✅ Block validated (Dilithium + VRF proofs verified)","index":7,"validator":"0x8258782Ed32d464973308E395055b964D3531ea8"}
{"level":"info","ts":1759253906.613,"msg":"🔷 NEW BLOCK #7 | Validator: 0x8258...1ea8 | Txs: 0 | Hash: 842a6e32...b15c0546"}
{"level":"info","ts":1759253906.613,"msg":"Block processed successfully","block":7,"new_height":7}
```

**Key Observation**:

* Beacon: "✅ Dilithium signature verified for block 7"
* Execution: "✅ Block validated (Dilithium + VRF proofs verified)"

Both layers **independently verify** signatures (defense-in-depth).

***

## Testing Defense-in-Depth

### Unit Tests

**Test 1: Beacon Verification**

```go
func TestBeaconVerifiesSignature(t *testing.T) {
    block := createValidBlock()
    err := beacon.ValidateBlock(block)
    assert.NoError(t, err)
    assert.True(t, beacon.HasForwardedToExecution(block))
}
```

**Test 2: Execution ALSO Verifies (Defense-in-Depth)**

```go
func TestExecutionAlsoVerifiesSignature(t *testing.T) {
    block := createBlockFromBeacon()
    
    // Execution MUST call dilithium.Verify() (defense-in-depth)
    mockDilithium := &MockDilithium{VerifyCalled: false}
    blockchain.SetDilithiumVerifier(mockDilithium)
    
    err := blockchain.AddBlock(block)
    assert.NoError(t, err)
    assert.True(t, mockDilithium.VerifyCalled, "Execution must verify signature (defense-in-depth)")
}
```

**Test 3: Execution Rejects Invalid Signature**

```go
func TestExecutionRejectsInvalidSignature(t *testing.T) {
    block := createBlockFromBeacon()
    block.Signature = []byte{0x00, 0x00, ...}  // Invalid signature
    
    err := blockchain.AddBlock(block)
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "DILITHIUM SIGNATURE VERIFICATION FAILED")
}
```

**Test 4: Execution Validates Merkle Root**

```go
func TestExecutionValidatesMerkleRoot(t *testing.T) {
    block := createBlockFromBeacon()
    block.Header.MerkleRoot = "0x0000..."  // Invalid root
    
    err := blockchain.AddBlock(block)
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "Merkle root mismatch")
}
```

### Integration Tests

**Test 5: End-to-End Block Flow with Defense-in-Depth**

```go
func TestDefenseInDepthBlockFlow(t *testing.T) {
    // 1. Validator proposes block
    block := validator.ProposeBlock()
    
    // 2. Beacon verifies Dilithium signature (VERIFICATION #1)
    err := beacon.ValidateBlock(block)
    assert.NoError(t, err)
    
    // 3. Beacon forwards to execution
    beacon.ForwardToExecution(block)
    
    // 4. Execution re-verifies signature (VERIFICATION #2 - defense-in-depth)
    assert.Eventually(t, func() bool {
        return execution.GetBlockHeight() == block.Header.Number
    }, 5*time.Second, 100*time.Millisecond)
    
    // 5. Verify both layers performed verification
    assert.True(t, beacon.VerifiedBlock(block.Header.Number))
    assert.True(t, execution.VerifiedBlock(block.Header.Number))
}
```

**Test 6: Compromised Beacon Attack (Defense-in-Depth Protection)**

```go
func TestCompromisedBeaconAttack(t *testing.T) {
    // Attacker controls beacon, sends block with invalid signature
    maliciousBlock := createBlockWithInvalidSignature()
    
    // Beacon (compromised) forwards without verification
    beacon.ForwardToExecution(maliciousBlock)
    
    // Execution (defense-in-depth) rejects due to signature verification
    assert.Eventually(t, func() bool {
        return execution.GetBlockHeight() == previousHeight  // Block rejected, height unchanged
    }, 5*time.Second, 100*time.Millisecond)
    
    // Verify execution logged signature failure
    logs := execution.GetLogs()
    assert.Contains(t, logs, "❌ DILITHIUM SIGNATURE VERIFICATION FAILED")
}
```

**Test 7: Merkle Root Tampering (MITM Attack)**

```go
func TestMerkleRootTampering(t *testing.T) {
    // Beacon verifies and forwards valid block
    validBlock := createValidBlock()
    beacon.ValidateBlock(validBlock)
    
    // Attacker intercepts and modifies transactions (MITM)
    tamperedBlock := validBlock.Clone()
    tamperedBlock.Transactions = append(tamperedBlock.Transactions, maliciousTx)
    // (Merkle root NOT updated, signature still valid for original block)
    
    // Execution rejects due to Merkle mismatch (defense-in-depth)
    err := execution.AddBlock(tamperedBlock)
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "Merkle root mismatch")
}
```

***

## Best Practices

### 1. Always Validate Critical Cryptographic Proofs

Defense-in-depth requires validation at **every layer**:

* ✅ Dilithium Mode 3 signatures (3,293 bytes)
* ✅ VRF randomness proofs
* ✅ Merkle roots (detect transaction tampering)
* ✅ Transaction signatures (detect forged transactions)
* ✅ State transitions (detect double spends)
* ✅ Validator existence (detect fake validators)

### 2. Use Canonical Encoding for Deterministic Hashing

```go
// ✅ CORRECT: Use canonical SignedHeader
signedHeader := &types.SignedHeader{}
signedHeader.FromBlockHeader(&block.Header, validatorIndex)
canonicalHash := signedHeader.Hash(chainID)
dilithium.Verify(publicKey, canonicalHash, signature)

// ❌ WRONG: Hash wire format BlockHeader
wireHash := block.Header.Hash()  // Non-deterministic across JSON transmission
dilithium.Verify(publicKey, wireHash, signature)  // Will fail!
```

### 3. Use TLS for Distributed Deployments

```yaml
# beacon-config.yaml
execution_endpoint: https://execution.internal:8546
tls_enabled: true
tls_verify_peer: true
```

**Note**: TLS prevents MITM, but defense-in-depth (signature re-verification) protects even without TLS.

### 4. Monitor Verification Failures

```go
func (bc *Blockchain) MonitorSignatureFailures() {
    ticker := time.NewTicker(1 * time.Minute)
    for range ticker.C {
        failureRate := bc.GetSignatureFailureRate()
        
        if failureRate > 0 {
            log.Error("⚠️ Dilithium signature failures detected!",
                "failure_rate", failureRate,
                "possible_cause", "compromised beacon or P2P attack")
            bc.TriggerSecurityAlert()
        }
    }
}
```

### 5. Implement Emergency Pause

```go
func (bc *Blockchain) EmergencyPause(reason string) {
    bc.paused = true
    log.Error("🚨 EMERGENCY PAUSE", "reason", reason)
    bc.NotifyOperators(reason)
    bc.DisableBlockAcceptance()
}

// Trigger on suspicious activity
if consecutiveSignatureFailures > 3 {
    bc.EmergencyPause("multiple signature verification failures")
}
```

### 6. Log Defense-in-Depth Validations

```go
log.Debug("✅ Dilithium signature verified",
    "index", block.Header.Index,
    "validator", block.Header.ValidatorID)

log.Info("✅ Block validated (Dilithium + VRF proofs verified)",
    "index", block.Header.Index,
    "validator", block.Header.ValidatorID,
    "merkle_root", block.Header.MerkleRoot)
```

***

## Conclusion

The **defense-in-depth architecture** is a **production-ready, security-first solution** that:

1. ✅ **Solves canonical encoding issue** using SignedHeader format for deterministic hashing
2. ✅ **Provides zero-trust security** between beacon and execution layers
3. ✅ **Protects against multiple attack vectors**:
   * Compromised beacon node (malicious block forwarding)
   * P2P network attacks (fake block injection)
   * MITM attacks (block tampering in transit)
   * Validator key compromise (invalid blocks with valid signatures)
4. ✅ **Maintains cryptographic guarantees** through independent verification at each layer
5. ✅ **Prioritizes security over performance** (\~6-14ms overhead acceptable for quantum-safe guarantees)
6. ✅ **Uses NIST-standardized cryptography** (Dilithium Mode 3, SHA3-256)

**Key Takeaway**: QuantumWing implements **Bitcoin-style full verification** across layers, not Ethereum 2.0-style trust boundaries. This defense-in-depth approach ensures that:

* **No single point of failure**: Compromised beacon cannot corrupt execution state
* **Multiple validation checkpoints**: Dilithium signature → VRF proof → Merkle root → Transaction signatures → State transitions
* **Quantum-safe end-to-end**: Every cryptographic proof independently verified at each layer
* **Production-ready security**: Has been validated with real Dilithium Mode 3 signatures, multiple validators, and RANDAO-based consensus

**Current Status** (June 2026): **92/100 production score** with defense-in-depth security model deployed and tested.

***

## Related Documentation

* [Three-Layer Design](/quantumwing/architecture/three-layer-design.md) - Detailed architecture overview
* [Canonical Encoding](/quantumwing/architecture/canonical-encoding.md) - SignedHeader format specification
* [Proof of Randomness](/quantumwing/consensus/proof-of-randomness.md) - PoR consensus mechanism
* [Dilithium Signatures](/quantumwing/cryptography/quantum-safe-crypto.md) - Quantum-safe cryptography
* [Production Setup](/quantumwing/deployment/production-setup.md) - Deployment guide with TLS configuration


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://quantumwing.gitbook.io/quantumwing/architecture/trust-boundaries.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `build a script that syncs our docs to a CMS` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
