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

Update SimpleSmt usage as per latest crypto crate updates #426

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ codegen-units = 1
lto = true

[workspace.dependencies]
assembly = { package = "miden-assembly", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
miden-verifier = { package = "miden-verifier", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
vm-processor = { package = "miden-processor", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
assembly = { package = "miden-assembly", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
miden-verifier = { package = "miden-verifier", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
vm-processor = { package = "miden-processor", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
2 changes: 1 addition & 1 deletion miden-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ testing = ["miden-objects/testing"]

[dependencies]
miden-objects = { package = "miden-objects", path = "../objects", default-features = false }
miden-stdlib = { package = "miden-stdlib", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
miden-stdlib = { package = "miden-stdlib", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }

[dev-dependencies]
miden-objects = { package = "miden-objects", path = "../objects", default-features = false, features = ["testing" ]}
Expand Down
30 changes: 19 additions & 11 deletions miden-lib/src/tests/test_account.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use miden_objects::accounts::{
AccountId, AccountType, ACCOUNT_ID_FUNGIBLE_FAUCET_ON_CHAIN, ACCOUNT_ID_INSUFFICIENT_ONES,
ACCOUNT_ID_NON_FUNGIBLE_FAUCET_OFF_CHAIN, ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN,
ACCOUNT_ID_REGULAR_ACCOUNT_UPDATABLE_CODE_OFF_CHAIN,
use miden_objects::{
accounts::{
AccountId, AccountType, ACCOUNT_ID_FUNGIBLE_FAUCET_ON_CHAIN, ACCOUNT_ID_INSUFFICIENT_ONES,
ACCOUNT_ID_NON_FUNGIBLE_FAUCET_OFF_CHAIN,
ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN,
ACCOUNT_ID_REGULAR_ACCOUNT_UPDATABLE_CODE_OFF_CHAIN,
},
crypto::merkle::LeafIndex,
};
use mock::{
constants::{
Expand Down Expand Up @@ -264,9 +268,9 @@ fn test_set_item() {
let init_root = account_smt.root();

// insert a new leaf value
const NEW_ITEM_INDEX: u64 = 12;
const NEW_ITEM_VALUE: Word = [Felt::new(91), Felt::new(92), Felt::new(93), Felt::new(94)];
account_smt.update_leaf(NEW_ITEM_INDEX, NEW_ITEM_VALUE).unwrap();
let new_item_index = LeafIndex::new(12).unwrap();
let new_item_value: Word = [Felt::new(91), Felt::new(92), Felt::new(93), Felt::new(94)];
account_smt.insert(new_item_index, new_item_value);
assert_ne!(account_smt.root(), init_root);

let code = format!(
Expand All @@ -283,7 +287,7 @@ fn test_set_item() {
push.{new_value}

# push the account storage item index
push.{NEW_ITEM_INDEX}
push.{new_item_index}

# get the item
exec.account::set_item
Expand All @@ -298,7 +302,8 @@ fn test_set_item() {
push.{new_root} assert_eqw
end
",
new_value = prepare_word(&NEW_ITEM_VALUE),
new_value = prepare_word(&new_item_value),
new_item_index = new_item_index.value(),
new_root = prepare_word(&account_smt.root()),
);

Expand Down Expand Up @@ -385,9 +390,12 @@ fn test_authenticate_procedure() {
mock_inputs(MockAccountType::StandardExisting, AssetPreservationStatus::Preserved);
let account = tx_inputs.account();

let proc0_index = LeafIndex::new(0).unwrap();
let proc1_index = LeafIndex::new(1).unwrap();

let test_cases = vec![
(account.code().procedure_tree().get_leaf(0).unwrap(), true),
(account.code().procedure_tree().get_leaf(1).unwrap(), true),
(account.code().procedure_tree().get_leaf(&proc0_index), true),
(account.code().procedure_tree().get_leaf(&proc1_index), true),
([ONE, ZERO, ONE, ZERO], false),
];

Expand Down
2 changes: 1 addition & 1 deletion miden-tx/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ std = ["miden-lib/std", "miden-objects/std", "miden-prover/std", "miden-verifier
[dependencies]
miden-lib = { package = "miden-lib", path = "../miden-lib", default-features = false }
miden-objects = { package = "miden-objects", path = "../objects", default-features = false }
miden-prover = { package = "miden-prover", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
miden-prover = { package = "miden-prover", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
miden-verifier = { workspace = true }
vm-processor = { workspace = true }

Expand Down
2 changes: 1 addition & 1 deletion mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ env_logger = { version = "0.10" }
hex = "0.4"
miden-lib = { path = "../miden-lib" }
miden-objects = { path = "../objects" , features = ["serde", "log", "testing"]}
miden-test-utils = { package = "miden-test-utils", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
miden-test-utils = { package = "miden-test-utils", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
postcard = { version = "1.0", features = [ "alloc" ] }
rand = { version = "0.8" }
rand_pcg = { version = "0.3", features = ["serde1"] }
Expand Down
5 changes: 2 additions & 3 deletions mock/src/mock/block.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use miden_objects::{
accounts::Account, crypto::merkle::SimpleSmt, utils::collections::Vec, BlockHeader, Digest,
Felt, StarkField, ZERO,
Felt, StarkField, ACCOUNT_TREE_DEPTH, ZERO,
};
use miden_test_utils::rand;

Expand All @@ -10,8 +10,7 @@ pub fn mock_block_header(
note_root: Option<Digest>,
accts: &[Account],
) -> BlockHeader {
let acct_db = SimpleSmt::with_leaves(
64,
let acct_db = SimpleSmt::<ACCOUNT_TREE_DEPTH>::with_leaves(
accts
.iter()
.flat_map(|acct| {
Expand Down
49 changes: 22 additions & 27 deletions mock/src/mock/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use core::fmt;
use miden_objects::{
accounts::{Account, AccountId, AccountType, SlotItem},
assets::Asset,
crypto::merkle::{Mmr, NodeIndex, PartialMmr, SimpleSmt, TieredSmt},
notes::{Note, NoteInclusionProof, NOTE_LEAF_DEPTH, NOTE_TREE_DEPTH},
crypto::merkle::{Mmr, PartialMmr, SimpleSmt, TieredSmt},
notes::{Note, NoteInclusionProof},
transaction::{ChainMmr, InputNote},
utils::collections::Vec,
BlockHeader, Digest, Felt, FieldElement, StarkField, Word,
BlockHeader, Digest, Felt, FieldElement, Word, ACCOUNT_TREE_DEPTH, NOTE_TREE_DEPTH,
};
use miden_test_utils::crypto::LeafIndex;
use rand::{Rng, SeedableRng};

use super::{
Expand Down Expand Up @@ -60,7 +61,7 @@ impl<R: Rng> Objects<R> {
&mut self,
pending: &mut Objects<R>,
header: BlockHeader,
notes: &SimpleSmt,
notes: &SimpleSmt<NOTE_TREE_DEPTH>,
) {
self.accounts.append(&mut pending.accounts);
self.fungible_faucets.append(&mut pending.fungible_faucets);
Expand All @@ -76,7 +77,7 @@ impl<R: Rng> Objects<R> {
/// The root of the tree is a commitment to all notes created in the block. The commitment
/// is not for all fields of the [Note] struct, but only for note metadata + core fields of
/// a note (i.e., vault, inputs, script, and serial number).
pub fn build_notes_tree(&self) -> SimpleSmt {
pub fn build_notes_tree(&self) -> SimpleSmt<NOTE_TREE_DEPTH> {
let mut entries = Vec::with_capacity(self.notes.len() * 2);

entries.extend(self.notes.iter().enumerate().map(|(index, note)| {
Expand All @@ -88,29 +89,30 @@ impl<R: Rng> Objects<R> {
(tree_index, note.metadata().into())
}));

SimpleSmt::with_leaves(NOTE_LEAF_DEPTH, entries).unwrap()
SimpleSmt::with_leaves(entries).unwrap()
}

/// Given the [BlockHeader] and its notedb's [SimpleSmt], set all the [Note]'s proof.
///
/// Update the [Note]'s proof once the [BlockHeader] has been created.
fn finalize_notes(&mut self, header: BlockHeader, notes: &SimpleSmt) -> Vec<InputNote> {
fn finalize_notes(
&mut self,
header: BlockHeader,
notes: &SimpleSmt<NOTE_TREE_DEPTH>,
) -> Vec<InputNote> {
self.notes
.drain(..)
.enumerate()
.map(|(index, note)| {
let auth_index =
NodeIndex::new(NOTE_TREE_DEPTH, index as u64).expect("index bigger than 2**20");
let note_path =
notes.get_path(auth_index).expect("auth_index outside of SimpleSmt range");
let auth_index = LeafIndex::new(index as u64).expect("index bigger than 2**20");
InputNote::new(
note.clone(),
NoteInclusionProof::new(
header.block_num(),
header.sub_hash(),
header.note_root(),
index as u64,
note_path,
notes.open(&auth_index).path,
)
.expect("Invalid data provided to proof constructor"),
)
Expand All @@ -133,8 +135,7 @@ pub struct MockChain<R> {
nullifiers: TieredSmt,

/// Tree containing the latest hash of each account.
// TODO: change this to a TieredSmt with 64bit keys.
accounts: SimpleSmt,
accounts: SimpleSmt<ACCOUNT_TREE_DEPTH>,

/// RNG used to seed builders.
///
Expand Down Expand Up @@ -199,7 +200,7 @@ impl<R: Rng + SeedableRng> MockChain<R> {
chain: Mmr::default(),
blocks: vec![],
nullifiers: TieredSmt::default(),
accounts: SimpleSmt::new(64).expect("depth too big for SimpleSmt"),
accounts: SimpleSmt::<ACCOUNT_TREE_DEPTH>::new().expect("depth too big for SimpleSmt"),
rng,
account_id_builder,
objects: Objects::new(),
Expand Down Expand Up @@ -443,12 +444,10 @@ impl<R: Rng + SeedableRng> MockChain<R> {
let block_num: u32 = self.blocks.len().try_into().expect("usize to u32 failed");

for (account, _seed) in self.pending_objects.accounts.iter() {
let id: Felt = account.id().into();
self.accounts.update_leaf(id.as_int(), account.hash().into()).unwrap();
self.accounts.insert(account.id().into(), account.hash().into());
}
for (account, _seed) in self.objects.accounts.iter() {
let id: Felt = account.id().into();
self.accounts.update_leaf(id.as_int(), account.hash().into()).unwrap();
self.accounts.insert(account.id().into(), account.hash().into());
}

// TODO:
Expand Down Expand Up @@ -606,12 +605,8 @@ pub fn mock_chain_data(consumed_notes: Vec<Note>) -> (ChainMmr, Vec<InputNote>)
// TODO: Consider how to better represent note authentication data.
// we use the index for both the block number and the leaf index in the note tree
for (index, note) in consumed_notes.iter().enumerate() {
let tree_index = 2 * index;
let smt_entries = vec![
(tree_index as u64, note.id().into()),
((tree_index + 1) as u64, note.metadata().into()),
];
let smt = SimpleSmt::with_leaves(NOTE_LEAF_DEPTH, smt_entries).unwrap();
let smt_entries = vec![(index as u64, note.authentication_hash().into())];
let smt = SimpleSmt::<NOTE_TREE_DEPTH>::with_leaves(smt_entries).unwrap();
note_trees.push(smt);
}

Expand All @@ -638,15 +633,15 @@ pub fn mock_chain_data(consumed_notes: Vec<Note>) -> (ChainMmr, Vec<InputNote>)
.enumerate()
.map(|(index, note)| {
let block_header = &block_chain[index];
let auth_index = NodeIndex::new(NOTE_TREE_DEPTH, index as u64).unwrap();
let auth_index = LeafIndex::new(index as u64).unwrap();
InputNote::new(
note,
NoteInclusionProof::new(
block_header.block_num(),
block_header.sub_hash(),
block_header.note_root(),
index as u64,
note_trees[index].get_path(auth_index).unwrap(),
note_trees[index].open(&auth_index).path,
)
.unwrap(),
)
Expand Down
4 changes: 2 additions & 2 deletions objects/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ testing = []
[dependencies]
assembly = { workspace = true }
log = { version = "0.4", optional = true }
miden-crypto = { git = "https://github.com/0xPolygonMiden/crypto", branch = "next", default-features = false }
miden-crypto = { git = "https://github.com/0xPolygonMiden/crypto", branch = "plafer-smt-trait", default-features = false }
miden-verifier = { workspace = true }
serde = { version = "1.0", optional = true, default-features = false, features = ["derive"] }
vm-core = { package = "miden-core", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "next", default-features = false }
vm-core = { package = "miden-core", git = "https://github.com/0xPolygonMiden/miden-vm.git", branch = "plafer-fix-build-smt", default-features = false }
vm-processor = { workspace = true }

[dev-dependencies]
Expand Down
51 changes: 32 additions & 19 deletions objects/src/accounts/account_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::{
get_account_seed, Account, AccountError, ByteReader, Deserializable, DeserializationError,
Digest, Felt, FieldElement, Hasher, Serializable, StarkField, String, ToString, Vec, Word,
};
use crate::utils::hex_to_bytes;
use crate::{crypto::merkle::LeafIndex, utils::hex_to_bytes, ACCOUNT_TREE_DEPTH};

// ACCOUNT ID
// ================================================================================================
Expand Down Expand Up @@ -225,6 +225,27 @@ impl AccountId {
}
}

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

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

impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0x{:02x}", self.0.as_int())
}
}

// CONVERSIONS FROM ACCOUNT ID
// ================================================================================================

impl From<AccountId> for Felt {
fn from(id: AccountId) -> Self {
id.0
Expand All @@ -245,6 +266,16 @@ impl From<AccountId> for u64 {
}
}

/// Account IDs are used as indexes in the account database, which is a tree of depth 64.
impl From<AccountId> for LeafIndex<ACCOUNT_TREE_DEPTH> {
fn from(id: AccountId) -> Self {
LeafIndex::new_max_depth(id.0.as_int())
}
}

// CONVERSIONS TO ACCOUNT ID
// ================================================================================================

impl TryFrom<Felt> for AccountId {
type Error = AccountError;

Expand Down Expand Up @@ -274,24 +305,6 @@ impl TryFrom<u64> for AccountId {
}
}

impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0x{:02x}", self.0.as_int())
}
}

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

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

// SERIALIZATION
// ================================================================================================

Expand Down
Loading
Loading