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.

ExportDescription
KiiErrorUnified error enum (NotFound, InvalidInput, Crypto, Storage, Network, etc.)
Result<T>Type alias for std::result::Result<T, KiiError>
EntityIdTyped identifier wrapper
TimestampChrono-based timestamp with serialization

Dependencies: None (leaf crate)

kiiworks-crypto

Purpose: All cryptographic primitives used by the platform.

ExportDescription
Bip39Mnemonic generation (12/24 words) and seed derivation
HasherSHA-256, BLAKE2b-256, double-SHA256
SchnorrKeypairsecp256k1 keypair generation and Schnorr signing
Argon2HasherPassword hashing with Argon2id
HkdfDeriverHKDF-SHA256 key derivation
AesGcmAES-256-GCM authenticated encryption

Key algorithms:

  • BIP-39 mnemonic generation with bip39 crate
  • 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.

ExportDescription
PngEncoderEncode pixel data to PNG format

Dependencies: png crate

kiiworks-qr

Purpose: QR code generation with GS1 Digital Link support.

ExportDescription
QrHelperGenerate QR codes from strings or GS1 URIs
QrConfigSize, error correction, quiet zone settings

Dependencies: kiiworks-image


Kaspa Integration Layer

kiiworks-foundry

Purpose: Low-level Kaspa blockchain interface — RPC client and transaction construction.

ExportDescription
KaspaRpcwRPC client (Borsh serialization over WebSocket)
TransactionBuilderFluent API for building unsigned transactions
TransactionTransaction data structure (inputs, outputs, gas, subnetwork)
UtxoEntryUnspent transaction output
NetworkIdNetwork identifier enum (Mainnet, Testnet10-12, Custom)
SubnetworkId20-byte subnetwork identifier

Key details:

  • wRPC connection: ws://host:port (Borsh-encoded messages)
  • SubnetworkId is 20 bytes (40 hex chars), NOT 32 bytes
  • Transaction gas field 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.

ExportDescription
HdKeyDerivationBIP-44 HD key derivation (m/44'/111111'/0'/0/{index})
SchnorrSignerTransaction signing with BLAKE2b-256 sighash
UtxoSelectorCoin selection (largest-first) with KIP-9 mass awareness
BurnAnchorP2PK burn script construction and hash extraction
ScriptBuilderRaw 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.

ExportDescription
VaultConnector (trait)store_secret(), get_secret(), delete_secret(), list_secrets()
InMemoryVaultDefault in-memory implementation
FileVaultFile-based encrypted storage

Dependencies: kiiworks-core, kiiworks-crypto

kiiworks-stamp

Purpose: NFT minting and KRC-20 token operations.

ExportDescription
NftMinterCreate non-fungible tokens via on-chain anchoring
Krc20KRC-20 token operations (mint, transfer, burn)
TokenMetadataOn-chain metadata structure

Dependencies: kiiworks-core, kiiworks-foundry, kiiworks-anvil

kiiworks-wire

Purpose: End-to-end encrypted messaging primitives.

ExportDescription
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
WireEnvelopeEncrypted message container (ciphertext + nonce + tag)
WireMessagePlaintext 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.

ExportDescription
DidKaspaMethodcreate(pubkey, network) → DID, resolve(did) → DID Document
VcIssuerissue(claims, did, key) → signed VC, verify(vc) → bool
DidDocumentW3C DID Core 1.0 document structure
VerifiableCredentialW3C VC data model with proof
TrustTagBlockchain-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).

ExportDescription
CovenantScriptScript compilation with lock conditions
LockConditionTimelock, hash preimage, multisig, data check
UnlockProofProof satisfying one or more conditions
EscrowCovenantPre-built escrow pattern

Dependencies: kiiworks-core, kiiworks-crypto, kiiworks-foundry

NEW-L1 — Multisig spendability: LockCondition::MultiSig compiles a structurally correct OP_CHECKMULTISIG redeem script, but Kaspa’s mainnet script VM does not currently honour OP_CHECKMULTISIG at 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.

ExportDescription
DppService (trait)create(), get(), update(), list(), add_lifecycle_stage()
InMemoryDppServiceDefault in-memory implementation
DigitalProductPassportFull passport data structure
LifecycleStageProduct lifecycle stage (Manufacturing, Shipping, Use, Recycling, etc.)
DppAnchorServiceHash passport state and anchor on Kaspa
EpcisEventServiceValidate 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.

ExportDescription
TraceEventSupply chain event (custody transfer, observation, transformation)
TraceService (trait)Record and query supply chain events
ProvenanceChainOrdered 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.

ExportDescription
MerkleTreefrom_leaves(hashes) → tree, root() → 32 bytes, proof(index) → proof
MerkleProofverify(leaf, root) → bool
ProofStepHash + direction (Left/Right) for proof traversal
AnchorBatchLifecycle: 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.

ExportDescription
ChainAdapter (trait)chain_id(), anchor(), verify()
StubChainAdapterStub implementations for testing
BridgeRegistryregister(), register_evm(), get(), multi_anchor(), list_chains()
ChainIdEnum: Kaspa, Ethereum, Polygon, Solana, Iota, Custom
AnchorRequest / AnchorReceiptRequest/response for anchoring
MultiAnchorResultResults from anchoring on multiple chains
EvmChainAdapterFull EVM/EBSI adapter — EIP-1559 transactions, calldata or AnchorRegistry contract anchoring
EvmConfigNetwork + key + RPC client + anchor mode + optional fee/gas overrides
EvmNetworkPresets: EbsiPreProduction, EbsiMainnet, EthereumMainnet/Sepolia, OptimismMainnet/Sepolia, ArbitrumMainnet/Sepolia, BaseMainnet/Sepolia, LineaMainnet/Sepolia, Custom
EvmKeysecp256k1 keypair, Ethereum address (keccak256(pubkey)[12..32]), EIP-55 checksum, recoverable signing
EvmTxBuilderConstruct + sign EIP-1559 type-2 transactions with RLP encoding
EvmFeeEstimatorPer-network static defaults + eth_feeHistory / eth_maxPriorityFeePerGas RPC path
EvmRpcClient (trait)JSON-RPC abstraction (real + mock implementations)
JsonRpcEvmClientreqwest + rustls implementation against any Ethereum JSON-RPC endpoint
MockEvmRpcClientIn-memory mock for tests — queued responses, error injection, last-broadcast inspection
AnchorModeCalldataOnly (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.

ExportDescription
EscrowBuilderFluent API: payer(), payee(), amount(), conditions(), expires_at(), build()
EscrowContractFull contract with conditions and status
EscrowCondition5 variants: DppAnchored, LifecycleReached, HashPreimage, MultiSig, TimeAfter
EscrowVerifierverify_condition(), all_conditions_met(), is_expired()
EscrowStatusCreated, Funded, ConditionsMet, Released, Refunded, Expired

Dependencies: kiiworks-core, kiiworks-crypto

kiiworks-standards

Purpose: Industry-standard type definitions for interoperability.

ModuleContents
unece29 UNECE Rec. 20 unit codes, 30 country codes, 16 currency codes
gs1GTIN validation, Application Identifiers, Digital Link URI
vda17 VDA part categories, 16 material classes
dcsaTransport events, equipment events, shipment status
gaiaxGaia-X participant, service, compliance types
epcis20 BizSteps with URNs, 11 dispositions, 7 business transactions
w3cDID methods, VC types, proof types, ODRL actions
schema_org14 Schema.org types with IRIs
dublin_core15 DC metadata elements
foaf10 FOAF properties

Dependencies: serde (no kiiworks deps — pure types)

kiiworks-storage-connectors

Purpose: Object store abstraction for external storage backends.

ExportDescription
ObjectStore (trait)put(), get(), head(), delete(), list(), exists(), stats(), backend_name()
InMemoryObjectStoreFull in-memory implementation with SHA-256 content hashing
S3Config / S3ObjectStoreAWS S3 configuration (delegates to in-memory)
MongoConfig / MongoObjectStoreMongoDB configuration (delegates to in-memory)
IpfsConfig / IpfsObjectStoreIPFS configuration (delegates to in-memory)

Dependencies: kiiworks-core, kiiworks-crypto

kiiworks-sync

Purpose: Offline-first hash chain event buffering.

ExportDescription
HashChaingenesis_hash(), compute_event_hash(), verify_chain()
SyncBufferappend() (auto-hashes), prepare_sync(), mark_synced(), verify()
BufferedEventEvent with hash chain link
SyncBatchBatch of events for synchronization
ChainStatusChain 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.

ExportDescription
TimelockEncryptorgenerate_key(), encrypt(), compute_anchor_hash()
TimelockDecryptordecrypt()
TimelockVaultcreate_capsule(), decrypt_capsule() (enforces time lock)
TimelockCapsuleEncrypted 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.

ExportDescription
Commitment / CommitmentOpeningSHA-256(value || blinding) commitments
CommitmentSchemecommit(), verify()
RangeProof / RangeStatementBit-decomposition range proofs with Fiat-Shamir
SelectiveDisclosureField-level disclosure with revealed/hidden fields
DisclosureProof / DisclosureRequestProve 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));