Skip to content

Commit

Permalink
refactor(amount): Amount -> NeptuneCoins
Browse files Browse the repository at this point in the history
NeptuneCoins is now a wrapper around nau, which is the atomic unit of
Neptune. 1 Neptune coin = 2^2 * 10^30 nau.

 - Rename `Amount` to `NeptuneCoins`
 - Drop `into` and `from` implementations as these are ambiguous.
 - Fix string conversion.
  • Loading branch information
aszepieniec committed Feb 3, 2024
1 parent 2fa96ae commit 99e8da6
Show file tree
Hide file tree
Showing 24 changed files with 701 additions and 538 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ num-traits = "0"
priority-queue = "1"
rand = "0.8"
ratatui = "0.23"
regex = "1.10.3"
semver = "^1.0.21"
serde = { version = "1", features = ["derive"] }
serde_derive = "1"
Expand Down
33 changes: 15 additions & 18 deletions src/bin/dashboard_src/history_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ use crossterm::event::{Event, KeyCode, KeyEventKind};
use itertools::Itertools;
use neptune_core::{
models::blockchain::block::block_height::BlockHeight,
models::blockchain::transaction::amount::{Amount, Sign},
rpc_server::RPCClient,
models::blockchain::transaction::neptune_coins::NeptuneCoins, rpc_server::RPCClient,
};
use num_traits::{CheckedSub, Zero};
use ratatui::{
Expand All @@ -23,7 +22,7 @@ use tokio::time::sleep;
use tokio::{select, task::JoinHandle};
use unicode_width::UnicodeWidthStr;

type BalanceUpdate = (BlockHeight, Duration, Amount, Sign, Amount);
type BalanceUpdate = (BlockHeight, Duration, NeptuneCoins, NeptuneCoins);
type BalanceUpdateArc = Arc<std::sync::Mutex<Vec<BalanceUpdate>>>;
type DashboardEventArc = Arc<std::sync::Mutex<Option<DashboardEvent>>>;
type JoinHandleArc = Arc<Mutex<JoinHandle<()>>>;
Expand Down Expand Up @@ -147,18 +146,16 @@ impl HistoryScreen {
_ = &mut balance_history => {
let bh = rpc_client.history(context::current()).await.unwrap();
let mut history_builder = Vec::with_capacity(bh.len());
let mut balance = Amount::zero();
for (_, block_height, timestamp, amount, sign) in bh.iter() {
match sign {
Sign::NonNegative => { balance = balance + *amount; }
Sign::Negative => {
balance = match balance.checked_sub(amount) {
Some(b) => b,
None => Amount::zero(),
};
}
let mut balance = NeptuneCoins::zero();
for (_, block_height, timestamp, amount) in bh.iter() {
if amount.is_negative() {
balance = match balance.checked_sub(amount) {
Some(b) => b,
None => NeptuneCoins::zero(),
};
}
history_builder.push((*block_height, *timestamp, *amount, *sign, balance));
else { balance = balance + *amount; }
history_builder.push((*block_height, *timestamp, *amount, balance));
}
*balance_updates.lock().unwrap() = history_builder;

Expand Down Expand Up @@ -267,14 +264,14 @@ impl Widget for HistoryScreen {
.iter()
.rev()
.map(|bu| {
let (height, timestamp, amount, sign, balance) = *bu;
let (height, timestamp, amount, balance) = *bu;
vec![
height.to_string(),
neptune_core::utc_timestamp_to_localtime(timestamp.as_millis()).to_string(),
if sign == Sign::NonNegative {
"".to_string()
if !amount.is_negative() {
"".to_string()
} else {
"".to_string()
"".to_string()
},
amount.to_string(),
balance.to_string(),
Expand Down
6 changes: 3 additions & 3 deletions src/bin/dashboard_src/overview_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use neptune_core::config_models::network::Network;
use neptune_core::models::blockchain::block::block_header::BlockHeader;
use neptune_core::models::blockchain::block::block_height::BlockHeight;
use neptune_core::models::blockchain::shared::Hash;
use neptune_core::models::blockchain::transaction::amount::Amount;
use neptune_core::models::blockchain::transaction::neptune_coins::NeptuneCoins;
use neptune_core::rpc_server::RPCClient;
use num_traits::Zero;
use ratatui::{
Expand All @@ -33,7 +33,7 @@ use super::screen::Screen;

#[derive(Debug, Clone)]
pub struct OverviewData {
synced_balance: Option<Amount>,
synced_balance: Option<NeptuneCoins>,
confirmations: Option<BlockHeight>,
synchronization_percentage: Option<f64>,

Expand Down Expand Up @@ -93,7 +93,7 @@ impl OverviewData {
}
pub fn test() -> Self {
OverviewData {
synced_balance: Some(Amount::zero()),
synced_balance: Some(NeptuneCoins::zero()),
confirmations: Some(17.into()),
synchronization_percentage: Some(99.5),

Expand Down
7 changes: 5 additions & 2 deletions src/bin/dashboard_src/send_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use super::{
use crossterm::event::{Event, KeyCode, KeyEventKind};
use neptune_core::{
config_models::network::Network,
models::{blockchain::transaction::amount::Amount, state::wallet::address::generation_address},
models::{
blockchain::transaction::neptune_coins::NeptuneCoins,
state::wallet::address::generation_address,
},
rpc_server::RPCClient,
};

Expand Down Expand Up @@ -123,7 +126,7 @@ impl SendScreen {
*notice_arc.lock().await = "Validated inputs; sending ...".to_string();

// TODO: Let user specify this number
let fee = Amount::zero();
let fee = NeptuneCoins::zero();

// Allow the generation of proves to take some time...
let mut send_ctx = context::current();
Expand Down
6 changes: 3 additions & 3 deletions src/bin/neptune-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use clap_complete::{generate, Shell};

use neptune_core::config_models::data_directory::DataDirectory;
use neptune_core::config_models::network::Network;
use neptune_core::models::blockchain::transaction::amount::Amount;
use neptune_core::models::blockchain::transaction::neptune_coins::NeptuneCoins;
use neptune_core::models::state::wallet::address::generation_address;
use neptune_core::models::state::wallet::WalletSecret;
use std::io;
Expand Down Expand Up @@ -54,9 +54,9 @@ enum Command {
ip: IpAddr,
},
Send {
amount: Amount,
amount: NeptuneCoins,
address: String,
fee: Amount,
fee: NeptuneCoins,
},
PauseMiner,
RestartMiner,
Expand Down
12 changes: 6 additions & 6 deletions src/mine_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::models::blockchain::block::block_height::BlockHeight;
use crate::models::blockchain::block::mutator_set_update::*;
use crate::models::blockchain::block::*;
use crate::models::blockchain::shared::*;
use crate::models::blockchain::transaction::amount::Amount;
use crate::models::blockchain::transaction::neptune_coins::NeptuneCoins;
use crate::models::blockchain::transaction::transaction_kernel::TransactionKernel;
use crate::models::blockchain::transaction::utxo::*;
use crate::models::blockchain::transaction::validity::TransactionValidationLogic;
Expand Down Expand Up @@ -186,7 +186,7 @@ fn make_coinbase_transaction(
.iter()
.filter(|coin| coin.type_script_hash == TypeScript::native_coin().hash())
.map(|coin| {
*Amount::decode(&coin.state)
*NeptuneCoins::decode(&coin.state)
.expect("Make coinbase transaction: failed to parse coin state as amount.")
})
.sum();
Expand All @@ -209,7 +209,7 @@ fn make_coinbase_transaction(
inputs: vec![],
outputs: vec![coinbase_addition_record],
public_announcements: vec![],
fee: Amount::zero(),
fee: NeptuneCoins::zero(),
timestamp,
coinbase: Some(coinbase_amount),
mutator_set_hash: mutator_set_accumulator.hash(),
Expand Down Expand Up @@ -253,7 +253,7 @@ fn create_block_transaction(
// Build coinbase UTXO
let transaction_fees = transactions_to_include
.iter()
.fold(Amount::zero(), |acc, tx| acc + tx.kernel.fee);
.fold(NeptuneCoins::zero(), |acc, tx| acc + tx.kernel.fee);

let coinbase_recipient_spending_key = global_state
.wallet_state
Expand Down Expand Up @@ -495,7 +495,7 @@ mod mine_loop_tests {
);

// Add a transaction to the mempool
let four_neptune_coins = Amount::from(4).to_native_coins();
let four_neptune_coins = NeptuneCoins::new(4).to_native_coins();
let receiver_privacy_digest = Digest::default();
let sender_randomness = Digest::default();
let public_announcement = PublicAnnouncement::default();
Expand All @@ -513,7 +513,7 @@ mod mine_loop_tests {
public_announcement,
}),
],
1.into(),
NeptuneCoins::new(1),
)
.await
.unwrap();
Expand Down
18 changes: 9 additions & 9 deletions src/models/blockchain/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use self::mutator_set_update::MutatorSetUpdate;
use self::transfer_block::TransferBlock;
use super::transaction::transaction_kernel::TransactionKernel;
use super::transaction::utxo::Utxo;
use super::transaction::{amount::Amount, Transaction};
use super::transaction::{neptune_coins::NeptuneCoins, Transaction};
use crate::models::blockchain::shared::Hash;
use crate::models::consensus::Witness;
use crate::models::state::wallet::address::generation_address;
Expand Down Expand Up @@ -109,8 +109,8 @@ impl Block {
self.kernel.body = block.kernel.body;
}

pub fn get_mining_reward(block_height: BlockHeight) -> Amount {
let mut reward: Amount = Amount(U32s::new([100, 0, 0, 0]));
pub fn get_mining_reward(block_height: BlockHeight) -> NeptuneCoins {
let mut reward: NeptuneCoins = NeptuneCoins::new(100);
let generation = block_height.get_generation();
for _ in 0..generation {
reward.div_two()
Expand All @@ -136,7 +136,7 @@ impl Block {
kernel: TransactionKernel {
inputs: vec![],
outputs: vec![],
fee: 0u32.into(),
fee: NeptuneCoins::new(0),
timestamp,
public_announcements: vec![],
coinbase: Some(total_premine_amount),
Expand Down Expand Up @@ -191,12 +191,12 @@ impl Block {
Self::new(header, body, None)
}

pub fn premine_distribution() -> Vec<(generation_address::ReceivingAddress, Amount)> {
pub fn premine_distribution() -> Vec<(generation_address::ReceivingAddress, NeptuneCoins)> {
// The premine UTXOs can be hardcoded here.
let authority_wallet = WalletSecret::devnet_wallet();
let authority_receiving_address =
authority_wallet.nth_generation_spending_key(0).to_address();
vec![(authority_receiving_address, 20000.into())]
vec![(authority_receiving_address, NeptuneCoins::new(20000))]
}

pub fn new(header: BlockHeader, body: BlockBody, proof: Option<Proof>) -> Self {
Expand Down Expand Up @@ -389,7 +389,7 @@ impl Block {

// 1.f) Verify that the coinbase claimed by the transaction does not exceed
// the allowed coinbase based on block height, epoch, etc., and fee
let miner_reward: Amount = Self::get_mining_reward(block_copy.kernel.header.height)
let miner_reward: NeptuneCoins = Self::get_mining_reward(block_copy.kernel.header.height)
+ self.kernel.body.transaction.kernel.fee;
if let Some(claimed_reward) = block_copy.kernel.body.transaction.kernel.coinbase {
if claimed_reward > miner_reward {
Expand Down Expand Up @@ -538,7 +538,7 @@ mod block_tests {
);

// create a new transaction, merge it into block 1 and check that block 1 is still valid
let new_utxo = Utxo::new_native_coin(other_address.lock_script(), 10.into());
let new_utxo = Utxo::new_native_coin(other_address.lock_script(), NeptuneCoins::new(10));
let reciever_data = UtxoReceiverData {
public_announcement: PublicAnnouncement::default(),
receiver_privacy_digest: other_address.privacy_digest,
Expand All @@ -548,7 +548,7 @@ mod block_tests {
let new_tx = global_state_lock
.lock_guard_mut()
.await
.create_transaction(vec![reciever_data], 1.into())
.create_transaction(vec![reciever_data], NeptuneCoins::new(1))
.await
.unwrap();
assert!(new_tx.is_valid(), "Created tx must be valid");
Expand Down
Loading

0 comments on commit 99e8da6

Please sign in to comment.