Skip to content

Commit

Permalink
Extend transactions with memo sections
Browse files Browse the repository at this point in the history
  • Loading branch information
sug0 committed Jan 3, 2024
1 parent 76840b5 commit b2a3789
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions core/src/proto/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::Deref;

use borsh::schema::{add_definition, Declaration, Definition};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
Expand Down Expand Up @@ -805,6 +806,47 @@ impl borsh::BorshSchema for MaspBuilder {
}
}

/// Memo field that may be populated with arbitrary data.
#[derive(
Clone,
Debug,
BorshSerialize,
BorshDeserialize,
BorshSchema,
Serialize,
Deserialize,
)]
pub struct Memo {
inner: Vec<u8>,
}

impl Memo {
/// Up to 1 KiB of data.
pub const MAX_CAPACITY: usize = 1024;

/// Build a new memo field.
pub fn new(data: &[u8]) -> Option<Self> {
(data.len() <= Self::MAX_CAPACITY).then(|| Memo {
inner: data.to_vec(),
})
}

/// Hash this memo section.
pub fn hash<'a>(&self, hasher: &'a mut Sha256) -> &'a mut Sha256 {
hasher.update(&self.inner);
hasher
}
}

impl Deref for Memo {
type Target = [u8];

#[inline]
fn deref(&self) -> &[u8] {
&self.inner
}
}

/// A section of a transaction. Carries an independent piece of information
/// necessary for the processing of a transaction.
#[derive(
Expand Down Expand Up @@ -836,6 +878,8 @@ pub enum Section {
/// A section providing the auxiliary inputs used to construct a MASP
/// transaction. Only send to wallet, never send to protocol.
MaspBuilder(MaspBuilder),
/// Memo containing arbitrary data.
Memo(Memo),
/// Wrap a header with a section for the purposes of computing hashes
Header(Header),
}
Expand All @@ -859,6 +903,7 @@ impl Section {
hasher.update(tx.txid().as_ref());
hasher
}
Self::Memo(memo) => memo.hash(hasher),
Self::Header(header) => header.hash(hasher),
}
}
Expand Down Expand Up @@ -1486,6 +1531,15 @@ impl Tx {
(self, sechash)
}

/// Add a memo section to the transaction
pub fn add_memo(
&mut self,
memo: Memo,
) -> (&mut Self, crate::types::hash::Hash) {
let sechash = self.add_section(Section::Memo(memo)).get_hash();
(self, sechash)
}

/// Add a masp tx section to the tx builder
pub fn add_masp_tx_section(
&mut self,
Expand Down

0 comments on commit b2a3789

Please sign in to comment.