anchor-cli 1.0.0-rc.4

Anchor CLI
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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use std::{
    fs,
    io::{self, Write},
    path::Path,
};

use anyhow::{anyhow, bail, Result};
use bip39::{Language, Mnemonic, MnemonicType, Seed};
use console::{Key, Term};
use dirs::home_dir;
use solana_instruction::{AccountMeta, Instruction};
use solana_keypair::Keypair;
use solana_pubkey::Pubkey;
use solana_signer::{EncodableKey, Signer};
use solana_transaction::Message;

use crate::{config::ConfigOverride, get_keypair, KeygenCommand};

/// Secure password input with asterisk visual feedback
/// - show_spaces: if true, spaces are visible (for seed phrases); if false, all characters are asterisks (for passphrases)
fn secure_input(prompt: &str, show_spaces: bool) -> Result<String> {
    print!("{}", prompt);
    io::stdout().flush()?;

    let term = Term::stdout();
    let mut input = String::new();

    loop {
        let key = term.read_key()?;
        match key {
            Key::Enter => {
                println!();
                break;
            }
            Key::Backspace => {
                if !input.is_empty() {
                    input.pop();
                    // Move cursor back, print space, move cursor back again
                    print!("\x08 \x08");
                    io::stdout().flush()?;
                }
            }
            Key::Char(c) => {
                input.push(c);
                // Display spaces as spaces if show_spaces is true, otherwise all asterisks
                if show_spaces && c == ' ' {
                    print!(" ");
                } else {
                    print!("*");
                }
                io::stdout().flush()?;
            }
            Key::Escape => {
                println!();
                bail!("Input cancelled");
            }
            _ => {}
        }
    }

    Ok(input)
}

/// Print a progress step with checkmark
fn print_step(step: &str) {
    println!("{}", step);
}

pub fn keygen(_cfg_override: &ConfigOverride, cmd: KeygenCommand) -> Result<()> {
    match cmd {
        KeygenCommand::New {
            outfile,
            force,
            no_passphrase,
            silent,
            word_count,
        } => keygen_new(outfile, force, no_passphrase, silent, word_count),
        KeygenCommand::Pubkey { keypair } => keygen_pubkey(keypair),
        KeygenCommand::Recover {
            outfile,
            force,
            skip_seed_phrase_validation,
            no_passphrase,
        } => keygen_recover(outfile, force, skip_seed_phrase_validation, no_passphrase),
        KeygenCommand::Verify { pubkey, keypair } => keygen_verify(pubkey, keypair),
    }
}

fn keygen_new(
    outfile: Option<String>,
    force: bool,
    no_passphrase: bool,
    silent: bool,
    word_count: usize,
) -> Result<()> {
    // Determine output file path
    let outfile_path = outfile.unwrap_or_else(|| {
        let mut path = home_dir().expect("home directory");
        path.push(".config");
        path.push("solana");
        path.push("id.json");
        path.to_str().unwrap().to_string()
    });

    // Check for overwrite
    if Path::new(&outfile_path).exists() {
        if !force {
            bail!(
                "Refusing to overwrite {} without --force flag",
                outfile_path
            );
        }
        println!(
            "⚠️  Warning: Overwriting existing keypair at {}",
            outfile_path
        );
    }

    println!("\n🔑 Generating a new keypair");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

    // Convert word count to MnemonicType
    let mnemonic_type = match word_count {
        12 => MnemonicType::Words12,
        15 => MnemonicType::Words15,
        18 => MnemonicType::Words18,
        21 => MnemonicType::Words21,
        24 => MnemonicType::Words24,
        _ => bail!(
            "Invalid word count: {}. Must be 12, 15, 18, 21, or 24",
            word_count
        ),
    };

    // Generate mnemonic with specified word count
    print_step(&format!("Generating {}-word mnemonic", word_count));
    let mnemonic = Mnemonic::new(mnemonic_type, Language::English);

    // Get passphrase
    let passphrase = if no_passphrase {
        print_step("No passphrase required");
        String::new()
    } else {
        println!("\n🔐 BIP39 Passphrase (optional)");
        let pass = secure_input("Enter BIP39 passphrase (leave empty for none): ", false)?;
        if !pass.is_empty() {
            print_step("Passphrase set");
        }
        pass
    };

    // Generate seed from mnemonic and passphrase
    print_step("Deriving keypair from seed");
    let seed = Seed::new(&mnemonic, &passphrase);

    // Create keypair from seed (use first 32 bytes as secret key)
    // Ed25519 keypair derivation: use the first 32 bytes of the seed as the secret key
    let secret_key_bytes: [u8; 32] = seed.as_bytes()[0..32].try_into().unwrap();
    let keypair = Keypair::new_from_array(secret_key_bytes);

    // Write keypair to file
    if let Some(outdir) = Path::new(&outfile_path).parent() {
        fs::create_dir_all(outdir)?;
    }
    keypair
        .write_to_file(&outfile_path)
        .map_err(|e| anyhow!("Failed to write keypair to {}: {}", outfile_path, e))?;

    // Set restrictive permissions (owner read/write only)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&outfile_path)?.permissions();
        perms.set_mode(0o600);
        fs::set_permissions(&outfile_path, perms)?;
    }

    print_step(&format!("Keypair saved to {}", outfile_path));

    let phrase: &str = mnemonic.phrase();
    let divider = "".repeat(phrase.len().max(60));
    let passphrase_msg = if passphrase.is_empty() {
        String::new()
    } else {
        " and your BIP39 passphrase".to_string()
    };

    // Always show the seed phrase - it's critical for recovery
    println!("\n{}", divider);
    if !silent {
        println!("📋 Public Key: {}", keypair.pubkey());
        println!("{}", divider);
    }
    println!(
        "\n⚠️  IMPORTANT: Save this seed phrase{} to recover your keypair:",
        passphrase_msg
    );
    println!("\n{}\n", phrase);
    println!("{}", divider);

    Ok(())
}

fn keygen_pubkey(keypair_path: Option<String>) -> Result<()> {
    let path = keypair_path.unwrap_or_else(|| {
        let mut p = home_dir().expect("home directory");
        p.push(".config");
        p.push("solana");
        p.push("id.json");
        p.to_str().unwrap().to_string()
    });

    let keypair = get_keypair(&path)?;
    println!("{}", keypair.pubkey());
    Ok(())
}

fn keygen_recover(
    outfile: Option<String>,
    force: bool,
    _skip_seed_phrase_validation: bool,
    no_passphrase: bool,
) -> Result<()> {
    println!("\n🔓 Recover keypair from seed phrase");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

    // Determine output file path
    let outfile_path = outfile.unwrap_or_else(|| {
        let mut path = home_dir().expect("home directory");
        path.push(".config");
        path.push("solana");
        path.push("id.json");
        path.to_str().unwrap().to_string()
    });

    // Check for overwrite
    if Path::new(&outfile_path).exists() {
        if !force {
            bail!(
                "Refusing to overwrite {} without --force flag",
                outfile_path
            );
        }
        println!(
            "⚠️  Warning: Overwriting existing keypair at {}",
            outfile_path
        );
    }

    // Prompt for seed phrase (secure input with spaces visible)
    println!("\n🌱 Enter Recovery Seed Phrase");
    let seed_phrase = secure_input("Seed phrase: ", true)?;

    // Parse mnemonic from seed phrase
    let mnemonic = Mnemonic::from_phrase(&seed_phrase, Language::English)
        .map_err(|e| anyhow!("Invalid seed phrase: {:?}", e))?;
    print_step("Seed phrase validated");

    // Get passphrase
    let passphrase = if no_passphrase {
        print_step("No passphrase required");
        String::new()
    } else {
        println!("\n🔐 BIP39 Passphrase (optional)");
        let pass = secure_input("Passphrase (leave empty for none): ", false)?;
        if !pass.is_empty() {
            print_step("Passphrase accepted");
        }
        pass
    };

    // Generate seed from mnemonic and passphrase
    print_step("Deriving keypair from seed");
    let seed = Seed::new(&mnemonic, &passphrase);

    // Create keypair from seed (use first 32 bytes as secret key)
    let secret_key_bytes: [u8; 32] = seed.as_bytes()[0..32].try_into().unwrap();
    let keypair = Keypair::new_from_array(secret_key_bytes);

    // Write keypair to file
    if let Some(outdir) = Path::new(&outfile_path).parent() {
        fs::create_dir_all(outdir)?;
    }
    keypair
        .write_to_file(&outfile_path)
        .map_err(|e| anyhow!("Failed to write keypair to {}: {}", outfile_path, e))?;

    // Set restrictive permissions (owner read/write only)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&outfile_path)?.permissions();
        perms.set_mode(0o600);
        fs::set_permissions(&outfile_path, perms)?;
    }

    print_step(&format!("Keypair recovered to {}", outfile_path));

    println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("📋 Public Key: {}", keypair.pubkey());
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");

    Ok(())
}

fn keygen_verify(pubkey: Pubkey, keypair_path: Option<String>) -> Result<()> {
    println!("\n🔍 Verifying keypair");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

    let path = keypair_path.unwrap_or_else(|| {
        let mut p = home_dir().expect("home directory");
        p.push(".config");
        p.push("solana");
        p.push("id.json");
        p.to_str().unwrap().to_string()
    });

    print_step(&format!("Loading keypair from {}", path));
    let keypair = get_keypair(&path)?;

    // Create a simple message to sign
    print_step("Creating test message");
    let message = Message::new(
        &[Instruction::new_with_bincode(
            Pubkey::default(),
            &0,
            vec![AccountMeta::new(keypair.pubkey(), true)],
        )],
        Some(&keypair.pubkey()),
    );

    // Sign the message
    print_step("Signing message with keypair");
    let signature = keypair.sign_message(message.serialize().as_slice());

    // Verify the signature
    print_step("Verifying signature");
    if signature.verify(pubkey.as_ref(), message.serialize().as_slice()) {
        println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!("✅ Verification Success");
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!("Public key {} matches the keypair\n", pubkey);
        Ok(())
    } else {
        println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!("❌ Verification Failed");
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        bail!("Public key {} does not match the keypair", pubkey);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::{tempdir, TempDir};

    fn tmp_outfile_path(out_dir: &TempDir, name: &str) -> String {
        let path = out_dir.path().join(name);
        path.into_os_string().into_string().unwrap()
    }

    fn read_keypair_file(path: &str) -> Result<Keypair> {
        get_keypair(path)
    }

    #[test]
    fn test_keygen_new() {
        let outfile_dir = tempdir().unwrap();
        let outfile_path = tmp_outfile_path(&outfile_dir, "test-keypair.json");

        // Test: successful keypair generation with default word count (12)
        keygen_new(Some(outfile_path.clone()), false, true, true, 12).unwrap();

        // Verify the keypair file was created
        assert!(Path::new(&outfile_path).exists());

        // Verify we can read the keypair back
        let keypair = read_keypair_file(&outfile_path).unwrap();
        assert_ne!(keypair.pubkey(), Pubkey::default());

        // Test: refuse to overwrite without --force
        let result = keygen_new(Some(outfile_path.clone()), false, true, true, 12);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Refusing to overwrite"));

        // Test: overwrite with --force flag
        keygen_new(Some(outfile_path.clone()), true, true, true, 12).unwrap();
        assert!(Path::new(&outfile_path).exists());
    }

    #[test]
    fn test_keygen_pubkey() {
        let keypair_dir = tempdir().unwrap();
        let keypair_path = tmp_outfile_path(&keypair_dir, "test-keypair.json");

        // Create a test keypair
        let test_keypair = Keypair::new();
        test_keypair.write_to_file(&keypair_path).unwrap();

        // Test: reading pubkey from file
        let result = keygen_pubkey(Some(keypair_path));
        // Since keygen_pubkey prints to stdout, we just verify it doesn't error
        assert!(result.is_ok());
    }

    #[test]
    fn test_keygen_verify() {
        let keypair_dir = tempdir().unwrap();
        let keypair_path = tmp_outfile_path(&keypair_dir, "test-keypair.json");

        // Create a test keypair
        let test_keypair = Keypair::new();
        test_keypair.write_to_file(&keypair_path).unwrap();
        let correct_pubkey = test_keypair.pubkey();

        // Test: verify with correct pubkey
        let result = keygen_verify(correct_pubkey, Some(keypair_path.clone()));
        assert!(result.is_ok());

        // Test: verify with incorrect pubkey
        let incorrect_pubkey = Pubkey::new_unique();
        let result = keygen_verify(incorrect_pubkey, Some(keypair_path));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(&format!(
            "Public key {} does not match the keypair",
            incorrect_pubkey
        )));
    }

    #[test]
    fn test_keypair_from_seed_consistency() {
        // Test that the same seed phrase produces the same keypair
        let test_phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";

        let mnemonic = Mnemonic::from_phrase(test_phrase, Language::English).unwrap();
        let seed1 = Seed::new(&mnemonic, "");
        let secret_key_bytes1: [u8; 32] = seed1.as_bytes()[0..32].try_into().unwrap();
        let keypair1 = Keypair::new_from_array(secret_key_bytes1);

        // Generate again with same phrase
        let mnemonic2 = Mnemonic::from_phrase(test_phrase, Language::English).unwrap();
        let seed2 = Seed::new(&mnemonic2, "");
        let secret_key_bytes2: [u8; 32] = seed2.as_bytes()[0..32].try_into().unwrap();
        let keypair2 = Keypair::new_from_array(secret_key_bytes2);

        // Should produce the same pubkey
        assert_eq!(keypair1.pubkey(), keypair2.pubkey());
        assert_eq!(keypair1.to_bytes(), keypair2.to_bytes());
    }

    #[test]
    fn test_keypair_with_passphrase() {
        // Test that different passphrases produce different keypairs
        let test_phrase =
            "park remain person kitchen mule spell knee armed position rail grid ankle";

        let mnemonic = Mnemonic::from_phrase(test_phrase, Language::English).unwrap();

        // Without passphrase
        let seed_no_pass = Seed::new(&mnemonic, "");
        let secret_key_bytes_no_pass: [u8; 32] = seed_no_pass.as_bytes()[0..32].try_into().unwrap();
        let keypair_no_pass = Keypair::new_from_array(secret_key_bytes_no_pass);

        // With passphrase
        let seed_with_pass = Seed::new(&mnemonic, "test_passphrase");
        let secret_key_bytes_with_pass: [u8; 32] =
            seed_with_pass.as_bytes()[0..32].try_into().unwrap();
        let keypair_with_pass = Keypair::new_from_array(secret_key_bytes_with_pass);

        // Should produce different pubkeys
        assert_ne!(keypair_no_pass.pubkey(), keypair_with_pass.pubkey());
    }

    #[test]
    fn test_word_count_variations() {
        // Test all supported word counts
        let word_counts = [12, 15, 18, 21, 24];

        for word_count in word_counts {
            let outfile_dir = tempdir().unwrap();
            let outfile_path =
                tmp_outfile_path(&outfile_dir, &format!("test-keypair-{}.json", word_count));

            // Test: successful keypair generation with different word counts
            let result = keygen_new(Some(outfile_path.clone()), false, true, true, word_count);
            assert!(
                result.is_ok(),
                "Failed to generate keypair with {} words",
                word_count
            );

            // Verify the keypair file was created
            assert!(Path::new(&outfile_path).exists());

            // Verify we can read the keypair back
            let keypair = read_keypair_file(&outfile_path).unwrap();
            assert_ne!(keypair.pubkey(), Pubkey::default());
        }
    }

    #[test]
    fn test_invalid_word_count() {
        let outfile_dir = tempdir().unwrap();
        let outfile_path = tmp_outfile_path(&outfile_dir, "test-invalid-wordcount.json");

        // Test: invalid word count should fail
        let result = keygen_new(Some(outfile_path), false, true, true, 9);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid word count"));
    }
}