Skip to content
Draft
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: 2 additions & 4 deletions src/connect_to_peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,15 +471,13 @@ mod connect_tests {
use anyhow::Result;
use tokio_test::io::Builder;
use tracing_test::traced_test;
use twenty_first::math::digest::Digest;

use crate::config_models::network::Network;
use crate::models::peer::ConnectionStatus;
use crate::models::peer::PeerInfo;
use crate::models::peer::PeerMessage;
use crate::models::peer::PeerSanctionReason;
use crate::models::peer::PeerStanding;
use crate::prelude::twenty_first;
use crate::tests::shared::get_dummy_handshake_data_for_genesis;
use crate::tests::shared::get_dummy_peer_connection_data_genesis;
use crate::tests::shared::get_dummy_socket_address;
Expand Down Expand Up @@ -650,7 +648,7 @@ mod connect_tests {
standing: i32::MIN,
latest_sanction: Some(PeerSanctionReason::InvalidBlock((
7u64.into(),
Digest::default(),
Default::default(),
))),
timestamp_of_latest_sanction: Some(SystemTime::now()),
};
Expand Down Expand Up @@ -937,7 +935,7 @@ mod connect_tests {
standing: i32::MIN,
latest_sanction: Some(PeerSanctionReason::InvalidBlock((
7u64.into(),
Digest::default(),
Default::default(),
))),
timestamp_of_latest_sanction: Some(SystemTime::now()),
};
Expand Down
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ pub mod tests;
use std::collections::HashMap;
use std::env;
use std::net::SocketAddr;
use std::str::FromStr;

use anyhow::Context;
use anyhow::Result;
use arbitrary::Arbitrary;
use chrono::DateTime;
use chrono::Local;
use chrono::NaiveDateTime;
Expand All @@ -34,12 +36,19 @@ use config_models::cli_args;
use futures::future;
use futures::Future;
use futures::StreamExt;
use get_size::GetSize;
use models::blockchain::block::Block;
use models::blockchain::shared::Hash;
use models::peer::PeerInfo;
use num_bigint::BigUint;
use prelude::tasm_lib;
use prelude::triton_vm;
use prelude::twenty_first;
use rand::distributions::Standard;
use rand::prelude::Distribution;
use rand::Rng;
use serde::Deserialize;
use serde::Serialize;
use tarpc::server;
use tarpc::server::incoming::Incoming;
use tarpc::server::Channel;
Expand Down Expand Up @@ -75,6 +84,9 @@ use crate::models::state::wallet::wallet_state::WalletState;
use crate::models::state::wallet::WalletSecret;
use crate::models::state::GlobalStateLock;
use crate::rpc_server::RPC;
use crate::twenty_first::error::TryFromDigestError;
use crate::twenty_first::math::digest::Digest;
use crate::twenty_first::prelude::BFieldCodec;

/// Magic string to ensure other program is Neptune Core
pub const MAGIC_STRING_REQUEST: &[u8] = b"EDE8991A9C599BE908A759B6BF3279CD";
Expand All @@ -84,6 +96,9 @@ const MINER_CHANNEL_CAPACITY: usize = 3;
const RPC_CHANNEL_CAPACITY: usize = 1000;
const VERSION: &str = env!("CARGO_PKG_VERSION");

// a Digest new-type to represent sender-randomness, for type safety.
crate::macros::digest_newtype!(SenderRandomness);

pub async fn initialize(cli_args: cli_args::Args) -> Result<()> {
// Get data directory (wallet, block database), create one if none exists
let data_dir = DataDirectory::get(cli_args.data_dir.clone(), cli_args.network)?;
Expand Down
114 changes: 114 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,125 @@ macro_rules! duration_async_debug {
};
}

macro_rules! digest_newtype {
($target: ident) => {
#[derive(
Copy,
Debug,
Clone,
Default,
Hash,
GetSize,
PartialEq,
Eq,
Serialize,
Deserialize,
BFieldCodec,
Arbitrary,
)]
pub struct $target(Digest);
impl std::ops::Deref for $target {
type Target = Digest;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::fmt::Display for $target {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl From<Digest> for $target {
fn from(d: Digest) -> Self {
Self(d)
}
}
impl From<$target> for Digest {
fn from(sr: $target) -> Self {
*sr
}
}
impl Distribution<$target> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $target {
$target(rng.gen())
}
}

impl FromStr for $target {
type Err = TryFromDigestError;

fn from_str(string: &str) -> Result<Self, Self::Err> {
Ok(Digest::from_str(string)?.into())
}
}

impl TryFrom<&[BFieldElement]> for $target {
type Error = TryFromDigestError;

fn try_from(value: &[BFieldElement]) -> Result<Self, Self::Error> {
Ok(Digest::try_from(value)?.into())
}
}

impl TryFrom<Vec<BFieldElement>> for $target {
type Error = TryFromDigestError;

fn try_from(value: Vec<BFieldElement>) -> Result<Self, Self::Error> {
Ok(Digest::try_from(value)?.into())
}
}

impl From<$target> for Vec<BFieldElement> {
fn from(val: $target) -> Self {
val.0.into()
}
}

impl From<$target> for [u8; Digest::BYTES] {
fn from(item: $target) -> Self {
item.0.into()
}
}

impl TryFrom<[u8; Digest::BYTES]> for $target {
type Error = TryFromDigestError;

fn try_from(item: [u8; Digest::BYTES]) -> Result<Self, Self::Error> {
Ok(Self(Digest::try_from(item)?))
}
}

impl TryFrom<&[u8]> for $target {
type Error = TryFromDigestError;

fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
Ok(Self(Digest::try_from(slice)?))
}
}

impl TryFrom<BigUint> for $target {
type Error = TryFromDigestError;

fn try_from(value: BigUint) -> Result<Self, Self::Error> {
Ok(Self(Digest::try_from(value)?))
}
}

impl From<$target> for BigUint {
fn from(digest: $target) -> Self {
digest.0.into()
}
}
};
}

// These allow the macros to be used as
// use crate::macros::xxxxx;
//
// see: https://stackoverflow.com/a/67140319/10087197

#[allow(unused_imports)]
pub(crate) use digest_newtype;
#[allow(unused_imports)]
pub(crate) use duration;
#[allow(unused_imports)]
Expand Down
9 changes: 4 additions & 5 deletions src/mine_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,8 @@ fn make_coinbase_transaction(
block_height: BlockHeight,
mutator_set_accumulator: MutatorSetAccumulator,
timestamp: Timestamp,
) -> (Transaction, Digest) {
let sender_randomness: Digest =
wallet_secret.generate_sender_randomness(block_height, receiver_digest);
) -> (Transaction, crate::SenderRandomness) {
let sender_randomness = wallet_secret.generate_sender_randomness(block_height, receiver_digest);

let coinbase_amount = coinbase_utxo
.coins
Expand Down Expand Up @@ -578,8 +577,8 @@ mod mine_loop_tests {

// Add a transaction to the mempool
let four_neptune_coins = NeptuneCoins::new(4).to_native_coins();
let receiver_privacy_digest = Digest::default();
let sender_randomness = Digest::default();
let receiver_privacy_digest = Default::default();
let sender_randomness = Default::default();
let tx_output = Utxo {
coins: four_neptune_coins,
lock_script_hash: LockScript::anyone_can_spend().hash(),
Expand Down
4 changes: 2 additions & 2 deletions src/models/blockchain/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ pub enum BlockType {
// initialized digest field and the other has not.
//
// The field should not be serialized, so it has the `#[serde(skip)]` attribute.
// Upon deserialization, the field will have Digest::default() which is desired
// Upon deserialization, the field will have Default::default() which is desired
// so that the digest will be recomputed if/when hash() is called.
//
// We likewise skip the field for `BFieldCodec`, and `GetSize` because there
Expand Down Expand Up @@ -290,7 +290,7 @@ impl Block {
let utxo_digest = Hash::hash(&utxo);
// generate randomness for mutator set commitment
// Sender randomness cannot be random because there is no sender.
let bad_randomness = Digest::default();
let bad_randomness = Default::default();
let receiver_digest = receiving_address.privacy_digest();

// Add pre-mine UTXO to MutatorSet
Expand Down
5 changes: 2 additions & 3 deletions src/models/blockchain/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ use super::type_scripts::TypeScript;
pub struct AnnouncedUtxo {
pub addition_record: AdditionRecord,
pub utxo: Utxo,
pub sender_randomness: Digest,
pub sender_randomness: crate::SenderRandomness,
pub receiver_preimage: Digest,
}

Expand Down Expand Up @@ -642,7 +642,6 @@ impl Transaction {

#[cfg(test)]
mod witness_tests {
use tasm_lib::Digest;
use witness_tests::primitive_witness::SaltedUtxos;

use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
Expand All @@ -658,7 +657,7 @@ mod witness_tests {
fee: NeptuneCoins::new(0),
coinbase: None,
timestamp: Default::default(),
mutator_set_hash: Digest::default(),
mutator_set_hash: Default::default(),
};
let primitive_witness = PrimitiveWitness {
input_utxos: SaltedUtxos::empty(),
Expand Down
4 changes: 2 additions & 2 deletions src/models/blockchain/transaction/primitive_witness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,10 @@ pub(crate) fn arbitrary_primitive_witness_with(
// - salt (output)
// - aocl size
(
vec(arb::<Digest>(), num_inputs),
vec(arb::<crate::SenderRandomness>(), num_inputs),
vec(arb::<Digest>(), num_inputs),
vec(arb::<BFieldElement>(), 3),
vec(arb::<Digest>(), num_outputs),
vec(arb::<crate::SenderRandomness>(), num_outputs),
vec(arb::<Digest>(), num_outputs),
vec(arb::<BFieldElement>(), 3),
0u64..=u64::MAX,
Expand Down
10 changes: 5 additions & 5 deletions src/models/blockchain/transaction/transaction_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub enum UtxoNotification {
#[derive(Debug, Clone)]
pub struct TxOutput {
pub utxo: Utxo,
pub sender_randomness: Digest,
pub sender_randomness: crate::SenderRandomness,
pub receiver_privacy_digest: Digest,
pub utxo_notification: UtxoNotification,
}
Expand Down Expand Up @@ -142,7 +142,7 @@ impl TxOutput {
wallet_state: &WalletState,
address: &ReceivingAddress,
amount: NeptuneCoins,
sender_randomness: Digest,
sender_randomness: crate::SenderRandomness,
owned_utxo_notify_method: UtxoNotifyMethod,
) -> Result<Self> {
let onchain = || -> Result<TxOutput> {
Expand Down Expand Up @@ -180,7 +180,7 @@ impl TxOutput {
/// For normal situations, auto() should be used instead.
pub fn onchain(
utxo: Utxo,
sender_randomness: Digest,
sender_randomness: crate::SenderRandomness,
receiver_privacy_digest: Digest,
public_announcement: PublicAnnouncement,
) -> Self {
Expand All @@ -197,7 +197,7 @@ impl TxOutput {
/// For normal situations, auto() should be used instead.
pub fn offchain(
utxo: Utxo,
sender_randomness: Digest,
sender_randomness: crate::SenderRandomness,
receiver_privacy_preimage: Digest,
) -> Self {
ExpectedUtxo::new(
Expand All @@ -213,7 +213,7 @@ impl TxOutput {
#[cfg(test)]
pub fn fake_address(
utxo: Utxo,
sender_randomness: Digest,
sender_randomness: crate::SenderRandomness,
receiver_privacy_digest: Digest,
) -> Self {
use crate::models::state::wallet::address::generation_address::GenerationReceivingAddress;
Expand Down
4 changes: 2 additions & 2 deletions src/models/blockchain/transaction/validity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl TransactionValidationLogic {
ValidityTree::none(),
ValidityTree::none(),
ValidityTree::new(
ValidityAstType::Atomic(None, Claim::new(Digest::default()), WhichProgram::Merger),
ValidityAstType::Atomic(None, Claim::new(Default::default()), WhichProgram::Merger),
WitnessType::Faith,
),
)
Expand Down Expand Up @@ -155,7 +155,7 @@ impl TransactionValidationLogic {
ValidityTree::new(
ValidityAstType::Atomic(
None,
Claim::new(Digest::default()),
Claim::new(Default::default()),
WhichProgram::MutatorSetUpdate,
),
WitnessType::Faith,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ impl<'a> Arbitrary<'a> for RemovalRecordsIntegrityWitness {
let mut kernel: TransactionKernel = u.arbitrary()?;
kernel.mutator_set_hash = Hash::hash_pair(
Hash::hash_pair(aocl.bag_peaks(), swbfi.bag_peaks()),
Hash::hash_pair(swbfa_hash, Digest::default()),
Hash::hash_pair(swbfa_hash, Default::default()),
);
kernel.inputs = input_utxos
.iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl CompiledProgram for RemovalRecordsIntegrity {
),
Hash::hash_pair(
removal_record_integrity_witness.swbfa_hash,
Digest::default(),
Default::default(),
),
);
assert_eq!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use tasm_lib::InitVmState;
use triton_vm::prelude::BFieldElement;
use triton_vm::triton_asm;
use twenty_first::math::bfield_codec::BFieldCodec;
use twenty_first::math::tip5::Digest;
use twenty_first::math::tip5::DIGEST_LENGTH;
use twenty_first::util_types::algebraic_hasher::AlgebraicHasher;

Expand Down Expand Up @@ -364,7 +363,7 @@ impl Function for TransactionKernelMastHash {
// address += BFieldElement::one() + BFieldElement::new(mutator_set_hash_size as u64);

// padding
let zero = Digest::default();
let zero = Default::default();

// Merkleize
let leafs = [
Expand Down Expand Up @@ -435,6 +434,7 @@ mod tests {
use tasm_lib::traits::rust_shadow::RustShadow;
use tasm_lib::twenty_first::math::tip5::Tip5;
use twenty_first::math::bfield_codec::BFieldCodec;
use twenty_first::math::digest::Digest;
use twenty_first::util_types::algebraic_hasher::Domain;

use crate::models::consensus::mast_hash::MastHash;
Expand Down
Loading
Loading