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
// 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>.

//! Anchors are data structures used in deterministic bitcoin commitments for
//! keeping information about the proof of the commitment in connection to the
//! transaction which contains the commitment, and multi-protocol merkle tree as
//! defined by LNPBP-4.

use std::cmp::Ordering;
use std::io::Write;

use amplify::Wrapper;
use bitcoin::hashes::{sha256, sha256t};
use bitcoin::{Transaction, Txid};
use commit_verify::convolve_commit::ConvolveCommitProof;
use commit_verify::lnpbp4::{self, Message, ProtocolId};
use commit_verify::{
    CommitEncode, CommitVerify, ConsensusCommit, PrehashedProtocol, TaggedHash,
};
#[cfg(feature = "wallet")]
use commit_verify::{EmbedCommitProof, EmbedCommitVerify, TryCommitVerify};
#[cfg(feature = "wallet")]
use psbt::Psbt;
use strict_encoding::StrictEncode;

#[cfg(feature = "wallet")]
use crate::tapret::{Lnpbp6, PsbtCommitError, PsbtVerifyError};
use crate::tapret::{TapretError, TapretProof};

/// Default depth of LNPBP-4 commitment tree
pub const ANCHOR_MIN_LNPBP4_DEPTH: u8 = 3;

static MIDSTATE_ANCHOR_ID: [u8; 32] = [
    148, 72, 59, 59, 150, 173, 163, 140, 159, 237, 69, 118, 104, 132, 194, 110,
    250, 108, 1, 140, 74, 248, 152, 205, 70, 32, 184, 87, 20, 102, 127, 20,
];

/// Tag used for [`AnchorId`] hash type
pub struct AnchorIdTag;

impl sha256t::Tag for AnchorIdTag {
    #[inline]
    fn engine() -> sha256::HashEngine {
        let midstate = sha256::Midstate::from_inner(MIDSTATE_ANCHOR_ID);
        sha256::HashEngine::from_midstate(midstate, 64)
    }
}

/// Unique anchor identifier equivalent to the anchor commitment hash
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", transparent)
)]
#[derive(
    Wrapper, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, From
)]
#[wrapper(
    Debug, Display, LowerHex, Index, IndexRange, IndexFrom, IndexTo, IndexFull
)]
pub struct AnchorId(sha256t::Hash<AnchorIdTag>);

impl<Msg> CommitVerify<Msg, PrehashedProtocol> for AnchorId
where
    Msg: AsRef<[u8]>,
{
    #[inline]
    fn commit(msg: &Msg) -> AnchorId { AnchorId::hash(msg) }
}

impl strict_encoding::Strategy for AnchorId {
    type Strategy = strict_encoding::strategies::Wrapped;
}

#[cfg(feature = "wallet")]
/// Errors working with anchors.
#[derive(Clone, Eq, PartialEq, Hash, Debug, Display, Error, From)]
#[display(inner)]
pub enum Error {
    /// Errors embedding LNPBP-4 commitment into PSBT
    #[from]
    EmbedCommit(PsbtCommitError),

    /// Errors constructing LNPBP-4 commitment
    #[from]
    Lnpbp4(lnpbp4::Error),
}

/// Errors verifying anchors.
#[derive(Clone, Eq, PartialEq, Debug, Display, Error, From)]
#[display(inner)]
pub enum VerifyError {
    /// Tapret commitment verification failure.
    #[from]
    Tapret(TapretError),

    /// LNPBP-4 invalid proof.
    #[from(lnpbp4::UnrelatedProof)]
    Lnpbp4UnrelatedProtocol,
}

/// Anchor is a data structure used in deterministic bitcoin commitments for
/// keeping information about the proof of the commitment in connection to the
/// transaction which contains the commitment, and multi-protocol merkle tree as
/// defined by LNPBP-4.
#[derive(Clone, PartialEq, Eq, Debug, StrictEncode, StrictDecode)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
pub struct Anchor<L: lnpbp4::Proof> {
    /// Transaction containing deterministic bitcoin commitment.
    pub txid: Txid,

    /// Structured multi-protocol LNPBP-4 data the transaction commits to.
    pub lnpbp4_proof: L,

    /// Proof of the DBC commitment.
    pub dbc_proof: Proof,
}

impl CommitEncode for Anchor<lnpbp4::MerkleBlock> {
    fn commit_encode<E: Write>(&self, mut e: E) -> usize {
        let mut len = self
            .txid
            .strict_encode(&mut e)
            .expect("memory encoders do not fail");
        len += self
            .dbc_proof
            .strict_encode(&mut e)
            .expect("memory encoders do not fail");
        len + self.lnpbp4_proof.commit_encode(e)
    }
}

impl ConsensusCommit for Anchor<lnpbp4::MerkleBlock> {
    type Commitment = AnchorId;
}

impl Ord for Anchor<lnpbp4::MerkleBlock> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.anchor_id().cmp(&other.anchor_id())
    }
}

impl PartialOrd for Anchor<lnpbp4::MerkleBlock> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Error merging two [`Anchor`]s.
#[derive(
    Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display, Error,
    From
)]
#[display(doc_comments)]
pub enum MergeError {
    /// Error merging two [`MultiCommitBlock`]s.
    #[display(inner)]
    #[from(lnpbp4::UnrelatedProof)]
    Lnpbp4Mismatch,

    /// anchors can't be merged since they have different witness transactions
    TxidMismatch,

    /// anchors can't be merged since they have different proofs
    ProofMismatch,
}

impl Anchor<lnpbp4::MerkleBlock> {
    /// Returns id of the anchor (commitment hash).
    #[inline]
    pub fn anchor_id(&self) -> AnchorId { self.consensus_commit() }

    /// Constructs anchor and embeds LNPBP4 commitment into PSBT.
    #[cfg(feature = "wallet")]
    pub fn commit(
        psbt: &mut Psbt,
        messages: lnpbp4::MessageMap,
    ) -> Result<Anchor<lnpbp4::MerkleBlock>, Error> {
        let multi_source = lnpbp4::MultiSource {
            min_depth: ANCHOR_MIN_LNPBP4_DEPTH,
            messages,
        };
        let lnpbp4_block = lnpbp4::MerkleTree::try_commit(&multi_source)?;
        let anchor = psbt.embed_commit(&lnpbp4_block)?;
        Ok(Anchor {
            txid: anchor.txid,
            lnpbp4_proof: lnpbp4::MerkleBlock::from(anchor.lnpbp4_proof),
            dbc_proof: anchor.dbc_proof,
        })
    }
}

impl Anchor<lnpbp4::MerkleProof> {
    /// Verifies that the transaction commits to the anchor and the anchor
    /// commits to the given message under the given protocol.
    pub fn verify(
        &self,
        protocol_id: ProtocolId,
        message: Message,
        tx: Transaction,
    ) -> Result<bool, VerifyError> {
        self.dbc_proof
            .verify(&self.lnpbp4_proof.convolve(protocol_id, message)?, tx)
            .map_err(VerifyError::from)
    }

    /// Verifies that the anchor commits to the given message under the given
    /// protocol.
    pub fn convolve(
        &self,
        protocol_id: ProtocolId,
        message: Message,
    ) -> Result<lnpbp4::CommitmentHash, lnpbp4::UnrelatedProof> {
        self.lnpbp4_proof.convolve(protocol_id, message)
    }
}

impl Anchor<lnpbp4::MerkleBlock> {
    /// Conceals all LNPBP-4 data except specific protocol and converts anchor
    /// into merkle proof anchor.
    pub fn into_merkle_proof(
        self,
        protocol: impl Into<ProtocolId>,
    ) -> Result<Anchor<lnpbp4::MerkleProof>, lnpbp4::LeafNotKnown> {
        let lnpbp4_proof =
            self.lnpbp4_proof.to_merkle_proof(protocol.into())?;
        Ok(Anchor {
            txid: self.txid,
            lnpbp4_proof,
            dbc_proof: self.dbc_proof,
        })
    }

    /// Conceals all LNPBP-4 data except specific protocol.
    pub fn conceal_except(
        &mut self,
        protocols: impl AsRef<[ProtocolId]>,
    ) -> Result<usize, lnpbp4::LeafNotKnown> {
        self.lnpbp4_proof.conceal_except(protocols)
    }

    /// Merges two anchors keeping revealed data.
    pub fn merge_reveal(mut self, other: Self) -> Result<Self, MergeError> {
        if self.txid != other.txid {
            return Err(MergeError::TxidMismatch);
        }
        if self.dbc_proof != other.dbc_proof {
            return Err(MergeError::ProofMismatch);
        }
        self.lnpbp4_proof.merge_reveal(other.lnpbp4_proof)?;
        Ok(self)
    }
}

#[cfg(feature = "wallet")]
impl EmbedCommitProof<lnpbp4::MerkleTree, Psbt, Lnpbp6>
    for Anchor<lnpbp4::MerkleTree>
{
    fn restore_original_container(
        &self,
        psbt: &Psbt,
    ) -> Result<Psbt, PsbtVerifyError> {
        match self.dbc_proof {
            Proof::Opret1st => todo!("Implement OpRet"),
            Proof::Tapret1st(ref proof) => {
                proof.restore_original_container(psbt)
            }
        }
    }
}

#[cfg(feature = "wallet")]
impl EmbedCommitVerify<lnpbp4::MerkleTree, Lnpbp6> for Psbt {
    type Proof = Anchor<lnpbp4::MerkleTree>;
    type CommitError = PsbtCommitError;
    type VerifyError = PsbtVerifyError;

    fn embed_commit(
        &mut self,
        msg: &lnpbp4::MerkleTree,
    ) -> Result<Self::Proof, Self::CommitError> {
        let lnpbp4_block = msg.clone();

        // TODO: Implement OpRet
        let proof = self.embed_commit(&lnpbp4_block.consensus_commit())?;

        let anchor = Anchor {
            txid: self.to_txid(),
            lnpbp4_proof: lnpbp4_block,
            dbc_proof: Proof::Tapret1st(proof),
        };

        // TODO: Update PSBT

        Ok(anchor)
    }
}

/// Type and type-specific proof information of a deterministic bitcoin
/// commitment.
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[derive(StrictEncode, StrictDecode)]
#[strict_encoding(by_order)]
#[non_exhaustive]
pub enum Proof {
    /// Opret commitment (no extra-transaction proof is required).
    Opret1st,

    /// Tapret commitment and a proof of it.
    Tapret1st(TapretProof),
}

impl Proof {
    /// Verifies validity of the proof.
    pub fn verify(
        &self,
        msg: &lnpbp4::CommitmentHash,
        tx: Transaction,
    ) -> Result<bool, TapretError> {
        match self {
            Proof::Opret1st => todo!("Implement opret commitment verification"),
            Proof::Tapret1st(proof) => {
                ConvolveCommitProof::<_, Transaction, _>::verify(proof, msg, tx)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use commit_verify::tagged_hash;

    use super::*;

    #[test]
    fn test_anchor_id_midstate() {
        let midstate = tagged_hash::Midstate::with(b"bp:dbc:anchor");
        assert_eq!(midstate.into_inner().into_inner(), MIDSTATE_ANCHOR_ID);
    }
}