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
// RGB standard library for working with smart contracts on Bitcoin & Lightning
//
// 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.

use std::collections::BTreeMap;

use amplify::confinement::Confined;
use amplify::Wrapper;
use bp::dbc::anchor::MergeError;
use commit_verify::{mpc, CommitmentId};
use rgb::{
    Anchor, AnchoredBundle, Assign, Assignments, BundleItem, ExposedSeal, ExposedState, Extension,
    Genesis, OpId, Transition, TransitionBundle, TypedAssigns,
};

#[derive(Copy, Clone, Eq, PartialEq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum MergeRevealError {
    /// operations {0} and {1} has different commitment ids and can't be
    /// merge-revealed. This usually means internal application business logic
    /// error which should be reported to the software vendor.
    OperationMismatch(OpId, OpId),

    #[from]
    #[display(inner)]
    AnchorMismatch(MergeError),
}

/// A trait to merge two structures modifying the revealed status
/// of the first one. The merge operation will **consume** both the structures
/// and return a new structure with revealed states.
///
/// The resulting structure will depend on the reveal status of both of the
/// variant. And the most revealed condition among the two will be selected
/// Usage: prevent hiding already known previous state data by merging
/// incoming new consignment in stash.
///
/// The following conversion logic is intended by this trait:
///
/// merge(Revealed, Anything) => Revealed
/// merge(ConfidentialSeal, ConfidentialAmount) => Revealed
/// merge(ConfidentialAmount, ConfidentialSeal) => Revealed
/// merge(Confidential, Anything) => Anything
pub trait MergeReveal: Sized {
    // TODO: Take self by mut ref instead of consuming (will remove clones in
    //       Stash::consume operation).
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError>;
}

impl MergeReveal for Anchor<mpc::MerkleBlock> {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        self.merge_reveal(other).map_err(MergeRevealError::from)
    }
}

impl<State: ExposedState, Seal: ExposedSeal> MergeReveal for Assign<State, Seal> {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        // TODO: Uncomment once bulletproofs will be there
        // debug_assert_eq!(self.commitment_id(), other.commitment_id());
        match (self, other) {
            // Anything + Revealed = Revealed
            (_, state @ Assign::Revealed { .. }) | (state @ Assign::Revealed { .. }, _) => {
                Ok(state)
            }

            // ConfidentialAmount + ConfidentialSeal = Revealed
            (Assign::ConfidentialSeal { state, .. }, Assign::ConfidentialState { seal, .. }) => {
                Ok(Assign::Revealed { seal, state })
            }

            // ConfidentialSeal + ConfidentialAmount = Revealed
            (Assign::ConfidentialState { seal, .. }, Assign::ConfidentialSeal { state, .. }) => {
                Ok(Assign::Revealed { seal, state })
            }

            // if self and other is of same variant return self
            (state @ Assign::ConfidentialState { .. }, Assign::ConfidentialState { .. }) => {
                Ok(state)
            }
            (state @ Assign::ConfidentialSeal { .. }, Assign::ConfidentialSeal { .. }) => Ok(state),

            // Anything + Confidential = Anything
            (state, Assign::Confidential { .. }) | (Assign::Confidential { .. }, state) => {
                Ok(state)
            }
        }
    }
}

impl<Seal: ExposedSeal> MergeReveal for TypedAssigns<Seal> {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        match (self, other) {
            (TypedAssigns::Declarative(first_vec), TypedAssigns::Declarative(second_vec)) => {
                let mut result = Vec::with_capacity(first_vec.len());
                for (first, second) in first_vec.into_iter().zip(second_vec.into_iter()) {
                    result.push(first.merge_reveal(second)?);
                }
                Ok(TypedAssigns::Declarative(
                    Confined::try_from(result).expect("collection of the same size"),
                ))
            }

            (TypedAssigns::Fungible(first_vec), TypedAssigns::Fungible(second_vec)) => {
                let mut result = Vec::with_capacity(first_vec.len());
                for (first, second) in first_vec.into_iter().zip(second_vec.into_iter()) {
                    result.push(first.merge_reveal(second)?);
                }
                Ok(TypedAssigns::Fungible(
                    Confined::try_from(result).expect("collection of the same size"),
                ))
            }

            (TypedAssigns::Structured(first_vec), TypedAssigns::Structured(second_vec)) => {
                let mut result = Vec::with_capacity(first_vec.len());
                for (first, second) in first_vec.into_iter().zip(second_vec.into_iter()) {
                    result.push(first.merge_reveal(second)?);
                }
                Ok(TypedAssigns::Structured(
                    Confined::try_from(result).expect("collection of the same size"),
                ))
            }

            (TypedAssigns::Attachment(first_vec), TypedAssigns::Attachment(second_vec)) => {
                let mut result = Vec::with_capacity(first_vec.len());
                for (first, second) in first_vec.into_iter().zip(second_vec.into_iter()) {
                    result.push(first.merge_reveal(second)?);
                }
                Ok(TypedAssigns::Attachment(
                    Confined::try_from(result).expect("collection of the same size"),
                ))
            }
            // No other patterns possible, should not reach here
            _ => {
                unreachable!("Assignments::consensus_commitments is broken")
            }
        }
    }
}

impl<Seal: ExposedSeal> MergeReveal for Assignments<Seal> {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        let mut result = BTreeMap::new();
        for (first, second) in self
            .into_inner()
            .into_iter()
            .zip(other.into_inner().into_iter())
        {
            debug_assert_eq!(first.0, second.0);
            result.insert(first.0, first.1.merge_reveal(second.1)?);
        }
        Ok(Assignments::from_inner(
            Confined::try_from(result).expect("collection of the same size"),
        ))
    }
}

impl MergeReveal for BundleItem {
    fn merge_reveal(mut self, other: Self) -> Result<Self, MergeRevealError> {
        debug_assert_eq!(self.inputs, other.inputs);
        if self.transition.is_none() {
            self.transition = other.transition
        }
        Ok(self)
    }
}

impl MergeReveal for TransitionBundle {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        debug_assert_eq!(self.commitment_id(), other.commitment_id());
        let mut result = BTreeMap::new();
        for (first, second) in self
            .into_inner()
            .into_iter()
            .zip(other.into_inner().into_iter())
        {
            debug_assert_eq!(first.0, second.0);
            result.insert(first.0, first.1.merge_reveal(second.1)?);
        }
        Ok(TransitionBundle::from_inner(
            Confined::try_from(result).expect("collection of the same size"),
        ))
    }
}

impl MergeReveal for AnchoredBundle {
    fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
        Ok(AnchoredBundle {
            // TODO: uncomment
            anchor: self.anchor, //.merge_reveal(other.anchor)?,
            bundle: self.bundle.merge_reveal(other.bundle)?,
        })
    }
}

impl MergeReveal for Genesis {
    fn merge_reveal(mut self, other: Self) -> Result<Self, MergeRevealError> {
        let self_id = self.commitment_id();
        let other_id = other.commitment_id();
        if self_id != other_id {
            return Err(MergeRevealError::OperationMismatch(
                OpId::from_inner(self_id.into_inner()),
                OpId::from_inner(other_id.into_inner()),
            ));
        }
        self.assignments = self.assignments.merge_reveal(other.assignments)?;
        Ok(self)
    }
}

impl MergeReveal for Transition {
    fn merge_reveal(mut self, other: Self) -> Result<Self, MergeRevealError> {
        let self_id = self.commitment_id();
        let other_id = other.commitment_id();
        if self_id != other_id {
            return Err(MergeRevealError::OperationMismatch(self_id, other_id));
        }
        self.assignments = self.assignments.merge_reveal(other.assignments)?;
        Ok(self)
    }
}

impl MergeReveal for Extension {
    fn merge_reveal(mut self, other: Self) -> Result<Self, MergeRevealError> {
        let self_id = self.commitment_id();
        let other_id = other.commitment_id();
        if self_id != other_id {
            return Err(MergeRevealError::OperationMismatch(self_id, other_id));
        }
        self.assignments = self.assignments.merge_reveal(other.assignments)?;
        Ok(self)
    }
}