Part II · Standard Library, PQC, Networking, Async, Durable State & Desktop UI
Chapter 7
Standard Library Foundations & Post-Quantum Cryptography
Collections, Thompson NFA regex, DEFLATE/Zstandard, AEAD sealing, and NIST FIPS 203/204/205 PQC
Veko ships a 95-module pure-.vk standard library under lib/ (embedded directly inside the single veko binary via stdlib_vfs.vk) that runs identically across all three execution tracks—the 64-bit VKO VM (--vm), the vvm WebAssembly 3.0 sandbox (--wasm), and standalone native x86_64 & AArch64 executables (--native). Every pure data, codec, archive, fuzzing, and cryptographic module requires zero host capabilities, while connected modules (io/*, net/*, reactor, web, db/*, durable/*, ui/*, ffi) declare fine-grained capabilities (allow-caps).
Pure-Veko Standard Library & Post-Quantum Cryptography Architecture
1,043 exported structs and functions across 79 modules — from core data structures to NIST FIPS 203/204/205 PQC.
| Component & Module | Architectural Role |
|---|---|
Core, Text, Math & CLIlib/fmt.vk + lib/cli.vk + lib/coll.vk | Provides formatting, subcommand CLI parsing, sets/rings/heaps/LRU, regex NFA, and UTF-8. |
Codecs, Wire & Archiveslib/codec/* + lib/archive/* | Encodes and decodes binary and text wire formats plus compressed TAR/ZIP archives. |
Streams, Reactor, DB & UIlib/reactor.vk + lib/web.vk + lib/durable.vk | Builds high-level networking, persistence, workflows, and UIs over the capability PAL. |
AEAD, Hashes & Curveslib/crypto/aes.vk + lib/crypto/x25519.vk | Constant-time symmetric AEADs, cryptographic Sponge/Merkle hashes, KDFs, and elliptic curves. |
NIST FIPS 203 / 204 / 205lib/crypto/mlkem.vk + lib/crypto/mldsa.vk | Quantum-resistant lattice KEMs, lattice signatures, and stateless hash signatures. |
crypto/seal & Auth Tokenslib/crypto/seal.vk + lib/auth/jwt.vk | Combines sealed AEAD envelopes with EdDSA/ML-DSA65 JWTs, OAuth2 PKCE, and RFC 6238 TOTP. |
1. Complete 95-Module Standard Library Map
| Category | Modules (use [...]) | Highlights | Dedicated Guide / Demo |
|---|---|---|---|
| Developer Harness, Fuzzing & Profiling | fmt, cli, testing, testing/fuzz, datetime, slog, diff, semver, retry, template, profile/flamegraph | Templates, IEC sizes, hexdumps, CLI subcommands, test/bench runner, SplitMix64 byte/UTF-8/homoiconic-block fuzzing & shrinking, RFC 3339 timestamps, structured logs, Myers diff, SemVer 2.0, backoff, interactive Light-Mode SVG flamegraphs | examples/17_stdlib_cli_fmt_and_collections.vk, examples/39_debugger_coverage_and_fuzzing.vk |
| Core Math, Text & Collections | math, bits, text, text/re, utf8, path, fs, seq, coll, rand | Checked/sat math, IEEE-754 transcendentals, CRC-32/Adler-32/varints, Unicode UTF-8, capture-group Thompson NFA text/re, safe path confinement, high-level fs, merge sort, Set/Ring/Heap/Lru/Memo, UUID v4/v7 | examples/17_stdlib_cli_fmt_and_collections.vk, examples/36_regex_captures_zstd_and_otel.vk |
| Buffers, Streams, Regex & Dialects | buf, io, io/{fs,net,open}, glob, regex, dialect | ByteReader/ByteWriter/StringBuilder, polymorphic io/Stream & SchemeMux, linear-time ** globbing, ReDoS-proof Thompson NFA regex, homoiconic dialect rewriters | examples/18_io_streams_regex_and_codecs.vk |
| Codecs, Compression, PNG & Packages | codec/{wire,hex,url,csv,ini,toml,vbin,cbor,http1,http2,http3,der,pem}, compress/{deflate,zstd}, image/png, archive/{tar,zip}, pkg/{vkp,lock} | Schema binary framing, Hex/Base64, URLs, CSV, INI, TOML, VBIN, CBOR, HTTP/1.1, HTTP/2 + HPACK + Huffman, HTTP/3 + QPACK, ASN.1 DER, PEM, DEFLATE/zlib/gzip, RFC 8878 Zstandard, lossless RGBA32 PNG, TAR/ZIP, signed VKP1 + veko.lock | examples/25_batteries_datetime_fs_archives_and_toml.vk, examples/37_clipboard_x11_flamegraph_and_lock.vk |
| Classical Crypto & Sealing | crypto/{sha256,sha3,blake,aes,chacha20,kdf,seal,sig,x25519,x509} | SHA-256/384/512, HKDF, FIPS 202 SHA3/SHAKE, BLAKE2b, AES-128/256-GCM, ChaCha20 & XChaCha20-Poly1305, PBKDF2, Argon2id, pub sealed Sealed + zeroizing unseal, X25519, Ed25519, P-256/P-384, RSA-PSS, X.509 | examples/19_modern_crypto_and_sealed_vault.vk |
| NIST Post-Quantum Crypto | crypto/{mlkem,mldsa,slhdsa} | FIPS 203 ML-KEM-512/768/1024, FIPS 204 ML-DSA-44/65/87, FIPS 205 SLH-DSA-SHA2/SHAKE | examples/20_post_quantum_nist_pqc.vk |
| Networking, Web, Auth, OTel & Zero-FFI DBs | reactor, conc/scope, otel, net/{dns,ip,client,tls13,http2,http3,websocket}, web, html, auth/{jwt,oauth2,totp}, db/{sqlite,kv,query,postgres,redis,sidecar} | Readiness reactor (epoll/kqueue/IOCP), structured task scopes, W3C OpenTelemetry, DNS, Hybrid PQC TLS 1.3 + built-in Let's Encrypt P-256/P-384 CAs, HTTP/2 + Rapid Reset guards, WAN QUIC v1 HTTP/3, streaming web + HEAD + HTML5 DSL, JWT/OAuth2/TOTP, Zero-FFI SQLite 3 (VKJRNL01 crash journal, B-tree indexes, INNER/LEFT JOIN, ORM), WAL KV, pooled TLS PgPool & RESP3 RedisPool | Net, Web, DB & VKP1, Async & Reactor |
| Durable State, Studio UI/Wayland/X11/TUI & Opt-In FFI | durable, durable/{object,workflow}, tui, ui, ui/{canvas,font,layout,widgets,wayland,x11}, ffi | Crash-safe Durable Objects & Workflows with retry backoff, DLQs & worker leases, TrueColor diffing TUI, RGBA32 2D canvas, font, flex/grid layout, 33 Studio widgets (code-editor, command-palette, file-picker, Tab focus rings), Win32 + Linux Wayland/X11 + macOS arm64 Cocoa + Wasm <canvas> + clipboard/Hi-DPI, and opt-in .ffi (VEKO_LIB) | Durable Objects & Workflows, TUI, UI & FFI |
2. Inspecting & Testing Libraries with veko doc
Because Veko extracts documentation directly from source // comments and AST signatures, documentation never drifts from the code:
# View all exported items in a library module
veko doc fmt
# View a single symbol's signature, capability tags, and doctest
veko doc crypto/mlkem keygen-deterministic
# Generate machine-readable api.json or Markdown API docs
veko doc --json fmt cli testing -o dist/api.json
veko doc --md crypto/aes crypto/seal -o dist/crypto_api.md
# Execute ```vk doctests on the 64-bit VKO VM, Wasm 3.0 (--check-slabs), or Native x86_64
veko doc --test --vm fmt cli testing math bits text path seq coll buf io
veko doc --test --native crypto/mlkem crypto/mldsa crypto/slhdsa
veko doc --test --all fmt cli3. Developer Harness: fmt, cli, and testing
Formatting, Units, Hex Dumps & Tables (fmt)
fmt turns raw numbers, byte buffers, and tabular records into readable output without external dependencies:
use [fmt]
msg = fmt/template 'Synced {name} ({sz}) in {dt}' {
name = 'edge-eu'
sz = (fmt/size 2621440) // '2.50 MiB'
dt = (fmt/dur 12500000) // '12.50 ms'
}
println msg
println (fmt/format 'radix-16={0} padded={1}' [(fmt/int-radix 255 16) (fmt/hex 42 4)])
println (fmt/table ['Node' 'Status'] [['edge-eu' 'READY'] ['edge-us' 'READY']])Key functions: fmt/format, fmt/template, fmt/int-radix, fmt/hex, fmt/hex-bytes, fmt/size, fmt/dur, fmt/pad-left, fmt/pad-right, fmt/hexdump, fmt/table.
Declarative CLI Parsing (cli)
cli parses --flag=value, --flag value, short flag clusters (-v), repeatable .list flags, subcommands, -- positional arguments, and auto-renders --help text:
use [cli]
spec = cli/CliSpec {
name = 'node-ctl'
version = '1.0.0'
summary = 'Cluster deployment tool'
flags = [
cli/FlagSpec { name = 'port', short = 'p', kind = .i64, default_val = 8443, help = 'Listen port' }
cli/FlagSpec { name = 'verbose', short = 'v', kind = .bool, default_val = false, help = 'Verbose output' }
]
commands = [
cli/CmdSpec { name = 'deploy', summary = 'Deploy a bundle', min_args = 1 }
]
}
res = cli/parse/or spec os/args [
println (cli/render-help spec)
return (err 'invalid arguments')
]
port = cli/flag-i64 res 'port' 8443Unit Tests & Micro-Benchmarks (testing)
testing provides structured assertion suites (Suite, new, ok, eq, neq, is-err, is-ok, approx, report, finish) and monotonic benchmarking (bench using .clocks):
use [t = testing, m = math]
mut s = t/new 'math-checks'
_ = t/eq mut s (m/gcd 48 18) 6 'gcd'
_ = t/approx mut s (m/sqrt 2.0) m/sqrt2 0.000000000001 'sqrt(2)'
_ = t/report s4. Core Utilities & Collections: math, bits, text, path, seq, coll, rand
math: Zero-overhead compile-time folded constants (math/pi,math/tau,math/e,math/ln2,math/sqrt2,math/i64-max,math/i64-min), overflow-safe integer math (add-checked,sub-checked,mul-checked,add-sat,sub-sat,clamp-i64,gcd,lcm,pow-i64,isqrt), 64/32-bit bitops (popcount,clz,ctz,rotl64,rotr64,rotl32,rotr32), and pure IEEE-754 double-precision transcendentals (sqrt,exp,ln,log2,log10,pow,sin,cos,tan,atan,atan2,floor,ceil,round,trunc,isnan?,isinf?).bits: 24-bit (get-u24-be/push-u24-be) and signed 16/32-bit wire helpers layered over hardware LE/BE intrinsics, IEEE-754f64-to-bits/bits-to-f64, LEB128push-varint-u64/read-varint-u64+zigzag-encode/zigzag-decode, checksums (crc32,adler32,fnv1a-64), byte search (index-of,starts-with?,ends-with?,xor-in-place!), and constant-time equality (ct-eq?).text: String search & replacement (starts-with?,ends-with?,index-of,last-index-of,replace,replace-all,repeat,trim-prefix,trim-suffix),lines,words, ASCII predicates (ascii-alpha?,ascii-digit?,ascii-alnum?,ascii-hex?,ascii-space?),slugify, and UTF-8 scalar codepoint helpers (utf8-len,utf8-codepoints,utf8-from-codepoints).path: Cross-platform lexical path operations (normalize,join,join-all,dir,base,ext,stem,with-ext,is-abs?,split-parts) plus security-firstpath/confine root relthat rejects absolute paths and..directory traversal attempts.seq: Stable $O(N \log N)$sort/sort-by(merge sort),binary-search,reverse,unique,chunk,zip,enumerate,flatten,take,drop,fold,any?,all?,find,partition,group-by,count-by,range-seq.coll: Five everyday data structures backed by Veko 1.0's hybrid hashedmapand O(1) in-placeput:Set(set-new,set-from,set-add,set-remove,set-has?,set-union,set-intersect,set-diff)Ring(fixed-capacity O(1) FIFO circular buffer:ring-new,ring-push,ring-pop,ring-peek)Heap(binary min-heap priority queue:heap-new,heap-push,heap-pop,heap-peek)Lru(bounded LRU cache:lru-new,lru-get,lru-put,lru-has?)Memo(memo-new,memo-call)
rand: DeterministicSplitMix64+xoshiro256++PRNG (seed,next-u64,range,f64-unit,bytes-fill,shuffle,choose) for reproducible simulations and tests, plus OS/hardware CSPRNG helpers (csprng-bytes,uuid-v4) for cryptographic randomness.
5. Buffers, Streams, Pattern Matchers & Dialects: buf, io, glob, regex, dialect
Cursor Buffers & ORO Streams (buf, io)
buf provides ByteReader (cursor reads for u8, u16/u32/i64 LE & BE, read-bytes, read-str, read-until), ByteWriter, and StringBuilder. io builds ORO-native value-state Streams (mem-stream, read, write, read-all, write-all, copy, close) and an extensible SchemeMux (mux-default with mem://):
use [io]
mux = io/mux-default
mut src = io/mux-open mux 'mem://hello-veko-stream'
mut dst = io/mem-stream (bytes/with-cap 0)
_ = io/copy mut src mut dst 16
println (bytes/to-str (io/read-all mut dst))Linear-Time Globbing, ReDoS-Proof Regex & Dialects (glob, regex, dialect)
glob: Linear-time dynamic-programming matching for*,**(recursive across/),?, and[a-z]/[!0-9]character classes (glob/match?,glob/filter).regex: Guaranteed $O(N \cdot S)$ Thompson NFA engine—immune to catastrophic backtracking (ReDoS). Supports literals,.,^,$,*,+,?,|,(...),[a-z],[^...],\\d,\\w,\\s(regex/compile,is-match?,find,find-all,replace-all).dialect: Structural tree walker (rewrite-tree,collect),$var/*pattern matcher (match-pattern), clause splitter (split-clauses), and rule compiler (apply-rules) for custom homoiconic DSLs.
6. Wire Formats, Structured Codecs & Compression (codec/*, compress/deflate)
All codecs follow Veko 1.0's "No nil" rules (wire null decodes cleanly to .null, and missing keys/truncated frames return recoverable err values):
codec/wire: Declarative binary packet packing & unpacking (Fieldkinds:.u8,.u16_le,.u16_be,.u32_le,.u32_be,.i64_le,.i64_be,.varint,.f64_be,.bytes_u16_be,.str_u16_be,.raw).codec/hex: Lowercase/uppercase RFC 4648 hexadecimal (encode,encode-upper,decode).codec/url: RFC 3986Urlparser/formatter (parse,format,encode-component,decode-component,parse-query,encode-query).codec/csv&codec/ini: RFC 4180 CSV (parse,parse-records,encode) and.ini/.conf(parse,get,encode).codec/vbin&codec/cbor: Canonical deterministic Veko binary (vbin/encode,vbin/decode) and RFC 8949 deterministic CBOR (cbor/encode,cbor/decode) with sorted map keys and.nullround-trip.codec/http2: RFC 9113 binaryFrameframing (encode-frame,decode-frame,encode-settings,decode-settings) and RFC 7541 HPACK header blocks (hpack-encode,hpack-decode).codec/der,codec/pem,codec/http1: ASN.1 DER TLV encoding/decoding, RFC 4648 Base64 + PEM blocks, and HTTP/1.1 wire framing.compress/deflate: Pure-.vkRFC 1951 DEFLATE (deflateLZ77 + Fixed Huffman with Stored fallback;inflatesupporting Stored, Fixed Huffman, and Dynamic Huffman blocks), RFC 1950zlib-compress/zlib-decompress(with Adler-32 check), and RFC 1952gzip-compress/gzip-decompress(with CRC-32 & ISIZE checks).
7. Classical Cryptography & Sealed Envelopes (crypto/*)
Every cryptographic primitive is implemented in 100% pure Veko with zero OpenSSL or OS crypto DLL dependencies:
- Hash & XOF Families:
crypto/sha256:sha256, streamingsha256-init/sha256-update/sha256-digest,sha384,sha512,hmac-sha256,hmac-sha384,hmac-sha512, and RFC 5869hkdf-*key derivation.crypto/sha3: FIPS 202 Keccak-f[1600] (sha3-256,sha3-512,shake128,shake256, and streamingshake128-init/shake256-init/xof-squeeze).crypto/blake: RFC 7693 BLAKE2b (blake2b,blake2b-256,blake2b-512,blake2b-keyed).
- Authenticated Encryption (AEAD) & Sealed Envelopes:
crypto/aes: Constant-time algebraic AES-128 & AES-256 (zero secret-indexed S-box tables) + NIST SP 800-38Dgcm-encrypt/gcm-decryptwith automatic round-key zeroization (bytes/zeroize!).crypto/chacha20: RFC 8439aead-encrypt/aead-decrypt(12-byte nonce) plushchacha20and 24-byte-noncexchacha20-poly1305-encrypt/xchacha20-poly1305-decrypt.crypto/seal: High-levelpub sealed Sealedenvelope (external code cannot forge or mutate fields) backed by AES-256-GCM + CSPRNG nonces, portableVKSLwire serialization (to-bytes/from-bytes), and RAIIseal/with-openthat unseals plaintext into a callback and scrubs it viadefer [ bytes/zeroize! mut pt ]:
use [seal = crypto/seal]
key = random/bytes 32
env = seal/encrypt key (bytes/from-str 'api-secret-payload') (bytes/from-str 'v1')
wire = seal/to-bytes env
restored = seal/from-bytes wire
n = seal/with-open restored key fn [pt] [ len pt ]
println n // 18 (plaintext buffer is zeroized automatically when callback returns)- Password KDFs & Signatures:
crypto/kdf:pbkdf2-sha256, memory-hard RFC 9106argon2id, and constant-timeverify-tag.crypto/x25519: RFC 7748 X25519 key agreement and RFC 8032 Ed25519 signing/verification.crypto/sig: RFC 6979 deterministicecdsa-p256-pubkey/ecdsa-p256-sign/ecdsa-p256-verify,ecdsa-p384-verify, RSA PKCS#1 v1.5 & RSA-PSS verification, andpkcs8-extract-private-key.crypto/x509&net/tls13: X.509 v3 certificate parsing/chain validation and pure-.vkRFC 8446 TLS 1.3.
8. NIST Post-Quantum Cryptography (crypto/mlkem, crypto/mldsa, crypto/slhdsa)
Veko ships all three finalized NIST Post-Quantum Cryptography standards natively in pure .vk, built directly atop crypto/sha3 and in-place put NTT polynomial arithmetic:
| Standard | Module | Parameter Sets | Purpose |
|---|---|---|---|
| FIPS 203 (ML-KEM) | crypto/mlkem | .mlkem512, .mlkem768, .mlkem1024 | Lattice key encapsulation (KEM) with constant-time implicit rejection on tampered ciphertexts |
| FIPS 204 (ML-DSA) | crypto/mldsa | .mldsa44, .mldsa65, .mldsa87 | Module-lattice digital signatures with full rejection sampling & hint verification |
| FIPS 205 (SLH-DSA) | crypto/slhdsa | .shake_128f, .shake_128s | Stateless hash-based signatures (WOTS+ + FORS + XMSS hypertree over SHAKE256) |
use [kem = crypto/mlkem, dsa = crypto/mldsa, slh = crypto/slhdsa]
// 1. Quantum-resistant key exchange (FIPS 203 ML-KEM-768)
kp = kem/keygen .mlkem768
enc = kem/encaps .mlkem768 kp.ek
ss = kem/decaps .mlkem768 kp.dk enc.ciphertext // matches enc.shared_secret
// 2. Lattice digital signature (FIPS 204 ML-DSA-65)
skp = dsa/keygen .mldsa65
sig = dsa/sign .mldsa65 skp.sk (bytes/from-str 'release manifest')
ok1 = dsa/verify .mldsa65 skp.pk (bytes/from-str 'release manifest') sig
// 3. Stateless hash-based signature (FIPS 205 SLH-DSA-SHAKE-128f)
hkp = slh/keygen .shake_128f
hsig = slh/sign .shake_128f hkp.sk (bytes/from-str 'root trust anchor')
ok2 = slh/verify .shake_128f hkp.pk (bytes/from-str 'root trust anchor') hsig9. Runnable Library Demos & Baseline Benchmarks
Explore all standard library modules in action:
# Core harness, math, collections, & PRNG (`fmt`, `cli`, `testing`, `math`, `text`, `path`, `seq`, `coll`, `rand`)
veko run examples/17_stdlib_cli_fmt_and_collections.vk
# Streams, matchers, codecs, & compression (`buf`, `io`, `glob`, `regex`, `dialect`, `codec/*`, `compress/deflate`)
veko run examples/18_io_streams_regex_and_codecs.vk
# Classical crypto & sealed vault (`sha3`, `blake`, `aes`, `chacha20`, `kdf`, `seal`, `sig`)
veko compile --native examples/19_modern_crypto_and_sealed_vault.vk -o dist/19.exe ; ./dist/19.exe
# NIST Post-Quantum Cryptography (`mlkem`, `mldsa`, `slhdsa`)
veko compile --native examples/20_post_quantum_nist_pqc.vk -o dist/20.exe ; ./dist/20.exe
# Connected I/O streams, DNS, Hybrid PQC TLS 1.3 (`X25519MLKEM768`) & HTTP/2
veko run --allow-net --allow-listen --allow-private-net examples/21_io_streams_dns_and_pqc_tls.vk
# Web micro-framework, HS256/EdDSA/ML-DSA-65 JWT, OAuth2 PKCE & RFC 6455 WebSockets
veko run --allow-net --allow-listen --allow-private-net examples/22_web_server_websocket_and_jwt.vk
# Embedded crash-safe KV store, PostgreSQL SCRAM-SHA-256, Redis RESP3 & Sidecar RPC
veko run --allow-net --allow-listen --allow-private-net examples/23_zero_ffi_databases_kv_pg_redis.vk
# Signed `VKP1` package bundles (Merkle tree + Hybrid Ed25519 & ML-DSA-65)
veko run examples/24_signed_vkp_package_bundles.vk
# Baseline performance benchmarks (`benchmarks/bench_suite.vk`)
veko compile --native benchmarks/bench_suite.vk -o dist/bench.exe ; ./dist/bench.exeSee Networking, Web, Databases & Signed Bundles Guide for dedicated walkthroughs of io/{fs,net,open}, net/{dns,tls13,http2,websocket}, web, auth/{jwt,oauth2}, db/{kv,postgres,redis,sidecar}, and pkg/vkp.