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)
| Crate | Purpose |
|---|---|
kiiworks-core | Error types (KiiError), result alias, entity IDs, timestamps, common traits |
kiiworks-crypto | BIP-39 mnemonics, Schnorr signing, SHA-256, BLAKE2b, Argon2, PBKDF2, HKDF, key derivation |
kiiworks-image | PNG encoding utilities for QR code rendering |
kiiworks-qr | QR code generation with GS1 Digital Link URI support |
Kaspa Integration Layer
| Crate | Purpose |
|---|---|
kiiworks-foundry | Kaspa RPC client (wRPC/Borsh), transaction builder, UTXO queries, network types |
kiiworks-anvil | HD key derivation (BIP-44), Schnorr signer, UTXO selector, script builder |
kiiworks-vault | Secret storage abstraction (in-memory, file-based) |
kiiworks-stamp | NFT minting, KRC-20 token operations via on-chain anchoring |
kiiworks-wire | X25519 key exchange + AES-256-GCM encryption for peer-to-peer messaging |
kiiworks-forge | DID:Kaspa method (create/resolve), Verifiable Credentials (issue/verify) |
kiiworks-covenant-sdk | KIP-10 covenant scripts — lock conditions, unlock proofs, script compilation |
Supply Chain Layer
| Crate | Purpose |
|---|---|
kiiworks-passport | Digital Product Passport data model, DPP service trait, EPCIS events, GS1 GTIN validation, lifecycle stages, anchor service |
kiiworks-trace | Supply chain traceability — events, provenance tracking, custody transfers |
Advanced Capabilities Layer
| Crate | Purpose |
|---|---|
kiiworks-anchor-tree | Merkle tree batch anchoring — O(1) blockchain cost for N items with individual inclusion proofs |
kiiworks-bridge | Cross-chain anchoring — pluggable ChainAdapter trait with Kaspa (full) and EVM/EBSI (full) adapters |
kiiworks-escrow | Covenant-based on-chain escrow with 5 condition types (DPP anchored, lifecycle, hash preimage, multisig, timelock) |
kiiworks-standards | Industry 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-connectors | Object store abstraction with S3/MongoDB/IPFS configuration stubs |
kiiworks-sync | Offline-first hash chain event buffering for environments with unreliable connectivity |
kiiworks-timelock | Time-locked AES-256-GCM encryption with deferred disclosure and blockchain anchor hashes |
kiiworks-zkp | Zero-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)
| Service | Mount | Description |
|---|---|---|
| entity-storage | /api/entity-storage | JSON entity CRUD with PostgreSQL or in-memory backend |
| blob-storage | /api/blob-storage | Binary object storage with metadata |
| document-management | /api/document-management | Structured document lifecycle |
| verifiable-storage | /api/verifiable-storage | Merkle-tree verified storage with inclusion proofs |
| synchronised-storage | /api/synchronised-storage | Multi-node synchronised storage with conflict resolution |
| vault-connector-hashicorp | — | HashiCorp Vault integration (no REST routes) |
| immutable-proof | /api/immutable-proof | SHA-256 proof generation and verification |
| logging | /api/logging | Structured audit log with query/filter |
Identity & Auth (3 services)
| Service | Mount | Description |
|---|---|---|
| auth | /api/auth | JWT authentication — register, login, token refresh |
| identity-auth | /api/identity-auth | DID-based challenge/response authentication |
| attestation | /api/attestation | Credential attestation management |
Trust & Rights (2 services)
| Service | Mount | Description |
|---|---|---|
| trust | /api/trust | Trust framework — Gaia-X compliance, artefact verification |
| rights-management | /api/rights-management | ODRL-based rights and policy management |
DPP & Product Data (4 services)
| Service | Mount | Description |
|---|---|---|
| dpp | /api/dpp | Digital Product Passport — CRUD, EPCIS events, QR codes, anchoring |
| iot-ingest | /api/iot-ingest | IoT sensor data ingestion with threshold-based DPP updates |
| feedback | /api/feedback | Consumer micropayment feedback with sompi rewards |
| regulator | /api/regulator | Regulatory compliance queries (EU Battery Reg, ESPR) |
Supply Chain (3 services)
| Service | Mount | Description |
|---|---|---|
| lineage | /api/lineage | Product-to-product DAG with cycle detection, ancestry tracing |
| circular | /api/circular | Circular economy marketplace with geospatial matching |
| geo | /api/geo | Geospatial tracking — haversine, geofences, route history |
Dataspace (4 services)
| Service | Mount | Description |
|---|---|---|
| dataspace | /api/dataspace-* | IDSA Dataspace Protocol — control plane + data plane |
| data-space-connector | /api/data-space-connector | Organisation-to-organisation data exchange |
| data-processing | /api/data-processing | ETL pipeline execution engine |
| federated-catalogue | /api/federated-catalogue | Cross-organisation asset discovery |
Infrastructure (7 services)
| Service | Mount | Description |
|---|---|---|
| event-bus | /api/event-bus | Pub/sub event distribution (REST + WebSocket) |
| telemetry | /api/telemetry | Metrics collection and reporting |
| background-task | /api/background-task | Task scheduling (cron, interval, one-shot) |
| workflow | /api/workflow | Compliance state machine engine |
| webhook | /api/webhook | HMAC-SHA256 signed outbound event delivery |
| sentinel | /api/sentinel | Anomaly detection — anchoring gaps, value anomalies, sequence violations |
| gateway | /api/gateway | API key management with sliding-window rate limiting |
Trade Rails (5 services)
| Service | Mount | Description |
|---|---|---|
| trade | /api/trade | Trade-document CRUD, e-BL endorsement chains, LC lifecycle (UCP 600), documentary collections (URC 522) |
| customs | /api/customs | EU Single Window declarations, HS classification (99-chapter index), customs procedure codes |
| cbam | /api/cbam | EU Carbon Border Adjustment Mechanism declarations — embedded emissions, verifier attestation, certificate calculation |
| sanctions | /api/sanctions | Sanctions and dual-use screening against OFAC, EU Consolidated, UK OFSI, UN SC, BIS Entity, EU Dual-Use lists; full audit trail |
| efti | /api/efti | EU Electronic Freight Transport Information envelopes with competent-authority access filtering |
See trade-rails.md for the full architecture.
Blockchain (2 services)
| Service | Mount | Description |
|---|---|---|
| wallet | /api/wallet | BIP-39 HD wallet management — create, derive, send, balance |
| wire-service | /api/wire | Encrypted P2P messaging channels (X25519 + AES-256-GCM) |
Application (3 services)
| Service | Mount | Description |
|---|---|---|
| identity (forge) | /api/identity | DID:Kaspa identity operations |
| supply-chain (trace) | /api/supply-chain | Supply chain event recording |
| nft (stamp) | /api/nft | NFT and KRC-20 token management |
Other (3 services)
| Service | Mount | Description |
|---|---|---|
| api | — | OpenAPI schema generation utilities |
| context | — | Request context propagation |
| engine | — | Core engine patterns |
| auditable-item-graph | /api/auditable-item-graph | DAG of auditable items with provenance |
| auditable-item-stream | /api/auditable-item-stream | Append-only auditable event stream |
Layer 3: Node Runner (platform/node)
The node is the composition root. It:
- Reads
NodeConfigfrom environment variables or defaults - Initialises tracing (text or JSON format)
- Creates a
ComponentRegistry - Calls
register_all()which instantiates all 39 services - Merges all service routers under
/api/{name}/ - Adds JWT authentication middleware (skipped in
dev_mode) - Adds CORS middleware
- Binds to
{host}:{port}(default0.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:
| Variable | Default | Description |
|---|---|---|
KIIWORKS_HOST | 0.0.0.0 | Bind address |
KIIWORKS_PORT | 4000 | HTTP port |
KIIWORKS_DATABASE_URL | — | PostgreSQL URL (omit for in-memory) |
KIIWORKS_JWT_SECRET | dev-secret | JWT signing key (MUST change in production) |
KIIWORKS_LOG_FORMAT | text | text or json |
KIIWORKS_TLS_CERT | — | Path to TLS certificate |
KIIWORKS_TLS_KEY | — | Path to TLS private key |
KIIWORKS_KASPA_ENDPOINT | ws://127.0.0.1:17210 | Kaspad wRPC URL |
KIIWORKS_DEV_MODE | true | Skip JWT in dev mode |
KIIWORKS_RATE_LIMIT | 100 | Global 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
-
Trait-based abstraction: Every service defines a trait (e.g.,
EntityStorageConnector,DppService,AuthService). In-memory implementations ship by default; PostgreSQL backends are optional. -
Single binary: All 39 services compile into one binary. No microservice orchestration needed in development. In production, you can selectively disable services via configuration.
-
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.
-
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.
-
Standards-first: Every data model references its controlling standard (ESPR, EPCIS 2.0, GS1, W3C DID/VC, UNECE Rec. 20, Gaia-X). The
kiiworks-standardscrate provides canonical type definitions. -
Zero-copy secrets: Private keys and mnemonics are held in memory only, never serialized to JSON responses or logs. The
zeroizecrate ensures cryptographic material is wiped on drop.