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

From the Inside

EP. 02 · 30 MIN SEASON 1 · ARC 1 · THE LOG
21:47, the ledger lies
21:47

9:47 p.m. The tea is hot, this time. It’s about the only thing going right in this room.

On my screen, the ledger shows four lines. That’s the right count. Zero, one, two, three: the numbers follow one another, that’s the right order. The second line says that line 4812 is identical on the server and on the backup. Nothing to see, move along.

The second line is lying. My ledger, the one I built last night precisely so that this would be impossible, has just been rewritten. Not deleted. Not truncated. Rewritten: impeccable numbering, zero scars, the aplomb of a stamped report. Exactly what was done to line 4812.

I know who did it. He has my fingerprints, my keyboard and my cup of tea. It took him one line of code.

Let me tell you how I ended up breaking into my own place. It starts this morning, in the kitchen, with a question from Émilie.

Act I “Did you try?”

Three hours of sleep, barely. When I came down, Émilie was already up; she’s always up before me, it’s one of the stable mysteries of this house. Coffee in hand, back against the countertop, she watched me walk in with the look of someone who has already read the incident report.

“Almost four in the morning, last night. So, what is it?”

I told her everything. Line 4812, the two clean versions, the report signed too fast. Then the ledger: you deposit at the end, you never take anything back, the numbers are the authority. Émilie is a developer, and a better one than me on half the subjects; which works out well, it’s the half I’m missing. She listens to a story the way she reads code: without interrupting, eyes compiling as she goes.

“So, a ledger nobody can rewrite.”

“Nobody.”

She took a sip, long enough to choose between leaving me my night of pride and waking me up for good. I’ve lived with her long enough to know how that kind of suspense ends.

“Did you try?”

“Try what?”

“To make it lie. You spent the night building a vault, you checked that it accepts honest deposits: your two traps, fine. Not for one second did you play the thief.”

“The field is private. There’s only append…”

She raised a hand, not to stop me: to lay down the principle. When Émilie lays down a principle, you take notes.

“A defense nobody has ever attacked isn’t called a defense. It’s called a hypothesis.”

I carried the question to the office like a pebble in my shoe. At 11 a.m., the crisis team officially closed the incident: no further action, congratulations all around, pastries. I smiled, I signed the attendance sheet, and I asked for a copy of the two exports of the authentication file. For my archives. They granted it the way you hand a toy to the well-behaved kid at the back of the room.

What I did with them I’ll show you later, each thing at its place in line. First, tonight, Émilie’s question. It deserves an honest answer, and an honest answer isn’t something you declare: it’s something you run.

The house is silent, the terminal is open. Taking stock: I run yesterday’s code again, without touching a thing.

nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     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
[0003] 3:40 by the microwave. the ledger holds. going to bed.

Cargo didn’t even recompile: nothing has changed since yesterday, and it knows that better than I do. Four lines, same as when we parted. The fourth one you know: the 3:40 a.m. one, mine and yours, since you wrote it with me, to the letter. Our two ledgers are identical to the byte, and that’s no detail: remember it, it’s going to become an instrument. If you didn’t deposit it last night, catch up now: open evidence/night-01.log, add it exactly as it stands (3:40 by the microwave. the ledger holds. going to bed.) and run again. The evening counts from that line on.

Now, the question. “Did you try to make it lie?”

The spec of the crime, I know by heart. It’s the spec of line 4812: replace one fact with another, without touching the numbering, without leaving a scar. If my ledger is what I think it is, that code is impossible to write. I write it anyway. Do it with me, on yours. I know, it stings. That’s the point.

The attack: one line
src/main.rs
    let mut ledger = Ledger::empty();
    for fact in facts.lines() {
        ledger.append(fact);
    }

    // If my ledger can lie, I'd rather hear it from my own keyboard.
    // The same gesture someone used on line 4812.
    ledger.events[1].what = String::from("line 4812 matches the backup — nothing to see");

Between the loading loop and the printing. Three lines in the editor: two of comment, because even my crimes keep a file, and just one that acts. It grabs deposit number one and replaces the fact with its opposite. If all goes well, the compiler will laugh in my face, the way it did twice yesterday.

I run it.

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.57s
     Running `target/debug/blackledger`
[0000] incident report received — status: "contained"
[0001] line 4812 matches the backup — nothing to see
[0002] opened my own ledger — no one rewrites this one
[0003] 3:40 by the microwave. the ledger holds. going to bed.
21:47

9:47 p.m. Here we are: this is the screen I opened the evening with.

It compiles. Not a warning, not a hesitation. The program loads the pieces, numbers them, then my line walks around behind the counter, opens the ledger with bare hands and rewrites deposit number one. The output comes out impeccable: four lines, zero scars. My ledger has just said, with all the authority of its neatly ordered numbers, that the night of the hack never happened.

Yesterday, switching off the screen, I thought this ledger looked tamper-proof. Looked. That was the whole problem, and last night’s “almost” has just caught up with me.

Ten seconds of wounded pride. I take them, they’re earned. Yesterday I wrote it in black and white: Private on purpose: the Vec is the paper, append() is the only pen. I meant it as I wrote it, and it was true. In my head. The trouble is that the compiler never promised anything of the kind. The proof: it has just watched my line touch the paper without a pen, and it didn’t say a word. The same compiler that refuses me a badly dressed println! found nothing to object to in a forgery.

Private. Private from whom?

Act II Walls, not promises

The sting has passed. What’s left is the flaw, and flaws are my trade: you find them, you fix them. This one isn’t in the language. It’s in the idea I had of the language. The real rule, once you see it, is going to give me exactly what I was missing: a wall.

In Rust, “private” isn’t a lock fitted on a field. It’s a border rule: a private field is invisible from other modules. Read that again, slowly. The important word isn’t “private.” It’s “other.”

A module is a room in the building of a program. Inside a room, everyone sees everything: private hides nothing from those who are already in; the border only works between rooms. Last night I built everything (the clerk’s office, the counter and me) in one and the same room: main.rs. My counter is planted in the middle of the clerk’s office floor. The posted rules say “deposit at the counter,” and everyone in the room has an arm long enough to grab the ledger directly. My attack line forced nothing: it was at home.

My guardrail wasn’t broken. It never existed. “Only append writes” was true in my head and nowhere else: exactly the trust everyone placed in the server logs the day before yesterday. The same mistake twice in two days, one of them mine. I prefer mine: mine, I can fix.

The fix is three letters long: mod. It’s the keyword that draws a border. Note this well: the wall is the module, not the file. You can raise a border right in the middle of a single file if you insist. But a wall deserves its own room, and a room, in Rust, is naturally a file.

The ledger is moving out. Create src/ledger.rs, then cut out of main.rs everything that has to do with the ledger: Event, Ledger, the whole impl. Cut, not copy: those lines must exist in one place only. Paste them into the new room. Here’s the result. Look closely, it isn’t all pasting: a few pub have appeared, and each one is a decision.

The clerk’s office gets its own room
src/ledger.rs
// The ledger's own room: "private" only counts between rooms.
// Walls first, promises second.

#[derive(Debug)]
pub struct Event {
    // Open doors: the world may READ a fact and its place in line.
    // Reading never rewrote anything.
    pub seq: u64,
    pub what: String,
}

// A ledger knows one gesture: append. No edit, no delete.
pub struct Ledger {
    // No pub: the Vec is the paper, append() is the only pen.
    events: Vec<Event>,
}

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

    // The ledger numbers the facts itself.
    pub 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.
    pub fn events(&self) -> impl Iterator<Item = &Event> {
        self.events.iter()
    }
}

Every pub is a door, and I opened them one by one, asking myself the same question each time: does the outside world need this?

pub struct Event, pub seq, pub what: yes, the world has the right to read a fact and its number. Reading never rewrote anything. pub fn empty, append, events: the counter, the three official gestures of the house. The Vec? Look at it. No pub. It’s the door that doesn’t exist. The whole episode comes down to that absence. From outside this room, the ledger’s paper is out of reach, and the pen of append is the only object that crosses the counter.

That leaves declaring the room on the main.rs side. At the very top of the file, in place of the lines you cut out:

The door: mod and use
src/main.rs
mod ledger;

use ledger::Ledger;

mod ledger; tells the building there’s a room named ledger; the compiler goes looking for it in src/ledger.rs. use ledger::Ledger; saves me writing out the full path on every visit. Keep the blank line that already separated the ledger from main: our two files have to stay identical down to the line number, you’ll see why in ten seconds. Two lines at the top, and main.rs is no longer the clerk’s office floor: it’s the lobby.

I left one thing in place on purpose: the attack. Still there, between the loading and the printing. It’s the judge. If my wall is worth anything, that line must no longer have the right to exist.

nika@home · zsh
nika@home:~/lab/blackledger$ cargo run
   Compiling blackledger v0.1.0 (/home/nika/lab/blackledger)
error[E0616]: field `events` of struct `Ledger` is private
  --> src/main.rs:17:12
   |
17 |     ledger.events[1].what = String::from("line 4812 matches the backup — nothing to see");
   |            ^^^^^^ private field

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

Refused. E0616: field events of struct Ledger is private. Two words of diagnosis, private field, and no suggestion this time, no “consider adding.” The compiler holds out a hand to the absent-minded, not to burglars.

Third refusal in two days. The first taught me to decorate a struct, the second not to keep a copy lying around. This one is of a different kind: this one, I ordered. Line 17, my attack, the one that sailed straight through twenty minutes ago, died at compile time. Yesterday, “only append writes” was a sentence in my head. Tonight it’s a rule the machine enforces for me, whether I think of it or not, whether I’m lucid or not, at two in the morning the same as at noon.

I delete the three lines of the attack. It did its job: it showed me the hole, then it showed me the wall.

Note the idea in passing, because it’s going to serve us for the whole investigation: there are traps you set and traps that are part of the walls. My two tests from yesterday, I have to remember to run: a gesture I choose to make, cargo test. The module border stands guard at every compile, uninvited. The best defenses are the ones that don’t depend on my memory.

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.10s
     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
[0003] 3:40 by the microwave. the ledger holds. going to bed.

The truth is back. It had never left, in fact: my attack rewrote the ledger in memory, not the case file. night-01.log hasn’t moved by a byte. That’s luck, and it should make you think rather than reassure me: at my place, tonight, the working copy lied and the original held. The night of the hack, it was the original that lied. Everything depends on where you write from. Remember that sentence, we’re not done with it.

The traps, now. They stayed in main.rs, watching the clerk’s office from the lobby. It works (they only go through the counter, like everyone else), but their place is in the room they guard: the day the clerk’s office moves again, I want its guards to leave with it. Cut the two tests out of main.rs and put them at the bottom of ledger.rs, in a back room of their own.

The traps move in
src/ledger.rs traps
// The traps sleep inside the vault they guard. A child module
// sees what its parent keeps private; the outside world never does.
#[cfg(test)]
mod tests {
    use super::*;

    // 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]);
    }

    // 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);
    }
}

The tests themselves haven’t changed by a comma; only their address has. Two new details, only two. #[cfg(test)]: this back room exists only during tests, cargo builds it for cargo test and takes it down for the binary. use super::*;, next: the traps see everything the room contains, private included. A child module sees its parent; the outside world doesn’t. The guards sleep in the vault.

Last night I hadn’t done this tidying, and it wasn’t a beginner’s oversight: in a single room, one more drawer wouldn’t have partitioned anything at all. Tonight there are walls, so tidying means something.

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 ledger::tests::append_leaves_the_past_untouched ... ok
test ledger::tests::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 greens. Look at the names, ledger::tests::…: every trap has an address now, the room, the back room, the name.

Above all, measure what has just happened on the scale of the evening. The two tests were green before the move; they’re green after. The walls moved, not the facts. That’s the exact definition of a refactor, and it’s the only proof worth having. Not “I was careful.” Not “it’s the same code, promise.” Two traps, set yesterday by a distrustful man, snapping green tonight in a rearranged house.

I lean back in the chair, and the day falls into place all at once, like a card being flipped over.

My attack tonight and line 4812: the same gesture, down to the detail. A clean write, numbering intact, coming from a place the system considered home. Tonight, at my place, that place was called main.rs: same room, no wall to breach. The night of the hack, the place line 4812 was rewritten from, I don’t yet know what it’s called. But I now know one thing about the hand that wrote: it didn’t break in. No alarm went off, no guardrail protested. Same as at my place. It was writing from inside the trust.

That thought opens a door I close again at once, because it’s past eleven at night and you don’t open a door like that without pieces to back it up: where I work, who lives in the same room as the logs?

Act III Counting bytes

The pieces, as it happens. I told you I’d left the meeting with the two exports, the server and the backup. At noon, between two corridors, I did what you do when you no longer believe contents: I laid the two versions of line 4812 side by side, and I counted. Not read: counted. The server’s version is exactly the same number of bytes as the backup’s.

Think with me, one last time for tonight. When you replace a line in the middle of a file, the lengths never come out even. One word more, one letter less, and everything after it shifts. A shift shows, a shift can be measured, a shift screams in the first diff tool that comes along. For a replacement to shift nothing, the lie has to be cut to the exact size of the truth. Byte by byte. Chance doesn’t count bytes. Neither does corruption: when a disk damages a file, it doesn’t stitch things up neatly behind itself. Someone did the cutting.

Noon, in an office corridor. Nika, standing in profile against a large window, bent over his laptop, which sits on the sill; his index finger points at the screen, where a few pale lines follow one another, as if to count them. A paper cup of coffee on the sill; at the end of the corridor, two blurred figures walk away.
SHOT 01 · NOON, BETWEEN TWO CORRIDORS: TWO VERSIONS OF THE SAME LINE, THE SAME NUMBER OF BYTES.

I wrote down the day’s facts as the hours went by, like last night. That’s how you keep a ledger: you deposit the moment you know. It’s the piece night-02.log, the second in the case file. Get it and put it in evidence/, next to the first.

EXHIBIT No. 02 night-02.log download today’s piece, to put in evidence/, next to the first
nika@home · zsh
nika@home:~/lab/blackledger$ ls evidence/
night-01.log
night-02.log

That leaves teaching the program that a case file can hold several pieces. main gets rewritten one last time, and look how it has melted away: it loads, it pours, it prints. A lobby, nothing more. The two files in order: the night first, the day after, the order in which I learned things.

Two pieces in the ledger
src/main.rs
mod ledger;

use ledger::Ledger;

fn main() {
    let mut ledger = Ledger::empty();

    // Two pieces now: the night I stopped trusting,
    // and the day I started counting bytes.
    for file in ["evidence/night-01.log", "evidence/night-02.log"] {
        // I don't retype evidence — I load it. Retyping is how errors are born.
        let facts = std::fs::read_to_string(file).expect("no evidence/");
        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

Eight lines: the fourth is yours

I run it. You too. Eight lines expected, the same on your machine, down to the last character.

$ 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.09s
     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
[0003] 3:40 by the microwave. the ledger holds. going to bed.
[0004] crisis team closed the case — "no further action"
[0005] compared both versions of line 4812, byte by byte
[0006] the rewrite is the exact same length as the original
[0007] chance doesn't count bytes. this was deliberate.

The night, then the day. The report, the anomaly, the decision, your testimony, and the day piling on top without touching anything, the way the house wants it.

Then the last line. I deposited it at 4:12 p.m., in an open-plan office that was already talking about something else, and it didn’t change on its way into the ledger: this was deliberate. Deliberate. Not a failure, not corruption, not an industrial accident. A hand, a gesture, an intention. Someone manufactured a made-to-measure truth, and that word is finally deposited somewhere it won’t move again.

Evidence tape. The two traps, one last time, from their new address.

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.09s
     Running unittests src/main.rs (target/debug/deps/blackledger-fe1612eee9b43bdb)

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

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

It’s almost midnight when Émilie comes in, two cups in hand, tea for me: she has given up on converting me to sleep. She sets mine down near the keyboard and reads the screen over my shoulder, in silence, from the last line to the first.

“Did you try to make it lie?”

“Yes. I won in one line. So I built a wall, and I lost again. Cleanly, this time.”

“Show me.”

I hand her the keyboard. She reopens main.rs and types an attack of her own: the same idea, in her own hand. The compiler refuses it before she has finished her sip. She nods, as a professional checking, not as a partner being kind. Then her eyes travel up to the last line of the ledger, and her smile goes out without a sound.

“Deliberate.”

“Deliberate.”

“Then it’ll be back.”

She says it calmly, the way you deposit a fact in the ledger. She hands the keyboard back and keeps her cup between her hands.

“Finish your tea, and build fast.”

Deliberate. Someone counted the bytes so that the lie would be exactly the size of the truth. Nobody cuts a lie to the byte in order to vanish afterward; that’s what you do when you plan on coming back.

So I’m counting too, now. Every fact, every deposit, every number. The night the hand comes back, my ledger will be able to say what existed first.

It’s that hand against me. It doesn’t know that yet.

Next episode
Episode 03 · Arc 1 · The Log

The Fingerprint

Episode 3: The hand that counts bytes will be back. The ledger has to learn to prove.

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.