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

Context inputs lexical ordering #1873

Merged
Show file tree
Hide file tree
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
10 changes: 8 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ iota-crypto = { version = "0.23.0", default-features = false, features = [
"ed25519",
"secp256k1",
] }
iterator-sorted = { version = "0.1.0", default-features = false }
iterator-sorted = { version = "0.2.0", default-features = false }
packable = { version = "0.10.1", default-features = false, features = [
"primitive-types",
] }
Expand Down
6 changes: 3 additions & 3 deletions sdk/src/types/block/context_input/block_issuance_credit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ impl BlockIssuanceCreditContextInput {
}

/// Returns the account id of the [`BlockIssuanceCreditContextInput`].
pub fn account_id(&self) -> AccountId {
self.0
pub fn account_id(&self) -> &AccountId {
&self.0
}
}

Expand Down Expand Up @@ -54,7 +54,7 @@ mod dto {
fn from(value: &BlockIssuanceCreditContextInput) -> Self {
Self {
kind: BlockIssuanceCreditContextInput::KIND,
account_id: value.account_id(),
account_id: *value.account_id(),
}
}
}
Expand Down
8 changes: 2 additions & 6 deletions sdk/src/types/block/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,11 @@ pub enum Error {
ConsumedAmountOverflow,
ConsumedManaOverflow,
ConsumedNativeTokensAmountOverflow,
ContextInputsNotUniqueSorted,
CreatedAmountOverflow,
CreatedManaOverflow,
CreatedNativeTokensAmountOverflow,
Crypto(CryptoError),
DuplicateBicAccountId(AccountId),
DuplicateRewardInputIndex(u16),
DuplicateSignatureUnlock(u16),
DuplicateUtxo(UtxoInput),
ExpirationUnlockConditionZero,
Expand Down Expand Up @@ -188,7 +187,6 @@ pub enum Error {
},
StorageDepositReturnOverflow,
TimelockUnlockConditionZero,
TooManyCommitmentInputs,
UnallowedFeature {
index: usize,
kind: u8,
Expand Down Expand Up @@ -222,12 +220,11 @@ impl fmt::Display for Error {
Self::ConsumedAmountOverflow => write!(f, "consumed amount overflow"),
Self::ConsumedManaOverflow => write!(f, "consumed mana overflow"),
Self::ConsumedNativeTokensAmountOverflow => write!(f, "consumed native tokens amount overflow"),
Self::ContextInputsNotUniqueSorted => write!(f, "context inputs are not unique and/or sorted"),
Self::CreatedAmountOverflow => write!(f, "created amount overflow"),
Self::CreatedManaOverflow => write!(f, "created mana overflow"),
Self::CreatedNativeTokensAmountOverflow => write!(f, "created native tokens amount overflow"),
Self::Crypto(e) => write!(f, "cryptographic error: {e}"),
Self::DuplicateBicAccountId(account_id) => write!(f, "duplicate BIC account id: {account_id}"),
Self::DuplicateRewardInputIndex(idx) => write!(f, "duplicate reward input index: {idx}"),
Self::DuplicateSignatureUnlock(index) => {
write!(f, "duplicate signature unlock at index: {index}")
}
Expand Down Expand Up @@ -434,7 +431,6 @@ impl fmt::Display for Error {
"timelock unlock condition with milestone index and timestamp set to 0",
)
}
Self::TooManyCommitmentInputs => write!(f, "too many commitment inputs"),
Self::UnallowedFeature { index, kind } => {
write!(f, "unallowed feature at index {index} with kind {kind}")
}
Expand Down
51 changes: 19 additions & 32 deletions sdk/src/types/block/payload/signed_transaction/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// SPDX-License-Identifier: Apache-2.0

use alloc::{collections::BTreeSet, vec::Vec};
use core::cmp::Ordering;

use crypto::hashes::{blake2b::Blake2b256, Digest};
use hashbrown::HashSet;
use iterator_sorted::is_unique_sorted_by;
use packable::{bounded::BoundedU16, prefix::BoxedSlicePrefix, Packable, PackableExt};

use crate::{
Expand Down Expand Up @@ -126,7 +128,7 @@ impl TransactionBuilder {

/// Finishes a [`TransactionBuilder`] into a [`Transaction`].
pub fn finish_with_params<'a>(
self,
mut self,
params: impl Into<Option<&'a ProtocolParameters>>,
) -> Result<Transaction, Error> {
let params = params.into();
Expand Down Expand Up @@ -158,6 +160,8 @@ impl TransactionBuilder {
})
.ok_or(Error::InvalidField("creation slot"))?;

self.context_inputs.sort_by(context_inputs_cmp);

let context_inputs: BoxedSlicePrefix<ContextInput, ContextInputCount> = self
.context_inputs
.into_boxed_slice()
Expand Down Expand Up @@ -365,38 +369,21 @@ fn verify_context_inputs_packable<const VERIFY: bool>(
Ok(())
}

fn verify_context_inputs(context_inputs: &[ContextInput]) -> Result<(), Error> {
// There must be zero or one Commitment Input.
if context_inputs
.iter()
.filter(|i| matches!(i, ContextInput::Commitment(_)))
.count()
> 1
{
return Err(Error::TooManyCommitmentInputs);
}

let mut reward_index_set = HashSet::new();
let mut bic_account_id_set = HashSet::new();

for input in context_inputs.iter() {
match input {
ContextInput::BlockIssuanceCredit(bic) => {
let account_id = bic.account_id();
// All Block Issuance Credit Inputs must reference a different Account ID.
if !bic_account_id_set.insert(account_id) {
return Err(Error::DuplicateBicAccountId(account_id));
}
}
ContextInput::Reward(r) => {
let idx = r.index();
// All Rewards Inputs must reference a different Index
if !reward_index_set.insert(idx) {
return Err(Error::DuplicateRewardInputIndex(idx));
}
}
_ => (),
fn context_inputs_cmp(a: &ContextInput, b: &ContextInput) -> Ordering {
a.kind().cmp(&b.kind()).then_with(|| match (a, b) {
(ContextInput::Commitment(_), ContextInput::Commitment(_)) => Ordering::Equal,
(ContextInput::BlockIssuanceCredit(a), ContextInput::BlockIssuanceCredit(b)) => {
a.account_id().cmp(b.account_id())
}
(ContextInput::Reward(a), ContextInput::Reward(b)) => a.index().cmp(&b.index()),
// No need to evaluate all combinations as `then_with` is only called on Equal.
_ => unreachable!(),
})
}

fn verify_context_inputs(context_inputs: &[ContextInput]) -> Result<(), Error> {
if !is_unique_sorted_by(context_inputs.iter(), |a, b| context_inputs_cmp(a, b)) {
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
return Err(Error::ContextInputsNotUniqueSorted);
}

Ok(())
Expand Down