zebra_rpc/methods/types/
transaction.rs

1//! Transaction-related types.
2
3use std::sync::Arc;
4
5use crate::methods::arrayhex;
6use chrono::{DateTime, Utc};
7use derive_getters::Getters;
8use derive_new::new;
9use hex::ToHex;
10
11use serde_with::serde_as;
12use zebra_chain::{
13    amount::{self, Amount, NegativeOrZero, NonNegative},
14    block::{self, merkle::AUTH_DIGEST_PLACEHOLDER, Height},
15    orchard,
16    parameters::Network,
17    primitives::ed25519,
18    sapling::ValueCommitment,
19    serialization::ZcashSerialize,
20    transaction::{self, SerializedTransaction, Transaction, UnminedTx, VerifiedUnminedTx},
21    transparent::Script,
22};
23use zebra_consensus::groth16::Description;
24use zebra_script::Sigops;
25use zebra_state::IntoDisk;
26
27use super::super::opthex;
28use super::zec::Zec;
29
30/// Transaction data and fields needed to generate blocks using the `getblocktemplate` RPC.
31#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
32#[serde(bound = "FeeConstraint: amount::Constraint + Clone")]
33pub struct TransactionTemplate<FeeConstraint>
34where
35    FeeConstraint: amount::Constraint + Clone + Copy,
36{
37    /// The hex-encoded serialized data for this transaction.
38    #[serde(with = "hex")]
39    pub(crate) data: SerializedTransaction,
40
41    /// The transaction ID of this transaction.
42    #[serde(with = "hex")]
43    #[getter(copy)]
44    pub(crate) hash: transaction::Hash,
45
46    /// The authorizing data digest of a v5 transaction, or a placeholder for older versions.
47    #[serde(rename = "authdigest")]
48    #[serde(with = "hex")]
49    #[getter(copy)]
50    pub(crate) auth_digest: transaction::AuthDigest,
51
52    /// The transactions in this block template that this transaction depends upon.
53    /// These are 1-based indexes in the `transactions` list.
54    ///
55    /// Zebra's mempool does not support transaction dependencies, so this list is always empty.
56    ///
57    /// We use `u16` because 2 MB blocks are limited to around 39,000 transactions.
58    pub(crate) depends: Vec<u16>,
59
60    /// The fee for this transaction.
61    ///
62    /// Non-coinbase transactions must be `NonNegative`.
63    /// The Coinbase transaction `fee` is the negative sum of the fees of the transactions in
64    /// the block, so their fee must be `NegativeOrZero`.
65    #[getter(copy)]
66    pub(crate) fee: Amount<FeeConstraint>,
67
68    /// The number of transparent signature operations in this transaction.
69    pub(crate) sigops: u32,
70
71    /// Is this transaction required in the block?
72    ///
73    /// Coinbase transactions are required, all other transactions are not.
74    pub(crate) required: bool,
75}
76
77// Convert from a mempool transaction to a non-coinbase transaction template.
78impl From<&VerifiedUnminedTx> for TransactionTemplate<NonNegative> {
79    fn from(tx: &VerifiedUnminedTx) -> Self {
80        assert!(
81            !tx.transaction.transaction.is_coinbase(),
82            "unexpected coinbase transaction in mempool"
83        );
84
85        Self {
86            data: tx.transaction.transaction.as_ref().into(),
87            hash: tx.transaction.id.mined_id(),
88            auth_digest: tx
89                .transaction
90                .id
91                .auth_digest()
92                .unwrap_or(AUTH_DIGEST_PLACEHOLDER),
93
94            // Always empty, not supported by Zebra's mempool.
95            depends: Vec::new(),
96
97            fee: tx.miner_fee,
98
99            sigops: tx.sigops,
100
101            // Zebra does not require any transactions except the coinbase transaction.
102            required: false,
103        }
104    }
105}
106
107impl From<VerifiedUnminedTx> for TransactionTemplate<NonNegative> {
108    fn from(tx: VerifiedUnminedTx) -> Self {
109        Self::from(&tx)
110    }
111}
112
113impl TransactionTemplate<NegativeOrZero> {
114    /// Convert from a generated coinbase transaction into a coinbase transaction template.
115    ///
116    /// `miner_fee` is the total miner fees for the block, excluding newly created block rewards.
117    //
118    // TODO: use a different type for generated coinbase transactions?
119    pub fn from_coinbase(tx: &UnminedTx, miner_fee: Amount<NonNegative>) -> Self {
120        assert!(
121            tx.transaction.is_coinbase(),
122            "invalid generated coinbase transaction: \
123             must have exactly one input, which must be a coinbase input",
124        );
125
126        let miner_fee = (-miner_fee)
127            .constrain()
128            .expect("negating a NonNegative amount always results in a valid NegativeOrZero");
129
130        Self {
131            data: tx.transaction.as_ref().into(),
132            hash: tx.id.mined_id(),
133            auth_digest: tx.id.auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER),
134
135            // Always empty, coinbase transactions never have inputs.
136            depends: Vec::new(),
137
138            fee: miner_fee,
139
140            sigops: tx.sigops().expect("sigops count should be valid"),
141
142            // Zcash requires a coinbase transaction.
143            required: true,
144        }
145    }
146}
147
148/// A Transaction object as returned by `getrawtransaction` and `getblock` RPC
149/// requests.
150#[allow(clippy::too_many_arguments)]
151#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
152pub struct TransactionObject {
153    /// Whether specified block is in the active chain or not (only present with
154    /// explicit "blockhash" argument)
155    #[serde(skip_serializing_if = "Option::is_none")]
156    #[getter(copy)]
157    pub(crate) in_active_chain: Option<bool>,
158    /// The raw transaction, encoded as hex bytes.
159    #[serde(with = "hex")]
160    pub(crate) hex: SerializedTransaction,
161    /// The height of the block in the best chain that contains the tx or `None` if the tx is in
162    /// the mempool.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    #[getter(copy)]
165    pub(crate) height: Option<u32>,
166    /// The height diff between the block containing the tx and the best chain tip + 1 or `None`
167    /// if the tx is in the mempool.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    #[getter(copy)]
170    pub(crate) confirmations: Option<u32>,
171
172    /// Transparent inputs of the transaction.
173    #[serde(rename = "vin")]
174    pub(crate) inputs: Vec<Input>,
175
176    /// Transparent outputs of the transaction.
177    #[serde(rename = "vout")]
178    pub(crate) outputs: Vec<Output>,
179
180    /// Sapling spends of the transaction.
181    #[serde(rename = "vShieldedSpend")]
182    pub(crate) shielded_spends: Vec<ShieldedSpend>,
183
184    /// Sapling outputs of the transaction.
185    #[serde(rename = "vShieldedOutput")]
186    pub(crate) shielded_outputs: Vec<ShieldedOutput>,
187
188    /// Transparent outputs of the transaction.
189    #[serde(rename = "vjoinsplit")]
190    pub(crate) joinsplits: Vec<JoinSplit>,
191
192    /// Sapling binding signature of the transaction.
193    #[serde(
194        skip_serializing_if = "Option::is_none",
195        with = "opthex",
196        default,
197        rename = "bindingSig"
198    )]
199    #[getter(copy)]
200    pub(crate) binding_sig: Option<[u8; 64]>,
201
202    /// JoinSplit public key of the transaction.
203    #[serde(
204        skip_serializing_if = "Option::is_none",
205        with = "opthex",
206        default,
207        rename = "joinSplitPubKey"
208    )]
209    #[getter(copy)]
210    pub(crate) joinsplit_pub_key: Option<[u8; 32]>,
211
212    /// JoinSplit signature of the transaction.
213    #[serde(
214        skip_serializing_if = "Option::is_none",
215        with = "opthex",
216        default,
217        rename = "joinSplitSig"
218    )]
219    #[getter(copy)]
220    pub(crate) joinsplit_sig: Option<[u8; ed25519::Signature::BYTE_SIZE]>,
221
222    /// Orchard actions of the transaction.
223    #[serde(rename = "orchard", skip_serializing_if = "Option::is_none")]
224    pub(crate) orchard: Option<Orchard>,
225
226    /// The net value of Sapling Spends minus Outputs in ZEC
227    #[serde(rename = "valueBalance", skip_serializing_if = "Option::is_none")]
228    #[getter(copy)]
229    pub(crate) value_balance: Option<f64>,
230
231    /// The net value of Sapling Spends minus Outputs in zatoshis
232    #[serde(rename = "valueBalanceZat", skip_serializing_if = "Option::is_none")]
233    #[getter(copy)]
234    pub(crate) value_balance_zat: Option<i64>,
235
236    /// The size of the transaction in bytes.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    #[getter(copy)]
239    pub(crate) size: Option<i64>,
240
241    /// The time the transaction was included in a block.
242    #[serde(skip_serializing_if = "Option::is_none")]
243    #[getter(copy)]
244    pub(crate) time: Option<i64>,
245
246    /// The transaction identifier, encoded as hex bytes.
247    #[serde(with = "hex")]
248    #[getter(copy)]
249    pub txid: transaction::Hash,
250
251    /// The transaction's auth digest. For pre-v5 transactions this will be
252    /// ffff..ffff
253    #[serde(
254        rename = "authdigest",
255        with = "opthex",
256        skip_serializing_if = "Option::is_none",
257        default
258    )]
259    #[getter(copy)]
260    pub(crate) auth_digest: Option<transaction::AuthDigest>,
261
262    /// Whether the overwintered flag is set
263    pub(crate) overwintered: bool,
264
265    /// The version of the transaction.
266    pub(crate) version: u32,
267
268    /// The version group ID.
269    #[serde(
270        rename = "versiongroupid",
271        with = "opthex",
272        skip_serializing_if = "Option::is_none",
273        default
274    )]
275    pub(crate) version_group_id: Option<Vec<u8>>,
276
277    /// The lock time
278    #[serde(rename = "locktime")]
279    pub(crate) lock_time: u32,
280
281    /// The block height after which the transaction expires
282    #[serde(rename = "expiryheight", skip_serializing_if = "Option::is_none")]
283    #[getter(copy)]
284    pub(crate) expiry_height: Option<Height>,
285
286    /// The block hash
287    #[serde(
288        rename = "blockhash",
289        with = "opthex",
290        skip_serializing_if = "Option::is_none",
291        default
292    )]
293    #[getter(copy)]
294    pub(crate) block_hash: Option<block::Hash>,
295
296    /// The block height after which the transaction expires
297    #[serde(rename = "blocktime", skip_serializing_if = "Option::is_none")]
298    #[getter(copy)]
299    pub(crate) block_time: Option<i64>,
300}
301
302/// The transparent input of a transaction.
303#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
304#[serde(untagged)]
305pub enum Input {
306    /// A coinbase input.
307    Coinbase {
308        /// The coinbase scriptSig as hex.
309        #[serde(with = "hex")]
310        coinbase: Vec<u8>,
311        /// The script sequence number.
312        sequence: u32,
313    },
314    /// A non-coinbase input.
315    NonCoinbase {
316        /// The transaction id.
317        txid: String,
318        /// The vout index.
319        vout: u32,
320        /// The script.
321        #[serde(rename = "scriptSig")]
322        script_sig: ScriptSig,
323        /// The script sequence number.
324        sequence: u32,
325        /// The value of the output being spent in ZEC.
326        #[serde(skip_serializing_if = "Option::is_none")]
327        value: Option<f64>,
328        /// The value of the output being spent, in zats, named to match zcashd.
329        #[serde(rename = "valueSat", skip_serializing_if = "Option::is_none")]
330        value_zat: Option<i64>,
331        /// The address of the output being spent.
332        #[serde(skip_serializing_if = "Option::is_none")]
333        address: Option<String>,
334    },
335}
336
337/// The transparent output of a transaction.
338#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
339pub struct Output {
340    /// The value in ZEC.
341    value: f64,
342    /// The value in zats.
343    #[serde(rename = "valueZat")]
344    value_zat: i64,
345    /// index.
346    n: u32,
347    /// The scriptPubKey.
348    #[serde(rename = "scriptPubKey")]
349    script_pub_key: ScriptPubKey,
350}
351
352/// The scriptPubKey of a transaction output.
353#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
354pub struct ScriptPubKey {
355    /// the asm.
356    // #9330: The `asm` field is not currently populated.
357    asm: String,
358    /// the hex.
359    #[serde(with = "hex")]
360    hex: Script,
361    /// The required sigs.
362    #[serde(rename = "reqSigs")]
363    #[serde(default)]
364    #[serde(skip_serializing_if = "Option::is_none")]
365    #[getter(copy)]
366    req_sigs: Option<u32>,
367    /// The type, eg 'pubkeyhash'.
368    // #9330: The `type` field is not currently populated.
369    r#type: String,
370    /// The addresses.
371    #[serde(default)]
372    #[serde(skip_serializing_if = "Option::is_none")]
373    addresses: Option<Vec<String>>,
374}
375
376/// The scriptSig of a transaction input.
377#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
378pub struct ScriptSig {
379    /// The asm.
380    // #9330: The `asm` field is not currently populated.
381    asm: String,
382    /// The hex.
383    hex: Script,
384}
385
386/// A Sprout JoinSplit of a transaction.
387#[allow(clippy::too_many_arguments)]
388#[serde_with::serde_as]
389#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
390pub struct JoinSplit {
391    /// Public input value in ZEC.
392    #[serde(rename = "vpub_old")]
393    old_public_value: f64,
394    /// Public input value in zatoshis.
395    #[serde(rename = "vpub_oldZat")]
396    old_public_value_zat: i64,
397    /// Public input value in ZEC.
398    #[serde(rename = "vpub_new")]
399    new_public_value: f64,
400    /// Public input value in zatoshis.
401    #[serde(rename = "vpub_newZat")]
402    new_public_value_zat: i64,
403    /// Merkle root of the Sprout note commitment tree.
404    #[serde(with = "hex")]
405    #[getter(copy)]
406    anchor: [u8; 32],
407    /// The nullifier of the input notes.
408    #[serde_as(as = "Vec<serde_with::hex::Hex>")]
409    nullifiers: Vec<[u8; 32]>,
410    /// The commitments of the output notes.
411    #[serde_as(as = "Vec<serde_with::hex::Hex>")]
412    commitments: Vec<[u8; 32]>,
413    /// The onetime public key used to encrypt the ciphertexts
414    #[serde(rename = "onetimePubKey")]
415    #[serde(with = "hex")]
416    #[getter(copy)]
417    one_time_pubkey: [u8; 32],
418    /// The random seed
419    #[serde(rename = "randomSeed")]
420    #[serde(with = "hex")]
421    #[getter(copy)]
422    random_seed: [u8; 32],
423    /// The input notes MACs.
424    #[serde_as(as = "Vec<serde_with::hex::Hex>")]
425    macs: Vec<[u8; 32]>,
426    /// A zero-knowledge proof using the Sprout circuit.
427    #[serde(with = "hex")]
428    proof: Vec<u8>,
429    /// The output notes ciphertexts.
430    #[serde_as(as = "Vec<serde_with::hex::Hex>")]
431    ciphertexts: Vec<Vec<u8>>,
432}
433
434/// A Sapling spend of a transaction.
435#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
436pub struct ShieldedSpend {
437    /// Value commitment to the input note.
438    #[serde(with = "hex")]
439    #[getter(skip)]
440    cv: ValueCommitment,
441    /// Merkle root of the Sapling note commitment tree.
442    #[serde(with = "hex")]
443    #[getter(copy)]
444    anchor: [u8; 32],
445    /// The nullifier of the input note.
446    #[serde(with = "hex")]
447    #[getter(copy)]
448    nullifier: [u8; 32],
449    /// The randomized public key for spendAuthSig.
450    #[serde(with = "hex")]
451    #[getter(copy)]
452    rk: [u8; 32],
453    /// A zero-knowledge proof using the Sapling Spend circuit.
454    #[serde(with = "hex")]
455    #[getter(copy)]
456    proof: [u8; 192],
457    /// A signature authorizing this Spend.
458    #[serde(rename = "spendAuthSig", with = "hex")]
459    #[getter(copy)]
460    spend_auth_sig: [u8; 64],
461}
462
463// We can't use `#[getter(copy)]` as upstream `sapling_crypto::note::ValueCommitment` is not `Copy`.
464impl ShieldedSpend {
465    /// The value commitment to the input note.
466    pub fn cv(&self) -> ValueCommitment {
467        self.cv.clone()
468    }
469}
470
471/// A Sapling output of a transaction.
472#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
473pub struct ShieldedOutput {
474    /// Value commitment to the input note.
475    #[serde(with = "hex")]
476    #[getter(skip)]
477    cv: ValueCommitment,
478    /// The u-coordinate of the note commitment for the output note.
479    #[serde(rename = "cmu", with = "hex")]
480    cm_u: [u8; 32],
481    /// A Jubjub public key.
482    #[serde(rename = "ephemeralKey", with = "hex")]
483    ephemeral_key: [u8; 32],
484    /// The output note encrypted to the recipient.
485    #[serde(rename = "encCiphertext", with = "arrayhex")]
486    enc_ciphertext: [u8; 580],
487    /// A ciphertext enabling the sender to recover the output note.
488    #[serde(rename = "outCiphertext", with = "hex")]
489    out_ciphertext: [u8; 80],
490    /// A zero-knowledge proof using the Sapling Output circuit.
491    #[serde(with = "hex")]
492    proof: [u8; 192],
493}
494
495// We can't use `#[getter(copy)]` as upstream `sapling_crypto::note::ValueCommitment` is not `Copy`.
496impl ShieldedOutput {
497    /// The value commitment to the output note.
498    pub fn cv(&self) -> ValueCommitment {
499        self.cv.clone()
500    }
501}
502
503/// Object with Orchard-specific information.
504#[serde_with::serde_as]
505#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
506pub struct Orchard {
507    /// Array of Orchard actions.
508    actions: Vec<OrchardAction>,
509    /// The net value of Orchard Actions in ZEC.
510    #[serde(rename = "valueBalance")]
511    value_balance: f64,
512    /// The net value of Orchard Actions in zatoshis.
513    #[serde(rename = "valueBalanceZat")]
514    value_balance_zat: i64,
515    /// The flags.
516    #[serde(skip_serializing_if = "Option::is_none")]
517    flags: Option<OrchardFlags>,
518    /// A root of the Orchard note commitment tree at some block height in the past
519    #[serde_as(as = "Option<serde_with::hex::Hex>")]
520    #[serde(skip_serializing_if = "Option::is_none")]
521    #[getter(copy)]
522    anchor: Option<[u8; 32]>,
523    /// Encoding of aggregated zk-SNARK proofs for Orchard Actions
524    #[serde_as(as = "Option<serde_with::hex::Hex>")]
525    #[serde(skip_serializing_if = "Option::is_none")]
526    proof: Option<Vec<u8>>,
527    /// An Orchard binding signature on the SIGHASH transaction hash
528    #[serde(rename = "bindingSig")]
529    #[serde(skip_serializing_if = "Option::is_none")]
530    #[serde_as(as = "Option<serde_with::hex::Hex>")]
531    #[getter(copy)]
532    binding_sig: Option<[u8; 64]>,
533}
534
535/// Object with Orchard-specific information.
536#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
537pub struct OrchardFlags {
538    /// Whether Orchard outputs are enabled.
539    #[serde(rename = "enableOutputs")]
540    enable_outputs: bool,
541    /// Whether Orchard spends are enabled.
542    #[serde(rename = "enableSpends")]
543    enable_spends: bool,
544}
545
546/// The Orchard action of a transaction.
547#[allow(clippy::too_many_arguments)]
548#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
549pub struct OrchardAction {
550    /// A value commitment to the net value of the input note minus the output note.
551    #[serde(with = "hex")]
552    cv: [u8; 32],
553    /// The nullifier of the input note.
554    #[serde(with = "hex")]
555    nullifier: [u8; 32],
556    /// The randomized validating key for spendAuthSig.
557    #[serde(with = "hex")]
558    rk: [u8; 32],
559    /// The x-coordinate of the note commitment for the output note.
560    #[serde(rename = "cmx", with = "hex")]
561    cm_x: [u8; 32],
562    /// An encoding of an ephemeral Pallas public key.
563    #[serde(rename = "ephemeralKey", with = "hex")]
564    ephemeral_key: [u8; 32],
565    /// The output note encrypted to the recipient.
566    #[serde(rename = "encCiphertext", with = "arrayhex")]
567    enc_ciphertext: [u8; 580],
568    /// A ciphertext enabling the sender to recover the output note.
569    #[serde(rename = "spendAuthSig", with = "hex")]
570    spend_auth_sig: [u8; 64],
571    /// A signature authorizing the spend in this Action.
572    #[serde(rename = "outCiphertext", with = "hex")]
573    out_ciphertext: [u8; 80],
574}
575
576impl Default for TransactionObject {
577    fn default() -> Self {
578        Self {
579            hex: SerializedTransaction::from(
580                [0u8; zebra_chain::transaction::MIN_TRANSPARENT_TX_SIZE as usize].to_vec(),
581            ),
582            height: Option::default(),
583            confirmations: Option::default(),
584            inputs: Vec::new(),
585            outputs: Vec::new(),
586            shielded_spends: Vec::new(),
587            shielded_outputs: Vec::new(),
588            joinsplits: Vec::new(),
589            orchard: None,
590            binding_sig: None,
591            joinsplit_pub_key: None,
592            joinsplit_sig: None,
593            value_balance: None,
594            value_balance_zat: None,
595            size: None,
596            time: None,
597            txid: transaction::Hash::from([0u8; 32]),
598            in_active_chain: None,
599            auth_digest: None,
600            overwintered: false,
601            version: 4,
602            version_group_id: None,
603            lock_time: 0,
604            expiry_height: None,
605            block_hash: None,
606            block_time: None,
607        }
608    }
609}
610
611impl TransactionObject {
612    /// Converts `tx` and `height` into a new `GetRawTransaction` in the `verbose` format.
613    #[allow(clippy::unwrap_in_result)]
614    #[allow(clippy::too_many_arguments)]
615    pub fn from_transaction(
616        tx: Arc<Transaction>,
617        height: Option<block::Height>,
618        confirmations: Option<u32>,
619        network: &Network,
620        block_time: Option<DateTime<Utc>>,
621        block_hash: Option<block::Hash>,
622        in_active_chain: Option<bool>,
623        txid: transaction::Hash,
624    ) -> Self {
625        let block_time = block_time.map(|bt| bt.timestamp());
626        Self {
627            hex: tx.clone().into(),
628            height: height.map(|height| height.0),
629            confirmations,
630            inputs: tx
631                .inputs()
632                .iter()
633                .map(|input| match input {
634                    zebra_chain::transparent::Input::Coinbase { sequence, .. } => Input::Coinbase {
635                        coinbase: input
636                            .coinbase_script()
637                            .expect("we know it is a valid coinbase script"),
638                        sequence: *sequence,
639                    },
640                    zebra_chain::transparent::Input::PrevOut {
641                        sequence,
642                        unlock_script,
643                        outpoint,
644                    } => Input::NonCoinbase {
645                        txid: outpoint.hash.encode_hex(),
646                        vout: outpoint.index,
647                        script_sig: ScriptSig {
648                            asm: "".to_string(),
649                            hex: unlock_script.clone(),
650                        },
651                        sequence: *sequence,
652                        value: None,
653                        value_zat: None,
654                        address: None,
655                    },
656                })
657                .collect(),
658            outputs: tx
659                .outputs()
660                .iter()
661                .enumerate()
662                .map(|output| {
663                    // Parse the scriptPubKey to find destination addresses.
664                    let (addresses, req_sigs) = output
665                        .1
666                        .address(network)
667                        .map(|address| (vec![address.to_string()], 1))
668                        .unzip();
669
670                    Output {
671                        value: Zec::from(output.1.value).lossy_zec(),
672                        value_zat: output.1.value.zatoshis(),
673                        n: output.0 as u32,
674                        script_pub_key: ScriptPubKey {
675                            // TODO: Fill this out.
676                            asm: "".to_string(),
677                            hex: output.1.lock_script.clone(),
678                            req_sigs,
679                            // TODO: Fill this out.
680                            r#type: "".to_string(),
681                            addresses,
682                        },
683                    }
684                })
685                .collect(),
686            shielded_spends: tx
687                .sapling_spends_per_anchor()
688                .map(|spend| {
689                    let mut anchor = spend.per_spend_anchor.as_bytes();
690                    anchor.reverse();
691
692                    let mut nullifier = spend.nullifier.as_bytes();
693                    nullifier.reverse();
694
695                    let mut rk: [u8; 32] = spend.clone().rk.into();
696                    rk.reverse();
697
698                    let spend_auth_sig: [u8; 64] = spend.spend_auth_sig.into();
699
700                    ShieldedSpend {
701                        cv: spend.cv.clone(),
702                        anchor,
703                        nullifier,
704                        rk,
705                        proof: spend.proof().0,
706                        spend_auth_sig,
707                    }
708                })
709                .collect(),
710            shielded_outputs: tx
711                .sapling_outputs()
712                .map(|output| {
713                    let mut cm_u: [u8; 32] = output.cm_u.to_bytes();
714                    cm_u.reverse();
715                    let mut ephemeral_key: [u8; 32] = output.ephemeral_key.into();
716                    ephemeral_key.reverse();
717                    let enc_ciphertext: [u8; 580] = output.enc_ciphertext.into();
718                    let out_ciphertext: [u8; 80] = output.out_ciphertext.into();
719
720                    ShieldedOutput {
721                        cv: output.cv.clone(),
722                        cm_u,
723                        ephemeral_key,
724                        enc_ciphertext,
725                        out_ciphertext,
726                        proof: output.proof().0,
727                    }
728                })
729                .collect(),
730            joinsplits: tx
731                .sprout_joinsplits()
732                .map(|joinsplit| {
733                    let mut ephemeral_key_bytes: [u8; 32] = joinsplit.ephemeral_key.to_bytes();
734                    ephemeral_key_bytes.reverse();
735
736                    JoinSplit {
737                        old_public_value: Zec::from(joinsplit.vpub_old).lossy_zec(),
738                        old_public_value_zat: joinsplit.vpub_old.zatoshis(),
739                        new_public_value: Zec::from(joinsplit.vpub_new).lossy_zec(),
740                        new_public_value_zat: joinsplit.vpub_new.zatoshis(),
741                        anchor: joinsplit.anchor.bytes_in_display_order(),
742                        nullifiers: joinsplit
743                            .nullifiers
744                            .iter()
745                            .map(|n| n.bytes_in_display_order())
746                            .collect(),
747                        commitments: joinsplit
748                            .commitments
749                            .iter()
750                            .map(|c| c.bytes_in_display_order())
751                            .collect(),
752                        one_time_pubkey: ephemeral_key_bytes,
753                        random_seed: joinsplit.random_seed.bytes_in_display_order(),
754                        macs: joinsplit
755                            .vmacs
756                            .iter()
757                            .map(|m| m.bytes_in_display_order())
758                            .collect(),
759                        proof: joinsplit.zkproof.unwrap_or_default(),
760                        ciphertexts: joinsplit
761                            .enc_ciphertexts
762                            .iter()
763                            .map(|c| c.zcash_serialize_to_vec().unwrap_or_default())
764                            .collect(),
765                    }
766                })
767                .collect(),
768            value_balance: Some(Zec::from(tx.sapling_value_balance().sapling_amount()).lossy_zec()),
769            value_balance_zat: Some(tx.sapling_value_balance().sapling_amount().zatoshis()),
770            orchard: Some(Orchard {
771                actions: tx
772                    .orchard_actions()
773                    .collect::<Vec<_>>()
774                    .iter()
775                    .map(|action| {
776                        let spend_auth_sig: [u8; 64] = tx
777                            .orchard_shielded_data()
778                            .and_then(|shielded_data| {
779                                shielded_data
780                                    .actions
781                                    .iter()
782                                    .find(|authorized_action| authorized_action.action == **action)
783                                    .map(|authorized_action| {
784                                        authorized_action.spend_auth_sig.into()
785                                    })
786                            })
787                            .unwrap_or([0; 64]);
788
789                        let cv: [u8; 32] = action.cv.into();
790                        let nullifier: [u8; 32] = action.nullifier.into();
791                        let rk: [u8; 32] = action.rk.into();
792                        let cm_x: [u8; 32] = action.cm_x.into();
793                        let ephemeral_key: [u8; 32] = action.ephemeral_key.into();
794                        let enc_ciphertext: [u8; 580] = action.enc_ciphertext.into();
795                        let out_ciphertext: [u8; 80] = action.out_ciphertext.into();
796
797                        OrchardAction {
798                            cv,
799                            nullifier,
800                            rk,
801                            cm_x,
802                            ephemeral_key,
803                            enc_ciphertext,
804                            spend_auth_sig,
805                            out_ciphertext,
806                        }
807                    })
808                    .collect(),
809                value_balance: Zec::from(tx.orchard_value_balance().orchard_amount()).lossy_zec(),
810                value_balance_zat: tx.orchard_value_balance().orchard_amount().zatoshis(),
811                flags: tx.orchard_shielded_data().map(|data| {
812                    OrchardFlags::new(
813                        data.flags.contains(orchard::Flags::ENABLE_OUTPUTS),
814                        data.flags.contains(orchard::Flags::ENABLE_SPENDS),
815                    )
816                }),
817                anchor: tx
818                    .orchard_shielded_data()
819                    .map(|data| data.shared_anchor.bytes_in_display_order()),
820                proof: tx
821                    .orchard_shielded_data()
822                    .map(|data| data.proof.bytes_in_display_order()),
823                binding_sig: tx
824                    .orchard_shielded_data()
825                    .map(|data| data.binding_sig.into()),
826            }),
827            binding_sig: tx.sapling_binding_sig().map(|raw_sig| raw_sig.into()),
828            joinsplit_pub_key: tx.joinsplit_pub_key().map(|raw_key| {
829                // Display order is reversed in the RPC output.
830                let mut key: [u8; 32] = raw_key.into();
831                key.reverse();
832                key
833            }),
834            joinsplit_sig: tx.joinsplit_sig().map(|raw_sig| raw_sig.into()),
835            size: tx.as_bytes().len().try_into().ok(),
836            time: block_time,
837            txid,
838            in_active_chain,
839            auth_digest: tx.auth_digest(),
840            overwintered: tx.is_overwintered(),
841            version: tx.version(),
842            version_group_id: tx.version_group_id().map(|id| id.to_be_bytes().to_vec()),
843            lock_time: tx.raw_lock_time(),
844            expiry_height: tx.expiry_height(),
845            block_hash,
846            block_time,
847        }
848    }
849}