entropy_contract
The words a client and an entropy service exchange to move random bytes, and the rules for reading
what comes back. no_std, no dependencies, no system calls of its own: the caller supplies the
CALL. A CALL is the kernel's synchronous message call, one word in and two words back, sent to
an endpoint: a capability that names the service. The service, its clients and any library that
wraps the call share this one definition, so they cannot drift. A backend is the driver for one
kind of random-number device.
The contract
A CALL carries one request word and returns two reply words.
- Request: the opcode in bits 63:56 (
OPERATION_SHIFTis 56), the byte count in bits 7:0. There is one operation,GET(1). Build a request withrequest, read it withoperationandrequested_bytes.requestrefuses an opcode above 0xff withOperationOutOfRangein every build. A service answers any other opcode withNO_ENTROPY. Bits 55:8 are reserved: a client sends zero there, and a service answers a request with any of them set withNO_ENTROPY(request_is_well_formedsays whether a word is well formed). - Reply word 1: the count of valid bytes in word 2, from 0 to
MAXIMUM_BYTES(8). A count of 0 isNO_ENTROPY: the service has none to give, and it never pads, repeats an earlier answer or substitutes a pseudo-random stand-in. A caller that receives no randomness must find out. - Reply word 2: those bytes, little-endian, in the low bytes, and zeros above them. A caller must not read the rest of the word, which carries no entropy.
- A request for more than
MAXIMUM_BYTESgetsMAXIMUM_BYTES, not a refusal:requestclamps the count it encodes andrequested_bytesclamps the count it reads, so the caller loops. - A reply word 1 above
MAXIMUM_BYTESdid not come from the service. The contract asks the caller's kernel to report a failedCALLas a word aboveMAXIMUM_BYTES. A kernel that returns a small negative error number meets that, since each reads as an enormous unsigned value. Thendelivered_bytesreturnsNonefor it, and a caller with no entropy capability finds out without a probe. - Readiness: a service reports its bring-up on a second endpoint, its readiness endpoint, apart
from the one clients call. It sends
READYthere only after it holds a first draw that is not all zero and, for a draw of at leastMAXIMUM_BYTESbytes, not one value repeated (readinessdecides).READYis 0x524E475550,BRING_UP_FAILEDis 0xDEAD_0000_0000_0000 andNO_ENTROPYis 0. Otherwise it sendsBRING_UP_FAILED | step(bring_up_failure), where the step isSTEP_NO_FIRST_BYTES(0x10, the device never answered),STEP_FIRST_ALL_ZERO(0x11, every byte was zero) orSTEP_FIRST_ALL_SAME(0x12, at leastMAXIMUM_BYTESbytes, every one equal and nonzero).bring_up_failurerefuses a step above 0xff withStepOutOfRangein every build. Steps 0x01 to 0x0f belong to each backend. This contract reserves steps 0x00 and 0x13 to 0xff for later shared steps and assigns none of them. Treating an all-zero first draw as a dead device is wrong with probability 2^-64 for an 8-byte draw down to 2^-2048 for a 256-byte one. For eight equal bytes it is 255 in 2^64 or less. Both errors are the safe way round. INTERFACE_ID(12) is this interface's number. No other interface takes it, and a format change is a new version, never a new number.VERSION(1) is the protocol's version: one number for the operation set and the reply shape. A break bumps it. A new opcode does not. A new field in the request word must be a new opcode or a version bump, because a service refuses any request with a reserved bit set. A program that speaks this interface declares the pair ofINTERFACE_IDandVERSIONin the note that lists its interfaces.- A service builds its reply with
reply: the count, then the delivered bytes little-endian in the low bytes of the word, with zeros above them.
EXAMPLES
use entropy_contract::{GET, MAXIMUM_BYTES, delivered_bytes, request, copy_delivered_bytes, requested_bytes};
// Stands in for the service: it answers with a count and a word of bytes.
fn service(request_word: u64) -> (u64, u64) {
(requested_bytes(request_word), 0x0807_0605_0403_0201)
}
let mut key = [0u8; 20];
let mut filled = 0;
while filled < key.len() {
let (first_reply_word, reply_word) = service(request(GET, (key.len() - filled) as u64).expect("GET fits"));
let byte_count = delivered_bytes(first_reply_word).expect("the service answered");
assert_ne!(byte_count, 0, "a zero count is NO_ENTROPY: fail, do not retry");
filled += copy_delivered_bytes(byte_count, reply_word, &mut key[filled..]);
}
assert_eq!(MAXIMUM_BYTES, 8);
fill_with(out, call) runs a stricter form of that loop, given a closure that performs the
CALL. It refuses a partial count because a caller filling a key must never hold fewer random
bytes than it asked for and believe otherwise. It returns Ok(()) for an empty slice without
calling the closure. It refuses any reply whose count differs from the one it asked for. It returns
Err(Refusal::NoService) when a reply is not a count, and Err(Refusal::ShortReply { asked, delivered }) when a reply carries a different count than the request asked for, a larger one
included. A dry device causes the second, so a caller can tell a missing grant from an empty
source. Refusal is #[non_exhaustive], so a match on it needs a wildcard arm.
A service answers one request by checking that the word is well formed, checking the opcode,
clamping the count and building the reply. Here draw stands in for the device:
use entropy_contract::{
GET, NO_ENTROPY, MAXIMUM_BYTES, operation, reply, request, request_is_well_formed,
requested_bytes,
};
fn handle(request_word: u64, draw: &mut impl FnMut(&mut [u8])) -> (u64, u64) {
if !request_is_well_formed(request_word) || operation(request_word) != GET {
return (NO_ENTROPY, 0);
}
let mut bytes = [0u8; MAXIMUM_BYTES as usize];
let count = requested_bytes(request_word) as usize; // already at most MAXIMUM_BYTES
draw(&mut bytes[..count]);
reply(&bytes[..count])
}
let mut device = |out: &mut [u8]| out.fill(0xab);
assert_eq!(handle(request(GET, 3).expect("GET fits"), &mut device), (3, 0x00ab_abab));
assert_eq!(handle(request(2, 3).expect("2 fits"), &mut device), (NO_ENTROPY, 0));
What is proven
Seven Kani harnesses in src/lib.rs prove these properties, each within the stated bounds:
- A request word reads back as built: for any opcode that fits the top byte and any byte count,
operationreturns the opcode.requested_bytesreturns the count, clamped toMAXIMUM_BYTES. - A copy writes only the delivered bytes: for any count, any reply word and any slice of up to 12
bytes,
copy_delivered_byteswrites the least of the count,MAXIMUM_BYTESand the slice length. It writes them in little-endian order and leaves every other byte alone. - A fill succeeds exactly when every reply is full: for any slice of up to 17 bytes and any
replies,
fill_withasks for the remainder clamped toMAXIMUM_BYTESeach time. It answersOkexactly when every reply delivers the bytes it asked for, and then holds those bytes in order. Otherwise it refuses withNoServiceexactly when the reply was not a count, and withShortReplynaming the asked and delivered counts exactly when it was. - A reply reads back as built: for any bytes up to 12,
replyanswers the count of the least of their number andMAXIMUM_BYTES.delivered_bytesaccepts that count,copy_delivered_bytesreturns the bytes in order, and every byte of the word above them is zero. - An opcode or a step past one byte gets a refusal: for any value,
requestanswersOperationOutOfRangeexactly when it is above 0xff, andbring_up_failureanswersStepOutOfRangeexactly when it is above 0xff. Otherwise the word is neitherREADYnor a count, and its low byte is the step. - Readiness refuses a repeated first draw: for any first draw of up to 9 bytes,
readinessnamesSTEP_FIRST_ALL_SAMEwhen the draw holds at leastMAXIMUM_BYTESbytes of one nonzero value. It answersREADYfor every draw that is neither empty, zero nor such a repeat. - Readiness is
READYexactly when a byte of the first draw is nonzero: for any first draw of up to 4 bytes,readinessanswersREADYwhen at least one byte is nonzero. Otherwise it namesSTEP_NO_FIRST_BYTESfor an empty draw orSTEP_FIRST_ALL_ZEROfor a draw of zeros.
The table gives each harness's full path, the property it proves and the falsification patch that
turns it red. cargo kani list prints the harnesses. A patch in falsifications/ takes the name
verification.<harness>.patch.
| Harness | Property | Falsification patch |
|---|---|---|
verification::a_request_word_carries_its_opcode_and_clamped_count |
a request reads back as built | verification.a_request_word_carries_its_opcode_and_clamped_count.patch |
verification::an_opcode_or_step_past_one_byte_is_refused |
an opcode or a step past one byte is refused | verification.an_opcode_or_step_past_one_byte_is_refused.patch |
verification::copying_writes_exactly_the_delivered_bytes |
a copy writes only the delivered bytes | verification.copying_writes_exactly_the_delivered_bytes.patch |
verification::a_fill_succeeds_exactly_when_every_reply_is_full |
a fill succeeds exactly when every reply is full | verification.a_fill_succeeds_exactly_when_every_reply_is_full.patch |
verification::a_reply_reads_back_as_built |
a reply reads back as built | verification.a_reply_reads_back_as_built.patch |
verification::readiness_refuses_a_repeated_first_draw_of_at_least_eight_bytes |
readiness refuses a repeated first draw | verification.readiness_refuses_a_repeated_first_draw_of_at_least_eight_bytes.patch |
verification::readiness_is_reported_exactly_when_a_first_byte_is_nonzero |
readiness is READY exactly when a byte is nonzero |
verification.readiness_is_reported_exactly_when_a_first_byte_is_nonzero.patch |
Every harness carries a falsification patch in falsifications/, a small defect that turns the
harness red. Unit tests and doctests cover the rest, among them that no byte count collides with a
kernel error.
Building and testing
You need git, a Rust toolchain installed with rustup and a C linker. The
proofs also need patch. Get the source and build from its top directory:
git clone https://github.com/nifeos/entropy_contract
cd entropy_contract
cargo test
rustup target add x86_64-unknown-none aarch64-unknown-none-softfloat riscv64imac-unknown-none-elf
cargo build --lib --target x86_64-unknown-none
cargo build --lib --target aarch64-unknown-none-softfloat
cargo build --lib --target riscv64imac-unknown-none-elf
The crate has no features and no dependencies, so a plain cargo test runs every unit test and
doctest.
Running the proofs
Install Kani first: run cargo install --locked kani-verifier --version 0.68.0, then cargo kani setup. Both need network access. cargo install builds only Kani's small installer, about ten crates. Setup downloads Kani's release
bundle, about 140 megabytes, and the nightly Rust toolchain Kani is pinned to. It then holds
about 485 megabytes in ~/.kani and 1.5 gigabytes in ~/.rustup. On the host measured below,
from empty Cargo and rustup directories, the install took 5 seconds and setup 30. Release bundles
exist for x86_64 and aarch64 Linux and macOS, and not for Windows. Then run every harness:
cargo kani
The seven harnesses take about one minute and peak near 2.2 gigabytes of memory, as
/usr/bin/time -v cargo kani (Linux only; macOS has no -v) measured on a shared 80-core x86_64 host. Almost all of the time is
a_fill_succeeds_exactly_when_every_reply_is_full; each other harness takes seconds. To run one harness, give its full path, because
--exact refuses a bare name:
cargo kani --harness verification::a_reply_reads_back_as_built --exact
A passing run prints lines that look alarming and mean nothing. They are the use of an unstable feature warning for register_tool, the Found the following unsupported constructs warning, and
many aborting path on assume(false) lines, which are paths Kani discards on purpose. The answer
is the last line, Complete - 7 successfully verified harnesses, 0 failures, 7 total., and
cargo kani exits 0.
Running one falsification patch
Each file in falsifications/ applies a small defect that turns its harness red. Apply one,
confirm the proof fails, then undo it with the same patch reversed:
patch -p1 --no-backup-if-mismatch < falsifications/verification.readiness_is_reported_exactly_when_a_first_byte_is_nonzero.patch
cargo kani --harness verification::readiness_is_reported_exactly_when_a_first_byte_is_nonzero --exact
patch -R -p1 --no-backup-if-mismatch < falsifications/verification.readiness_is_reported_exactly_when_a_first_byte_is_nonzero.patch
patch may report Hunk #1 succeeded at a line number with an offset; that is harmless. The
failing run prints Failed Checks: assertion failed: word == READY and
VERIFICATION:- FAILED. It ends with Complete - 0 successfully verified harnesses, 1 failures, 1 total., and cargo kani exits 1. Each patch's opening lines name the check it expects to fail.
Using it
The project has not published this crate, and publishing is on hold. No release tag exists yet, so
there is no tag to name; the tag is pending. Depend on it by git, pinned to a commit of this repository's main
and never to a branch:
[dependencies]
entropy_contract = { git = "https://github.com/nifeos/entropy_contract", rev = "<full commit hash>" }
Once a pre-release tag exists, use tag = "<that tag>" in place of rev.
The service holds the random-number device. A client holds an endpoint that names no device, sends a request word naming a byte count, and gets the bytes back in the reply words. The service transforms no byte on the way, so the claim stays "these are the device's bytes".
BUGS
- A client cannot tell an unknown operation from a dry source: both are answered
NO_ENTROPY, and the reply has no room for a third answer. readinessreads an all-zero first draw as a dead device: wrong with probability 2^-64 to 2^-2048 by source, and the safe way round. It reads a first draw of eight or more equal bytes the same way: wrong with probability at most 255 in 2^64 for eight bytes from a uniform source. It does not judge a shorter draw for repeats.- Continuous health testing of the source is not part of this contract and is a decision the project still has to make. The checks are bring-up only.
- No request carries
VERSION, and the service answers no query for the versions it serves, so a client built against another version is not refused at bind.
Minimum Rust version
Rust 1.88. To check it, install the toolchain and its bare-metal targets, then run the tests and
all three bare-metal builds with +1.88:
rustup toolchain install 1.88 --profile minimal
rustup target add --toolchain 1.88 x86_64-unknown-none aarch64-unknown-none-softfloat riscv64imac-unknown-none-elf
cargo +1.88 test
cargo +1.88 build --lib --target x86_64-unknown-none
cargo +1.88 build --lib --target aarch64-unknown-none-softfloat
cargo +1.88 build --lib --target riscv64imac-unknown-none-elf
License
Licensed under either of MIT (LICENSE-MIT) or Apache-2.0 (LICENSE-APACHE), at your option.