Skip to content

Commit

Permalink
simplify: overall logic
Browse files Browse the repository at this point in the history
  • Loading branch information
berzanorg committed Apr 9, 2024
1 parent 3a09e36 commit 40335d0
Show file tree
Hide file tree
Showing 44 changed files with 1,146 additions and 663 deletions.
4 changes: 3 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"rust-lang.rust-analyzer",
"tamasfe.even-better-toml",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"bradlc.vscode-tailwindcss"
],
"settings": {
"terminal.integrated.defaultProfile.linux": "fish",
Expand Down
8 changes: 4 additions & 4 deletions balances-db/src/balances_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
BalancesDbError, DoubleBalanceWitness, SingleBalanceWitness, BALANCES_TREE_HEIGHT,
BALANCES_TREE_SIBLING_COUNT, BALANCE_SIZE_IN_BYTES,
};
use nacho_data_structures::{Address, Balance, FromBytes, ToBytes, ToFields, U256};
use nacho_data_structures::{Address, Balance, ByteConversion, FieldConversion, U256};
use nacho_dynamic_list::DynamicList;
use nacho_merkle_tree::MerkleTree;
use nacho_poseidon_hash::{create_poseidon_hasher, poseidon_hash, PoseidonHasher};
Expand All @@ -27,7 +27,7 @@ impl BalancesDb {
let hasher = create_poseidon_hasher();

list.for_each(&mut indexes, |buf, index, indexes| {
let balance = Balance::from_bytes(buf);
let balance = Balance::from_bytes(&buf);

match indexes.get_mut(&balance.owner) {
Some(indexes) => {
Expand Down Expand Up @@ -108,7 +108,7 @@ impl BalancesDb {

let buf = self.list.get(index).await?;

let balance = Balance::from_bytes(buf);
let balance = Balance::from_bytes(&buf);

Ok(balance)
}
Expand All @@ -124,7 +124,7 @@ impl BalancesDb {
for &(index, _) in indexes {
let buf = self.list.get(index).await?;

let balance = Balance::from_bytes(buf);
let balance = Balance::from_bytes(&buf);

balances.push(balance)
}
Expand Down
8 changes: 4 additions & 4 deletions burns-db/src/burns_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
BurnsDbError, SingleBurnWitness, BURNS_TREE_HEIGHT, BURNS_TREE_SIBLING_COUNT,
BURN_SIZE_IN_BYTES,
};
use nacho_data_structures::{Address, Burn, FromBytes, ToBytes, ToFields, U256};
use nacho_data_structures::{Address, Burn, ByteConversion, FieldConversion, U256};
use nacho_dynamic_list::DynamicList;
use nacho_merkle_tree::MerkleTree;
use nacho_poseidon_hash::{create_poseidon_hasher, poseidon_hash, PoseidonHasher};
Expand All @@ -27,7 +27,7 @@ impl BurnsDb {
let hasher = create_poseidon_hasher();

list.for_each(&mut indexes, |buf, index, indexes| {
let burn = Burn::from_bytes(buf);
let burn = Burn::from_bytes(&buf);

match indexes.get_mut(&burn.burner) {
Some(indexes) => {
Expand Down Expand Up @@ -109,7 +109,7 @@ impl BurnsDb {

let buf = self.list.get(index).await?;

let burn = Burn::from_bytes(buf);
let burn = Burn::from_bytes(&buf);

Ok(burn)
}
Expand All @@ -125,7 +125,7 @@ impl BurnsDb {
for &(index, _) in indexes {
let buf = self.list.get(index).await?;

let burn = Burn::from_bytes(buf);
let burn = Burn::from_bytes(&buf);

burns.push(burn)
}
Expand Down
95 changes: 48 additions & 47 deletions data-structures/src/address.rs
Original file line number Diff line number Diff line change
@@ -1,87 +1,88 @@
use crate::{ByteConversion, Field, FieldConversion};
use mina_signer::CompressedPubKey;

use crate::{Field, FromBytes, ToBytes, ToFields};

/// Byte representation of base 58 encoded public keys.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Address([u8; 55]);

impl Address {
// Example: B62qoTFrus93Ryi1VzbFakzErBBmcikHEq27vhMkU4FfjGfCovv41fb
// Regexp: /^B62q[1-9A-HJ-NP-Za-km-z]{51}$/
pub fn is_valid(addr: &str) -> Result<(), ()> {
if addr.len() != 55 {
return Err(());
}
impl FieldConversion<2> for Address {
fn to_fields(&self) -> [Field; 2] {
let pubkey = CompressedPubKey::from_address(std::str::from_utf8(&self.0).unwrap()).unwrap();

if addr[0..4].as_bytes() != [66, 54, 50, 113] {
return Err(());
}
let [field_0] = pubkey.x.to_fields();
let [field_1] = pubkey.is_odd.to_fields();

for c in addr.bytes() {
match c {
b'1'..=b'9'
| b'A'..=b'H'
| b'J'..=b'N'
| b'P'..=b'Z'
| b'a'..=b'k'
| b'm'..=b'z' => (),
_ => return Err(()),
}
}

Ok(())
[field_0, field_1]
}
}

impl FromBytes for Address {
type Bytes = [u8; 55];

fn from_bytes(bytes: Self::Bytes) -> Self {
Address(bytes)
impl ByteConversion<55> for Address {
fn to_bytes(&self) -> [u8; 55] {
self.0
}
}

impl ToBytes for Address {
type Bytes = [u8; 55];

fn to_bytes(&self) -> Self::Bytes {
self.0
fn from_bytes(bytes: &[u8; 55]) -> Self {
Address(bytes.to_owned())
}
}

impl ToFields for Address {
type Fields = [Field; 2];
/// Checks the given address to be valid.
///
/// Returns `true` if it is a valid address, otherwise returns `false`.
///
/// Example valid address: `B62qoTFrus93Ryi1VzbFakzErBBmcikHEq27vhMkU4FfjGfCovv41fb`
///
/// Regular expression: `/^B62q[1-9A-HJ-NP-Za-km-z]{51}$/`
///
/// # Examples
///
/// Check an address:
///
/// ```rs
/// let is_valid = check_address("B62qoTFrus93Ryi1VzbFakzErBBmcikHEq27vhMkU4FfjGfCovv41fb");
/// assert_eq!(is_valid, true);
/// ```
///
pub fn check_address(addr: &str) -> bool {
if addr.len() != 55 {
return false;
}

fn to_fields(&self) -> Self::Fields {
let pubkey = CompressedPubKey::from_address(std::str::from_utf8(&self.0).unwrap()).unwrap();
if addr[0..4].as_bytes() != [66, 54, 50, 113] {
return false;
}

[pubkey.x, pubkey.is_odd.into()]
for c in addr.bytes() {
match c {
b'1'..=b'9' | b'A'..=b'H' | b'J'..=b'N' | b'P'..=b'Z' | b'a'..=b'k' | b'm'..=b'z' => (),
_ => return false,
}
}

true
}

#[cfg(test)]
mod tests {
use super::*;

#[test]

fn checks_if_address_is_valid() {
// /^B62q[1-9A-HJ-NP-Za-km-z]{51}$/

let addr = "B62qoTFrus93Ryi1VzbFakzErBBmcikHEq27vhMkU4FfjGfCovv41fb";
assert_eq!(Address::is_valid(addr), Ok(()));
assert_eq!(check_address(addr), true);

let addr = "B63qoTFrus93Ryi1VzbFakzErBBmcikHEq27vhMkU4FfjGfCovv41fb";
assert_eq!(Address::is_valid(addr), Err(()));
assert_eq!(check_address(addr), false);

let addr = "B63qoTFrus93Ryi1VzbFakzErBBmcikHEq2ivhMkU4FfjGfCovv41fb";
assert_eq!(Address::is_valid(addr), Err(()));
assert_eq!(check_address(addr), false);

let addr = "B63qoTFrus93Ryi1VzbFakzErBBmcikHEq2fjGfCovv41fb";
assert_eq!(Address::is_valid(addr), Err(()));
assert_eq!(check_address(addr), false);

let addr = "B63qoTFrus93Ryi1VzbFakzErBBmcikHEq2ivhMkU4FfvhMkU4FfjGfCovv41fb";
assert_eq!(Address::is_valid(addr), Err(()));
assert_eq!(check_address(addr), false);
}
}
45 changes: 17 additions & 28 deletions data-structures/src/balance.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Address, Field, FromBytes, ToBytes, ToFields, U256};
use crate::{Address, ByteConversion, Field, FieldConversion, U256};

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Balance {
Expand All @@ -7,37 +7,18 @@ pub struct Balance {
pub token_amount: u64,
}

impl ToFields for Balance {
type Fields = [Field; 4];
impl FieldConversion<4> for Balance {
fn to_fields(&self) -> [Field; 4] {
let [field_0, field_1] = self.owner.to_fields();
let [field_2] = self.token_id.to_fields();
let [field_3] = self.token_amount.to_fields();

fn to_fields(&self) -> Self::Fields {
let owner = self.owner.to_fields();

[
owner[0],
owner[1],
(&self.token_id).into(),
self.token_amount.into(),
]
}
}

impl FromBytes for Balance {
type Bytes = [u8; 95];

fn from_bytes(bytes: Self::Bytes) -> Self {
Self {
owner: Address::from_bytes(bytes[0..55].try_into().unwrap()),
token_id: U256::from_bytes(bytes[55..87].try_into().unwrap()),
token_amount: u64::from_bytes(bytes[87..95].try_into().unwrap()),
}
[field_0, field_1, field_2, field_3]
}
}

impl ToBytes for Balance {
type Bytes = [u8; 95];

fn to_bytes(&self) -> Self::Bytes {
impl ByteConversion<95> for Balance {
fn to_bytes(&self) -> [u8; 95] {
let mut bytes = [0u8; 95];

bytes[0..55].copy_from_slice(&self.owner.to_bytes());
Expand All @@ -46,4 +27,12 @@ impl ToBytes for Balance {

bytes
}

fn from_bytes(bytes: &[u8; 95]) -> Self {
Self {
owner: Address::from_bytes(bytes[0..55].try_into().unwrap()),
token_id: U256::from_bytes(bytes[55..87].try_into().unwrap()),
token_amount: u64::from_bytes(bytes[87..95].try_into().unwrap()),
}
}
}
45 changes: 17 additions & 28 deletions data-structures/src/burn.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Address, Field, FromBytes, ToBytes, ToFields, U256};
use crate::{Address, ByteConversion, Field, FieldConversion, U256};

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Burn {
Expand All @@ -7,37 +7,18 @@ pub struct Burn {
pub token_amount: u64,
}

impl ToFields for Burn {
type Fields = [Field; 4];
impl FieldConversion<4> for Burn {
fn to_fields(&self) -> [Field; 4] {
let [field_0, field_1] = self.burner.to_fields();
let [field_2] = self.token_id.to_fields();
let [field_3] = self.token_amount.to_fields();

fn to_fields(&self) -> Self::Fields {
let burner = self.burner.to_fields();

[
burner[0],
burner[1],
(&self.token_id).into(),
self.token_amount.into(),
]
}
}

impl FromBytes for Burn {
type Bytes = [u8; 95];

fn from_bytes(bytes: Self::Bytes) -> Self {
Self {
burner: Address::from_bytes(bytes[0..55].try_into().unwrap()),
token_id: U256::from_bytes(bytes[55..87].try_into().unwrap()),
token_amount: u64::from_bytes(bytes[87..95].try_into().unwrap()),
}
[field_0, field_1, field_2, field_3]
}
}

impl ToBytes for Burn {
type Bytes = [u8; 95];

fn to_bytes(&self) -> Self::Bytes {
impl ByteConversion<95> for Burn {
fn to_bytes(&self) -> [u8; 95] {
let mut bytes = [0u8; 95];

bytes[0..55].copy_from_slice(&self.burner.to_bytes());
Expand All @@ -46,4 +27,12 @@ impl ToBytes for Burn {

bytes
}

fn from_bytes(bytes: &[u8; 95]) -> Self {
Self {
burner: Address::from_bytes(bytes[0..55].try_into().unwrap()),
token_id: U256::from_bytes(bytes[55..87].try_into().unwrap()),
token_amount: u64::from_bytes(bytes[87..95].try_into().unwrap()),
}
}
}
48 changes: 48 additions & 0 deletions data-structures/src/byte_conversion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/// The trait that is used to convert statically sized data structures back and forth into bytes.
///
/// The constant generic parameter `L` represents the length of the byte representation of the data structures.
pub trait ByteConversion<const L: usize> {
/// Converts the data structure to bytes.
///
/// # Examples
///
/// Convert to bytes:
///
/// ```rs
/// let bytes = data.to_bytes();
/// ```
///
fn to_bytes(&self) -> [u8; L];

/// Creates a data structure from the given bytes.
///
/// # Examples
///
/// Create a data structure:
///
/// ```rs
/// let data = ByteConversion.from_bytes(bytes);
/// ```
///
fn from_bytes(bytes: &[u8; L]) -> Self;
}

impl ByteConversion<8> for u64 {
fn to_bytes(&self) -> [u8; 8] {
self.to_le_bytes()
}

fn from_bytes(bytes: &[u8; 8]) -> Self {
u64::from_le_bytes(bytes.to_owned())
}
}

impl ByteConversion<1> for bool {
fn to_bytes(&self) -> [u8; 1] {
(self.to_owned() as u8).to_le_bytes()
}

fn from_bytes(bytes: &[u8; 1]) -> Self {
bytes[0] != 0
}
}
Loading

0 comments on commit 40335d0

Please sign in to comment.