Merge pull request #420 from zcash/unified-viewing-keys

`zcash_address`: Parse unified viewing keys
This commit is contained in:
Kris Nuttycombe 2021-12-07 14:15:47 -07:00 committed by GitHub
commit 6fb0fbea31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 1040 additions and 190 deletions

View File

@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc fd6f22032b9add1319ad27b183de7d522bf9dfa0d6ef56354812bce5a803c11c # shrinks to network = Main, ua = Address([Orchard([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 101, 7, 48, 33, 241, 53, 105]), P2pkh([104, 47, 211, 146, 155, 136, 129, 215, 137, 152, 117, 157, 55, 4, 199, 123, 69, 12, 133, 89]), Sapling([164, 56, 210, 240, 243, 207, 59, 213, 35, 184, 250, 69, 206, 249, 184, 252, 184, 103, 227, 207, 249, 127, 133, 218, 97, 241, 242, 12, 155, 162, 137, 100, 200, 50, 96, 79, 33, 137, 242, 172, 43, 6, 255])])

View File

@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc e104d5971b8fa530680706dab1f954d27650407285c4d78f3c8428fe20c8f008 # shrinks to network = Main, ufvk = Ufvk([Sapling([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), Orchard([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 199, 56, 71, 87, 43, 196, 81, 100, 9, 151, 208, 145, 131, 104, 86, 105, 222, 242, 35, 138, 199, 195, 23, 165, 218, 165, 79, 239, 183, 228, 111, 72, 26, 242, 158, 79, 109, 240, 47, 52, 59, 46, 164, 181, 240, 159, 234, 120, 160, 214, 6, 235, 69, 147, 88, 78, 48, 20, 53, 243, 221, 39, 208, 139, 21, 211, 238, 118, 101, 5, 77, 77, 29, 176, 157, 151, 6, 72])])

View File

@ -2,7 +2,7 @@ use std::{convert::TryInto, error::Error, fmt, str::FromStr};
use bech32::{self, FromBase32, ToBase32, Variant};
use crate::kind::unified::{private::SealedContainer, Encoding};
use crate::kind::unified::Encoding;
use crate::{kind::*, AddressKind, Network, ZcashAddress};
/// An error while attempting to parse a string as a Zcash address.
@ -20,6 +20,7 @@ impl From<unified::ParseError> for ParseError {
fn from(e: unified::ParseError) -> Self {
match e {
unified::ParseError::InvalidEncoding(_) => Self::InvalidEncoding,
unified::ParseError::UnknownPrefix(_) => Self::NotZcash,
_ => Self::Unified(e),
}
}
@ -45,50 +46,42 @@ impl FromStr for ZcashAddress {
// Remove leading and trailing whitespace, to handle copy-paste errors.
let s = s.trim();
// Most Zcash addresses use Bech32 or Bech32m, so try those first.
match bech32::decode(s) {
Ok((hrp, data, Variant::Bech32m)) => {
// If we reached this point, the encoding is supposed to be valid Bech32m.
let data =
Vec::<u8>::from_base32(&data).map_err(|_| ParseError::InvalidEncoding)?;
let net = match hrp.as_str() {
unified::address::Address::MAINNET => Network::Main,
unified::address::Address::TESTNET => Network::Test,
unified::address::Address::REGTEST => Network::Regtest,
// We will not define new Bech32m address encodings.
_ => {
return Err(ParseError::NotZcash);
}
};
return unified::Address::try_from_bytes(hrp.as_str(), &data[..])
.map(AddressKind::Unified)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
// Try decoding as a unified address
match unified::Address::decode(s) {
Ok((net, data)) => {
return Ok(ZcashAddress {
net,
kind: AddressKind::Unified(data),
});
}
Ok((hrp, data, Variant::Bech32)) => {
// If we reached this point, the encoding is supposed to be valid Bech32.
let data =
Vec::<u8>::from_base32(&data).map_err(|_| ParseError::InvalidEncoding)?;
let net = match hrp.as_str() {
sapling::MAINNET => Network::Main,
sapling::TESTNET => Network::Test,
sapling::REGTEST => Network::Regtest,
// We will not define new Bech32 address encodings.
_ => {
return Err(ParseError::NotZcash);
}
};
return data[..]
.try_into()
.map(AddressKind::Sapling)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
Err(unified::ParseError::NotUnified) => {
// allow decoding to fall through to Sapling/Transparent
}
Err(_) => (),
Err(e) => {
return Err(ParseError::from(e));
}
}
// Try decoding as a Sapling address (Bech32)
if let Ok((hrp, data, Variant::Bech32)) = bech32::decode(s) {
// If we reached this point, the encoding is supposed to be valid Bech32.
let data = Vec::<u8>::from_base32(&data).map_err(|_| ParseError::InvalidEncoding)?;
let net = match hrp.as_str() {
sapling::MAINNET => Network::Main,
sapling::TESTNET => Network::Test,
sapling::REGTEST => Network::Regtest,
// We will not define new Bech32 address encodings.
_ => {
return Err(ParseError::NotZcash);
}
};
return data[..]
.try_into()
.map(AddressKind::Sapling)
.map_err(|_| ParseError::InvalidEncoding)
.map(|kind| ZcashAddress { net, kind });
}
// The rest use Base58Check.
@ -112,15 +105,11 @@ impl FromStr for ZcashAddress {
.map(|kind| ZcashAddress { kind, net });
};
// If it's not valid Bech32 or Base58Check, it's not a Zcash address.
// If it's not valid Bech32, Bech32m, or Base58Check, it's not a Zcash address.
Err(ParseError::NotZcash)
}
}
fn encode_bech32m(hrp: &str, data: &[u8]) -> String {
bech32::encode(hrp, data.to_base32(), Variant::Bech32m).expect("hrp is invalid")
}
fn encode_bech32(hrp: &str, data: &[u8]) -> String {
bech32::encode(hrp, data.to_base32(), Variant::Bech32).expect("hrp is invalid")
}
@ -150,14 +139,7 @@ impl fmt::Display for ZcashAddress {
},
data,
),
AddressKind::Unified(data) => {
let hrp = match self.net {
Network::Main => unified::address::Address::MAINNET,
Network::Test => unified::address::Address::TESTNET,
Network::Regtest => unified::address::Address::REGTEST,
};
encode_bech32m(hrp, &data.to_bytes(hrp))
}
AddressKind::Unified(addr) => addr.encode(&self.net),
AddressKind::P2pkh(data) => encode_b58(
match self.net {
Network::Main => p2pkh::MAINNET,
@ -247,6 +229,12 @@ mod tests {
kind: AddressKind::Unified(unified::Address(vec![unified::address::Receiver::Sapling([0; 43])])),
},
);
let badencoded = "uinvalid1ck5navqwcng43gvsxwrxsplc22p7uzlcag6qfa0zh09e87efq6rq8wsnv25umqjjravw70rl994n5ueuhza2fghge5gl7zrl2qp6cwmp";
assert_eq!(
badencoded.parse::<ZcashAddress>(),
Err(ParseError::NotZcash)
);
}
#[test]

View File

@ -1,13 +1,18 @@
use bech32::{self, FromBase32, ToBase32, Variant};
use std::cmp;
use std::collections::HashSet;
use std::convert::{TryFrom, TryInto};
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use zcash_encoding::CompactSize;
use crate::Network;
pub(crate) mod address;
pub(crate) mod fvk;
pub(crate) mod ivk;
pub use address::Address;
pub use address::{Address, Receiver};
pub use fvk::{Fvk, Ufvk};
pub use ivk::{Ivk, Uivk};
const PADDING_LEN: usize = 16;
@ -96,16 +101,20 @@ impl Typecode {
/// An error while attempting to parse a string as a Zcash address.
#[derive(Debug, PartialEq)]
pub enum ParseError {
/// The unified address contains both P2PKH and P2SH items.
/// The unified container contains both P2PKH and P2SH items.
BothP2phkAndP2sh,
/// The unified address contains a duplicated typecode.
/// The unified container contains a duplicated typecode.
DuplicateTypecode(Typecode),
/// The parsed typecode exceeds the maximum allowed CompactSize value.
InvalidTypecodeValue(u64),
/// The string is an invalid encoding.
InvalidEncoding(String),
/// The unified address only contains transparent items.
/// The unified container only contains transparent items.
OnlyTransparent,
/// The string is not Bech32m encoded, and so cannot be a unified address.
NotUnified,
/// The Bech32m string has an unrecognized human-readable prefix.
UnknownPrefix(String),
}
impl fmt::Display for ParseError {
@ -116,6 +125,10 @@ impl fmt::Display for ParseError {
ParseError::InvalidTypecodeValue(v) => write!(f, "Typecode value out of range {}", v),
ParseError::InvalidEncoding(msg) => write!(f, "Invalid encoding: {}", msg),
ParseError::OnlyTransparent => write!(f, "UA only contains transparent items"),
ParseError::NotUnified => write!(f, "Address is not Bech32m encoded"),
ParseError::UnknownPrefix(s) => {
write!(f, "Unrecognized Bech32m human-readable prefix: {}", s)
}
}
}
}
@ -124,8 +137,10 @@ impl Error for ParseError {}
pub(crate) mod private {
use super::{ParseError, Typecode, PADDING_LEN};
use crate::Network;
use std::{
cmp,
collections::HashSet,
convert::{TryFrom, TryInto},
io::Write,
};
@ -140,7 +155,7 @@ pub(crate) mod private {
}
/// A Unified Container containing addresses or viewing keys.
pub trait SealedContainer: super::Container {
pub trait SealedContainer: super::Container + std::marker::Sized {
const MAINNET: &'static str;
const TESTNET: &'static str;
const REGTEST: &'static str;
@ -150,21 +165,41 @@ pub(crate) mod private {
/// general invariants that apply to all unified containers.
fn from_inner(items: Vec<Self::Item>) -> Self;
fn network_hrp(network: &Network) -> &'static str {
match network {
Network::Main => Self::MAINNET,
Network::Test => Self::TESTNET,
Network::Regtest => Self::REGTEST,
}
}
fn hrp_network(hrp: &str) -> Option<Network> {
if hrp == Self::MAINNET {
Some(Network::Main)
} else if hrp == Self::TESTNET {
Some(Network::Test)
} else if hrp == Self::REGTEST {
Some(Network::Regtest)
} else {
None
}
}
fn write_raw_encoding<W: Write>(&self, mut writer: W) {
for item in &self.items() {
let addr = item.data();
for item in self.items_as_parsed() {
let data = item.data();
CompactSize::write(
&mut writer,
<u32>::from(item.typecode()).try_into().unwrap(),
)
.unwrap();
CompactSize::write(&mut writer, addr.len()).unwrap();
writer.write_all(addr).unwrap();
CompactSize::write(&mut writer, data.len()).unwrap();
writer.write_all(data).unwrap();
}
}
/// Returns the jumbled padded raw encoding of this Unified Address or viewing key.
fn to_bytes(&self, hrp: &str) -> Vec<u8> {
fn to_jumbled_bytes(&self, hrp: &str) -> Vec<u8> {
assert!(hrp.len() <= PADDING_LEN);
let mut writer = std::io::Cursor::new(Vec::new());
@ -174,103 +209,174 @@ pub(crate) mod private {
padding[0..hrp.len()].copy_from_slice(hrp.as_bytes());
writer.write_all(&padding).unwrap();
f4jumble::f4jumble(&writer.into_inner()).unwrap()
let padded = writer.into_inner();
f4jumble::f4jumble(&padded).unwrap_or_else(|| panic!("f4jumble failed on {:?}", padded))
}
/// Parse the items of the unified container.
fn parse_items(hrp: &str, buf: &[u8]) -> Result<Vec<Self::Item>, ParseError> {
fn read_receiver<R: SealedItem>(
mut cursor: &mut std::io::Cursor<&[u8]>,
) -> Result<R, ParseError> {
let typecode = CompactSize::read(&mut cursor)
.map(|v| u32::try_from(v).expect("CompactSize::read enforces MAX_SIZE limit"))
.map_err(|e| {
ParseError::InvalidEncoding(format!(
"Failed to deserialize CompactSize-encoded typecode {}",
e
))
})?;
let length = CompactSize::read(&mut cursor).map_err(|e| {
ParseError::InvalidEncoding(format!(
"Failed to deserialize CompactSize-encoded length {}",
e
))
})?;
let addr_end = cursor.position().checked_add(length).ok_or_else(|| {
ParseError::InvalidEncoding(format!(
"Length value {} caused an overflow error",
length
))
})?;
let buf = cursor.get_ref();
if (buf.len() as u64) < addr_end {
return Err(ParseError::InvalidEncoding(format!(
"Truncated: unable to read {} bytes of item data",
length
)));
}
let result = R::try_from((
typecode,
&buf[cursor.position() as usize..addr_end as usize],
));
cursor.set_position(addr_end);
result
}
let encoded = f4jumble::f4jumble_inv(buf).ok_or_else(|| {
ParseError::InvalidEncoding("F4Jumble decoding failed".to_owned())
})?;
// Validate and strip trailing padding bytes.
if hrp.len() > 16 {
return Err(ParseError::InvalidEncoding(
"Invalid human-readable part".to_owned(),
));
}
let mut expected_padding = [0; PADDING_LEN];
expected_padding[0..hrp.len()].copy_from_slice(hrp.as_bytes());
let encoded = match encoded.split_at(encoded.len() - PADDING_LEN) {
(encoded, tail) if tail == expected_padding => Ok(encoded),
_ => Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned(),
)),
}?;
let mut cursor = std::io::Cursor::new(encoded);
let mut result = vec![];
while cursor.position() < encoded.len().try_into().unwrap() {
result.push(read_receiver(&mut cursor)?);
}
assert_eq!(cursor.position(), encoded.len().try_into().unwrap());
Ok(result)
}
/// A private function that constructs a unified container with the
/// items in their given order.
fn try_from_items_internal(items: Vec<Self::Item>) -> Result<Self, ParseError> {
let mut typecodes = HashSet::with_capacity(items.len());
for item in &items {
let t = item.typecode();
if typecodes.contains(&t) {
return Err(ParseError::DuplicateTypecode(t));
} else if (t == Typecode::P2pkh && typecodes.contains(&Typecode::P2sh))
|| (t == Typecode::P2sh && typecodes.contains(&Typecode::P2pkh))
{
return Err(ParseError::BothP2phkAndP2sh);
} else {
typecodes.insert(t);
}
}
if typecodes.iter().all(|t| t.is_transparent()) {
Err(ParseError::OnlyTransparent)
} else {
// All checks pass!
Ok(Self::from_inner(items))
}
}
fn parse_internal(hrp: &str, buf: &[u8]) -> Result<Self, ParseError> {
Self::parse_items(hrp, buf).and_then(Self::try_from_items_internal)
}
}
}
use private::SealedItem;
/// Trait providing common encoding logic for Unified containers.
pub trait Encoding: private::SealedContainer + std::marker::Sized {
fn try_from_bytes(hrp: &str, buf: &[u8]) -> Result<Self, ParseError> {
fn read_receiver<R: SealedItem>(
mut cursor: &mut std::io::Cursor<&[u8]>,
) -> Result<R, ParseError> {
let typecode = CompactSize::read(&mut cursor)
.map(|v| u32::try_from(v).expect("CompactSize::read enforces MAX_SIZE limit"))
.map_err(|e| {
ParseError::InvalidEncoding(format!(
"Failed to deserialize CompactSize-encoded typecode {}",
e
))
})?;
let length = CompactSize::read(&mut cursor).map_err(|e| {
ParseError::InvalidEncoding(format!(
"Failed to deserialize CompactSize-encoded length {}",
e
))
})?;
let addr_end = cursor.position().checked_add(length).ok_or_else(|| {
ParseError::InvalidEncoding(format!(
"Length value {} caused an overflow error",
length
))
})?;
let buf = cursor.get_ref();
if (buf.len() as u64) < addr_end {
return Err(ParseError::InvalidEncoding(format!(
"Truncated: unable to read {} bytes of address data",
length
)));
}
let result = R::try_from((
typecode,
&buf[cursor.position() as usize..addr_end as usize],
));
cursor.set_position(addr_end);
result
}
let encoded = f4jumble::f4jumble_inv(buf)
.ok_or_else(|| ParseError::InvalidEncoding("F4Jumble decoding failed".to_owned()))?;
// Validate and strip trailing padding bytes.
if hrp.len() > 16 {
return Err(ParseError::InvalidEncoding(
"Invalid human-readable part".to_owned(),
));
}
let mut expected_padding = [0; PADDING_LEN];
expected_padding[0..hrp.len()].copy_from_slice(hrp.as_bytes());
let encoded = match encoded.split_at(encoded.len() - PADDING_LEN) {
(encoded, tail) if tail == expected_padding => Ok(encoded),
_ => Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned(),
)),
}?;
let mut cursor = std::io::Cursor::new(encoded);
let mut result = vec![];
while cursor.position() < encoded.len().try_into().unwrap() {
result.push(read_receiver(&mut cursor)?);
}
assert_eq!(cursor.position(), encoded.len().try_into().unwrap());
Self::try_from_items(result)
/// Trait providing common encoding and decoding logic for Unified containers.
pub trait Encoding: private::SealedContainer {
/// Constructs a value of a unified container type from a vector
/// of container items, sorted according to typecode as specified
/// in ZIP 316.
///
/// This function will return an error in the case that the following ZIP 316
/// invariants concerning the composition of a unified container are
/// violated:
/// * the item list may not contain two items having the same typecode
/// * the item list may not contain only a single transparent item
fn try_from_items(mut items: Vec<Self::Item>) -> Result<Self, ParseError> {
items.sort_unstable_by_key(|i| i.typecode());
Self::try_from_items_internal(items)
}
fn try_from_items(items: Vec<Self::Item>) -> Result<Self, ParseError> {
let mut typecodes = HashSet::with_capacity(items.len());
for item in &items {
let t = item.typecode();
if typecodes.contains(&t) {
return Err(ParseError::DuplicateTypecode(t));
} else if (t == Typecode::P2pkh && typecodes.contains(&Typecode::P2sh))
|| (t == Typecode::P2sh && typecodes.contains(&Typecode::P2pkh))
{
return Err(ParseError::BothP2phkAndP2sh);
} else {
typecodes.insert(t);
}
}
/// Constructs a value of a unified container type from a vector
/// of container items, preserving the order of the provided vector
/// in the serialized form, potentially contravening the ordering
/// recommended by ZIP 316.
///
/// This function will return an error in the case that the following ZIP 316
/// invariants concerning the composition of a unified container are
/// violated:
/// * the item list may not contain two items having the same typecode
/// * the item list may not contain only a single transparent item
fn try_from_items_preserving_order(items: Vec<Self::Item>) -> Result<Self, ParseError> {
Self::try_from_items_internal(items)
}
if typecodes.iter().all(|t| t.is_transparent()) {
Err(ParseError::OnlyTransparent)
/// Decodes a unified container from its string representation, preserving
/// the order of its components so that it correctly obeys round-trip
/// serialization invariants.
fn decode(s: &str) -> Result<(Network, Self), ParseError> {
if let Ok((hrp, data, Variant::Bech32m)) = bech32::decode(s) {
let hrp = hrp.as_str();
// validate that the HRP corresponds to a known network.
let net =
Self::hrp_network(hrp).ok_or_else(|| ParseError::UnknownPrefix(hrp.to_string()))?;
let data = Vec::<u8>::from_base32(&data)
.map_err(|e| ParseError::InvalidEncoding(e.to_string()))?;
Self::parse_internal(hrp, &data[..]).map(|value| (net, value))
} else {
// All checks pass!
Ok(Self::from_inner(items))
Err(ParseError::NotUnified)
}
}
/// Encodes the contents of the unified container to its string representation
/// using the correct constants for the specified network, preserving the
/// ordering of the contained items such that it correctly obeys round-trip
/// serialization invariants.
fn encode(&self, network: &Network) -> String {
let hrp = Self::network_hrp(network);
bech32::encode(
hrp,
self.to_jumbled_bytes(hrp).to_base32(),
Variant::Bech32m,
)
.expect("hrp is invalid")
}
}
/// Trait for for Unified containers, that exposes the items within them.

View File

@ -113,11 +113,18 @@ pub(crate) mod test_vectors;
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use zcash_encoding::MAX_COMPACT_SIZE;
use crate::{
kind::unified::{private::SealedContainer, Container, Encoding},
Network,
};
use crate::kind::unified::{private::SealedContainer, Container, Encoding};
use proptest::{
array::{uniform11, uniform20, uniform32},
collection::vec,
prelude::*,
sample::select,
};
use super::{Address, ParseError, Receiver, Typecode};
@ -131,40 +138,65 @@ mod tests {
}
}
fn arb_shielded_receiver() -> BoxedStrategy<Receiver> {
prop_oneof![
uniform43().prop_map(Receiver::Sapling),
uniform43().prop_map(Receiver::Orchard),
]
.boxed()
fn arb_transparent_typecode() -> impl Strategy<Value = Typecode> {
select(vec![Typecode::P2pkh, Typecode::P2sh])
}
fn arb_transparent_receiver() -> BoxedStrategy<Receiver> {
fn arb_shielded_typecode() -> impl Strategy<Value = Typecode> {
prop_oneof![
uniform20(0u8..).prop_map(Receiver::P2pkh),
uniform20(0u8..).prop_map(Receiver::P2sh),
Just(Typecode::Sapling),
Just(Typecode::Orchard),
((<u32>::from(Typecode::Orchard) + 1)..MAX_COMPACT_SIZE).prop_map(Typecode::Unknown)
]
.boxed()
}
prop_compose! {
fn arb_unified_address()(
shielded in prop::collection::hash_set(arb_shielded_receiver(), 1..2),
transparent in prop::option::of(arb_transparent_receiver()),
) -> Address {
Address(shielded.into_iter().chain(transparent).collect())
}
/// A strategy to generate an arbitrary valid set of typecodes without
/// duplication and containing only one of P2sh and P2pkh transparent
/// typecodes.
fn arb_typecodes() -> impl Strategy<Value = Vec<Typecode>> {
prop::option::of(arb_transparent_typecode())
.prop_flat_map(|transparent| {
prop::collection::hash_set(arb_shielded_typecode(), 1..4)
.prop_map(move |xs| xs.into_iter().chain(transparent).collect())
.boxed()
})
.prop_shuffle()
}
fn arb_unified_address_for_typecodes(
typecodes: Vec<Typecode>,
) -> impl Strategy<Value = Vec<Receiver>> {
typecodes
.into_iter()
.map(|tc| match tc {
Typecode::P2pkh => uniform20(0u8..).prop_map(Receiver::P2pkh).boxed(),
Typecode::P2sh => uniform20(0u8..).prop_map(Receiver::P2sh).boxed(),
Typecode::Sapling => uniform43().prop_map(Receiver::Sapling).boxed(),
Typecode::Orchard => uniform43().prop_map(Receiver::Orchard).boxed(),
Typecode::Unknown(typecode) => vec(any::<u8>(), 32..256)
.prop_map(move |data| Receiver::Unknown { typecode, data })
.boxed(),
})
.collect::<Vec<_>>()
}
fn arb_unified_address() -> impl Strategy<Value = Address> {
arb_typecodes()
.prop_flat_map(arb_unified_address_for_typecodes)
.prop_map(Address)
}
proptest! {
#[test]
fn ua_roundtrip(
hrp in prop_oneof![Address::MAINNET, Address::TESTNET, Address::REGTEST],
network in select(vec![Network::Main, Network::Test, Network::Regtest]),
ua in arb_unified_address(),
) {
let bytes = ua.to_bytes(&hrp);
let decoded = Address::try_from_bytes(hrp.as_str(), &bytes[..]);
prop_assert_eq!(decoded, Ok(ua));
let encoded = ua.encode(&network);
let decoded = Address::decode(&encoded);
prop_assert_eq!(&decoded, &Ok((network, ua)));
let reencoded = decoded.unwrap().1.encode(&network);
prop_assert_eq!(reencoded, encoded);
}
}
@ -172,7 +204,7 @@ mod tests {
fn padding() {
// The test cases below use `Address(vec![Receiver::Orchard([1; 43])])` as base.
// Invalid padding ([0xff; 16] instead of [b'u', 0x00, 0x00, 0x00...])
// Invalid padding ([0xff; 16] instead of [0x75, 0x00, 0x00, 0x00...])
let invalid_padding = [
0xe6, 0x59, 0xd1, 0xed, 0xf7, 0x4b, 0xe3, 0x5e, 0x5a, 0x54, 0x0e, 0x41, 0x5d, 0x2f,
0x0c, 0x0d, 0x33, 0x42, 0xbd, 0xbe, 0x9f, 0x82, 0x62, 0x01, 0xc1, 0x1b, 0xd4, 0x1e,
@ -181,7 +213,7 @@ mod tests {
0x7b, 0x28, 0x69, 0xc9, 0x84,
];
assert_eq!(
Address::try_from_bytes(Address::MAINNET, &invalid_padding[..]),
Address::parse_internal(Address::MAINNET, &invalid_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
@ -196,7 +228,7 @@ mod tests {
0x4b, 0x31, 0xee, 0x5a,
];
assert_eq!(
Address::try_from_bytes(Address::MAINNET, &truncated_padding[..]),
Address::parse_internal(Address::MAINNET, &truncated_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
@ -221,7 +253,7 @@ mod tests {
0xc6, 0x5e, 0x68, 0xa2, 0x78, 0x6c, 0x9e,
];
assert_matches!(
Address::try_from_bytes(Address::MAINNET, &truncated_sapling_data[..]),
Address::parse_internal(Address::MAINNET, &truncated_sapling_data[..]),
Err(ParseError::InvalidEncoding(_))
);
@ -234,29 +266,32 @@ mod tests {
0xe6, 0x70, 0x36, 0x5b, 0x7b, 0x9e,
];
assert_matches!(
Address::try_from_bytes(Address::MAINNET, &truncated_after_sapling_typecode[..]),
Address::parse_internal(Address::MAINNET, &truncated_after_sapling_typecode[..]),
Err(ParseError::InvalidEncoding(_))
);
}
#[test]
fn duplicate_typecode() {
// Construct and serialize an invalid UA.
// Construct and serialize an invalid UA. This must be done using private
// methods, as the public API does not permit construction of such invalid values.
let ua = Address(vec![Receiver::Sapling([1; 43]), Receiver::Sapling([2; 43])]);
let encoded = ua.to_bytes(Address::MAINNET);
let encoded = ua.to_jumbled_bytes(Address::MAINNET);
assert_eq!(
Address::try_from_bytes(Address::MAINNET, &encoded[..]),
Address::parse_internal(Address::MAINNET, &encoded[..]),
Err(ParseError::DuplicateTypecode(Typecode::Sapling))
);
}
#[test]
fn p2pkh_and_p2sh() {
// Construct and serialize an invalid UA.
// Construct and serialize an invalid UA. This must be done using private
// methods, as the public API does not permit construction of such invalid values.
let ua = Address(vec![Receiver::P2pkh([0; 20]), Receiver::P2sh([0; 20])]);
let encoded = ua.to_bytes(Address::MAINNET);
let encoded = ua.to_jumbled_bytes(Address::MAINNET);
// ensure that decoding catches the error
assert_eq!(
Address::try_from_bytes(Address::MAINNET, &encoded[..]),
Address::parse_internal(Address::MAINNET, &encoded[..]),
Err(ParseError::BothP2phkAndP2sh)
);
}
@ -275,7 +310,7 @@ mod tests {
// with only one of them we don't have sufficient data for F4Jumble (so we hit a
// different error).
assert_matches!(
Address::try_from_bytes(Address::MAINNET, &encoded[..]),
Address::parse_internal(Address::MAINNET, &encoded[..]),
Err(ParseError::InvalidEncoding(_))
);
}

View File

@ -0,0 +1,362 @@
use std::cmp;
use std::convert::{TryFrom, TryInto};
use super::{
private::{SealedContainer, SealedItem},
Container, Encoding, ParseError, Typecode,
};
/// The set of known FVKs for Unified FVKs.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Fvk {
/// The raw encoding of an Orchard Full Viewing Key.
///
/// `(ak, nk, rivk)` each 32 bytes.
Orchard([u8; 96]),
/// Data contained within the Sapling component of a Unified Full Viewing Key
///
/// `(ak, nk, ovk, dk)` each 32 bytes.
Sapling([u8; 128]),
/// A pruned version of the extended public key for the BIP 44 account corresponding to the
/// transparent address subtree from which transparent addresses are derived. This
/// includes just the chain code (32 bytes) and the compressed public key (33 bytes), and excludes
/// the depth of in the derivation tree, the parent key fingerprint, and the child key
/// number (which would reveal the wallet account number for which this UFVK was generated).
///
/// Transparent addresses don't have "viewing keys" - the addresses themselves serve
/// that purpose. However, we want the ability to derive diversified Unified Addresses
/// from Unified Viewing Keys, and to not break the unlinkability property when they
/// include transparent receivers. To achieve this, we treat the last hardened node in
/// the BIP 44 derivation path as the "transparent viewing key"; all addresses derived
/// from this node use non-hardened derivation, and can thus be derived just from this
/// pruned extended public key.
P2pkh([u8; 65]),
Unknown {
typecode: u32,
data: Vec<u8>,
},
}
impl cmp::Ord for Fvk {
fn cmp(&self, other: &Self) -> cmp::Ordering {
match self.typecode().cmp(&other.typecode()) {
cmp::Ordering::Equal => self.data().cmp(other.data()),
res => res,
}
}
}
impl cmp::PartialOrd for Fvk {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl TryFrom<(u32, &[u8])> for Fvk {
type Error = ParseError;
fn try_from((typecode, data): (u32, &[u8])) -> Result<Self, Self::Error> {
let data = data.to_vec();
match typecode.try_into()? {
Typecode::P2pkh => data.try_into().map(Fvk::P2pkh),
Typecode::P2sh => Err(data),
Typecode::Sapling => data.try_into().map(Fvk::Sapling),
Typecode::Orchard => data.try_into().map(Fvk::Orchard),
Typecode::Unknown(_) => Ok(Fvk::Unknown { typecode, data }),
}
.map_err(|e| {
ParseError::InvalidEncoding(format!("Invalid fvk for typecode {}: {:?}", typecode, e))
})
}
}
impl SealedItem for Fvk {
fn typecode(&self) -> Typecode {
match self {
Fvk::P2pkh(_) => Typecode::P2pkh,
Fvk::Sapling(_) => Typecode::Sapling,
Fvk::Orchard(_) => Typecode::Orchard,
Fvk::Unknown { typecode, .. } => Typecode::Unknown(*typecode),
}
}
fn data(&self) -> &[u8] {
match self {
Fvk::P2pkh(data) => data,
Fvk::Sapling(data) => data,
Fvk::Orchard(data) => data,
Fvk::Unknown { data, .. } => data,
}
}
}
/// A Unified Full Viewing Key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Ufvk(pub(crate) Vec<Fvk>);
impl Container for Ufvk {
type Item = Fvk;
/// Returns the FVKs contained within this UFVK, in the order they were
/// parsed from the string encoding.
///
/// This API is for advanced usage; in most cases you should use `Ufvk::receivers`.
fn items_as_parsed(&self) -> &[Fvk] {
&self.0
}
}
impl Encoding for Ufvk {}
impl SealedContainer for Ufvk {
/// The HRP for a Bech32m-encoded mainnet Unified FVK.
///
/// Defined in [ZIP 316][zip-0316].
///
/// [zip-0316]: https://zips.z.cash/zip-0316
const MAINNET: &'static str = "uview";
/// The HRP for a Bech32m-encoded testnet Unified FVK.
///
/// Defined in [ZIP 316][zip-0316].
///
/// [zip-0316]: https://zips.z.cash/zip-0316
const TESTNET: &'static str = "uviewtest";
/// The HRP for a Bech32m-encoded regtest Unified FVK.
const REGTEST: &'static str = "uviewregtest";
fn from_inner(fvks: Vec<Self::Item>) -> Self {
Self(fvks)
}
}
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use proptest::{array::uniform1, array::uniform32, prelude::*, sample::select};
use super::{Fvk, ParseError, Typecode, Ufvk};
use crate::{
kind::unified::{private::SealedContainer, Container, Encoding},
Network,
};
prop_compose! {
fn uniform128()(a in uniform96(), b in uniform32(0u8..)) -> [u8; 128] {
let mut fvk = [0; 128];
fvk[..96].copy_from_slice(&a);
fvk[96..].copy_from_slice(&b);
fvk
}
}
prop_compose! {
fn uniform96()(a in uniform32(0u8..), b in uniform32(0u8..), c in uniform32(0u8..)) -> [u8; 96] {
let mut fvk = [0; 96];
fvk[..32].copy_from_slice(&a);
fvk[32..64].copy_from_slice(&b);
fvk[64..].copy_from_slice(&c);
fvk
}
}
prop_compose! {
fn uniform65()(a in uniform32(0u8..), b in uniform32(0u8..), c in uniform1(0u8..)) -> [u8; 65] {
let mut fvk = [0; 65];
fvk[..32].copy_from_slice(&a);
fvk[32..64].copy_from_slice(&b);
fvk[64..].copy_from_slice(&c);
fvk
}
}
pub fn arb_orchard_fvk() -> impl Strategy<Value = Fvk> {
uniform96().prop_map(Fvk::Orchard)
}
pub fn arb_sapling_fvk() -> impl Strategy<Value = Fvk> {
uniform128().prop_map(Fvk::Sapling)
}
fn arb_shielded_fvk() -> impl Strategy<Value = Vec<Fvk>> {
prop_oneof![
vec![arb_sapling_fvk().boxed()],
vec![arb_orchard_fvk().boxed()],
vec![arb_orchard_fvk().boxed(), arb_sapling_fvk().boxed()],
]
}
fn arb_transparent_fvk() -> BoxedStrategy<Fvk> {
uniform65().prop_map(Fvk::P2pkh).boxed()
}
prop_compose! {
fn arb_unified_fvk()(
shielded in arb_shielded_fvk(),
transparent in prop::option::of(arb_transparent_fvk()),
) -> Ufvk {
Ufvk(shielded.into_iter().chain(transparent).collect())
}
}
proptest! {
#[test]
fn ufvk_roundtrip(
network in select(vec![Network::Main, Network::Test, Network::Regtest]),
ufvk in arb_unified_fvk(),
) {
let encoded = ufvk.encode(&network);
let decoded = Ufvk::decode(&encoded);
prop_assert_eq!(decoded, Ok((network, ufvk)));
}
}
#[test]
fn padding() {
// The test cases below use `Ufvk(vec![Fvk::Orchard([1; 96])])` as base.
// Invalid padding ([0xff; 16] instead of [b'u', 0x00, 0x00, 0x00...])
let invalid_padding = vec![
0x6b, 0x32, 0x44, 0xf1, 0xb, 0x67, 0xe9, 0x8f, 0x6, 0x57, 0xe3, 0x5, 0x17, 0xa0, 0x7,
0x5c, 0xb0, 0xc9, 0x23, 0xcc, 0xb7, 0x54, 0xac, 0x55, 0x6a, 0x65, 0x99, 0x95, 0x32,
0x97, 0xd5, 0x34, 0xa7, 0xc8, 0x6f, 0xc, 0xd7, 0x3b, 0xe0, 0x88, 0x19, 0xf3, 0x3e,
0x26, 0x19, 0xd6, 0x5f, 0x9a, 0x62, 0xc9, 0x6f, 0xad, 0x3b, 0xe5, 0xdd, 0xf1, 0xff,
0x5b, 0x4a, 0x13, 0x61, 0xc0, 0xd5, 0xa5, 0x87, 0xc5, 0x69, 0x48, 0xdb, 0x7e, 0xc6,
0x4e, 0xb0, 0x55, 0x41, 0x3f, 0xc0, 0x53, 0xbb, 0x79, 0x8b, 0x24, 0xa0, 0xfa, 0xd1,
0x6e, 0xea, 0x9, 0xea, 0xb3, 0xaf, 0x0, 0x7d, 0x86, 0x47, 0xdb, 0x8b, 0x38, 0xdd, 0x7b,
0xdf, 0x63, 0xe7, 0xef, 0x65, 0x6b, 0x18, 0x23, 0xf7, 0x3e, 0x35, 0x7c, 0xf3, 0xc4,
];
assert_eq!(
Ufvk::parse_internal(Ufvk::MAINNET, &invalid_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
);
// Short padding (padded to 15 bytes instead of 16)
let truncated_padding = vec![
0xdf, 0xea, 0x84, 0x55, 0xc3, 0x4a, 0x7c, 0x6e, 0x9f, 0x83, 0x3, 0x21, 0x14, 0xb0,
0xcf, 0xb0, 0x60, 0x84, 0x75, 0x3a, 0xdc, 0xb9, 0x93, 0x16, 0xc0, 0x8f, 0x28, 0x5f,
0x61, 0x5e, 0xf0, 0x8e, 0x44, 0xae, 0xa6, 0x74, 0xc5, 0x64, 0xad, 0xfa, 0xdc, 0x7d,
0x64, 0x2a, 0x9, 0x47, 0x16, 0xf6, 0x5d, 0x8e, 0x46, 0xc4, 0xf0, 0x54, 0xfa, 0x5, 0x28,
0x1e, 0x3d, 0x7d, 0x37, 0xa5, 0x9f, 0x8b, 0x62, 0x78, 0xf6, 0x50, 0x18, 0x63, 0xe4,
0x51, 0x14, 0xae, 0x89, 0x41, 0x86, 0xd4, 0x9f, 0x10, 0x4b, 0x66, 0x2b, 0xf9, 0x46,
0x9c, 0xeb, 0xe8, 0x90, 0x8, 0xad, 0xd9, 0x6c, 0x6a, 0xf1, 0xed, 0xeb, 0x72, 0x44,
0x43, 0x8e, 0xc0, 0x3e, 0x9f, 0xf4, 0xf1, 0x80, 0x32, 0xcf, 0x2f, 0x7e, 0x7f, 0x91,
];
assert_eq!(
Ufvk::parse_internal(Ufvk::MAINNET, &truncated_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
);
}
#[test]
fn truncated() {
// The test cases below start from an encoding of
// `Ufvk(vec![Fvk::Orchard([1; 96]), Fvk::Sapling([2; 96])])`
// with the fvk data truncated, but valid padding.
// - Missing the last data byte of the Sapling fvk.
let truncated_sapling_data = vec![
0x43, 0xbf, 0x17, 0xa2, 0xb7, 0x85, 0xe7, 0x8e, 0xa4, 0x6d, 0x36, 0xa5, 0xf1, 0x1d,
0x74, 0xd1, 0x40, 0x6e, 0xed, 0xbd, 0x6b, 0x51, 0x6a, 0x36, 0x9c, 0xb3, 0x28, 0xd,
0x90, 0xa1, 0x1e, 0x3a, 0x67, 0xa2, 0x15, 0xc5, 0xfb, 0x82, 0x96, 0xf4, 0x35, 0x57,
0x71, 0x5d, 0xbb, 0xac, 0x30, 0x1d, 0x1, 0x6d, 0xdd, 0x2e, 0xf, 0x8, 0x4b, 0xcf, 0x5,
0xfe, 0x86, 0xd7, 0xa0, 0x9d, 0x94, 0x9f, 0x16, 0x5e, 0xa0, 0x3, 0x58, 0x81, 0x71,
0x40, 0xe4, 0xb8, 0xfc, 0x64, 0x75, 0x80, 0x46, 0x4f, 0x51, 0x2d, 0xb2, 0x51, 0xf,
0x22, 0x49, 0x53, 0x95, 0xbd, 0x7b, 0x66, 0xd9, 0x17, 0xda, 0x15, 0x62, 0xe0, 0xc6,
0xf8, 0x5c, 0xdf, 0x75, 0x6d, 0x7, 0xb, 0xf7, 0xab, 0xfc, 0x20, 0x61, 0xd0, 0xf4, 0x79,
0xfa, 0x4, 0xd3, 0xac, 0x8b, 0xf, 0x3c, 0x30, 0x23, 0x32, 0x37, 0x51, 0xc5, 0xfc, 0x66,
0x7e, 0xe1, 0x9c, 0xa8, 0xec, 0x52, 0x57, 0x7e, 0xc0, 0x31, 0x83, 0x1c, 0x31, 0x5,
0x1b, 0xc3, 0x70, 0xd3, 0x44, 0x74, 0xd2, 0x8a, 0xda, 0x32, 0x4, 0x93, 0xd2, 0xbf,
0xb4, 0xbb, 0xa, 0x9e, 0x8c, 0xe9, 0x8f, 0xe7, 0x8a, 0x95, 0xc8, 0x21, 0xfa, 0x12,
0x41, 0x2e, 0x69, 0x54, 0xf0, 0x7a, 0x9e, 0x20, 0x94, 0xa3, 0xaa, 0xc3, 0x50, 0x43,
0xc5, 0xe2, 0x32, 0x8b, 0x2e, 0x4f, 0xbb, 0xb4, 0xc0, 0x7f, 0x47, 0x35, 0xab, 0x89,
0x8c, 0x7a, 0xbf, 0x7b, 0x9a, 0xdd, 0xee, 0x18, 0x2c, 0x2d, 0xc2, 0xfc,
];
assert_matches!(
Ufvk::parse_internal(Ufvk::MAINNET, &truncated_sapling_data[..]),
Err(ParseError::InvalidEncoding(_))
);
// - Truncated after the typecode of the Sapling fvk.
let truncated_after_sapling_typecode = vec![
0xac, 0x26, 0x5b, 0x19, 0x8f, 0x88, 0xb0, 0x7, 0xb3, 0x0, 0x91, 0x19, 0x52, 0xe1, 0x73,
0x48, 0xff, 0x66, 0x7a, 0xef, 0xcf, 0x57, 0x9c, 0x65, 0xe4, 0x6a, 0x7a, 0x1d, 0x19,
0x75, 0x6b, 0x43, 0xdd, 0xcf, 0xb9, 0x9a, 0xf3, 0x7a, 0xf8, 0xb, 0x23, 0x96, 0x64,
0x8c, 0x57, 0x56, 0x67, 0x9, 0x40, 0x35, 0xcb, 0xb1, 0xa4, 0x91, 0x4f, 0xdc, 0x39, 0x0,
0x98, 0x56, 0xa8, 0xf7, 0x25, 0x1a, 0xc8, 0xbc, 0xd7, 0xb3, 0xb0, 0xfa, 0x78, 0x6,
0xe8, 0x50, 0xfe, 0x92, 0xec, 0x5b, 0x1f, 0x74, 0xb9, 0xcf, 0x1f, 0x2e, 0x3b, 0x41,
0x54, 0xd1, 0x9e, 0xec, 0x8b, 0xef, 0x35, 0xb8, 0x44, 0xdd, 0xab, 0x9a, 0x8d,
];
assert_matches!(
Ufvk::parse_internal(Ufvk::MAINNET, &truncated_after_sapling_typecode[..]),
Err(ParseError::InvalidEncoding(_))
);
}
#[test]
fn duplicate_typecode() {
// Construct and serialize an invalid Ufvk. This must be done using private
// methods, as the public API does not permit construction of such invalid values.
let ufvk = Ufvk(vec![Fvk::Sapling([1; 128]), Fvk::Sapling([2; 128])]);
let encoded = ufvk.to_jumbled_bytes(Ufvk::MAINNET);
assert_eq!(
Ufvk::parse_internal(Ufvk::MAINNET, &encoded[..]),
Err(ParseError::DuplicateTypecode(Typecode::Sapling))
);
}
#[test]
fn only_transparent() {
// Raw encoding of `Ufvk(vec![Fvk::P2pkh([0; 65])])`.
let encoded = vec![
0xc4, 0x70, 0xc8, 0x7a, 0xcc, 0xe6, 0x6b, 0x1a, 0x62, 0xc7, 0xcd, 0x5f, 0x76, 0xd8,
0xcc, 0x9c, 0x50, 0xbd, 0xce, 0x85, 0x80, 0xd7, 0x78, 0x25, 0x3e, 0x47, 0x9, 0x57,
0x7d, 0x6a, 0xdb, 0x10, 0xb4, 0x11, 0x80, 0x13, 0x4c, 0x83, 0x76, 0xb4, 0x6b, 0xbd,
0xef, 0x83, 0x5c, 0xa7, 0x68, 0xe6, 0xba, 0x41, 0x12, 0xbd, 0x43, 0x24, 0xf5, 0xaa,
0xa0, 0xf5, 0xf8, 0xe1, 0x59, 0xa0, 0x95, 0x85, 0x86, 0xf1, 0x9e, 0xcf, 0x8f, 0x94,
0xf4, 0xf5, 0x16, 0xef, 0x5c, 0xe0, 0x26, 0xbc, 0x23, 0x73, 0x76, 0x3f, 0x4b,
];
assert_eq!(
Ufvk::parse_internal(Ufvk::MAINNET, &encoded[..]),
Err(ParseError::OnlyTransparent)
);
}
#[test]
fn fvks_are_sorted() {
// Construct a UFVK with fvks in an unsorted order.
let ufvk = Ufvk(vec![
Fvk::P2pkh([0; 65]),
Fvk::Orchard([0; 96]),
Fvk::Unknown {
typecode: 0xff,
data: vec![],
},
Fvk::Sapling([0; 128]),
]);
// `Ufvk::items` sorts the fvks in priority order.
assert_eq!(
ufvk.items(),
vec![
Fvk::Orchard([0; 96]),
Fvk::Sapling([0; 128]),
Fvk::P2pkh([0; 65]),
Fvk::Unknown {
typecode: 0xff,
data: vec![],
},
]
)
}
}

View File

@ -0,0 +1,344 @@
use std::cmp;
use std::convert::{TryFrom, TryInto};
use super::{
private::{SealedContainer, SealedItem},
Container, Encoding, ParseError, Typecode,
};
/// The set of known IVKs for Unified IVKs.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Ivk {
/// The raw encoding of an Orchard Incoming Viewing Key.
///
/// `(dk, ivk)` each 32 bytes.
Orchard([u8; 64]),
/// Data contained within the Sapling component of a Unified Incoming Viewing Key.
///
/// In order to ensure that Unified Addresses can always be derived from UIVKs, we
/// store more data here than was specified to be part of a Sapling IVK. Specifically,
/// we store the same data here as we do for Orchard.
///
/// `(dk, ivk)` each 32 bytes.
Sapling([u8; 64]),
/// A pruned version of the extended public key for the BIP 44 account corresponding to the
/// transparent address subtree from which transparent addresses are derived,
/// at the external `change` BIP 44 path, i.e. `m/44'/133'/<account_id>'/0`. This
/// includes just the chain code (32 bytes) and the compressed public key (33 bytes), and excludes
/// the depth of in the derivation tree, the parent key fingerprint, and the child key
/// number (which would reveal the wallet account number for which this UFVK was generated).
///
/// Transparent addresses don't have "viewing keys" - the addresses themselves serve
/// that purpose. However, we want the ability to derive diversified Unified Addresses
/// from Unified Viewing Keys, and to not break the unlinkability property when they
/// include transparent receivers. To achieve this, we treat the last hardened node in
/// the BIP 44 derivation path as the "transparent viewing key"; all addresses derived
/// from this node use non-hardened derivation, and can thus be derived just from this
/// pruned extended public key.
P2pkh([u8; 65]),
Unknown {
typecode: u32,
data: Vec<u8>,
},
}
impl cmp::Ord for Ivk {
fn cmp(&self, other: &Self) -> cmp::Ordering {
match self.typecode().cmp(&other.typecode()) {
cmp::Ordering::Equal => self.data().cmp(other.data()),
res => res,
}
}
}
impl cmp::PartialOrd for Ivk {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl TryFrom<(u32, &[u8])> for Ivk {
type Error = ParseError;
fn try_from((typecode, data): (u32, &[u8])) -> Result<Self, Self::Error> {
let data = data.to_vec();
match typecode.try_into()? {
Typecode::P2pkh => data.try_into().map(Ivk::P2pkh),
Typecode::P2sh => Err(data),
Typecode::Sapling => data.try_into().map(Ivk::Sapling),
Typecode::Orchard => data.try_into().map(Ivk::Orchard),
Typecode::Unknown(_) => Ok(Ivk::Unknown { typecode, data }),
}
.map_err(|e| {
ParseError::InvalidEncoding(format!("Invalid ivk for typecode {}: {:?}", typecode, e))
})
}
}
impl SealedItem for Ivk {
fn typecode(&self) -> Typecode {
match self {
Ivk::P2pkh(_) => Typecode::P2pkh,
Ivk::Sapling(_) => Typecode::Sapling,
Ivk::Orchard(_) => Typecode::Orchard,
Ivk::Unknown { typecode, .. } => Typecode::Unknown(*typecode),
}
}
fn data(&self) -> &[u8] {
match self {
Ivk::P2pkh(data) => data,
Ivk::Sapling(data) => data,
Ivk::Orchard(data) => data,
Ivk::Unknown { data, .. } => data,
}
}
}
/// A Unified Incoming Viewing Key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Uivk(pub(crate) Vec<Ivk>);
impl Container for Uivk {
type Item = Ivk;
/// Returns the IVKs contained within this UIVK, in the order they were
/// parsed from the string encoding.
///
/// This API is for advanced usage; in most cases you should use `Uivk::items`.
fn items_as_parsed(&self) -> &[Ivk] {
&self.0
}
}
impl Encoding for Uivk {}
impl SealedContainer for Uivk {
/// The HRP for a Bech32m-encoded mainnet Unified IVK.
///
/// Defined in [ZIP 316][zip-0316].
///
/// [zip-0316]: https://zips.z.cash/zip-0316
const MAINNET: &'static str = "uivk";
/// The HRP for a Bech32m-encoded testnet Unified IVK.
///
/// Defined in [ZIP 316][zip-0316].
///
/// [zip-0316]: https://zips.z.cash/zip-0316
const TESTNET: &'static str = "uivktest";
/// The HRP for a Bech32m-encoded regtest Unified IVK.
const REGTEST: &'static str = "uivkregtest";
fn from_inner(ivks: Vec<Self::Item>) -> Self {
Self(ivks)
}
}
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use proptest::{
array::{uniform1, uniform32},
prelude::*,
sample::select,
};
use super::{Ivk, ParseError, Typecode, Uivk};
use crate::{
kind::unified::{private::SealedContainer, Container, Encoding},
Network,
};
prop_compose! {
fn uniform64()(a in uniform32(0u8..), b in uniform32(0u8..)) -> [u8; 64] {
let mut c = [0; 64];
c[..32].copy_from_slice(&a);
c[32..].copy_from_slice(&b);
c
}
}
prop_compose! {
fn uniform65()(a in uniform1(0u8..), b in uniform64()) -> [u8; 65] {
let mut c = [0; 65];
c[..1].copy_from_slice(&a);
c[1..].copy_from_slice(&b);
c
}
}
fn arb_shielded_ivk() -> impl Strategy<Value = Vec<Ivk>> {
prop_oneof![
vec![uniform64().prop_map(Ivk::Sapling)],
vec![uniform64().prop_map(Ivk::Orchard)],
vec![
uniform64().prop_map(Ivk::Orchard as fn([u8; 64]) -> Ivk),
uniform64().prop_map(Ivk::Sapling)
],
]
}
fn arb_transparent_ivk() -> impl Strategy<Value = Ivk> {
uniform65().prop_map(Ivk::P2pkh)
}
prop_compose! {
fn arb_unified_ivk()(
shielded in arb_shielded_ivk(),
transparent in prop::option::of(arb_transparent_ivk()),
) -> Uivk {
Uivk(shielded.into_iter().chain(transparent).collect())
}
}
proptest! {
#[test]
fn uivk_roundtrip(
network in select(vec![Network::Main, Network::Test, Network::Regtest]),
uivk in arb_unified_ivk(),
) {
let encoded = uivk.encode(&network);
let decoded = Uivk::decode(&encoded);
prop_assert_eq!(decoded, Ok((network, uivk)));
}
}
#[test]
fn padding() {
// The test cases below use `Uivk(vec![Ivk::Orchard([1; 64])])` as base.
// Invalid padding ([0xff; 16] instead of [b'u', 0x00, 0x00, 0x00...])
let invalid_padding = vec![
0xba, 0xbc, 0xc0, 0x71, 0xcd, 0x3b, 0xfd, 0x9a, 0x32, 0x19, 0x7e, 0xeb, 0x8a, 0xa7,
0x6e, 0xd4, 0xac, 0xcb, 0x59, 0xc2, 0x54, 0x26, 0xc6, 0xab, 0x71, 0xc7, 0xc3, 0x72,
0xc, 0xa9, 0xad, 0xa4, 0xad, 0x8c, 0x9e, 0x35, 0x7b, 0x4c, 0x5d, 0xc7, 0x66, 0x12,
0x8a, 0xc5, 0x42, 0x89, 0xc1, 0x77, 0x32, 0xdc, 0xe8, 0x4b, 0x51, 0x31, 0x30, 0x3,
0x20, 0xe3, 0xb6, 0x8c, 0xbb, 0xab, 0xe8, 0x89, 0xf8, 0xed, 0xac, 0x6d, 0x8e, 0xb1,
0x83, 0xe8, 0x92, 0x18, 0x28, 0x70, 0x1e, 0x81, 0x76, 0x56, 0xb6, 0x15,
];
assert_eq!(
Uivk::parse_internal(Uivk::MAINNET, &invalid_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
);
// Short padding (padded to 15 bytes instead of 16)
let truncated_padding = vec![
0x96, 0x73, 0x6a, 0x56, 0xbc, 0x44, 0x38, 0xe2, 0x47, 0x41, 0x1c, 0x70, 0xe4, 0x6,
0x87, 0xbe, 0xb6, 0x90, 0xbd, 0xab, 0x1b, 0xd8, 0x27, 0x10, 0x0, 0x21, 0x30, 0x2, 0x77,
0x87, 0x0, 0x25, 0x96, 0x94, 0x8f, 0x1e, 0x39, 0xd2, 0xd8, 0x65, 0xb4, 0x3c, 0x72,
0xd8, 0xac, 0xec, 0x5b, 0xa2, 0x18, 0x62, 0x3f, 0xb, 0x88, 0xb4, 0x41, 0xf1, 0x55,
0x39, 0x53, 0xbf, 0x2a, 0xd6, 0xcf, 0xdd, 0x46, 0xb7, 0xd8, 0xc1, 0x39, 0x34, 0x4d,
0xf9, 0x65, 0x49, 0x14, 0xab, 0x7c, 0x55, 0x7b, 0x39, 0x47,
];
assert_eq!(
Uivk::parse_internal(Uivk::MAINNET, &truncated_padding[..]),
Err(ParseError::InvalidEncoding(
"Invalid padding bytes".to_owned()
))
);
}
#[test]
fn truncated() {
// The test cases below start from an encoding of
// `Uivk(vec![Ivk::Orchard([1; 64]), Ivk::Sapling([2; 64])])`
// with the ivk data truncated, but valid padding.
// - Missing the last data byte of the Sapling ivk.
let truncated_sapling_data = vec![
0xce, 0xbc, 0xfe, 0xc5, 0xef, 0x2d, 0xe, 0x66, 0xc2, 0x8c, 0x34, 0xdc, 0x2e, 0x24,
0xd2, 0xc7, 0x4b, 0xac, 0x36, 0xe0, 0x43, 0x72, 0xa7, 0x33, 0xa4, 0xe, 0xe0, 0x52,
0x15, 0x64, 0x66, 0x92, 0x36, 0xa7, 0x60, 0x8e, 0x48, 0xe8, 0xb0, 0x30, 0x4d, 0xcb,
0xd, 0x6f, 0x5, 0xd4, 0xb8, 0x72, 0x6a, 0xdc, 0x6c, 0x5c, 0xa, 0xf8, 0xdf, 0x95, 0x5a,
0xba, 0xe1, 0xaa, 0x82, 0x51, 0xe2, 0x70, 0x8d, 0x13, 0x16, 0x88, 0x6a, 0xc0, 0xc1,
0x99, 0x3c, 0xaf, 0x2c, 0x16, 0x54, 0x80, 0x7e, 0xb, 0xad, 0x31, 0x29, 0x26, 0xdd,
0x7a, 0x55, 0x98, 0x1, 0x18, 0xb, 0x14, 0x94, 0xb2, 0x6b, 0x81, 0x67, 0x73, 0xa6, 0xd0,
0x20, 0x94, 0x17, 0x3a, 0xf9, 0x98, 0x43, 0x58, 0xd6, 0x1, 0x10, 0x73, 0x32, 0xb4,
0x99, 0xad, 0x6b, 0xfe, 0xc0, 0x97, 0xaf, 0xd2, 0xee, 0x8, 0xe5, 0x83, 0x6b, 0xb6,
0xd9, 0x0, 0xef, 0x84, 0xff, 0xe8, 0x58, 0xba, 0xe8, 0x10, 0xea, 0x2d, 0xee, 0x72,
0xf5, 0xd5, 0x8a, 0xb5, 0x1a,
];
assert_matches!(
Uivk::parse_internal(Uivk::MAINNET, &truncated_sapling_data[..]),
Err(ParseError::InvalidEncoding(_))
);
// - Truncated after the typecode of the Sapling ivk.
let truncated_after_sapling_typecode = vec![
0xf7, 0x3, 0xd8, 0xbe, 0x6a, 0x27, 0xfa, 0xa1, 0xd3, 0x11, 0xea, 0x25, 0x94, 0xe2, 0xb,
0xde, 0xed, 0x6a, 0xaa, 0x8, 0x46, 0x7d, 0xe4, 0xb1, 0xe, 0xf1, 0xde, 0x61, 0xd7, 0x95,
0xf7, 0x82, 0x62, 0x32, 0x7a, 0x73, 0x8c, 0x55, 0x93, 0xa1, 0x63, 0x75, 0xe2, 0xca,
0xcb, 0x73, 0xd5, 0xe5, 0xa3, 0xbd, 0xb3, 0xf2, 0x26, 0xfa, 0x1c, 0xa2, 0xad, 0xb6,
0xd8, 0x21, 0x5e, 0x8, 0xa, 0x82, 0x95, 0x21, 0x74,
];
assert_matches!(
Uivk::parse_internal(Uivk::MAINNET, &truncated_after_sapling_typecode[..]),
Err(ParseError::InvalidEncoding(_))
);
}
#[test]
fn duplicate_typecode() {
// Construct and serialize an invalid UIVK.
let uivk = Uivk(vec![Ivk::Sapling([1; 64]), Ivk::Sapling([2; 64])]);
let encoded = uivk.encode(&Network::Main);
assert_eq!(
Uivk::decode(&encoded),
Err(ParseError::DuplicateTypecode(Typecode::Sapling))
);
}
#[test]
fn only_transparent() {
// Raw Encoding of `Uivk(vec![Ivk::P2pkh([0; 65])])`.
let encoded = vec![
0x12, 0x51, 0x37, 0xc7, 0xac, 0x8c, 0xd, 0x13, 0x3a, 0x5f, 0xc6, 0x84, 0x53, 0x90,
0xf8, 0xe7, 0x23, 0x34, 0xfb, 0xda, 0x49, 0x3c, 0x87, 0x1c, 0x8f, 0x1a, 0xe1, 0x63,
0xba, 0xdf, 0x77, 0x64, 0x43, 0xcf, 0xdc, 0x37, 0x1f, 0xd2, 0x89, 0x60, 0xe3, 0x77,
0x20, 0xd0, 0x1c, 0x5, 0x40, 0xe5, 0x43, 0x55, 0xc4, 0xe5, 0xf8, 0xaa, 0xe, 0x7a, 0xe7,
0x8c, 0x53, 0x15, 0xb8, 0x8f, 0x90, 0x14, 0x33, 0x30, 0x52, 0x2b, 0x8, 0x89, 0x90,
0xbd, 0xfe, 0xa4, 0xb7, 0x47, 0x20, 0x92, 0x6, 0xf0, 0x0, 0xf9, 0x64,
];
assert_eq!(
Uivk::parse_internal(Uivk::MAINNET, &encoded[..]),
Err(ParseError::OnlyTransparent)
);
}
#[test]
fn ivks_are_sorted() {
// Construct a UIVK with ivks in an unsorted order.
let uivk = Uivk(vec![
Ivk::P2pkh([0; 65]),
Ivk::Orchard([0; 64]),
Ivk::Unknown {
typecode: 0xff,
data: vec![],
},
Ivk::Sapling([0; 64]),
]);
// `Uivk::items` sorts the ivks in priority order.
assert_eq!(
uivk.items(),
vec![
Ivk::Orchard([0; 64]),
Ivk::Sapling([0; 64]),
Ivk::P2pkh([0; 65]),
Ivk::Unknown {
typecode: 0xff,
data: vec![],
},
]
)
}
}

View File

@ -13,7 +13,8 @@ use nonempty::NonEmpty;
use std::convert::TryFrom;
use std::io::{self, Read, Write};
const MAX_SIZE: u64 = 0x02000000;
/// The maximum allowed value representable as a `[CompactSize]`
pub const MAX_COMPACT_SIZE: u32 = 0x02000000;
/// Namespace for functions for compact encoding of integers.
///
@ -54,7 +55,7 @@ impl CompactSize {
}?;
match result {
s if s > MAX_SIZE => Err(io::Error::new(
s if s > <u64>::from(MAX_COMPACT_SIZE) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"CompactSize too large",
)),