Skip to main content

heika_harvesting/
unlocked.rs

1//! ノードが引き受ける委任を、今のチェーンの状態で確かめる。catapult の harvesting 拡張の `UnlockedAccountsUpdater` に合わせている。
2//!
3//! 委任は、要求に入っていたリモートの鍵と VRF の鍵で表す。メインアカウントは要求の署名者ではなく、リモートアカウントの
4//! 状態のリンクから辿る。harvesters.dat には要求の中身しか残らないので、catapult もそうしている。
5//!
6//! 取り込めるのは、次がそろっているときだけ。
7//! - リモートの鍵のアカウントがリモートの種類で、メインアカウントにリンクしている
8//! - メインアカウントの AccountKeyLink がリモートの鍵、VrfKeyLink が VRF の鍵
9//! - メインアカウントの NodeKeyLink が、このノードの委任の鍵
10//!
11//! NodeKeyLink は合意のルールではなく、ノードの決まり。委任した人が選んだノードだけがハーベストし、
12//! 別のノードに乗り換えた人の古い要求でハーベストし続けないようにする。
13
14use heika_core::key::PublicKey;
15
16use crate::delegation::LinkKind;
17
18/// 確かめるのに要る、アカウントの状態の一部
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub struct AccountLinks {
21    /// リモートアカウントの種類か
22    pub remote: bool,
23    /// AccountKeyLink。リモートアカウントなら、メインアカウントの公開鍵
24    pub linked: Option<PublicKey>,
25    pub vrf: Option<PublicKey>,
26    pub node: Option<PublicKey>,
27    /// 今の重要度
28    pub importance: u64,
29}
30
31/// 委任を取り込めない理由
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub enum Rejection {
34    /// リモートの鍵のアカウントがないか、リモートの種類でないか、メインアカウントが見つからない
35    NoMainAccount,
36    /// メインアカウントのリンクが要求と合わない
37    Mismatched(Vec<LinkKind>),
38}
39
40/// 取り込める委任の、メインアカウントと重要度
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct Eligible {
43    pub main_account: PublicKey,
44    pub importance: u64,
45}
46
47/// `remote` と `vrf` の鍵の委任を、今の状態で取り込めるか。`lookup` は公開鍵のアカウントの状態を返す(なければ `None`)
48pub fn check(
49    remote: &PublicKey,
50    vrf: &PublicKey,
51    node_key: &PublicKey,
52    lookup: impl Fn(&PublicKey) -> Option<AccountLinks>,
53) -> Result<Eligible, Rejection> {
54    let remote_account = lookup(remote).ok_or(Rejection::NoMainAccount)?;
55    let main_account = match remote_account {
56        AccountLinks {
57            remote: true,
58            linked: Some(main),
59            ..
60        } => main,
61        _ => return Err(Rejection::NoMainAccount),
62    };
63    let main = lookup(&main_account).ok_or(Rejection::NoMainAccount)?;
64    let mismatched: Vec<LinkKind> = [
65        (LinkKind::Remote, main.linked, remote),
66        (LinkKind::Vrf, main.vrf, vrf),
67        (LinkKind::Node, main.node, node_key),
68    ]
69    .into_iter()
70    .filter(|(_, linked, expected)| *linked != Some(**expected))
71    .map(|(kind, _, _)| kind)
72    .collect();
73    if !mismatched.is_empty() {
74        return Err(Rejection::Mismatched(mismatched));
75    }
76    Ok(Eligible {
77        main_account,
78        importance: main.importance,
79    })
80}
81
82/// 取り込める委任から、重要度の大きい順に `max` 件を選ぶ。重要度が同じなら、先に並んでいた(先に届いた)ほうを残す。
83/// catapult の既定の `delegatePrioritizationPolicy = Importance` に合わせる
84pub fn choose<T>(mut eligible: Vec<(T, Eligible)>, max: usize) -> Vec<(T, Eligible)> {
85    eligible.sort_by_key(|(_, eligible)| std::cmp::Reverse(eligible.importance));
86    eligible.truncate(max);
87    eligible
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    fn key(byte: u8) -> PublicKey {
95        PublicKey([byte; 32])
96    }
97
98    /// メイン 1、リモート 2、VRF 3、ノード 4 の、そろった委任
99    fn accounts(main: AccountLinks) -> impl Fn(&PublicKey) -> Option<AccountLinks> {
100        move |public_key| match public_key.0[0] {
101            1 => Some(main),
102            2 => Some(AccountLinks {
103                remote: true,
104                linked: Some(key(1)),
105                ..Default::default()
106            }),
107            _ => None,
108        }
109    }
110
111    fn linked_main() -> AccountLinks {
112        AccountLinks {
113            remote: false,
114            linked: Some(key(2)),
115            vrf: Some(key(3)),
116            node: Some(key(4)),
117            importance: 10,
118        }
119    }
120
121    #[test]
122    fn accepts_when_all_three_links_match() {
123        let eligible = check(&key(2), &key(3), &key(4), accounts(linked_main())).unwrap();
124        assert_eq!(
125            eligible,
126            Eligible {
127                main_account: key(1),
128                importance: 10
129            }
130        );
131    }
132
133    #[test]
134    fn rejects_when_the_node_link_points_elsewhere() {
135        let main = AccountLinks {
136            node: Some(key(9)),
137            ..linked_main()
138        };
139        assert_eq!(
140            check(&key(2), &key(3), &key(4), accounts(main)),
141            Err(Rejection::Mismatched(vec![LinkKind::Node]))
142        );
143        let unlinked = AccountLinks {
144            node: None,
145            vrf: None,
146            ..linked_main()
147        };
148        assert_eq!(
149            check(&key(2), &key(3), &key(4), accounts(unlinked)),
150            Err(Rejection::Mismatched(vec![LinkKind::Vrf, LinkKind::Node]))
151        );
152    }
153
154    #[test]
155    fn rejects_without_a_linked_remote_account() {
156        // リモートの鍵のアカウントがない
157        assert_eq!(
158            check(&key(5), &key(3), &key(4), accounts(linked_main())),
159            Err(Rejection::NoMainAccount)
160        );
161        // メインアカウントの鍵を、リモートとして渡された
162        assert_eq!(
163            check(&key(1), &key(3), &key(4), accounts(linked_main())),
164            Err(Rejection::NoMainAccount)
165        );
166    }
167
168    #[test]
169    fn chooses_by_importance_keeping_arrival_order_on_ties() {
170        let eligible = |importance| Eligible {
171            main_account: key(1),
172            importance,
173        };
174        let chosen = choose(
175            vec![
176                ("a", eligible(5)),
177                ("b", eligible(9)),
178                ("c", eligible(5)),
179                ("d", eligible(1)),
180            ],
181            3,
182        );
183        assert_eq!(
184            chosen.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
185            ["b", "a", "c"]
186        );
187    }
188}