1use alloc::vec::Vec;
3use core::convert::TryFrom;
4use corez::io::{self, Read, Write};
5
6use nonempty::NonEmpty;
7
8use core::mem::size_of;
9use orchard::{
10 Action, Anchor, ValuePool,
11 bundle::{Authorization, Authorized, BundleVersion, Flags},
12 note::{ExtractedNoteCommitment, Nullifier, TransmittedNoteCiphertext},
13 note_encryption::{ENC_CIPHERTEXT_SIZE, NoteBytesData},
14 primitives::redpallas::{self, SigType, Signature, SpendAuth, VerificationKey},
15 value::ValueCommitment,
16};
17use zcash_encoding::{Array, CompactSize, Vector};
18use zcash_note_encryption::{EphemeralKeyBytes, OUT_CIPHERTEXT_SIZE};
19use zcash_protocol::{
20 consensus::{BranchId, OrchardProtocolRevision},
21 value::ZatBalance,
22};
23
24use crate::transaction::Transaction;
25
26pub const FLAG_SPENDS_ENABLED: u8 = 0b0000_0001;
27pub const FLAG_OUTPUTS_ENABLED: u8 = 0b0000_0010;
28pub const FLAGS_EXPECTED_UNSET: u8 = !(FLAG_SPENDS_ENABLED | FLAG_OUTPUTS_ENABLED);
29
30const VALUE_COMMITMENT_BYTE_SIZE: usize = 32;
41const NULLIFIER_BYTE_SIZE: usize = 32;
43const VERIFICATION_KEY_BYTE_SIZE: usize = 32;
45const NOTE_COMMITMENT_BYTE_SIZE: usize = 32;
47const EPHEMERAL_KEY_BYTE_SIZE: usize = size_of::<EphemeralKeyBytes>();
51
52pub const ACTION_SIZE: usize = VALUE_COMMITMENT_BYTE_SIZE
60 + NULLIFIER_BYTE_SIZE
61 + VERIFICATION_KEY_BYTE_SIZE
62 + NOTE_COMMITMENT_BYTE_SIZE
63 + EPHEMERAL_KEY_BYTE_SIZE
64 + ENC_CIPHERTEXT_SIZE
65 + OUT_CIPHERTEXT_SIZE;
66
67pub const SPEND_AUTH_SIG_SIZE: usize = 64;
70
71pub const BUNDLE_OVERHEAD: usize = 1 + 8 + 32 + 64 + 10;
78
79pub trait MapAuth<A: Authorization, B: Authorization> {
80 fn map_spend_auth(&self, s: A::SpendAuth) -> B::SpendAuth;
81 fn map_authorization(&self, a: A) -> B;
82}
83
84impl MapAuth<Authorized, Authorized> for () {
91 fn map_spend_auth(
92 &self,
93 s: <Authorized as Authorization>::SpendAuth,
94 ) -> <Authorized as Authorization>::SpendAuth {
95 s
96 }
97
98 fn map_authorization(&self, a: Authorized) -> Authorized {
99 a
100 }
101}
102
103fn read_bundle<R: Read>(
104 mut reader: R,
105 bundle_version: Option<BundleVersion>,
106) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
107 #[allow(clippy::redundant_closure)]
108 let actions_without_auth = Vector::read(&mut reader, |r| read_action_without_auth(r))?;
109 if actions_without_auth.is_empty() {
110 Ok(None)
111 } else {
112 let bundle_version = bundle_version.ok_or_else(|| {
113 io::Error::new(
114 io::ErrorKind::InvalidData,
115 "Orchard-protocol bundles may not be present in this transaction version \
116 under the transaction's consensus branch ID",
117 )
118 })?;
119 let flags = read_flags(&mut reader, bundle_version)?;
120 let value_balance = Transaction::read_amount(&mut reader)?;
121 let anchor = read_anchor(&mut reader)?;
122 let proof_bytes = Vector::read_bytes(&mut reader)?;
123 let actions = NonEmpty::from_vec(
124 actions_without_auth
125 .into_iter()
126 .map(|act| act.try_map(|_| read_signature::<_, redpallas::SpendAuth>(&mut reader)))
127 .collect::<Result<Vec<_>, _>>()?,
128 )
129 .expect("A nonzero number of actions was read from the transaction data.");
130 let binding_signature = read_signature::<_, redpallas::Binding>(&mut reader)?;
131
132 let authorization = orchard::bundle::Authorized::from_parts(
133 orchard::Proof::new(proof_bytes),
134 binding_signature,
135 );
136
137 orchard::Bundle::try_from_parts(
142 actions,
143 flags,
144 value_balance,
145 anchor,
146 authorization,
147 bundle_version,
148 )
149 .map(Some)
150 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
151 }
152}
153
154pub fn bundle_version_for_branch(
168 consensus_branch_id: BranchId,
169 pool: ValuePool,
170) -> Option<BundleVersion> {
171 let revision = consensus_branch_id.orchard_protocol_revision()?;
172 match pool {
173 ValuePool::Orchard => Some(match revision {
174 OrchardProtocolRevision::InsecureV1 => BundleVersion::orchard_insecure_v1(),
175 OrchardProtocolRevision::V2 => BundleVersion::orchard_v2(),
176 OrchardProtocolRevision::V3 => BundleVersion::orchard_v3(),
177 }),
178 ValuePool::Ironwood => match revision {
179 OrchardProtocolRevision::InsecureV1 | OrchardProtocolRevision::V2 => None,
180 OrchardProtocolRevision::V3 => Some(BundleVersion::ironwood_v3()),
181 },
182 }
183}
184
185pub fn read_v5_bundle<R: Read>(
194 reader: R,
195 consensus_branch_id: BranchId,
196) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
197 read_bundle(
198 reader,
199 bundle_version_for_branch(consensus_branch_id, ValuePool::Orchard),
200 )
201}
202
203fn check_v6_bundle_version(bundle_version: BundleVersion) -> io::Result<()> {
208 if bundle_version == BundleVersion::orchard_v3()
209 || bundle_version == BundleVersion::ironwood_v3()
210 {
211 Ok(())
212 } else {
213 Err(io::Error::new(
214 io::ErrorKind::InvalidInput,
215 "v6 Orchard bundles require orchard_v3 or ironwood_v3",
216 ))
217 }
218}
219
220pub fn read_v6_bundle<R: Read>(
228 reader: R,
229 consensus_branch_id: BranchId,
230 pool: ValuePool,
231) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
232 read_bundle(reader, bundle_version_for_branch(consensus_branch_id, pool))
233}
234
235pub fn read_value_commitment<R: Read>(mut reader: R) -> io::Result<ValueCommitment> {
236 let mut bytes = [0u8; 32];
237 reader.read_exact(&mut bytes)?;
238 let cv = ValueCommitment::from_bytes(&bytes);
239
240 if cv.is_none().into() {
241 Err(io::Error::new(
242 io::ErrorKind::InvalidInput,
243 "invalid Pallas point for value commitment",
244 ))
245 } else {
246 Ok(cv.unwrap())
247 }
248}
249
250pub fn read_nullifier<R: Read>(mut reader: R) -> io::Result<Nullifier> {
251 let mut bytes = [0u8; 32];
252 reader.read_exact(&mut bytes)?;
253 let nullifier_ctopt = Nullifier::from_bytes(&bytes);
254 if nullifier_ctopt.is_none().into() {
255 Err(io::Error::new(
256 io::ErrorKind::InvalidInput,
257 "invalid Pallas point for nullifier",
258 ))
259 } else {
260 Ok(nullifier_ctopt.unwrap())
261 }
262}
263
264pub fn read_verification_key<R: Read>(mut reader: R) -> io::Result<VerificationKey<SpendAuth>> {
265 let mut bytes = [0u8; 32];
266 reader.read_exact(&mut bytes)?;
267 VerificationKey::try_from(bytes)
268 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid verification key"))
269}
270
271pub fn read_cmx<R: Read>(mut reader: R) -> io::Result<ExtractedNoteCommitment> {
272 let mut bytes = [0u8; 32];
273 reader.read_exact(&mut bytes)?;
274 let cmx = ExtractedNoteCommitment::from_bytes(&bytes);
275 Option::from(cmx).ok_or_else(|| {
276 io::Error::new(
277 io::ErrorKind::InvalidInput,
278 "invalid Pallas base for field cmx",
279 )
280 })
281}
282
283pub fn read_note_ciphertext<R: Read>(mut reader: R) -> io::Result<TransmittedNoteCiphertext> {
284 let mut tnc = TransmittedNoteCiphertext {
285 epk_bytes: [0u8; 32],
286 enc_ciphertext: NoteBytesData([0u8; ENC_CIPHERTEXT_SIZE]),
287 out_ciphertext: [0u8; OUT_CIPHERTEXT_SIZE],
288 };
289
290 reader.read_exact(&mut tnc.epk_bytes)?;
291 reader.read_exact(&mut tnc.enc_ciphertext.0)?;
292 reader.read_exact(&mut tnc.out_ciphertext)?;
293
294 Ok(tnc)
295}
296
297pub fn read_action_without_auth<R: Read>(mut reader: R) -> io::Result<Action<()>> {
298 let cv_net = read_value_commitment(&mut reader)?;
299 let nf_old = read_nullifier(&mut reader)?;
300 let rk = read_verification_key(&mut reader)?;
301 let cmx = read_cmx(&mut reader)?;
302 let encrypted_note = read_note_ciphertext(&mut reader)?;
303
304 Action::from_parts(nf_old, rk, cmx, encrypted_note, cv_net, ())
305 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
306}
307
308pub fn read_flags<R: Read>(mut reader: R, bundle_version: BundleVersion) -> io::Result<Flags> {
309 let mut byte = [0u8; 1];
310 reader.read_exact(&mut byte)?;
311 Flags::from_byte(byte[0], bundle_version)
312 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid Orchard flags"))
313}
314
315pub fn read_anchor<R: Read>(mut reader: R) -> io::Result<Anchor> {
316 let mut bytes = [0u8; 32];
317 reader.read_exact(&mut bytes)?;
318 Option::from(Anchor::from_bytes(bytes))
319 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid Orchard anchor"))
320}
321
322pub fn read_signature<R: Read, T: SigType>(mut reader: R) -> io::Result<Signature<T>> {
323 let mut bytes = [0u8; 64];
324 reader.read_exact(&mut bytes)?;
325 Ok(Signature::from(bytes))
326}
327
328fn write_bundle<W: Write>(
329 bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
330 mut writer: W,
331) -> io::Result<()> {
332 if let Some(bundle) = &bundle {
333 Vector::write_nonempty(&mut writer, bundle.actions(), |w, a| {
334 write_action_without_auth(w, a)
335 })?;
336
337 writer.write_all(&[bundle.flag_byte()])?;
340 writer.write_all(&bundle.value_balance().to_i64_le_bytes())?;
341 writer.write_all(&bundle.anchor().to_bytes())?;
342 Vector::write_bytes(&mut writer, bundle.authorization().proof().as_ref())?;
343 Array::write(
344 &mut writer,
345 bundle.actions().iter().map(|a| a.authorization()),
346 |w, auth| w.write_all(&<[u8; 64]>::from(*auth)),
347 )?;
348 writer.write_all(&<[u8; 64]>::from(
349 bundle.authorization().binding_signature(),
350 ))?;
351 } else {
352 CompactSize::write(&mut writer, 0)?;
353 }
354
355 Ok(())
356}
357
358pub fn write_v5_bundle<W: Write>(
363 bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
364 writer: W,
365) -> io::Result<()> {
366 write_bundle(bundle, writer)
367}
368
369pub fn write_v6_bundle<W: Write>(
373 bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
374 writer: W,
375) -> io::Result<()> {
376 if let Some(bundle) = bundle {
377 check_v6_bundle_version(bundle.bundle_version())?;
378 }
379 write_bundle(bundle, writer)
380}
381
382pub fn write_value_commitment<W: Write>(mut writer: W, cv: &ValueCommitment) -> io::Result<()> {
383 writer.write_all(&cv.to_bytes())
384}
385
386pub fn write_nullifier<W: Write>(mut writer: W, nf: &Nullifier) -> io::Result<()> {
387 writer.write_all(&nf.to_bytes())
388}
389
390pub fn write_verification_key<W: Write>(
391 mut writer: W,
392 rk: &redpallas::VerificationKey<SpendAuth>,
393) -> io::Result<()> {
394 writer.write_all(&<[u8; 32]>::from(rk))
395}
396
397pub fn write_cmx<W: Write>(mut writer: W, cmx: &ExtractedNoteCommitment) -> io::Result<()> {
398 writer.write_all(&cmx.to_bytes())
399}
400
401pub fn write_note_ciphertext<W: Write>(
402 mut writer: W,
403 nc: &TransmittedNoteCiphertext,
404) -> io::Result<()> {
405 writer.write_all(&nc.epk_bytes)?;
406 writer.write_all(&nc.enc_ciphertext.0)?;
407 writer.write_all(&nc.out_ciphertext)
408}
409
410pub fn write_action_without_auth<W: Write>(
411 mut writer: W,
412 act: &Action<<Authorized as Authorization>::SpendAuth>,
413) -> io::Result<()> {
414 write_value_commitment(&mut writer, act.cv_net())?;
415 write_nullifier(&mut writer, act.nullifier())?;
416 write_verification_key(&mut writer, act.rk())?;
417 write_cmx(&mut writer, act.cmx())?;
418 write_note_ciphertext(&mut writer, act.encrypted_note())?;
419 Ok(())
420}
421
422#[cfg(any(test, feature = "test-dependencies"))]
423pub mod testing {
424 use proptest::prelude::*;
425
426 use orchard::bundle::{
427 Authorized, Bundle, BundleVersion, Flags,
428 testing::{self as t_orch},
429 };
430 use zcash_protocol::value::{ZatBalance, testing::arb_zat_balance};
431
432 use crate::transaction::TxVersion;
433
434 prop_compose! {
435 pub fn arb_bundle(n_actions: usize)(
436 orchard_value_balance in arb_zat_balance(),
437 bundle in t_orch::arb_bundle(n_actions)
438 ) -> Bundle<Authorized, ZatBalance> {
439 bundle.try_map_value_balance::<_, (), _>(|_| Ok(orchard_value_balance)).unwrap()
442 }
443 }
444
445 pub fn arb_bundle_for_version(
446 v: TxVersion,
447 ) -> impl Strategy<Value = Option<Bundle<Authorized, ZatBalance>>> {
448 if v.has_orchard() {
449 let bundle_version = orchard_bundle_version(v);
453 (1usize..100)
454 .prop_flat_map(move |n| {
455 prop::option::of(
456 arb_bundle(n).prop_map(move |b| rebuild_with_version(b, bundle_version)),
457 )
458 })
459 .boxed()
460 } else {
461 Just(None).boxed()
462 }
463 }
464
465 pub fn arb_ironwood_bundle_for_version(
469 v: TxVersion,
470 ) -> impl Strategy<Value = Option<Bundle<Authorized, ZatBalance>>> {
471 if v.has_ironwood() {
472 (1usize..100)
473 .prop_flat_map(|n| {
474 prop::option::of(
475 arb_bundle(n)
476 .prop_map(|b| rebuild_with_version(b, BundleVersion::ironwood_v3())),
477 )
478 })
479 .boxed()
480 } else {
481 Just(None).boxed()
482 }
483 }
484
485 fn orchard_bundle_version(v: TxVersion) -> BundleVersion {
488 if match v {
489 TxVersion::V6 => true,
490 #[cfg(zcash_unstable = "nutachyon")]
491 TxVersion::V7 => true,
492 _ => false,
493 } {
494 return BundleVersion::orchard_v3();
495 }
496 let _ = v;
497 BundleVersion::orchard_v2()
498 }
499
500 pub(crate) fn rebuild_with_version(
507 bundle: Bundle<Authorized, ZatBalance>,
508 bundle_version: BundleVersion,
509 ) -> Bundle<Authorized, ZatBalance> {
510 let mut byte = u8::from(bundle.flags().spends_enabled())
511 | (u8::from(bundle.flags().outputs_enabled()) << 1);
512 if bundle_version == BundleVersion::ironwood_v3() {
513 byte |= 0b100;
514 }
515 let flags = Flags::from_byte(byte, bundle_version)
516 .expect("constructed flag byte is representable under the target version");
517 ::orchard::Bundle::try_from_parts(
518 bundle.actions().clone(),
519 flags,
520 *bundle.value_balance(),
521 *bundle.anchor(),
522 bundle.authorization().clone(),
523 bundle_version,
524 )
525 .expect("flags are representable under the target version")
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use alloc::vec::Vec;
532
533 use orchard::{bundle::testing::arb_action, note::NoteVersion, value::NoteValue};
534 use proptest::prelude::*;
535
536 use super::{
537 ACTION_SIZE, ENC_CIPHERTEXT_SIZE, EPHEMERAL_KEY_BYTE_SIZE, NOTE_COMMITMENT_BYTE_SIZE,
538 NULLIFIER_BYTE_SIZE, OUT_CIPHERTEXT_SIZE, VALUE_COMMITMENT_BYTE_SIZE,
539 VERIFICATION_KEY_BYTE_SIZE, io, write_action_without_auth, write_cmx,
540 write_note_ciphertext, write_nullifier, write_value_commitment, write_verification_key,
541 };
542
543 fn encoded_len(write: impl FnOnce(&mut Vec<u8>) -> io::Result<()>) -> usize {
545 let mut buf = Vec::new();
546 write(&mut buf).expect("writing to a Vec cannot fail");
547 buf.len()
548 }
549
550 proptest! {
551 #[test]
559 fn action_size_matches_the_encoding(
560 action in arb_action(
561 NoteVersion::V2,
562 NoteValue::from_raw(1),
563 NoteValue::from_raw(1),
564 ),
565 ) {
566 prop_assert_eq!(
567 encoded_len(|w| write_action_without_auth(w, &action)),
568 ACTION_SIZE
569 );
570
571 prop_assert_eq!(
573 encoded_len(|w| write_value_commitment(w, action.cv_net())),
574 VALUE_COMMITMENT_BYTE_SIZE
575 );
576 prop_assert_eq!(
577 encoded_len(|w| write_nullifier(w, action.nullifier())),
578 NULLIFIER_BYTE_SIZE
579 );
580 prop_assert_eq!(
581 encoded_len(|w| write_verification_key(w, action.rk())),
582 VERIFICATION_KEY_BYTE_SIZE
583 );
584 prop_assert_eq!(
585 encoded_len(|w| write_cmx(w, action.cmx())),
586 NOTE_COMMITMENT_BYTE_SIZE
587 );
588
589 prop_assert_eq!(
592 encoded_len(|w| write_note_ciphertext(w, action.encrypted_note())),
593 EPHEMERAL_KEY_BYTE_SIZE + ENC_CIPHERTEXT_SIZE + OUT_CIPHERTEXT_SIZE
594 );
595 }
596 }
597}