Skip to content

Commit

Permalink
operation: introduce StateData type
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Oct 15, 2024
1 parent 90e76b3 commit 8267ce2
Show file tree
Hide file tree
Showing 15 changed files with 200 additions and 163 deletions.
7 changes: 4 additions & 3 deletions src/operation/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::fmt::{Display, Formatter};
use std::str::FromStr;
use std::{fmt, vec};

use amplify::confinement::{Confined, MediumOrdMap, SmallBlob, U16 as U16MAX};
use amplify::confinement::{Confined, MediumOrdMap, U16 as U16MAX};
use amplify::hex::{FromHex, ToHex};
use amplify::num::u256;
use amplify::{hex, ByteArray, Bytes32, FromSliceError, Wrapper};
Expand All @@ -40,7 +40,8 @@ use crate::operation::state::StateCommitment;
use crate::{
impl_serde_baid64, Assign, AssignmentType, Assignments, BundleId, ExposedSeal, Extension,
ExtensionType, Ffv, Genesis, GlobalState, GlobalStateType, Operation, Redeemed, SchemaId,
SecretSeal, Transition, TransitionBundle, TransitionType, XChain, LIB_NAME_RGB_COMMIT,
SecretSeal, StateData, Transition, TransitionBundle, TransitionType, XChain,
LIB_NAME_RGB_COMMIT,
};

/// Unique contract identifier equivalent to the contract genesis commitment
Expand Down Expand Up @@ -385,7 +386,7 @@ impl<Seal: ExposedSeal> MerkleLeaves for Assignments<Seal> {
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct GlobalCommitment {
pub ty: GlobalStateType,
pub state: SmallBlob,
pub state: StateData,
}

impl CommitEncode for GlobalCommitment {
Expand Down
18 changes: 9 additions & 9 deletions src/operation/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
use std::collections::btree_map;
use std::vec;

use amplify::confinement::{Confined, NonEmptyVec, SmallBlob, TinyOrdMap, U16 as U16MAX};
use amplify::confinement::{Confined, NonEmptyVec, TinyOrdMap, U16 as U16MAX};
use amplify::{confinement, Wrapper};
use strict_encoding::StrictDumb;

use crate::{schema, LIB_NAME_RGB_COMMIT};
use crate::{schema, StateData, LIB_NAME_RGB_COMMIT};

#[derive(Wrapper, WrapperMut, Clone, PartialEq, Eq, Hash, Debug, From)]
#[wrapper(Deref)]
Expand All @@ -39,19 +39,19 @@ use crate::{schema, LIB_NAME_RGB_COMMIT};
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
pub struct GlobalValues(NonEmptyVec<SmallBlob, U16MAX>);
pub struct GlobalValues(NonEmptyVec<StateData, U16MAX>);

impl StrictDumb for GlobalValues {
fn strict_dumb() -> Self { Self(NonEmptyVec::with(SmallBlob::strict_dumb())) }
fn strict_dumb() -> Self { Self(NonEmptyVec::with(StateData::strict_dumb())) }
}

impl GlobalValues {
pub fn with(state: SmallBlob) -> Self { GlobalValues(Confined::with(state)) }
pub fn with(state: impl Into<StateData>) -> Self { GlobalValues(Confined::with(state.into())) }

Check warning on line 49 in src/operation/global.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/global.rs#L49

Added line #L49 was not covered by tests
}

impl IntoIterator for GlobalValues {
type Item = SmallBlob;
type IntoIter = vec::IntoIter<SmallBlob>;
type Item = StateData;
type IntoIter = vec::IntoIter<StateData>;

fn into_iter(self) -> Self::IntoIter { self.0.into_iter() }
}
Expand All @@ -72,7 +72,7 @@ impl GlobalState {
pub fn add_state(
&mut self,
ty: schema::GlobalStateType,
state: SmallBlob,
state: StateData,

Check warning on line 75 in src/operation/global.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/global.rs#L75

Added line #L75 was not covered by tests
) -> Result<(), confinement::Error> {
match self.0.get_mut(&ty) {
Some(vec) => vec.push(state),
Expand All @@ -83,7 +83,7 @@ impl GlobalState {
pub fn extend_state(
&mut self,
ty: schema::GlobalStateType,
iter: impl IntoIterator<Item = SmallBlob>,
iter: impl IntoIterator<Item = StateData>,

Check warning on line 86 in src/operation/global.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/global.rs#L86

Added line #L86 was not covered by tests
) -> Result<(), confinement::Error> {
match self.0.get_mut(&ty) {
Some(vec) => vec.extend(iter),
Expand Down
2 changes: 1 addition & 1 deletion src/operation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub use seal::{
ExposedSeal, GenesisSeal, GraphSeal, OutputSeal, SecretSeal, TxoSeal, XGenesisSeal, XGraphSeal,
XOutputSeal,
};
pub use state::{AttachId, State, StateCommitment};
pub use state::{AttachId, State, StateCommitment, StateData};
pub use xchain::{
AltLayer1, AltLayer1Set, Impossible, Layer1, XChain, XChainParseError, XOutpoint,
XCHAIN_BITCOIN_PREFIX, XCHAIN_LIQUID_PREFIX,
Expand Down
45 changes: 39 additions & 6 deletions src/operation/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::fmt::{Display, Formatter};
use std::str::FromStr;

use amplify::confinement::{SmallBlob, U16 as U16MAX};
use amplify::{Bytes32, Wrapper};
use amplify::{ByteArray, Bytes32, Wrapper};
use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
use commit_verify::{CommitmentId, DigestExt, ReservedBytes, Sha256};
use strict_encoding::{StrictDeserialize, StrictSerialize, StrictType};
Expand Down Expand Up @@ -63,6 +63,30 @@ impl Display for AttachId {

impl_serde_baid64!(AttachId);

#[derive(Wrapper, Clone, PartialOrd, Ord, Eq, PartialEq, Hash, Debug, From)]
#[wrapper(Deref, BorrowSlice, Index, RangeOps)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_RGB_COMMIT)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
pub struct StateData(SmallBlob);

impl StrictSerialize for StateData {}
impl StrictDeserialize for StateData {}

impl AsRef<[u8]> for StateData {
fn as_ref(&self) -> &[u8] { self.0.as_slice() }

Check warning on line 81 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L81

Added line #L81 was not covered by tests
}

impl StateData {
pub fn from_checked(vec: Vec<u8>) -> Self { Self(SmallBlob::from_checked(vec)) }

Check warning on line 85 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L85

Added line #L85 was not covered by tests

pub fn as_slice(&self) -> &[u8] { self.0.as_slice() }

Check warning on line 87 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L87

Added line #L87 was not covered by tests
}

#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Hash, Debug)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_RGB_COMMIT)]
Expand All @@ -71,12 +95,19 @@ impl_serde_baid64!(AttachId);
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"))]

Check warning on line 95 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L95

Added line #L95 was not covered by tests
pub struct State {
pub reserved: ReservedBytes<1>,
pub value: SmallBlob,
pub value: StateData,
pub attach: Option<AttachId>,
}

impl StrictSerialize for State {}
impl StrictDeserialize for State {}
impl From<StateData> for State {
fn from(value: StateData) -> Self {
State {
reserved: default!(),
value,
attach: None,

Check warning on line 107 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L103-L107

Added lines #L103 - L107 were not covered by tests
}
}
}

impl State {
/// # Panics
Expand All @@ -87,7 +118,8 @@ impl State {
reserved: default!(),
value: value
.to_strict_serialized::<U16MAX>()
.expect("unable to fit in the data"),
.expect("unable to fit in the data")
.into(),
attach: None,
}
}

Check warning on line 125 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L116-L125

Added lines #L116 - L125 were not covered by tests
Expand All @@ -100,7 +132,8 @@ impl State {
reserved: default!(),
value: value
.to_strict_serialized::<U16MAX>()
.expect("unable to fit in the data"),
.expect("unable to fit in the data")
.into(),
attach: Some(attach),
}
}

Check warning on line 139 in src/operation/state.rs

View check run for this annotation

Codecov / codecov/patch

src/operation/state.rs#L130-L139

Added lines #L130 - L139 were not covered by tests
Expand Down
4 changes: 2 additions & 2 deletions src/stl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ use crate::{

/// Strict types id for the library providing data types for RGB consensus.
pub const LIB_ID_RGB_COMMIT: &str =
"stl:JepgtiGZ-TYqkSmV-vo6ysWP-gZZEU03-pVoHbyj-nR02608#aspect-shoe-garcia";
"stl:r43G92Ru-4TQgKzY-eeZQr$e-k0DccV0-6d0mlAI-Dil$Hr4#printer-window-alpine";
/// Strict types id for the library providing data types for RGB consensus.
pub const LIB_ID_RGB_LOGIC: &str =
"stl:nKQEKac1-dDxkN3M-dXhgnba-CkprxwT-So5aC5D-meYuULE#charm-chief-invite";
"stl:51OgjzV6-F5XuTyt-FMJe4k6-opdtsQd-cptXuc4-FqM7npk#ohio-electra-dilemma";

fn _rgb_commit_stl() -> Result<TypeLib, CompileError> {
LibBuilder::new(libname!(LIB_NAME_RGB_COMMIT), tiny_bset! {
Expand Down
9 changes: 4 additions & 5 deletions src/vm/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ use std::num::NonZeroU32;
use std::rc::Rc;

use amplify::confinement;
use amplify::confinement::SmallBlob;
use amplify::num::u24;
use bp::seals::txout::{CloseMethod, ExplicitSeal, VerifyError, Witness};
use bp::{dbc, Tx, Txid};
Expand All @@ -40,8 +39,8 @@ use strict_encoding::{StrictDecode, StrictDumb, StrictEncode};
use crate::{
AssignmentType, Assignments, AssignmentsRef, ContractId, ExposedSeal, Extension, ExtensionType,
Genesis, GlobalState, GlobalStateType, GraphSeal, Impossible, Inputs, Layer1, Metadata,
OpFullType, OpId, OpType, Operation, State, Transition, TransitionType, TxoSeal, TypedAssigns,
Valencies, XChain, XOutpoint, XOutputSeal, LIB_NAME_RGB_LOGIC,
OpFullType, OpId, OpType, Operation, State, StateData, Transition, TransitionType, TxoSeal,
TypedAssigns, Valencies, XChain, XOutpoint, XOutputSeal, LIB_NAME_RGB_LOGIC,
};

pub type XWitnessId = XChain<Txid>;
Expand Down Expand Up @@ -572,7 +571,7 @@ impl GlobalOrd {
}

pub trait GlobalStateIter {
type Data: Borrow<SmallBlob>;
type Data: Borrow<StateData>;
fn size(&mut self) -> u24;
fn prev(&mut self) -> Option<(GlobalOrd, Self::Data)>;
fn last(&mut self) -> Option<(GlobalOrd, Self::Data)>;
Expand Down Expand Up @@ -633,7 +632,7 @@ impl<I: GlobalStateIter> GlobalContractState<I> {
/// Retrieves global state data located `depth` items back from the most
/// recent global state value. Ensures that the global state ordering is
/// consensus-based.
pub fn nth(&mut self, depth: u24) -> Option<impl Borrow<SmallBlob> + '_> {
pub fn nth(&mut self, depth: u24) -> Option<impl Borrow<StateData> + '_> {

Check warning on line 635 in src/vm/contract.rs

View check run for this annotation

Codecov / codecov/patch

src/vm/contract.rs#L635

Added line #L635 was not covered by tests
if depth >= self.iter.size() {
return None;
}
Expand Down
8 changes: 4 additions & 4 deletions src/vm/op_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ impl<S: ContractStateAccess> InstructionSet for ContractOp<S> {
else {
fail!()
};
regs.set_s(*reg, Some(&state.value));
regs.set_s(*reg, Some(state.value.as_inner()));

Check warning on line 242 in src/vm/op_contract.rs

View check run for this annotation

Codecov / codecov/patch

src/vm/op_contract.rs#L242

Added line #L242 was not covered by tests
}
ContractOp::LdS(state_type, reg_32, reg) => {
let Some(reg_32) = *regs.get_n(RegA::A16, *reg_32) else {
Expand All @@ -255,7 +255,7 @@ impl<S: ContractStateAccess> InstructionSet for ContractOp<S> {
else {
fail!()
};
regs.set_s(*reg, Some(state.value));
regs.set_s(*reg, Some(state.value.into_inner()));

Check warning on line 258 in src/vm/op_contract.rs

View check run for this annotation

Codecov / codecov/patch

src/vm/op_contract.rs#L258

Added line #L258 was not covered by tests
}
ContractOp::LdG(state_type, reg_8, reg_s) => {
let Some(reg_32) = *regs.get_n(RegA::A8, *reg_8) else {
Expand All @@ -271,7 +271,7 @@ impl<S: ContractStateAccess> InstructionSet for ContractOp<S> {
else {
fail!()
};
regs.set_s(*reg_s, Some(state));
regs.set_s(*reg_s, Some(state.as_inner()));
}

ContractOp::LdC(state_type, reg_32, reg_s) => {
Expand All @@ -289,7 +289,7 @@ impl<S: ContractStateAccess> InstructionSet for ContractOp<S> {
let Some(state) = global.nth(index) else {
fail!()
};
regs.set_s(*reg_s, Some(state.borrow()));
regs.set_s(*reg_s, Some(state.borrow().as_inner()));
}
ContractOp::LdM(type_id, reg) => {
let Some(meta) = context.op_info.metadata.get(type_id) else {
Expand Down
6 changes: 3 additions & 3 deletions stl/AnchoredBundle.vesper
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ TransitionBundle rec
globals map len=0..MAX8 aka=GlobalState
key is U16 aka=GlobalStateType
value list len=1..MAX16 aka=GlobalValues
element bytes len=0..MAX16
element bytes len=0..MAX16 aka=StateData
inputs set len=0..MAX16 aka=Inputs
Input rec
prevOut rec Opout
Expand All @@ -55,7 +55,7 @@ TransitionBundle rec
liquid bytes len=32 wrapped aka=SecretSeal tag=1
state rec State
reserved bytes len=1 aka=ReservedBytes1
value bytes len=0..MAX16
value bytes len=0..MAX16 aka=StateData
some bytes len=32 option wrapped aka=AttachId tag=1
lock bytes len=2 aka=ReservedBytes2
revealed rec tag=1
Expand All @@ -76,7 +76,7 @@ TransitionBundle rec
blinding is U64
state rec State
reserved bytes len=1 aka=ReservedBytes1
value bytes len=0..MAX16
value bytes len=0..MAX16 aka=StateData
some bytes len=32 option wrapped aka=AttachId tag=1
lock bytes len=2 aka=ReservedBytes2
valencies set len=0..MAX8 aka=Valencies
Expand Down
Loading

0 comments on commit 8267ce2

Please sign in to comment.