Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to pay from both tapret and opret inputs #256

Merged
merged 1 commit into from
Aug 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 101 additions & 45 deletions src/persistence/stock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::cmp::Ordering;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::Infallible;
Expand All @@ -35,9 +34,9 @@ use chrono::Utc;
use invoice::{Amount, Beneficiary, InvoiceState, NonFungible, RgbInvoice};
use rgb::validation::{DbcProof, EAnchor, ResolveWitness, WitnessResolverError};
use rgb::{
validation, AssignmentType, BlindingFactor, BundleId, ContractId, GraphSeal, Identity, OpId,
Operation, Opout, SchemaId, SecretSeal, Transition, TxoSeal, XChain, XOutpoint, XOutputSeal,
XWitnessId,
validation, AssignmentType, BlindingFactor, BundleId, ContractId, DataState, GraphSeal,
Identity, OpId, Operation, Opout, SchemaId, SecretSeal, Transition, TxoSeal, XChain, XOutpoint,
XOutputSeal, XWitnessId,
};
use strict_encoding::FieldName;

Expand Down Expand Up @@ -989,6 +988,13 @@ impl<S: StashProvider, H: StateProvider, P: IndexProvider> Stock<S, H, P> {
.assignments_type(&assignment_name)
.ok_or(BuilderError::InvalidStateField(assignment_name.clone()))?;

// If there are inputs which are using different seal closing method from our
// wallet (and thus main state transition) we need to put them aside and
// allocate a different state transition spending them as a change.
let mut alt_builder =
self.transition_builder(contract_id, iface.clone(), invoice.operation.clone())?;
let mut alt_inputs = Vec::<XOutputSeal>::new();

let layer1 = invoice.beneficiary.chain_network().layer1();
let beneficiary = match (invoice.beneficiary.into_inner(), beneficiary_vout) {
(Beneficiary::BlindedSeal(seal), None) => {
Expand All @@ -1010,83 +1016,125 @@ impl<S: StashProvider, H: StateProvider, P: IndexProvider> Stock<S, H, P> {
// 2. Prepare transition
let mut main_inputs = Vec::<XOutputSeal>::new();
let mut sum_inputs = Amount::ZERO;
let mut sum_alt = Amount::ZERO;
let mut data_inputs = vec![];

// If there are inputs which are using different seal closing method from our
// wallet (and thus main state transition) we need to put them aside and
// allocate a different state transition spending them as a change.
let mut wrong_builder =
self.transition_builder(contract_id, iface.clone(), invoice.operation.clone())?;
let mut wrong_inputs = Vec::<XOutputSeal>::new();
let mut data_main = true;
let lookup_state =
if let InvoiceState::Data(NonFungible::RGB21(allocation)) = &invoice.owned_state {
Some(DataState::from(allocation.clone()))
} else {
None
};

for (output, list) in
self.contract_assignments_for(contract_id, prev_outputs.iter().copied())?
{
if output.method() == method {
main_inputs.push(output)
} else {
wrong_inputs.push(output)
alt_inputs.push(output)
};
for (opout, mut state) in list {
if output.method() == method {
main_builder = main_builder.add_input(opout, state.clone())?;
} else {
wrong_builder = wrong_builder.add_input(opout, state.clone())?;
alt_builder = alt_builder.add_input(opout, state.clone())?;
}
if opout.ty != assignment_id || output.method() != method {
if opout.ty != assignment_id {
let seal = output_for_assignment(contract_id, opout.ty)?;
state.update_blinding(pedersen_blinder(contract_id, assignment_id));
if output.method() == method {
main_builder = main_builder.add_owned_state_raw(opout.ty, seal, state)?;
} else {
wrong_builder = wrong_builder.add_owned_state_raw(opout.ty, seal, state)?;
alt_builder = alt_builder.add_owned_state_raw(opout.ty, seal, state)?;
}
} else if let PersistedState::Amount(value, _, _) = state {
sum_inputs += value;
if output.method() != method {
sum_alt += value;
}
} else if let PersistedState::Data(value, _) = state {
if lookup_state.as_ref() == Some(&value) && output.method() != method {
data_main = false;
}
data_inputs.push(value);
}
}
}
// Add change
let main_transition = match invoice.owned_state.clone() {
match invoice.owned_state.clone() {
InvoiceState::Amount(amt) => {
match sum_inputs.cmp(&amt) {
Ordering::Greater => {
let seal = output_for_assignment(contract_id, assignment_id)?;
main_builder = main_builder.add_fungible_state_raw(
if sum_inputs < amt {
return Err(ComposeError::InsufficientState.into());
}
let change_seal = output_for_assignment(contract_id, assignment_id)?;
let blinding_beneficiary = pedersen_blinder(contract_id, assignment_id);
let blinding_change = pedersen_blinder(contract_id, assignment_id);
let sum_main = sum_inputs - sum_alt;

// Pay beneficiary
let mut paid_main = Amount::ZERO;
let mut paid_alt = Amount::ZERO;
if sum_inputs > amt {
paid_main = if sum_main < amt { sum_main } else { amt };
main_builder = main_builder.add_fungible_state_raw(
assignment_id,
beneficiary,
paid_main,
blinding_beneficiary,
)?;
if sum_main < amt {
paid_alt = amt - sum_main;
alt_builder = alt_builder.add_fungible_state_raw(
assignment_id,
seal,
sum_inputs - amt,
pedersen_blinder(contract_id, assignment_id),
beneficiary,
paid_alt,
blinding_beneficiary,
)?;
}
Ordering::Less => return Err(ComposeError::InsufficientState.into()),
Ordering::Equal => {}
}
main_builder
.add_fungible_state_raw(

// Pay change
if sum_main > paid_main {
main_builder = main_builder.add_fungible_state_raw(
assignment_id,
beneficiary,
amt,
pedersen_blinder(contract_id, assignment_id),
)?
.complete_transition()?
change_seal,
sum_main - paid_main,
blinding_change,
)?;
}
if sum_alt > paid_alt {
alt_builder = alt_builder.add_fungible_state_raw(
assignment_id,
change_seal,
sum_alt - paid_alt,
blinding_change,
)?;
}
}
InvoiceState::Data(data) => match data {
NonFungible::RGB21(allocation) => {
if !data_inputs.into_iter().any(|x| x == allocation.into()) {
let lookup_state = DataState::from(allocation);
if !data_inputs.into_iter().any(|x| x == lookup_state) {
return Err(ComposeError::InsufficientState.into());
}

main_builder
.add_data_raw(
let seal = seal_blinder(contract_id, assignment_id);
if data_main {
main_builder = main_builder.add_data_raw(
assignment_id,
beneficiary,
allocation,
seal,
)?;
} else {
alt_builder = alt_builder.add_data_raw(
assignment_id,
beneficiary,
allocation,
seal_blinder(contract_id, assignment_id),
)?
.complete_transition()?
seal,
)?;
}
}
},
_ => {
Expand All @@ -1095,7 +1143,7 @@ impl<S: StashProvider, H: StateProvider, P: IndexProvider> Stock<S, H, P> {
supported"
)
}
};
}

// 3. Prepare other transitions
// Enumerate state
Expand Down Expand Up @@ -1161,12 +1209,20 @@ impl<S: StashProvider, H: StateProvider, P: IndexProvider> Stock<S, H, P> {
.map_err(|_| ComposeError::TooManyBlanks)?;
}

let first = TransitionInfo::new(main_transition, main_inputs).map_err(|e| {
debug_assert!(!matches!(e, TransitionInfoError::CloseMethodDivergence(_)));
ComposeError::TooManyInputs
})?;
let second = if wrong_builder.has_inputs() {
Some(TransitionInfo::new(wrong_builder.complete_transition()?, wrong_inputs).map_err(
let (first_builder, second_builder) =
match (main_builder.has_inputs(), alt_builder.has_inputs()) {
(true, true) => (main_builder, Some(alt_builder)),
(true, false) => (main_builder, None),
(false, true) => (alt_builder, None),
(false, false) => return Err(ComposeError::InsufficientState.into()),
};
let first = TransitionInfo::new(first_builder.complete_transition()?, main_inputs)
.map_err(|e| {
debug_assert!(!matches!(e, TransitionInfoError::CloseMethodDivergence(_)));
ComposeError::TooManyInputs
})?;
let second = if let Some(second_builder) = second_builder {
Some(TransitionInfo::new(second_builder.complete_transition()?, alt_inputs).map_err(
|e| {
debug_assert!(!matches!(e, TransitionInfoError::CloseMethodDivergence(_)));
ComposeError::TooManyInputs
Expand Down