agorix
AirdropMarketsCollectionsLeaderboardActivity
Agorix · Decentralized Marketplace
Independent · Resilient · Community-Run

A cross-chain marketplace, run by the community.

Discover, list, and trade across Bitcoin, Ethereum, and Solana on an open, community-run network.

Marketplace
CollectionsMarketsLeaderboardActivity
Network
GovernanceExplorerAirdropDocs
Account
ProfileSettings
Legal
Terms of ServicePrivacy PolicyYour Privacy Choices
agorix.io — Lasting Access
CID: 0xA60R1X · v0.1
AirdropMarketsCollections
D
Protocol Docs
OverviewHow It WorksRunning a NodeArchitecture
Docs/Getting Started/Architecture
Getting Started

Architecture

Deep dive into the system architecture: monorepo packages, dependency flow, node isolation, gossip mesh protocol, shard ring, binary wire format, neighbor selection, and Rust node-core internals.

#Architecture

This page covers the full system architecture: how the monorepo is organized, how nodes communicate, how data is replicated and sharded, and what the Rust microservice does.

#Monorepo Structure

The codebase is organized into 8 packages and 2 services with strict dependency rules. No package may import from a package that depends on it (no circular dependencies).

Packages:

PackageDependenciesPurpose
protocolNone (zero framework deps)Pure Zod schemas, 46 event types, deterministic validation logic, consensus rules
dbprotocolDrizzle ORM schemas, PostgreSQL 16 migrations, typed query helpers
agentprotocol, dbGossip mesh networking, peer discovery, event propagation, WebSocket management
serverprotocol, db, cache, configBusiness logic, tRPC routers, API handlers, settlement orchestration
cacheNone (standalone)ioredis client, rate limiting, caching strategies, pubsub
configNone (standalone)Environment validation, feature flags, node configuration schemas
cliprotocol, configCommand-line tooling for node operators
front-door-gatewaycache onlyStateless edge proxy, rate limiting, request routing

Services:

ServiceStackPurpose
node-coreRust (Axum)60+ HTTP endpoints for PSBT operations, Ed25519 signing, AES-GCM encryption, Shamir splitting, scanner loops
benchmark-dashboardTypeScriptDevelopment performance dashboard with live JSON Lines streaming

#Dependency Flow

The dependency graph is strictly acyclic:

text
                    protocol
                   (zero deps)
                   /         \
                  v           v
                db          config
              /    \          |
             v      v         v
          agent   server <----+
            |       |
            v       v
               cache
                 |
                 v
        front-door-gateway
           (cache only)

The protocol package sits at the root. It contains all 46 event type definitions, Zod schemas for validation, and deterministic logic (witness selection, fee calculation, threshold checks). Because it has zero dependencies, it can be used by any other package safely. It is also the package that gets version-locked for consensus -- all nodes must agree on the protocol version.

#Node Isolation

There is no shared database. This is a fundamental design constraint.

Each node runs its own PostgreSQL 16 instance with its own schemas and data. Nodes do not connect to each other's databases. There is no central database, no database replication, no read replicas shared between nodes.

How data consistency works without a shared database:

Data TypeReplication Strategy
Protocol events (listings, orders, attestations, votes)Fully replicated via gossip -- every node stores every event
Chat messagesSharded via rendezvous hashing -- each thread assigned to specific nodes
Media cacheSharded via rendezvous hashing -- each entry assigned to specific nodes
PSBT shardsShamir 3-of-4 distribution to specific shard-holder nodes
Node state (local)Not replicated -- internal bookkeeping per node

This isolation means a compromised node cannot tamper with another node's data. It also means the network has no single point of failure for storage.

#Binary Wire Protocol

Node-to-node communication uses a compact binary wire protocol with minimal overhead. Every message starts with a 1-byte type tag followed by the payload.

ByteMessage TypeDirectionPurpose
0x01HELLOBidirectionalInitial handshake with Ed25519 pubkey and protocol version
0x02HELLO_ACKResponseHandshake acknowledgement with challenge nonce
0x03AUTH_CHALLENGERequestEd25519 signature challenge
0x04AUTH_RESPONSEResponseSigned challenge response
0x05EVENT_NOTIFYPushNotify peer of a new event (hash + metadata)
0x06EVENT_REQUESTPullRequest full event payload by hash
0x07EVENT_PAYLOADResponseFull event data
0x08HEARTBEATBidirectionalLiveness and state vector exchange
0x09PEER_LISTPushShare known peers for discovery
0x0ASHARD_STOREPushStore an encrypted PSBT shard
0x0BSHARD_REQUESTPullRequest a stored shard for reconstruction
0x0CSHARD_PAYLOADResponseEncrypted shard data
0x0DCHALLENGE_REQRequestPoA challenge for capability verification
0x0ECHALLENGE_RESResponsePoA challenge answer
0x0FCOHORT_JOINPushJoin a temporary session cohort
0x10COHORT_MSGPushMessage within a session cohort
0x11COHORT_LEAVEPushLeave a session cohort
0x12PINGBidirectionalKeepalive

The 18 message types (0x01 through 0x12) cover the full range of node interactions. The binary format avoids JSON parsing overhead for high-frequency messages like heartbeats and event notifications.

#Gossip Mesh

Nodes connect to each other over WebSocket at the /gossip endpoint. Every connection begins with Ed25519 authentication -- a node must prove it owns the private key corresponding to its announced public key.

Event Propagation:

The gossip protocol uses a push-pull model:

  • Push (EVENT_NOTIFY): When a node receives or creates a new event, it sends the event hash and metadata to its neighbors.
  • Pull (EVENT_REQUEST): A neighbor that does not have the event requests the full payload.
  • Payload (EVENT_PAYLOAD): The originating node sends the complete event.

This is more efficient than broadcasting full events because most neighbors already have most events. The push notification is small (just a hash), and the pull only happens when needed.

#K=6 Neighbor Selection

Each node maintains connections to exactly 6 neighbors, selected to balance network locality with resilience:

SlotSelection StrategyPurpose
3 close neighborsLowest latency from recent measurementsFast propagation to nearby nodes
2 mid-range neighborsModerate distance in the ID spaceBridge between clusters
1 random neighborUniformly random from all known nodesPrevent network partitions

This K=6 strategy ensures that the gossip mesh does not form disconnected clusters. The 3 close neighbors provide fast local propagation, the 2 mid-range neighbors bridge regions, and the 1 random neighbor provides a probabilistic guarantee against partitions.

Neighbors are periodically re-evaluated based on measured latency and liveness.

#Epidemic Heartbeats

Nodes exchange heartbeats to track liveness and synchronize state vectors. The heartbeat protocol uses epidemic (gossip-style) propagation:

text
Convergence: O(log N) rounds for N nodes
TTL per heartbeat: max(4, ceil(ln(N)))

Each heartbeat contains:

  • The sending node's current state vector (which events it has seen)
  • Timestamps for liveness tracking
  • A TTL counter that decrements at each hop

With O(log N) convergence, a network of 1,000 nodes converges in roughly 7 rounds. The TTL formula max(4, ceil(ln(N))) ensures heartbeats propagate far enough to reach all nodes without flooding the network -- at 1,000 nodes the TTL is 7, at 10,000 nodes the TTL is 10.

#Shard Ring

Non-protocol data (chat threads, media cache) is distributed across nodes using rendezvous hashing (highest random weight):

text
For a given data key and set of N nodes:
  For each node:
    weight = hash(key + nodeId)
  Sort nodes by weight descending
  Assign data to the top R nodes

The replica count R is calculated as:

text
R = ceil(N / 3)

For a 9-node network, R = 3. For a 12-node network, R = 4. Each chat thread is cloned to roughly one third of the live mesh, and different thread keys spread those replicas across the full network.

Rendezvous hashing has a key advantage over consistent hashing: when a node joins or leaves, only the data that hashes to that node needs to move. There is no cascading redistribution.

Operators can override the shard ring by enabling full-node mode (FULL_NODE_CHAT=1, FULL_NODE_MEDIA=1), which stores all data locally regardless of shard assignment. This does not affect PSBT shard distribution, which always uses the Shamir 3-of-4 scheme.

#Cohort Mesh

For time-sensitive session consensus (like attestation rounds), the protocol creates temporary direct WebSocket connections between participants:

  • When a session starts, the selected witnesses establish direct connections to each other (COHORT_JOIN)
  • Session messages are exchanged directly within the cohort (COHORT_MSG), bypassing the gossip mesh for lower latency
  • When the session concludes, the cohort is dissolved (COHORT_LEAVE) and the results are propagated via the normal gossip mesh

This two-tier approach means the gossip mesh handles bulk event propagation (where O(log N) convergence is fine), while the cohort mesh handles time-critical consensus (where direct connections provide sub-second latency).

#Rust Node-Core

The node-core service is a Rust binary built on the Axum web framework. It runs on port 9100 by default and exposes 60+ HTTP endpoints consumed by the TypeScript layer.

Why Rust?

The operations handled by node-core are performance-critical and security-sensitive:

  • PSBT construction and validation -- parsing and manipulating Bitcoin transactions requires exact byte-level correctness
  • Ed25519 signing and verification -- all 46 event types must be signed, and signature verification is on the hot path for every incoming gossip message
  • AES-GCM encryption/decryption -- PSBT shards are encrypted before distribution
  • Shamir secret sharing -- splitting and reconstructing PSBT data requires modular arithmetic over finite fields
  • Scanner loops -- mempool watching and block scanning run continuously and must be efficient

Key Endpoint Categories:

CategoryExamplesCount
PSBT operationsCreate, validate, split, reconstruct, sign~15
CryptographyEd25519 sign/verify, AES-GCM encrypt/decrypt, Shamir split/combine~10
Chain scanningMempool watch, block scan, confirmation tracking~8
Protocol evaluationValidate sale, compute fees, check thresholds~12
Node managementHealth checks, capability probes, metrics~8
PoA challengesGenerate challenge, verify response~5

The TypeScript layer calls node-core via HTTP (RUST_NODE_CORE_URL). This clean separation means the Rust code handles cryptography and chain interaction while TypeScript handles business logic, API routing, and database operations.

#MPC Treasury Wallet

The network maintains a threshold wallet where the private key is split across ALL participating nodes using multi-party computation (MPC):

  • Threshold: 67% of nodes (BFT standard, lowered from the original 80%)
  • No hot wallet: The complete key never exists in one place
  • Weekly epoch batching: Treasury operations are batched into weekly epochs to reduce coordination overhead
  • Auto-reshare on membership changes: When nodes join or leave, the key shares are automatically redistributed without reconstructing the key
  • Emergency health-based reshare: If too many nodes go offline, an emergency reshare is triggered with a 5-minute grace period
  • Sweep loop: Runs every 15-30 seconds checking for pending treasury operations

In production, the foundation master node (Node-1) manually activates MPC keygen and the reward token. Full key distribution waits until sufficient decentralization is achieved.

#Foundation Transparency

Node-1 is the foundation master node with beta-phase veto and admin powers. However, all foundation actions are subject to full transparency:

  • Every foundation action is a signed protocol event
  • Events are gossiped to all nodes (same as any other event)
  • All actions are visible in the protocol explorer
  • No hidden operations are possible

A separate rewards MPC wallet at the same 67% BFT threshold handles automated claim payouts for node operator rewards. Claims are signature-based, not transfer-based -- the foundation treasury is auditable at all times.

PreviousRunning a NodeNext Protocol Truth

On this page

  • Architecture
  • Monorepo Structure
  • Dependency Flow
  • Node Isolation
  • Binary Wire Protocol
  • Gossip Mesh
  • K=6 Neighbor Selection
  • Epidemic Heartbeats
  • Shard Ring
  • Cohort Mesh
  • Rust Node-Core
  • MPC Treasury Wallet
  • Foundation Transparency