Skip to main content

heika_wallet/
keystore.rs

1//! キーストア。ニーモニックや秘密鍵と、そこから使うアカウントをまとめて、パスフレーズで暗号化して持つ。
2//!
3//! 暗号化は [`crate::age`] の形式で、heika がなくても `age -d` で開ける。開いた中身は、メールのヘッダーのような
4//! `キー: 値` の行のまとまりを空行で区切ったテキストで、秘密1つにつき1まとまりにする。
5//!
6//! ```text
7//! Heika-Keystore-Version: 1
8//! Secret-Type: Mnemonic
9//! Secret: <単語> <単語> … <単語>
10//! Harvest-Secret: <単語> <単語> … <単語>
11//! Account: mainnet 0 main
12//! Account: testnet 0 test
13//!
14//! Heika-Keystore-Version: 1
15//! Secret-Type: Private-Key
16//! Secret: <秘密鍵の16進>
17//! Harvest-Secret: <単語> <単語> … <単語>
18//! Account: mainnet cold
19//! ```
20//!
21//! - ニーモニックのアカウントは、ネットワーク、公式ウォレットと同じパスの番号、ラベルの順。秘密鍵のアカウントは、ネットワークとラベル
22//! - ラベルは行の残り全部で、空白を含められる。改行と制御文字は入れられない。ファイル全体で重ならない
23//! - 知らないキーは読み飛ばすので、あとからキーを足せる
24//! - ニーモニックは単語のまま入れる。パスフレーズを空にしたシードを入れると、あとから BIP39 のパスフレーズで
25//!   別のウォレットを導出できなくなるため
26//! - `Harvest-Secret` は、ハーベストに使うリモートと VRF の鍵を導出するための 24 語のニーモニック。
27//!   使うかどうかに関わらず、書くときにすべての秘密に入れる([`Keystore::fill_harvest_secrets`])。
28//!   どのキーストアにも同じようにあるので、あることからはハーベストしているかどうかがわからない。
29//!   アカウントと同じ BIP39 のパスフレーズをかけて導出するので、パスフレーズ(25 番目の単語)ごとに別の鍵になり、
30//!   キーストアを開けても、隠しウォレットのリンクはたどれない。一度入れたら書き換えない。
31//!   書き換えた時刻が、チェーンでリンクした時刻と並んで、どのアカウントかの手がかりになるため。
32//!   鍵を作り直すときは、導出の番号を上げる([`slip10::harvest_path`])
33//!
34//! 秘密は、復号したバッファから参照で切り出して、消える型に直接読む。書くときは先に長さを数えて確保し、
35//! バッファが引っ越して古い領域が消えずに残ることがないようにする。
36
37use std::fmt;
38
39use heika_core::key::PrivateKey;
40use heika_core::network::NetworkIdentifier;
41use rand_core::CryptoRng;
42use zeroize::Zeroizing;
43
44use crate::age::{self, AgeError};
45use crate::bip39::{InvalidPassphrase, Mnemonic, WordCount};
46use crate::harvest_request::HarvesterKeys;
47use crate::slip10::{self, ExtendedKey, HarvestRole};
48
49const VERSION: &str = "1";
50
51/// しまってある秘密。
52pub enum Secret {
53    Mnemonic(Mnemonic),
54    PrivateKey(PrivateKey),
55}
56
57impl fmt::Debug for Secret {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(match self {
60            Self::Mnemonic(_) => "Secret::Mnemonic(..)",
61            Self::PrivateKey(_) => "Secret::PrivateKey(..)",
62        })
63    }
64}
65
66/// 秘密から使うアカウント。
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct Account {
69    pub network: NetworkIdentifier,
70    /// ニーモニックから導出するときの、アカウントの番号。秘密鍵なら `None`
71    pub index: Option<u32>,
72    pub label: String,
73}
74
75/// 秘密1つと、そのアカウント。
76#[derive(Debug)]
77pub struct Entry {
78    pub secret: Secret,
79    /// ハーベストの鍵を導出するニーモニック。足すときは `None` にしておけば、書くときに作る
80    pub harvest_secret: Option<Mnemonic>,
81    pub accounts: Vec<Account>,
82}
83
84#[derive(Debug, Default)]
85pub struct Keystore {
86    entries: Vec<Entry>,
87}
88
89impl Keystore {
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    pub fn entries(&self) -> &[Entry] {
95        &self.entries
96    }
97
98    /// 秘密を足す。アカウントのラベルが正しくないか、すでにあるものと重なるなら足さない。
99    pub fn add(&mut self, entry: Entry) -> Result<(), KeystoreError> {
100        check_accounts(&entry, self.accounts())?;
101        self.entries.push(entry);
102        Ok(())
103    }
104
105    /// すでにある秘密にアカウントを足す。
106    pub fn add_account(&mut self, entry: usize, account: Account) -> Result<(), KeystoreError> {
107        let target = self.entries.get(entry).ok_or(KeystoreError::Format)?;
108        check_account(&target.secret, &account)?;
109        if self
110            .accounts()
111            .any(|(_, other)| other.label == account.label)
112        {
113            return Err(KeystoreError::DuplicateLabel(account.label));
114        }
115        self.entries[entry].accounts.push(account);
116        Ok(())
117    }
118
119    /// アカウントのラベルを変える。
120    pub fn rename_account(&mut self, label: &str, new_label: &str) -> Result<(), KeystoreError> {
121        check_label(new_label)?;
122        let (entry, position) = self.position(label)?;
123        if self
124            .accounts()
125            .any(|(_, other)| other.label == new_label && other.label != label)
126        {
127            return Err(KeystoreError::DuplicateLabel(new_label.to_owned()));
128        }
129        self.entries[entry].accounts[position].label = new_label.to_owned();
130        Ok(())
131    }
132
133    /// アカウントを外す。秘密は、アカウントがなくなっても残す。
134    pub fn remove_account(&mut self, label: &str) -> Result<(usize, Account), KeystoreError> {
135        let (entry, position) = self.position(label)?;
136        Ok((entry, self.entries[entry].accounts.remove(position)))
137    }
138
139    /// 秘密を、残っているアカウントごと消す。
140    pub fn remove_entry(&mut self, entry: usize) -> Result<Entry, KeystoreError> {
141        if entry >= self.entries.len() {
142            return Err(KeystoreError::Format);
143        }
144        Ok(self.entries.remove(entry))
145    }
146
147    /// ラベルのアカウントが、何番目の秘密の何番目にあるか。
148    fn position(&self, label: &str) -> Result<(usize, usize), KeystoreError> {
149        self.entries
150            .iter()
151            .enumerate()
152            .find_map(|(index, entry)| {
153                entry
154                    .accounts
155                    .iter()
156                    .position(|account| account.label == label)
157                    .map(|position| (index, position))
158            })
159            .ok_or_else(|| KeystoreError::UnknownLabel(label.to_owned()))
160    }
161
162    /// すべてのアカウントと、その秘密の番号。
163    pub fn accounts(&self) -> impl Iterator<Item = (usize, &Account)> {
164        self.entries
165            .iter()
166            .enumerate()
167            .flat_map(|(index, entry)| entry.accounts.iter().map(move |account| (index, account)))
168    }
169
170    /// ラベルでアカウントを探し、その秘密鍵を求める。
171    ///
172    /// ニーモニックのアカウントは、`bip39_passphrase` を BIP39 のパスフレーズにして導出する。
173    /// 公式ウォレットと同じ鍵になるのは空のときだけで、それ以外は同じ番号でも別の鍵(隠しウォレット)になる。
174    /// 秘密鍵のアカウントには関係しない。
175    pub fn private_key(
176        &self,
177        label: &str,
178        bip39_passphrase: &str,
179    ) -> Result<(&Account, PrivateKey), KeystoreError> {
180        let (entry, account) = self
181            .accounts()
182            .find(|(_, account)| account.label == label)
183            .ok_or_else(|| KeystoreError::UnknownLabel(label.to_owned()))?;
184        let private_key = match &self.entries[entry].secret {
185            Secret::PrivateKey(private_key) => PrivateKey::from_bytes(private_key.as_bytes()),
186            Secret::Mnemonic(mnemonic) => {
187                let seed = mnemonic
188                    .to_seed(bip39_passphrase)
189                    .map_err(KeystoreError::Bip39Passphrase)?;
190                let index = account.index.expect("checked when added or read");
191                ExtendedKey::from_seed(seed.as_bytes())
192                    .derive_path(&slip10::symbol_path(account.network, index))
193                    .private_key()
194            }
195        };
196        Ok((account, private_key))
197    }
198
199    /// ハーベストの秘密がない秘密に、新しく作って入れる。すでにあるものは変えない。
200    pub fn fill_harvest_secrets<R: CryptoRng + ?Sized>(&mut self, rng: &mut R) {
201        for entry in &mut self.entries {
202            entry
203                .harvest_secret
204                .get_or_insert_with(|| Mnemonic::generate_with_rng(rng, WordCount::Words24));
205        }
206    }
207
208    /// ラベルでアカウントを探し、そのハーベストの鍵を求める。
209    ///
210    /// `bip39_passphrase` は [`Self::private_key`] と同じで、ニーモニックのアカウントでだけ使う。
211    /// `rotation` は作り直しの番号で、ふだんは 0。ハーベストの秘密がまだなければ `None`
212    pub fn harvester_keys(
213        &self,
214        label: &str,
215        bip39_passphrase: &str,
216        rotation: u32,
217    ) -> Result<Option<HarvesterKeys>, KeystoreError> {
218        let (entry, account) = self
219            .accounts()
220            .find(|(_, account)| account.label == label)
221            .ok_or_else(|| KeystoreError::UnknownLabel(label.to_owned()))?;
222        let entry = &self.entries[entry];
223        let Some(harvest_secret) = &entry.harvest_secret else {
224            return Ok(None);
225        };
226        let passphrase = match entry.secret {
227            Secret::Mnemonic(_) => bip39_passphrase,
228            Secret::PrivateKey(_) => "",
229        };
230        let seed = harvest_secret
231            .to_seed(passphrase)
232            .map_err(KeystoreError::Bip39Passphrase)?;
233        let root = ExtendedKey::from_seed(seed.as_bytes());
234        let derive = |role| {
235            root.derive_path(&slip10::harvest_path(
236                account.network,
237                account.index.unwrap_or(0),
238                role,
239                rotation,
240            ))
241            .private_key()
242        };
243        Ok(Some(HarvesterKeys {
244            signing: derive(HarvestRole::Remote),
245            vrf: derive(HarvestRole::Vrf),
246        }))
247    }
248
249    /// 開いた中身のテキスト。秘密が入るので、消えるようにして返す。
250    pub fn to_text(&self) -> Zeroizing<Vec<u8>> {
251        let mut parts: Vec<Zeroizing<String>> = Vec::new();
252        for (index, entry) in self.entries.iter().enumerate() {
253            if index > 0 {
254                parts.push(Zeroizing::new("\n".to_owned()));
255            }
256            parts.push(Zeroizing::new(format!(
257                "Heika-Keystore-Version: {VERSION}\n"
258            )));
259            let (secret_type, secret) = match &entry.secret {
260                Secret::Mnemonic(mnemonic) => ("Mnemonic", mnemonic.to_phrase()),
261                Secret::PrivateKey(private_key) => ("Private-Key", private_key.to_hex()),
262            };
263            parts.push(Zeroizing::new(format!("Secret-Type: {secret_type}\n")));
264            parts.push(Zeroizing::new("Secret: ".to_owned()));
265            parts.push(secret);
266            parts.push(Zeroizing::new("\n".to_owned()));
267            if let Some(harvest_secret) = &entry.harvest_secret {
268                parts.push(Zeroizing::new("Harvest-Secret: ".to_owned()));
269                parts.push(harvest_secret.to_phrase());
270                parts.push(Zeroizing::new("\n".to_owned()));
271            }
272            for account in &entry.accounts {
273                let network = network_name(account.network);
274                parts.push(Zeroizing::new(match account.index {
275                    Some(index) => format!("Account: {network} {index} {}\n", account.label),
276                    None => format!("Account: {network} {}\n", account.label),
277                }));
278            }
279        }
280        // 先に長さを数えて確保し、書くあいだにバッファが引っ越さないようにする
281        let mut text = Zeroizing::new(Vec::with_capacity(
282            parts.iter().map(|part| part.len()).sum(),
283        ));
284        for part in &parts {
285            text.extend_from_slice(part.as_bytes());
286        }
287        text
288    }
289
290    /// 開いた中身のテキストを読む。
291    pub fn from_text(text: &[u8]) -> Result<Self, KeystoreError> {
292        let text = std::str::from_utf8(text).map_err(|_| KeystoreError::Format)?;
293        let mut keystore = Self::new();
294        // 秘密がまだないキーストアは空のテキスト
295        if text.is_empty() {
296            return Ok(keystore);
297        }
298        for block in text.split("\n\n") {
299            let block = block.strip_suffix('\n').unwrap_or(block);
300            let mut version = None;
301            let mut secret_type = None;
302            let mut secret = None;
303            let mut harvest_secret = None;
304            let mut accounts = Vec::new();
305            for line in block.split('\n') {
306                let (key, value) = line.split_once(": ").ok_or(KeystoreError::Format)?;
307                let slot = match key {
308                    "Heika-Keystore-Version" => &mut version,
309                    "Secret-Type" => &mut secret_type,
310                    "Secret" => &mut secret,
311                    "Harvest-Secret" => &mut harvest_secret,
312                    "Account" => {
313                        accounts.push(value);
314                        continue;
315                    }
316                    // 知らないキーは、あとの版で足したものとして読み飛ばす
317                    _ => continue,
318                };
319                if slot.replace(value).is_some() {
320                    return Err(KeystoreError::Format);
321                }
322            }
323            match version {
324                Some(VERSION) => {}
325                Some(_) => return Err(KeystoreError::UnsupportedVersion),
326                None => return Err(KeystoreError::Format),
327            }
328            let secret = secret.ok_or(KeystoreError::Format)?;
329            let (secret, mnemonic) = match secret_type {
330                Some("Mnemonic") => (
331                    Secret::Mnemonic(secret.parse().map_err(|_| KeystoreError::InvalidSecret)?),
332                    true,
333                ),
334                Some("Private-Key") => (
335                    Secret::PrivateKey(secret.parse().map_err(|_| KeystoreError::InvalidSecret)?),
336                    false,
337                ),
338                _ => return Err(KeystoreError::Format),
339            };
340            let harvest_secret = harvest_secret
341                .map(|value| value.parse().map_err(|_| KeystoreError::InvalidSecret))
342                .transpose()?;
343            let accounts = accounts
344                .into_iter()
345                .map(|value| parse_account(value, mnemonic))
346                .collect::<Result<_, _>>()?;
347            keystore.add(Entry {
348                secret,
349                harvest_secret,
350                accounts,
351            })?;
352        }
353        Ok(keystore)
354    }
355
356    /// パスフレーズで暗号化する。
357    pub fn seal<R: CryptoRng + ?Sized>(
358        &self,
359        rng: &mut R,
360        passphrase: &[u8],
361        work_factor: u8,
362    ) -> Vec<u8> {
363        age::encrypt(rng, passphrase, work_factor, &self.to_text())
364    }
365
366    /// パスフレーズで開く。
367    pub fn open(passphrase: &[u8], sealed: &[u8]) -> Result<Self, KeystoreError> {
368        let text = age::decrypt(passphrase, sealed).map_err(KeystoreError::Age)?;
369        Self::from_text(&text)
370    }
371}
372
373fn parse_account(value: &str, mnemonic: bool) -> Result<Account, KeystoreError> {
374    let (network, rest) = value.split_once(' ').ok_or(KeystoreError::Format)?;
375    let network = match network {
376        "mainnet" => NetworkIdentifier::MAINNET,
377        "testnet" => NetworkIdentifier::TESTNET,
378        _ => return Err(KeystoreError::Format),
379    };
380    let (index, label) = if mnemonic {
381        let (index, label) = rest.split_once(' ').ok_or(KeystoreError::Format)?;
382        // 先頭に 0 を付けた番号は、書き戻すと変わるので受け付けない
383        if index.len() > 1 && index.starts_with('0') {
384            return Err(KeystoreError::Format);
385        }
386        (
387            Some(index.parse().map_err(|_| KeystoreError::Format)?),
388            label,
389        )
390    } else {
391        (None, rest)
392    };
393    Ok(Account {
394        network,
395        index,
396        label: label.to_owned(),
397    })
398}
399
400fn network_name(network: NetworkIdentifier) -> &'static str {
401    match network {
402        NetworkIdentifier::MAINNET => "mainnet",
403        NetworkIdentifier::TESTNET => "testnet",
404        _ => unreachable!("only mainnet and testnet accounts are accepted"),
405    }
406}
407
408/// 足す秘密のアカウントが正しく、ラベルが互いにもすでにあるものとも重ならないか。
409fn check_accounts<'a>(
410    entry: &Entry,
411    existing: impl Iterator<Item = (usize, &'a Account)>,
412) -> Result<(), KeystoreError> {
413    let mut labels: Vec<&str> = existing
414        .map(|(_, account)| account.label.as_str())
415        .collect();
416    for account in &entry.accounts {
417        check_account(&entry.secret, account)?;
418        if labels.contains(&account.label.as_str()) {
419            return Err(KeystoreError::DuplicateLabel(account.label.clone()));
420        }
421        labels.push(&account.label);
422    }
423    Ok(())
424}
425
426fn check_account(secret: &Secret, account: &Account) -> Result<(), KeystoreError> {
427    if ![NetworkIdentifier::MAINNET, NetworkIdentifier::TESTNET].contains(&account.network) {
428        return Err(KeystoreError::Format);
429    }
430    match (secret, account.index) {
431        (Secret::Mnemonic(_), Some(index)) if index < 0x8000_0000 => {}
432        (Secret::PrivateKey(_), None) => {}
433        _ => return Err(KeystoreError::Format),
434    }
435    check_label(&account.label)
436}
437
438/// ラベルは1文字以上で、制御文字を含まず、前後に空白がない。
439pub fn check_label(label: &str) -> Result<(), KeystoreError> {
440    if label.is_empty() || label.trim() != label || label.chars().any(char::is_control) {
441        return Err(KeystoreError::InvalidLabel(label.to_owned()));
442    }
443    Ok(())
444}
445
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub enum KeystoreError {
448    /// 暗号化を解けない(パスフレーズが違う、壊れている)
449    Age(AgeError),
450    /// 中身の形が正しくない
451    Format,
452    /// heika が知らない版のキーストア
453    UnsupportedVersion,
454    /// ニーモニックか秘密鍵として読めない
455    InvalidSecret,
456    /// ラベルに使えない文字がある
457    InvalidLabel(String),
458    /// 同じラベルのアカウントがすでにある
459    DuplicateLabel(String),
460    /// そのラベルのアカウントがない
461    UnknownLabel(String),
462    /// BIP39 のパスフレーズに使えない
463    Bip39Passphrase(InvalidPassphrase),
464}
465
466impl fmt::Display for KeystoreError {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        match self {
469            Self::Age(error) => write!(f, "{error}"),
470            Self::Format => f.write_str("キーストアの中身の形が正しくありません"),
471            Self::UnsupportedVersion => {
472                f.write_str("この heika が知らない版のキーストアです。heika を新しくしてください")
473            }
474            Self::InvalidSecret => {
475                f.write_str("キーストアの秘密を、ニーモニックか秘密鍵として読めません")
476            }
477            Self::InvalidLabel(_) => f.write_str(
478                "ラベルは1文字以上で、制御文字を含まず、前後に空白がないものにしてください",
479            ),
480            Self::DuplicateLabel(label) => write!(f, "ラベル {label:?} のアカウントはもうあります"),
481            Self::UnknownLabel(label) => write!(f, "ラベル {label:?} のアカウントはありません"),
482            Self::Bip39Passphrase(error) => write!(f, "BIP39 のパスフレーズ: {error}"),
483        }
484    }
485}
486
487impl std::error::Error for KeystoreError {}
488
489#[cfg(test)]
490mod tests {
491    use heika_core::key::PublicKey;
492
493    use super::*;
494    use crate::testing::Replay;
495
496    /// 誰でも知っているテスト用のニーモニック
497    const MNEMONIC: &str = "test test test test test test test test test test test junk";
498    const PRIVATE_KEY: &str = "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60";
499
500    fn keystore() -> Keystore {
501        let mut keystore = Keystore::new();
502        keystore
503            .add(Entry {
504                secret: Secret::Mnemonic(MNEMONIC.parse().unwrap()),
505                harvest_secret: None,
506                accounts: vec![
507                    Account {
508                        network: NetworkIdentifier::MAINNET,
509                        index: Some(0),
510                        label: "main".to_owned(),
511                    },
512                    Account {
513                        network: NetworkIdentifier::TESTNET,
514                        index: Some(3),
515                        label: "テスト用 3".to_owned(),
516                    },
517                ],
518            })
519            .unwrap();
520        keystore
521            .add(Entry {
522                secret: Secret::PrivateKey(PRIVATE_KEY.parse().unwrap()),
523                harvest_secret: None,
524                accounts: vec![Account {
525                    network: NetworkIdentifier::MAINNET,
526                    index: None,
527                    label: "cold".to_owned(),
528                }],
529            })
530            .unwrap();
531        keystore
532    }
533
534    #[test]
535    fn writes_header_blocks() {
536        let text = keystore().to_text();
537        assert_eq!(
538            std::str::from_utf8(&text).unwrap(),
539            format!(
540                "Heika-Keystore-Version: 1\nSecret-Type: Mnemonic\nSecret: {MNEMONIC}\nAccount: mainnet 0 main\nAccount: testnet 3 テスト用 3\n\nHeika-Keystore-Version: 1\nSecret-Type: Private-Key\nSecret: {PRIVATE_KEY}\nAccount: mainnet cold\n"
541            )
542        );
543        // 先に確保したとおりで、書くあいだに引っ越していない
544        assert_eq!(text.capacity(), text.len());
545    }
546
547    #[test]
548    fn reads_back_what_it_writes() {
549        assert_eq!(
550            Keystore::from_text(&Keystore::new().to_text())
551                .unwrap()
552                .entries()
553                .len(),
554            0
555        );
556        let original = keystore();
557        let read = Keystore::from_text(&original.to_text()).unwrap();
558        assert_eq!(*read.to_text(), *original.to_text());
559        let accounts: Vec<_> = read
560            .accounts()
561            .map(|(_, account)| account.clone())
562            .collect();
563        assert_eq!(accounts.len(), 3);
564    }
565
566    #[test]
567    fn derives_keys_like_heika_key_derive() {
568        let keystore = keystore();
569        let (account, main) = keystore.private_key("main", "").unwrap();
570        assert_eq!(account.index, Some(0));
571        let seed = MNEMONIC.parse::<Mnemonic>().unwrap().to_seed("").unwrap();
572        let expected = ExtendedKey::from_seed(seed.as_bytes())
573            .derive_path(&slip10::symbol_path(NetworkIdentifier::MAINNET, 0))
574            .private_key();
575        assert_eq!(main.as_bytes(), expected.as_bytes());
576        let (_, cold) = keystore.private_key("cold", "").unwrap();
577        assert_eq!(*cold.to_hex(), PRIVATE_KEY);
578        assert_ne!(
579            PublicKey::from_private_key(&keystore.private_key("テスト用 3", "").unwrap().1),
580            PublicKey::from_private_key(&main)
581        );
582        assert_eq!(
583            keystore.private_key("none", "").unwrap_err(),
584            KeystoreError::UnknownLabel("none".to_owned())
585        );
586        // BIP39 のパスフレーズを変えると、同じ番号でも別の鍵になる。秘密鍵のアカウントは変わらない
587        let hidden = keystore.private_key("main", "hidden").unwrap().1;
588        assert_ne!(hidden.as_bytes(), main.as_bytes());
589        let seed = MNEMONIC
590            .parse::<Mnemonic>()
591            .unwrap()
592            .to_seed("hidden")
593            .unwrap();
594        let expected = ExtendedKey::from_seed(seed.as_bytes())
595            .derive_path(&slip10::symbol_path(NetworkIdentifier::MAINNET, 0))
596            .private_key();
597        assert_eq!(hidden.as_bytes(), expected.as_bytes());
598        assert_eq!(
599            *keystore.private_key("cold", "hidden").unwrap().1.to_hex(),
600            PRIVATE_KEY
601        );
602    }
603
604    #[test]
605    fn skips_unknown_keys_and_rejects_broken_text() {
606        let text = format!(
607            "Heika-Keystore-Version: 1\nCreated: 2026-10-12\nSecret-Type: Private-Key\nSecret: {PRIVATE_KEY}\nAccount: testnet a b\n"
608        );
609        let read = Keystore::from_text(text.as_bytes()).unwrap();
610        assert_eq!(read.accounts().next().unwrap().1.label, "a b");
611
612        let valid =
613            format!("Heika-Keystore-Version: 1\nSecret-Type: Private-Key\nSecret: {PRIVATE_KEY}\n");
614        for (name, text, error) in [
615            (
616                "version",
617                valid.replace("Version: 1", "Version: 2"),
618                KeystoreError::UnsupportedVersion,
619            ),
620            (
621                "no version",
622                valid.replace("Heika-Keystore-Version: 1\n", ""),
623                KeystoreError::Format,
624            ),
625            (
626                "type",
627                valid.replace("Private-Key", "Seed"),
628                KeystoreError::Format,
629            ),
630            (
631                "secret",
632                valid.replace(PRIVATE_KEY, "00"),
633                KeystoreError::InvalidSecret,
634            ),
635            (
636                "twice",
637                format!("{valid}Secret: {PRIVATE_KEY}\n"),
638                KeystoreError::Format,
639            ),
640            (
641                "no colon",
642                format!("{valid}Account mainnet a\n"),
643                KeystoreError::Format,
644            ),
645            (
646                "network",
647                format!("{valid}Account: devnet a\n"),
648                KeystoreError::Format,
649            ),
650            (
651                "index",
652                format!("{valid}Account: mainnet 0 a\n")
653                    .replace("Private-Key", "Mnemonic")
654                    .replace(PRIVATE_KEY, MNEMONIC)
655                    .replace("0 a", "00 a"),
656                KeystoreError::Format,
657            ),
658            (
659                "label",
660                format!("{valid}Account: mainnet  a\n"),
661                KeystoreError::InvalidLabel(" a".to_owned()),
662            ),
663            (
664                "duplicate",
665                format!("{valid}Account: mainnet a\nAccount: testnet a\n"),
666                KeystoreError::DuplicateLabel("a".to_owned()),
667            ),
668        ] {
669            assert_eq!(
670                Keystore::from_text(text.as_bytes()).unwrap_err(),
671                error,
672                "{name}"
673            );
674        }
675    }
676
677    #[test]
678    fn renames_and_removes_accounts() {
679        let mut keystore = keystore();
680        keystore.rename_account("main", "メイン").unwrap();
681        assert_eq!(keystore.private_key("メイン", "").unwrap().0.index, Some(0));
682        // 同じラベルへの変更はそのまま通る
683        keystore.rename_account("cold", "cold").unwrap();
684        assert_eq!(
685            keystore.rename_account("メイン", "cold").unwrap_err(),
686            KeystoreError::DuplicateLabel("cold".to_owned())
687        );
688        assert_eq!(
689            keystore.rename_account("メイン", " a").unwrap_err(),
690            KeystoreError::InvalidLabel(" a".to_owned())
691        );
692        assert_eq!(
693            keystore.rename_account("main", "a").unwrap_err(),
694            KeystoreError::UnknownLabel("main".to_owned())
695        );
696
697        let (entry, account) = keystore.remove_account("テスト用 3").unwrap();
698        assert_eq!((entry, account.index), (0, Some(3)));
699        // アカウントのない秘密も、書いて読み戻せる
700        let (entry, _) = keystore.remove_account("cold").unwrap();
701        let read = Keystore::from_text(&keystore.to_text()).unwrap();
702        assert_eq!(read.entries().len(), 2);
703        assert_eq!(read.accounts().count(), 1);
704        assert!(keystore.remove_entry(entry).unwrap().accounts.is_empty());
705        assert_eq!(keystore.entries().len(), 1);
706        assert_eq!(keystore.remove_entry(1).unwrap_err(), KeystoreError::Format);
707        assert_eq!(
708            keystore.remove_account("cold").unwrap_err(),
709            KeystoreError::UnknownLabel("cold".to_owned())
710        );
711    }
712
713    #[test]
714    fn rejects_labels_that_break_the_text() {
715        for label in ["", " a", "a ", "a\nb", "a\u{7}"] {
716            assert!(check_label(label).is_err(), "{label:?}");
717        }
718        assert!(check_label("メイン 1").is_ok());
719    }
720
721    /// ハーベストの秘密を、どちらの秘密にもテスト用のニーモニックで入れたもの
722    fn keystore_with_harvest_secrets() -> Keystore {
723        let mut keystore = keystore();
724        for entry in &mut keystore.entries {
725            entry.harvest_secret = Some(MNEMONIC.parse().unwrap());
726        }
727        keystore
728    }
729
730    #[test]
731    fn fills_harvest_secrets_only_where_missing() {
732        let mut keystore = keystore();
733        keystore.entries[1].harvest_secret = Some(MNEMONIC.parse().unwrap());
734        keystore.fill_harvest_secrets(&mut Replay(&[5; 32]));
735        let filled = keystore.entries[0].harvest_secret.as_ref().unwrap();
736        assert_eq!(filled.word_count(), 24);
737        assert_eq!(filled.entropy(), &[5; 32]);
738        // すでにあったものは変えない
739        assert_eq!(
740            *keystore.entries[1]
741                .harvest_secret
742                .as_ref()
743                .unwrap()
744                .to_phrase(),
745            MNEMONIC
746        );
747    }
748
749    #[test]
750    fn writes_and_reads_harvest_secrets() {
751        let keystore = keystore_with_harvest_secrets();
752        let text = keystore.to_text();
753        let text = std::str::from_utf8(&text).unwrap();
754        assert!(text.contains(&format!(
755            "Secret: {MNEMONIC}\nHarvest-Secret: {MNEMONIC}\nAccount: mainnet 0 main\n"
756        )));
757        assert!(text.contains(&format!(
758            "Secret: {PRIVATE_KEY}\nHarvest-Secret: {MNEMONIC}\nAccount: mainnet cold\n"
759        )));
760        let read = Keystore::from_text(text.as_bytes()).unwrap();
761        assert_eq!(*read.to_text(), *keystore.to_text());
762    }
763
764    #[test]
765    fn derives_harvester_keys() {
766        let hex = |keys: &HarvesterKeys| (keys.signing.to_hex(), keys.vrf.to_hex());
767        // 値は、ニーモニックから BIP39 と SLIP-10 を Python で別に計算したもの
768        const REMOTE: &str = "FFD1CB7DC92FE03ED9BDF3709FA66E06B39A9E793C0DF0B14A5AD97FA57F4B1C";
769        const VRF: &str = "36B7DE817C0FCF97BA88941F03A9D2208F64159AFCCA0D57047B8AF54C66CBA0";
770
771        assert!(keystore().harvester_keys("main", "", 0).unwrap().is_none());
772        let keystore = keystore_with_harvest_secrets();
773        let (remote, vrf) = hex(&keystore.harvester_keys("main", "", 0).unwrap().unwrap());
774        assert_eq!((remote.as_str(), vrf.as_str()), (REMOTE, VRF));
775        // アカウントの鍵とは別
776        let (_, main) = keystore.private_key("main", "").unwrap();
777        assert_ne!(*main.to_hex(), *remote);
778
779        // テストネットの3番、作り直しの番号 1 の、リモートの鍵
780        let keys = keystore
781            .harvester_keys("テスト用 3", "", 1)
782            .unwrap()
783            .unwrap();
784        assert_eq!(
785            &*keys.signing.to_hex(),
786            "9115B2B24728D41247C50F2372EAA06197E5158415166BD459A4DDF60461B47D"
787        );
788        // 25 番目の単語が違えば、別の鍵
789        let keys = keystore
790            .harvester_keys("テスト用 3", "hidden", 1)
791            .unwrap()
792            .unwrap();
793        assert_eq!(
794            &*keys.signing.to_hex(),
795            "69D097D192C832194E6210E0E5260CD2E476FEF576B2CEA7F20844AD26C50C31"
796        );
797
798        // 秘密鍵のアカウントは、25 番目の単語を使わず、番号 0 として導出する
799        let (remote, vrf) = hex(&keystore
800            .harvester_keys("cold", "hidden", 0)
801            .unwrap()
802            .unwrap());
803        assert_eq!((remote.as_str(), vrf.as_str()), (REMOTE, VRF));
804    }
805
806    #[test]
807    fn seals_and_opens_with_a_passphrase() {
808        let random = [7; 48];
809        let sealed = keystore().seal(&mut Replay(&random), b"passphrase", 4);
810        assert!(sealed.starts_with(b"age-encryption.org/v1\n"));
811        let opened = Keystore::open(b"passphrase", &sealed).unwrap();
812        assert_eq!(*opened.to_text(), *keystore().to_text());
813        assert_eq!(
814            Keystore::open(b"wrong", &sealed).unwrap_err(),
815            KeystoreError::Age(AgeError::NoMatch)
816        );
817    }
818}