1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Wallet-level libraries for bitcoin protocol by LNP/BP Association
//
// Written in 2020-2022 by
//     Dr. Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// This software is distributed without any warranty.
//
// You should have received a copy of the Apache-2.0 License
// along with this software.
// If not, see <https://opensource.org/licenses/Apache-2.0>.

use amplify::Slice32;
use bitcoin::hashes::Hash;
use commit_verify::lnpbp4;
use commit_verify::lnpbp4::{Message, ProtocolId};
use strict_encoding::{StrictDecode, StrictEncode};

use crate::{Output, ProprietaryKey, Psbt};

/// PSBT proprietary key prefix used for LNPBP4 commitment-related data.
pub const PSBT_LNPBP4_PREFIX: &[u8] = b"LNPBP4";

/// Proprietary key subtype for storing LNPBP4 information about each specific
/// protocol.
pub const PSBT_GLOBAL_LNPBP4_PROTOCOL_INFO: u8 = 0x00;

/// Proprietary key subtype for storing LNPBP4 single commitment message under
/// some protocol in global map.
pub const PSBT_OUT_LNPBP4_MESSAGE: u8 = 0x00;
/// Proprietary key subtype for storing LNPBP4 entropy constant.
pub const PSBT_OUT_LNPBP4_ENTROPY: u8 = 0x01;
/// Proprietary key subtype for storing LNPBP4 requirement for a minimal tree
/// size.
pub const PSBT_OUT_LNPBP4_MIN_TREE_DEPTH: u8 = 0x02;

/// Extension trait for static functions returning LNPBP4-related proprietary
/// keys.
pub trait ProprietaryKeyLnpbp4 {
    fn lnpbp4_message(protocol_id: ProtocolId) -> ProprietaryKey;
    fn lnpbp4_entropy() -> ProprietaryKey;
    fn lnpbp4_min_tree_depth() -> ProprietaryKey;
    fn lnpbp4_protocol_info(protocol_id: ProtocolId) -> ProprietaryKey;
}

impl ProprietaryKeyLnpbp4 for ProprietaryKey {
    /// Constructs [`PSBT_OUT_LNPBP4_MESSAGE`] proprietary key.
    fn lnpbp4_message(protocol_id: ProtocolId) -> ProprietaryKey {
        ProprietaryKey {
            prefix: PSBT_LNPBP4_PREFIX.to_vec(),
            subtype: PSBT_OUT_LNPBP4_MESSAGE,
            key: protocol_id.to_vec(),
        }
    }

    /// Constructs [`PSBT_OUT_LNPBP4_ENTROPY`] proprietary key.
    fn lnpbp4_entropy() -> ProprietaryKey {
        ProprietaryKey {
            prefix: PSBT_LNPBP4_PREFIX.to_vec(),
            subtype: PSBT_OUT_LNPBP4_ENTROPY,
            key: empty!(),
        }
    }

    /// Constructs [`PSBT_OUT_LNPBP4_MIN_TREE_DEPTH`] proprietary key.
    fn lnpbp4_min_tree_depth() -> ProprietaryKey {
        ProprietaryKey {
            prefix: PSBT_LNPBP4_PREFIX.to_vec(),
            subtype: PSBT_OUT_LNPBP4_MIN_TREE_DEPTH,
            key: empty!(),
        }
    }

    /// Constructs [`PSBT_GLOBAL_LNPBP4_PROTOCOL_INFO`] proprietary key.
    fn lnpbp4_protocol_info(protocol_id: ProtocolId) -> ProprietaryKey {
        ProprietaryKey {
            prefix: PSBT_LNPBP4_PREFIX.to_vec(),
            subtype: PSBT_GLOBAL_LNPBP4_PROTOCOL_INFO,
            key: protocol_id.to_vec(),
        }
    }
}

/// Errors processing LNPBP4-related proprietary PSBT keys and their values.
#[derive(
    Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display, Error, From
)]
#[display(doc_comments)]
pub enum Lnpbp4KeyError {
    /// The key contains invalid value
    #[from(strict_encoding::Error)]
    #[from(bitcoin::hashes::Error)]
    InvalidKeyValue,

    /// The key is already present, but has a different value
    AlreadySet,
}

#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Default)]
#[derive(StrictEncode, StrictDecode)]
pub struct Lnpbp4Info {
    pub hash_tag: Option<String>,
    pub inner_id: Option<Slice32>,
}

/// Extension trait for [`Psbt`] for working with proprietary LNPBP4 keys.
impl Psbt {
    /// Returns an information about the given LNPBP4 [`ProtocolId`], if any.
    ///
    /// # Errors
    ///
    /// If the key is present, but it's value can't be deserialized as a valid
    /// protocol information block.
    pub fn lnpbp4_protocol_info(
        &self,
        protocol_id: ProtocolId,
    ) -> Result<Lnpbp4Info, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_protocol_info(protocol_id);
        Ok(self
            .proprietary
            .get(&key)
            .map(Lnpbp4Info::strict_deserialize)
            .transpose()?
            .unwrap_or_default())
    }

    /// Adds LNPBP4 protocol information.
    ///
    /// # Returns
    ///
    /// `true`, if the protocol information was successfully added, `false` if
    /// it was already present.
    ///
    /// # Errors
    ///
    /// If the key for the given [`ProtocolId`] is already present and the
    /// information was different.
    pub fn set_lnpbp4_protocol_info(
        &mut self,
        protocol_id: ProtocolId,
        hash_tag: Option<String>,
        inner_id: Option<Slice32>,
    ) -> Result<bool, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_protocol_info(protocol_id);
        let val = Lnpbp4Info { hash_tag, inner_id }
            .strict_serialize()
            .expect("memory serializer should not fail");
        if let Some(v) = self.proprietary.get(&key) {
            if v != &val {
                return Err(Lnpbp4KeyError::InvalidKeyValue);
            }
            return Ok(false);
        }
        self.proprietary.insert(key, val);
        Ok(true)
    }
}

/// Extension trait for [`Output`] for working with proprietary LNPBP4
/// keys.
impl Output {
    /// Returns [`lnpbp4::MessageMap`] constructed from the proprietary key
    /// data.
    pub fn lnpbp4_message_map(&self) -> Result<lnpbp4::MessageMap, Lnpbp4KeyError> {
        self.proprietary
            .iter()
            .filter(|(key, _)| {
                key.prefix == PSBT_LNPBP4_PREFIX && key.subtype == PSBT_OUT_LNPBP4_MESSAGE
            })
            .map(|(key, val)| {
                Ok((
                    ProtocolId::from_slice(&key.key).ok_or(Lnpbp4KeyError::InvalidKeyValue)?,
                    Message::from_slice(val).map_err(|_| Lnpbp4KeyError::InvalidKeyValue)?,
                ))
            })
            .collect()
    }

    /// Returns a valid LNPBP-4 [`Message`] associated with the given
    /// [`ProtocolId`], if any.
    ///
    /// # Errors
    ///
    /// If the key is present, but it's value can't be deserialized as a valid
    /// [`Message`].
    pub fn lnpbp4_message(
        &self,
        protocol_id: ProtocolId,
    ) -> Result<Option<Message>, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_message(protocol_id);
        self.proprietary
            .get(&key)
            .map(Message::strict_deserialize)
            .transpose()
            .map_err(Lnpbp4KeyError::from)
    }

    /// Returns a valid LNPBP-4 entropy value, if present.
    ///
    /// # Errors
    ///
    /// If the key is present, but it's value can't be deserialized as a valid
    /// entropy value.
    pub fn lnpbp4_entropy(&self) -> Result<Option<u64>, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_entropy();
        self.proprietary
            .get(&key)
            .map(u64::strict_deserialize)
            .transpose()
            .map_err(Lnpbp4KeyError::from)
    }

    /// Returns a valid LNPBP-4 minimal tree depth value, if present.
    ///
    /// # Errors
    ///
    /// If the key is present, but it's value can't be deserialized as a valid
    /// minimal tree depth value.
    pub fn lnpbp4_min_tree_depth(&self) -> Result<Option<u8>, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_min_tree_depth();
        self.proprietary
            .get(&key)
            .map(u8::strict_deserialize)
            .transpose()
            .map_err(Lnpbp4KeyError::from)
    }

    /// Sets LNPBP4 [`Message`] for the given [`ProtocolId`].
    ///
    /// # Returns
    ///
    /// `true`, if the message was set successfully, `false` if this message was
    /// already present for this protocol.
    ///
    /// # Errors
    ///
    /// If the key for the given [`ProtocolId`] is already present and the
    /// message is different.
    pub fn set_lnpbp4_message(
        &mut self,
        protocol_id: ProtocolId,
        message: Message,
    ) -> Result<bool, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_message(protocol_id);
        let val = message
            .strict_serialize()
            .expect("memory serializer should not fail");
        if let Some(v) = self.proprietary.get(&key) {
            if v != &val {
                return Err(Lnpbp4KeyError::InvalidKeyValue);
            }
            return Ok(false);
        }
        self.proprietary.insert(key, val);
        Ok(true)
    }

    /// Sets LNPBP4 entropy value.
    ///
    /// # Returns
    ///
    /// `true`, if the entropy was set successfully, `false` if this entropy
    /// value was already set.
    ///
    /// # Errors
    ///
    /// If the entropy was already set with a different value than the provided
    /// one.
    pub fn set_lnpbp4_entropy(&mut self, entropy: u64) -> Result<bool, Lnpbp4KeyError> {
        let key = ProprietaryKey::lnpbp4_entropy();
        let val = entropy
            .strict_serialize()
            .expect("memory serializer should not fail");
        if let Some(v) = self.proprietary.get(&key) {
            if v != &val {
                return Err(Lnpbp4KeyError::InvalidKeyValue);
            }
            return Ok(false);
        }
        self.proprietary.insert(key, val);
        Ok(true)
    }

    /// Sets LNPBP4 min tree depth value.
    ///
    /// # Returns
    ///
    /// Previous minimal tree depth value, if it was present and valid - or None
    /// if the value was absent or invalid (the new value is still assigned).
    pub fn set_lnpbp4_min_tree_depth(&mut self, min_depth: u8) -> Option<u8> {
        let key = ProprietaryKey::lnpbp4_min_tree_depth();
        let val = min_depth
            .strict_serialize()
            .expect("memory serializer should not fail");
        self.proprietary
            .insert(key, val)
            .and_then(|v| u8::strict_deserialize(v).ok())
    }
}