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
// RGB standard library for working with smart contracts on Bitcoin & Lightning
//
// SPDX-License-Identifier: Apache-2.0
//
// Written in 2019-2024 by
// Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// Copyright (C) 2019-2024 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::Txid;
use commit_verify::{mpc, Conceal};
use rgb::{
Assign, Assignments, BundleId, ExposedSeal, ExposedState, Extension, Genesis, OpId, Operation,
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),
/// mismatch in anchor chains: one grip references bitcoin transaction
/// {bitcoin} and the other merged part references liquid transaction
/// {liquid}.
ChainMismatch { bitcoin: Txid, liquid: Txid },
/// mismatching transaction id for merge-revealed: {0} and {1}.
TxidMismatch(Txid, Txid),
/// anchors in anchored bundle are not equal for bundle {0}.
AnchorsNonEqual(BundleId),
/// the merged bundles contain more transitions than inputs.
InsufficientInputs,
/// contract id provided for the merge-reveal operation doesn't match
/// multiprotocol commitment.
#[from(mpc::InvalidProof)]
#[from(mpc::LeafNotKnown)]
ContractMismatch,
}
/// 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>;
}
/*
pub trait MergeRevealContract: Sized {
fn merge_reveal_contract(
self,
other: Self,
contract_id: ContractId,
) -> Result<Self, MergeRevealError>;
}
*/
impl<State: ExposedState, Seal: ExposedSeal> MergeReveal for Assign<State, Seal> {
fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError> {
debug_assert_eq!(self.conceal(), other.conceal());
match (self, other) {
// Anything + Revealed = Revealed
(_, state @ Assign::Revealed { .. }) | (state @ Assign::Revealed { .. }, _) => {
Ok(state)
}
// ConfidentialAmount + ConfidentialSeal = Revealed
(
Assign::ConfidentialSeal {
state, lock: lock1, ..
},
Assign::ConfidentialState {
seal, lock: lock2, ..
},
) => {
debug_assert_eq!(lock1, lock2);
Ok(Assign::Revealed {
seal,
state,
lock: lock1,
})
}
// ConfidentialSeal + ConfidentialAmount = Revealed
(
Assign::ConfidentialState {
seal, lock: lock1, ..
},
Assign::ConfidentialSeal {
state, lock: lock2, ..
},
) => {
debug_assert_eq!(lock1, lock2);
Ok(Assign::Revealed {
seal,
state,
lock: lock1,
})
}
// 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 TransitionBundle {
fn merge_reveal(mut self, other: Self) -> Result<Self, MergeRevealError> {
debug_assert_eq!(self.bundle_id(), other.bundle_id());
let mut self_transitions = self.known_transitions.release();
for (opid, other_transition) in other.known_transitions {
if let Some(mut transition) = self_transitions.remove(&opid) {
transition = transition.merge_reveal(other_transition)?;
self_transitions.insert(opid, transition);
}
}
self.known_transitions = Confined::from_checked(self_transitions);
if self.input_map.len() < self.known_transitions.len() {
return Err(MergeRevealError::InsufficientInputs);
}
Ok(self)
}
}
/*
impl MergeRevealContract for AnchoredBundle {
fn merge_reveal_contract(
self,
other: Self,
contract_id: ContractId,
) -> Result<Self, MergeRevealError> {
let bundle_id = self.bundle_id();
let anchor1 = self.anchor.into_merkle_block(contract_id, bundle_id)?;
let anchor2 = other.anchor.into_merkle_block(contract_id, bundle_id)?;
Ok(AnchoredBundle {
anchor: anchor1
.merge_reveal(anchor2)?
.into_merkle_proof(contract_id)?,
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.id();
let other_id = other.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.id();
let other_id = other.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.id();
let other_id = other.id();
if self_id != other_id {
return Err(MergeRevealError::OperationMismatch(self_id, other_id));
}
self.assignments = self.assignments.merge_reveal(other.assignments)?;
Ok(self)
}
}