Add get_phantom_scid and get_phantom_route_hints + scid_utils::fake_scid module
[rust-lightning] / lightning / src / 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 /// Maximum block height that can be used in a `short_channel_id`. This
11 /// value is based on the 3-bytes available for block height.
12 pub const MAX_SCID_BLOCK: u64 = 0x00ffffff;
13
14 /// Maximum transaction index that can be used in a `short_channel_id`.
15 /// This value is based on the 3-bytes available for tx index.
16 pub const MAX_SCID_TX_INDEX: u64 = 0x00ffffff;
17
18 /// Maximum vout index that can be used in a `short_channel_id`. This
19 /// value is based on the 2-bytes available for the vout index.
20 pub const MAX_SCID_VOUT_INDEX: u64 = 0xffff;
21
22 /// A `short_channel_id` construction error
23 #[derive(Debug, PartialEq)]
24 pub enum ShortChannelIdError {
25         BlockOverflow,
26         TxIndexOverflow,
27         VoutIndexOverflow,
28 }
29
30 /// Extracts the block height (most significant 3-bytes) from the `short_channel_id`
31 pub fn block_from_scid(short_channel_id: &u64) -> u32 {
32         return (short_channel_id >> 40) as u32;
33 }
34
35 /// Extracts the tx index (bytes [2..4]) from the `short_channel_id`
36 pub fn tx_index_from_scid(short_channel_id: &u64) -> u32 {
37         return ((short_channel_id >> 16) & MAX_SCID_TX_INDEX) as u32;
38 }
39
40 /// Extracts the vout (bytes [0..2]) from the `short_channel_id`
41 pub fn vout_from_scid(short_channel_id: &u64) -> u16 {
42         return ((short_channel_id) & MAX_SCID_VOUT_INDEX) as u16;
43 }
44
45 /// Constructs a `short_channel_id` using the components pieces. Results in an error
46 /// if the block height, tx index, or vout index overflow the maximum sizes.
47 pub fn scid_from_parts(block: u64, tx_index: u64, vout_index: u64) -> Result<u64, ShortChannelIdError> {
48         if block > MAX_SCID_BLOCK {
49                 return Err(ShortChannelIdError::BlockOverflow);
50         }
51
52         if tx_index > MAX_SCID_TX_INDEX {
53                 return Err(ShortChannelIdError::TxIndexOverflow);
54         }
55
56         if vout_index > MAX_SCID_VOUT_INDEX {
57                 return Err(ShortChannelIdError::VoutIndexOverflow);
58         }
59
60         Ok((block << 40) | (tx_index << 16) | vout_index)
61 }
62
63 /// LDK has multiple reasons to generate fake short channel ids:
64 /// 1) zero-conf channels that don't have a confirmed channel id yet
65 /// 2) phantom node payments, to get an scid for the phantom node's phantom channel
66 pub(crate) mod fake_scid {
67         use bitcoin::hash_types::BlockHash;
68         use bitcoin::hashes::hex::FromHex;
69         use chain::keysinterface::{Sign, KeysInterface};
70         use util::chacha20::ChaCha20;
71         use util::scid_utils;
72
73         use core::convert::TryInto;
74         use core::ops::Deref;
75
76         const TEST_SEGWIT_ACTIVATION_HEIGHT: u32 = 0;
77         const MAINNET_SEGWIT_ACTIVATION_HEIGHT: u32 = 481_824;
78         const MAX_TX_INDEX: u32 = 2_500;
79         const MAX_NAMESPACES: u8 = 8; // We allocate 3 bits for the namespace identifier.
80         const NAMESPACE_ID_BITMASK: u8 = 0b111;
81
82         /// Fake scids are divided into namespaces, with each namespace having its own identifier between
83         /// [0..7]. This allows us to identify what namespace a fake scid corresponds to upon HTLC
84         /// receipt, and handle the HTLC accordingly. The namespace identifier is encrypted when encoded
85         /// into the fake scid.
86         #[derive(Copy, Clone)]
87         pub(super) enum Namespace {
88                 Phantom,
89                 // Coming soon: a variant for the zero-conf scid namespace
90         }
91
92         impl Namespace {
93                 /// We generate "realistic-looking" random scids here, meaning the scid's block height is
94                 /// between segwit activation and the current best known height, and the tx index and output
95                 /// index are also selected from a "reasonable" range. We add this logic because it makes it
96                 /// non-obvious at a glance that the scid is fake, e.g. if it appears in invoice route hints.
97                 pub(super) fn get_fake_scid<Signer: Sign, K: Deref>(&self, highest_seen_blockheight: u32, genesis_hash: &BlockHash, fake_scid_rand_bytes: &[u8; 32], keys_manager: &K) -> u64
98                         where K::Target: KeysInterface<Signer = Signer>,
99                 {
100                         // Ensure we haven't created a namespace that doesn't fit into the 3 bits we've allocated for
101                         // namespaces.
102                         assert!((*self as u8) < MAX_NAMESPACES);
103                         const BLOCKS_PER_MONTH: u32 = 144 /* blocks per day */ * 30 /* days per month */;
104                         let rand_bytes = keys_manager.get_secure_random_bytes();
105
106                         let segwit_activation_height = segwit_activation_height(genesis_hash);
107                         let mut valid_block_range = if highest_seen_blockheight > segwit_activation_height {
108                                 highest_seen_blockheight - segwit_activation_height
109                         } else {
110                                 1
111                         };
112                         // We want to ensure that this fake channel won't conflict with any transactions we haven't
113                         // seen yet, in case `highest_seen_blockheight` is updated before we get full information
114                         // about transactions confirmed in the given block.
115                         if valid_block_range > BLOCKS_PER_MONTH { valid_block_range -= BLOCKS_PER_MONTH; }
116
117                         let rand_for_height = u32::from_be_bytes(rand_bytes[..4].try_into().unwrap());
118                         let fake_scid_height = segwit_activation_height + rand_for_height % valid_block_range;
119
120                         let rand_for_tx_index = u32::from_be_bytes(rand_bytes[4..8].try_into().unwrap());
121                         let fake_scid_tx_index = rand_for_tx_index % MAX_TX_INDEX;
122
123                         // Put the scid in the given namespace.
124                         let fake_scid_vout = self.get_encrypted_vout(fake_scid_height, fake_scid_tx_index, fake_scid_rand_bytes);
125                         scid_utils::scid_from_parts(fake_scid_height as u64, fake_scid_tx_index as u64, fake_scid_vout as u64).unwrap()
126                 }
127
128                 /// We want to ensure that a 3rd party can't identify a payment as belong to a given
129                 /// `Namespace`. Therefore, we encrypt it using a random bytes provided by `ChannelManager`.
130                 fn get_encrypted_vout(&self, block_height: u32, tx_index: u32, fake_scid_rand_bytes: &[u8; 32]) -> u8 {
131                         let mut salt = [0 as u8; 8];
132                         let block_height_bytes = block_height.to_be_bytes();
133                         salt[0..4].copy_from_slice(&block_height_bytes);
134                         let tx_index_bytes = tx_index.to_be_bytes();
135                         salt[4..8].copy_from_slice(&tx_index_bytes);
136
137                         let mut chacha = ChaCha20::new(fake_scid_rand_bytes, &salt);
138                         let mut vout_byte = [*self as u8];
139                         chacha.process_in_place(&mut vout_byte);
140                         vout_byte[0] & NAMESPACE_ID_BITMASK
141                 }
142         }
143
144         pub fn get_phantom_scid<Signer: Sign, K: Deref>(fake_scid_rand_bytes: &[u8; 32], highest_seen_blockheight: u32, genesis_hash: &BlockHash, keys_manager: &K) -> u64
145                 where K::Target: KeysInterface<Signer = Signer>,
146         {
147                 let namespace = Namespace::Phantom;
148                 namespace.get_fake_scid(highest_seen_blockheight, genesis_hash, fake_scid_rand_bytes, keys_manager)
149         }
150
151         fn segwit_activation_height(genesis: &BlockHash) -> u32 {
152                 const MAINNET_GENESIS_STR: &'static str = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f";
153                 if BlockHash::from_hex(MAINNET_GENESIS_STR).unwrap() == *genesis {
154                         MAINNET_SEGWIT_ACTIVATION_HEIGHT
155                 } else {
156                         TEST_SEGWIT_ACTIVATION_HEIGHT
157                 }
158         }
159
160         /// Returns whether the given fake scid falls into the given namespace.
161         pub fn is_valid_phantom(fake_scid_rand_bytes: &[u8; 32], scid: u64) -> bool {
162                 let block_height = scid_utils::block_from_scid(&scid);
163                 let tx_index = scid_utils::tx_index_from_scid(&scid);
164                 let namespace = Namespace::Phantom;
165                 let valid_vout = namespace.get_encrypted_vout(block_height, tx_index, fake_scid_rand_bytes);
166                 valid_vout == scid_utils::vout_from_scid(&scid) as u8
167         }
168
169         #[cfg(test)]
170         mod tests {
171                 use bitcoin::blockdata::constants::genesis_block;
172                 use bitcoin::network::constants::Network;
173                 use util::scid_utils::fake_scid::{is_valid_phantom, MAINNET_SEGWIT_ACTIVATION_HEIGHT, MAX_TX_INDEX, MAX_NAMESPACES, Namespace, NAMESPACE_ID_BITMASK, segwit_activation_height, TEST_SEGWIT_ACTIVATION_HEIGHT};
174                 use util::scid_utils;
175                 use util::test_utils;
176                 use sync::Arc;
177
178                 #[test]
179                 fn namespace_identifier_is_within_range() {
180                         let phantom_namespace = Namespace::Phantom;
181                         assert!((phantom_namespace as u8) < MAX_NAMESPACES);
182                         assert!((phantom_namespace as u8) <= NAMESPACE_ID_BITMASK);
183                 }
184
185                 #[test]
186                 fn test_segwit_activation_height() {
187                         let mainnet_genesis = genesis_block(Network::Bitcoin).header.block_hash();
188                         assert_eq!(segwit_activation_height(&mainnet_genesis), MAINNET_SEGWIT_ACTIVATION_HEIGHT);
189
190                         let testnet_genesis = genesis_block(Network::Testnet).header.block_hash();
191                         assert_eq!(segwit_activation_height(&testnet_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
192
193                         let signet_genesis = genesis_block(Network::Signet).header.block_hash();
194                         assert_eq!(segwit_activation_height(&signet_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
195
196                         let regtest_genesis = genesis_block(Network::Regtest).header.block_hash();
197                         assert_eq!(segwit_activation_height(&regtest_genesis), TEST_SEGWIT_ACTIVATION_HEIGHT);
198                 }
199
200                 #[test]
201                 fn test_is_valid_phantom() {
202                         let namespace = Namespace::Phantom;
203                         let fake_scid_rand_bytes = [0; 32];
204                         let valid_encrypted_vout = namespace.get_encrypted_vout(0, 0, &fake_scid_rand_bytes);
205                         let valid_fake_scid = scid_utils::scid_from_parts(0, 0, valid_encrypted_vout as u64).unwrap();
206                         assert!(is_valid_phantom(&fake_scid_rand_bytes, valid_fake_scid));
207                         let invalid_fake_scid = scid_utils::scid_from_parts(0, 0, 12).unwrap();
208                         assert!(!is_valid_phantom(&fake_scid_rand_bytes, invalid_fake_scid));
209                 }
210
211                 #[test]
212                 fn test_get_fake_scid() {
213                         let mainnet_genesis = genesis_block(Network::Bitcoin).header.block_hash();
214                         let seed = [0; 32];
215                         let fake_scid_rand_bytes = [1; 32];
216                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet));
217                         let namespace = Namespace::Phantom;
218                         let fake_scid = namespace.get_fake_scid(500_000, &mainnet_genesis, &fake_scid_rand_bytes, &keys_manager);
219
220                         let fake_height = scid_utils::block_from_scid(&fake_scid);
221                         assert!(fake_height >= MAINNET_SEGWIT_ACTIVATION_HEIGHT);
222                         assert!(fake_height <= 500_000);
223
224                         let fake_tx_index = scid_utils::tx_index_from_scid(&fake_scid);
225                         assert!(fake_tx_index <= MAX_TX_INDEX);
226
227                         let fake_vout = scid_utils::vout_from_scid(&fake_scid);
228                         assert!(fake_vout < MAX_NAMESPACES as u16);
229                 }
230         }
231 }
232
233 #[cfg(test)]
234 mod tests {
235         use super::*;
236
237         #[test]
238         fn test_block_from_scid() {
239                 assert_eq!(block_from_scid(&0x000000_000000_0000), 0);
240                 assert_eq!(block_from_scid(&0x000001_000000_0000), 1);
241                 assert_eq!(block_from_scid(&0x000001_ffffff_ffff), 1);
242                 assert_eq!(block_from_scid(&0x800000_ffffff_ffff), 0x800000);
243                 assert_eq!(block_from_scid(&0xffffff_ffffff_ffff), 0xffffff);
244         }
245
246         #[test]
247         fn test_tx_index_from_scid() {
248                 assert_eq!(tx_index_from_scid(&0x000000_000000_0000), 0);
249                 assert_eq!(tx_index_from_scid(&0x000000_000001_0000), 1);
250                 assert_eq!(tx_index_from_scid(&0xffffff_000001_ffff), 1);
251                 assert_eq!(tx_index_from_scid(&0xffffff_800000_ffff), 0x800000);
252                 assert_eq!(tx_index_from_scid(&0xffffff_ffffff_ffff), 0xffffff);
253         }
254
255         #[test]
256         fn test_vout_from_scid() {
257                 assert_eq!(vout_from_scid(&0x000000_000000_0000), 0);
258                 assert_eq!(vout_from_scid(&0x000000_000000_0001), 1);
259                 assert_eq!(vout_from_scid(&0xffffff_ffffff_0001), 1);
260                 assert_eq!(vout_from_scid(&0xffffff_ffffff_8000), 0x8000);
261                 assert_eq!(vout_from_scid(&0xffffff_ffffff_ffff), 0xffff);
262         }
263
264         #[test]
265         fn test_scid_from_parts() {
266                 assert_eq!(scid_from_parts(0x00000000, 0x00000000, 0x0000).unwrap(), 0x000000_000000_0000);
267                 assert_eq!(scid_from_parts(0x00000001, 0x00000002, 0x0003).unwrap(), 0x000001_000002_0003);
268                 assert_eq!(scid_from_parts(0x00111111, 0x00222222, 0x3333).unwrap(), 0x111111_222222_3333);
269                 assert_eq!(scid_from_parts(0x00ffffff, 0x00ffffff, 0xffff).unwrap(), 0xffffff_ffffff_ffff);
270                 assert_eq!(scid_from_parts(0x01ffffff, 0x00000000, 0x0000).err().unwrap(), ShortChannelIdError::BlockOverflow);
271                 assert_eq!(scid_from_parts(0x00000000, 0x01ffffff, 0x0000).err().unwrap(), ShortChannelIdError::TxIndexOverflow);
272                 assert_eq!(scid_from_parts(0x00000000, 0x00000000, 0x010000).err().unwrap(), ShortChannelIdError::VoutIndexOverflow);
273         }
274 }