tinystore-cli 0.11.0

The tinystore command: a store's directory served to other processes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! `tinystore serve` as its clients start it: frames written by hand, so that
//! the test speaks the protocol as an SDK does, not through the library.

use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};

use hmac::{Hmac, Mac};
use sha2::Sha256;
use tokio_rustls::rustls::pki_types::ServerName;
use tokio_rustls::rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned, crypto};

const BINARY: &str = env!("CARGO_BIN_EXE_tinystore");
const HELLO: u8 = 1;
const WELCOME: u8 = 2;
const REQUEST: u8 = 3;
const RESPONSE: u8 = 4;
const GOAWAY: u8 = 10;
const END: u8 = 1;
const ERROR: u8 = 2;
const ADMIN: &str = "4dGQ6tR2kq0SxVZpLWn8E1yHf7cJmB3aUoN9Tz5Ki0E";
const DATA: &str = "Yq8wHn2xLz5Rb7Tc0Vm3Kj6Fd9Gs1Ap4Ue8Wo2Ni5Qt";
const SERVER_STOP: u16 = 0x0001;

fn frame(kind: u8, flags: u8, method: u16, stream: u32, body: &[u8]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(12 + body.len());
    bytes.extend_from_slice(&u32::try_from(body.len()).unwrap().to_le_bytes());
    bytes.extend_from_slice(&[kind, flags]);
    bytes.extend_from_slice(&method.to_le_bytes());
    bytes.extend_from_slice(&stream.to_le_bytes());
    bytes.extend_from_slice(body);
    bytes
}

/// A HELLO of protocol 1, `{1: 1}`, with a challenge when given, `{6: bin}`.
fn hello(challenge: Option<&[u8; 16]>) -> Vec<u8> {
    let body = match challenge {
        None => vec![0x81, 0x01, 0x01],
        Some(challenge) => [&[0x82, 0x01, 0x01, 0x06, 0xc4, 0x10][..], challenge].concat(),
    };
    frame(HELLO, 0, 0, 0, &body)
}

/// A HELLO of protocol 1 with a token, `{1: 1, 3: str}`.
fn hello_with(token: &str) -> Vec<u8> {
    let body = [&[0x82, 0x01, 0x01, 0x03, 0xd9, u8::try_from(token.len()).unwrap()][..], token.as_bytes()].concat();
    frame(HELLO, 0, 0, 0, &body)
}

fn holds(body: &[u8], text: &str) -> bool {
    body.windows(text.len()).any(|window| window == text.as_bytes())
}

/// The next frame: its kind, flags, stream and body.
fn read_frame(reader: &mut impl Read) -> (u8, u8, u32, Vec<u8>) {
    try_frame(reader).unwrap()
}

/// The next frame, or what ended the stream before it.
fn try_frame(reader: &mut impl Read) -> std::io::Result<(u8, u8, u32, Vec<u8>)> {
    let mut header = [0; 12];
    reader.read_exact(&mut header)?;
    let length = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
    let stream = u32::from_le_bytes(header[8..12].try_into().unwrap());
    let mut body = vec![0; length];
    reader.read_exact(&mut body)?;
    Ok((header[4], header[5], stream, body))
}

/// The next frame, a failure to read it showing what the server logged.
fn logged_frame(reader: &mut impl Read, log: &Path) -> (u8, u8, u32, Vec<u8>) {
    try_frame(reader).unwrap_or_else(|error| {
        panic!("{error}; the server logged: {}", std::fs::read_to_string(log).unwrap_or_default())
    })
}

fn wait(child: &mut Child) -> i32 {
    let deadline = Instant::now() + Duration::from_secs(15);
    loop {
        if let Some(status) = child.try_wait().unwrap() {
            return status.code().unwrap_or(-1);
        }
        assert!(Instant::now() < deadline, "the server did not exit");
        std::thread::sleep(Duration::from_millis(20));
    }
}

#[test]
fn a_server_started_with_a_durability_opens_its_store_with_it_and_says_so() {
    let dir = tempfile::tempdir().unwrap();
    let mut child = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(dir.path())
        .args(["--stdio", "--durability", "os"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(&hello(None)).unwrap();
    let (kind, _, _, welcome) = read_frame(child.stdout.as_mut().unwrap());
    assert_eq!(kind, WELCOME);
    // WELCOME's field 12, a str of two bytes
    assert!(
        welcome.windows(4).any(|window| window == [12, 0xa2, b'o', b's']),
        "the WELCOME names the store's durability"
    );
    drop(child.stdin.take());
    assert_eq!(wait(&mut child), 0);
}

// contract: WIRE-09
#[test]
fn a_private_child_answers_hello_and_leaves_when_its_stdin_ends() {
    let dir = tempfile::tempdir().unwrap();
    let mut child = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(dir.path())
        .arg("--stdio")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(&hello(None)).unwrap();
    let (kind, ..) = read_frame(child.stdout.as_mut().unwrap());
    assert_eq!(kind, WELCOME);
    drop(child.stdin.take());
    assert_eq!(wait(&mut child), 0, "the end of stdin asks it to leave");
}

/// A private child whose answer cannot be written, its parent's stdin open
/// and silent: it exits then, rather than at the parent's next bytes, and
/// its parent learns the connection is lost.
#[test]
fn a_private_child_whose_answer_cannot_be_written_exits_though_its_stdin_stays_open() {
    const PING: u8 = 8;
    let dir = tempfile::tempdir().unwrap();
    let mut child = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(dir.path())
        .arg("--stdio")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    stdin.write_all(&hello(None)).unwrap();
    let (kind, ..) = read_frame(child.stdout.as_mut().unwrap());
    assert_eq!(kind, WELCOME);
    // the parent stops reading: the PING's PONG has nowhere to go
    drop(child.stdout.take());
    stdin.write_all(&frame(PING, 0, 0, 0, &[7; 8])).unwrap();
    assert_eq!(wait(&mut child), 0, "the child left once its writer failed");
    drop(stdin);
}

#[test]
fn a_local_server_publishes_serve_proves_itself_stops_and_holds_its_directory_meanwhile() {
    let (dir, logs) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
    let log = logs.path().join("serve.log");
    let mut server = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(dir.path())
        .args(["--local", "--idle", "0ms", "--log-file"])
        .arg(&log)
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    let serve = published(&dir.path().join("server").join("SERVE"));
    assert_eq!(serve["protocol"], 1);
    assert_eq!(serve["sidecar"], true);

    let held =
        Command::new(BINARY).args(["serve", "--dir"]).arg(dir.path()).arg("--local").stderr(Stdio::null()).status();
    assert_eq!(held.unwrap().code(), Some(3), "a second server finds the directory held");

    let mut client = connect(serve["endpoints"][0].as_str().unwrap());
    let challenge = *b"0123456789abcdef";
    client.write_all(&hello(Some(&challenge))).unwrap();
    let (kind, _, _, welcome) = logged_frame(&mut client, &log);
    assert_eq!(kind, WELCOME);
    let secret = base64url(serve["secret"].as_str().unwrap());
    let mut mac = Hmac::<Sha256>::new_from_slice(&secret).unwrap();
    mac.update(&challenge);
    let proof = &welcome[welcome.len() - 35..];
    assert_eq!(&proof[..3], &[0x0b, 0xc4, 0x20], "the proof is WELCOME's last field, 32 bytes");
    assert_eq!(&proof[3..], &mac.finalize().into_bytes()[..]);

    client.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    let (kind, flags, stream, _) = logged_frame(&mut client, &log);
    assert_eq!((kind, flags & END, stream), (RESPONSE, END, 1));
    assert_eq!(wait(&mut server), 0);
    assert!(!dir.path().join("server").join("SERVE").exists(), "SERVE goes before the directory is let go");
}

/// A server on a directory's local endpoint and on `listen`, with an admin
/// token and a data token and the flags `more` names, and what `SERVE` says
/// of it.
fn remote(dir: &Path, listen: &str, tls: &[&Path], more: &[&str]) -> (Child, serde_json::Value) {
    let tokens = dir.join("tokens");
    std::fs::write(&tokens, format!("# who may connect\nadmin {ADMIN}\ndata  {DATA}\n")).unwrap();
    let mut command = Command::new(BINARY);
    command.arg("serve").arg(dir.join("store")).args(["--listen", listen, "--tokens"]).arg(&tokens);
    if let [cert, key] = tls {
        command.arg("--tls-cert").arg(cert).arg("--tls-key").arg(key);
    }
    command.args(more);
    let server = command.stderr(Stdio::null()).spawn().unwrap();
    let serve = published(&dir.join("store").join("server").join("SERVE"));
    (server, serve)
}

// contract: SEC-02
#[test]
fn a_remote_client_is_admitted_by_its_token_and_may_do_what_its_line_says() {
    let dir = tempfile::tempdir().unwrap();
    let (mut server, serve) = remote(dir.path(), "tcp://127.0.0.1:0", &[], &[]);
    let endpoint = serve["endpoints"][1].as_str().unwrap();
    let address = endpoint.strip_prefix("tcp://").unwrap();

    let mut stranger = std::net::TcpStream::connect(address).unwrap();
    stranger.write_all(&hello(None)).unwrap();
    let (kind, _, _, body) = read_frame(&mut stranger);
    assert!(kind == GOAWAY && holds(&body, "unauthenticated"), "no token");

    let mut data = std::net::TcpStream::connect(address).unwrap();
    data.write_all(&hello_with(DATA)).unwrap();
    let (kind, _, _, welcome) = read_frame(&mut data);
    assert!(kind == WELCOME && holds(&welcome, "data"));
    data.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    let (_, flags, _, refused) = read_frame(&mut data);
    assert!(flags & ERROR != 0 && holds(&refused, "permission"), "a data client cannot stop the server");

    let mut admin = std::net::TcpStream::connect(address).unwrap();
    admin.write_all(&hello_with(ADMIN)).unwrap();
    let (kind, _, _, welcome) = read_frame(&mut admin);
    assert!(kind == WELCOME && holds(&welcome, "admin"));
    admin.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    assert_eq!(read_frame(&mut admin).0, RESPONSE);
    assert_eq!(wait(&mut server), 0);
}

// contract: WIRE-12
#[test]
fn a_remote_connection_past_the_bound_is_turned_away_limit_and_a_local_one_is_not_counted() {
    let dir = tempfile::tempdir().unwrap();
    let (mut server, serve) = remote(dir.path(), "tcp://127.0.0.1:0", &[], &["--max-connections", "2"]);
    let address = serve["endpoints"][1].as_str().unwrap().strip_prefix("tcp://").unwrap().to_owned();
    let welcomed = |stream: &mut std::net::TcpStream| {
        stream.write_all(&hello_with(DATA)).unwrap();
        read_frame(stream)
    };
    let mut first = std::net::TcpStream::connect(&address).unwrap();
    assert_eq!(welcomed(&mut first).0, WELCOME);
    let mut second = std::net::TcpStream::connect(&address).unwrap();
    assert_eq!(welcomed(&mut second).0, WELCOME);

    let mut third = std::net::TcpStream::connect(&address).unwrap();
    let (kind, _, _, body) = welcomed(&mut third);
    assert!(kind == GOAWAY && holds(&body, "limit"), "past the bound: {}", String::from_utf8_lossy(&body));
    assert!(holds(&body, "2 connections at most"), "names the bound: {}", String::from_utf8_lossy(&body));
    let mut stranger = std::net::TcpStream::connect(&address).unwrap();
    stranger.write_all(&hello(None)).unwrap();
    let (kind, _, _, body) = read_frame(&mut stranger);
    assert!(kind == GOAWAY && holds(&body, "unauthenticated"), "a token is checked first");

    let mut local = connect(serve["endpoints"][0].as_str().unwrap());
    local.write_all(&hello(Some(b"0123456789abcdef"))).unwrap();
    assert_eq!(read_frame(&mut local).0, WELCOME, "this machine's clients are not counted");

    drop(first);
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let mut again = std::net::TcpStream::connect(&address).unwrap();
        if welcomed(&mut again).0 == WELCOME {
            break;
        }
        assert!(Instant::now() < deadline, "a place given back is taken again");
        std::thread::sleep(Duration::from_millis(20));
    }
    drop(second);
    local.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    assert_eq!(read_frame(&mut local).0, RESPONSE);
    assert_eq!(wait(&mut server), 0);
}

#[test]
fn a_tls_server_answers_over_its_certificate() {
    let dir = tempfile::tempdir().unwrap();
    let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
    let (cert, key) = (dir.path().join("cert.pem"), dir.path().join("key.pem"));
    std::fs::write(&cert, certified.cert.pem()).unwrap();
    std::fs::write(&key, certified.signing_key.serialize_pem()).unwrap();
    let (mut server, serve) = remote(dir.path(), "tls://127.0.0.1:0", &[&cert, &key], &[]);
    let endpoint = serve["endpoints"][1].as_str().unwrap();
    assert!(endpoint.starts_with("tls://127.0.0.1:"), "{endpoint}");

    let mut roots = RootCertStore::empty();
    roots.add(certified.cert.der().clone()).unwrap();
    let config = ClientConfig::builder_with_provider(Arc::new(crypto::ring::default_provider()))
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_root_certificates(roots)
        .with_no_client_auth();
    let tcp = std::net::TcpStream::connect(endpoint.strip_prefix("tls://").unwrap()).unwrap();
    let connection = ClientConnection::new(Arc::new(config), ServerName::try_from("localhost").unwrap()).unwrap();
    let mut tls = StreamOwned::new(connection, tcp);
    tls.write_all(&hello_with(ADMIN)).unwrap();
    assert_eq!(read_frame(&mut tls).0, WELCOME);
    tls.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    assert_eq!(read_frame(&mut tls).0, RESPONSE);
    assert_eq!(wait(&mut server), 0);
}

#[test]
fn a_connection_that_says_no_hello_ends_with_the_handshakes_time() {
    let dir = tempfile::tempdir().unwrap();
    let (mut server, serve) = remote(dir.path(), "tcp://127.0.0.1:0", &[], &[]);
    let address = serve["endpoints"][1].as_str().unwrap().strip_prefix("tcp://").unwrap().to_owned();
    let mut silent = std::net::TcpStream::connect(&address).unwrap();
    let began = Instant::now();
    let mut byte = [0];
    let read = silent.read(&mut byte);
    assert!(matches!(read, Ok(0) | Err(_)), "the server ended the connection: {read:?}");
    assert!(began.elapsed() < Duration::from_secs(10), "after {:?}", began.elapsed());

    let mut admin = std::net::TcpStream::connect(&address).unwrap();
    admin.write_all(&hello_with(ADMIN)).unwrap();
    assert_eq!(read_frame(&mut admin).0, WELCOME);
    admin.write_all(&frame(REQUEST, END, SERVER_STOP, 1, &[0x80])).unwrap();
    assert_eq!(read_frame(&mut admin).0, RESPONSE);
    assert_eq!(wait(&mut server), 0);
}

#[test]
fn a_mistake_in_the_tokens_leaves_no_files_behind() {
    let dir = tempfile::tempdir().unwrap();
    let tokens = dir.path().join("tokens");
    std::fs::write(&tokens, "admin short\n").unwrap();
    let store = dir.path().join("store");
    let status = Command::new(BINARY)
        .arg("serve")
        .arg(&store)
        .args(["--listen", "tcp://127.0.0.1:0", "--tokens"])
        .arg(&tokens)
        .stderr(Stdio::null())
        .status()
        .unwrap();
    assert_eq!(status.code(), Some(1));
    assert!(!store.exists(), "the store never opened");
}

// contract: ERR-02
#[test]
fn a_log_that_cannot_be_made_is_named_with_its_cause() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("data");
    std::fs::write(&file, "not a directory").unwrap();
    let log = file.join("server").join("serve.log");
    let failed = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(&file)
        .args(["--local", "--log-file"])
        .arg(&log)
        .output()
        .unwrap();
    let said = String::from_utf8_lossy(&failed.stderr);
    assert_eq!(failed.status.code(), Some(1), "{said}");
    let named = format!("tinystore serve: its log {}: ", log.display());
    assert!(said.starts_with(&named), "{said}");
}

/// A sidecar's starter reads its stderr while it starts, and lets it go once
/// it serves: a failure said after that goes nowhere, and the exit says it.
#[test]
fn a_server_whose_stderr_nobody_reads_still_exits_with_why_it_stopped() {
    let dir = tempfile::tempdir().unwrap();
    let mut holder = Command::new(BINARY);
    holder.arg("serve").arg(dir.path()).stdout(Stdio::null()).stderr(Stdio::null());
    let mut holder = Stopped(holder.spawn().unwrap());
    published(&dir.path().join("server").join("SERVE"));
    let mut held = Command::new(BINARY)
        .args(["serve", "--dir"])
        .arg(dir.path())
        .args(["--local", "--log-file"])
        .arg(dir.path().join("server").join("held.log"))
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    drop(held.stderr.take());
    assert_eq!(wait(&mut held), 3, "a directory held is exit 3, its stderr gone or not");
    let stop = Command::new(BINARY).arg("stop").arg(dir.path()).output().unwrap();
    assert!(stop.status.success(), "{}", String::from_utf8_lossy(&stop.stderr));
    assert_eq!(wait(&mut holder.0), 0);
}

/// A server a test started, killed if the test fails before it stops.
struct Stopped(Child);

impl Drop for Stopped {
    fn drop(&mut self) {
        if self.0.try_wait().is_ok_and(|exited| exited.is_none()) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }
}

// contract: CLI-03, SEC-05
#[test]
fn status_finds_a_running_server_and_stop_stops_it_its_serve_gone() {
    let dir = tempfile::tempdir().unwrap();
    let mut server = Command::new(BINARY)
        .arg("serve")
        .arg(dir.path())
        .args(["--durability", "os"])
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    published(&dir.path().join("server").join("SERVE"));
    let status = Command::new(BINARY).arg("status").arg(dir.path()).output().unwrap();
    let said = String::from_utf8_lossy(&status.stdout);
    assert!(status.status.success() && said.contains("served by tinystore"), "{said}");
    assert!(said.contains("durability os"), "the durability a program must ask for, or ask nothing: {said}");
    let stop = Command::new(BINARY).arg("stop").arg(dir.path()).output().unwrap();
    let said = format!("{}{}", String::from_utf8_lossy(&stop.stdout), String::from_utf8_lossy(&stop.stderr));
    assert!(stop.status.success() && said.contains("stopped"), "{said}");
    assert!(!dir.path().join("server").join("SERVE").exists(), "SERVE is gone once stop returns");
    assert_eq!(wait(&mut server), 0);
    let status = Command::new(BINARY).arg("status").arg(dir.path()).output().unwrap();
    assert!(String::from_utf8_lossy(&status.stdout).contains("not served"));
    let again = Command::new(BINARY).arg("stop").arg(dir.path()).output().unwrap();
    assert_eq!(again.status.code(), Some(1), "no server to stop");
}

/// `SERVE` once the server has written it.
fn published(path: &Path) -> serde_json::Value {
    let deadline = Instant::now() + Duration::from_secs(15);
    loop {
        if let Ok(text) = std::fs::read_to_string(path) {
            return serde_json::from_str(&text).unwrap();
        }
        assert!(Instant::now() < deadline, "no SERVE");
        std::thread::sleep(Duration::from_millis(20));
    }
}

#[cfg(unix)]
fn connect(endpoint: &str) -> std::os::unix::net::UnixStream {
    std::os::unix::net::UnixStream::connect(endpoint.strip_prefix("unix://").unwrap()).unwrap()
}

#[cfg(windows)]
fn connect(endpoint: &str) -> std::fs::File {
    let name = format!(r"\\.\pipe\{}", endpoint.strip_prefix("pipe:").unwrap());
    std::fs::OpenOptions::new().read(true).write(true).open(name).unwrap()
}

fn base64url(text: &str) -> Vec<u8> {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let sextets: Vec<u32> =
        text.bytes().map(|byte| ALPHABET.iter().position(|letter| *letter == byte).unwrap() as u32).collect();
    let mut bytes = Vec::new();
    for chunk in sextets.chunks(4) {
        let joined = chunk.iter().enumerate().fold(0, |joined, (at, sextet)| joined | sextet << (18 - 6 * at));
        bytes.extend((0..chunk.len() - 1).map(|at| (joined >> (16 - 8 * at)) as u8));
    }
    bytes
}