btc-keygen 0.3.0

Minimal offline Bitcoin key generator for cold storage
Documentation
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
use std::io::Write;
use std::process::{Command, Stdio};

/// Helper: runs the btc-keygen binary with the given arguments.
fn run_btc_keygen(args: &[&str]) -> std::process::Output {
    let binary = env!("CARGO_BIN_EXE_btc-keygen");
    Command::new(binary)
        .args(args)
        .output()
        .expect("failed to execute btc-keygen binary")
}

/// Helper: runs the binary with `input` piped to its stdin.
fn run_btc_keygen_with_stdin(args: &[&str], input: &[u8]) -> std::process::Output {
    let binary = env!("CARGO_BIN_EXE_btc-keygen");
    let mut child = Command::new(binary)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn btc-keygen binary");

    child
        .stdin
        .as_mut()
        .expect("stdin was piped")
        .write_all(input)
        .expect("failed to write to stdin");

    child.wait_with_output().expect("failed to collect output")
}

// ---------------------------------------------------------------
// Importing a key without putting it in the process arguments
// ---------------------------------------------------------------

const SCALAR_ONE_HEX: &str = "0000000000000000000000000000000000000000000000000000000000000001";
const SCALAR_ONE_ADDRESS: &str = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
const SCALAR_ONE_WIF: &str = "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn";

#[test]
fn test_from_hex_stdin_matches_argument_form() {
    let piped = run_btc_keygen_with_stdin(
        &["generate", "--from-hex", "-", "--hex", "--pubkey", "--json"],
        format!("{SCALAR_ONE_HEX}\n").as_bytes(),
    );
    assert!(piped.status.success(), "piping the key must succeed");

    let on_argv = run_btc_keygen(&[
        "generate",
        "--from-hex",
        SCALAR_ONE_HEX,
        "--hex",
        "--pubkey",
        "--json",
    ]);

    // Same key in, byte-identical keypair out, whichever channel carried it.
    assert_eq!(
        piped.stdout, on_argv.stdout,
        "stdin and argument forms must produce identical output"
    );
    let stdout = String::from_utf8(piped.stdout).unwrap();
    assert!(stdout.contains(SCALAR_ONE_ADDRESS));
    assert!(stdout.contains(SCALAR_ONE_WIF));
}

#[test]
fn test_from_hex_stdin_tolerates_no_trailing_newline() {
    let output =
        run_btc_keygen_with_stdin(&["generate", "--from-hex", "-"], SCALAR_ONE_HEX.as_bytes());
    assert!(output.status.success());
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.contains(SCALAR_ONE_ADDRESS));
}

#[test]
fn test_from_hex_stdin_tolerates_crlf_and_whitespace() {
    let output = run_btc_keygen_with_stdin(
        &["generate", "--from-hex", "-"],
        format!("  {SCALAR_ONE_HEX}  \r\n").as_bytes(),
    );
    assert!(output.status.success());
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.contains(SCALAR_ONE_ADDRESS));
}

#[test]
fn test_from_hex_stdin_accepts_uppercase() {
    let output = run_btc_keygen_with_stdin(
        &["generate", "--from-hex", "-"],
        b"0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D\n",
    );
    assert!(output.status.success(), "uppercase hex must be accepted");
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.contains("KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617"));
}

#[test]
fn test_from_hex_stdin_empty_fails_loudly() {
    let output = run_btc_keygen_with_stdin(&["generate", "--from-hex", "-"], b"");
    assert!(
        !output.status.success(),
        "empty stdin must not silently generate a random key"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("failed to read private key"),
        "must say why, got:\n{stderr}"
    );
}

#[test]
fn test_from_hex_stdin_rejects_overlong_input() {
    let junk = vec![b'0'; 4096];
    let output = run_btc_keygen_with_stdin(&["generate", "--from-hex", "-"], &junk);
    assert!(
        !output.status.success(),
        "over-long input must be rejected, never truncated to a different key"
    );
}

#[test]
fn test_stdin_form_emits_no_argv_warning() {
    let piped = run_btc_keygen_with_stdin(
        &["generate", "--from-hex", "-"],
        format!("{SCALAR_ONE_HEX}\n").as_bytes(),
    );
    let stderr = String::from_utf8(piped.stderr).unwrap();
    assert!(
        !stderr.contains("command-line argument"),
        "the safe channel must not be scolded, got:\n{stderr}"
    );
}

#[test]
fn test_argv_form_still_works_but_warns() {
    let output = run_btc_keygen(&["generate", "--from-hex", SCALAR_ONE_HEX]);
    assert!(
        output.status.success(),
        "the argument form must keep working for existing scripts"
    );

    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("command-line argument") && stderr.contains("history"),
        "passing a key on argv must warn about history and ps, got:\n{stderr}"
    );
    assert!(
        stderr.contains("--from-hex -"),
        "the warning must point at the safe alternative"
    );

    // The warning goes to stderr only: stdout stays machine-readable.
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(!stdout.to_lowercase().contains("warning"));
}

// ---------------------------------------------------------------
// 6.10: CLI integration tests
// ---------------------------------------------------------------

#[test]
fn test_cli_generate_exit_code_zero() {
    let output = run_btc_keygen(&["generate"]);
    assert!(
        output.status.success(),
        "btc-keygen generate must exit 0, got: {:?}\nstderr: {}",
        output.status.code(),
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_generate_stdout_has_address_and_wif() {
    let output = run_btc_keygen(&["generate"]);
    let stdout = String::from_utf8(output.stdout).unwrap();

    assert!(
        stdout.contains("bc1q"),
        "stdout must contain a bc1q address, got:\n{stdout}"
    );

    // WIF for compressed mainnet keys starts with K or L.
    let has_wif = stdout.lines().any(|line| {
        let trimmed = line.trim();
        (trimmed.starts_with('K') || trimmed.starts_with('L')) && trimmed.len() == 52
    });
    // Also check if the WIF appears as a value in a key:value line.
    let has_wif_in_field = stdout.lines().any(|line| {
        let parts: Vec<&str> = line.splitn(2, ':').collect();
        if parts.len() == 2 {
            let val = parts[1].trim();
            (val.starts_with('K') || val.starts_with('L')) && val.len() == 52
        } else {
            false
        }
    });
    assert!(
        has_wif || has_wif_in_field,
        "stdout must contain a WIF private key, got:\n{stdout}"
    );
}

#[test]
fn test_cli_generate_stderr_has_warnings() {
    let output = run_btc_keygen(&["generate"]);
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(!stderr.is_empty(), "stderr must contain safety warnings");
}

#[test]
fn test_cli_json_flag() {
    let output = run_btc_keygen(&["generate", "--json"]);
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.starts_with('{'), "JSON must start with {{");
    assert!(
        stdout.contains("\"address\""),
        "JSON must have address field"
    );
    assert!(stdout.contains("\"wif\""), "JSON must have wif field");
}

#[test]
fn test_cli_hex_flag() {
    let output = run_btc_keygen(&["generate", "--hex"]);
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    // Must contain a 64-character hex string (the raw private key).
    let has_hex = stdout
        .lines()
        .any(|line| line.chars().filter(|c| c.is_ascii_hexdigit()).count() >= 64);
    assert!(
        has_hex,
        "stdout with --hex must contain 64-char hex string, got:\n{stdout}"
    );
}

#[test]
fn test_cli_pubkey_flag() {
    let output = run_btc_keygen(&["generate", "--pubkey"]);
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    // Compressed pubkey is 66 hex characters (33 bytes).
    let has_pubkey = stdout.lines().any(|line| {
        let trimmed = line.trim();
        // The pubkey hex starts with 02 or 03.
        trimmed.contains("02") || trimmed.contains("03")
    });
    assert!(
        has_pubkey,
        "stdout with --pubkey must contain compressed public key hex, got:\n{stdout}"
    );
}

#[test]
fn test_cli_all_flags_json() {
    let output = run_btc_keygen(&["generate", "--hex", "--pubkey", "--json"]);
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.starts_with('{'), "JSON must start with {{");
    assert!(stdout.contains("\"address\""));
    assert!(stdout.contains("\"wif\""));
    assert!(stdout.contains("\"private_key_hex\""));
    assert!(stdout.contains("\"pubkey_hex\""));
}

#[test]
fn test_cli_no_subcommand_shows_help() {
    let output = run_btc_keygen(&[]);
    // clap exits non-zero when no subcommand is given.
    assert!(
        !output.status.success(),
        "no subcommand should produce non-zero exit"
    );
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("Usage") || stderr.contains("usage"),
        "should show usage info, got:\n{stderr}"
    );
}

#[test]
fn test_cli_unknown_flag_errors() {
    let output = run_btc_keygen(&["generate", "--unknown-flag"]);
    assert!(
        !output.status.success(),
        "unknown flag must produce non-zero exit"
    );
}

#[test]
fn test_cli_from_hex_produces_known_keypair() {
    let output = run_btc_keygen(&[
        "generate",
        "--from-hex",
        "0000000000000000000000000000000000000000000000000000000000000001",
    ]);
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.contains("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"),
        "expected known address for scalar 1, got:\n{stdout}"
    );
    assert!(
        stdout.contains("KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"),
        "expected known WIF for scalar 1, got:\n{stdout}"
    );
}

#[test]
fn test_cli_from_hex_invalid_input_exits_non_zero() {
    let output = run_btc_keygen(&["generate", "--from-hex", "notavalidhex"]);
    assert!(
        !output.status.success(),
        "invalid hex must produce non-zero exit"
    );
}

// ---------------------------------------------------------------
// 6.8: Statelessness tests
// ---------------------------------------------------------------

#[test]
fn test_two_cli_runs_produce_different_keys() {
    let output1 = run_btc_keygen(&["generate", "--json"]);
    let output2 = run_btc_keygen(&["generate", "--json"]);

    assert!(output1.status.success());
    assert!(output2.status.success());

    let stdout1 = String::from_utf8(output1.stdout).unwrap();
    let stdout2 = String::from_utf8(output2.stdout).unwrap();

    assert_ne!(stdout1, stdout2, "two runs must produce different output");
}

#[test]
fn test_no_file_artifacts() {
    let dir = std::env::temp_dir().join("btc_keygen_artifact_test");
    let _ = std::fs::create_dir_all(&dir);

    let before: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();

    let binary = env!("CARGO_BIN_EXE_btc-keygen");
    let output = Command::new(binary)
        .args(["generate"])
        .current_dir(&dir)
        .output()
        .unwrap();
    assert!(output.status.success());

    let after: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();

    assert_eq!(
        before.len(),
        after.len(),
        "generate must not create any files"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn test_no_env_mutation() {
    let env_before: std::collections::HashMap<String, String> = std::env::vars().collect();

    let output = run_btc_keygen(&["generate"]);
    assert!(output.status.success());

    // Verify no env vars were added or changed in *this* process.
    // The child process runs in its own address space, so it cannot mutate
    // our env. This test confirms the tool's design: it communicates only
    // via stdout/stderr, not environment variables.
    let env_after: std::collections::HashMap<String, String> = std::env::vars().collect();

    assert_eq!(
        env_before, env_after,
        "running btc-keygen must not mutate the parent process environment"
    );
}

// ---------------------------------------------------------------
// 6.9: Structural safety checks
// ---------------------------------------------------------------

#[test]
fn test_no_network_deps() {
    let output = Command::new("cargo")
        .args(["tree", "--prefix", "none"])
        .output()
        .expect("cargo tree must succeed");
    let tree = String::from_utf8(output.stdout).unwrap();

    let banned = [
        "reqwest",
        "hyper",
        "tokio",
        "async-std",
        "surf",
        "ureq",
        "curl",
    ];
    for crate_name in &banned {
        assert!(
            !tree.lines().any(|line| line.starts_with(crate_name)),
            "dependency tree must not contain networking crate '{}'\ntree:\n{}",
            crate_name,
            tree
        );
    }
}