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
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions components/zcash_protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[dependencies]
sapling.workspace = true

# - Logging and metrics
memuse = { workspace = true, optional = true }

Expand All @@ -31,6 +33,7 @@ document-features = { workspace = true, optional = true }
# - Encodings
core2.workspace = true
hex.workspace = true
wasabi_leb128 = "0.4"

# - Test dependencies
proptest = { workspace = true, optional = true }
Expand Down
25 changes: 23 additions & 2 deletions components/zcash_protocol/src/memo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ use core::str;
#[cfg(feature = "std")]
use std::error;

mod builder;
pub use builder::Builder;

mod structured;
pub use structured::{Payload, StructuredMemo};

/// Format a byte array as a colon-delimited hex string.
///
/// - Source: <https://github.com/tendermint/signatory>
Expand All @@ -35,13 +41,17 @@ where
/// Errors that may result from attempting to construct an invalid memo.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
InvalidEncoding,
InvalidPayload,
InvalidUtf8(core::str::Utf8Error),
TooLong(usize),
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidEncoding => write!(f, "Invalid memo encoding"),
Error::InvalidPayload => write!(f, "Invalid memo payload"),
Error::InvalidUtf8(e) => write!(f, "Invalid UTF-8: {e}"),
Error::TooLong(n) => write!(f, "Memo length {n} is larger than maximum of 512"),
}
Expand Down Expand Up @@ -136,7 +146,7 @@ impl MemoBytes {
}

/// Type-safe wrapper around String to enforce memo length requirements.
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextMemo(String);

impl From<TextMemo> for String {
Expand All @@ -162,6 +172,8 @@ pub enum Memo {
Empty,
/// A memo field containing a UTF-8 string.
Text(TextMemo),
/// A structured memo field containing one or more payloads.
Structured(StructuredMemo),
/// Some unknown memo format from ✨*the future*✨ that we can't parse.
Future(MemoBytes),
/// A memo field containing arbitrary bytes.
Expand All @@ -172,7 +184,8 @@ impl fmt::Debug for Memo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Memo::Empty => write!(f, "Memo::Empty"),
Memo::Text(memo) => write!(f, "Memo::Text(\"{}\")", memo.0),
Memo::Text(memo) => write!(f, "Memo::Text({:?})", memo),
Memo::Structured(memo) => write!(f, "Memo::Structured({:?})", memo),
Memo::Future(bytes) => write!(f, "Memo::Future({:0x})", bytes.0[0]),
Memo::Arbitrary(bytes) => {
write!(f, "Memo::Arbitrary(")?;
Expand All @@ -188,6 +201,7 @@ impl PartialEq for Memo {
match (self, rhs) {
(Memo::Empty, Memo::Empty) => true,
(Memo::Text(a), Memo::Text(b)) => a == b,
(Memo::Structured(a), Memo::Structured(b)) => a == b,
(Memo::Future(a), Memo::Future(b)) => a.0[..] == b.0[..],
(Memo::Arbitrary(a), Memo::Arbitrary(b)) => a[..] == b[..],
_ => false,
Expand Down Expand Up @@ -216,6 +230,7 @@ impl TryFrom<&MemoBytes> for Memo {
/// example, if the slice is not 512 bytes, or the encoded `Memo` is non-canonical).
fn try_from(bytes: &MemoBytes) -> Result<Self, Self::Error> {
match bytes.0[0] {
0xF5 => StructuredMemo::parse(&bytes.0[1..]).map(Memo::Structured),
0xF6 if bytes.0.iter().skip(1).all(|&b| b == 0) => Ok(Memo::Empty),
0xFF => Ok(Memo::Arbitrary(Box::new(bytes.0[1..].try_into().unwrap()))),
b if b <= 0xF4 => str::from_utf8(bytes.as_slice())
Expand Down Expand Up @@ -249,6 +264,12 @@ impl From<&Memo> for MemoBytes {
bytes[..s_bytes.len()].copy_from_slice(s_bytes);
MemoBytes(Box::new(bytes))
}
Memo::Structured(s) => {
let mut bytes = [0u8; 512];
bytes[0] = 0xF5;
s.serialize(&mut bytes[1..]);
MemoBytes(Box::new(bytes))
}
Memo::Future(memo) => memo.clone(),
Memo::Arbitrary(arb) => {
let mut bytes = [0u8; 512];
Expand Down
55 changes: 55 additions & 0 deletions components/zcash_protocol/src/memo/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//! Memo-building interface.

use alloc::string::String;
use alloc::vec;
use core::str::FromStr;

use sapling::PaymentAddress;

use super::{Error, Memo, Payload, StructuredMemo, TextMemo};

pub struct Builder {
return_address: Option<PaymentAddress>,
text: Option<String>,
}

impl Default for Builder {
fn default() -> Self {
Self::new()
}
}

impl Builder {
pub fn new() -> Self {
Builder {
return_address: None,
text: None,
}
}

pub fn return_address(&mut self, return_address: PaymentAddress) -> &mut Self {
self.return_address = Some(return_address);
self
}

pub fn text(&mut self, text: String) -> &mut Self {
self.text = Some(text);
self
}

pub fn build(&self) -> Result<Memo, Error> {
if let Some(pa) = self.return_address.as_ref() {
let mut payloads = vec![Payload::ReturnAddress(pa.clone())];

if let Some(s) = self.text.as_ref() {
payloads.push(Payload::Text(TextMemo(s.clone())));
}

StructuredMemo::new(payloads).map(Memo::Structured)
} else if let Some(s) = self.text.as_ref() {
Memo::from_str(s)
} else {
Ok(Memo::Empty)
}
}
}
Loading
Loading