Technical Documentation

CONTEXT Whitepaper

Decentralized P2P Messaging Network with Blockchain Economy

📄 Version: 1.0 📅 May 2026 🪙 Token Ticker: CTX

1. Abstract

CONTEXT is an open decentralized P2P messaging network built on top of the libp2p protocol using Ed25519 cryptography and Noise Protocol transport encryption. The system eliminates the single point of failure of traditional messengers: messages are replicated across a network of independent relay nodes, whose operation is incentivized by the native CTX token.

Key properties of the system:


2. Introduction & Motivation

2.1 The Problem of Centralized Messengers

Modern communication platforms (Telegram, WhatsApp, Signal) store metadata and/or message content on the company's servers. This creates systemic risks:

Risk Description
Single point of failure Infrastructure failure makes the service globally unavailable
Censorship Companies or governments can block the service or users
Metadata leakage Communication graph, IP addresses, and timestamps reveal significant information
Vendor Lock-In Users do not control their data and identity
Trust in third party Even with E2E encryption, users must trust the server

2.2 Limitations of Existing Decentralized Solutions

Existing decentralized solutions (Matrix, Session, Briar) have their own trade-offs:

2.3 The CONTEXT Approach

CONTEXT uses a relay architecture: specialized nodes (relays) accept messages from clients, temporarily store them, and replicate among themselves. Relays are not "servers" in the traditional sense — anyone can run their own node, and the network economy motivates operators toward honest behavior through staking and slashing mechanisms.

Client A → Relay-1 ↔ Relay-2 ↔ Relay-3 → Client B
                 ↕ DHT Discovery ↕
               (Kademlia / mDNS)

3. System Architecture

3.1 Network Topology

The CONTEXT network consists of three types of nodes:

Node Type Role Run By
Relay Storage, routing, message replication Operators (earn CTX)
Client Sending and receiving messages End users
Service Bots, storage, media conversion (Phase 4+) Service operators

Key topology constraints:

3.2 Relay Node Multi-Layer Architecture

┌────────────────────────────────────────────────────┐
│                    Layer 1: Transport               │
│   TCP + QUIC │ AutoNAT │ Circuit Relay v2 │ Tor      │
├────────────────────────────────────────────────────┤
│                    Layer 2: Discovery               │
│   Kademlia DHT │ mDNS (LAN) │ GossipSub │ PubSub    │
├────────────────────────────────────────────────────┤
│                    Layer 3: Protocol                │
│   /ctx/1.2  │  Framing  │  Stream Mux  │  Noise     │
├────────────────────────────────────────────────────┤
│                  Layer 4: Business Logic            │
│  Message Handler │ Replicator │ Auth Module │ VClock │
├────────────────────────────────────────────────────┤
│                    Layer 5: Storage                 │
│   SQLite │ Unit of Work │ Message Repo │ Tombstones  │
└────────────────────────────────────────────────────┘

3.3 Component Diagram

[libp2p Host]
     │
     ├─ [CTX Protocol Handler /ctx/1.2]
     │        ├─ [Auth Verifier] ← Ed25519 sig check
     │        ├─ [Rate Limiter] ← Token Bucket / PeerID
     │        ├─ [Unit of Work] ← transactionality
     │        └─ [Replicator] → other relays
     │
     ├─ [DHT Module] ← Kademlia peer discovery
     ├─ [GossipSub] ← pub/sub topics
     ├─ [AutoNAT] ← NAT type detection
     ├─ [Health Server] ← HTTP /health /ready
     └─ [Blockchain Node] ← Phase 2
              ├─ [TxPool]
              ├─ [BFT Validator]
              ├─ [EmissionService]
              ├─ [UptimeTracker]
              └─ [ContractEngine]

3.4 Message Lifecycle

1. Client composes a message:
   - Generates UUID
   - Computes SHA-256(payload) → hash_sum
   - Signs Ed25519(privkey, message_hash)

2. SEND /ctx/1.2 → Relay-1:
   - Relay validates signature
   - Checks hash_sum
   - Rate-limit check (Token Bucket)
   - Validates timestamp ± 5 min (replay protection)

3. Relay-1 saves to SQLite:
   - UnitOfWork.Begin()
   - MessageRepo.Save(msg)
   - UnitOfWork.Commit()
   - ACK → Client

4. Eager Push replication:
   - Relay-1 → Relay-2, Relay-3 asynchronously
   - REPLICATE action (relay→relay)
   - Deduplication by MessageID on receiving side

5. Push notification (Phase 3):
   - Relay sends APNS/FCM/Huawei push
   - Recipient receives offline notification

6. Recipient online:
   - FETCH /ctx/1.2 → any Relay in the pool
   - Retrieves messages since_ts
   - Decrypts payload locally

7. Blockchain registration (Phase 2):
   - TxTypeMessageRegistration (without payload)
   - FullMessageHash = SHA-256(entire message with payload)
   - Verifiability without content disclosure

4. CTX Protocol v1.2

4.1 Transport Specification

CTX operates on top of libp2p streams with the identifier /ctx/1.2/{ReceiverPeerID}.

Framing: each message is preceded by a 4-byte big-endian length prefix:

┌──────────────┬─────────────────────────────────────┐
│   4 bytes    │           N bytes                    │
│  Big-Endian  │         JSON Payload                 │
│    Length    │                                      │
└──────────────┴─────────────────────────────────────┘

5. Cryptography & Security

5.1 Node Identity

Each relay and client is identified through an Ed25519 keypair:

Ed25519 keypair → PeerID = multihash(SHA-256(pubkey))
Multiaddr: /ip4/{IP}/tcp/{PORT}/p2p/{PeerID}

The keypair is generated on first launch and saved to the identity.key file. Loss of the key means loss of identity.

5.2 Transport Encryption

Noise Protocol (XX handshake pattern) provides:

Noise is built into libp2p as the default security transport — all connections in the CONTEXT network are automatically encrypted.

5.3 Message Integrity

Each message contains:

5.4 Connection Gater

Connection Gater operates at the TCP/QUIC connection level:

5.5 Anti-Fraud (7 levels) — Phase 2

When blockchain mode is activated, a 7-level anti-fraud system is added:

Level Check Type Action on Violation
1 Signature verification Immediate rejection
2 Sequence / Nonce check Rejection, warning
3 Timestamp validation Rejection
4 Challenge-response Repeat request
5 Proof-of-Work micro Throttle
6 Attestation check Reputation downgrade
7 Auto-ban Network exclusion

6. Privacy Models

6.1 Public Mode

In public mode, the relay accepts and replicates any messages without additional checks. Transport is encrypted (Noise), payload may be encrypted by the application, but the relay imposes no restrictions.

Public channels always operate in public mode — their messages are distributed across the entire network.

6.2 Private Mode

Private mode is activated at the relay level via RELAY_PRIVATE_MODE=true. It operates on group authentication with three keys:

Key Stored Purpose
AUTH_SERVICE_PUBKEY Publicly known to the entire group Ed25519 public key of the group admin operator
NETSIGN On each relay Ed25519 signature of this relay's PeerID, made by the operator
NETSIGN On the client Ed25519 signature of the ClientID, made by the operator

Receiving relay verification:

Verify(AUTH_SERVICE_PUBKEY_src, ID_dst, NETSIGN_stored) = True

Client verification:

Verify(AUTH_SERVICE_PUBKEY_relay, ID_client, NETSIGN_relay) = True

6.3 Private Message Routing Rules

Client sends IsPrivate=true → only to verified private relays
Relay receives IsPrivate=true → replicates only within the private cluster
Public relay receives IsPrivate=true → rejects when PRIVATE_MODE=true

6.4 Chat Types

Type IsPrivate Availability
Public Channel false All network nodes
Personal Chat false Any relays
Group Chat false Any relays
Personal Private true Private relays only
Group Private true Private relays only

7. Blockchain Core

7.1 Concept

CONTEXT uses a linear blockchain (not DAG, not sharded in Phase 2) with the following characteristics:

Storage separation principle:

7.2 Block Structure

Block {
  Height:       uint64          // Monotonic number
  Timestamp:    int64           // Unix nanoseconds
  PrevHash:     [32]byte        // SHA-256 of previous block
  TxRoot:       [32]byte        // Merkle root of transactions
  StateRoot:    [32]byte        // Merkle root of balances
  ContractRoot: [32]byte        // Merkle root of contracts
  Transactions: []*Transaction  // Ordered list
  ProposerAddr: Address         // Proposer validator address
  Signatures:   []BlockSig      // BFT validator signatures (≥⅔)
  Hash:         [32]byte        // SHA-256 of block (without Signatures)
}

7.3 Transaction Types

Type Hex Description
TxTypeMessageRegistration 0x01 Message registration (without payload)
TxTypeTransfer 0x02 CTX token transfer
TxTypeReward 0x03 Uptime reward payout
TxTypeCheckpoint 0x04 Checkpoint with epoch data
TxTypeContractDeploy 0x05 Smart contract publication
TxTypeContractCall 0x06 Session open / payment
TxTypeContractSettle 0x07 Session close / escrow settlement
TxTypeBurn 0x08 Token burning

7.4 Transaction Structure

Transaction {
  Hash:      [32]byte  // SHA-256(all fields except Signature)
  Type:      uint8     // Transaction type
  Timestamp: int64     // Unix nanoseconds
  Sender:    [20]byte  // Address from Ed25519 pubkey
  Recipient: [20]byte  // Recipient address
  Amount:    uint64    // In smallest units (1 CTX = 10^8)
  Nonce:     uint64    // Sequence number (anti-replay)
  Data:      []byte    // Protobuf data (depends on Type)

  // TxTypeMessageRegistration:
  MessageID:       string   // Message UUID
  FromPeer:        string   // libp2p PeerID
  FullMessageHash: [32]byte // SHA-256(full message with payload)
  IsPrivate:       bool
  LifeTime:        int

  // Signature:
  SenderPubKey: []byte  // Ed25519 pubkey (32 bytes)
  Signature:    []byte  // Ed25519 signature (64 bytes)
}

7.5 BFT Consensus

CONTEXT uses Byzantine Fault Tolerant consensus:

Validators = top-N relays by stake size
Proposer = deterministic selection from validators (round-robin)
Commit = ≥⅔ validator signatures for the block
Resilience: network continues operation with ≤⅓ malicious nodes

Checkpoint is created every N blocks and contains:

7.6 Message Registration on Blockchain

Each message is registered on the blockchain without payload to save space:

TxTypeMessageRegistration:
  ✓ MessageID     → message UUID
  ✓ FromPeer      → sender
  ✓ FullMessageHash → SHA-256(full message with payload)
  ✗ Payload       → NOT written to blockchain

FullMessageHash allows verifying message integrity during replication without storing content in the public ledger.


9. CTX Tokenomics

8.1 Token Parameters

Parameter Value
Name Context Token
Ticker CTX
Decimals 8 (1 CTX = 100,000,000 units)
Initial Supply 0 CTX (fair launch, no pre-mine)
Initial Emission 128 CTX / 24 hours
Halving Every 4 years (~1,461 epochs)
Asymptotic Limit ~373,760 CTX
Minimum Stake 100 CTX
Model Decreasing inflationary + deflationary burn

8.2 Emission Mechanism (Uptime Rewards)

Epoch = 24 hours. Emission is distributed proportionally to uptime:

reward_i = emission_per_epoch × (uptime_i / total_uptime_eligible_peers)

Conditions for receiving rewards:

If no eligible peers during an epoch — emission is burned (sent to Burn Address).

8.3 Halving Schedule

Period Epochs CTX / day CTX / year Cumulative Emission
Year 1–4 0–1,460 128 46,720 186,880
Year 5–8 1,461–2,921 64 23,360 280,320
Year 9–12 2,922–4,382 32 11,680 327,040
Year 13–16 4,383–5,843 16 5,840 350,400
Year 17–20 5,844–7,304 8 2,920 362,080
Year 21–24 7,305–8,765 4 1,460 367,920
Year 25+ 8,766+ 2 730 → 373,760 (asymptote)

After 24 years, emission is fixed at a symbolic 2 CTX/day as an incentive for maintaining infrastructure.

8.4 Staking

Minimum stake:          1000 CTX
Lock-up period:         Epoch (24 hours)
Stake withdrawal:       After epoch completion without violations
Slashing (double-sign): -100% of stake (burned)
Slashing (downtime):    -5% of stake when downtime > 1 hour

8.5 Burn Mechanism

Burn creates deflationary pressure and ensures utilization of undistributed emission:

Channel Type Amount Frequency
Undistributed emission TxTypeBurn 100% of emission Each epoch (rare)
Division remainder (dust) TxTypeBurn < 1 CTX Each epoch
Contract fee TxTypeBurn 10% of escrow amount On each ContractSettle
Transfer fee TxTypeBurn 0.001 CTX On each Transfer
Slashing TxTypeBurn 5% or 100% On violation

Burn Address — deterministic address with no known private key:

BurnAddress = SHA-512("CTX-Burn-Address-v1")[:20]

Any tokens sent to this address are permanently removed from circulation. Attempts to spend funds from the Burn Address are rejected at the validator level.

8.6 Economic Incentives

Network growth scenario (year 1):
  Emission:              +46,720 CTX
  Burn (transfers):      -500 CTX (estimated)
  Burn (contracts):      -300 CTX (estimated)
  Burn (slashing):       -200 CTX (estimated)
  Net inflation:         ≈ +45,720 CTX

Mature network scenario (year 10):
  Emission:              +11,680 CTX
  Burn (all channels):   -3,000 CTX (estimated)
  Net inflation:         ≈ +8,680 CTX

9. Smart Contracts

9.1 Concept

CTX smart contracts are deterministic, non-Turing-complete constructs for managing service sessions. Unlike EVM contracts:

9.2 Service Node Types

Type String Payment Unit
Bot service:bot per_request
Storage service:storage per_mb_day
Media service:media per_operation
Bridge service:bridge per_transfer
Index service:index per_query
Custom service:custom per_unit

9.3 Session Lifecycle

Provider publishes ServiceContract:
  └─ TxTypeContractDeploy → blockchain
     - ServiceType, Name, PricePerUnit
     - MinDeposit, SessionTTL
     - ProviderAddr, ProviderPubKey

User opens session:
  └─ TxTypeContractCall → blockchain
     - DepositTxHash (freezes CTX in escrow)
     - UserAddr, UserPubKey
     - ContractID

Service usage:
  - User interacts with the service node
  - Provider tracks consumption (UnitsConsumed)

Session close:
  └─ TxTypeContractSettle → blockchain
     - Provider receives: Amount - 10% burn
     - User receives: Deposit - Amount
     - BurnAddress receives: 10% of Amount

Dispute resolution:
  └─ DisputeContract (oracle or validator voting)

9.4 Contract Registry

All active service contracts are stored in the Registry:


10. Fraud Protection

10.1 Uptime Anti-Fraud

Uptime Tracker implements 7-level heartbeat message verification to prevent activity time falsification:

Level 1: Signature     — Ed25519 heartbeat signature
Level 2: Sequence      — Monotonic counter (anti-replay)
Level 3: Timestamp     — Delta validation (Clock Skew ≤ 30s)
Level 4: Challenge     — Random challenge-response
Level 5: PoW micro     — Light hashcash for Sybil protection
Level 6: Attestation   — Verification via other nodes
Level 7: Auto-ban      — Violator exclusion

10.2 Double-Sign Protection

If a validator signs two different blocks at the same height:

  1. BFT validators detect the double signature
  2. TxTypeSlash transaction → 100% of stake burned
  3. PeerID added to blocklist

10.3 Downtime Slashing

On heartbeat absence for more than 1 hour with active stake:


11. Desktop Wallet

11.1 Technology Stack

CTX Wallet — desktop application with the following architecture:

11.2 Cryptographic Standards

Function Standard
Mnemonic generation BIP-39 (2048 words)
Key derivation SLIP-0010 (Ed25519)
Keystore encryption AES-256-GCM + scrypt (N=262144)
Keystore MAC HMAC-SHA256
File permissions 0400 (owner read-only)
Mnemonic (12/24 words BIP-39)
         ↓ SLIP-0010
Ed25519 Master Key
         ↓ Derivation Path m/44'/CTX'/0'/0/0
Ed25519 Account Key → CTX Address (20 bytes)

11.3 Functionality


12. Comparative Analysis

Criterion CONTEXT Telegram Signal Matrix Session
Decentralization ✅ Full ❌ None ❌ None ⚠️ Federated ✅ Full
E2E Encryption ✅ (opt.) ⚠️ Secret Chat ✅ Full ⚠️ Optional ✅ Full
No Registration ❌ Phone ❌ Phone ❌ Email/Phone
Censorship Resistance ✅ Tor+DHT ⚠️ ✅ Onion
Open Source ⚠️ Partial ⚠️ Partial
Economic Incentives ✅ CTX
Push Without Server ✅ APNS/FCM
Offline Work ⚠️ mDNS (LAN)
Smart Contracts ✅ Phase 4
Central Server ❌ None ✅ Yes ✅ Yes ⚠️ Domain ❌ None

13. Roadmap

Phase 1 — Basic Infrastructure ✅ Completed

Phase 2 — Security & Replication ✅ Completed

Phase 3 — Push & Mobile Clients ✅ Completed

Phase 4 — Blockchain & Tokenomics 🔵 In Development

Phase 5 — Ecosystem ○ Planned


14. Tech Stack

Component Technology Version
Relay runtime Go 1.25+
P2P networking go-libp2p latest
Database (P1) SQLite (modernc, Pure Go)
Database (P2) Pebble (LSM-tree)
Mobile client Flutter / Dart 3.x
Desktop wallet Wails v2 + Svelte + TypeScript
Protobuf google.golang.org/protobuf
Cryptography Ed25519 (stdlib crypto/ed25519)
Transport security Noise Protocol (libp2p built-in)
Containerization Docker + Docker Compose
Key derivation SLIP-0010 (BIP-39 mnemonic)
Keystore encryption AES-256-GCM + scrypt N=262144

14.1 Key Architectural Decisions

Decision Rationale
Unit of Work Transactional integrity for save + replication
Eager Push replication Minimal latency (push on receive, not pull on demand)
Vector Clock Causal ordering without a central coordinator
Linear blockchain Simplicity, predictability, 1s blocks without fork probability
Ed25519 stdlib No external crypto dependencies, standard algorithm security
Proof of Stake Energy-efficient consensus with economic incentives
Escrow + Burn Fair service marketplace with deflationary mechanism
Pure-Go SQLite No CGO dependencies, simple compilation and cross-compilation
Noise Transport Standard libp2p encryption (ChaCha20-Poly1305)
Per-PeerID RateLimit Token Bucket protection against flood from specific peers
ConnectionGater Blocking at TCP/QUIC level before stream establishment
Multi-stage Docker Minimal production image without Go toolchain

15. Conclusion

CONTEXT presents an architecturally complete solution for decentralized communications, combining several key innovations:

  1. Relay architecture eliminates the single point of failure while maintaining practicality (push notifications, offline delivery)
  2. Cryptographic identity based on Ed25519 gives users full sovereignty over their identity without dependence on phone numbers or email
  3. CTX tokenomics creates a sustainable economic model for infrastructure operators through an uptime-rewards mechanism with halving and deflationary burn
  4. Blockchain verifiability provides transparent auditing without disclosing message content
  5. Multi-layer security from transport level (Noise) to application level (Ed25519 signatures, private mode) protects against various attack classes

The project is developed openly under the MIT license. Community participation is welcome at all levels: from running relay nodes to contributing to the protocol.


16. References