From 56d7391f6d066e09ec18fc77842c677a39518703 Mon Sep 17 00:00:00 2001 From: Henry de Valence Date: Sun, 9 Feb 2020 20:55:52 -0800 Subject: [PATCH] Add convenience methods to Transaction. Because we represent each transaction version as a different variant of the Transaction enum, we end up in a situation where fields that are common to different transaction versions are awkward to access, requiring a match statement with identical match arms. To fix this, this commit adds the following convenience methods: * `Transaction::inputs() -> impl Iterator`; * `Transaction::outputs() -> impl Iterator`; * `Transaction::lock_time() -> LockTime`; * `Transaction::expiry_height() -> Option`; The last returns an `Option` because the field is only present in V3 and V4 transactions. There are some remaining fields that do not get common accessors, because it probably doesn't make sense to access independently of knowing the transaction version: `joinsplit_data`, `shielded_data`, `value_balance`. --- zebra-chain/src/transaction.rs | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/zebra-chain/src/transaction.rs b/zebra-chain/src/transaction.rs index 6148a7f4..d771b498 100644 --- a/zebra-chain/src/transaction.rs +++ b/zebra-chain/src/transaction.rs @@ -90,3 +90,45 @@ pub enum Transaction { joinsplit_data: Option>, }, } + +impl Transaction { + /// Iterate over the transparent inputs of this transaction, if any. + pub fn inputs(&self) -> impl Iterator { + match self { + Transaction::V1 { ref inputs, .. } => inputs.iter(), + Transaction::V2 { ref inputs, .. } => inputs.iter(), + Transaction::V3 { ref inputs, .. } => inputs.iter(), + Transaction::V4 { ref inputs, .. } => inputs.iter(), + } + } + + /// Iterate over the transparent outputs of this transaction, if any. + pub fn outputs(&self) -> impl Iterator { + match self { + Transaction::V1 { ref outputs, .. } => outputs.iter(), + Transaction::V2 { ref outputs, .. } => outputs.iter(), + Transaction::V3 { ref outputs, .. } => outputs.iter(), + Transaction::V4 { ref outputs, .. } => outputs.iter(), + } + } + + /// Get this transaction's lock time. + pub fn lock_time(&self) -> LockTime { + match self { + Transaction::V1 { lock_time, .. } => *lock_time, + Transaction::V2 { lock_time, .. } => *lock_time, + Transaction::V3 { lock_time, .. } => *lock_time, + Transaction::V4 { lock_time, .. } => *lock_time, + } + } + + /// Get this transaction's expiry height, if any. + pub fn expiry_height(&self) -> Option { + match self { + Transaction::V1 { .. } => None, + Transaction::V2 { .. } => None, + Transaction::V3 { expiry_height, .. } => Some(*expiry_height), + Transaction::V4 { expiry_height, .. } => Some(*expiry_height), + } + } +}