1use std::collections::{HashMap, HashSet};
17
18use heika_core::address::Address;
19use heika_core::key::{PrivateKey, PublicKey};
20use heika_core::network::NetworkIdentifier;
21use heika_transaction::{Body, KeyLink, LinkAction, Scanned};
22use heika_wallet::harvest_request;
23
24pub const ENCRYPTED_PAYLOAD_SIZE: usize =
26 harvest_request::MESSAGE_SIZE - harvest_request::MARKER.len();
27
28#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum LinkKind {
31 Remote,
33 Vrf,
35 Node,
37}
38
39#[derive(Clone, PartialEq, Eq, Debug)]
41pub struct Delegation {
42 pub height: u64,
44 pub main_account: PublicKey,
46 pub remote: PublicKey,
48 pub vrf: PublicKey,
50 pub encrypted_payload: [u8; ENCRYPTED_PAYLOAD_SIZE],
52 pub status: Status,
53}
54
55#[derive(Clone, PartialEq, Eq, Debug)]
56pub enum Status {
57 Active,
59 Inactive { mismatched: Vec<LinkKind> },
61 Unknown { unseen: Vec<LinkKind> },
63}
64
65#[derive(Clone, PartialEq, Eq, Debug)]
67pub struct Report {
68 pub delegations: Vec<Delegation>,
70 pub namespace_recipients: usize,
72 pub undecryptable: usize,
74}
75
76pub struct DelegationTracker<'a> {
78 node_private_key: &'a PrivateKey,
79 node_public_key: PublicKey,
80 recipient: Address,
81 delegations: Vec<Delegation>,
82 seen_payloads: HashSet<[u8; ENCRYPTED_PAYLOAD_SIZE]>,
83 links: HashMap<PublicKey, Links>,
84 namespace_recipients: usize,
85 undecryptable: usize,
86}
87
88#[derive(Default)]
90struct Links {
91 remote: Option<Option<PublicKey>>,
92 vrf: Option<Option<PublicKey>>,
93 node: Option<Option<PublicKey>>,
94}
95
96impl<'a> DelegationTracker<'a> {
97 pub fn new(node_private_key: &'a PrivateKey, network: NetworkIdentifier) -> Self {
99 let node_public_key = PublicKey::from_private_key(node_private_key);
100 Self {
101 node_private_key,
102 node_public_key,
103 recipient: harvest_request::recipient_address(&node_public_key, network),
104 delegations: Vec::new(),
105 seen_payloads: HashSet::new(),
106 links: HashMap::new(),
107 namespace_recipients: 0,
108 undecryptable: 0,
109 }
110 }
111
112 pub fn observe(&mut self, height: u64, scanned: &Scanned) {
114 let signer = scanned.signer_public_key;
115 match &scanned.body {
116 Body::AccountKeyLink(link) => {
117 self.links.entry(signer).or_default().remote = Some(linked(link))
118 }
119 Body::VrfKeyLink(link) => {
120 self.links.entry(signer).or_default().vrf = Some(linked(link))
121 }
122 Body::NodeKeyLink(link) => {
123 self.links.entry(signer).or_default().node = Some(linked(link))
124 }
125 Body::Transfer(transfer) => {
126 let message = transfer.message();
127 if !harvest_request::is_harvest_request(message) {
128 return;
129 }
130 let recipient = transfer.recipient_address().0;
131 if recipient[0] & 1 == 1 {
133 self.namespace_recipients += 1;
134 } else if recipient == self.recipient.0 {
135 self.request(height, signer, message);
136 }
137 }
138 _ => {}
140 }
141 }
142
143 fn request(&mut self, height: u64, main_account: PublicKey, message: &[u8]) {
144 let encrypted_payload: [u8; ENCRYPTED_PAYLOAD_SIZE] = message
145 [harvest_request::MARKER.len()..]
146 .try_into()
147 .expect("is_harvest_request checks the size");
148 if !self.seen_payloads.insert(encrypted_payload) {
149 return;
150 }
151 let Ok(keys) = harvest_request::decode(self.node_private_key, message) else {
153 self.undecryptable += 1;
154 return;
155 };
156 self.delegations.push(Delegation {
157 height,
158 main_account,
159 remote: PublicKey::from_private_key(&keys.signing),
160 vrf: PublicKey::from_private_key(&keys.vrf),
161 encrypted_payload,
162 status: Status::Unknown { unseen: Vec::new() },
164 });
165 }
166
167 pub fn finish(self) -> Report {
169 let no_links = Links::default();
170 let delegations = self
171 .delegations
172 .into_iter()
173 .map(|delegation| {
174 let links = self
175 .links
176 .get(&delegation.main_account)
177 .unwrap_or(&no_links);
178 let mut mismatched = Vec::new();
179 let mut unseen = Vec::new();
180 for (kind, last, expected) in [
181 (LinkKind::Remote, links.remote, delegation.remote),
182 (LinkKind::Vrf, links.vrf, delegation.vrf),
183 (LinkKind::Node, links.node, self.node_public_key),
184 ] {
185 match last {
186 None => unseen.push(kind),
187 Some(linked) if linked != Some(expected) => mismatched.push(kind),
188 Some(_) => {}
189 }
190 }
191 let status = if !mismatched.is_empty() {
192 Status::Inactive { mismatched }
193 } else if !unseen.is_empty() {
194 Status::Unknown { unseen }
195 } else {
196 Status::Active
197 };
198 Delegation {
199 status,
200 ..delegation
201 }
202 })
203 .collect();
204 Report {
205 delegations,
206 namespace_recipients: self.namespace_recipients,
207 undecryptable: self.undecryptable,
208 }
209 }
210}
211
212fn linked(link: &KeyLink) -> Option<PublicKey> {
214 match link.link_action {
215 LinkAction::Link => Some(link.linked_public_key),
216 LinkAction::Unlink => None,
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use std::collections::BTreeMap;
223
224 use heika_transaction::{
225 AliasAction, MosaicAlias, MosaicId, NamespaceId, Transfer, UnresolvedAddress,
226 };
227 use heika_wallet::harvest_request::HarvesterKeys;
228
229 use super::*;
230 use crate::testing::Replay;
231
232 const NETWORK: NetworkIdentifier = NetworkIdentifier::MAINNET;
233
234 fn private_key(seed: u8) -> PrivateKey {
235 PrivateKey::from_bytes(&[seed; 32])
236 }
237
238 fn public_key(seed: u8) -> PublicKey {
239 PublicKey::from_private_key(&private_key(seed))
240 }
241
242 fn scanned(signer: PublicKey, body: Body) -> Scanned {
243 Scanned {
244 signer_public_key: signer,
245 network: NETWORK,
246 aggregate_signer: None,
247 body,
248 }
249 }
250
251 fn transfer(recipient: [u8; 24], message: Vec<u8>) -> Body {
252 Body::Transfer(
253 Transfer::new(UnresolvedAddress(recipient), BTreeMap::new(), message).unwrap(),
254 )
255 }
256
257 fn message(node: &PrivateKey, remote: u8, vrf: u8, randomness: u8) -> Vec<u8> {
259 let keys = HarvesterKeys {
260 signing: private_key(remote),
261 vrf: private_key(vrf),
262 };
263 let randomness = [randomness; 32 + 12];
264 harvest_request::encode(
265 &mut Replay(&randomness),
266 &PublicKey::from_private_key(node),
267 &keys,
268 )
269 .unwrap()
270 }
271
272 fn request(node: &PrivateKey, main: u8, remote: u8, vrf: u8, randomness: u8) -> Scanned {
273 let recipient =
274 harvest_request::recipient_address(&PublicKey::from_private_key(node), NETWORK);
275 scanned(
276 public_key(main),
277 transfer(recipient.0, message(node, remote, vrf, randomness)),
278 )
279 }
280
281 fn link(signer: u8, body: fn(KeyLink) -> Body, linked: Option<PublicKey>) -> Scanned {
282 let link = KeyLink {
283 linked_public_key: linked.unwrap_or(public_key(0)),
284 link_action: if linked.is_some() {
285 LinkAction::Link
286 } else {
287 LinkAction::Unlink
288 },
289 };
290 scanned(public_key(signer), body(link))
291 }
292
293 fn links(main: u8, remote: u8, vrf: u8, node: PublicKey) -> [Scanned; 3] {
295 [
296 link(main, Body::AccountKeyLink, Some(public_key(remote))),
297 link(main, Body::VrfKeyLink, Some(public_key(vrf))),
298 link(main, Body::NodeKeyLink, Some(node)),
299 ]
300 }
301
302 #[test]
303 fn classifies_requests_by_the_last_links() {
304 let node = private_key(100);
305 let node_public = PublicKey::from_private_key(&node);
306 let mut tracker = DelegationTracker::new(&node, NETWORK);
307 for scanned in links(1, 11, 21, node_public) {
309 tracker.observe(10, &scanned);
310 }
311 tracker.observe(10, &request(&node, 1, 11, 21, 1));
312 for scanned in links(2, 12, 22, node_public) {
314 tracker.observe(11, &scanned);
315 }
316 tracker.observe(11, &request(&node, 2, 12, 22, 2));
317 tracker.observe(20, &link(2, Body::AccountKeyLink, Some(public_key(13))));
318 for scanned in links(3, 14, 24, node_public) {
320 tracker.observe(12, &scanned);
321 }
322 tracker.observe(12, &request(&node, 3, 14, 24, 3));
323 tracker.observe(21, &link(3, Body::NodeKeyLink, None));
324 tracker.observe(13, &request(&node, 4, 15, 25, 4));
326
327 let report = tracker.finish();
328 let statuses: Vec<_> = report
329 .delegations
330 .iter()
331 .map(|delegation| (delegation.height, delegation.status.clone()))
332 .collect();
333 assert_eq!(
334 statuses,
335 [
336 (10, Status::Active),
337 (
338 11,
339 Status::Inactive {
340 mismatched: vec![LinkKind::Remote]
341 }
342 ),
343 (
344 12,
345 Status::Inactive {
346 mismatched: vec![LinkKind::Node]
347 }
348 ),
349 (
350 13,
351 Status::Unknown {
352 unseen: vec![LinkKind::Remote, LinkKind::Vrf, LinkKind::Node]
353 }
354 ),
355 ]
356 );
357 let first = &report.delegations[0];
358 assert_eq!(first.main_account, public_key(1));
359 assert_eq!(first.remote, public_key(11));
360 assert_eq!(first.vrf, public_key(21));
361 assert_eq!(first.encrypted_payload[..], message(&node, 11, 21, 1)[8..]);
362 }
363
364 #[test]
365 fn a_node_link_to_another_node_makes_the_request_inactive() {
366 let node = private_key(100);
367 let mut tracker = DelegationTracker::new(&node, NETWORK);
368 for scanned in links(1, 11, 21, public_key(101)) {
369 tracker.observe(10, &scanned);
370 }
371 tracker.observe(10, &request(&node, 1, 11, 21, 1));
372 assert_eq!(
373 tracker.finish().delegations[0].status,
374 Status::Inactive {
375 mismatched: vec![LinkKind::Node]
376 }
377 );
378 }
379
380 #[test]
381 fn ignores_other_recipients_and_counts_what_it_cannot_use() {
382 let node = private_key(100);
383 let other = private_key(101);
384 let mut tracker = DelegationTracker::new(&node, NETWORK);
385 tracker.observe(10, &request(&other, 1, 11, 21, 1));
387 let recipient =
389 harvest_request::recipient_address(&PublicKey::from_private_key(&node), NETWORK);
390 tracker.observe(
391 10,
392 &scanned(public_key(1), transfer(recipient.0, b"hello".to_vec())),
393 );
394 let mut namespace = [0; 24];
396 namespace[0] = NETWORK.0 | 1;
397 tracker.observe(
398 10,
399 &scanned(
400 public_key(1),
401 transfer(namespace, message(&node, 11, 21, 2)),
402 ),
403 );
404 tracker.observe(
406 10,
407 &scanned(
408 public_key(1),
409 transfer(recipient.0, message(&other, 11, 21, 3)),
410 ),
411 );
412 tracker.observe(
414 10,
415 &scanned(
416 public_key(1),
417 Body::MosaicAlias(MosaicAlias {
418 namespace_id: NamespaceId(0x8000_0000_0000_0001),
419 mosaic_id: MosaicId(1),
420 alias_action: AliasAction::Link,
421 }),
422 ),
423 );
424
425 let report = tracker.finish();
426 assert!(report.delegations.is_empty());
427 assert_eq!(report.namespace_recipients, 1);
428 assert_eq!(report.undecryptable, 1);
429 }
430
431 #[test]
432 fn keeps_only_the_first_of_identical_requests() {
433 let node = private_key(100);
434 let mut tracker = DelegationTracker::new(&node, NETWORK);
435 tracker.observe(10, &request(&node, 1, 11, 21, 1));
436 tracker.observe(20, &request(&node, 1, 11, 21, 1));
437 tracker.observe(30, &request(&node, 1, 11, 21, 2));
439 let heights: Vec<_> = tracker
440 .finish()
441 .delegations
442 .iter()
443 .map(|delegation| delegation.height)
444 .collect();
445 assert_eq!(heights, [10, 30]);
446 }
447}