KiiWORKS / Documentation

KiiWORKS v2 Architecture

SOURCE · docs/architecture.md · synced from the engineering repo

KiiWORKS v2 Architecture

Overview

KiiWORKS v2 is a Rust workspace of 62 members organized into four layers. Every platform service compiles into a single binary (kiiworks) that boots on port 4000 and exposes all services under /api/{service-name}/.

                        ┌──────────────┐
                        │  CLI Binary  │  tools/cli (21 commands)
                        └──────┬───────┘

                        ┌──────┴───────┐
                        │  Node Runner │  platform/node
                        │  Axum 0.8   │  JWT · CORS · TLS
                        └──────┬───────┘

            ┌──────────────────┼──────────────────┐
            │                  │                   │
   ┌────────┴────────┐ ┌──────┴──────┐ ┌─────────┴────────┐
   │ Storage Services│ │ DPP & Chain │ │ Infra Services    │
   │ (8 services)    │ │ (9 services)│ │ (22 services)     │
   └────────┬────────┘ └──────┬──────┘ └─────────┬────────┘
            │                  │                   │
            └──────────────────┼──────────────────┘

                    ┌──────────┴──────────┐
                    │  Library Crates     │  crates/* (21 crates)
                    │  Pure logic, no HTTP│
                    └──────────┬──────────┘

                    ┌──────────┴──────────┐
                    │  Kaspa BlockDAG     │  wRPC (Borsh)
                    │  Testnet-12 / Main  │  ws://127.0.0.1:17210
                    └─────────────────────┘

Layer 1: Library Crates (crates/)

Pure Rust libraries with no HTTP dependencies. These contain all business logic, cryptography, data models, and blockchain protocol implementation.

Foundation Layer (no inter-crate deps)

CratePurpose
kiiworks-coreError types (KiiError), result alias, entity IDs, timestamps, common traits
kiiworks-cryptoBIP-39 mnemonics, Schnorr signing, SHA-256, BLAKE2b, Argon2, PBKDF2, HKDF, key derivation
kiiworks-imagePNG encoding utilities for QR code rendering
kiiworks-qrQR code generation with GS1 Digital Link URI support

Kaspa Integration Layer

CratePurpose
kiiworks-foundryKaspa RPC client (wRPC/Borsh), transaction builder, UTXO queries, network types
kiiworks-anvilHD key derivation (BIP-44), Schnorr signer, UTXO selector, script builder
kiiworks-vaultSecret storage abstraction (in-memory, file-based)
kiiworks-stampNFT minting, KRC-20 token operations via on-chain anchoring
kiiworks-wireX25519 key exchange + AES-256-GCM encryption for peer-to-peer messaging
kiiworks-forgeDID:Kaspa method (create/resolve), Verifiable Credentials (issue/verify)
kiiworks-covenant-sdkKIP-10 covenant scripts — lock conditions, unlock proofs, script compilation

Supply Chain Layer

CratePurpose
kiiworks-passportDigital Product Passport data model, DPP service trait, EPCIS events, GS1 GTIN validation, lifecycle stages, anchor service
kiiworks-traceSupply chain traceability — events, provenance tracking, custody transfers

Advanced Capabilities Layer

CratePurpose
kiiworks-anchor-treeMerkle tree batch anchoring — O(1) blockchain cost for N items with individual inclusion proofs
kiiworks-bridgeCross-chain anchoring — pluggable ChainAdapter trait with Kaspa (full) and EVM/EBSI (full) adapters
kiiworks-escrowCovenant-based on-chain escrow with 5 condition types (DPP anchored, lifecycle, hash preimage, multisig, timelock)
kiiworks-standardsIndustry type definitions — UNECE Rec. 20, GS1 GTIN, VDA automotive, DCSA shipping, Gaia-X, W3C DID/VC, EPCIS 2.0, Dublin Core, FOAF, Schema.org
kiiworks-storage-connectorsObject store abstraction with S3/MongoDB/IPFS configuration stubs
kiiworks-syncOffline-first hash chain event buffering for environments with unreliable connectivity
kiiworks-timelockTime-locked AES-256-GCM encryption with deferred disclosure and blockchain anchor hashes
kiiworks-zkpZero-knowledge selective disclosure — hash commitments, range proofs, field-level disclosure

Layer 2: Platform Services (platform/)

Each service follows a consistent pattern:

platform/{service}/
├── Cargo.toml          # Depends on library crates + axum
├── src/
│   ├── lib.rs          # Re-exports routes, state, models
│   ├── models.rs       # Request/response types (Serialize/Deserialize)
│   ├── state.rs        # Service state struct (Clone, wraps Arc<RwLock<...>>)
│   └── routes.rs       # Axum handlers returning Router<ServiceState>

Key pattern: Every service exports a *_routes() function that returns Router<ServiceState>. The node calls .with_state(state) to convert it to Router<()> before mounting.

Service Categories

Storage (8 services)

ServiceMountDescription
entity-storage/api/entity-storageJSON entity CRUD with PostgreSQL or in-memory backend
blob-storage/api/blob-storageBinary object storage with metadata
document-management/api/document-managementStructured document lifecycle
verifiable-storage/api/verifiable-storageMerkle-tree verified storage with inclusion proofs
synchronised-storage/api/synchronised-storageMulti-node synchronised storage with conflict resolution
vault-connector-hashicorpHashiCorp Vault integration (no REST routes)
immutable-proof/api/immutable-proofSHA-256 proof generation and verification
logging/api/loggingStructured audit log with query/filter

Identity & Auth (3 services)

ServiceMountDescription
auth/api/authJWT authentication — register, login, token refresh
identity-auth/api/identity-authDID-based challenge/response authentication
attestation/api/attestationCredential attestation management

Trust & Rights (2 services)

ServiceMountDescription
trust/api/trustTrust framework — Gaia-X compliance, artefact verification
rights-management/api/rights-managementODRL-based rights and policy management

DPP & Product Data (4 services)

ServiceMountDescription
dpp/api/dppDigital Product Passport — CRUD, EPCIS events, QR codes, anchoring
iot-ingest/api/iot-ingestIoT sensor data ingestion with threshold-based DPP updates
feedback/api/feedbackConsumer micropayment feedback with sompi rewards
regulator/api/regulatorRegulatory compliance queries (EU Battery Reg, ESPR)

Supply Chain (3 services)

ServiceMountDescription
lineage/api/lineageProduct-to-product DAG with cycle detection, ancestry tracing
circular/api/circularCircular economy marketplace with geospatial matching
geo/api/geoGeospatial tracking — haversine, geofences, route history

Dataspace (4 services)

ServiceMountDescription
dataspace/api/dataspace-*IDSA Dataspace Protocol — control plane + data plane
data-space-connector/api/data-space-connectorOrganisation-to-organisation data exchange
data-processing/api/data-processingETL pipeline execution engine
federated-catalogue/api/federated-catalogueCross-organisation asset discovery

Infrastructure (7 services)

ServiceMountDescription
event-bus/api/event-busPub/sub event distribution (REST + WebSocket)
telemetry/api/telemetryMetrics collection and reporting
background-task/api/background-taskTask scheduling (cron, interval, one-shot)
workflow/api/workflowCompliance state machine engine
webhook/api/webhookHMAC-SHA256 signed outbound event delivery
sentinel/api/sentinelAnomaly detection — anchoring gaps, value anomalies, sequence violations
gateway/api/gatewayAPI key management with sliding-window rate limiting

Trade Rails (5 services)

ServiceMountDescription
trade/api/tradeTrade-document CRUD, e-BL endorsement chains, LC lifecycle (UCP 600), documentary collections (URC 522)
customs/api/customsEU Single Window declarations, HS classification (99-chapter index), customs procedure codes
cbam/api/cbamEU Carbon Border Adjustment Mechanism declarations — embedded emissions, verifier attestation, certificate calculation
sanctions/api/sanctionsSanctions and dual-use screening against OFAC, EU Consolidated, UK OFSI, UN SC, BIS Entity, EU Dual-Use lists; full audit trail
efti/api/eftiEU Electronic Freight Transport Information envelopes with competent-authority access filtering

See trade-rails.md for the full architecture.

Blockchain (2 services)

ServiceMountDescription
wallet/api/walletBIP-39 HD wallet management — create, derive, send, balance
wire-service/api/wireEncrypted P2P messaging channels (X25519 + AES-256-GCM)

Application (3 services)

ServiceMountDescription
identity (forge)/api/identityDID:Kaspa identity operations
supply-chain (trace)/api/supply-chainSupply chain event recording
nft (stamp)/api/nftNFT and KRC-20 token management

Other (3 services)

ServiceMountDescription
apiOpenAPI schema generation utilities
contextRequest context propagation
engineCore engine patterns
auditable-item-graph/api/auditable-item-graphDAG of auditable items with provenance
auditable-item-stream/api/auditable-item-streamAppend-only auditable event stream

Layer 3: Node Runner (platform/node)

The node is the composition root. It:

  1. Reads NodeConfig from environment variables or defaults
  2. Initialises tracing (text or JSON format)
  3. Creates a ComponentRegistry
  4. Calls register_all() which instantiates all 39 services
  5. Merges all service routers under /api/{name}/
  6. Adds JWT authentication middleware (skipped in dev_mode)
  7. Adds CORS middleware
  8. Binds to {host}:{port} (default 0.0.0.0:4000)

Request Flow

Client Request


  Axum Server (:4000)

     ├── /health → 200 OK

     ├── /api/auth/* → No JWT required

     └── /api/{service}/* → JWT middleware → Service Router → Handler


                            Arc<dyn ServiceTrait>


                          In-Memory or PostgreSQL

Configuration

All configuration is via environment variables:

VariableDefaultDescription
KIIWORKS_HOST0.0.0.0Bind address
KIIWORKS_PORT4000HTTP port
KIIWORKS_DATABASE_URLPostgreSQL URL (omit for in-memory)
KIIWORKS_JWT_SECRETdev-secretJWT signing key (MUST change in production)
KIIWORKS_LOG_FORMATtexttext or json
KIIWORKS_TLS_CERTPath to TLS certificate
KIIWORKS_TLS_KEYPath to TLS private key
KIIWORKS_KASPA_ENDPOINTws://127.0.0.1:17210Kaspad wRPC URL
KIIWORKS_DEV_MODEtrueSkip JWT in dev mode
KIIWORKS_RATE_LIMIT100Global requests/minute/client

Layer 4: CLI (tools/cli)

The CLI binary wraps the library crates for command-line operations:

  • Wallet: Create, balance, send, consolidate UTXOs
  • DID: Create and resolve did:kaspa: identities
  • Anchor: Hash data and anchor on Kaspa, verify anchors
  • VC: Issue and verify W3C Verifiable Credentials
  • Trust Tag: Create blockchain-anchored trust markers
  • Node: Start the platform server
  • Config: Show and modify configuration

Data Flow Examples

DPP Lifecycle

1. POST /api/dpp/dpp            → Create passport (in-memory or Postgres)
2. POST /api/dpp/dpp/{id}/epcis → Add EPCIS event → auto-maps to lifecycle stage
3. POST /api/dpp/dpp/{id}/anchor → Hash passport → anchor on Kaspa BlockDAG
4. GET  /api/dpp/dpp/{id}/qr    → Generate QR code with GS1 Digital Link
5. GET  /api/dpp/dpp/{id}       → Full passport with lifecycle history + anchors

Wire Messaging

1. Alice: POST /api/wire/channels         → Generate X25519 keypair, get channel_id + public_key
2. Bob:   POST /api/wire/channels         → Generate X25519 keypair
3. Alice: POST /channels/{id}/handshake   → Send Bob's public key → derive shared secret
4. Bob:   POST /channels/{id}/handshake   → Send Alice's public key → derive same shared secret
5. Alice: POST /channels/{id}/messages    → Encrypt with AES-256-GCM using shared secret
6. Bob:   GET  /channels/{id}/messages    → Decrypt and read

Wallet → Anchor → Verify

1. POST /api/wallet/wallets          → Create BIP-39 HD wallet (mnemonic shown once)
2. POST /api/immutable-proof/proofs  → Compute SHA-256 hash of data
3. CLI:  kiiworks anchor create      → Build P2PK burn TX with hash, sign with Schnorr, submit
4. CLI:  kiiworks anchor verify      → Query Kaspa for TX, extract hash, compare

Dependency Graph (Simplified)

kiiworks-core ──────────────────────────────────────┐
     │                                               │
kiiworks-crypto ─────────────────────────────────┐   │
     │                                            │   │
     ├── kiiworks-foundry (Kaspa RPC)             │   │
     │        │                                   │   │
     │        ├── kiiworks-anvil (HD keys, UTXO)  │   │
     │        │        │                          │   │
     │        │        ├── kiiworks-forge (DID/VC) │   │
     │        │        │                          │   │
     │        │        └── kiiworks-stamp (NFT)   │   │
     │        │                                   │   │
     │        └── kiiworks-covenant-sdk (KIP-10)  │   │
     │                                            │   │
     ├── kiiworks-wire (encryption)               │   │
     ├── kiiworks-anchor-tree (Merkle)            │   │
     ├── kiiworks-zkp (zero-knowledge)            │   │
     ├── kiiworks-timelock (timed encryption)     │   │
     ├── kiiworks-escrow (covenant escrow)        │   │
     ├── kiiworks-sync (offline sync)             │   │
     └── kiiworks-bridge (cross-chain)            │   │
                                                  │   │
     kiiworks-passport (DPP model) ───────────────┘   │
     kiiworks-trace (supply chain) ───────────────────┘
     kiiworks-standards (industry types)
     kiiworks-storage-connectors (S3/Mongo/IPFS)

Design Principles

  1. Trait-based abstraction: Every service defines a trait (e.g., EntityStorageConnector, DppService, AuthService). In-memory implementations ship by default; PostgreSQL backends are optional.

  2. Single binary: All 39 services compile into one binary. No microservice orchestration needed in development. In production, you can selectively disable services via configuration.

  3. No OP_RETURN: Kaspa rejects OP_RETURN as non-standard. All blockchain anchoring uses the P2PK burn strategy — data hashes are embedded in transaction scripts that send to unspendable addresses.

  4. Offline-first: The sync crate provides hash-chain event buffering for factory environments without reliable internet. Events are cryptographically chained for tamper detection and batch-synced when connectivity returns.

  5. Standards-first: Every data model references its controlling standard (ESPR, EPCIS 2.0, GS1, W3C DID/VC, UNECE Rec. 20, Gaia-X). The kiiworks-standards crate provides canonical type definitions.

  6. Zero-copy secrets: Private keys and mnemonics are held in memory only, never serialized to JSON responses or logs. The zeroize crate ensures cryptographic material is wiped on drop.