Skip to content

Commit

Permalink
feat: use dedicated Nonce type Instead of u32
Browse files Browse the repository at this point in the history
Fixes #1287
  • Loading branch information
jhult committed Jul 15, 2024
1 parent 3eaff8f commit b0dfd34
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 36 deletions.
15 changes: 9 additions & 6 deletions rust/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ pub mod store;
use crate::{
block::{precomputed::PrecomputedBlock, BlockHash},
command::signed::{SignedCommand, SignedCommandWithKind},
ledger::{account::Amount, public_key::PublicKey},
ledger::{
account::{Amount, Nonce},
public_key::PublicKey,
},
protocol::serialization_types::staged_ledger_diff as mina_rs,
};
use log::trace;
Expand Down Expand Up @@ -34,15 +37,15 @@ pub struct CommandWithStateHash {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub struct Payment {
pub source: PublicKey,
pub nonce: u32,
pub nonce: Nonce,
pub amount: Amount,
pub receiver: PublicKey,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub struct Delegation {
pub delegator: PublicKey,
pub nonce: u32,
pub nonce: Nonce,
pub delegate: PublicKey,
}

Expand Down Expand Up @@ -144,7 +147,7 @@ pub trait UserCommandWithStatusT {

fn receiver(&self) -> PublicKey;

fn nonce(&self) -> u32;
fn nonce(&self) -> Nonce;

fn amount(&self) -> u64;

Expand Down Expand Up @@ -246,7 +249,7 @@ impl UserCommandWithStatusT for UserCommandWithStatus {
}
}

fn nonce(&self) -> u32 {
fn nonce(&self) -> Nonce {
self.to_command().nonce()
}

Expand Down Expand Up @@ -343,7 +346,7 @@ impl Command {
.collect()
}

pub fn nonce(&self) -> u32 {
pub fn nonce(&self) -> Nonce {
match self {
Self::Delegation(Delegation { nonce, .. }) => *nonce,
Self::Payment(Payment { nonce, .. }) => *nonce,
Expand Down
4 changes: 2 additions & 2 deletions rust/src/command/signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ impl SignedCommand {
}
}

pub fn source_nonce(&self) -> u32 {
self.payload_common().nonce.t.t as u32
pub fn source_nonce(&self) -> Nonce {
Nonce(self.payload_common().nonce.t.t as u32)
}

pub fn payload_body(&self) -> mina_rs::SignedCommandPayloadBody {
Expand Down
55 changes: 48 additions & 7 deletions rust/src/ledger/account/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ use crate::{
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::Number;
use std::{
fmt::{self, Display},
ops::{Add, Sub},
};

#[derive(
Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash, Serialize, Deserialize,
Expand All @@ -18,25 +23,61 @@ impl ToString for Amount {
}
}

impl std::ops::Add<Amount> for Amount {
impl Add<Amount> for Amount {
type Output = Amount;

fn add(self, rhs: Amount) -> Self::Output {
Self(self.0 + rhs.0)
}
}

impl std::ops::Sub<Amount> for Amount {
impl Sub<Amount> for Amount {
type Output = Amount;

fn sub(self, rhs: Amount) -> Self::Output {
Self(self.0 - rhs.0)
}
}

#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Serialize, Deserialize)]
#[derive(
PartialEq, Eq, Debug, Copy, Clone, Default, Serialize, Deserialize, PartialOrd, Ord, Hash,
)]
pub struct Nonce(pub u32);

impl Add<i32> for Nonce {
type Output = Nonce;

fn add(self, other: i32) -> Nonce {
Nonce(self.0.wrapping_add(other as u32))
}
}

impl Sub<i32> for Nonce {
type Output = Nonce;

fn sub(self, other: i32) -> Self::Output {
Self(self.0.wrapping_sub(other as u32))
}
}

impl From<String> for Nonce {
fn from(s: String) -> Self {
Nonce(s.parse::<u32>().expect("nonce is u32"))
}
}

impl From<Nonce> for serde_json::value::Number {
fn from(n: Nonce) -> Self {
Number::from(n.0)
}
}

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

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
pub public_key: PublicKey,
Expand Down Expand Up @@ -148,13 +189,13 @@ impl Account {
}
}

fn from_debit(pre: Self, amount: Amount, nonce: Option<u32>) -> Option<Self> {
fn from_debit(pre: Self, amount: Amount, nonce: Option<Nonce>) -> Option<Self> {
if amount > pre.balance {
None
} else {
Some(Account {
balance: pre.balance - amount,
nonce: Nonce(nonce.unwrap_or(pre.nonce.0)),
nonce: nonce.unwrap_or(pre.nonce),
..pre
})
}
Expand All @@ -177,9 +218,9 @@ impl Account {
}
}

pub fn from_failed_transaction(pre: Self, nonce: u32) -> Self {
pub fn from_failed_transaction(pre: Self, nonce: Nonce) -> Self {
Account {
nonce: Nonce(nonce + 1),
nonce: nonce + 1,
..pre
}
}
Expand Down
22 changes: 11 additions & 11 deletions rust/src/ledger/diff/account.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
block::precomputed::PrecomputedBlock,
command::{signed::SignedCommand, Command, UserCommandWithStatus},
ledger::{coinbase::Coinbase, Amount, PublicKey},
ledger::{account::Nonce, coinbase::Coinbase, Amount, PublicKey},
snark_work::SnarkWorkSummary,
};
use serde::{Deserialize, Serialize};
Expand All @@ -10,7 +10,7 @@ use std::collections::HashMap;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
pub enum UpdateType {
/// Carries Some(nonce) for a user command, None for internal command
Debit(Option<u32>),
Debit(Option<Nonce>),
Credit,
}

Expand All @@ -23,7 +23,7 @@ pub struct PaymentDiff {

#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Serialize, Deserialize)]
pub struct DelegationDiff {
pub nonce: u32,
pub nonce: Nonce,
pub delegator: PublicKey,
pub delegate: PublicKey,
}
Expand All @@ -37,7 +37,7 @@ pub struct CoinbaseDiff {
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Serialize, Deserialize)]
pub struct FailedTransactionNonceDiff {
pub public_key: PublicKey,
pub nonce: u32,
pub nonce: Nonce,
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Serialize, Deserialize)]
Expand Down Expand Up @@ -213,7 +213,7 @@ impl AccountDiff {
Self::Payment(PaymentDiff {
public_key: sender.into(),
amount: amount.into(),
update_type: UpdateType::Debit(Some(nonce)),
update_type: UpdateType::Debit(Some(Nonce(nonce))),
}),
Self::Payment(PaymentDiff {
public_key: receiver.into(),
Expand All @@ -224,7 +224,7 @@ impl AccountDiff {
AccountDiffType::Delegation(nonce) => vec![Self::Delegation(DelegationDiff {
delegate: sender.into(),
delegator: receiver.into(),
nonce,
nonce: Nonce(nonce),
})],
AccountDiffType::Coinbase => vec![Self::Coinbase(CoinbaseDiff {
public_key: sender.into(),
Expand Down Expand Up @@ -342,7 +342,7 @@ mod tests {
use crate::{
command::{Command, Delegation, Payment},
ledger::{
account::Amount,
account::{Amount, Nonce},
coinbase::{Coinbase, CoinbaseFeeTransfer, CoinbaseKind},
PublicKey,
},
Expand Down Expand Up @@ -391,7 +391,7 @@ mod tests {
let source_public_key = PublicKey::new(source_str);
let receiver_str = "B62qjoDXHMPZx8AACUrdaKVyDcn7uxbym1kxodgMXztn6iJC2yqEKbs";
let receiver_public_key = PublicKey::new(receiver_str);
let nonce = 5;
let nonce = Nonce(5);

let payment_command = Command::Payment(Payment {
source: source_public_key.clone(),
Expand Down Expand Up @@ -421,7 +421,7 @@ mod tests {
let delegator_public_key = PublicKey::new(delegator_str);
let delegate_str = "B62qjSytpSK7aEauBprjXDSZwc9ai4YMv9tpmXLQK14Vy941YV36rMz";
let delegate_public_key = PublicKey::new(delegate_str);
let nonce = 42;
let nonce = Nonce(42);

let delegation_command = Command::Delegation(Delegation {
delegator: delegator_public_key.clone(),
Expand Down Expand Up @@ -460,7 +460,7 @@ mod tests {

#[test]
fn test_public_key_payment() {
let nonce = 42;
let nonce = Nonce(42);
let payment_diff = PaymentDiff {
public_key: PublicKey::new("B62qqmveaSLtpcfNeaF9KsEvLyjsoKvnfaHy4LHyApihPVzR3qDNNEG"),
amount: 536900000000.into(),
Expand All @@ -475,7 +475,7 @@ mod tests {

#[test]
fn test_public_key_delegation() {
let nonce = 42;
let nonce = Nonce(42);
let delegation_diff = DelegationDiff {
delegator: PublicKey::new("B62qpYZ5BUaXq7gkUksirDA5c7okVMBY6VrQbj7YHLARWiBvu6A2fqi"),
delegate: PublicKey::new("B62qjSytpSK7aEauBprjXDSZwc9ai4YMv9tpmXLQK14Vy941YV36rMz"),
Expand Down
2 changes: 1 addition & 1 deletion rust/src/ledger/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub struct GenesisRoot {
pub struct GenesisAccount {
pub pk: String,
pub balance: String,
pub nonce: Option<u32>,
pub nonce: Option<Nonce>,
pub delegate: Option<String>,
pub token: Option<u64>,
pub token_permissions: Option<TokenPermissions>,
Expand Down
4 changes: 2 additions & 2 deletions rust/src/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ mod tests {
public_key::PublicKey,
Ledger, LedgerHash,
};
use crate::block::BlockHash;
use crate::{block::BlockHash, ledger::account::Nonce};
use std::collections::{BTreeMap, HashMap};

#[test]
Expand Down Expand Up @@ -387,7 +387,7 @@ mod tests {

#[test]
fn apply_diff_delegation() {
let nonce = 42;
let nonce = Nonce(42);
let public_key = PublicKey::new("B62qre3erTHfzQckNuibViWQGyyKwZseztqrjPZBv6SQF384Rg6ESAy");
let delegate_key =
PublicKey::new("B62qmMypEDCchUgPD6RU99gVKXJcY46urKdjbFmG5cYtaVpfKysXTz6");
Expand Down
7 changes: 3 additions & 4 deletions rust/src/ledger/staking/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod parser;

use super::account::Nonce;
use crate::{
block::BlockHash,
chain::Network,
Expand Down Expand Up @@ -38,7 +39,7 @@ pub struct StakingAccount {
pub receipt_chain_hash: ReceiptChainHash,
pub voting_for: BlockHash,
pub permissions: Permissions,
pub nonce: Option<u32>,
pub nonce: Option<Nonce>,
pub timing: Option<Timing>,
pub zkapp: Option<ZkappAccount>,
}
Expand Down Expand Up @@ -98,9 +99,7 @@ pub struct AggregatedEpochStakeDelegation {
impl From<StakingAccountJson> for StakingAccount {
fn from(value: StakingAccountJson) -> Self {
let token = Some(value.token.parse().expect("token is u32"));
let nonce = value
.nonce
.map(|nonce| nonce.parse().expect("nonce is u32"));
let nonce = value.nonce.map(|nonce| nonce.into());
let balance = match value.balance.parse::<Decimal>() {
Ok(amt) => (amt * dec!(1_000_000_000))
.to_u64()
Expand Down
2 changes: 1 addition & 1 deletion rust/src/web/graphql/stakes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ impl
Self {
chain_id: StakingAccount::chain_id(),
balance,
nonce,
nonce: nonce.0,
delegate,
pk,
public_key,
Expand Down
4 changes: 2 additions & 2 deletions rust/tests/state/ledger/diff_from_precomputed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async fn account_diffs() {
*balance -= amount.0 as i64;

if let Some(new_nonce) = new_nonce {
*nonce = new_nonce;
*nonce = new_nonce.0;
}
}
}
Expand Down Expand Up @@ -133,7 +133,7 @@ async fn account_diffs() {
println!("nonce: {new_nonce}");

if let Some((_, nonce)) = ledger.get_mut(&public_key) {
*nonce += new_nonce;
*nonce += new_nonce.0;
} else {
ledger.insert(public_key, (0, 0));
}
Expand Down

0 comments on commit b0dfd34

Please sign in to comment.