From 511305152ff95af4faf279e960b6bdcf65ab5a99 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Thu, 2 Jan 2020 20:05:17 -0500 Subject: [PATCH] Add a helper struct to allow a user to safely pass in an addr list --- lightning/src/ln/msgs.rs | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 8d23ac9a8..04bd85179 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -306,6 +306,56 @@ impl NetAddress { } } +/// A "set" of addresses which enforces that there can be only up to one of each net address type. +pub struct NetAddressSet { + v4: Option, + v6: Option, + onion2: Option, + onion3: Option, +} +impl NetAddressSet { + /// Creates a new, empty, NetAddressSet + pub fn new() -> Self { + NetAddressSet { v4: None, v6: None, onion2: None, onion3: None } + } + + /// Sets the IPv4 socket address in this set, overwriting any previous IPv4 socket address. + pub fn set_v4(&mut self, addr: [u8; 4], port: u16) { + self.v4 = Some(NetAddress::IPv4 { addr, port }); + } + /// Sets the IPv6 socket address in this set, overwriting any previous IPv6 socket address. + pub fn set_v6(&mut self, addr: [u8; 16], port: u16) { + self.v6 = Some(NetAddress::IPv6 { addr, port }); + } + /// Sets the Tor Onion v2 socket address in this set, overwriting any previous Tor Onion v2 + /// socket address. + pub fn set_onion_v2(&mut self, addr: [u8; 10], port: u16) { + self.onion2 = Some(NetAddress::OnionV2 { addr, port }); + } + /// Sets the Tor Onion v3 socket address in this set, overwriting any previous Tor Onion v3 + /// socket address. + pub fn set_onion_v3(&mut self, ed25519_pubkey: [u8; 32], checksum: u16, version: u8, port: u16) { + self.onion3 = Some(NetAddress::OnionV3 { ed25519_pubkey, checksum, version, port }); + } + + pub(crate) fn into_vec(mut self) -> Vec { + let mut res = Vec::new(); + if let Some(addr) = self.v4.take() { + res.push(addr); + } + if let Some(addr) = self.v6.take() { + res.push(addr); + } + if let Some(addr) = self.onion2.take() { + res.push(addr); + } + if let Some(addr) = self.onion3.take() { + res.push(addr); + } + res + } +} + impl Writeable for NetAddress { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { match self { -- 2.39.5