diff --git a/composer/src/composer/prover/transaction.rs b/composer/src/composer/prover/transaction.rs index 3e19be3..351426f 100644 --- a/composer/src/composer/prover/transaction.rs +++ b/composer/src/composer/prover/transaction.rs @@ -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) diff --git a/composer/src/core/args.rs b/composer/src/core/args.rs index a2cc6a6..e78b5f2 100644 --- a/composer/src/core/args.rs +++ b/composer/src/core/args.rs @@ -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; @@ -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, } impl Args { @@ -124,4 +133,14 @@ impl Args { ret.into() } + + pub(crate) fn announcement(&self) -> Option { + 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)) + }) + } } diff --git a/standards/Cargo.toml b/standards/Cargo.toml index efed333..c51a471 100644 --- a/standards/Cargo.toml +++ b/standards/Cargo.toml @@ -22,6 +22,7 @@ bincode = "1.3" thiserror = "1.0.65" num-traits = "0.2" tiny-bip39 = "1.0" +rand = "0.10" [dev-dependencies] diff --git a/standards/src/wallet/keys/mod.rs b/standards/src/wallet/keys/mod.rs index 3744973..b93cc07 100644 --- a/standards/src/wallet/keys/mod.rs +++ b/standards/src/wallet/keys/mod.rs @@ -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) { @@ -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) } } diff --git a/standards/src/wallet/notes/content.rs b/standards/src/wallet/notes/content.rs index d9a79d5..33f3ba0 100644 --- a/standards/src/wallet/notes/content.rs +++ b/standards/src/wallet/notes/content.rs @@ -41,9 +41,38 @@ impl UtxoContent { } } +/// Text message payload. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, BFieldCodec)] +pub struct MessageContent { + pub message: Vec, +} + +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) -> Self { + let mut message = message.into().into_bytes(); + message.push(b' '); + message.extend_from_slice(&rand::random::().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) -> Self { + Self { + message: message.into().into_bytes(), + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum NoteContent { Utxo(UtxoContent), + Message(MessageContent), } impl NoteContent { @@ -51,6 +80,7 @@ impl NoteContent { pub fn discriminant(&self) -> u64 { match self { Self::Utxo(_) => UtxoContent::DISCRIMINANT, + Self::Message(_) => MessageContent::DISCRIMINANT, } } } @@ -61,12 +91,19 @@ impl From for NoteContent { } } +impl From for NoteContent { + fn from(message: MessageContent) -> Self { + Self::Message(message) + } +} + impl BFieldCodec for NoteContent { type Error = NoteContentError; fn encode(&self) -> Vec { 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()); @@ -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)), } } @@ -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. diff --git a/wallet/core/src/transaction/builder/mod.rs b/wallet/core/src/transaction/builder/mod.rs index c1577d7..d150adc 100644 --- a/wallet/core/src/transaction/builder/mod.rs +++ b/wallet/core/src/transaction/builder/mod.rs @@ -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; @@ -35,6 +36,7 @@ pub struct TransactionBuilder { coinbase: Option, timestamp: Option, mutator_set_accumulator: Option, + announcements: Vec, } // Builder interface @@ -47,6 +49,7 @@ impl TransactionBuilder { coinbase: None, timestamp: None, mutator_set_accumulator: None, + announcements: Vec::new(), } } @@ -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) -> Self { + self.announcements = announcements; + self + } } impl TransactionBuilder { @@ -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, diff --git a/wallet/sdk/src/scanners/chain.rs b/wallet/sdk/src/scanners/chain.rs index 0d6174a..d9f1323 100644 --- a/wallet/sdk/src/scanners/chain.rs +++ b/wallet/sdk/src/scanners/chain.rs @@ -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.