Skip to main content

bitcoin_silent_payments/
lib.rs

1// SPDX-License-Identifier: MIT
2
3#[cfg(feature = "compat_v32")]
4pub mod compat_v32;
5pub mod input;
6/// This library provides a small set of structs and methods to help in the implementation of the
7/// Silent Payments protocol.
8///
9/// Silent Payments are a privacy-enhancing protocol in Bitcoin that allows recipients to receive
10/// payments without revealing their code or creating any on-chain link between payments.
11///
12/// This library **does not implement** the cryptographic primitives required for the full
13/// implementation of Silent Payments.
14pub mod receive;
15pub mod send;
16
17pub use bitcoin_network_kind;
18pub use bitcoin_primitives;
19pub use secp256k1;
20
21use bitcoin_primitives::OutPoint;
22
23/// NUMS-H point from BIP 341. A taproot input using this as its internal
24/// key is skipped for BIP 352 shared-secret derivation.
25#[rustfmt::skip]
26pub const NUMS_H: [u8; 32] = [
27    0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54,
28    0xb7, 0x8b, 0x4b, 0x60, 0x35, 0xe9, 0x7a, 0x5e,
29    0x07, 0x8a, 0x5a, 0x0f, 0x28, 0xec, 0x96, 0xd5,
30    0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0,
31];
32
33/// Returns true if `x` equals the BIP 341 NUMS-H point.
34///
35/// A taproot input whose internal key is NUMS-H is a script-path-only spend
36/// and must be excluded from BIP 352 shared-secret derivation.
37pub fn is_nums(x: &[u8; 32]) -> bool {
38    *x == NUMS_H
39}
40
41/// Error type returned when attempting to retrieve the minimum outpoint
42/// from a [`LexMin`] that has not received any updates.
43///
44/// This error indicates that [`LexMin::bytes`] was called before any
45/// outpoints were provided via [`LexMin::update`].
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct NoMinOutpoint;
48
49impl core::error::Error for NoMinOutpoint {}
50
51impl core::fmt::Display for NoMinOutpoint {
52    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53        write!(f, "No minimal outpoint, update at least once")
54    }
55}
56
57/// A structure for tracking the lexicographically minimal [`OutPoint`].
58///
59/// `LexMin` maintains a reference to the smallest outpoint seen so far, using lexicographic
60/// comparison. The comparison first orders by Txid bytes, then by output index in little-endian
61/// byte order.
62///
63/// # Lifetime
64/// The `'a` lifetime parameter ensures that the tracked outpoint references
65/// remain valid for the duration of the `LexMin` instance.
66///
67/// # Example
68/// ```rust
69/// # use bitcoin_silent_payments::LexMin;
70/// # use bitcoin_primitives::{Txid, OutPoint};
71/// let mut tracker = LexMin::default();
72///
73/// let outpoint1 = OutPoint {
74///     txid: Txid::from_byte_array([8u8; 32]),
75///     vout: 0,
76/// };
77/// let outpoint2 = OutPoint {
78///     txid: Txid::from_byte_array([5u8; 32]),
79///     vout: 100,
80/// };
81///
82/// tracker.update(&outpoint1);
83/// tracker.update(&outpoint2);
84///
85/// let min_bytes = tracker.bytes().expect("updated at least once");
86/// ```
87#[derive(Default)]
88pub struct LexMin {
89    /// The current minimum outpoint, or `None` if no outpoints have been provided.
90    current_min: Option<OutPoint>,
91}
92
93impl LexMin {
94    /// Updates the tracker with a new outpoint and returns the current minimum.
95    ///
96    /// Compares the provided `outpoint` with the current minimum using
97    /// lexicographic ordering:
98    /// 1. First, compares txids as byte arrays
99    /// 2. If txids are equal, compares output indices as little-endian bytes
100    ///
101    /// # Arguments
102    /// * `outpoint` - A reference to the outpoint to compare against the current minimum.
103    ///
104    /// # Returns
105    /// A reference to the lexicographically smallest outpoint seen so far,
106    /// including the newly provided one.
107    pub fn update(&mut self, outpoint: &OutPoint) {
108        if let Some(ref min) = self.current_min {
109            let new_min = core::cmp::min_by(outpoint, min, |a, b| {
110                let a_txid = a.txid.to_byte_array();
111                let b_txid = b.txid.to_byte_array();
112
113                match a_txid.cmp(&b_txid) {
114                    core::cmp::Ordering::Equal => {
115                        let a_vout_bytes = a.vout.to_le_bytes();
116                        let b_vout_bytes = b.vout.to_le_bytes();
117                        a_vout_bytes.cmp(&b_vout_bytes)
118                    }
119                    other => other,
120                }
121            });
122            self.current_min = Some(*new_min);
123        } else {
124            self.current_min = Some(*outpoint);
125        }
126    }
127
128    /// Returns the 36-byte serialized representation of the minimum outpoint.
129    ///
130    /// The format is:
131    /// - bytes `[0..32]`: Txid as a byte array
132    /// - bytes `[32..36]`: Output index as little-endian `u32`
133    ///
134    /// # Errors
135    /// Returns [`NoMinOutpoint`] if [`LexMin::update`] has never been called.
136    ///
137    /// # Returns
138    /// A 36-byte array containing the serialized minimum outpoint.
139    pub fn bytes(&self) -> Result<[u8; 36], NoMinOutpoint> {
140        if let Some(min) = self.current_min {
141            let mut result = [0u8; 36];
142            result[..32].copy_from_slice(&min.txid.to_byte_array());
143            result[32..36].copy_from_slice(&min.vout.to_le_bytes());
144
145            Ok(result)
146        } else {
147            Err(NoMinOutpoint)
148        }
149    }
150}
151
152#[cfg(test)]
153#[cfg_attr(coverage_nightly, coverage(off))]
154mod test {
155    mod lex_min {
156        use crate::LexMin;
157        use bitcoin_primitives::{OutPoint, Txid};
158
159        #[test]
160        fn different_txids_and_vouts() {
161            let mut lex_min = LexMin::default();
162            let outpoints = [
163                OutPoint {
164                    txid: Txid::from_byte_array([3u8; 32]),
165                    vout: 2,
166                },
167                OutPoint {
168                    txid: Txid::from_byte_array([2u8; 32]),
169                    vout: 1,
170                },
171                OutPoint {
172                    txid: Txid::from_byte_array([5u8; 32]),
173                    vout: 3,
174                },
175            ];
176
177            for outpoint in outpoints.iter() {
178                lex_min.update(outpoint);
179            }
180
181            let result = lex_min.bytes().expect("should succeed");
182
183            let mut expected_bytes = [2u8; 36];
184            expected_bytes[32..36].copy_from_slice(&1u32.to_le_bytes());
185
186            assert_eq!(result, expected_bytes);
187        }
188
189        #[test]
190        fn fail_if_not_updated() {
191            let e = LexMin::default().bytes().expect_err("should fail");
192            assert_eq!("No minimal outpoint, update at least once", e.to_string());
193        }
194
195        #[test]
196        fn identical_txid_different_vouts() {
197            let mut lex_min = LexMin::default();
198            let txid = Txid::from_byte_array([0u8; 32]);
199            let outpoints = [
200                OutPoint { txid, vout: 10 },
201                OutPoint { txid, vout: 2 },
202                OutPoint { txid, vout: 5 },
203            ];
204
205            for outpoint in outpoints.iter() {
206                lex_min.update(outpoint);
207            }
208
209            let result = lex_min.bytes().expect("should succeed");
210
211            let mut expected_bytes = [0u8; 36];
212            expected_bytes[32..36].copy_from_slice(&2u32.to_le_bytes());
213            assert_eq!(result, expected_bytes);
214        }
215
216        #[test]
217        fn same_vout_different_txid() {
218            let mut lex_min = LexMin::default();
219            let outpoints = [
220                OutPoint {
221                    txid: Txid::from_byte_array([2u8; 32]),
222                    vout: 7,
223                },
224                OutPoint {
225                    txid: Txid::from_byte_array([1u8; 32]),
226                    vout: 7,
227                },
228                OutPoint {
229                    txid: Txid::from_byte_array([3u8; 32]),
230                    vout: 7,
231                },
232            ];
233
234            for outpoint in outpoints.iter() {
235                lex_min.update(outpoint);
236            }
237
238            let result = lex_min.bytes().expect("should succeed");
239
240            let mut expected_bytes = [1u8; 36];
241            expected_bytes[32..36].copy_from_slice(&7u32.to_le_bytes());
242            assert_eq!(result, expected_bytes);
243        }
244
245        #[test]
246        fn edge_case_vout_is_u32_max() {
247            let mut lex_min = LexMin::default();
248            let outpoints = [
249                OutPoint {
250                    txid: Txid::from_byte_array([1u8; 32]),
251                    vout: u32::MAX,
252                },
253                OutPoint {
254                    txid: Txid::from_byte_array([1u8; 32]),
255                    vout: u32::MIN,
256                },
257            ];
258
259            for outpoint in outpoints.iter() {
260                lex_min.update(outpoint);
261            }
262
263            let result = lex_min.bytes().expect("should succeed");
264
265            let mut expected_bytes = [1u8; 36];
266            expected_bytes[..32].copy_from_slice(&[1u8; 32]);
267            expected_bytes[32..36].copy_from_slice(&u32::MIN.to_le_bytes());
268            assert_eq!(result, expected_bytes);
269        }
270
271        #[test]
272        fn txid_takes_precedence() {
273            let mut lex_min = LexMin::default();
274            let outpoints = [
275                OutPoint {
276                    txid: Txid::from_byte_array([8u8; 32]),
277                    vout: 0,
278                },
279                OutPoint {
280                    txid: Txid::from_byte_array([5u8; 32]),
281                    vout: 100,
282                },
283            ];
284
285            for outpoint in outpoints.iter() {
286                lex_min.update(outpoint);
287            }
288
289            let result = lex_min.bytes().expect("should succeed");
290
291            let mut expected_bytes = [5u8; 36];
292            expected_bytes[32..36].copy_from_slice(&100u32.to_le_bytes());
293            assert_eq!(result, expected_bytes);
294        }
295
296        #[test]
297        fn txid_endianness_matters() {
298            let mut lex_min = LexMin::default();
299            // big endian: 0x[00][00][00][01]
300            // big endian: 0x[a1][b1][c1][d1]
301            let mut txid_bytes_be = [0u8; 32];
302            txid_bytes_be[0] = 1;
303
304            // little endian: 0x[01][00][00][00]
305            // little endian: 0x[a2][b2][c2][d2]
306            let mut txid_bytes_le = [0u8; 32];
307            txid_bytes_le[31] = 1;
308
309            let outpoints = [
310                OutPoint {
311                    txid: Txid::from_byte_array(txid_bytes_be),
312                    vout: 1,
313                },
314                OutPoint {
315                    txid: Txid::from_byte_array(txid_bytes_le),
316                    vout: 1,
317                },
318            ];
319
320            for outpoint in outpoints.iter() {
321                lex_min.update(outpoint);
322            }
323
324            // if Txid is big endian then: [a1] < [a2] => expected_bytes = txid_bytes_be
325            // if Txid is little endian then: [d2] < [d1] => expected_bytes = txid_bytes_le
326            let result = lex_min.bytes().expect("should succeed");
327
328            let mut expected_bytes = [0u8; 36];
329            // Txid is little endian
330            expected_bytes[31] = 1;
331            expected_bytes[32..36].copy_from_slice(&1u32.to_le_bytes());
332
333            assert_eq!(result, expected_bytes);
334        }
335    }
336}