1use crate::proto_serde::ProtoSerde;
2use crate::structs::{ErrorInfo, Hash, NetworkEnvironment, NodeMetadata, PartitionInfo, PeerNodeInfo, PublicKey, TransportInfo};
3use crate::util::xor_distance::xorfc_hash;
4use crate::{HashClear, RgResult, SafeOption};
5
6impl HashClear for NodeMetadata {
7 fn hash_clear(&mut self) {}
8}
9
10impl NodeMetadata {
11
12 pub fn nat_traversal_required(&self) -> bool {
13 self.transport_info
14 .as_ref()
15 .and_then(|t| t.nat_restricted)
16 .unwrap_or(false)
17 }
18 pub fn port_or(&self, network: NetworkEnvironment) -> u16 {
19 self.transport_info.as_ref()
20 .and_then(|ti| ti.port_offset)
21 .unwrap_or(network.default_port_offset() as i64) as u16
22 }
23 pub fn public_key_bytes(&self) -> Result<Vec<u8>, ErrorInfo> {
24 let x = self.public_key.safe_get()?;
25 let y= x.bytes.safe_get()?.value.clone();
26 Ok(y)
27 }
28
29 pub fn long_identifier(&self) -> String {
30 let pk = self.public_key.clone().map(|p| p.hex()).unwrap_or("".to_string());
31 let info = self.transport_info.clone().expect("ti");
32 let ip = info.external_host.or(info.external_ipv4).expect("ip");
33 format!("node_name {} public key {} ip {}",
34 self.node_name.clone().unwrap_or("none".to_string()), pk, ip,
35 )
36 }
37
38 pub fn external_address(&self) -> RgResult<String> {
39 self.transport_info.safe_get_msg("Missing transport info")
40 .and_then(|t| t.external_address())
41 }
42
43 pub fn tx_in_range(&self, h: &Hash) -> bool {
44 self.hash_in_range(h, |i| i.transaction_hash)
45 }
46
47 pub fn hash_in_range(&self, h: &Hash, f: fn(&PartitionInfo) -> Option<i64>) -> bool {
48 if let Some(d) = self.partition_info.as_ref().and_then(f) {
49 let pk = self.public_key.as_ref().expect("pk");
50 xorfc_hash(h, pk) < d
51 } else {
52 true
53 }
54 }
55
56}
57
58
59impl PeerNodeInfo {
60
61 pub fn nmd_pk(&self) -> Option<PublicKey> {
62 if let Some(t) = &self.latest_node_transaction {
63 if let Ok(n) = t.node_metadata() {
64 if let Some(p) = n.public_key {
65 return Some(p);
66 }
67 }
68 }
69 None
70 }
71 pub fn public_keys(&self) -> Vec<PublicKey> {
72 let mut res = vec![];
73 if let Some(t) = &self.latest_node_transaction {
74 if let Ok(p) = &t.peer_data() {
75 for n in &p.node_metadata {
76 if let Some(p) = &n.public_key {
77 res.push(p.clone());
78 }
79 }
80 }
81 }
82
83 if let Some(pk) = self.nmd_pk() {
84 res.push(pk.clone());
85 }
86
87 res
88 }
89}
90
91impl TransportInfo {
92 fn external_address(&self) -> RgResult<String> {
93 self.external_host.as_ref().or(self.external_ipv4.as_ref()).safe_get_msg("No external address")
94 .cloned()
95 .cloned()
96 }
97}