Skip to content
Open
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
1 change: 1 addition & 0 deletions composer/src/composer/prover/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ impl TransactionProver {
let transaction = TransactionBuilder::new()
.inputs(TxInputList::empty())
.outputs(composer_outputs.clone())
.custom_announcements(self.args.announcement().into_iter().collect())
.coinbase(coinbase_amount)
.fee(guesser_fee)
.timestamp(timestamp)
Expand Down
19 changes: 19 additions & 0 deletions composer/src/core/args.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
use clap::Parser;
use num_traits::CheckedSub;
use num_traits::Zero;
use nyks_consensus::BFieldElement;
use nyks_consensus::block::MINING_REWARD_TIME_LOCK_PERIOD;
use nyks_consensus::network::Network;
use nyks_consensus::proof_abstractions::timestamp::Timestamp;
use nyks_consensus::tasm_lib::prelude::Digest;
use nyks_consensus::transaction::announcement::Announcement;
use nyks_consensus::type_scripts::native_currency_amount::NativeCurrencyAmount;
use nyks_standards::wallet::keys::address::Address;
use nyks_standards::wallet::keys::address::Recipient;
use nyks_standards::wallet::notes::content::MessageContent;
use nyks_standards::wallet::notes::note::Note;
use nyks_standards::wallet::notes::note::PublicNote;
use nyks_wallet_core::transaction::builder::output::TxOutput;
use nyks_wallet_core::transaction::builder::output::TxOutputList;
use nyks_wallet_core::transaction::utxo::notifications::UtxoNotificationMedium;
Expand All @@ -33,6 +38,10 @@ pub struct Args {
/// How much reward we leave for guessers.
#[arg(long, default_value_t = 0.5f64)]
pub guesser_fee_fraction: f64,

/// Graffiti message to publish in the block announcement.
#[arg(long, default_value = "nyks-composer")]
pub graffiti: Option<String>,
}

impl Args {
Expand Down Expand Up @@ -124,4 +133,14 @@ impl Args {

ret.into()
}

pub(crate) fn announcement(&self) -> Option<Announcement> {
self.graffiti.as_ref().map(|message| {
let message = format!("{message} {}", env!("CARGO_PKG_VERSION"));
let content = MessageContent::without_random_suffix(message);
let public_note = PublicNote::new(BFieldElement::new(0), content.into());

Announcement::from(&Note::from(public_note))
})
}
}
1 change: 1 addition & 0 deletions standards/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ bincode = "1.3"
thiserror = "1.0.65"
num-traits = "0.2"
tiny-bip39 = "1.0"
rand = "0.10"

[dev-dependencies]

Expand Down
18 changes: 14 additions & 4 deletions standards/src/wallet/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ pub(crate) fn network_hrp_char(network: Network) -> char {
}
}

/// Derive a seed and a nonce deterministically, in order to produce
/// deterministic announcements, since these are needed to be able to
/// reuse proofs for tests. These values are used in the encryption
/// step.
/// Derive a seed and nonce deterministically from note content so encrypting
/// the same content again produces the same announcement. These values are
/// used in the encryption step and allow proofs to be reused in tests.
pub(crate) fn deterministically_derive_seed_and_nonce(
content: &NoteContent,
) -> ([u8; 32], BFieldElement) {
Expand All @@ -41,6 +40,17 @@ pub(crate) fn deterministically_derive_seed_and_nonce(
let e3: [u8; 8] = e3.into();
let seed: [u8; 32] = [e0, e1, e2, e3].concat().try_into().unwrap();

(seed, e4)
}
NoteContent::Message(m) => {
let hash = Tip5::hash(&m.message);
let [e0, e1, e2, e3, e4] = hash.values();
let e0: [u8; 8] = e0.into();
let e1: [u8; 8] = e1.into();
let e2: [u8; 8] = e2.into();
let e3: [u8; 8] = e3.into();
let seed = [e0, e1, e2, e3].concat().try_into().unwrap();

(seed, e4)
}
}
Expand Down
58 changes: 58 additions & 0 deletions standards/src/wallet/notes/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,46 @@ impl UtxoContent {
}
}

/// Text message payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, BFieldCodec)]
pub struct MessageContent {
pub message: Vec<u8>,
}

impl MessageContent {
pub const DISCRIMINANT: u64 = 1;

/// Also adds an 8-byte random suffix, separated from the message by a space.
pub fn new(message: impl Into<String>) -> Self {
let mut message = message.into().into_bytes();
message.push(b' ');
message.extend_from_slice(&rand::random::<u64>().to_be_bytes());

Self { message }
}

/// Create message content without a random suffix.
/// Encrypting identical content under the same key reuses its nonce. Use only
/// for unencrypted content or when nonce uniqueness is handled elsewhere.
pub fn without_random_suffix(message: impl Into<String>) -> Self {
Self {
message: message.into().into_bytes(),
}
}
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NoteContent {
Utxo(UtxoContent),
Message(MessageContent),
}

impl NoteContent {
/// Returns the discriminant of the contained content.
pub fn discriminant(&self) -> u64 {
match self {
Self::Utxo(_) => UtxoContent::DISCRIMINANT,
Self::Message(_) => MessageContent::DISCRIMINANT,
}
}
}
Expand All @@ -61,12 +91,19 @@ impl From<UtxoContent> for NoteContent {
}
}

impl From<MessageContent> for NoteContent {
fn from(message: MessageContent) -> Self {
Self::Message(message)
}
}

impl BFieldCodec for NoteContent {
type Error = NoteContentError;

fn encode(&self) -> Vec<BFieldElement> {
let (discriminant, mut payload) = match self {
Self::Utxo(u) => (UtxoContent::DISCRIMINANT, u.encode()),
Self::Message(message) => (MessageContent::DISCRIMINANT, message.encode()),
};

let mut out = Vec::with_capacity(1 + payload.len());
Expand All @@ -87,6 +124,11 @@ impl BFieldCodec for NoteContent {
UtxoContent::decode(rest).map_err(|e| NoteContentError::Decode(e.into()))?;
Ok(Box::new(Self::Utxo(*content)))
}
d if d == MessageContent::DISCRIMINANT => {
let message =
MessageContent::decode(rest).map_err(|e| NoteContentError::Decode(e.into()))?;
Ok(Box::new(Self::Message(*message)))
}
_ => Err(NoteContentError::UnknownDiscriminant(discriminant)),
}
}
Expand Down Expand Up @@ -123,6 +165,22 @@ mod tests {
assert_eq!(decoded, note_content);
}

#[test]
fn message_content_round_trips_through_note_content() {
let message = MessageContent::new("Hello, Nyks!");
let content: NoteContent = message.clone().into();

assert_eq!(content.discriminant(), MessageContent::DISCRIMINANT);
assert_eq!(content, NoteContent::Message(message));

// Encoding prefixes the message payload with the message discriminant.
let encoded = content.encode();
assert_eq!(encoded[0], BFieldElement::new(MessageContent::DISCRIMINANT));

// Decoding the encoded content reconstructs the original value.
assert_eq!(*NoteContent::decode(&encoded).unwrap(), content);
}

#[test]
fn decode_rejects_invalid_sequences() {
// Empty sequence: no discriminant element at all.
Expand Down
15 changes: 14 additions & 1 deletion wallet/core/src/transaction/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use num_traits::Zero;

use nyks_consensus::mutator_set::mutator_set_accumulator::MutatorSetAccumulator;
use nyks_consensus::proof_abstractions::timestamp::Timestamp;
use nyks_consensus::transaction::announcement::Announcement;
use nyks_consensus::transaction::transaction_kernel::TransactionKernelProxy;
use nyks_consensus::type_scripts::native_currency_amount::NativeCurrencyAmount;
use thiserror::Error;
Expand Down Expand Up @@ -35,6 +36,7 @@ pub struct TransactionBuilder {
coinbase: Option<NativeCurrencyAmount>,
timestamp: Option<Timestamp>,
mutator_set_accumulator: Option<MutatorSetAccumulator>,
announcements: Vec<Announcement>,
}

// Builder interface
Expand All @@ -47,6 +49,7 @@ impl TransactionBuilder {
coinbase: None,
timestamp: None,
mutator_set_accumulator: None,
announcements: Vec::new(),
}
}

Expand Down Expand Up @@ -79,6 +82,12 @@ impl TransactionBuilder {
self.mutator_set_accumulator = Some(msa);
self
}

/// Add public announcements before output notification announcements.
pub fn custom_announcements(mut self, announcements: Vec<Announcement>) -> Self {
self.announcements = announcements;
self
}
}

impl TransactionBuilder {
Expand All @@ -94,7 +103,11 @@ impl TransactionBuilder {
let kernel = {
let input_records = inputs.removal_records(&msa);
let output_records = outputs.addition_records();
let announcements = outputs.announcements();
let announcements = self
.announcements
.into_iter()
.chain(outputs.announcements())
.collect();

TransactionKernelProxy {
inputs: input_records,
Expand Down
1 change: 1 addition & 0 deletions wallet/sdk/src/scanners/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ impl ChainScanner {
utxo,
sender_randomness,
}) => Some((utxo, sender_randomness, receiver_preimage)),
NoteContent::Message(_) => None,
})
// A third party can craft a note that decrypts under this key but
// whose UTXO isn't actually spendable by us.
Expand Down
Loading