]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Add genesis block hash to NetworkGraph
authorbmancini55 <bmancini@gmail.com>
Sun, 29 Nov 2020 20:20:35 +0000 (15:20 -0500)
committerbmancini55 <bmancini@gmail.com>
Wed, 9 Dec 2020 20:02:32 +0000 (15:02 -0500)
This changes adds the genesis block hash as a BlockHash to the
NetworkGraph struct. Making the NetworkGraph aware allows the message
handler to validate the chain_hash for received messages. This change
also adds the hash value to the Writeable and Readable methods.

fuzz/src/full_stack.rs
fuzz/src/router.rs
lightning/src/ln/functional_test_utils.rs
lightning/src/routing/network_graph.rs
lightning/src/routing/router.rs

index 3aeb3d233b0b19d62196466c3de3f2a23dfe98dd..6375d0765d76a3d4a7940d4781ef2b574b90b564 100644 (file)
@@ -19,6 +19,7 @@ use bitcoin::blockdata::script::{Builder, Script};
 use bitcoin::blockdata::opcodes;
 use bitcoin::consensus::encode::deserialize;
 use bitcoin::network::constants::Network;
+use bitcoin::blockdata::constants::genesis_block;
 
 use bitcoin::hashes::Hash as TraitImport;
 use bitcoin::hashes::HashEngine as TraitImportEngine;
@@ -343,7 +344,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
        config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
        let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0));
        let our_id = PublicKey::from_secret_key(&Secp256k1::signing_only(), &keys_manager.get_node_secret());
-       let net_graph_msg_handler = Arc::new(NetGraphMsgHandler::new(None, Arc::clone(&logger)));
+       let net_graph_msg_handler = Arc::new(NetGraphMsgHandler::new(genesis_block(Network::Bitcoin).header.block_hash(), None, Arc::clone(&logger)));
 
        let peers = RefCell::new([false; 256]);
        let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler {
@@ -609,7 +610,7 @@ mod tests {
                // What each byte represents is broken down below, and then everything is concatenated into
                // one large test at the end (you want %s/ -.*//g %s/\n\| \|\t\|\///g).
 
-               // Following BOLT 8, lightning message on the wire are: 2-byte encrypted message length + 
+               // Following BOLT 8, lightning message on the wire are: 2-byte encrypted message length +
                // 16-byte MAC of the encrypted message length + encrypted Lightning message + 16-byte MAC
                // of the Lightning message
                // I.e 2nd inbound read, len 18 : 0006 (encrypted message length) + 03000000000000000000000000000000 (MAC of the encrypted message length)
index 671adcfda51ff48d3d1f6f18db8f5cda01426a14..4eb85714f3e22a813393a6c47a1e50bab7caaaf9 100644 (file)
@@ -21,6 +21,8 @@ use lightning::util::ser::Readable;
 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
 
 use bitcoin::secp256k1::key::PublicKey;
+use bitcoin::network::constants::Network;
+use bitcoin::blockdata::constants::genesis_block;
 
 use utils::test_logger;
 
@@ -155,7 +157,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
        let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
 
        let our_pubkey = get_pubkey!();
-       let mut net_graph = NetworkGraph::new();
+       let mut net_graph = NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash());
 
        let mut node_pks = HashSet::new();
        let mut scid = 42;
index 8ff3d4eacf85c3972d7dd322747570b9c66779fc..d54045f8e619d7d3075482d7e893279ca04f7686 100644 (file)
@@ -1171,7 +1171,7 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeC
        let payment_count = Rc::new(RefCell::new(0));
 
        for i in 0..node_count {
-               let net_graph_msg_handler = NetGraphMsgHandler::new(None, cfgs[i].logger);
+               let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].chain_source.genesis_hash, None, cfgs[i].logger);
                nodes.push(Node{ chain_source: cfgs[i].chain_source,
                                 tx_broadcaster: cfgs[i].tx_broadcaster, chain_monitor: &cfgs[i].chain_monitor,
                                 keys_manager: &cfgs[i].keys_manager, node: &chan_mgrs[i], net_graph_msg_handler,
index b0cfb982e086e1d51250981a045658092792f0de..bce9633012c6a21a2a35e16663add90a1b4c36a3 100644 (file)
@@ -55,6 +55,7 @@ const MAX_REPLY_CHANNEL_RANGE_PER_QUERY: usize = 250;
 /// Represents the network as nodes and channels between them
 #[derive(PartialEq)]
 pub struct NetworkGraph {
+       genesis_hash: BlockHash,
        channels: BTreeMap<u64, ChannelInfo>,
        nodes: BTreeMap<PublicKey, NodeInfo>,
 }
@@ -87,13 +88,10 @@ impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access
        /// Chain monitor is used to make sure announced channels exist on-chain,
        /// channel data is correct, and that the announcement is signed with
        /// channel owners' keys.
-       pub fn new(chain_access: Option<C>, logger: L) -> Self {
+       pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
                NetGraphMsgHandler {
                        secp_ctx: Secp256k1::verification_only(),
-                       network_graph: RwLock::new(NetworkGraph {
-                               channels: BTreeMap::new(),
-                               nodes: BTreeMap::new(),
-                       }),
+                       network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
                        full_syncs_requested: AtomicUsize::new(0),
                        chain_access,
                        pending_events: Mutex::new(vec![]),
@@ -903,6 +901,7 @@ impl Readable for NodeInfo {
 
 impl Writeable for NetworkGraph {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+               self.genesis_hash.write(writer)?;
                (self.channels.len() as u64).write(writer)?;
                for (ref chan_id, ref chan_info) in self.channels.iter() {
                        (*chan_id).write(writer)?;
@@ -919,6 +918,7 @@ impl Writeable for NetworkGraph {
 
 impl Readable for NetworkGraph {
        fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
+               let genesis_hash: BlockHash = Readable::read(reader)?;
                let channels_count: u64 = Readable::read(reader)?;
                let mut channels = BTreeMap::new();
                for _ in 0..channels_count {
@@ -934,6 +934,7 @@ impl Readable for NetworkGraph {
                        nodes.insert(node_id, node_info);
                }
                Ok(NetworkGraph {
+                       genesis_hash,
                        channels,
                        nodes,
                })
@@ -979,8 +980,9 @@ impl NetworkGraph {
        }
 
        /// Creates a new, empty, network graph.
-       pub fn new() -> NetworkGraph {
+       pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
                Self {
+                       genesis_hash,
                        channels: BTreeMap::new(),
                        nodes: BTreeMap::new(),
                }
@@ -1365,7 +1367,8 @@ mod tests {
        fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
                let secp_ctx = Secp256k1::new();
                let logger = Arc::new(test_utils::TestLogger::new());
-               let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
+               let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
+               let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
                (secp_ctx, net_graph_msg_handler)
        }
 
@@ -1526,7 +1529,7 @@ mod tests {
                };
 
                // Test if the UTXO lookups were not supported
-               let mut net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
+               let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
                match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
                        Ok(res) => assert!(res),
                        _ => panic!()
@@ -1550,7 +1553,7 @@ mod tests {
                // Test if an associated transaction were not on-chain (or not confirmed).
                let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
                *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
-               net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
+               net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
                unsigned_announcement.short_channel_id += 1;
 
                msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
@@ -1674,7 +1677,7 @@ mod tests {
                let secp_ctx = Secp256k1::new();
                let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
                let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
-               let net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
+               let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
 
                let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
                let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
index 490b6b4048cbd33a7ba60e8b578b6dddbfcd4e17..f73a9a501bfbb75cf3bbafcb3f2193093bfba969 100644 (file)
@@ -538,7 +538,7 @@ mod tests {
        fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<std::sync::Arc<crate::util::test_utils::TestChainSource>, std::sync::Arc<crate::util::test_utils::TestLogger>>, std::sync::Arc<test_utils::TestLogger>) {
                let secp_ctx = Secp256k1::new();
                let logger = Arc::new(test_utils::TestLogger::new());
-               let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
+               let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
                // Build network from our_id to node7:
                //
                //        -1(1)2-  node0  -1(3)2-
@@ -1258,7 +1258,7 @@ mod tests {
                        inbound_capacity_msat: 100000,
                        is_live: true,
                }];
-               let route = get_route(&source_node_id, &NetworkGraph::new(), &target_node_id, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
+               let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
 
                assert_eq!(route.paths[0].len(), 2);