Skip to main content

heika_node/
delegated.rs

1//! ほかの人の委任ハーベストを引き受ける。catapult の transfer プラグインの `TransferMessageObserver` と、harvesting 拡張の
2//! `UnlockedAccountsUpdater` と `UnlockedAccountsStorage` に合わせている。
3//!
4//! - 委任の要求は、委任の鍵のアドレスあてのメッセージで届く。catapult と同じく、先端に足したブロックを高さの順に読む。
5//!   委任する人を、確定まで待たせないため
6//! - 引き受けるかどうかは、そのときのチェーンの状態のリンクで決める([`heika_harvesting::unlocked`])。ブロックを足すたびに、
7//!   引き受けているものも確かめ直し、合わなくなったものは外す。リンクと要求の入ったブロックが巻き戻れば、リンクも
8//!   なくなるので、ここで外れる。枝を取り替えたら、分かれ目から読み直す
9//! - 取り込める委任は、暗号化したまま `harvesters.dat`(catapult と同じ形)に、どこまで読んだかは `harvesters.height`
10//!   にしまう。上限を超えた分も残しておき、空きができたら重要度の大きい順に使う。初めて動かしたときは、
11//!   それより前の要求は読まない
12//! - 届いた要求ごとに、引き受けたか、なぜ引き受けなかったかを覚えておき、API で委任した人に見せる。止めても消えないように
13//!   `delegations.yaml` にしまい、起動したら読み戻す
14
15use std::path::{Path, PathBuf};
16
17use heika_block::Block;
18use heika_core::address::Address;
19use heika_core::key::{PrivateKey, PublicKey};
20use heika_core::network::NetworkIdentifier;
21use heika_core::patricia::SubCache;
22use heika_harvesting::delegation::{DelegationTracker, ENCRYPTED_PAYLOAD_SIZE, LinkKind};
23use heika_harvesting::unlocked::{self, AccountLinks, Rejection};
24use heika_state_transition::account::AccountType;
25use heika_state_transition::executor::persist::{decode_account_row, row_key};
26use heika_store_redb::Db;
27use heika_wallet::harvest_request;
28use serde::{Deserialize, Serialize};
29
30use crate::driver::NodeError;
31use crate::harvesters::KeyPair;
32
33type Payload = [u8; ENCRYPTED_PAYLOAD_SIZE];
34
35/// 覚えておく、引き受けなかった要求の数
36const MAX_REJECTED: usize = 64;
37
38/// 取り込める委任1件
39struct Candidate {
40    payload: Payload,
41    signing: PrivateKey,
42    vrf: PrivateKey,
43    /// 要求が入っていたブロックの高さ。`harvesters.dat` から読んだものはわからない
44    height: Option<u64>,
45}
46
47/// 委任の今の様子
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum DelegationState {
50    /// 引き受けて、ハーベストしている
51    Accepted,
52    /// 取り込めるが、上限を超えているので空きを待っている
53    Waiting,
54    /// 引き受けなかった。わけを添える
55    Rejected(String),
56}
57
58/// 届いた委任1件の様子
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct DelegationStatus {
61    /// メインアカウント。リンクから辿れなかったときは、要求を送った人
62    pub main_account: Option<PublicKey>,
63    /// 要求に入っていたリモートの鍵
64    pub remote: PublicKey,
65    /// 要求が入っていたブロックの高さ
66    pub height: Option<u64>,
67    pub state: DelegationState,
68}
69
70/// `delegations.yaml` の1件。[`DelegationStatus`] を、鍵を16進にして書く
71#[derive(Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73struct SavedStatus {
74    main_account: Option<String>,
75    remote: String,
76    height: Option<u64>,
77    state: SavedState,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    reason: Option<String>,
80}
81
82#[derive(Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84enum SavedState {
85    Accepted,
86    Waiting,
87    Rejected,
88}
89
90impl From<&DelegationStatus> for SavedStatus {
91    fn from(status: &DelegationStatus) -> Self {
92        let (state, reason) = match &status.state {
93            DelegationState::Accepted => (SavedState::Accepted, None),
94            DelegationState::Waiting => (SavedState::Waiting, None),
95            DelegationState::Rejected(reason) => (SavedState::Rejected, Some(reason.clone())),
96        };
97        Self {
98            main_account: status.main_account.map(|key| key.to_string()),
99            remote: status.remote.to_string(),
100            height: status.height,
101            state,
102            reason,
103        }
104    }
105}
106
107impl SavedStatus {
108    fn restore(self) -> Option<DelegationStatus> {
109        let main_account = match self.main_account {
110            Some(text) => Some(text.parse().ok()?),
111            None => None,
112        };
113        Some(DelegationStatus {
114            main_account,
115            remote: self.remote.parse().ok()?,
116            height: self.height,
117            state: match self.state {
118                SavedState::Accepted => DelegationState::Accepted,
119                SavedState::Waiting => DelegationState::Waiting,
120                SavedState::Rejected => DelegationState::Rejected(self.reason.unwrap_or_default()),
121            },
122        })
123    }
124}
125
126/// 委任の引き受け
127pub struct Delegated {
128    key: PrivateKey,
129    public_key: PublicKey,
130    network: NetworkIdentifier,
131    max: usize,
132    file: PathBuf,
133    height_file: PathBuf,
134    status_file: PathBuf,
135    /// 取り込める委任。重要度の大きい順で、先頭の `max` 件でハーベストする
136    candidates: Vec<Candidate>,
137    /// 届いた要求ごとの様子。取り込めるものと、最近の引き受けなかったもの
138    statuses: Vec<DelegationStatus>,
139    /// 要求を読み終えた高さ
140    through: u64,
141}
142
143/// ブロックを読んだ結果。`changed` なら、ハーベストする鍵を入れ替える
144pub struct Progress {
145    pub changed: bool,
146    pub message: Option<String>,
147}
148
149fn decrypt(key: &PrivateKey, payload: &Payload, height: Option<u64>) -> Option<Candidate> {
150    let message = [&harvest_request::MARKER[..], payload].concat();
151    let keys = harvest_request::decode(key, &message).ok()?;
152    Some(Candidate {
153        payload: *payload,
154        signing: keys.signing,
155        vrf: keys.vrf,
156        height,
157    })
158}
159
160/// catapult での要求の識別子(暗号化した中身の先頭の32バイト、使い捨ての公開鍵)
161fn identifier(payload: &Payload) -> &[u8] {
162    &payload[..32]
163}
164
165fn reason(rejection: &Rejection) -> String {
166    match rejection {
167        Rejection::NoMainAccount => {
168            "リモートの鍵のアカウントが、メインアカウントにリンクしていません(AccountKeyLink がまだブロックに入っていないか、外した)".to_owned()
169        }
170        Rejection::Mismatched(kinds) => {
171            let names: Vec<&str> = kinds
172                .iter()
173                .map(|kind| match kind {
174                    LinkKind::Remote => "AccountKeyLink がリモートの鍵",
175                    LinkKind::Vrf => "VrfKeyLink が VRF の鍵",
176                    LinkKind::Node => "NodeKeyLink がこのノードの委任の鍵",
177                })
178                .collect();
179            format!("メインアカウントの {}になっていません", names.join("、"))
180        }
181    }
182}
183
184impl Delegated {
185    /// `data_directory` の `harvesters.dat`、`harvesters.height`、`delegations.yaml` を読む。なければ、高さ `tip` より後の
186    /// 要求を読む
187    pub fn open(
188        key: PrivateKey,
189        network: NetworkIdentifier,
190        max: usize,
191        data_directory: &Path,
192        tip: u64,
193    ) -> Result<Self, NodeError> {
194        let file = data_directory.join("harvesters.dat");
195        let height_file = data_directory.join("harvesters.height");
196        let status_file = data_directory.join("delegations.yaml");
197        let mut candidates = Vec::new();
198        match std::fs::read(&file) {
199            Ok(bytes) => {
200                if !bytes.len().is_multiple_of(ENCRYPTED_PAYLOAD_SIZE) {
201                    return Err(format!(
202                        "{} が壊れています(大きさ {})",
203                        file.display(),
204                        bytes.len()
205                    )
206                    .into());
207                }
208                for chunk in bytes.chunks(ENCRYPTED_PAYLOAD_SIZE) {
209                    let payload: Payload = chunk.try_into().expect("chunks of the payload size");
210                    match decrypt(&key, &payload, None) {
211                        Some(entry) => candidates.push(entry),
212                        // 委任の鍵を替えたときなど。catapult は起動しないが、ここでは外して続ける
213                        None => eprintln!(
214                            "警告: {} に、委任の鍵で復号できない委任があったので外します",
215                            file.display()
216                        ),
217                    }
218                }
219            }
220            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
221            Err(error) => return Err(format!("{} を読めません: {error}", file.display()).into()),
222        }
223        let through = match std::fs::read_to_string(&height_file) {
224            Ok(text) => text
225                .trim()
226                .parse()
227                .map_err(|_| format!("{} が読めません", height_file.display()))?,
228            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
229                println!("委任の要求は、高さ {tip} より後に届いたものから読みます");
230                tip
231            }
232            Err(error) => {
233                return Err(format!("{} を読めません: {error}", height_file.display()).into());
234            }
235        };
236        let statuses = read_statuses(&status_file);
237        // `harvesters.dat` には高さがないので、しまった様子から戻す
238        for entry in &mut candidates {
239            let remote = PublicKey::from_private_key(&entry.signing);
240            entry.height = statuses
241                .iter()
242                .find(|status| status.remote == remote)
243                .and_then(|status| status.height);
244        }
245        let public_key = PublicKey::from_private_key(&key);
246        println!(
247            "委任を引き受けます(上限 {max} 件、要求の届け先 {})",
248            harvest_request::recipient_address(&public_key, network)
249        );
250        Ok(Self {
251            key,
252            public_key,
253            network,
254            max,
255            file,
256            height_file,
257            status_file,
258            candidates,
259            statuses,
260            through,
261        })
262    }
263
264    /// 委任の鍵の公開鍵。委任する人は、NodeKeyLink をこれに向け、要求をこれのアドレスに送る
265    pub fn public_key(&self) -> PublicKey {
266        self.public_key
267    }
268
269    /// 引き受けている委任の鍵の組
270    pub fn keys(&self) -> Vec<KeyPair> {
271        let copy = |key: &PrivateKey| PrivateKey::from_bytes(key.as_bytes());
272        self.candidates
273            .iter()
274            .take(self.max)
275            .map(|entry| (copy(&entry.signing), copy(&entry.vrf)))
276            .collect()
277    }
278
279    /// 届いた要求ごとの様子。引き受けているもの、待っているもの、最近の引き受けなかったものの順
280    pub fn statuses(&self) -> Vec<DelegationStatus> {
281        self.statuses.clone()
282    }
283
284    /// 枝を取り替えた。分かれ目 `common` より上の要求は、新しい枝で読み直す
285    pub fn rewind(&mut self, common: u64) {
286        self.through = self.through.min(common);
287    }
288
289    /// 先端が `tip` まで進んだ。新しい要求を読み、取り込めるものと合わせて、今の状態で確かめ直す
290    pub fn advance(&mut self, db: &Db, tip: u64) -> Result<Progress, NodeError> {
291        let mut tracker = DelegationTracker::new(&self.key, self.network);
292        let mut missing = 0;
293        for height in self.through + 1..=tip {
294            let Some(bytes) = db.block(height)? else {
295                missing += 1;
296                continue;
297            };
298            let block = Block::from_bytes(&bytes)
299                .map_err(|error| format!("高さ {height} のブロックが読めません: {error}"))?;
300            for transaction in block.transactions() {
301                // チェーンが認めたトランザクションなので、読めない種類は委任の要求ではない
302                for scanned in heika_transaction::scan(transaction).unwrap_or_default() {
303                    tracker.observe(height, &scanned);
304                }
305            }
306        }
307        let report = tracker.finish();
308        let previous: Vec<Payload> = self
309            .candidates
310            .iter()
311            .take(self.max)
312            .map(|entry| entry.payload)
313            .collect();
314        let mut pool: Vec<(Candidate, Option<PublicKey>)> = std::mem::take(&mut self.candidates)
315            .into_iter()
316            .map(|entry| (entry, None))
317            .collect();
318        for delegation in report.delegations {
319            let known = pool.iter().any(|(entry, _)| {
320                identifier(&entry.payload) == identifier(&delegation.encrypted_payload)
321            });
322            if !known
323                && let Some(entry) = decrypt(
324                    &self.key,
325                    &delegation.encrypted_payload,
326                    Some(delegation.height),
327                )
328            {
329                pool.push((entry, Some(delegation.main_account)));
330            }
331        }
332
333        let lookup = |public_key: &PublicKey| self.account_links(db, public_key);
334        let mut eligible = Vec::new();
335        let mut rejected = Vec::new();
336        for (entry, sender) in pool {
337            let remote = PublicKey::from_private_key(&entry.signing);
338            let vrf = PublicKey::from_private_key(&entry.vrf);
339            match unlocked::check(&remote, &vrf, &self.public_key, lookup) {
340                Ok(found) => eligible.push((entry, found)),
341                Err(rejection) => rejected.push(DelegationStatus {
342                    // 前に引き受けていたものなら、そのときに辿れたメインアカウントを引き継ぐ
343                    main_account: sender.or_else(|| {
344                        self.statuses
345                            .iter()
346                            .find(|status| status.remote == remote)
347                            .and_then(|status| status.main_account)
348                    }),
349                    remote,
350                    height: entry.height,
351                    state: DelegationState::Rejected(reason(&rejection)),
352                }),
353            }
354        }
355        let ordered = unlocked::choose(eligible, usize::MAX);
356        let mut statuses: Vec<DelegationStatus> = ordered
357            .iter()
358            .enumerate()
359            .map(|(index, (entry, found))| DelegationStatus {
360                main_account: Some(found.main_account),
361                remote: PublicKey::from_private_key(&entry.signing),
362                height: entry.height,
363                state: if index < self.max {
364                    DelegationState::Accepted
365                } else {
366                    DelegationState::Waiting
367                },
368            })
369            .collect();
370        // 前に引き受けなかったもので、今回また読んだものでないものも、しばらく覚えておく
371        let old_rejected: Vec<DelegationStatus> = self
372            .statuses
373            .iter()
374            .filter(|status| matches!(status.state, DelegationState::Rejected(_)))
375            .filter(|old| !rejected.iter().any(|new| new.remote == old.remote))
376            .cloned()
377            .collect();
378        // 取り込めるようになったリモートの鍵は、引き受けなかったものから外す
379        let usable: Vec<PublicKey> = statuses.iter().map(|status| status.remote).collect();
380        statuses.extend(
381            rejected
382                .into_iter()
383                .chain(old_rejected)
384                .filter(|status| !usable.contains(&status.remote))
385                .take(MAX_REJECTED),
386        );
387        self.candidates = ordered.into_iter().map(|(entry, _)| entry).collect();
388        self.statuses = statuses;
389        self.through = tip;
390
391        let now: Vec<Payload> = self
392            .candidates
393            .iter()
394            .take(self.max)
395            .map(|entry| entry.payload)
396            .collect();
397        let changed = now != previous;
398        self.save()?;
399        self.save_statuses()?;
400        std::fs::write(&self.height_file, format!("{tip}\n"))
401            .map_err(|error| format!("{} を書けません: {error}", self.height_file.display()))?;
402        let message = (changed || missing > 0).then(|| {
403            let mut text = format!("委任 {} 件でハーベストします", now.len());
404            let waiting = self.candidates.len().saturating_sub(self.max);
405            if waiting > 0 {
406                text.push_str(&format!("(上限を超えて待っているもの {waiting} 件)"));
407            }
408            if missing > 0 {
409                text.push_str(&format!(
410                    "(ブロックのない高さ {missing} か所の要求は読めませんでした)"
411                ));
412            }
413            text
414        });
415        Ok(Progress { changed, message })
416    }
417
418    fn account_links(&self, db: &Db, public_key: &PublicKey) -> Option<AccountLinks> {
419        let address = Address::from_public_key(public_key, self.network);
420        let row = db
421            .state_row(&row_key(SubCache::AccountState, &address.0))
422            .ok()??;
423        let account = decode_account_row(&row).ok()?;
424        Some(AccountLinks {
425            remote: account.account_type == AccountType::Remote,
426            linked: account.linked.map(PublicKey),
427            vrf: account.vrf.map(PublicKey),
428            node: account.node.map(PublicKey),
429            importance: account.snapshots[0].importance,
430        })
431    }
432
433    fn save_statuses(&self) -> Result<(), NodeError> {
434        let saved: Vec<SavedStatus> = self.statuses.iter().map(SavedStatus::from).collect();
435        let text = serde_norway::to_string(&saved)
436            .map_err(|error| format!("委任の様子を書き出せません: {error}"))?;
437        write_replacing(&self.status_file, text.as_bytes())
438    }
439
440    fn save(&self) -> Result<(), NodeError> {
441        let bytes: Vec<u8> = self
442            .candidates
443            .iter()
444            .flat_map(|entry| entry.payload)
445            .collect();
446        write_replacing(&self.file, &bytes)
447    }
448}
449
450/// 書きかけで落ちても壊さないように、別のファイルに書いてから置き換える
451fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), NodeError> {
452    let mut temporary = path.as_os_str().to_owned();
453    temporary.push(".new");
454    std::fs::write(&temporary, bytes)
455        .and_then(|()| std::fs::rename(&temporary, path))
456        .map_err(|error| format!("{} を書けません: {error}", path.display()).into())
457}
458
459/// しまった様子。見せるためだけのものなので、なかったり読めなかったりしたら、空から始める(次にブロックを足したときに
460/// 作り直す。引き受けなかったものは、そこで忘れる)
461fn read_statuses(path: &Path) -> Vec<DelegationStatus> {
462    let text = match std::fs::read_to_string(path) {
463        Ok(text) => text,
464        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
465        Err(error) => {
466            eprintln!("警告: {} を読めません: {error}", path.display());
467            return Vec::new();
468        }
469    };
470    match serde_norway::from_str::<Vec<SavedStatus>>(&text) {
471        Ok(saved) => saved.into_iter().filter_map(SavedStatus::restore).collect(),
472        Err(error) => {
473            eprintln!(
474                "警告: {} が読めないので、委任の様子を空から始めます: {error}",
475                path.display()
476            );
477            Vec::new()
478        }
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use heika_wallet::harvest_request::HarvesterKeys;
485
486    use super::*;
487
488    /// 決まったバイト列を返す乱数
489    struct Replay<'a>(&'a [u8]);
490
491    impl rand_core::TryRng for Replay<'_> {
492        type Error = core::convert::Infallible;
493
494        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
495            unimplemented!("only fill_bytes is used")
496        }
497
498        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
499            unimplemented!("only fill_bytes is used")
500        }
501
502        fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
503            let (head, rest) = self.0.split_at(dst.len());
504            dst.copy_from_slice(head);
505            self.0 = rest;
506            Ok(())
507        }
508    }
509
510    impl rand_core::TryCryptoRng for Replay<'_> {}
511
512    fn key(byte: u8) -> PrivateKey {
513        PrivateKey::from_bytes(&[byte; 32])
514    }
515
516    #[test]
517    fn statuses_survive_a_restart() {
518        let directory =
519            std::env::temp_dir().join(format!("heika-delegated-{}", std::process::id()));
520        std::fs::create_dir_all(&directory).unwrap();
521        let node = key(1);
522        let keys = HarvesterKeys {
523            signing: key(2),
524            vrf: key(3),
525        };
526        let message = harvest_request::encode(
527            &mut Replay(&[4; 64]),
528            &PublicKey::from_private_key(&node),
529            &keys,
530        )
531        .unwrap();
532        std::fs::write(
533            directory.join("harvesters.dat"),
534            &message[harvest_request::MARKER.len()..],
535        )
536        .unwrap();
537        std::fs::write(directory.join("harvesters.height"), "10\n").unwrap();
538        let open = || {
539            Delegated::open(
540                PrivateKey::from_bytes(node.as_bytes()),
541                NetworkIdentifier::TESTNET,
542                5,
543                &directory,
544                10,
545            )
546            .unwrap()
547        };
548
549        // しまった様子がなければ、空から始める
550        let mut delegated = open();
551        assert!(delegated.statuses().is_empty());
552        assert_eq!(delegated.candidates[0].height, None);
553        let remote = PublicKey::from_private_key(&keys.signing);
554        delegated.statuses = vec![
555            DelegationStatus {
556                main_account: Some(PublicKey::from_private_key(&key(5))),
557                remote,
558                height: Some(7),
559                state: DelegationState::Accepted,
560            },
561            DelegationStatus {
562                main_account: None,
563                remote: PublicKey::from_private_key(&key(6)),
564                height: Some(8),
565                state: DelegationState::Rejected("わけ".to_owned()),
566            },
567        ];
568        delegated.save_statuses().unwrap();
569
570        // 起動し直しても、様子と、要求が入っていた高さが戻る
571        let reopened = open();
572        assert_eq!(reopened.statuses(), delegated.statuses());
573        assert_eq!(reopened.candidates[0].height, Some(7));
574
575        // 読めなければ、空から始める(委任そのものは harvesters.dat から読む)
576        std::fs::write(directory.join("delegations.yaml"), "- [壊れている").unwrap();
577        let broken = open();
578        assert!(broken.statuses().is_empty());
579        assert_eq!(broken.keys().len(), 1);
580        std::fs::remove_dir_all(&directory).unwrap();
581    }
582}