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

Add parents and burned_mana to rust block #925

Merged
merged 7 commits into from
Jul 26, 2023
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
1 change: 0 additions & 1 deletion Cargo.lock

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

3 changes: 0 additions & 3 deletions sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ fern-logger = { version = "0.5.0", default-features = false, optional = true }
futures = { version = "0.3.28", default-features = false, features = [
"thread-pool",
], optional = true }
heck = { version = "0.4.1", default-features = false, optional = true }
instant = { version = "0.1.12", default-features = false, optional = true }
iota-ledger-nano = { version = "1.0.0-alpha.4", default-features = false, optional = true }
iota_stronghold = { version = "2.0.0-rc.2", default-features = false, optional = true }
Expand Down Expand Up @@ -169,7 +168,6 @@ storage = [
"dep:time",
"dep:anymap",
"dep:once_cell",
"dep:heck",
]
stronghold = [
"iota_stronghold",
Expand All @@ -178,7 +176,6 @@ stronghold = [
"dep:time",
"dep:anymap",
"dep:once_cell",
"dep:heck",
]
tls = ["reqwest?/rustls-tls", "rumqttc?/use-rustls"]

Expand Down
124 changes: 100 additions & 24 deletions sdk/src/types/block/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

use alloc::vec::Vec;
use core::ops::Deref;

use crypto::hashes::{blake2b::Blake2b256, Digest};
use packable::{
Expand All @@ -13,7 +12,7 @@ use packable::{
};

use crate::types::block::{
parent::StrongParents,
parent::{ShallowLikeParents, StrongParents, WeakParents},
payload::{OptionalPayload, Payload},
protocol::ProtocolParameters,
BlockId, Error, PROTOCOL_VERSION,
Expand All @@ -25,8 +24,11 @@ use crate::types::block::{
pub struct BlockBuilder {
protocol_version: Option<u8>,
strong_parents: StrongParents,
weak_parents: WeakParents,
shallow_like_parents: ShallowLikeParents,
payload: OptionalPayload,
nonce: Option<u64>,
burned_mana: u64,
}

impl BlockBuilder {
Expand All @@ -38,8 +40,11 @@ impl BlockBuilder {
Self {
protocol_version: None,
strong_parents,
weak_parents: Default::default(),
shallow_like_parents: Default::default(),
payload: OptionalPayload::default(),
nonce: None,
burned_mana: Default::default(),
}
}

Expand All @@ -50,6 +55,20 @@ impl BlockBuilder {
self
}

/// Adds weak parents to a [`BlockBuilder`].
#[inline(always)]
pub fn with_weak_parents(mut self, weak_parents: impl Into<WeakParents>) -> Self {
self.weak_parents = weak_parents.into();
self
}

/// Adds shallow like parents to a [`BlockBuilder`].
#[inline(always)]
pub fn with_shallow_like_parents(mut self, shallow_like_parents: impl Into<ShallowLikeParents>) -> Self {
self.shallow_like_parents = shallow_like_parents.into();
self
}

/// Adds a payload to a [`BlockBuilder`].
#[inline(always)]
pub fn with_payload(mut self, payload: impl Into<OptionalPayload>) -> Self {
Expand All @@ -64,13 +83,23 @@ impl BlockBuilder {
self
}

/// Adds burned mana to a [`BlockBuilder`].
#[inline(always)]
pub fn with_burned_mana(mut self, burned_mana: u64) -> Self {
self.burned_mana = burned_mana;
self
}

fn _finish(self) -> Result<(Block, Vec<u8>), Error> {
verify_payload(self.payload.as_ref())?;
verify_parents(&self.strong_parents, &self.weak_parents, &self.shallow_like_parents)?;

let block = Block {
protocol_version: self.protocol_version.unwrap_or(PROTOCOL_VERSION),
strong_parents: self.strong_parents,
weak_parents: self.weak_parents,
shallow_like_parents: self.shallow_like_parents,
payload: self.payload,
burned_mana: self.burned_mana,
nonce: self.nonce.unwrap_or(Self::DEFAULT_NONCE),
};

Expand Down Expand Up @@ -106,8 +135,15 @@ pub struct Block {
protocol_version: u8,
/// Blocks that are strongly directly approved.
strong_parents: StrongParents,
/// Blocks that are weakly directly approved.
weak_parents: WeakParents,
/// Blocks that are directly referenced to adjust opinion.
shallow_like_parents: ShallowLikeParents,
/// The optional [Payload] of the block.
payload: OptionalPayload,
/// The amount of mana the Account identified by [`IssuerId`](super::IssuerId) is at most
/// willing to burn for this block.
burned_mana: u64,
/// The result of the Proof of Work in order for the block to be accepted into the tangle.
nonce: u64,
}
Expand Down Expand Up @@ -136,6 +172,18 @@ impl Block {
&self.strong_parents
}

/// Returns the weak parents of a [`Block`].
#[inline(always)]
pub fn weak_parents(&self) -> &WeakParents {
&self.weak_parents
}

/// Returns the shallow like parents of a [`Block`].
#[inline(always)]
pub fn shallow_like_parents(&self) -> &ShallowLikeParents {
&self.shallow_like_parents
}

/// Returns the optional payload of a [`Block`].
#[inline(always)]
pub fn payload(&self) -> Option<&Payload> {
Expand All @@ -148,6 +196,12 @@ impl Block {
self.nonce
}

/// Returns the burned mana of a [`Block`].
#[inline(always)]
pub fn burned_mana(&self) -> u64 {
self.burned_mana
}

/// Computes the identifier of the block.
#[inline(always)]
pub fn id(&self) -> BlockId {
Expand Down Expand Up @@ -185,7 +239,10 @@ impl Packable for Block {
fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
self.protocol_version.pack(packer)?;
self.strong_parents.pack(packer)?;
self.weak_parents.pack(packer)?;
self.shallow_like_parents.pack(packer)?;
self.payload.pack(packer)?;
self.burned_mana.pack(packer)?;
self.nonce.pack(packer)?;

Ok(())
Expand All @@ -207,18 +264,26 @@ impl Packable for Block {
}

let strong_parents = StrongParents::unpack::<_, VERIFY>(unpacker, &())?;
let payload = OptionalPayload::unpack::<_, VERIFY>(unpacker, visitor)?;
let weak_parents = WeakParents::unpack::<_, VERIFY>(unpacker, &())?;
let shallow_like_parents = ShallowLikeParents::unpack::<_, VERIFY>(unpacker, &())?;

if VERIFY {
verify_payload(payload.deref().as_ref()).map_err(UnpackError::Packable)?;
verify_parents(&strong_parents, &weak_parents, &shallow_like_parents).map_err(UnpackError::Packable)?;
}

let payload = OptionalPayload::unpack::<_, VERIFY>(unpacker, visitor)?;

let burned_mana = u64::unpack::<_, VERIFY>(unpacker, &()).coerce()?;

let nonce = u64::unpack::<_, VERIFY>(unpacker, &()).coerce()?;

let block = Self {
protocol_version,
strong_parents,
weak_parents,
shallow_like_parents,
payload,
burned_mana,
nonce,
};

Expand All @@ -238,21 +303,27 @@ impl Packable for Block {
}
}

// TODO not needed anymore?
fn verify_payload(payload: Option<&Payload>) -> Result<(), Error> {
if !matches!(
payload,
None | Some(Payload::Transaction(_)) | Some(Payload::TaggedData(_))
) {
// Safe to unwrap since it's known not to be None.
Err(Error::InvalidPayloadKind(payload.unwrap().kind()))
} else {
Ok(())
fn verify_parents(
strong_parents: &StrongParents,
weak_parents: &WeakParents,
shallow_like_parents: &ShallowLikeParents,
) -> Result<(), Error> {
let (strong_parents, weak_parents, shallow_like_parents) = (
strong_parents.to_set(),
weak_parents.to_set(),
shallow_like_parents.to_set(),
);
if !weak_parents.is_disjoint(&strong_parents) || !weak_parents.is_disjoint(&shallow_like_parents) {
return Err(Error::NonDisjointParents);
}
Ok(())
}

pub(crate) mod dto {
use alloc::string::{String, ToString};
use alloc::{
collections::BTreeSet,
string::{String, ToString},
};

use serde::{Deserialize, Serialize};

Expand All @@ -269,10 +340,14 @@ pub(crate) mod dto {
///
pub protocol_version: u8,
///
pub strong_parents: Vec<String>,
pub strong_parents: BTreeSet<BlockId>,
pub weak_parents: BTreeSet<BlockId>,
pub shallow_like_parents: BTreeSet<BlockId>,
///
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload: Option<PayloadDto>,
#[serde(with = "crate::utils::serde::string")]
pub burned_mana: u64,
///
pub nonce: String,
}
Expand All @@ -281,8 +356,11 @@ pub(crate) mod dto {
fn from(value: &Block) -> Self {
Self {
protocol_version: value.protocol_version(),
strong_parents: value.strong_parents().iter().map(BlockId::to_string).collect(),
strong_parents: value.strong_parents().to_set(),
weak_parents: value.weak_parents().to_set(),
shallow_like_parents: value.shallow_like_parents().to_set(),
payload: value.payload().map(Into::into),
burned_mana: value.burned_mana(),
nonce: value.nonce().to_string(),
}
}
Expand All @@ -293,15 +371,13 @@ pub(crate) mod dto {
type Error = Error;

fn try_from_dto_with_params_inner(dto: Self::Dto, params: ValidationParams<'_>) -> Result<Self, Self::Error> {
let strong_parents = StrongParents::from_vec(
dto.strong_parents
.into_iter()
.map(|m| m.parse::<BlockId>().map_err(|_| Error::InvalidField("parents")))
.collect::<Result<Vec<BlockId>, Error>>()?,
)?;
let strong_parents = StrongParents::from_set(dto.strong_parents)?;

let mut builder = BlockBuilder::new(strong_parents)
.with_weak_parents(WeakParents::from_set(dto.weak_parents)?)
.with_shallow_like_parents(ShallowLikeParents::from_set(dto.shallow_like_parents)?)
.with_protocol_version(dto.protocol_version)
.with_burned_mana(dto.burned_mana)
.with_nonce(dto.nonce.parse::<u64>().map_err(|_| Error::InvalidField("nonce"))?);

if let Some(p) = dto.payload {
Expand Down
4 changes: 4 additions & 0 deletions sdk/src/types/block/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub enum Error {
NativeTokensNullAmount,
NativeTokensOverflow,
NetworkIdMismatch { expected: u64, actual: u64 },
NonDisjointParents,
NonZeroStateIndexOrFoundryCounter,
ParentsNotUniqueSorted,
ProtocolVersionMismatch { expected: u8, actual: u8 },
Expand Down Expand Up @@ -234,6 +235,9 @@ impl fmt::Display for Error {
Self::NetworkIdMismatch { expected, actual } => {
write!(f, "network ID mismatch: expected {expected} but got {actual}")
}
Self::NonDisjointParents => {
write!(f, "weak parents are not disjoint to strong or shallow like parents")
}
Self::NonZeroStateIndexOrFoundryCounter => {
write!(
f,
Expand Down
17 changes: 16 additions & 1 deletion sdk/src/types/block/parent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ pub struct Parents<const MIN: u8, const MAX: u8>(
#[packable(verify_with = verify_parents)] BoxedSlicePrefix<BlockId, BoundedU8<MIN, MAX>>,
);

#[allow(clippy::len_without_is_empty)]
impl<const MIN: u8, const MAX: u8> Parents<MIN, MAX> {
/// The range representing the valid number of parents.
pub const COUNT_RANGE: RangeInclusive<u8> = MIN..=MAX;
Expand Down Expand Up @@ -55,11 +54,21 @@ impl<const MIN: u8, const MAX: u8> Parents<MIN, MAX> {
))
}

/// Returns the unique, ordered set of parents.
pub fn to_set(&self) -> BTreeSet<BlockId> {
self.0.iter().copied().collect()
}

/// Returns the number of parents.
pub fn len(&self) -> usize {
self.0.len()
}

/// Returns whether the parents list is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
Alex6323 marked this conversation as resolved.
Show resolved Hide resolved
}

/// Returns an iterator over the parents.
pub fn iter(&self) -> impl ExactSizeIterator<Item = &BlockId> + '_ {
self.0.iter()
Expand All @@ -74,6 +83,12 @@ fn verify_parents<const VERIFY: bool>(parents: &[BlockId], _: &()) -> Result<(),
}
}

impl<const MAX: u8> Default for Parents<0, MAX> {
fn default() -> Self {
Self(Default::default())
}
}

pub type StrongParents = Parents<1, 8>;
pub type WeakParents = Parents<0, 8>;
pub type ShallowLikeParents = Parents<0, 8>;
Loading