← Back to Demos & Examples

08_kv_store_and_audit_log.vk

Raw .vk
// Example 08: ORO Data-Oriented KV Store, Hash-Chained Audit Log & Secret Zeroization
// Track A (ORO VM) : veko run examples/08_kv_store_and_audit_log.vk
// Track A (.vko)   : veko compile --vko examples/08_kv_store_and_audit_log.vk -o dist/08.vko ; veko run dist/08.vko
// Track B (Wasm 3) : veko run --wasm examples/08_kv_store_and_audit_log.vk
// Track C (Native) : veko compile --native examples/08_kv_store_and_audit_log.vk -o dist/08.exe ; ./dist/08.exe
use [bytes, j = json, str]

// Verify audit hash chain recursively in constant stack via `recur`
verify-chain = fn [entries idx prev-hash] [
	if idx >= entries.len [return true]
	entry = entries[idx]
	expected = hash (str/join [prev-hash entry.op entry.key] '|')
	if entry.sig != expected [return false]
	recur entries (idx + 1) expected
]

// Single-owner ORO store closure: owns data, audit log, and tip hash in one private slab
make-kv-store = fn [secret-seed] [
	mut data = {}
	mut audit = []
	base-hash = hash secret-seed
	mut tip-hash = base-hash

	fn [cmd k v] [
		match cmd [
			.put [
				map/set mut data k v
				tip-hash = hash (str/join [tip-hash 'put' k] '|')
				push mut audit { op = 'put', key = k, sig = tip-hash }
				true
			]
			.get [
				map/get data k
			]
			.snapshot [
				{ keys = map/keys data, audit = audit, tip = tip-hash }
			]
			.verify [
				verify-chain audit 0 base-hash
			]
			_ [
				err 'unknown-kv-command'
			]
		]
	]
]

// Ephemeral secret buffer wiped deterministically on scope exit
derive-session-seed = fn [] [
	mut secret = bytes/with-secret 64b
	bytes/push-all mut secret (bytes/from-str 'veko-galago-audit-key-2026')
	hash (bytes/to-str secret)
]

seed = mold (call derive-session-seed)
kv = make-kv-store seed

(kv .put 'node.host' '127.0.0.1')
(kv .put 'node.port' 8443)
(kv .put 'node.mode' 'mtls')

println (kv .get 'node.host' .none)
println (kv .get 'node.port' .none)

snap = (kv .snapshot .none .none)
println (str/append 'audit-valid=' (mold (kv .verify .none .none)))
println (str/append 'entries=' (mold snap.audit.len))

// JSON round-trip persistence check
encoded = j/encode snap
reloaded = j/decode encoded
println (str/append 'roundtrip-keys=' (mold reloaded.keys.len))