5966b37116479abad227d5c896784ca2c028584f
[rust-lightning] / lightning / src / ln / types.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 //! Various wrapper types (most around 32-byte arrays) for use in lightning.
11
12 use crate::chain::transaction::OutPoint;
13 use crate::io;
14 use crate::ln::msgs::DecodeError;
15 use crate::sign::EntropySource;
16 use crate::util::ser::{Readable, Writeable, Writer};
17 use super::channel_keys::RevocationBasepoint;
18
19 #[allow(unused_imports)]
20 use crate::prelude::*;
21
22 use bitcoin::hashes::{
23         Hash as _,
24         HashEngine as _,
25         sha256::Hash as Sha256,
26 };
27 use core::fmt;
28 use core::ops::Deref;
29
30 /// A unique 32-byte identifier for a channel.
31 /// Depending on how the ID is generated, several varieties are distinguished
32 /// (but all are stored as 32 bytes):
33 ///   _v1_ and _temporary_.
34 /// A _v1_ channel ID is generated based on funding tx outpoint (txid & index).
35 /// A _temporary_ ID is generated randomly.
36 /// (Later revocation-point-based _v2_ is a possibility.)
37 /// The variety (context) is not stored, it is relevant only at creation.
38 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
39 pub struct ChannelId(pub [u8; 32]);
40
41 impl ChannelId {
42         /// Create _v1_ channel ID based on a funding TX ID and output index
43         pub fn v1_from_funding_txid(txid: &[u8; 32], output_index: u16) -> Self {
44                 let mut res = [0; 32];
45                 res[..].copy_from_slice(&txid[..]);
46                 res[30] ^= ((output_index >> 8) & 0xff) as u8;
47                 res[31] ^= ((output_index >> 0) & 0xff) as u8;
48                 Self(res)
49         }
50
51         /// Create _v1_ channel ID from a funding tx outpoint
52         pub fn v1_from_funding_outpoint(outpoint: OutPoint) -> Self {
53                 Self::v1_from_funding_txid(outpoint.txid.as_byte_array(), outpoint.index)
54         }
55
56         /// Create a _temporary_ channel ID randomly, based on an entropy source.
57         pub fn temporary_from_entropy_source<ES: Deref>(entropy_source: &ES) -> Self
58         where ES::Target: EntropySource {
59                 Self(entropy_source.get_secure_random_bytes())
60         }
61
62         /// Generic constructor; create a new channel ID from the provided data.
63         /// Use a more specific `*_from_*` constructor when possible.
64         pub fn from_bytes(data: [u8; 32]) -> Self {
65                 Self(data)
66         }
67
68         /// Create a channel ID consisting of all-zeros data (e.g. when uninitialized or a placeholder).
69         pub fn new_zero() -> Self {
70                 Self([0; 32])
71         }
72
73         /// Check whether ID is consisting of all zeros (uninitialized)
74         pub fn is_zero(&self) -> bool {
75                 self.0[..] == [0; 32]
76         }
77
78         /// Create _v2_ channel ID by concatenating the holder revocation basepoint with the counterparty
79         /// revocation basepoint and hashing the result. The basepoints will be concatenated in increasing
80         /// sorted order.
81         pub fn v2_from_revocation_basepoints(
82                 ours: &RevocationBasepoint,
83                 theirs: &RevocationBasepoint,
84         ) -> Self {
85                 let ours = ours.0.serialize();
86                 let theirs = theirs.0.serialize();
87                 let (lesser, greater) = if ours < theirs {
88                         (ours, theirs)
89                 } else {
90                         (theirs, ours)
91                 };
92                 let mut engine = Sha256::engine();
93                 engine.input(&lesser[..]);
94                 engine.input(&greater[..]);
95                 Self(Sha256::from_engine(engine).to_byte_array())
96         }
97
98         /// Create temporary _v2_ channel ID by concatenating a zeroed out basepoint with the holder
99         /// revocation basepoint and hashing the result.
100         pub fn temporary_v2_from_revocation_basepoint(our_revocation_basepoint: &RevocationBasepoint) -> Self {
101                 Self(Sha256::hash(&[[0u8; 33], our_revocation_basepoint.0.serialize()].concat()).to_byte_array())
102         }
103 }
104
105 impl Writeable for ChannelId {
106         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
107                 self.0.write(w)
108         }
109 }
110
111 impl Readable for ChannelId {
112         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
113                 let buf: [u8; 32] = Readable::read(r)?;
114                 Ok(ChannelId(buf))
115         }
116 }
117
118 impl fmt::Display for ChannelId {
119         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120                 crate::util::logger::DebugBytes(&self.0).fmt(f)
121         }
122 }
123
124
125 /// The payment hash is the hash of the [`PaymentPreimage`] which is the value used to lock funds
126 /// in HTLCs while they transit the lightning network.
127 ///
128 /// This is not exported to bindings users as we just use [u8; 32] directly
129 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
130 pub struct PaymentHash(pub [u8; 32]);
131
132 impl core::fmt::Display for PaymentHash {
133         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
134                 crate::util::logger::DebugBytes(&self.0).fmt(f)
135         }
136 }
137
138 /// The payment preimage is the "secret key" which is used to claim the funds of an HTLC on-chain
139 /// or in a lightning channel.
140 ///
141 /// This is not exported to bindings users as we just use [u8; 32] directly
142 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
143 pub struct PaymentPreimage(pub [u8; 32]);
144
145 impl core::fmt::Display for PaymentPreimage {
146         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
147                 crate::util::logger::DebugBytes(&self.0).fmt(f)
148         }
149 }
150
151 /// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256.
152 impl From<PaymentPreimage> for PaymentHash {
153         fn from(value: PaymentPreimage) -> Self {
154                 PaymentHash(Sha256::hash(&value.0).to_byte_array())
155         }
156 }
157
158 /// The payment secret is used to authenticate the sender of an HTLC to the recipient and tie
159 /// multi-part HTLCs together into a single payment.
160 ///
161 /// This is not exported to bindings users as we just use [u8; 32] directly
162 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
163 pub struct PaymentSecret(pub [u8; 32]);
164
165 use bitcoin::bech32;
166 use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, WriteBase32, u5};
167
168 impl FromBase32 for PaymentSecret {
169         type Err = bech32::Error;
170
171         fn from_base32(field_data: &[u5]) -> Result<PaymentSecret, bech32::Error> {
172                 if field_data.len() != 52 {
173                         return Err(bech32::Error::InvalidLength)
174                 } else {
175                         let data_bytes = Vec::<u8>::from_base32(field_data)?;
176                         let mut payment_secret = [0; 32];
177                         payment_secret.copy_from_slice(&data_bytes);
178                         Ok(PaymentSecret(payment_secret))
179                 }
180         }
181 }
182
183 impl ToBase32 for PaymentSecret {
184         fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
185                 (&self.0[..]).write_base32(writer)
186         }
187 }
188
189 impl Base32Len for PaymentSecret {
190         fn base32_len(&self) -> usize {
191                 52
192         }
193 }
194
195 #[cfg(test)]
196 mod tests {
197         use bitcoin::hashes::{
198                 Hash as _,
199                 HashEngine as _,
200                 hex::FromHex as _,
201                 sha256::Hash as Sha256,
202         };
203         use bitcoin::secp256k1::PublicKey;
204         use hex::DisplayHex;
205
206         use super::ChannelId;
207         use crate::ln::channel_keys::RevocationBasepoint;
208         use crate::util::ser::{Readable, Writeable};
209         use crate::util::test_utils;
210         use crate::prelude::*;
211         use crate::io;
212
213         #[test]
214         fn test_channel_id_v1_from_funding_txid() {
215                 let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
216                 assert_eq!(channel_id.0.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020203");
217         }
218
219         #[test]
220         fn test_channel_id_new_from_data() {
221                 let data: [u8; 32] = [2; 32];
222                 let channel_id = ChannelId::from_bytes(data.clone());
223                 assert_eq!(channel_id.0, data);
224         }
225
226         #[test]
227         fn test_channel_id_equals() {
228                 let channel_id11 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
229                 let channel_id12 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
230                 let channel_id21 = ChannelId::v1_from_funding_txid(&[2; 32], 42);
231                 assert_eq!(channel_id11, channel_id12);
232                 assert_ne!(channel_id11, channel_id21);
233         }
234
235         #[test]
236         fn test_channel_id_write_read() {
237                 let data: [u8; 32] = [2; 32];
238                 let channel_id = ChannelId::from_bytes(data.clone());
239
240                 let mut w = test_utils::TestVecWriter(Vec::new());
241                 channel_id.write(&mut w).unwrap();
242
243                 let channel_id_2 = ChannelId::read(&mut io::Cursor::new(&w.0)).unwrap();
244                 assert_eq!(channel_id_2, channel_id);
245                 assert_eq!(channel_id_2.0, data);
246         }
247
248         #[test]
249         fn test_channel_id_display() {
250                 let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
251                 assert_eq!(format!("{}", &channel_id), "0202020202020202020202020202020202020202020202020202020202020203");
252         }
253
254         #[test]
255         fn test_channel_id_v2_from_basepoints() {
256                 // Ours greater than theirs
257                 let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap());
258                 let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
259
260                 let mut engine = Sha256::engine();
261                 engine.input(&theirs.0.serialize());
262                 engine.input(&ours.0.serialize());
263                 let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
264
265                 assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
266
267                 // Theirs greater than ours
268                 let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap());
269                 let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
270
271                 let mut engine = Sha256::engine();
272                 engine.input(&ours.0.serialize());
273                 engine.input(&theirs.0.serialize());
274                 let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
275
276                 assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
277         }
278 }