Skip to content

Commit

Permalink
chore: continue refactoring for multi-chain
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Nov 7, 2023
1 parent 8db4140 commit 5f65ee7
Show file tree
Hide file tree
Showing 11 changed files with 125 additions and 128 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src/accessors/merge_reveal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use std::collections::BTreeMap;
use amplify::confinement::Confined;
use amplify::Wrapper;
use bp::dbc::anchor::MergeError;
use commit_verify::CommitmentId;
use commit_verify::{mpc, CommitmentId};
use rgb::{
Anchor, AnchoredBundle, Assign, Assignments, BundleItem, ExposedSeal, ExposedState, Extension,
Genesis, OpId, Transition, TransitionBundle, TypedAssigns,
Expand Down Expand Up @@ -64,9 +64,9 @@ pub trait MergeReveal: Sized {
fn merge_reveal(self, other: Self) -> Result<Self, MergeRevealError>;
}

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

Expand Down
23 changes: 11 additions & 12 deletions src/containers/consignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ use std::{iter, slice};

use amplify::confinement::{LargeVec, MediumBlob, SmallOrdMap, TinyOrdMap, TinyOrdSet};
use commit_verify::Conceal;
use rgb::validation::{AnchoredBundle, ConsignmentApi};
use rgb::validation::{self, ConsignmentApi};
use rgb::{
validation, AssetTag, AssignmentType, AttachId, BundleId, ContractHistory, ContractId,
AnchoredBundle, AssetTag, AssignmentType, AttachId, BundleId, ContractHistory, ContractId,
Extension, Genesis, GraphSeal, OpId, OpRef, Operation, Schema, SchemaId, SealDefinition,
SecretSeal, SubSchema, Transition, TransitionBundle, WitnessAnchor,
SecretSeal, SubSchema, Transition, TransitionBundle,
};
use strict_encoding::{StrictDeserialize, StrictDumb, StrictSerialize};

Expand Down Expand Up @@ -185,10 +185,9 @@ impl<const TYPE: bool> Consignment<TYPE> {
for anchored_bundle in &self.bundles {
for item in anchored_bundle.bundle.values() {
if let Some(transition) = &item.transition {
let txid = anchored_bundle.anchor.txid;
let height = resolver.resolve_height(txid)?;
let ord_txid = WitnessAnchor::new(height, txid);
history.add_transition(transition, ord_txid);
let witness_anchor = resolver.resolve_anchor(&anchored_bundle.anchor)?;

history.add_transition(transition, witness_anchor);
for (id, used) in &mut extension_idx {
if *used {
continue;
Expand All @@ -197,11 +196,11 @@ impl<const TYPE: bool> Consignment<TYPE> {
if input.prev_out.op == *id {
*used = true;
if let Some(ord) = ordered_extensions.get_mut(id) {
if *ord > ord_txid {
*ord = ord_txid;
if *ord > witness_anchor {
*ord = witness_anchor;
}
} else {
ordered_extensions.insert(*id, ord_txid);
ordered_extensions.insert(*id, witness_anchor);
}
}
}
Expand All @@ -210,8 +209,8 @@ impl<const TYPE: bool> Consignment<TYPE> {
}
}
for extension in &self.extensions {
if let Some(ord_txid) = ordered_extensions.get(&extension.id()) {
history.add_extension(extension, *ord_txid);
if let Some(witness_anchor) = ordered_extensions.get(&extension.id()) {
history.add_extension(extension, *witness_anchor);
}
}

Expand Down
10 changes: 8 additions & 2 deletions src/interface/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,14 @@ impl ContractBuilder {
pub fn add_layer1(mut self, layer1: AltLayer1) -> Result<Self, BuilderError> {
self.alt_layers1
.push(layer1)
.map(|_| self)
.map_err(|_| BuilderError::TooManyLayers1)
.map_err(|_| BuilderError::TooManyLayers1)?;
Ok(self)
}

#[inline]
pub fn add_asset_tag(mut self, assignment_type: AssignmentType, asset_tag: AssetTag) -> Self {
self.builder = self.builder.add_asset_tag(assignment_type, asset_tag);
self
}

pub fn assignments_type(&self, name: &FieldName) -> Option<AssignmentType> {
Expand Down
44 changes: 21 additions & 23 deletions src/interface/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use std::ops::Deref;
use amplify::confinement::{LargeOrdMap, LargeVec, SmallVec};
use bp::Outpoint;
use rgb::{

Check failure on line 27 in src/interface/contract.rs

View workflow job for this annotation

GitHub Actions / testing

multiple candidates for `rlib` dependency `rgb` found
AssignmentType, AttachId, ContractId, ContractState, FungibleOutput, MediaType, RevealedAttach,
RevealedData, SealWitness,
AssignmentType, AttachId, ContractId, ContractState, FungibleOutput, MediaType, Output,
RevealedAttach, RevealedData, WitnessId,
};
use strict_encoding::FieldName;
use strict_types::typify::TypedVal;
Expand Down Expand Up @@ -76,8 +76,8 @@ impl From<RevealedAttach> for AttachedState {

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct FungibleAllocation {
pub owner: Outpoint,
pub witness: SealWitness,
pub owner: Output,
pub witness: Option<WitnessId>,
pub value: u64,
}

Expand All @@ -88,60 +88,58 @@ impl From<FungibleOutput> for FungibleAllocation {
impl From<&FungibleOutput> for FungibleAllocation {
fn from(out: &FungibleOutput) -> Self {
FungibleAllocation {
owner: out.seal,
owner: out.output,
witness: out.witness,
value: out.state.value.as_u64(),
}
}
}

pub trait OutpointFilter {
fn include_outpoint(&self, outpoint: Outpoint) -> bool;
fn include_output(&self, output: Output) -> bool;
}

pub struct FilterIncludeAll;
pub struct FilterExclude<T: OutpointFilter>(pub T);

impl<T: OutpointFilter> OutpointFilter for &T {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { (*self).include_outpoint(outpoint) }
fn include_output(&self, output: Output) -> bool { (*self).include_output(output) }
}

impl<T: OutpointFilter> OutpointFilter for &mut T {
fn include_outpoint(&self, outpoint: Outpoint) -> bool {
self.deref().include_outpoint(outpoint)
}
fn include_output(&self, output: Output) -> bool { self.deref().include_output(output) }
}

impl<T: OutpointFilter> OutpointFilter for Option<T> {
fn include_outpoint(&self, outpoint: Outpoint) -> bool {
fn include_output(&self, output: Output) -> bool {
self.as_ref()
.map(|filter| filter.include_outpoint(outpoint))
.map(|filter| filter.include_output(output))
.unwrap_or(true)
}
}

impl OutpointFilter for FilterIncludeAll {
fn include_outpoint(&self, _: Outpoint) -> bool { true }
fn include_output(&self, _: Output) -> bool { true }
}

impl<T: OutpointFilter> OutpointFilter for FilterExclude<T> {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { !self.0.include_outpoint(outpoint) }
fn include_output(&self, output: Output) -> bool { !self.0.include_output(output) }
}

impl OutpointFilter for &[Outpoint] {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { self.contains(&outpoint) }
impl OutpointFilter for &[Output] {
fn include_output(&self, output: Output) -> bool { self.contains(&output) }
}

impl OutpointFilter for Vec<Outpoint> {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { self.contains(&outpoint) }
impl OutpointFilter for Vec<Output> {
fn include_output(&self, output: Output) -> bool { self.contains(&output) }
}

impl OutpointFilter for HashSet<Outpoint> {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { self.contains(&outpoint) }
impl OutpointFilter for HashSet<Output> {
fn include_output(&self, output: Output) -> bool { self.contains(&output) }
}

impl OutpointFilter for BTreeSet<Outpoint> {
fn include_outpoint(&self, outpoint: Outpoint) -> bool { self.contains(&outpoint) }
impl OutpointFilter for BTreeSet<Output> {
fn include_output(&self, output: Output) -> bool { self.contains(&output) }
}

/// Contract state is an in-memory structure providing API to read structured
Expand Down Expand Up @@ -200,7 +198,7 @@ impl ContractIface {
.fungibles()
.iter()
.filter(|outp| outp.opout.ty == type_id)
.filter(|outp| filter.include_outpoint(outp.seal))
.filter(|outp| filter.include_output(outp.output))
.map(FungibleAllocation::from);
Ok(LargeVec::try_from_iter(state).expect("same or smaller collection size"))
}
Expand Down
11 changes: 7 additions & 4 deletions src/persistence/hoard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub struct Hoard {
pub(super) suppl: TinyOrdMap<ContractId, TinyOrdSet<ContractSuppl>>,
pub(super) bundles: LargeOrdMap<BundleId, TransitionBundle>,
pub(super) extensions: LargeOrdMap<OpId, Extension>,
pub(super) anchors: LargeOrdMap<AnchorId, Anchor>,
pub(super) anchors: LargeOrdMap<AnchorId, Anchor<mpc::MerkleBlock>>,
pub(super) sigs: SmallOrdMap<ContentId, ContentSigs>,
}

Expand Down Expand Up @@ -172,7 +172,7 @@ impl Hoard {

for AnchoredBundle { anchor, bundle } in consignment.bundles {
let bundle_id = bundle.bundle_id();
let anchor = anchor.into_merkle_block(contract_id, bundle_id.into())?;
let anchor = anchor.map(|a| a.into_merkle_block(contract_id, bundle_id.into()))?;
self.consume_anchor(anchor)?;
self.consume_bundle(bundle)?;
}
Expand All @@ -198,7 +198,7 @@ impl Hoard {
}

// TODO: Move into Stash trait and re-implement using trait accessor methods
pub fn consume_anchor(&mut self, anchor: Anchor) -> Result<(), ConsumeError> {
pub fn consume_anchor(&mut self, anchor: Anchor<mpc::MerkleBlock>) -> Result<(), ConsumeError> {
let anchor_id = anchor.anchor_id();
match self.anchors.get_mut(&anchor_id) {
Some(a) => *a = a.clone().merge_reveal(anchor)?,
Expand Down Expand Up @@ -300,7 +300,10 @@ impl Stash for Hoard {
Ok(self.anchors.keys().copied().collect())
}

fn anchor(&self, anchor_id: AnchorId) -> Result<&Anchor, StashError<Self::Error>> {
fn anchor(
&self,
anchor_id: AnchorId,
) -> Result<&Anchor<mpc::MerkleBlock>, StashError<Self::Error>> {
self.anchors
.get(&anchor_id)
.ok_or(StashInconsistency::AnchorAbsent(anchor_id).into())
Expand Down
33 changes: 19 additions & 14 deletions src/persistence/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ use bp::Txid;
use commit_verify::{mpc, Conceal};
use rgb::{
validation, Anchor, AnchoredBundle, BundleId, ContractId, ExposedSeal, GraphSeal, OpId,
Operation, Opout, SchemaId, SealDefinition, SecretSeal, SubSchema, Transition,
TransitionBundle,
Operation, Opout, Output, SchemaId, SealDefinition, SecretSeal, SubSchema, Transition,
TransitionBundle, WitnessId,
};
use strict_encoding::TypeName;

Expand All @@ -46,7 +46,6 @@ use crate::persistence::hoard::ConsumeError;
use crate::persistence::stash::StashInconsistency;
use crate::persistence::{Stash, StashError};
use crate::resolvers::ResolveHeight;
use crate::Outpoint;

#[derive(Debug, Display, Error, From)]
#[display(doc_comments)]
Expand Down Expand Up @@ -160,6 +159,9 @@ pub enum DataError {
/// you'd like to take the risc, call `import_contract_force`.
TerminalsUnmined,

/// mismatch between witness seal chain and anchor chain.
ChainMismatch,

#[display(inner)]
#[from]
Reveal(RevealError),
Expand All @@ -169,7 +171,7 @@ pub enum DataError {
Merge(MergeRevealError),

/// outpoint {0} is not part of the contract {1}.
OutpointUnknown(Outpoint, ContractId),
OutpointUnknown(Output, ContractId),

#[from]
Confinement(confinement::Error),
Expand Down Expand Up @@ -304,7 +306,10 @@ pub trait Inventory: Deref<Target = Self::Stash> {
/// Assumes that the bundle belongs to a non-mined witness transaction. Must
/// be used only to consume locally-produced bundles before witness
/// transactions are mined.
fn consume_anchor(&mut self, anchor: Anchor) -> Result<(), InventoryError<Self::Error>>;
fn consume_anchor(
&mut self,
anchor: Anchor<mpc::MerkleBlock>,
) -> Result<(), InventoryError<Self::Error>>;

/// # Safety
///
Expand All @@ -315,7 +320,7 @@ pub trait Inventory: Deref<Target = Self::Stash> {
&mut self,
contract_id: ContractId,
bundle: TransitionBundle,
witness_txid: Txid,
witness_id: WitnessId,
) -> Result<(), InventoryError<Self::Error>>;

/// # Safety
Expand Down Expand Up @@ -440,31 +445,31 @@ pub trait Inventory: Deref<Target = Self::Stash> {

fn transition(&self, opid: OpId) -> Result<&Transition, InventoryError<Self::Error>>;

fn contracts_by_outpoints(
fn contracts_by_outputs(
&mut self,
outpoints: impl IntoIterator<Item = impl Into<Outpoint>>,
outputs: impl IntoIterator<Item = impl Into<Output>>,
) -> Result<BTreeSet<ContractId>, InventoryError<Self::Error>>;

fn public_opouts(
&mut self,
contract_id: ContractId,
) -> Result<BTreeSet<Opout>, InventoryError<Self::Error>>;

fn opouts_by_outpoints(
fn opouts_by_outputs(
&mut self,
contract_id: ContractId,
outpoints: impl IntoIterator<Item = impl Into<Outpoint>>,
outputs: impl IntoIterator<Item = impl Into<Output>>,
) -> Result<BTreeSet<Opout>, InventoryError<Self::Error>>;

fn opouts_by_terminals(
&mut self,
terminals: impl IntoIterator<Item = SecretSeal>,
) -> Result<BTreeSet<Opout>, InventoryError<Self::Error>>;

fn state_for_outpoints(
fn state_for_outputs(
&mut self,
contract_id: ContractId,
outpoints: impl IntoIterator<Item = impl Into<Outpoint>>,
outputs: impl IntoIterator<Item = impl Into<Output>>,
) -> Result<BTreeMap<Opout, TypedState>, InventoryError<Self::Error>>;

fn store_seal_secret(
Expand Down Expand Up @@ -518,11 +523,11 @@ pub trait Inventory: Deref<Target = Self::Stash> {
let (outpoint_seals, terminal_seals) = seals
.into_iter()
.map(|seal| match seal.into() {
BuilderSeal::Revealed(seal) => (seal.outpoint(), seal.conceal()),
BuilderSeal::Revealed(seal) => (seal.output(), seal.conceal()),
BuilderSeal::Concealed(seal) => (None, seal),
})
.unzip::<_, _, Vec<_>, Vec<_>>();
opouts.extend(self.opouts_by_outpoints(contract_id, outpoint_seals.into_iter().flatten())?);
opouts.extend(self.opouts_by_outputs(contract_id, outpoint_seals.into_iter().flatten())?);
opouts.extend(self.opouts_by_terminals(terminal_seals.iter().copied())?);

// 1.1. Get all public transitions
Expand Down
6 changes: 5 additions & 1 deletion src/persistence/stash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;

use amplify::confinement::TinyOrdSet;
use commit_verify::mpc;
use rgb::{
Anchor, AnchorId, BundleId, ContractId, Extension, Genesis, OpId, SchemaId, TransitionBundle,
};
Expand Down Expand Up @@ -124,5 +125,8 @@ pub trait Stash {

fn anchor_ids(&self) -> Result<BTreeSet<AnchorId>, Self::Error>;

fn anchor(&self, anchor_id: AnchorId) -> Result<&Anchor, StashError<Self::Error>>;
fn anchor(
&self,
anchor_id: AnchorId,
) -> Result<&Anchor<mpc::MerkleBlock>, StashError<Self::Error>>;
}
Loading

0 comments on commit 5f65ee7

Please sign in to comment.