dealcode (Rust)
Collision-free, random-looking codes from a counter. Rust implementation of the dealcode spec.
Install
Requires Rust ≥ 1.85. The only runtime dependencies are the audited
RustCrypto crates
aes and
sha2, used for AES and key derivation.
Quickstart
use Dealcode;
let codec = new?;
codec.encode?; // "767a5b" (6 hex chars)
codec.encode?; // "421163" never collides with any other counter
codec.decode?; // 1
# Ok::
The key can be raw bytes (16/24/32 bytes are used as-is as an AES key) or any
string/bytes, which are deterministically expanded to an AES-256 key. Generate
one with openssl rand -hex 32 and keep it in your secret manager — the
mapping is stable only while the key (and every other option) stays fixed.
Options
use Dealcode;
let codec = builder // impl Into<Key>: &str, String, &[u8], Vec<u8>, [u8; N]
.alphabet // "dec" | "hex" | "base32" | "crockford" | "base36"
// | "base58" | "base62" | "base64url" | custom string
.min_length // codes start at this length...
.max_length // ...and grow one char at a time up to this
// (default: max length whose code space fits 2^63)
.domain // namespace: same key, unrelated codes per domain
.build?;
let coupon = builder.alphabet.domain.build?;
// human-friendly, e.g. "97HVZ6"
let order = builder.alphabet.min_length.domain.build?;
// digits only
let fixed = builder.min_length.max_length.build?;
// constant-length hex
decode returns Err(Error::InvalidCode(_)) for malformed input — wrong
length, characters outside the alphabet, or a value outside the issuable
range. A well-formed code always decodes to some counter, whether or not
that counter was ever issued (inherent to a permutation — see SPEC §7).
Treat decode as parsing, not proof of existence: look the counter up before
acting on it, and note that a one-character typo in a valid code can resolve
to a different valid counter — add rate limiting (and, for human-typed
flows, an existence check or your own check digit).
encode returns Err(Error::Range { .. }) outside [0, codec.capacity()).
Invalid configuration is rejected at build time with Err(Error::Config).
All three are variants of dealcode::Error, which implements
std::error::Error.
Using it with your database
Dealcode does not talk to your database — it only turns a counter into a code. Any source of never-repeating integers works. With PostgreSQL:
;
(
id bigint PRIMARY KEY, -- the counter
code text NOT NULL UNIQUE, -- safety net; alerts on config mistakes
...
);
use ;
let codec = builder
.domain
.build?;
// on create:
let n: i64 = client.query_one?.get;
let code = codec.encode?;
client.execute?;
// on lookup:
Sequences never hand out the same number twice (even across concurrent transactions and rollbacks), so codes never collide. Gaps in the sequence are invisible — codes look random anyway.
If the UNIQUE constraint on code ever fires, do not retry: it means the
key/config changed for an existing namespace. Investigate.
Fixed-length cycling mode
For code shapes that must never grow (airline-PNR-style), CyclingDealcode
issues codes that are always exactly length characters. The counter space is
spent in cycles of capacity() = radix^length codes each; when a cycle is
exhausted, the next cycle refills the same code space through a different
permutation (SPEC §11).
use CyclingDealcode;
Configuration mirrors Dealcode (key, alphabet, domain) with a single fixed
length: 2 <= length <= 128 and 100 <= radix^length <= 2^63.
Operational rule: codes repeat across cycles by design, so a global
UNIQUE(code) index spanning cycles WILL fire — scope uniqueness as
UNIQUE(cycle, code), keep at most one cycle's codes live at a time per scope
(retire or expire cycle e before issuing from e+1), and persist each live
code's cycle (or the currently active cycle): decode needs it, and the
library cannot recover the cycle from the code string. Decoding with a wrong
(but in-range) cycle is not an error — it silently returns a different
counter; the existence check on the decoded counter is what catches it.
Thread safety & performance
A Dealcode instance is immutable and Send + Sync; create one per namespace
at startup and share it freely (e.g. in an Arc or a static). AES round
keys and per-length FF1 parameters are precomputed at build time; encoding is
ten AES-CBC-MAC rounds — a few microseconds, O(1) in the counter value, no
locks.
Interoperability
This crate implements format version 1 of the spec exactly and passes the
official NIST FF1-AES sample vectors plus the shared
testvectors/
suite; codes are byte-for-byte identical to those produced by every other
conforming implementation (e.g. the
Python package).
Running the tests
From rust/:
The suite covers the official NIST FF1 sample vectors, every shared
cross-language vector in
testvectors/,
behavioural cases, and doctests.
License
MIT — see LICENSE.