KiiWORKS / Documentation
Library Crates Reference
SOURCE · docs/library-crates.md · synced from the engineering repo
Library Crates Reference
The 21 library crates in crates/ contain all business logic, cryptography, data models, and blockchain protocol implementation. They have no HTTP dependencies and can be used independently.
Foundation Layer
kiiworks-core
Purpose: Common types shared across all crates.
| Export | Description |
|---|---|
KiiError | Unified error enum (NotFound, InvalidInput, Crypto, Storage, Network, etc.) |
Result<T> | Type alias for std::result::Result<T, KiiError> |
EntityId | Typed identifier wrapper |
Timestamp | Chrono-based timestamp with serialization |
Dependencies: None (leaf crate)
kiiworks-crypto
Purpose: All cryptographic primitives used by the platform.
| Export | Description |
|---|---|
Bip39 | Mnemonic generation (12/24 words) and seed derivation |
Hasher | SHA-256, BLAKE2b-256, double-SHA256 |
SchnorrKeypair | secp256k1 keypair generation and Schnorr signing |
Argon2Hasher | Password hashing with Argon2id |
HkdfDeriver | HKDF-SHA256 key derivation |
AesGcm | AES-256-GCM authenticated encryption |
Key algorithms:
- BIP-39 mnemonic generation with
bip39crate - Schnorr signatures over secp256k1
- BLAKE2b-256 with keyed mode for Kaspa sighash
- Argon2id for password storage
- HKDF-SHA256 for key stretching
Dependencies: kiiworks-core
kiiworks-image
Purpose: PNG encoding utilities for image generation.
| Export | Description |
|---|---|
PngEncoder | Encode pixel data to PNG format |
Dependencies: png crate
kiiworks-qr
Purpose: QR code generation with GS1 Digital Link support.
| Export | Description |
|---|---|
QrHelper | Generate QR codes from strings or GS1 URIs |
QrConfig | Size, error correction, quiet zone settings |
Dependencies: kiiworks-image
Kaspa Integration Layer
kiiworks-foundry
Purpose: Low-level Kaspa blockchain interface — RPC client and transaction construction.
| Export | Description |
|---|---|
KaspaRpc | wRPC client (Borsh serialization over WebSocket) |
TransactionBuilder | Fluent API for building unsigned transactions |
Transaction | Transaction data structure (inputs, outputs, gas, subnetwork) |
UtxoEntry | Unspent transaction output |
NetworkId | Network identifier enum (Mainnet, Testnet10-12, Custom) |
SubnetworkId | 20-byte subnetwork identifier |
Key details:
- wRPC connection:
ws://host:port(Borsh-encoded messages) - SubnetworkId is 20 bytes (40 hex chars), NOT 32 bytes
- Transaction
gasfield required (default 0 for native subnetwork) - Methods:
connect(),get_utxos_by_addresses(),submit_transaction(),get_block_dag_info()
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-anvil
Purpose: Key management, transaction signing, and UTXO selection.
| Export | Description |
|---|---|
HdKeyDerivation | BIP-44 HD key derivation (m/44'/111111'/0'/0/{index}) |
SchnorrSigner | Transaction signing with BLAKE2b-256 sighash |
UtxoSelector | Coin selection (largest-first) with KIP-9 mass awareness |
BurnAnchor | P2PK burn script construction and hash extraction |
ScriptBuilder | Raw script construction (P2PK, P2SH) |
Key details:
- Sighash: BLAKE2b-256 with
key = b"TransactionSigningHash" - Signature script:
[0x41][64-byte-sig][0x01] - P2PK script:
[0x20][32-byte-pubkey][0xac] - Minimum output: 1 KAS (avoid KIP-9 storage mass penalty)
Dependencies: kiiworks-core, kiiworks-crypto, kiiworks-foundry
kiiworks-vault
Purpose: Secret storage abstraction.
| Export | Description |
|---|---|
VaultConnector (trait) | store_secret(), get_secret(), delete_secret(), list_secrets() |
InMemoryVault | Default in-memory implementation |
FileVault | File-based encrypted storage |
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-stamp
Purpose: NFT minting and KRC-20 token operations.
| Export | Description |
|---|---|
NftMinter | Create non-fungible tokens via on-chain anchoring |
Krc20 | KRC-20 token operations (mint, transfer, burn) |
TokenMetadata | On-chain metadata structure |
Dependencies: kiiworks-core, kiiworks-foundry, kiiworks-anvil
kiiworks-wire
Purpose: End-to-end encrypted messaging primitives.
| Export | Description |
|---|---|
generate_x25519_key_pair() | Generate X25519 keypair for ECDH |
derive_shared_secret() | Compute shared secret from private + peer public key |
encrypt_payload() | AES-256-GCM encryption with HKDF-derived key |
decrypt_payload() | AES-256-GCM decryption |
generate_nonce() | 96-bit random nonce |
WireEnvelope | Encrypted message container (ciphertext + nonce + tag) |
WireMessage | Plaintext message structure |
Crypto flow: X25519 ECDH → shared secret → HKDF-SHA256 → AES-256-GCM key → encrypt/decrypt
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-forge
Purpose: Decentralised identity (DID) and Verifiable Credentials.
| Export | Description |
|---|---|
DidKaspaMethod | create(pubkey, network) → DID, resolve(did) → DID Document |
VcIssuer | issue(claims, did, key) → signed VC, verify(vc) → bool |
DidDocument | W3C DID Core 1.0 document structure |
VerifiableCredential | W3C VC data model with proof |
TrustTag | Blockchain-anchored trust marker |
DID format: did:kaspa:{network}:{hex_pubkey} (32-byte x-only secp256k1 public key)
Dependencies: kiiworks-core, kiiworks-crypto, kiiworks-anvil
kiiworks-covenant-sdk
Purpose: Covenant script compilation (KIP-10 SDK design; spend-time introspection enforcement activates at the Toccata hardfork, ~30 June 2026, via KIP-17).
| Export | Description |
|---|---|
CovenantScript | Script compilation with lock conditions |
LockCondition | Timelock, hash preimage, multisig, data check |
UnlockProof | Proof satisfying one or more conditions |
EscrowCovenant | Pre-built escrow pattern |
Dependencies: kiiworks-core, kiiworks-crypto, kiiworks-foundry
NEW-L1 — Multisig spendability:
LockCondition::MultiSigcompiles a structurally correctOP_CHECKMULTISIGredeem script, but Kaspa’s mainnet script VM does not currently honourOP_CHECKMULTISIGat spend time. Multisig outputs are creatable today; spend-time enforcement of the M-of-N threshold requires the Kaspa Toccata covenant-introspection upgrade (target Q3 2026). HashLock and TimeLock conditions are unaffected.
Supply Chain Layer
kiiworks-passport
Purpose: Digital Product Passport data model and business logic.
| Export | Description |
|---|---|
DppService (trait) | create(), get(), update(), list(), add_lifecycle_stage() |
InMemoryDppService | Default in-memory implementation |
DigitalProductPassport | Full passport data structure |
LifecycleStage | Product lifecycle stage (Manufacturing, Shipping, Use, Recycling, etc.) |
DppAnchorService | Hash passport state and anchor on Kaspa |
EpcisEventService | Validate EPCIS events and map to lifecycle stages |
validate_gtin() | GS1 GTIN-8/12/13/14 validation with check digit |
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-trace
Purpose: Supply chain event traceability.
| Export | Description |
|---|---|
TraceEvent | Supply chain event (custody transfer, observation, transformation) |
TraceService (trait) | Record and query supply chain events |
ProvenanceChain | Ordered chain of custody records |
Dependencies: kiiworks-core
Advanced Capabilities Layer
kiiworks-anchor-tree
Purpose: Merkle tree batch anchoring — O(1) blockchain cost for N items.
| Export | Description |
|---|---|
MerkleTree | from_leaves(hashes) → tree, root() → 32 bytes, proof(index) → proof |
MerkleProof | verify(leaf, root) → bool |
ProofStep | Hash + direction (Left/Right) for proof traversal |
AnchorBatch | Lifecycle: add_item() → build_tree() → get_proof() → mark_anchored() |
Algorithm: SHA-256 pair hashing. Left and right children concatenated and hashed. Odd leaf count: last leaf duplicated.
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-bridge
Purpose: Cross-chain anchoring abstraction. Adapter status: Kaspa (full) + EVM/EBSI (full) — one unified EVM adapter covers EBSI (EU-sovereign permissioned Besu) and the major public Ethereum L2s (Optimism, Arbitrum, Base, Linea) plus their Sepolia testnets.
| Export | Description |
|---|---|
ChainAdapter (trait) | chain_id(), anchor(), verify() |
StubChainAdapter | Stub implementations for testing |
BridgeRegistry | register(), register_evm(), get(), multi_anchor(), list_chains() |
ChainId | Enum: Kaspa, Ethereum, Polygon, Solana, Iota, Custom |
AnchorRequest / AnchorReceipt | Request/response for anchoring |
MultiAnchorResult | Results from anchoring on multiple chains |
EvmChainAdapter | Full EVM/EBSI adapter — EIP-1559 transactions, calldata or AnchorRegistry contract anchoring |
EvmConfig | Network + key + RPC client + anchor mode + optional fee/gas overrides |
EvmNetwork | Presets: EbsiPreProduction, EbsiMainnet, EthereumMainnet/Sepolia, OptimismMainnet/Sepolia, ArbitrumMainnet/Sepolia, BaseMainnet/Sepolia, LineaMainnet/Sepolia, Custom |
EvmKey | secp256k1 keypair, Ethereum address (keccak256(pubkey)[12..32]), EIP-55 checksum, recoverable signing |
EvmTxBuilder | Construct + sign EIP-1559 type-2 transactions with RLP encoding |
EvmFeeEstimator | Per-network static defaults + eth_feeHistory / eth_maxPriorityFeePerGas RPC path |
EvmRpcClient (trait) | JSON-RPC abstraction (real + mock implementations) |
JsonRpcEvmClient | reqwest + rustls implementation against any Ethereum JSON-RPC endpoint |
MockEvmRpcClient | In-memory mock for tests — queued responses, error injection, last-broadcast inspection |
AnchorMode | CalldataOnly (cheap, 21,500 gas) or ContractCall { contract } (queryable, ~50,000 gas) |
anchor_registry::{SOURCE_SOLIDITY, ARTIFACT_JSON} | Bundled AnchorRegistry.sol + ABI for operator deployment |
Dependencies: kiiworks-core, k256, tiny-keccak, rlp, reqwest,
sha2. See ebsi-evm-anchor guide for operational
detail.
kiiworks-escrow
Purpose: Covenant-based on-chain escrow.
| Export | Description |
|---|---|
EscrowBuilder | Fluent API: payer(), payee(), amount(), conditions(), expires_at(), build() |
EscrowContract | Full contract with conditions and status |
EscrowCondition | 5 variants: DppAnchored, LifecycleReached, HashPreimage, MultiSig, TimeAfter |
EscrowVerifier | verify_condition(), all_conditions_met(), is_expired() |
EscrowStatus | Created, Funded, ConditionsMet, Released, Refunded, Expired |
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-standards
Purpose: Industry-standard type definitions for interoperability.
| Module | Contents |
|---|---|
unece | 29 UNECE Rec. 20 unit codes, 30 country codes, 16 currency codes |
gs1 | GTIN validation, Application Identifiers, Digital Link URI |
vda | 17 VDA part categories, 16 material classes |
dcsa | Transport events, equipment events, shipment status |
gaiax | Gaia-X participant, service, compliance types |
epcis | 20 BizSteps with URNs, 11 dispositions, 7 business transactions |
w3c | DID methods, VC types, proof types, ODRL actions |
schema_org | 14 Schema.org types with IRIs |
dublin_core | 15 DC metadata elements |
foaf | 10 FOAF properties |
Dependencies: serde (no kiiworks deps — pure types)
kiiworks-storage-connectors
Purpose: Object store abstraction for external storage backends.
| Export | Description |
|---|---|
ObjectStore (trait) | put(), get(), head(), delete(), list(), exists(), stats(), backend_name() |
InMemoryObjectStore | Full in-memory implementation with SHA-256 content hashing |
S3Config / S3ObjectStore | AWS S3 configuration (delegates to in-memory) |
MongoConfig / MongoObjectStore | MongoDB configuration (delegates to in-memory) |
IpfsConfig / IpfsObjectStore | IPFS configuration (delegates to in-memory) |
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-sync
Purpose: Offline-first hash chain event buffering.
| Export | Description |
|---|---|
HashChain | genesis_hash(), compute_event_hash(), verify_chain() |
SyncBuffer | append() (auto-hashes), prepare_sync(), mark_synced(), verify() |
BufferedEvent | Event with hash chain link |
SyncBatch | Batch of events for synchronization |
ChainStatus | Chain integrity status |
Algorithm: Each event’s hash = SHA-256(prev_hash || event_type || payload || timestamp). Genesis hash is SHA-256(“genesis”). Chain is verified by recomputing all hashes.
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-timelock
Purpose: Time-locked encryption with deferred disclosure.
| Export | Description |
|---|---|
TimelockEncryptor | generate_key(), encrypt(), compute_anchor_hash() |
TimelockDecryptor | decrypt() |
TimelockVault | create_capsule(), decrypt_capsule() (enforces time lock) |
TimelockCapsule | Encrypted data with disclosure date and anchor hash |
Crypto: AES-256-GCM encryption. Anchor hash = SHA-256(ciphertext) for proof-of-existence anchoring. Disclosure enforced by checking Utc::now() >= disclosure_date.
Dependencies: kiiworks-core, kiiworks-crypto
kiiworks-zkp
Purpose: Zero-knowledge selective disclosure for DPP privacy.
| Export | Description |
|---|---|
Commitment / CommitmentOpening | SHA-256(value || blinding) commitments |
CommitmentScheme | commit(), verify() |
RangeProof / RangeStatement | Bit-decomposition range proofs with Fiat-Shamir |
SelectiveDisclosure | Field-level disclosure with revealed/hidden fields |
DisclosureProof / DisclosureRequest | Prove specific fields without revealing all |
Use case: A battery manufacturer can prove “carbon footprint < 50 kgCO2e/kWh” without revealing the exact value, or prove “recycled cobalt content > 12%” without disclosing the full bill of materials.
Dependencies: kiiworks-core, kiiworks-crypto
Using Library Crates Directly
Library crates can be used without the platform services:
use kiiworks_crypto::Bip39;
use kiiworks_anvil::HdKeyDerivation;
use kiiworks_forge::DidKaspaMethod;
// Generate wallet
let mnemonic = Bip39::generate_mnemonic(12);
let keypair = HdKeyDerivation::derive(&mnemonic, 0)?;
// Create DID
let did = DidKaspaMethod::create(&keypair.public_key, "testnet-12");
// → "did:kaspa:testnet-12:a1b2c3..."
// Resolve DID
let doc = DidKaspaMethod::resolve(&did)?;
use kiiworks_anchor_tree::{MerkleTree, AnchorBatch};
// Batch anchor 1000 items with 1 transaction
let mut batch = AnchorBatch::new();
for item in items {
batch.add_item(sha256(item));
}
batch.build_tree();
let root = batch.root_hash(); // Anchor this single hash
let proof = batch.get_proof(42); // Individual proof for item 42
assert!(proof.verify(items[42], root));