lightning/util/
scid_utils.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Utilities for creating and parsing short channel ids.
11
12/// Maximum block height that can be used in a `short_channel_id`. This
13/// value is based on the 3-bytes available for block height.
14pub const MAX_SCID_BLOCK: u64 = 0x00ffffff;
15
16/// Maximum transaction index that can be used in a `short_channel_id`.
17/// This value is based on the 3-bytes available for tx index.
18pub const MAX_SCID_TX_INDEX: u64 = 0x00ffffff;
19
20/// Maximum vout index that can be used in a `short_channel_id`. This
21/// value is based on the 2-bytes available for the vout index.
22pub const MAX_SCID_VOUT_INDEX: u64 = 0xffff;
23
24/// A `short_channel_id` construction error
25#[derive(Debug, PartialEq, Eq)]
26pub enum ShortChannelIdError {
27	/// Block height too high
28	BlockOverflow,
29	/// Tx index too high
30	TxIndexOverflow,
31	/// Vout index too high
32	VoutIndexOverflow,
33}
34
35/// Extracts the block height (most significant 3-bytes) from the `short_channel_id`
36pub fn block_from_scid(short_channel_id: u64) -> u32 {
37	return (short_channel_id >> 40) as u32;
38}
39
40/// Extracts the tx index (bytes [2..4]) from the `short_channel_id`
41pub fn tx_index_from_scid(short_channel_id: u64) -> u32 {
42	return ((short_channel_id >> 16) & MAX_SCID_TX_INDEX) as u32;
43}
44
45/// Extracts the vout (bytes [0..2]) from the `short_channel_id`
46pub fn vout_from_scid(short_channel_id: u64) -> u16 {
47	return ((short_channel_id) & MAX_SCID_VOUT_INDEX) as u16;
48}
49
50/// Constructs a `short_channel_id` using the components pieces. Results in an error
51/// if the block height, tx index, or vout index overflow the maximum sizes.
52pub fn scid_from_parts(
53	block: u64, tx_index: u64, vout_index: u64,
54) -> Result<u64, ShortChannelIdError> {
55	if block > MAX_SCID_BLOCK {
56		return Err(ShortChannelIdError::BlockOverflow);
57	}
58
59	if tx_index > MAX_SCID_TX_INDEX {
60		return Err(ShortChannelIdError::TxIndexOverflow);
61	}
62
63	if vout_index > MAX_SCID_VOUT_INDEX {
64		return Err(ShortChannelIdError::VoutIndexOverflow);
65	}
66
67	Ok((block << 40) | (tx_index << 16) | vout_index)
68}
69
70/// LDK has multiple reasons to generate fake short channel ids:
71/// 1) outbound SCID aliases we use for private channels
72/// 2) phantom node payments, to get an scid for the phantom node's phantom channel
73/// 3) payments intended to be intercepted will route using a fake scid (this is typically used so
74///    the forwarding node can open a JIT channel to the next hop)
75pub(crate) mod fake_scid {
76	use crate::crypto::chacha20::ChaCha20;
77	use crate::prelude::*;
78	use crate::sign::EntropySource;
79	use crate::util::scid_utils;
80	use bitcoin::constants::ChainHash;
81	use bitcoin::Network;
82
83	use core::ops::Deref;
84
85	const TEST_SEGWIT_ACTIVATION_HEIGHT: u32 = 1;
86	const MAINNET_SEGWIT_ACTIVATION_HEIGHT: u32 = 481_824;
87	const MAX_TX_INDEX: u32 = 2_500;
88	const MAX_NAMESPACES: u8 = 8; // We allocate 3 bits for the namespace identifier.
89	const NAMESPACE_ID_BITMASK: u8 = 0b111;
90
91	const BLOCKS_PER_MONTH: u32 = 144 /* blocks per day */ * 30 /* days per month */;
92	pub(crate) const MAX_SCID_BLOCKS_FROM_NOW: u32 = BLOCKS_PER_MONTH;
93
94	/// Fake scids are divided into namespaces, with each namespace having its own identifier between
95	/// [0..7]. This allows us to identify what namespace a fake scid corresponds to upon HTLC
96	/// receipt, and handle the HTLC accordingly. The namespace identifier is encrypted when encoded
97	/// into the fake scid.
98	#[derive(Copy, Clone)]
99	pub(crate) enum Namespace {
100		/// Phantom nodes namespace
101		Phantom,
102		/// SCID aliases for outbound private channels
103		OutboundAlias,
104		/// Payment interception namespace
105		Intercept,
106	}
107
108	impl Namespace {
109		/// We generate "realistic-looking" random scids here, meaning the scid's block height is
110		/// between segwit activation and the current best known height, and the tx index and output
111		/// index are also selected from a "reasonable" range. We add this logic because it makes it
112		/// non-obvious at a glance that the scid is fake, e.g. if it appears in invoice route hints.
113		pub(crate) fn get_fake_scid<ES: Deref>(
114			&self, highest_seen_blockheight: u32, chain_hash: &ChainHash,
115			fake_scid_rand_bytes: &[u8; 32], entropy_source: &ES,
116		) -> u64
117		where
118			ES::Target: EntropySource,
119		{
120			// Ensure we haven't created a namespace that doesn't fit into the 3 bits we've allocated for
121			// namespaces.
122			assert!((*self as u8) < MAX_NAMESPACES);
123			let rand_bytes = entropy_source.get_secure_random_bytes();
124
125			let segwit_activation_height = segwit_activation_height(chain_hash);
126			let mut blocks_since_segwit_activation =
127				highest_seen_blockheight.saturating_sub(segwit_activation_height);
128
129			// We want to ensure that this fake channel won't conflict with any transactions we haven't
130			// seen yet, in case `highest_seen_blockheight` is updated before we get full information
131			// about transactions confirmed in the given block.
132			blocks_since_segwit_activation =
133				blocks_since_segwit_activation.saturating_sub(MAX_SCID_BLOCKS_FROM_NOW);
134
135			let rand_for_height = u32::from_be_bytes(rand_bytes[..4].try_into().unwrap());
136			let fake_scid_height =
137				segwit_activation_height + rand_for_height % (blocks_since_segwit_activation + 1);
138
139			let rand_for_tx_index = u32::from_be_bytes(rand_bytes[4..8].try_into().unwrap());
140			let fake_scid_tx_index = rand_for_tx_index % MAX_TX_INDEX;
141
142			// Put the scid in the given namespace.
143			let fake_scid_vout =
144				self.get_encrypted_vout(fake_scid_height, fake_scid_tx_index, fake_scid_rand_bytes);
145			scid_utils::scid_from_parts(
146				fake_scid_height as u64,
147				fake_scid_tx_index as u64,
148				fake_scid_vout as u64,
149			)
150			.unwrap()
151		}
152
153		/// We want to ensure that a 3rd party can't identify a payment as belong to a given
154		/// `Namespace`. Therefore, we encrypt it using a random bytes provided by `ChannelManager`.
155		fn get_encrypted_vout(
156			&self, block_height: u32, tx_index: u32, fake_scid_rand_bytes: &[u8; 32],
157		) -> u8 {
158			let mut salt = [0 as u8; 8];
159			let block_height_bytes = block_height.to_be_bytes();
160			salt[0..4].copy_from_slice(&block_height_bytes);
161			let tx_index_bytes = tx_index.to_be_bytes();
162			salt[4..8].copy_from_slice(&tx_index_bytes);
163
164			let mut chacha = ChaCha20::new(fake_scid_rand_bytes, &salt);
165			let mut vout_byte = [*self as u8];
166			chacha.process_in_place(&mut vout_byte);
167			vout_byte[0] & NAMESPACE_ID_BITMASK
168		}
169	}
170
171	fn segwit_activation_height(chain_hash: &ChainHash) -> u32 {
172		if *chain_hash == ChainHash::using_genesis_block(Network::Bitcoin) {
173			MAINNET_SEGWIT_ACTIVATION_HEIGHT
174		} else {
175			TEST_SEGWIT_ACTIVATION_HEIGHT
176		}
177	}
178
179	/// Returns whether the given fake scid falls into the phantom namespace.
180	pub fn is_valid_phantom(
181		fake_scid_rand_bytes: &[u8; 32], scid: u64, chain_hash: &ChainHash,
182	) -> bool {
183		let block_height = scid_utils::block_from_scid(scid);
184		let tx_index = scid_utils::tx_index_from_scid(scid);
185		let namespace = Namespace::Phantom;
186		let valid_vout = namespace.get_encrypted_vout(block_height, tx_index, fake_scid_rand_bytes);
187		block_height >= segwit_activation_height(chain_hash)
188			&& valid_vout == scid_utils::vout_from_scid(scid) as u8
189	}
190
191	/// Returns whether the given fake scid falls into the intercept namespace.
192	pub fn is_valid_intercept(
193		fake_scid_rand_bytes: &[u8; 32], scid: u64, chain_hash: &ChainHash,
194	) -> bool {
195		let block_height = scid_utils::block_from_scid(scid);
196		let tx_index = scid_utils::tx_index_from_scid(scid);
197		let namespace = Namespace::Intercept;
198		let valid_vout = namespace.get_encrypted_vout(block_height, tx_index, fake_scid_rand_bytes);
199		block_height >= segwit_activation_height(chain_hash)
200			&& valid_vout == scid_utils::vout_from_scid(scid) as u8
201	}
202
203	#[cfg(test)]
204	mod tests {
205		use crate::sync::Arc;
206		use crate::util::scid_utils;
207		use crate::util::scid_utils::fake_scid::{
208			is_valid_intercept, is_valid_phantom, segwit_activation_height, Namespace,
209			MAINNET_SEGWIT_ACTIVATION_HEIGHT, MAX_NAMESPACES, MAX_TX_INDEX, NAMESPACE_ID_BITMASK,
210			TEST_SEGWIT_ACTIVATION_HEIGHT,
211		};
212		use crate::util::test_utils;
213		use bitcoin::constants::ChainHash;
214		use bitcoin::network::Network;
215
216		#[test]
217		fn namespace_identifier_is_within_range() {
218			let phantom_namespace = Namespace::Phantom;
219			assert!((phantom_namespace as u8) < MAX_NAMESPACES);
220			assert!((phantom_namespace as u8) <= NAMESPACE_ID_BITMASK);
221
222			let intercept_namespace = Namespace::Intercept;
223			assert!((intercept_namespace as u8) < MAX_NAMESPACES);
224			assert!((intercept_namespace as u8) <= NAMESPACE_ID_BITMASK);
225		}
226
227		#[test]
228		fn test_segwit_activation_height() {
229			let mainnet_genesis = ChainHash::using_genesis_block(Network::Bitcoin);
230			assert_eq!(
231				segwit_activation_height(&mainnet_genesis),
232				MAINNET_SEGWIT_ACTIVATION_HEIGHT
233			);
234
235			let testnet_genesis = ChainHash::using_genesis_block(Network::Testnet);
236			assert_eq!(segwit_activation_height(&testnet_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
237
238			let signet_genesis = ChainHash::using_genesis_block(Network::Signet);
239			assert_eq!(segwit_activation_height(&signet_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
240
241			let regtest_genesis = ChainHash::using_genesis_block(Network::Regtest);
242			assert_eq!(segwit_activation_height(&regtest_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
243		}
244
245		#[test]
246		fn test_is_valid_phantom() {
247			let namespace = Namespace::Phantom;
248			let fake_scid_rand_bytes = [0; 32];
249			let testnet_genesis = ChainHash::using_genesis_block(Network::Testnet);
250			let valid_encrypted_vout = namespace.get_encrypted_vout(0, 0, &fake_scid_rand_bytes);
251			let valid_fake_scid =
252				scid_utils::scid_from_parts(1, 0, valid_encrypted_vout as u64).unwrap();
253			assert!(is_valid_phantom(&fake_scid_rand_bytes, valid_fake_scid, &testnet_genesis));
254			let invalid_fake_scid = scid_utils::scid_from_parts(1, 0, 12).unwrap();
255			assert!(!is_valid_phantom(&fake_scid_rand_bytes, invalid_fake_scid, &testnet_genesis));
256		}
257
258		#[test]
259		fn test_is_valid_intercept() {
260			let namespace = Namespace::Intercept;
261			let fake_scid_rand_bytes = [0; 32];
262			let testnet_genesis = ChainHash::using_genesis_block(Network::Testnet);
263			let valid_encrypted_vout = namespace.get_encrypted_vout(0, 0, &fake_scid_rand_bytes);
264			let valid_fake_scid =
265				scid_utils::scid_from_parts(1, 0, valid_encrypted_vout as u64).unwrap();
266			assert!(is_valid_intercept(&fake_scid_rand_bytes, valid_fake_scid, &testnet_genesis));
267			let invalid_fake_scid = scid_utils::scid_from_parts(1, 0, 12).unwrap();
268			assert!(!is_valid_intercept(
269				&fake_scid_rand_bytes,
270				invalid_fake_scid,
271				&testnet_genesis
272			));
273		}
274
275		#[test]
276		fn test_get_fake_scid() {
277			let mainnet_genesis = ChainHash::using_genesis_block(Network::Bitcoin);
278			let seed = [0; 32];
279			let fake_scid_rand_bytes = [1; 32];
280			let keys_manager =
281				Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
282			let namespace = Namespace::Phantom;
283			let fake_scid = namespace.get_fake_scid(
284				500_000,
285				&mainnet_genesis,
286				&fake_scid_rand_bytes,
287				&keys_manager,
288			);
289
290			let fake_height = scid_utils::block_from_scid(fake_scid);
291			assert!(fake_height >= MAINNET_SEGWIT_ACTIVATION_HEIGHT);
292			assert!(fake_height <= 500_000);
293
294			let fake_tx_index = scid_utils::tx_index_from_scid(fake_scid);
295			assert!(fake_tx_index <= MAX_TX_INDEX);
296
297			let fake_vout = scid_utils::vout_from_scid(fake_scid);
298			assert!(fake_vout < MAX_NAMESPACES as u16);
299		}
300	}
301}
302
303#[cfg(test)]
304mod tests {
305	use super::*;
306
307	#[test]
308	fn test_block_from_scid() {
309		assert_eq!(block_from_scid(0x000000_000000_0000), 0);
310		assert_eq!(block_from_scid(0x000001_000000_0000), 1);
311		assert_eq!(block_from_scid(0x000001_ffffff_ffff), 1);
312		assert_eq!(block_from_scid(0x800000_ffffff_ffff), 0x800000);
313		assert_eq!(block_from_scid(0xffffff_ffffff_ffff), 0xffffff);
314	}
315
316	#[test]
317	fn test_tx_index_from_scid() {
318		assert_eq!(tx_index_from_scid(0x000000_000000_0000), 0);
319		assert_eq!(tx_index_from_scid(0x000000_000001_0000), 1);
320		assert_eq!(tx_index_from_scid(0xffffff_000001_ffff), 1);
321		assert_eq!(tx_index_from_scid(0xffffff_800000_ffff), 0x800000);
322		assert_eq!(tx_index_from_scid(0xffffff_ffffff_ffff), 0xffffff);
323	}
324
325	#[test]
326	fn test_vout_from_scid() {
327		assert_eq!(vout_from_scid(0x000000_000000_0000), 0);
328		assert_eq!(vout_from_scid(0x000000_000000_0001), 1);
329		assert_eq!(vout_from_scid(0xffffff_ffffff_0001), 1);
330		assert_eq!(vout_from_scid(0xffffff_ffffff_8000), 0x8000);
331		assert_eq!(vout_from_scid(0xffffff_ffffff_ffff), 0xffff);
332	}
333
334	#[test]
335	fn test_scid_from_parts() {
336		assert_eq!(scid_from_parts(0x00000000, 0x00000000, 0x0000).unwrap(), 0x000000_000000_0000);
337		assert_eq!(scid_from_parts(0x00000001, 0x00000002, 0x0003).unwrap(), 0x000001_000002_0003);
338		assert_eq!(scid_from_parts(0x00111111, 0x00222222, 0x3333).unwrap(), 0x111111_222222_3333);
339		assert_eq!(scid_from_parts(0x00ffffff, 0x00ffffff, 0xffff).unwrap(), 0xffffff_ffffff_ffff);
340		assert_eq!(
341			scid_from_parts(0x01ffffff, 0x00000000, 0x0000).err().unwrap(),
342			ShortChannelIdError::BlockOverflow
343		);
344		assert_eq!(
345			scid_from_parts(0x00000000, 0x01ffffff, 0x0000).err().unwrap(),
346			ShortChannelIdError::TxIndexOverflow
347		);
348		assert_eq!(
349			scid_from_parts(0x00000000, 0x00000000, 0x010000).err().unwrap(),
350			ShortChannelIdError::VoutIndexOverflow
351		);
352	}
353}