Skip to content

Commit

Permalink
Add work score trait and impls (#1235)
Browse files Browse the repository at this point in the history
* add workscore calc

* fix merge

* finish calculations

* nits

* merge import

* nits

* rename trait fn

* update work score computations

* nit

* move work score types into own module

* add and impl mana cost fn

* PR suggestions 1

Co-authored-by: DaughterOfMars <[email protected]>

* is_signature

* remove todo

* review 1

* review 2

* review 3

* fix copyright year

Co-authored-by: Thibault Martinez <[email protected]>

* StorageScore ❤️ WorkScore

* Fix def_is_as_opt panic message (#1659)

* Remove native tokens from AnchorOutput (#1660)

* Python: add multi address (#1658)

* add weighted address and multi address

* fmt

* fmt

* align + more impls

* nit

* default impl for all features

* default impl for all unlocks

* self

* rm WorkScore impl for NativeTokens type

* review suggestions

* align and improve

* cleanup

* cleanup 2

* forward work score in NativeTokenFeature

* cleanup 3

* forward 2

* let's see if we're faster than thibault

* unnecessary import

* underscore

Co-authored-by: Thibault Martinez <[email protected]>

* final touches

* remove todo

* rm mana_cost fn from work score trait

---------

Co-authored-by: DaughterOfMars <[email protected]>
Co-authored-by: Thibault Martinez <[email protected]>
Co-authored-by: Thibault Martinez <[email protected]>
  • Loading branch information
4 people authored Nov 27, 2023
1 parent 2d13dc0 commit 13cf460
Show file tree
Hide file tree
Showing 49 changed files with 620 additions and 218 deletions.
2 changes: 1 addition & 1 deletion sdk/src/client/stronghold/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ mod tests {
// Address generation returns an error when the key is cleared.
assert!(
stronghold_adapter
.generate_ed25519_addresses(IOTA_COIN_TYPE, 0, 0..1, None,)
.generate_ed25519_addresses(IOTA_COIN_TYPE, 0, 0..1, None)
.await
.is_err()
);
Expand Down
11 changes: 10 additions & 1 deletion sdk/src/types/block/context_input/block_issuance_credit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

use derive_more::{Display, From};

use crate::types::block::output::AccountId;
use crate::types::block::{
output::AccountId,
protocol::{WorkScore, WorkScoreParameters},
};

/// A Block Issuance Credit (BIC) Context Input provides the VM with context for the value of
/// the BIC vector of a specific slot.
Expand All @@ -25,6 +28,12 @@ impl BlockIssuanceCreditContextInput {
}
}

impl WorkScore for BlockIssuanceCreditContextInput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.context_input()
}
}

#[cfg(feature = "serde")]
mod dto {
use serde::{Deserialize, Serialize};
Expand Down
11 changes: 10 additions & 1 deletion sdk/src/types/block/context_input/commitment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

use derive_more::{Display, From};

use crate::types::block::slot::SlotCommitmentId;
use crate::types::block::{
protocol::{WorkScore, WorkScoreParameters},
slot::SlotCommitmentId,
};

/// A Commitment Context Input references a commitment to a certain slot.
#[derive(Clone, Copy, Display, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, From, packable::Packable)]
Expand All @@ -24,6 +27,12 @@ impl CommitmentContextInput {
}
}

impl WorkScore for CommitmentContextInput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.context_input()
}
}

#[cfg(feature = "serde")]
mod dto {
use serde::{Deserialize, Serialize};
Expand Down
35 changes: 24 additions & 11 deletions sdk/src/types/block/context_input/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ pub use self::{
block_issuance_credit::BlockIssuanceCreditContextInput, commitment::CommitmentContextInput,
reward::RewardContextInput,
};
use crate::types::block::Error;
use crate::types::block::{
protocol::{WorkScore, WorkScoreParameters},
Error,
};

/// The maximum number of context inputs of a transaction.
pub const CONTEXT_INPUT_COUNT_MAX: u16 = 128;
Expand All @@ -39,16 +42,6 @@ pub enum ContextInput {
Reward(RewardContextInput),
}

impl core::fmt::Debug for ContextInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Commitment(input) => input.fmt(f),
Self::BlockIssuanceCredit(input) => input.fmt(f),
Self::Reward(input) => input.fmt(f),
}
}
}

impl ContextInput {
/// Returns the context input kind of a `ContextInput`.
pub fn kind(&self) -> u8 {
Expand All @@ -62,6 +55,26 @@ impl ContextInput {
crate::def_is_as_opt!(ContextInput: Commitment, BlockIssuanceCredit, Reward);
}

impl WorkScore for ContextInput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
match self {
Self::Commitment(commitment) => commitment.work_score(params),
Self::BlockIssuanceCredit(bic) => bic.work_score(params),
Self::Reward(reward) => reward.work_score(params),
}
}
}

impl core::fmt::Debug for ContextInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Commitment(input) => input.fmt(f),
Self::BlockIssuanceCredit(input) => input.fmt(f),
Self::Reward(input) => input.fmt(f),
}
}
}

#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
Expand Down
11 changes: 10 additions & 1 deletion sdk/src/types/block/context_input/reward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
use packable::bounded::BoundedU16;

use super::CONTEXT_INPUT_COUNT_RANGE;
use crate::types::block::Error;
use crate::types::block::{
protocol::{WorkScore, WorkScoreParameters},
Error,
};

pub(crate) type RewardContextInputIndex =
BoundedU16<{ *CONTEXT_INPUT_COUNT_RANGE.start() }, { *CONTEXT_INPUT_COUNT_RANGE.end() }>;
Expand All @@ -29,6 +32,12 @@ impl RewardContextInput {
}
}

impl WorkScore for RewardContextInput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.context_input()
}
}

impl core::fmt::Display for RewardContextInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "RewardContextInput({})", self.index())
Expand Down
13 changes: 12 additions & 1 deletion sdk/src/types/block/core/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use packable::Packable;
use crate::types::block::{
core::{parent::verify_parents_sets, BlockBody, Parents},
payload::{OptionalPayload, Payload},
protocol::ProtocolParameters,
protocol::{ProtocolParameters, WorkScore, WorkScoreParameters},
Error,
};

Expand Down Expand Up @@ -154,6 +154,17 @@ impl BasicBlockBody {
}
}

impl WorkScore for BasicBlockBody {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.block()
+ self
.payload
.as_ref()
.map(|payload| payload.work_score(params))
.unwrap_or(0)
}
}

fn verify_basic_block_body<const VERIFY: bool>(
basic_block_body: &BasicBlockBody,
_: &ProtocolParameters,
Expand Down
10 changes: 9 additions & 1 deletion sdk/src/types/block/core/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::types::block::{
block_id::{BlockHash, BlockId},
core::{BasicBlockBody, ValidationBlockBody},
output::AccountId,
protocol::ProtocolParameters,
protocol::{ProtocolParameters, WorkScore, WorkScoreParameters},
signature::Signature,
slot::{SlotCommitmentId, SlotIndex},
BlockBody, Error,
Expand Down Expand Up @@ -110,6 +110,8 @@ impl BlockHeader {
}
}

impl WorkScore for BlockHeader {}

impl Packable for BlockHeader {
type UnpackError = Error;
type UnpackVisitor = ProtocolParameters;
Expand Down Expand Up @@ -291,6 +293,12 @@ impl Block {
}
}

impl WorkScore for Block {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
self.header.work_score(params) + self.body.work_score(params) + self.signature.work_score(params)
}
}

impl Packable for Block {
type UnpackError = Error;
type UnpackVisitor = ProtocolParameters;
Expand Down
11 changes: 10 additions & 1 deletion sdk/src/types/block/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub use self::{
validation::{ValidationBlockBody, ValidationBlockBodyBuilder},
};
use crate::types::block::{
protocol::{ProtocolParameters, ProtocolParametersHash},
protocol::{ProtocolParameters, ProtocolParametersHash, WorkScore, WorkScoreParameters},
Error,
};

Expand Down Expand Up @@ -102,6 +102,15 @@ impl BlockBody {
}
}

impl WorkScore for BlockBody {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
match self {
Self::Basic(basic) => basic.work_score(params),
Self::Validation(validation) => validation.work_score(params),
}
}
}

#[cfg(feature = "serde")]
pub(crate) mod dto {
use alloc::format;
Expand Down
4 changes: 3 additions & 1 deletion sdk/src/types/block/core/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use packable::Packable;

use crate::types::block::{
core::{parent::verify_parents_sets, BlockBody, Parents},
protocol::{ProtocolParameters, ProtocolParametersHash},
protocol::{ProtocolParameters, ProtocolParametersHash, WorkScore},
Error,
};

Expand Down Expand Up @@ -160,6 +160,8 @@ impl ValidationBlockBody {
}
}

impl WorkScore for ValidationBlockBody {}

fn verify_protocol_parameters_hash<const VERIFY: bool>(
hash: &ProtocolParametersHash,
params: &ProtocolParameters,
Expand Down
5 changes: 4 additions & 1 deletion sdk/src/types/block/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ use crate::types::block::{
unlock_condition::UnlockConditionCount,
AccountId, AnchorId, ChainId, MetadataFeatureLength, NativeTokenCount, NftId, OutputIndex, TagFeatureLength,
},
payload::{ContextInputCount, InputCount, OutputCount, TagLength, TaggedDataLength},
payload::{
tagged_data::{TagLength, TaggedDataLength},
ContextInputCount, InputCount, OutputCount,
},
protocol::ProtocolParametersHash,
unlock::{UnlockCount, UnlockIndex, UnlocksCount},
};
Expand Down
13 changes: 12 additions & 1 deletion sdk/src/types/block/input/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use core::ops::RangeInclusive;
use derive_more::From;

pub use self::utxo::UtxoInput;
use crate::types::block::Error;
use crate::types::block::{
protocol::{WorkScore, WorkScoreParameters},
Error,
};

/// The maximum number of inputs of a transaction.
pub const INPUT_COUNT_MAX: u16 = 128;
Expand All @@ -30,6 +33,14 @@ pub enum Input {
Utxo(UtxoInput),
}

impl WorkScore for Input {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
match self {
Self::Utxo(utxo) => utxo.work_score(params),
}
}
}

impl core::fmt::Debug for Input {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Expand Down
13 changes: 12 additions & 1 deletion sdk/src/types/block/input/utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ use core::str::FromStr;

use derive_more::From;

use crate::types::block::{output::OutputId, payload::signed_transaction::TransactionId, Error};
use crate::types::block::{
output::OutputId,
payload::signed_transaction::TransactionId,
protocol::{WorkScore, WorkScoreParameters},
Error,
};

/// Represents an input referencing an output.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd, From, packable::Packable)]
Expand All @@ -26,6 +31,12 @@ impl UtxoInput {
}
}

impl WorkScore for UtxoInput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.input()
}
}

impl FromStr for UtxoInput {
type Err = Error;

Expand Down
36 changes: 23 additions & 13 deletions sdk/src/types/block/mana/allotment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

use packable::Packable;

use crate::types::block::{output::AccountId, protocol::ProtocolParameters, Error};
use crate::types::block::{
output::AccountId,
protocol::{ProtocolParameters, WorkScore, WorkScoreParameters},
Error,
};

/// An allotment of Mana which will be added upon commitment of the slot in which the containing transaction was issued,
/// in the form of Block Issuance Credits to the account.
Expand All @@ -16,18 +20,6 @@ pub struct ManaAllotment {
pub(crate) mana: u64,
}

impl PartialOrd for ManaAllotment {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl Ord for ManaAllotment {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.account_id.cmp(&other.account_id)
}
}

impl ManaAllotment {
pub fn new(account_id: AccountId, mana: u64, protocol_params: &ProtocolParameters) -> Result<Self, Error> {
verify_mana::<true>(&mana, protocol_params)?;
Expand All @@ -44,6 +36,24 @@ impl ManaAllotment {
}
}

impl PartialOrd for ManaAllotment {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl Ord for ManaAllotment {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.account_id.cmp(&other.account_id)
}
}

impl WorkScore for ManaAllotment {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.allotment()
}
}

fn verify_mana<const VERIFY: bool>(mana: &u64, params: &ProtocolParameters) -> Result<(), Error> {
if VERIFY && *mana > params.mana_parameters().max_mana() {
return Err(Error::InvalidManaValue(*mana));
Expand Down
11 changes: 10 additions & 1 deletion sdk/src/types/block/output/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::types::block::{
StateTransitionVerifier, StorageScore, StorageScoreParameters,
},
payload::signed_transaction::TransactionCapabilityFlag,
protocol::ProtocolParameters,
protocol::{ProtocolParameters, WorkScore, WorkScoreParameters},
semantic::{SemanticValidationContext, TransactionFailureReason},
unlock::Unlock,
Error,
Expand Down Expand Up @@ -505,6 +505,15 @@ impl StorageScore for AccountOutput {
}
}

impl WorkScore for AccountOutput {
fn work_score(&self, params: WorkScoreParameters) -> u32 {
params.output()
+ self.unlock_conditions.work_score(params)
+ self.features.work_score(params)
+ self.immutable_features.work_score(params)
}
}

impl MinimumOutputAmount for AccountOutput {}

impl Packable for AccountOutput {
Expand Down
Loading

0 comments on commit 13cf460

Please sign in to comment.