1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use bech32::{self, FromBase32, ToBase32, Variant};
use std::cmp;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use crate::Network;
pub(crate) mod address;
pub(crate) mod fvk;
pub(crate) mod ivk;
pub use address::{Address, Receiver};
pub use fvk::{Fvk, Ufvk};
pub use ivk::{Ivk, Uivk};
const PADDING_LEN: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Typecode {
P2pkh,
P2sh,
Sapling,
Orchard,
Unknown(u32),
}
impl Typecode {
pub fn preference_order(a: &Self, b: &Self) -> cmp::Ordering {
match (a, b) {
(Self::Orchard, Self::Orchard)
| (Self::Sapling, Self::Sapling)
| (Self::P2sh, Self::P2sh)
| (Self::P2pkh, Self::P2pkh) => cmp::Ordering::Equal,
(Self::Unknown(a), Self::Unknown(b)) => b.cmp(a),
(Self::Orchard, _) => cmp::Ordering::Less,
(_, Self::Orchard) => cmp::Ordering::Greater,
(Self::Sapling, _) => cmp::Ordering::Less,
(_, Self::Sapling) => cmp::Ordering::Greater,
(Self::P2sh, _) => cmp::Ordering::Less,
(_, Self::P2sh) => cmp::Ordering::Greater,
(Self::P2pkh, _) => cmp::Ordering::Less,
(_, Self::P2pkh) => cmp::Ordering::Greater,
}
}
pub fn encoding_order(a: &Self, b: &Self) -> cmp::Ordering {
u32::from(*a).cmp(&u32::from(*b))
}
}
impl TryFrom<u32> for Typecode {
type Error = ParseError;
fn try_from(typecode: u32) -> Result<Self, Self::Error> {
match typecode {
0x00 => Ok(Typecode::P2pkh),
0x01 => Ok(Typecode::P2sh),
0x02 => Ok(Typecode::Sapling),
0x03 => Ok(Typecode::Orchard),
0x04..=0x02000000 => Ok(Typecode::Unknown(typecode)),
0x02000001..=u32::MAX => Err(ParseError::InvalidTypecodeValue(typecode as u64)),
}
}
}
impl From<Typecode> for u32 {
fn from(t: Typecode) -> Self {
match t {
Typecode::P2pkh => 0x00,
Typecode::P2sh => 0x01,
Typecode::Sapling => 0x02,
Typecode::Orchard => 0x03,
Typecode::Unknown(typecode) => typecode,
}
}
}
impl Typecode {
fn is_transparent(&self) -> bool {
matches!(self, Typecode::P2pkh | Typecode::P2sh)
}
}
#[derive(Debug, PartialEq)]
pub enum ParseError {
BothP2phkAndP2sh,
DuplicateTypecode(Typecode),
InvalidTypecodeValue(u64),
InvalidEncoding(String),
InvalidTypecodeOrder,
OnlyTransparent,
NotUnified,
UnknownPrefix(String),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::BothP2phkAndP2sh => write!(f, "UA contains both P2PKH and P2SH items"),
ParseError::DuplicateTypecode(c) => write!(f, "Duplicate typecode {}", u32::from(*c)),
ParseError::InvalidTypecodeValue(v) => write!(f, "Typecode value out of range {}", v),
ParseError::InvalidEncoding(msg) => write!(f, "Invalid encoding: {}", msg),
ParseError::InvalidTypecodeOrder => write!(f, "Items are out of order."),
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)
}
}
}
}
impl Error for ParseError {}
pub(crate) mod private {
use super::{ParseError, Typecode, PADDING_LEN};
use crate::Network;
use std::{
cmp,
convert::{TryFrom, TryInto},
io::Write,
};
use zcash_encoding::CompactSize;
pub trait SealedItem: for<'a> TryFrom<(u32, &'a [u8]), Error = ParseError> + Clone {
fn typecode(&self) -> Typecode;
fn data(&self) -> &[u8];
fn preference_order(a: &Self, b: &Self) -> cmp::Ordering {
match Typecode::preference_order(&a.typecode(), &b.typecode()) {
cmp::Ordering::Equal => a.data().cmp(b.data()),
res => res,
}
}
fn encoding_order(a: &Self, b: &Self) -> cmp::Ordering {
match Typecode::encoding_order(&a.typecode(), &b.typecode()) {
cmp::Ordering::Equal => a.data().cmp(b.data()),
res => res,
}
}
}
pub trait SealedContainer: super::Container + std::marker::Sized {
const MAINNET: &'static str;
const TESTNET: &'static str;
const REGTEST: &'static str;
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_as_parsed() {
let data = item.data();
CompactSize::write(
&mut writer,
<u32>::from(item.typecode()).try_into().unwrap(),
)
.unwrap();
CompactSize::write(&mut writer, data.len()).unwrap();
writer.write_all(data).unwrap();
}
}
fn to_jumbled_bytes(&self, hrp: &str) -> Vec<u8> {
assert!(hrp.len() <= PADDING_LEN);
let mut writer = std::io::Cursor::new(Vec::new());
self.write_raw_encoding(&mut writer);
let mut padding = [0u8; PADDING_LEN];
padding[0..hrp.len()].copy_from_slice(hrp.as_bytes());
writer.write_all(&padding).unwrap();
let padded = writer.into_inner();
f4jumble::f4jumble(&padded)
.unwrap_or_else(|e| panic!("f4jumble failed on {:?}: {}", padded, e))
}
fn parse_items<T: Into<Vec<u8>>>(hrp: &str, buf: T) -> 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 mut encoded = buf.into();
f4jumble::f4jumble_inv_mut(&mut encoded[..]).map_err(|e| {
ParseError::InvalidEncoding(format!("F4Jumble decoding failed: {}", e))
})?;
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)
}
fn try_from_items_internal(items: Vec<Self::Item>) -> Result<Self, ParseError> {
assert!(u32::from(Typecode::P2sh) == u32::from(Typecode::P2pkh) + 1);
let mut only_transparent = true;
let mut prev_code = None;
for item in &items {
let t = item.typecode();
let t_code = Some(u32::from(t));
if t_code < prev_code {
return Err(ParseError::InvalidTypecodeOrder);
} else if t_code == prev_code {
return Err(ParseError::DuplicateTypecode(t));
} else if t == Typecode::P2sh && prev_code == Some(u32::from(Typecode::P2pkh)) {
return Err(ParseError::BothP2phkAndP2sh);
} else {
prev_code = t_code;
only_transparent = only_transparent && t.is_transparent();
}
}
if only_transparent {
Err(ParseError::OnlyTransparent)
} else {
Ok(Self::from_inner(items))
}
}
fn parse_internal<T: Into<Vec<u8>>>(hrp: &str, buf: T) -> Result<Self, ParseError> {
Self::parse_items(hrp, buf).and_then(Self::try_from_items_internal)
}
}
}
use private::SealedItem;
pub trait Encoding: private::SealedContainer {
fn try_from_items(mut items: Vec<Self::Item>) -> Result<Self, ParseError> {
items.sort_unstable_by(Self::Item::encoding_order);
Self::try_from_items_internal(items)
}
fn decode(s: &str) -> Result<(Network, Self), ParseError> {
if let Ok((hrp, data, Variant::Bech32m)) = bech32::decode(s) {
let hrp = hrp.as_str();
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 {
Err(ParseError::NotUnified)
}
}
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")
}
}
pub trait Container {
type Item: SealedItem;
fn items(&self) -> Vec<Self::Item> {
let mut items = self.items_as_parsed().to_vec();
items.sort_unstable_by(Self::Item::preference_order);
items
}
fn items_as_parsed(&self) -> &[Self::Item];
}