mirror of
https://github.com/lightningdevkit/rust-lightning.git
synced 2025-02-24 15:02:20 +01:00
Add genesis block hash to NetworkGraph
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.
This commit is contained in:
parent
69da2daeae
commit
d183b975da
5 changed files with 22 additions and 16 deletions
|
@ -19,6 +19,7 @@ use bitcoin::blockdata::script::{Builder, Script};
|
||||||
use bitcoin::blockdata::opcodes;
|
use bitcoin::blockdata::opcodes;
|
||||||
use bitcoin::consensus::encode::deserialize;
|
use bitcoin::consensus::encode::deserialize;
|
||||||
use bitcoin::network::constants::Network;
|
use bitcoin::network::constants::Network;
|
||||||
|
use bitcoin::blockdata::constants::genesis_block;
|
||||||
|
|
||||||
use bitcoin::hashes::Hash as TraitImport;
|
use bitcoin::hashes::Hash as TraitImport;
|
||||||
use bitcoin::hashes::HashEngine as TraitImportEngine;
|
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;
|
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 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 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 peers = RefCell::new([false; 256]);
|
||||||
let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler {
|
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
|
// 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).
|
// 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
|
// 16-byte MAC of the encrypted message length + encrypted Lightning message + 16-byte MAC
|
||||||
// of the Lightning message
|
// of the Lightning message
|
||||||
// I.e 2nd inbound read, len 18 : 0006 (encrypted message length) + 03000000000000000000000000000000 (MAC of the encrypted message length)
|
// I.e 2nd inbound read, len 18 : 0006 (encrypted message length) + 03000000000000000000000000000000 (MAC of the encrypted message length)
|
||||||
|
|
|
@ -21,6 +21,8 @@ use lightning::util::ser::Readable;
|
||||||
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
|
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
|
||||||
|
|
||||||
use bitcoin::secp256k1::key::PublicKey;
|
use bitcoin::secp256k1::key::PublicKey;
|
||||||
|
use bitcoin::network::constants::Network;
|
||||||
|
use bitcoin::blockdata::constants::genesis_block;
|
||||||
|
|
||||||
use utils::test_logger;
|
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 logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
|
||||||
|
|
||||||
let our_pubkey = get_pubkey!();
|
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 node_pks = HashSet::new();
|
||||||
let mut scid = 42;
|
let mut scid = 42;
|
||||||
|
|
|
@ -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));
|
let payment_count = Rc::new(RefCell::new(0));
|
||||||
|
|
||||||
for i in 0..node_count {
|
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,
|
nodes.push(Node{ chain_source: cfgs[i].chain_source,
|
||||||
tx_broadcaster: cfgs[i].tx_broadcaster, chain_monitor: &cfgs[i].chain_monitor,
|
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,
|
keys_manager: &cfgs[i].keys_manager, node: &chan_mgrs[i], net_graph_msg_handler,
|
||||||
|
|
|
@ -55,6 +55,7 @@ const MAX_REPLY_CHANNEL_RANGE_PER_QUERY: usize = 250;
|
||||||
/// Represents the network as nodes and channels between them
|
/// Represents the network as nodes and channels between them
|
||||||
#[derive(PartialEq)]
|
#[derive(PartialEq)]
|
||||||
pub struct NetworkGraph {
|
pub struct NetworkGraph {
|
||||||
|
genesis_hash: BlockHash,
|
||||||
channels: BTreeMap<u64, ChannelInfo>,
|
channels: BTreeMap<u64, ChannelInfo>,
|
||||||
nodes: BTreeMap<PublicKey, NodeInfo>,
|
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,
|
/// Chain monitor is used to make sure announced channels exist on-chain,
|
||||||
/// channel data is correct, and that the announcement is signed with
|
/// channel data is correct, and that the announcement is signed with
|
||||||
/// channel owners' keys.
|
/// 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 {
|
NetGraphMsgHandler {
|
||||||
secp_ctx: Secp256k1::verification_only(),
|
secp_ctx: Secp256k1::verification_only(),
|
||||||
network_graph: RwLock::new(NetworkGraph {
|
network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
|
||||||
channels: BTreeMap::new(),
|
|
||||||
nodes: BTreeMap::new(),
|
|
||||||
}),
|
|
||||||
full_syncs_requested: AtomicUsize::new(0),
|
full_syncs_requested: AtomicUsize::new(0),
|
||||||
chain_access,
|
chain_access,
|
||||||
pending_events: Mutex::new(vec![]),
|
pending_events: Mutex::new(vec![]),
|
||||||
|
@ -903,6 +901,7 @@ impl Readable for NodeInfo {
|
||||||
|
|
||||||
impl Writeable for NetworkGraph {
|
impl Writeable for NetworkGraph {
|
||||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
|
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
|
||||||
|
self.genesis_hash.write(writer)?;
|
||||||
(self.channels.len() as u64).write(writer)?;
|
(self.channels.len() as u64).write(writer)?;
|
||||||
for (ref chan_id, ref chan_info) in self.channels.iter() {
|
for (ref chan_id, ref chan_info) in self.channels.iter() {
|
||||||
(*chan_id).write(writer)?;
|
(*chan_id).write(writer)?;
|
||||||
|
@ -919,6 +918,7 @@ impl Writeable for NetworkGraph {
|
||||||
|
|
||||||
impl Readable for NetworkGraph {
|
impl Readable for NetworkGraph {
|
||||||
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
|
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 channels_count: u64 = Readable::read(reader)?;
|
||||||
let mut channels = BTreeMap::new();
|
let mut channels = BTreeMap::new();
|
||||||
for _ in 0..channels_count {
|
for _ in 0..channels_count {
|
||||||
|
@ -934,6 +934,7 @@ impl Readable for NetworkGraph {
|
||||||
nodes.insert(node_id, node_info);
|
nodes.insert(node_id, node_info);
|
||||||
}
|
}
|
||||||
Ok(NetworkGraph {
|
Ok(NetworkGraph {
|
||||||
|
genesis_hash,
|
||||||
channels,
|
channels,
|
||||||
nodes,
|
nodes,
|
||||||
})
|
})
|
||||||
|
@ -979,8 +980,9 @@ impl NetworkGraph {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new, empty, network graph.
|
/// Creates a new, empty, network graph.
|
||||||
pub fn new() -> NetworkGraph {
|
pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
|
||||||
Self {
|
Self {
|
||||||
|
genesis_hash,
|
||||||
channels: BTreeMap::new(),
|
channels: BTreeMap::new(),
|
||||||
nodes: 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>>) {
|
fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
|
||||||
let secp_ctx = Secp256k1::new();
|
let secp_ctx = Secp256k1::new();
|
||||||
let logger = Arc::new(test_utils::TestLogger::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)
|
(secp_ctx, net_graph_msg_handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1526,7 +1529,7 @@ mod tests {
|
||||||
};
|
};
|
||||||
|
|
||||||
// Test if the UTXO lookups were not supported
|
// 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) {
|
match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
|
||||||
Ok(res) => assert!(res),
|
Ok(res) => assert!(res),
|
||||||
_ => panic!()
|
_ => panic!()
|
||||||
|
@ -1550,7 +1553,7 @@ mod tests {
|
||||||
// Test if an associated transaction were not on-chain (or not confirmed).
|
// Test if an associated transaction were not on-chain (or not confirmed).
|
||||||
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
|
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
|
||||||
*chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
|
*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;
|
unsigned_announcement.short_channel_id += 1;
|
||||||
|
|
||||||
msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
|
msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
|
||||||
|
@ -1674,7 +1677,7 @@ mod tests {
|
||||||
let secp_ctx = Secp256k1::new();
|
let secp_ctx = Secp256k1::new();
|
||||||
let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
|
let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
|
||||||
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
|
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_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
|
||||||
let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
|
let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
|
||||||
|
|
|
@ -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>) {
|
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 secp_ctx = Secp256k1::new();
|
||||||
let logger = Arc::new(test_utils::TestLogger::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:
|
// Build network from our_id to node7:
|
||||||
//
|
//
|
||||||
// -1(1)2- node0 -1(3)2-
|
// -1(1)2- node0 -1(3)2-
|
||||||
|
@ -1258,7 +1258,7 @@ mod tests {
|
||||||
inbound_capacity_msat: 100000,
|
inbound_capacity_msat: 100000,
|
||||||
is_live: true,
|
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);
|
assert_eq!(route.paths[0].len(), 2);
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue