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

feat: symmetric key notifications #169

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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ default-run = "neptune-core"
publish = false

[dependencies]
aead = "0.5"
aead = { version = "0.5", features = ["std"] }
aes-gcm = "0.10"
anyhow = "1.0"
arbitrary = { version = "1.3", features = ["derive"] }
Expand Down
10 changes: 8 additions & 2 deletions src/bin/dashboard_src/send_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crossterm::event::{Event, KeyCode, KeyEventKind};
use neptune_core::{
config_models::network::Network,
models::{
blockchain::type_scripts::neptune_coins::NeptuneCoins,
blockchain::{transaction::UtxoNotifyMethod, type_scripts::neptune_coins::NeptuneCoins},
state::wallet::address::ReceivingAddressType,
},
rpc_server::RPCClient,
Expand Down Expand Up @@ -133,7 +133,13 @@ impl SendScreen {
const SEND_DEADLINE_IN_SECONDS: u64 = 40;
send_ctx.deadline = SystemTime::now() + Duration::from_secs(SEND_DEADLINE_IN_SECONDS);
let send_result = rpc_client
.send(send_ctx, valid_amount, valid_address, fee)
.send(
send_ctx,
valid_amount,
valid_address,
UtxoNotifyMethod::OnChainSymmetricKey,
fee,
)
.await
.unwrap();

Expand Down
20 changes: 18 additions & 2 deletions src/bin/neptune-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,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::block::block_selector::BlockSelector;
use neptune_core::models::blockchain::transaction::UtxoNotifyMethod;
use neptune_core::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use neptune_core::models::state::wallet::address::ReceivingAddressType;
use neptune_core::models::state::wallet::coin_with_possible_timelock::CoinWithPossibleTimeLock;
Expand Down Expand Up @@ -452,7 +453,15 @@ async fn main() -> Result<()> {
// Parse on client
let receiving_address = ReceivingAddressType::from_bech32m(&address, args.network)?;

client.send(ctx, amount, receiving_address, fee).await?;
client
.send(
ctx,
amount,
receiving_address,
UtxoNotifyMethod::OnChainSymmetricKey,
fee,
)
.await?;
println!("Send completed.");
}
Command::SendToMany { outputs, fee } => {
Expand All @@ -461,7 +470,14 @@ async fn main() -> Result<()> {
.map(|o| o.to_receiving_address_amount_tuple(args.network))
.collect::<Result<Vec<_>>>()?;

client.send_to_many(ctx, parsed_outputs, fee).await?;
client
.send_to_many(
ctx,
parsed_outputs,
UtxoNotifyMethod::OnChainSymmetricKey,
fee,
)
.await?;
println!("Send completed.");
}
Command::PauseMiner => {
Expand Down
36 changes: 36 additions & 0 deletions src/models/blockchain/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::models::blockchain::block::mutator_set_update::MutatorSetUpdate;
use crate::models::consensus::mast_hash::MastHash;
use crate::models::consensus::{ValidityTree, WitnessType};
use crate::models::state::wallet::utxo_notification_pool::ExpectedUtxo;
use crate::prelude::{triton_vm, twenty_first};

pub mod primitive_witness;
Expand All @@ -27,6 +28,7 @@ use triton_vm::prelude::NonDeterminism;
use twenty_first::math::b_field_element::BFieldElement;
use twenty_first::math::bfield_codec::BFieldCodec;
use twenty_first::util_types::algebraic_hasher::AlgebraicHasher;
use utxo::Utxo;

use self::primitive_witness::PrimitiveWitness;
use self::transaction_kernel::TransactionKernel;
Expand All @@ -45,7 +47,41 @@ pub use transaction_output::TxOutput;
pub use transaction_output::TxOutputList;
pub use transaction_output::UtxoNotification;
pub use transaction_output::UtxoNotifyMethod;
pub use transaction_output::UtxoNotifyMethodSpecifier;

/// represents a utxo and secrets necessary for recipient to claim it.
///
/// these are built from one of:
/// onchain symmetric-key public announcements
/// onchain asymmetric-key public announcements
/// offchain expected-utxos
///
/// See [PublicAnnouncement], [UtxoNotification], [ExpectedUtxo]
#[derive(Clone, Debug)]
pub struct AnnouncedUtxo {
pub addition_record: AdditionRecord,
pub utxo: Utxo,
pub sender_randomness: Digest,
pub receiver_preimage: Digest,
}

impl From<&ExpectedUtxo> for AnnouncedUtxo {
fn from(eu: &ExpectedUtxo) -> Self {
Self {
addition_record: eu.addition_record,
utxo: eu.utxo.clone(),
sender_randomness: eu.sender_randomness,
receiver_preimage: eu.receiver_preimage,
}
}
}

/// represents arbitrary data that can be stored in a transaction on the public blockchain
///
/// initially these are used for transmitting encrypted secrets necessary
/// for a utxo recipient to identify and claim it.
///
/// See [Transaction], [UtxoNotification]
#[derive(
Clone, Debug, Serialize, Deserialize, PartialEq, Eq, GetSize, BFieldCodec, Default, Arbitrary,
)]
Expand Down
95 changes: 93 additions & 2 deletions src/models/blockchain/transaction/transaction_output.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use super::utxo::LockScript;
use crate::models::blockchain::shared::Hash;
use crate::models::blockchain::transaction::utxo::Utxo;
use crate::models::blockchain::transaction::PublicAnnouncement;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::state::wallet::address::symmetric_key::SymmetricKey;
use crate::models::state::wallet::address::ReceivingAddressType;
use crate::models::state::wallet::address::SpendingKeyType;
use crate::models::state::wallet::utxo_notification_pool::ExpectedUtxo;
use crate::models::state::wallet::utxo_notification_pool::UtxoNotifier;
use crate::models::state::wallet::wallet_state::WalletState;
Expand All @@ -11,24 +14,112 @@ use crate::prelude::twenty_first::util_types::algebraic_hasher::AlgebraicHasher;
use crate::util_types::mutator_set::addition_record::AdditionRecord;
use crate::util_types::mutator_set::commit;
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
use std::ops::Deref;
use std::ops::DerefMut;

/// enumerates how a transaction recipient should be notified
/// that a Utxo exists which they can claim/spend.
///
/// see also: [UtxoNotification]
#[derive(Debug, Clone)]
/// see also: [UtxoNotifyMethodSpecifier], [UtxoNotification]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UtxoNotifyMethod {
OnChainPubKey,
OnChainSymmetricKey,
OffChain,
}

/// enumerates how a transaction recipient should be notified
/// that a Utxo exists and specifies receiver details
///
/// see also: [UtxoNotifyMethod], [UtxoNotification]
#[derive(Debug, Clone)]
pub enum UtxoNotifyMethodSpecifier {
OnChainPubKey(ReceivingAddressType),
OnChainSymmetricKey(SymmetricKey),
OffChain(SpendingKeyType),
}

impl UtxoNotifyMethodSpecifier {
/// converts [UtxoNotifyMethod] to [UtxoNotifyMethodSpecifier]
///
/// This method derives the next key of appropriate type. This requires
/// modifying wallet state in order for the wallet to track the latest key.
pub fn from_utxo_notify_method_and_wallet(
utxo_notify_method: UtxoNotifyMethod,
wallet_state: &mut WalletState,
) -> Self {
let ws = &mut wallet_state.wallet_secret;

match utxo_notify_method {
UtxoNotifyMethod::OnChainPubKey => UtxoNotifyMethodSpecifier::OnChainPubKey(
ws.next_unused_generation_spending_key().to_address().into(),
),
UtxoNotifyMethod::OnChainSymmetricKey => {
UtxoNotifyMethodSpecifier::OnChainSymmetricKey(ws.next_unused_symmetric_key())
}
UtxoNotifyMethod::OffChain => {
UtxoNotifyMethodSpecifier::OffChain(ws.next_unused_generation_spending_key().into())
}
}
}

/// returns [LockScript] of the underlying key or address
pub fn lock_script(&self) -> LockScript {
match self {
Self::OnChainPubKey(addr) => addr.lock_script(),
Self::OnChainSymmetricKey(key) => key.lock_script(),
Self::OffChain(key) => key.to_address().lock_script(),
}
}

/// returns privacy digest of the underlying key or address
pub fn privacy_digest(&self) -> Digest {
match self {
Self::OnChainPubKey(addr) => addr.privacy_digest(),
Self::OnChainSymmetricKey(key) => key.privacy_digest(),
Self::OffChain(key) => key.to_address().privacy_digest(),
}
}

/// generates a [TxOutput] for the underlying key or address
pub fn tx_output(&self, utxo: Utxo, sender_randomness: Digest) -> Result<TxOutput> {
let tx_output = match self {
Self::OnChainPubKey(change_address) => {
let public_announcement =
change_address.generate_public_announcement(&utxo, sender_randomness)?;
TxOutput::onchain_pubkey(
utxo,
sender_randomness,
change_address.privacy_digest(),
public_announcement,
)
}
Self::OnChainSymmetricKey(symmetric_key) => {
let public_announcement =
symmetric_key.generate_public_announcement(&utxo, sender_randomness)?;
TxOutput::onchain_symkey(
utxo,
sender_randomness,
symmetric_key.privacy_digest(),
public_announcement,
)
}
Self::OffChain(spending_key) => {
TxOutput::offchain(utxo, sender_randomness, spending_key.privacy_preimage())
}
};
Ok(tx_output)
}
}

/// enumerates transaction notifications.
///
/// This mirrors variants in [`UtxoNotifyMethod`] but also holds notification
/// data.
///
/// see also: [UtxoNotifyMethod], [UtxoNotifyMethodSpecifier]
#[derive(Debug, Clone)]
pub enum UtxoNotification {
OnChainPubKey(PublicAnnouncement),
Expand Down
42 changes: 12 additions & 30 deletions src/models/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use self::blockchain_state::BlockchainState;
use self::mempool::Mempool;
use self::networking_state::NetworkingState;
use self::wallet::address::ReceivingAddressType;
use self::wallet::address::SpendingKeyType;
use self::wallet::utxo_notification_pool::UtxoNotifier;
use self::wallet::wallet_state::WalletState;
use self::wallet::wallet_status::WalletStatus;
Expand All @@ -16,7 +15,7 @@ use super::blockchain::transaction::Transaction;
use super::blockchain::transaction::TxInputList;
use super::blockchain::transaction::TxOutput;
use super::blockchain::transaction::TxOutputList;
use super::blockchain::transaction::UtxoNotifyMethod;
use super::blockchain::transaction::UtxoNotifyMethodSpecifier;
use super::blockchain::type_scripts::native_currency::NativeCurrency;
use super::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use super::blockchain::type_scripts::time_lock::TimeLock;
Expand Down Expand Up @@ -526,8 +525,7 @@ impl GlobalState {
pub async fn create_transaction(
&self,
tx_outputs: &mut TxOutputList,
change_spending_key: SpendingKeyType,
change_utxo_notify_method: UtxoNotifyMethod,
change_utxo_notify_method: UtxoNotifyMethodSpecifier,
fee: NeptuneCoins,
timestamp: Timestamp,
) -> Result<Transaction> {
Expand All @@ -546,36 +544,21 @@ impl GlobalState {

if total_spend < input_amount {
let block_height = self.chain.light_state().header().height;
let change_address = change_spending_key.to_address();

let amount = input_amount.checked_sub(&total_spend).ok_or_else(|| {
anyhow::anyhow!("underflow subtracting total_spend from input_amount")
})?;

let utxo = Utxo::new_native_coin(change_address.lock_script(), amount);
let tx_output = {
let change = change_utxo_notify_method;

let sender_randomness = self
.wallet_state
.wallet_secret
.generate_sender_randomness(block_height, change_address.privacy_digest());

let tx_output = match change_utxo_notify_method {
UtxoNotifyMethod::OnChainPubKey => {
let public_announcement =
change_address.generate_public_announcement(&utxo, sender_randomness)?;
TxOutput::onchain_pubkey(
utxo,
sender_randomness,
change_address.privacy_digest(),
public_announcement,
)
}
UtxoNotifyMethod::OnChainSymmetricKey => unimplemented!(),
UtxoNotifyMethod::OffChain => TxOutput::offchain(
utxo,
sender_randomness,
change_spending_key.privacy_preimage(),
),
let utxo = Utxo::new_native_coin(change.lock_script(), amount);
let sender_randomness = self
.wallet_state
.wallet_secret
.generate_sender_randomness(block_height, change.privacy_digest());

change.tx_output(utxo, sender_randomness)?
};

tx_outputs.push(tx_output);
Expand Down Expand Up @@ -654,8 +637,7 @@ impl GlobalState {
let transaction = self
.create_transaction(
&mut tx_outputs,
change_spending_key.into(),
UtxoNotifyMethod::OffChain,
UtxoNotifyMethodSpecifier::OffChain(change_spending_key.into()),
fee,
timestamp,
)
Expand Down
1 change: 1 addition & 0 deletions src/models/state/wallet/address.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod address_type;
pub mod generation_address;
pub mod symmetric_key;

/// ReceivingAddressType abstracts over any address type and should be used
/// wherever possible.
Expand Down
Loading
Loading