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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Deterministic bitcoin commitments library, implementing LNPBP standards
// Part of bitcoin protocol core library (BP Core Lib)
//
// Written in 2020-2022 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. 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>.

//! `EmbedCommit: TapTree, Msg -> TapTree', TapNode`

use core::fmt::Debug;
use core::hash::Hash;

use bitcoin::psbt::{IncompleteTapTree, TapTree};
use bitcoin::util::taproot::TaprootBuilderError;
use bitcoin_scripts::taproot::{
    self, Branch, CutError, DfsOrder, DfsOrdering, DfsPath, DfsTraversalError,
    InstillError, MaxDepthExceeded, Node, TaprootScriptTree, TreeNode,
    UnsplittableTree,
};
use bitcoin_scripts::{LeafScript, TapNodeHash, TapScript};
use commit_verify::{
    lnpbp4, CommitVerify, EmbedCommitProof, EmbedCommitVerify,
};

use super::{Lnpbp6, TapretNodePartner, TapretPathProof};
use crate::tapret::TapretPathError;

// TODO: Re-check the use of all error variants
/// Errors during tapret commitment embedding into tapscript tree.
#[derive(Clone, Eq, PartialEq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum TapretTreeError {
    /// the provided commitment data can't be strict encoded. Details: {0}
    #[from]
    StrictEncoding(strict_encoding::Error),

    /// unable to update tap tree with the commitment. Details: {0}
    #[from]
    TapTree(TaprootBuilderError),

    /// the taproot script tree is invalid. Details: {0}
    #[from]
    TreeBuilder(IncompleteTapTree),

    /// the tapret commitment is impossible since the taproot script tree
    /// already has the maximal depth.
    #[from(MaxDepthExceeded)]
    MaxDepthExceeded,

    /// the provided taproot script tree has no revealed nodes to prove the
    /// commitment.
    IncompleteTree(TaprootScriptTree),

    /// unable to add an invalid tapret node partner information {1} to the
    /// merkle path proof at the level {0}.
    InvalidPartnerProof(u8, TapretNodePartner),
}

/// Errors during taproot script tree tapret commitment verification and
/// restoration of the original container structure.
#[derive(
    Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, Display, Error, From
)]
#[display(doc_comments)]
pub enum TapretProofError {
    /// the provided tapret proof does not contain a taproot script tree, i.e.
    /// can't contain a commitment
    EmptyTree,

    /// the provided tapret proof consists of a single node
    #[from(UnsplittableTree)]
    UnsplittableTree,

    /// Errors in the taproot script tree and tapret path proof
    /// correspondences. See [`TapretSourceError`] for details.
    #[from]
    #[display(inner)]
    SourceError(TapretSourceError),
}

impl From<taproot::CutError> for TapretProofError {
    fn from(err: CutError) -> Self {
        match err {
            CutError::UnsplittableTree => Self::UnsplittableTree,
            CutError::DfsTraversal(e) => Self::SourceError(e.into()),
        }
    }
}

/// Errors during taproot script tree tapret commitment ebmedding.
#[derive(
    Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, Display, Error, From
)]
#[display(doc_comments)]
pub enum TapretSourceError {
    /// the length of the constructed tapret path proof exceeds taproot path
    /// length limit.
    #[from(MaxDepthExceeded)]
    MaxDepthExceeded,

    /// the node partner {0} at the level 1 can't be proven not to contain an
    /// alternative tapret commitment.
    InvalidNodePartner(TapretNodePartner),

    /// unable to produce tapret commitment since the commitment path {0} does
    /// not exist within the tree.
    PathNotExists(DfsPath),

    /// the provided taproot script tree contains hidden node {0} at path {1}
    /// and can't be used for tapret commit instillation.
    HiddenNode(TapNodeHash, DfsPath),

    /// the provided tapret commitment path {1} points at the leaf node {0}
    /// and can't be used for tapret commit instillation.
    LeafNode(LeafScript, DfsPath),
}

impl From<InstillError> for TapretSourceError {
    fn from(err: InstillError) -> Self {
        match err {
            InstillError::MaxDepthExceeded => Self::MaxDepthExceeded,
            InstillError::DfsTraversal(e) => e.into(),
        }
    }
}

impl From<DfsTraversalError> for TapretSourceError {
    fn from(err: DfsTraversalError) -> Self {
        match err {
            DfsTraversalError::PathNotExists(path) => Self::PathNotExists(path),
            DfsTraversalError::HiddenNode {
                node_hash,
                failed_path,
                path_leftover: _,
            } => Self::HiddenNode(node_hash, failed_path),
            DfsTraversalError::LeafNode {
                leaf_script,
                failed_path,
                path_leftover: _,
            } => Self::LeafNode(leaf_script, failed_path),
        }
    }
}

impl From<TapretPathError> for TapretSourceError {
    fn from(err: TapretPathError) -> Self {
        match err {
            TapretPathError::MaxDepthExceeded => Self::MaxDepthExceeded,
            TapretPathError::InvalidNodePartner(partner) => {
                Self::InvalidNodePartner(partner)
            }
        }
    }
}

/// Structure wrapping concrete taproot script tree, acting as a source of the
/// tapret commitment, keeping information about DFS path which should be used
/// for embedding tapret commit.
///
/// The structure can be used with [`TapTree`] and [`TaprootScriptTree`].
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TapretSourceInfo<Tree>(Option<Tree>)
where
    Tree: Clone + Eq + Debug;

impl TapretSourceInfo<TaprootScriptTree> {
    /// Validates that the provided path can be used for a tapret commitment
    /// embedding and constructs [`SourceTree`] from the provided
    /// [`TaprootScriptTree`] and a valid path. The path must point to a branch
    /// node in the tree.
    ///
    /// # Errors
    ///
    /// The following errors may happen:
    /// - [`DfsPathError::PathNotExists`], if the path does not exists within
    ///   the tree;
    /// - [`DfsPathError::HiddenNode`], if the path passes through a hidden node
    ///   of the tree;
    /// - [`DfsPathError::LeafNode`], if the path points at a leaf node.
    pub fn with(
        tap_tree: Option<TaprootScriptTree>,
    ) -> Result<Self, TapretSourceError> {
        Ok(TapretSourceInfo(tap_tree))
    }

    /// Returns reference to the script tree root node, if taproot script tree
    /// is present in the source data.
    pub fn as_root_node(&self) -> Option<&TreeNode> {
        self.0.as_ref().map(TaprootScriptTree::as_root_node)
    }

    /// Releases internal [`TapTree`] data, if present.
    #[inline]
    pub fn into_tap_tree(self) -> Option<TapTree> { self.0.map(TapTree::from) }
}

impl TapretSourceInfo<TapTree> {
    /// Validates that the provided path can be used for a tapret commitment
    /// embedding and constructs [`SourceTree`] from the provided [`TapTree`]
    /// and a valid path. The path must point to a branch node in the tree.
    ///
    /// # Errors
    ///
    /// The following errors may happen:
    /// - [`DfsPathError::PathNotExists`], if the path does not exists within
    ///   the tree;
    /// - [`DfsPathError::HiddenNode`], if the path passes through a hidden node
    ///   of the tree;
    /// - [`DfsPathError::LeafNode`], if the path points at a leaf node.
    #[inline]
    pub fn with(tap_tree: Option<TapTree>) -> Result<Self, TapretSourceError> {
        TapretSourceInfo::<TaprootScriptTree>::with(
            tap_tree.map(TaprootScriptTree::from),
        )
        .map(TapretSourceInfo::from)
    }

    /// Releases internal [`TapTree`] data, if present.
    #[inline]
    pub fn into_tap_tree(self) -> Option<TapTree> { self.0 }
}

impl From<&TapretSourceInfo<TapTree>> for TapretSourceInfo<TaprootScriptTree> {
    fn from(source: &TapretSourceInfo<TapTree>) -> Self {
        let tap_tree = source.0.as_ref().cloned().map(TaprootScriptTree::from);
        TapretSourceInfo(tap_tree)
    }
}

impl From<TapretSourceInfo<TaprootScriptTree>> for TapretSourceInfo<TapTree> {
    fn from(source: TapretSourceInfo<TaprootScriptTree>) -> Self {
        let tap_tree = source.0.map(TapTree::from);
        TapretSourceInfo(tap_tree)
    }
}

impl
    EmbedCommitProof<
        lnpbp4::CommitmentHash,
        TapretSourceInfo<TaprootScriptTree>,
        Lnpbp6,
    > for TapretPathProof
{
    fn restore_original_container(
        &self,
        modified_tree: &TapretSourceInfo<TaprootScriptTree>,
    ) -> Result<TapretSourceInfo<TaprootScriptTree>, TapretProofError> {
        let tap_tree = modified_tree
            .0
            .as_ref()
            .cloned()
            .ok_or(TapretProofError::EmptyTree)?;

        match self.partner_node {
            // Taproot has key-only spending
            None => Ok(TapretSourceInfo(None)),
            // Taproot has script spendings
            Some(_) => {
                let (original_tree, _) = tap_tree.split()?;
                Ok(TapretSourceInfo(Some(original_tree)))
            }
        }
    }
}

impl EmbedCommitVerify<lnpbp4::CommitmentHash, Lnpbp6>
    for TapretSourceInfo<TaprootScriptTree>
{
    type Proof = TapretPathProof;
    type CommitError = TapretSourceError;
    type VerifyError = TapretProofError;

    fn embed_commit(
        &mut self,
        msg: &lnpbp4::CommitmentHash,
    ) -> Result<Self::Proof, Self::CommitError> {
        for nonce in 0..=u8::MAX {
            let commitment_script = TapScript::commit(&(*msg, nonce));

            let commitment_node =
                TreeNode::with_tap_script(commitment_script, 0);
            let commitment_subtree = TaprootScriptTree::with(commitment_node)
                .expect("invalid commitment node construction");

            let tap_tree = if let Some(ref mut tap_tree) = self.0 {
                tap_tree
            } else {
                self.0 = Some(commitment_subtree);
                return Ok(TapretPathProof::new());
            };

            let original_tree = tap_tree.clone();
            *tap_tree =
                original_tree.join(commitment_subtree, DfsOrder::Last)?;

            let branch = tap_tree
                .as_root_node()
                .as_branch()
                .expect("instill algorithm is broken");
            let partner = branch.as_dfs_child_node(DfsOrder::First);

            let partner_is_left_node =
                branch.dfs_ordering() == DfsOrdering::LeftRight;

            let partner_proof = match (partner_is_left_node, partner) {
                (true, node) => TapretNodePartner::LeftNode(node.node_hash()),
                (false, TreeNode::Leaf(script, _)) => {
                    TapretNodePartner::RightLeaf(script.clone())
                }
                (false, TreeNode::Hidden(partner_hash, _)) => {
                    return Err(TapretSourceError::HiddenNode(
                        *partner_hash,
                        vec![DfsOrder::First].into(),
                    ))
                }
                (false, TreeNode::Branch(partner_branch, _)) => {
                    TapretNodePartner::right_branch(
                        partner_branch.as_left_node().node_hash(),
                        partner_branch.as_right_node().node_hash(),
                    )
                }
            };

            if partner_is_left_node || nonce == u8::MAX {
                return TapretPathProof::with(partner_proof, nonce)
                    .map_err(TapretSourceError::from);
            }
        }
        unreachable!("for cycle always returns before exiting")
    }
}

impl EmbedCommitProof<lnpbp4::CommitmentHash, TapretSourceInfo<TapTree>, Lnpbp6>
    for TapretPathProof
{
    fn restore_original_container(
        &self,
        modified_container: &TapretSourceInfo<TapTree>,
    ) -> Result<TapretSourceInfo<TapTree>, TapretProofError> {
        EmbedCommitProof::<
            _,
            TapretSourceInfo<TaprootScriptTree>,
            _,
        >::restore_original_container(
            self, &modified_container.into()
        ).map(TapretSourceInfo::into)
    }
}

impl EmbedCommitVerify<lnpbp4::CommitmentHash, Lnpbp6>
    for TapretSourceInfo<TapTree>
{
    type Proof = TapretPathProof;
    type CommitError = TapretSourceError;
    type VerifyError = TapretProofError;

    fn embed_commit(
        &mut self,
        msg: &lnpbp4::CommitmentHash,
    ) -> Result<Self::Proof, Self::CommitError> {
        let mut source = TapretSourceInfo::<TaprootScriptTree>::from(
            self as &TapretSourceInfo<_>,
        );
        let proof = source.embed_commit(msg)?;
        *self = source.into();
        Ok(proof)
    }
}