Skip to the text
Blackledger
A noir series in Rust
Episode 01

Line 4812

EP. 01 · 30 MIN SEASON 1 · ARC 1 · THE LOG
02:14, the night after
02:14

2:14 a.m. Or so says the clock at the top of the screen. I stopped believing clocks yesterday.

The tea went cold without my touching it. On the left screen, the crisis team’s report, twelve pages, signed, stamped: “incident contained.” The intrusion dates from last night, 3:07 a.m.: that’s what the logs say, and everyone has decided the logs are telling the truth. Yesterday morning’s meeting lasted twenty minutes. The word “contained” was said too fast, by too many people, with too much relief.

On the right screen, I have something else. Two extracts of the same authentication file. One comes from the server. The other from the previous day’s backup. They should be identical down to the last byte: same file, same night, same machine.

At line 4812, they stop telling the same story.

Not deleted. Not truncated. Rewritten. Two clean, plausible versions, each with its own impeccable timestamp. Someone manufactured a truth, dated it, and filed it right where it belonged. My tools, twelve years of tools, can’t tell me which of the two versions existed first.

I’m warning you now, because we’re spending the night together, you and I: I’m not going to sleep. If I can’t trust other people’s notes anymore, I’ll keep my own. In a tool I understand down to the last byte, because I’ll have written it.

Act I I’m done trusting other people’s notes

My boxing jacket is still on the chair, where I dropped it when I came in. The body wanted to hit something tonight; the head won. I open a terminal.

A ledger. That’s the word that has been circling in my head since the meeting. Not a log file. A ledger, like in a courthouse clerk’s office: things get deposited, nothing gets taken back. A black ledger, for a night just as black. I run the two words together, blackledger, and it’s christened before I even know what it will hold.

nika@home · zsh
nika@home:~/lab$ cargo new blackledger
    Creating binary (application) `blackledger` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
nika@home:~/lab$ cd blackledger
nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s
     Running `target/debug/blackledger`
Hello, world!

“Hello, world!” The most honest program I’ve read all day: it says exactly what it does.

Before I write anything, one question, the only one that matters tonight: what is a note that can’t betray me?

Line 4812 gave me the answer in negative. A line of text in a file can be rewritten: I’ve just seen the proof, in two copies. A timestamp can be forged: I have two of them, perfectly plausible, contradicting each other. What’s left once you take away the free text and the clock? A fact, and its place in line. What happened, and in what position I learned it.

I start by giving that a shape. An event: a sequence number, a fact.

The shape of a fact
src/main.rs
// A fact has a place in line, not a date. Both versions of line 4812
// carry perfectly plausible timestamps. Clocks lie — I learned that tonight.
struct Event {
    // Position in the ledger. Not "when it happened" — "when I wrote it down".
    // The order of writing is the one thing no clock can rewrite.
    seq: u64,
    what: String,
}

fn main() {
    let event = Event {
        seq: 0,
        what: String::from("a test note — checking the shape of a fact"),
    };
    println!("{event:?}");
}

A trial note, nothing more. I check the shape before pouring anything real into it. I run it.

nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
error[E0277]: `Event` doesn't implement `Debug`
  --> src/main.rs:15:15
   |
15 |     println!("{event:?}");
   |               ^^^^^^^^^ `Event` cannot be formatted using `{:?}` because it doesn't implement `Debug`
   |
   = help: the trait `Debug` is not implemented for `Event`
   = note: add `#[derive(Debug)]` to `Event` or manually `impl Debug for Event`
help: consider annotating `Event` with `#[derive(Debug)]`
   |
 3 + #[derive(Debug)]
 4 | struct Event {
   |

For more information about this error, try `rustc --explain E0277`.
error: could not compile `blackledger` (bin "blackledger") due to 1 previous error

Refused. I asked the compiler to print my event in debug mode (that’s the {event:?}) without telling it how. It doesn’t guess, it doesn’t assume, it doesn’t improvise: it refuses, and it hands me the fix, right down to the line to copy. #[derive(Debug)] above the struct.

I spent the day with people who guessed, assumed and improvised. This refusal does me a world of good.

The derive, granted
src/main.rs new lines
// A fact has a place in line, not a date. Both versions of line 4812
// carry perfectly plausible timestamps. Clocks lie — I learned that tonight.
#[derive(Debug)]
struct Event {
    // Position in the ledger. Not "when it happened" — "when I wrote it down".
    // The order of writing is the one thing no clock can rewrite.
    seq: u64,
    what: String,
}
nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
warning: fields `seq` and `what` are never read
 --> src/main.rs:7:5
  |
4 | struct Event {
  |        ----- fields in this struct
...
7 |     seq: u64,
  |     ^^^
8 |     what: String,
  |     ^^^^
  |
  = note: `Event` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: `blackledger` (bin "blackledger") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
     Running `target/debug/blackledger`
Event { seq: 0, what: "a test note — checking the shape of a fact" }

My first event prints. Just above it, the compiler is still grumbling: fields are never read. I’m writing fields I never read. It has a point. Writing facts down and never reading them back is exactly what the system on the other side was doing. Patience, the reading is coming.

An event, I know how to write. Now I need the place where it becomes untouchable.

Night, in a small home office, seen in profile. Nika, thin-rimmed glasses, a few days’ stubble, dark tousled hair, in navy pajamas with white piping, sleeves pushed up, types on his laptop, open on a dark terminal. To the left, a second screen glowing, a desk lamp bent low. On the desk, a glass cup of tea and sheets of paper marked with a red stamp. Behind him, a dark jacket thrown over a chair, and a closed door edged with a thread of warm light.
SHOT 01 · 2:31 A.M. A NEARLY EMPTY PROJECT ON THE SCREEN.
Act II A place that only knows how to append

Think with me. Where do I put my events? The reflex is a Vec: a list, and you stack. But a Vec left out in the open is something anyone can write into. Any line of code can replace element 3, cut off the end, reorder the whole thing. A bare Vec is a log file: a self-service crime scene.

What I want is a clerk’s office. You walk up, you deposit, you leave. Nobody comes back around the counter to correct yesterday’s deposits, not even me. Especially not me: at 2 a.m., I’m the number one threat to my own notes.

In Rust, that takes two gestures. The first: hide the Vec, a private field, nobody touches it directly. The second, more important: offer the outside world nothing but operations whose signatures promise the right behavior. One method to deposit. One method to read, which hands back immutable references and nothing else: a look, never a pen.

The clerk’s office: Ledger
src/main.rs
// A ledger knows one gesture: append. No edit, no delete.
struct Ledger {
    // Private on purpose: the Vec is the paper, append() is the only pen.
    events: Vec<Event>,
}

impl Ledger {
    fn empty() -> Ledger {
        // Every investigation starts the same way: an empty page.
        Ledger { events: Vec::new() }
    }

    // The ledger numbers the facts itself.
    fn append(&mut self, what: impl Into<String>) -> u64 {
        let seq = self.events.len() as u64;
        self.events.push(Event {
            seq,
            what: what.into(),
        });
        seq
    }

    // Read everything, touch nothing. The signature IS the promise:
    // &Event means look — not rewrite.
    fn events(&self) -> impl Iterator<Item = &Event> {
        self.events.iter()
    }
}

Look at the signatures, they say it all. append takes &mut self: depositing changes the ledger, openly, and it’s the only gesture that does. The sequence number is the ledger’s choice: len() keeps the count, the next deposit takes the next number, no gap possible. events(), for its part, hands back an iterator of &Event: read-only references. You can look at everything, you can touch nothing. That’s what the signatures promise, and tonight that’s enough for me.

The small luxury along the way: impl Into<String> in append, so I can deposit a &str or a String alike, no ceremony. I’m typing fast tonight.

I try out my clerk’s office. Two trial deposits, and I keep the last one under my eyes while I go on writing, the way you keep a sticky note on the edge of the screen.

The sticky note on the edge of the screen
src/main.rs
fn main() {
    let mut ledger = Ledger::empty();
    ledger.append("first deposit — a test note, nothing more");

    // I keep the last deposit under my eyes while I write the next one.
    let last = ledger.events().last();
    ledger.append("second deposit — still just testing");
    println!("{last:?}");
}
nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
error[E0502]: cannot borrow `ledger` as mutable because it is also borrowed as immutable
  --> src/main.rs:46:5
   |
45 |     let last = ledger.events().last();
   |                ------ immutable borrow occurs here
46 |     ledger.append("second deposit — still just testing");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
47 |     println!("{last:?}");
   |                ---- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `blackledger` (bin "blackledger") due to 1 previous error

Refused, again. This time it isn’t an oversight on my part, it’s a disagreement on substance. The borrow checker has just told me: you can’t hold a reading of the ledger and modify it at the same time. My sticky note, my reference to the last deposit, is a photograph of the ledger at a given instant, and I was about to write over that instant.

Take a second to savor this, because it’s the first time it has happened to me all night: someone is more paranoid than I am. This language refuses to take anyone’s word. It doesn’t ask whether my reference will probably still be valid: it demands that it be provable, or it won’t compile.

It’s right, and I even know the forensic version of its rule: you don’t work from a copy that’s been lying around. When I want the truth, I go back to the ledger.

Write first, read after
src/main.rs new lines
fn main() {
    let mut ledger = Ledger::empty();
    ledger.append("first deposit — a test note, nothing more");
    ledger.append("second deposit — still just testing");

    // Write first, read after. A forensic reflex, enforced by a compiler:
    // no working copies — when I want the truth, I go back to the ledger.
    if let Some(last) = ledger.events().last() {
        println!("{last:?}");
    }
}
nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
warning: fields `seq` and `what` are never read
 --> src/main.rs:7:5
  |
4 | struct Event {
  |        ----- fields in this struct
...
7 |     seq: u64,
  |     ^^^
8 |     what: String,
  |     ^^^^
  |
  = note: `Event` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: `blackledger` (bin "blackledger") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/blackledger`
Event { seq: 1, what: "second deposit — still just testing" }

The phone lights up on the desk. “Coming to bed?”

I glance at the time in the terminal bar, out of reflex, then I answer with what’s true: “Not yet. I think I’ve found something.” Three dots, for a while. “I know. Don’t let it win.” She’s a developer, she knows exactly what state you’re in when you’re writing code at this hour, and she knows there’s no point insisting. The bedroom light goes out under the door.

Don’t let it win. Exactly. My clerk’s office looks correct. It’s precisely when my code looks correct that I stop trusting myself: “looks correct,” past a certain hour, is the first symptom of the error. So I do what I always do in this state: I set a trap for myself. That’s what a test is. A trap set for my own code, written while I’m still lucid, that will snap later without asking my opinion.

First trap: the sequence numbers. Three deposits, three numbers, zero gaps, and the order you read in is the order it was written in.

First trap: the numbers don’t lie
src/main.rs traps
// Three deposits, three numbers, no gaps.
// A ledger that skips is a ledger that hides.
#[test]
fn appended_events_get_next_seqs() {
    let mut ledger = Ledger::empty();
    ledger.append("first");
    ledger.append("second");
    ledger.append("third");

    let seqs: Vec<u64> = ledger.events().map(|event| event.seq).collect();
    assert_eq!(seqs, vec![0, 1, 2]);
}
nika@home · zsh
nika@home:~/lab/blackledger$ cargo test
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
warning: field `what` is never read
 --> src/main.rs:8:5
  |
4 | struct Event {
  |        ----- field in this struct
...
8 |     what: String,
  |     ^^^^
  |
  = note: `Event` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: `blackledger` (bin "blackledger" test) generated 1 warning
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.11s
     Running unittests src/main.rs (target/debug/deps/blackledger-fe1612eee9b43bdb)

running 1 test
test appended_events_get_next_seqs ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Green. A detail I like: the compiler now grumbles only about what. The test has just read seq, so the complaint about seq went quiet. This language keeps accounts of what gets read and what doesn’t. We’re going to get along.

I lean back in the chair, and line 4812 comes back. It always comes back when I close my eyes. Two versions of the same file. I replay the scene from the attacker’s side: someone opened the log, replaced a line, adjusted the timestamp, closed it again. Clean. No system flinched, because no system considered that write abnormal. Overwriting a line was an expected operation.

Now, what if the system on the other side had kept a ledger like mine? Rewriting line 4812 wouldn’t have been “modify element 4812”: the operation doesn’t exist. A new version would have had to be deposited on top, with a new sequence number, in full view of everyone. The forgery would have become a confession. A scar in the numbering.

That’s what I’m building, at three in the morning, in pajamas in my office: a place where lying leaves marks.

Second trap, straight after, because this is THE trap, the one that guards the thesis of this whole night: depositing doesn’t overwrite the past. I photograph the ledger, I pile a deposit on top, and I check that nothing moved underneath.

Second trap: the past doesn’t move
src/main.rs traps
// I photograph the past, pile the present on top,
// and check that nothing moved.
#[test]
fn append_leaves_the_past_untouched() {
    let mut ledger = Ledger::empty();
    ledger.append("the fact I must protect");

    let before: Vec<String> = ledger.events().map(|event| event.what.clone()).collect();
    ledger.append("a newer fact, piling on top");
    let after: Vec<String> = ledger
        .events()
        .take(1)
        .map(|event| event.what.clone())
        .collect();

    assert_eq!(before, after);
}
nika@home · zsh
nika@home:~/lab/blackledger$ cargo test
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.11s
     Running unittests src/main.rs (target/debug/deps/blackledger-fe1612eee9b43bdb)

running 2 tests
test append_leaves_the_past_untouched ... ok
test appended_events_get_next_seqs ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Two traps, two greens. The grumbling about what has gone quiet too, everything gets read, the compiler has nothing left to hold against me. The trade has a name for what I’ve just built: append-only. You write at the end, never inside. Me, tonight, I call it a clerk’s office.

Act III First deposit

Time to stop with the trial notes.

Since early evening I’ve had a file open in a corner: my running notes of the night. The facts, written down by hand as the hours went by, in the order I learned them. It’s the piece night-01.log of the case file, the one you picked up with the foreword. Put the evidence/ folder at the root of the project, next to Cargo.toml; mine is already there. Three lines for now. Three lines that sum up why I’m not sleeping.

I’m not going to retype them into the code. You don’t retype evidence: retyping is how errors are born, and a typo in a ledger is one more truth that never existed. Evidence gets loaded. The file comes in, each line becomes a deposit, the ledger numbers them.

While we’re at it, we bury the {event:?}. A ledger doesn’t read in debug dumps, it reads in columns.

nika@home · zsh
nika@home:~/lab/blackledger$ ls evidence/
night-01.log
The first deposit
src/main.rs
fn main() {
    // The facts of the night, exactly as I collected them.
    // I don't retype evidence — I load it. Retyping is how errors are born.
    let facts = std::fs::read_to_string("evidence/night-01.log").expect("no evidence/");

    let mut ledger = Ledger::empty();
    for fact in facts.lines() {
        ledger.append(fact);
    }

    // A ledger reads in columns, not in debug dumps.
    for event in ledger.events() {
        println!("[{:04}] {}", event.seq, event.what);
    }
}
The moment of truth

Our two screens have to say the same thing

There. One type, one clerk’s office, two traps, one load. It isn’t much, and it’s exactly enough.

I run it. You too: for the first time tonight, our two screens have to say the same thing.

$ cargo run
My terminal, to compare with yours
nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s
     Running `target/debug/blackledger`
[0000] incident report received — status: "contained"
[0001] line 4812 differs between server and backup
[0002] opened my own ledger — no one rewrites this one

Three lines in columns. The report, the anomaly, the decision. The whole night fits in there, numbered by a tool that doesn’t know how to lie, because it doesn’t know how to do anything but append.

All of this lives in memory, and I know it: if my machine goes dark, the ledger goes dark with it. Tonight I don’t care: I want to understand. Survival can wait until it’s a problem.

Evidence tape, before closing up. Both traps have to snap green one last time: they’re the ones who’ll stand guard once my back is turned.

nika@home · zsh
nika@home:~/lab/blackledger$ cargo test
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.12s
     Running unittests src/main.rs (target/debug/deps/blackledger-fe1612eee9b43bdb)

running 2 tests
test appended_events_get_next_seqs ... ok
test append_leaves_the_past_untouched ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

I go downstairs to rinse the cup. The cold tea I finish standing at the sink: it’s foul, I finish it anyway. Above the countertop, the microwave reads 3:40. I go back up with the time in my head.

One last thing, before you shut down. Open evidence/night-01.log and add a line, mine, to the letter, final period included:

3:40 by the microwave. the ledger holds. going to bed.

Three forty by the kitchen microwave. I know what we said about clocks, and I’m signing it all the same: a fact, its place in line. It’s surely not 3:40 a.m. where you are; write it exactly as it stands. This file isn’t your diary: it’s a piece of the case file, and a case file doesn’t tell the evening of whoever happens to be reading it. Starting tomorrow, your screen and mine will have to say the same bytes, all of them, down to the last. You’ll see why. You’ll see that it’s a weapon. Run it again: [0003], the same line here and on your machine, at the same rank. This ledger isn’t mine anymore: it belongs to the two of us.

Four lines. A ledger nobody can rewrite.

That’s what I tell myself as I switch off the screen, and I’m almost right.

Almost.

Next episode
Episode 02 · Arc 1 · The Log

From the Inside

Episode 2: The ledger looks tamper-proof. “Looks” is the problem.

Blackledger · season 1 a noir series in Rust companion repository blackledger

Feedback?

Tell me what’s off.

A typo, a sentence that snags, an explanation that is missing: it goes straight to the author.

Number of the paragraph concerned, pre-filled with the one in front of you.

Your feedback leaves without your address.