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
// Bitcoin protocol single-use-seals library.
//
// SPDX-License-Identifier: Apache-2.0
//
// Written in 2019-2023 by
//     Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// Copyright (C) 2019-2023 LNP/BP Standards Association. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! TxOut single-use-seals.

use std::fmt::{self, Display, Formatter};
use std::str::FromStr;

use amplify::hex;
use bc::{Outpoint, Txid, Vout};

use crate::txout::seal::{SealTxid, TxPtr};
use crate::txout::{CloseMethod, MethodParseError, TxoSeal, WitnessVoutError};

/// Revealed seal definition which may point to a witness transactions and does
/// not contain blinding data.
///
/// These data are not used within RGB contract data, thus we do not have a
/// commitment and conceal procedures (since without knowing a blinding factor
/// we can't perform them).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = dbc::LIB_NAME_BPCORE)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"))]
pub struct ExplicitSeal<Id: SealTxid> {
    /// Commitment to the specific seal close method [`CloseMethod`] which must
    /// be used to close this seal.
    pub method: CloseMethod,

    /// Txid of the seal definition.
    ///
    /// It may be missed in situations when ID of a transaction is not known,
    /// but the transaction still can be identified by some other means (for
    /// instance it is a transaction spending specific outpoint, like other
    /// seal definition).
    pub txid: Id,

    /// Tx output number, which should be always known.
    pub vout: Vout,
}

impl TryFrom<&ExplicitSeal<TxPtr>> for Outpoint {
    type Error = WitnessVoutError;

    #[inline]
    fn try_from(reveal: &ExplicitSeal<TxPtr>) -> Result<Self, Self::Error> {
        reveal
            .txid
            .map_to_outpoint(reveal.vout)
            .ok_or(WitnessVoutError)
    }
}

impl TryFrom<ExplicitSeal<TxPtr>> for Outpoint {
    type Error = WitnessVoutError;

    #[inline]
    fn try_from(reveal: ExplicitSeal<TxPtr>) -> Result<Self, Self::Error> {
        Outpoint::try_from(&reveal)
    }
}

impl From<&ExplicitSeal<Txid>> for Outpoint {
    fn from(seal: &ExplicitSeal<Txid>) -> Self { Outpoint::new(seal.txid, seal.vout) }
}

impl From<ExplicitSeal<Txid>> for Outpoint {
    fn from(seal: ExplicitSeal<Txid>) -> Self { Outpoint::from(&seal) }
}

impl<Id: SealTxid> From<&Outpoint> for ExplicitSeal<Id> {
    #[inline]
    fn from(outpoint: &Outpoint) -> Self {
        Self {
            method: CloseMethod::TapretFirst,
            txid: outpoint.txid.into(),
            vout: outpoint.vout,
        }
    }
}

impl<Id: SealTxid> From<Outpoint> for ExplicitSeal<Id> {
    #[inline]
    fn from(outpoint: Outpoint) -> Self { ExplicitSeal::from(&outpoint) }
}

impl<Id: SealTxid> TxoSeal for ExplicitSeal<Id> {
    #[inline]
    fn method(&self) -> CloseMethod { self.method }

    #[inline]
    fn txid(&self) -> Option<Txid> { self.txid.txid() }

    #[inline]
    fn vout(&self) -> Vout { self.vout }

    #[inline]
    fn outpoint(&self) -> Option<Outpoint> { self.txid.map_to_outpoint(self.vout) }

    #[inline]
    fn txid_or(&self, default_txid: Txid) -> Txid { self.txid.txid_or(default_txid) }

    #[inline]
    fn outpoint_or(&self, default_txid: Txid) -> Outpoint {
        Outpoint::new(self.txid.txid_or(default_txid), self.vout)
    }
}

impl<Id: SealTxid> ExplicitSeal<Id> {
    /// Constructs seal for the provided outpoint and seal closing method.
    #[inline]
    pub fn new(method: CloseMethod, outpoint: Outpoint) -> ExplicitSeal<Id> {
        Self {
            method,
            txid: Id::from(outpoint.txid),
            vout: outpoint.vout,
        }
    }

    /// Constructs seal.
    #[inline]
    pub fn with(method: CloseMethod, txid: Id, vout: impl Into<Vout>) -> ExplicitSeal<Id> {
        ExplicitSeal {
            method,
            txid,
            vout: vout.into(),
        }
    }
}

/// Errors happening during parsing string representation of different forms of
/// single-use-seals
#[derive(Clone, PartialEq, Eq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum ParseError {
    /// single-use-seal must start with method name (e.g. 'tapret1st' etc)
    MethodRequired,

    /// full transaction id is required for the seal specification
    TxidRequired,

    /// wrong seal close method id
    #[display(inner)]
    #[from]
    WrongMethod(MethodParseError),

    /// unable to parse transaction id value; it must be 64-character
    /// hexadecimal string, however {0}
    WrongTxid(hex::Error),

    /// unable to parse transaction vout value; it must be a decimal unsigned
    /// integer
    WrongVout,

    /// wrong structure of seal string representation
    WrongStructure,
}

impl<Id: SealTxid> FromStr for ExplicitSeal<Id> {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut split = s.split(&[':', '#'][..]);
        match (split.next(), split.next(), split.next(), split.next()) {
            (Some("~"), ..) | (Some(""), ..) => Err(ParseError::MethodRequired),
            (Some(_), Some(""), ..) => Err(ParseError::TxidRequired),
            (Some(method), Some(txid), Some(vout), None) => Ok(ExplicitSeal {
                method: method.parse()?,
                txid: Id::from_str(txid).map_err(ParseError::WrongTxid)?,
                vout: vout.parse().map_err(|_| ParseError::WrongVout)?,
            }),
            _ => Err(ParseError::WrongStructure),
        }
    }
}

impl<Id: SealTxid> Display for ExplicitSeal<Id> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}:{}", self.method, self.txid, self.vout,)
    }
}