Bump rust-bitcoin to v0.30.2
[rust-lightning] / lightning / src / ln / channel_id.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 //! ChannelId definition.
11
12 use crate::ln::msgs::DecodeError;
13 use crate::sign::EntropySource;
14 use crate::util::ser::{Readable, Writeable, Writer};
15
16 use crate::io;
17 use core::fmt;
18 use core::ops::Deref;
19
20 /// A unique 32-byte identifier for a channel.
21 /// Depending on how the ID is generated, several varieties are distinguished
22 /// (but all are stored as 32 bytes):
23 ///   _v1_ and _temporary_.
24 /// A _v1_ channel ID is generated based on funding tx outpoint (txid & index).
25 /// A _temporary_ ID is generated randomly.
26 /// (Later revocation-point-based _v2_ is a possibility.)
27 /// The variety (context) is not stored, it is relevant only at creation.
28 ///
29 /// This is not exported to bindings users as we just use [u8; 32] directly.
30 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
31 pub struct ChannelId(pub [u8; 32]);
32
33 impl ChannelId {
34         /// Create _v1_ channel ID based on a funding TX ID and output index
35         pub fn v1_from_funding_txid(txid: &[u8; 32], output_index: u16) -> Self {
36                 let mut res = [0; 32];
37                 res[..].copy_from_slice(&txid[..]);
38                 res[30] ^= ((output_index >> 8) & 0xff) as u8;
39                 res[31] ^= ((output_index >> 0) & 0xff) as u8;
40                 Self(res)
41         }
42
43         /// Create a _temporary_ channel ID randomly, based on an entropy source.
44         pub fn temporary_from_entropy_source<ES: Deref>(entropy_source: &ES) -> Self
45         where ES::Target: EntropySource {
46                 Self(entropy_source.get_secure_random_bytes())
47         }
48
49         /// Generic constructor; create a new channel ID from the provided data.
50         /// Use a more specific `*_from_*` constructor when possible.
51         pub fn from_bytes(data: [u8; 32]) -> Self {
52                 Self(data)
53         }
54
55         /// Create a channel ID consisting of all-zeros data (e.g. when uninitialized or a placeholder).
56         pub fn new_zero() -> Self {
57                 Self([0; 32])
58         }
59
60         /// Check whether ID is consisting of all zeros (uninitialized)
61         pub fn is_zero(&self) -> bool {
62                 self.0[..] == [0; 32]
63         }
64 }
65
66 impl Writeable for ChannelId {
67         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
68                 self.0.write(w)
69         }
70 }
71
72 impl Readable for ChannelId {
73         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
74                 let buf: [u8; 32] = Readable::read(r)?;
75                 Ok(ChannelId(buf))
76         }
77 }
78
79 impl fmt::Display for ChannelId {
80         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81                 crate::util::logger::DebugBytes(&self.0).fmt(f)
82         }
83 }
84
85 #[cfg(test)]
86 mod tests {
87         use hex::DisplayHex;
88
89         use crate::ln::ChannelId;
90         use crate::util::ser::{Readable, Writeable};
91         use crate::util::test_utils;
92         use crate::prelude::*;
93         use crate::io;
94
95         #[test]
96         fn test_channel_id_v1_from_funding_txid() {
97                 let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
98                 assert_eq!(channel_id.0.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020203");
99         }
100
101         #[test]
102         fn test_channel_id_new_from_data() {
103                 let data: [u8; 32] = [2; 32];
104                 let channel_id = ChannelId::from_bytes(data.clone());
105                 assert_eq!(channel_id.0, data);
106         }
107
108         #[test]
109         fn test_channel_id_equals() {
110                 let channel_id11 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
111                 let channel_id12 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
112                 let channel_id21 = ChannelId::v1_from_funding_txid(&[2; 32], 42);
113                 assert_eq!(channel_id11, channel_id12);
114                 assert_ne!(channel_id11, channel_id21);
115         }
116
117         #[test]
118         fn test_channel_id_write_read() {
119                 let data: [u8; 32] = [2; 32];
120                 let channel_id = ChannelId::from_bytes(data.clone());
121
122                 let mut w = test_utils::TestVecWriter(Vec::new());
123                 channel_id.write(&mut w).unwrap();
124
125                 let channel_id_2 = ChannelId::read(&mut io::Cursor::new(&w.0)).unwrap();
126                 assert_eq!(channel_id_2, channel_id);
127                 assert_eq!(channel_id_2.0, data);
128         }
129
130         #[test]
131         fn test_channel_id_display() {
132                 let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
133                 assert_eq!(format!("{}", &channel_id), "0202020202020202020202020202020202020202020202020202020202020203");
134         }
135 }