Skip to content

Commit 41ada11

Browse files
committed
Add a helper struct to allow a user to safely pass in an addr list
1 parent 956a7a3 commit 41ada11

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

lightning/src/ln/msgs.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,58 @@ impl NetAddress {
522522
}
523523
}
524524

525+
/// A "set" of addresses which enforces that there can be only up to one of each net address type.
526+
pub struct NetAddressSet {
527+
v4: Option<NetAddress>,
528+
v6: Option<NetAddress>,
529+
onion2: Option<NetAddress>,
530+
onion3: Option<NetAddress>,
531+
}
532+
impl NetAddressSet {
533+
/// Creates a new, empty, NetAddressSet
534+
pub fn new() -> Self {
535+
NetAddressSet { v4: None, v6: None, onion2: None, onion3: None }
536+
}
537+
538+
/// Sets the IPv4 socket address in this set, overwriting any previous IPv4 socket addresses
539+
/// (if any).
540+
pub fn set_v4(&mut self, addr: [u8; 4], port: u16) {
541+
self.v4 = Some(NetAddress::IPv4 { addr, port });
542+
}
543+
/// Sets the IPv6 socket address in this set, overwriting any previous IPv4 socket addresses
544+
/// (if any).
545+
pub fn set_v6(&mut self, addr: [u8; 16], port: u16) {
546+
self.v6 = Some(NetAddress::IPv6 { addr, port });
547+
}
548+
/// Sets the Tor Onion v2 socket address in this set, overwriting any previous IPv4 socket
549+
/// address (if any).
550+
pub fn set_onion_v2(&mut self, addr: [u8; 10], port: u16) {
551+
self.onion2 = Some(NetAddress::OnionV2 { addr, port });
552+
}
553+
/// Sets the Tor Onion v3 socket address in this set, overwriting any previous IPv4 socket
554+
/// address (if any).
555+
pub fn set_onion_v3(&mut self, ed25519_pubkey: [u8; 32], checksum: u16, version: u8, port: u16) {
556+
self.onion3 = Some(NetAddress::OnionV3 { ed25519_pubkey, checksum, version, port });
557+
}
558+
559+
pub(crate) fn to_vec(mut self) -> Vec<NetAddress> {
560+
let mut res = Vec::new();
561+
if let Some(addr) = self.v4.take() {
562+
res.push(addr);
563+
}
564+
if let Some(addr) = self.v6.take() {
565+
res.push(addr);
566+
}
567+
if let Some(addr) = self.onion2.take() {
568+
res.push(addr);
569+
}
570+
if let Some(addr) = self.onion3.take() {
571+
res.push(addr);
572+
}
573+
res
574+
}
575+
}
576+
525577
impl Writeable for NetAddress {
526578
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
527579
match self {

0 commit comments

Comments
 (0)