Skip to main content

zebra_rpc/
methods.rs

1//! Zebra supported RPC methods.
2//!
3//! Based on the [`zcashd` RPC methods](https://zcash.github.io/rpc/)
4//! as used by `lightwalletd.`
5//!
6//! Some parts of the `zcashd` RPC documentation are outdated.
7//! So this implementation follows the `zcashd` server and `lightwalletd` client implementations.
8//!
9//! # Developing this module
10//!
11//! If RPCs are added or changed, ensure the following:
12//!
13//! - Request types can be instantiated from dependent crates, and
14//!   response types are fully-readable (up to each leaf component), meaning
15//!   every field on response types can be read, and any types used in response
16//!   types has an appropriate API for either directly accessing their fields, or
17//!   has an appropriate API for accessing any relevant data.
18//!
19//!   This should be achieved, wherever possible, by:
20//!   - Using `derive(Getters, new)` to keep new code succinct and consistent.
21//!     Ensure that fields on response types that implement `Copy` are tagged
22//!     with `#[getter(copy)]` field attributes to avoid unnecessary references.
23//!     This should be easily noticeable in the `serialization_tests` test crate, where
24//!     any fields implementing `Copy` but not tagged with `#[getter(Copy)]` will
25//!     be returned by reference, and will require dereferencing with the dereference
26//!     operator, `*`. If a value returned by a getter method requires dereferencing,
27//!     the associated field in the response type should likely be tagged with `#[getter(Copy)]`.
28//!   - If a field is added, use `#[new(...)]` so that it's not added to the
29//!     constructor. If that is unavoidable, then it will require a major
30//!     version bump.
31//!
32//! - A test has been added to the `serialization_tests` test crate to ensure the above.
33
34use std::{
35    cmp,
36    collections::{HashMap, HashSet},
37    fmt,
38    ops::RangeInclusive,
39    sync::{Arc, Mutex},
40    time::{Duration, Instant},
41};
42
43use chrono::Utc;
44use derive_getters::Getters;
45use derive_new::new;
46use futures::{stream::FuturesOrdered, StreamExt, TryFutureExt};
47use hex::{FromHex, ToHex};
48use indexmap::IndexMap;
49use jsonrpsee::core::{async_trait, RpcResult as Result};
50use jsonrpsee_proc_macros::rpc;
51use jsonrpsee_types::{ErrorCode, ErrorObject, ErrorObjectOwned};
52use schemars::JsonSchema;
53use tokio::{
54    sync::{broadcast, mpsc, watch},
55    task::JoinHandle,
56};
57use tower::ServiceExt;
58use tracing::Instrument;
59
60use zcash_address::{unified::Encoding, TryFromAddress};
61use zcash_protocol::consensus::{self, Parameters};
62use zebra_chain::{
63    amount::{Amount, NegativeAllowed, NonNegative},
64    block::{self, Block, Commitment, Height, SerializedBlock, TryIntoHeight},
65    chain_sync_status::ChainSyncStatus,
66    chain_tip::{ChainTip, NetworkChainTipHeightEstimator},
67    parameters::{
68        subsidy::{
69            block_subsidy, founders_reward, funding_stream_address, funding_stream_values,
70            miner_subsidy, nsm_value_balance_before, FundingStreamReceiver,
71        },
72        ConsensusBranchId, Network, NetworkUpgrade, GENESIS_PREVIOUS_BLOCK_HASH,
73    },
74    serialization::{
75        BytesInDisplayOrder, DateTime32, Duration32, ZcashDeserialize, ZcashSerialize,
76    },
77    subtree::NoteCommitmentSubtreeIndex,
78    transaction::{self, SerializedTransaction, Transaction, UnminedTx},
79    transparent::{self, Address, OutputIndex},
80    value_balance::ValueBalance,
81    work::{
82        difficulty::{CompactDifficulty, ExpandedDifficulty, ParameterDifficulty, U256},
83        equihash::Solution,
84    },
85};
86use zebra_consensus::{router::service_trait::BlockVerifierService, RouterError};
87use zebra_network::{address_book_peers::AddressBookPeers, types::PeerServices, PeerSocketAddr};
88use zebra_node_services::mempool::{self, CreatedOrSpent, MempoolService, MempoolTxSubscriber};
89use zebra_state::{
90    AnyTx, HashOrHeight, OutputLocation, ReadRequest, ReadResponse, ReadState as ReadStateService,
91    State as StateService, TransactionLocation,
92};
93
94use crate::{
95    client::Treestate,
96    config,
97    methods::types::{
98        validate_address::validate_address, z_validate_address::z_validate_address, zec::Zec,
99    },
100    queue::Queue,
101    server::{
102        self,
103        error::{MapError, OkOrError},
104    },
105};
106
107pub(crate) mod hex_data;
108pub(crate) mod trees;
109pub(crate) mod types;
110
111use hex_data::HexData;
112use trees::{GetSubtreesByIndexResponse, GetTreestateResponse, SubtreeRpcData};
113use types::{
114    get_block_template::{
115        constants::{
116            DEFAULT_SOLUTION_RATE_WINDOW_SIZE, MEMPOOL_LONG_POLL_INTERVAL,
117            ZCASHD_FUNDING_STREAM_ORDER,
118        },
119        precompute,
120        proposal::proposal_block_from_template,
121        BlockTemplateResponse, BlockTemplateTimeSource, GetBlockTemplateHandler,
122        GetBlockTemplateParameters, GetBlockTemplateResponse, MinerParams,
123    },
124    get_blockchain_info::GetBlockchainInfoBalance,
125    get_mempool_info::GetMempoolInfoResponse,
126    get_mining_info::GetMiningInfoResponse,
127    get_raw_mempool::{self, GetRawMempoolResponse},
128    get_standard_fee::{standard_fee, GetStandardFeeResponse},
129    long_poll::{LongPollId, LongPollInput},
130    network_info::{GetNetworkInfoResponse, NetworkInfo},
131    peer_info::PeerInfo,
132    submit_block::{
133        SubmitBlockErrorResponse, SubmitBlockParameters, SubmitBlockResponse, SUBMIT_BLOCK_TIMEOUT,
134        SUBMIT_BLOCK_VERIFY_TIMEOUT,
135    },
136    subsidy::GetBlockSubsidyResponse,
137    transaction::TransactionObject,
138    unified_address::ZListUnifiedReceiversResponse,
139    validate_address::ValidateAddressResponse,
140    z_validate_address::ZValidateAddressResponse,
141};
142
143include!(concat!(env!("OUT_DIR"), "/rpc_openrpc.rs"));
144
145// TODO: Review the parameter descriptions below, and update them as needed:
146// https://github.com/ZcashFoundation/zebra/issues/10320
147pub(super) const PARAM_VERBOSE_DESC: &str =
148    "Boolean flag to indicate verbosity, true for a json object, false for hex encoded data.";
149pub(super) const PARAM_POOL_DESC: &str =
150    "The pool from which subtrees should be returned. Either \"sapling\" or \"orchard\".";
151pub(super) const PARAM_START_INDEX_DESC: &str =
152    "The index of the first 2^16-leaf subtree to return.";
153pub(super) const PARAM_LIMIT_DESC: &str = "The maximum number of subtrees to return.";
154pub(super) const PARAM_REQUEST_DESC: &str = "The request object containing the parameters.";
155pub(super) const PARAM_INDEX_DESC: &str = "The index of the subtree to return.";
156pub(super) const PARAM_RAW_TRANSACTION_HEX_DESC: &str = "The hex-encoded raw transaction bytes.";
157#[allow(non_upper_case_globals)]
158pub(super) const PARAM__ALLOW_HIGH_FEES_DESC: &str = "Whether to allow high fees.";
159pub(super) const PARAM_NUM_BLOCKS_DESC: &str = "The number of blocks to return.";
160pub(super) const PARAM_HEIGHT_DESC: &str = "The height of the block to return.";
161pub(super) const PARAM_COMMAND_DESC: &str = "The command to execute.";
162#[allow(non_upper_case_globals)]
163pub(super) const PARAM__PARAMETERS_DESC: &str = "The parameters for the command.";
164pub(super) const PARAM_BLOCK_HASH_DESC: &str = "The hash of the block to return.";
165pub(super) const PARAM_ADDRESS_DESC: &str = "The address to return.";
166pub(super) const PARAM_ADDRESS_STRINGS_DESC: &str = "The addresses to return.";
167pub(super) const PARAM_ADDR_DESC: &str = "The address to return.";
168pub(super) const PARAM_HEX_DATA_DESC: &str = "The hex-encoded data to return.";
169pub(super) const PARAM_TXID_DESC: &str = "The transaction ID to return.";
170pub(super) const PARAM_HASH_OR_HEIGHT_DESC: &str = "The block hash or height to return.";
171pub(super) const PARAM_PARAMETERS_DESC: &str = "The parameters for the command.";
172pub(super) const PARAM_VERBOSITY_DESC: &str = "Whether to include verbose output.";
173pub(super) const PARAM_N_DESC: &str = "The output index in the transaction.";
174pub(super) const PARAM_INCLUDE_MEMPOOL_DESC: &str =
175    "Whether to include mempool transactions in the response.";
176
177#[cfg(test)]
178mod tests;
179
180#[rpc(server)]
181/// RPC method signatures.
182pub trait Rpc {
183    /// Returns software information from the RPC server, as a [`GetInfo`] JSON struct.
184    ///
185    /// zcashd reference: [`getinfo`](https://zcash.github.io/rpc/getinfo.html)
186    /// method: post
187    /// tags: control
188    ///
189    /// # Notes
190    ///
191    /// [The zcashd reference](https://zcash.github.io/rpc/getinfo.html) might not show some fields
192    /// in Zebra's [`GetInfo`]. Zebra uses the field names and formats from the
193    /// [zcashd code](https://github.com/zcash/zcash/blob/v4.6.0-1/src/rpc/misc.cpp#L86-L87).
194    ///
195    /// Some fields from the zcashd reference are missing from Zebra's [`GetInfo`]. It only contains the fields
196    /// [required for lightwalletd support.](https://github.com/zcash/lightwalletd/blob/v0.4.9/common/common.go#L91-L95)
197    #[method(name = "getinfo")]
198    async fn get_info(&self) -> Result<GetInfoResponse>;
199
200    /// Returns end of support information for this node release, as a
201    /// [`GetDeprecationInfoResponse`] JSON struct.
202    ///
203    /// zcashd reference: [`getdeprecationinfo`](https://zcash.github.io/rpc/getdeprecationinfo.html)
204    /// method: post
205    /// tags: network
206    ///
207    /// # Notes
208    ///
209    /// As in zcashd, the `end_of_service` object is only present on Mainnet, where end of
210    /// support is enforced. Zebra reports the estimated last height this release supports in
211    /// `end_of_service.block_height`; the node halts when the tip goes past it.
212    ///
213    /// Some fields from the zcashd reference are missing from Zebra's response: `version` and
214    /// `subversion` are available from `getinfo`, `deprecationheight` is deprecated in zcashd,
215    /// and Zebra does not have zcashd's feature deprecation framework.
216    ///
217    /// The estimate assumes the node is synced to the network tip; during initial sync it is
218    /// significantly overestimated.
219    #[method(name = "getdeprecationinfo")]
220    async fn get_deprecation_info(&self) -> Result<GetDeprecationInfoResponse>;
221
222    /// Returns blockchain state information, as a [`GetBlockchainInfoResponse`] JSON struct.
223    ///
224    /// zcashd reference: [`getblockchaininfo`](https://zcash.github.io/rpc/getblockchaininfo.html)
225    /// method: post
226    /// tags: blockchain
227    ///
228    /// # Notes
229    ///
230    /// Some fields from the zcashd reference are missing from Zebra's [`GetBlockchainInfoResponse`]. It only contains the fields
231    /// [required for lightwalletd support.](https://github.com/zcash/lightwalletd/blob/v0.4.9/common/common.go#L72-L89)
232    #[method(name = "getblockchaininfo")]
233    async fn get_blockchain_info(&self) -> Result<GetBlockchainInfoResponse>;
234
235    /// Returns the total balance of a provided `addresses` in an [`AddressBalance`] instance.
236    ///
237    /// zcashd reference: [`getaddressbalance`](https://zcash.github.io/rpc/getaddressbalance.html)
238    /// method: post
239    /// tags: address
240    ///
241    /// # Parameters
242    ///
243    /// - `address_strings`: (object, example={"addresses": ["tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"]}) A JSON map with a single entry
244    ///     - `addresses`: (array of strings) A list of base-58 encoded addresses.
245    ///
246    /// # Notes
247    ///
248    /// zcashd also accepts a single string parameter instead of an array of strings, but Zebra
249    /// doesn't because lightwalletd always calls this RPC with an array of addresses.
250    ///
251    /// zcashd also returns the total amount of Zatoshis received by the addresses, but Zebra
252    /// doesn't because lightwalletd doesn't use that information.
253    ///
254    /// The RPC documentation says that the returned object has a string `balance` field, but
255    /// zcashd actually [returns an
256    /// integer](https://github.com/zcash/lightwalletd/blob/bdaac63f3ee0dbef62bde04f6817a9f90d483b00/common/common.go#L128-L130).
257    #[method(name = "getaddressbalance")]
258    async fn get_address_balance(
259        &self,
260        address_strings: GetAddressBalanceRequest,
261    ) -> Result<GetAddressBalanceResponse>;
262
263    /// Sends the raw bytes of a signed transaction to the local node's mempool, if the transaction is valid.
264    /// Returns the [`SentTransactionHash`] for the transaction, as a JSON string.
265    ///
266    /// zcashd reference: [`sendrawtransaction`](https://zcash.github.io/rpc/sendrawtransaction.html)
267    /// method: post
268    /// tags: transaction
269    ///
270    /// # Parameters
271    ///
272    /// - `raw_transaction_hex`: (string, required, example="signedhex") The hex-encoded raw transaction bytes.
273    /// - `allow_high_fees`: (bool, optional) A legacy parameter accepted by zcashd but ignored by Zebra.
274    ///
275    /// # Notes
276    ///
277    /// zcashd accepts an optional `allowhighfees` parameter. Zebra doesn't support this parameter,
278    /// because lightwalletd doesn't use it.
279    #[method(name = "sendrawtransaction")]
280    async fn send_raw_transaction(
281        &self,
282        raw_transaction_hex: String,
283        _allow_high_fees: Option<bool>,
284    ) -> Result<SendRawTransactionResponse>;
285
286    /// Returns the requested block by hash or height, as a [`GetBlock`] JSON string.
287    /// If the block is not in Zebra's state, returns
288    /// [error code `-8`.](https://github.com/zcash/zcash/issues/5758) if a height was
289    /// passed or -5 if a hash was passed.
290    ///
291    /// zcashd reference: [`getblock`](https://zcash.github.io/rpc/getblock.html)
292    /// method: post
293    /// tags: blockchain
294    ///
295    /// # Parameters
296    ///
297    /// - `hash_or_height`: (string, required, example="1") The hash or height for the block to be returned.
298    /// - `verbosity`: (number, optional, default=1, example=1) 0 for hex encoded data, 1 for a json object, 2 for a json object with transaction data, and 3 for a json object with transaction data including prevout information for inputs.
299    ///
300    /// # Notes
301    ///
302    /// The `size` field is only returned with verbosity>=2.
303    ///
304    /// Verbosity 3 adds a `prevout` object to each transparent input and a `fee` field to each
305    /// non-coinbase transaction, matching Bitcoin Core's `getblock` verbosity 3.
306    ///
307    /// Verbosity 3 resolves each spent output by reading its parent transaction, so it is more
308    /// expensive than lower verbosities.
309    ///
310    /// The undocumented `chainwork` field is not returned.
311    #[method(name = "getblock")]
312    async fn get_block(
313        &self,
314        hash_or_height: String,
315        verbosity: Option<u8>,
316    ) -> Result<GetBlockResponse>;
317
318    /// Returns the requested block header by hash or height, as a [`GetBlockHeader`] JSON string.
319    /// If the block is not in Zebra's state,
320    /// returns [error code `-8`.](https://github.com/zcash/zcash/issues/5758)
321    /// if a height was passed or -5 if a hash was passed.
322    ///
323    /// zcashd reference: [`getblockheader`](https://zcash.github.io/rpc/getblockheader.html)
324    /// method: post
325    /// tags: blockchain
326    ///
327    /// # Parameters
328    ///
329    /// - `hash_or_height`: (string, required, example="1") The hash or height for the block to be returned.
330    /// - `verbose`: (bool, optional, default=false, example=true) false for hex encoded data, true for a json object
331    ///
332    /// # Notes
333    ///
334    /// The undocumented `chainwork` field is not returned.
335    #[method(name = "getblockheader")]
336    async fn get_block_header(
337        &self,
338        hash_or_height: String,
339        verbose: Option<bool>,
340    ) -> Result<GetBlockHeaderResponse>;
341
342    /// Returns the hash of the current best blockchain tip block, as a [`GetBlockHash`] JSON string.
343    ///
344    /// zcashd reference: [`getbestblockhash`](https://zcash.github.io/rpc/getbestblockhash.html)
345    /// method: post
346    /// tags: blockchain
347    #[method(name = "getbestblockhash")]
348    fn get_best_block_hash(&self) -> Result<GetBlockHashResponse>;
349
350    /// Returns the height and hash of the current best blockchain tip block, as a [`GetBlockHeightAndHashResponse`] JSON struct.
351    ///
352    /// zcashd reference: none
353    /// method: post
354    /// tags: blockchain
355    #[method(name = "getbestblockheightandhash")]
356    fn get_best_block_height_and_hash(&self) -> Result<GetBlockHeightAndHashResponse>;
357
358    /// Returns details on the active state of the TX memory pool.
359    ///
360    /// zcash reference: [`getmempoolinfo`](https://zcash.github.io/rpc/getmempoolinfo.html)
361    #[method(name = "getmempoolinfo")]
362    async fn get_mempool_info(&self) -> Result<GetMempoolInfoResponse>;
363
364    /// Returns all transaction ids in the memory pool, as a JSON array.
365    ///
366    /// # Parameters
367    ///
368    /// - `verbose`: (boolean, optional, default=false) true for a json object, false for array of transaction ids.
369    ///
370    /// zcashd reference: [`getrawmempool`](https://zcash.github.io/rpc/getrawmempool.html)
371    /// method: post
372    /// tags: blockchain
373    #[method(name = "getrawmempool")]
374    async fn get_raw_mempool(&self, verbose: Option<bool>) -> Result<GetRawMempoolResponse>;
375
376    /// Returns information about the given block's Sapling & Orchard tree state.
377    ///
378    /// zcashd reference: [`z_gettreestate`](https://zcash.github.io/rpc/z_gettreestate.html)
379    /// method: post
380    /// tags: blockchain
381    ///
382    /// # Parameters
383    ///
384    /// - `hash | height`: (string, required, example="00000000febc373a1da2bd9f887b105ad79ddc26ac26c2b28652d64e5207c5b5") The block hash or height.
385    ///
386    /// # Notes
387    ///
388    /// The zcashd doc reference above says that the parameter "`height` can be
389    /// negative where -1 is the last known valid block". On the other hand,
390    /// `lightwalletd` only uses positive heights, so Zebra does not support
391    /// negative heights.
392    #[method(name = "z_gettreestate")]
393    async fn z_get_treestate(&self, hash_or_height: String) -> Result<GetTreestateResponse>;
394
395    /// Returns information about a range of Sapling or Orchard subtrees.
396    ///
397    /// zcashd reference: [`z_getsubtreesbyindex`](https://zcash.github.io/rpc/z_getsubtreesbyindex.html) - TODO: fix link
398    /// method: post
399    /// tags: blockchain
400    ///
401    /// # Parameters
402    ///
403    /// - `pool`: (string, required) The pool from which subtrees should be returned. Either "sapling" or "orchard".
404    /// - `start_index`: (number, required) The index of the first 2^16-leaf subtree to return.
405    /// - `limit`: (number, optional) The maximum number of subtree values to return.
406    ///
407    /// # Notes
408    ///
409    /// While Zebra is doing its initial subtree index rebuild, subtrees will become available
410    /// starting at the chain tip. This RPC will return an empty list if the `start_index` subtree
411    /// exists, but has not been rebuilt yet. This matches `zcashd`'s behaviour when subtrees aren't
412    /// available yet. (But `zcashd` does its rebuild before syncing any blocks.)
413    #[method(name = "z_getsubtreesbyindex")]
414    async fn z_get_subtrees_by_index(
415        &self,
416        pool: String,
417        start_index: NoteCommitmentSubtreeIndex,
418        limit: Option<NoteCommitmentSubtreeIndex>,
419    ) -> Result<GetSubtreesByIndexResponse>;
420
421    /// Returns the raw transaction data, as a [`GetRawTransaction`] JSON string or structure.
422    ///
423    /// zcashd reference: [`getrawtransaction`](https://zcash.github.io/rpc/getrawtransaction.html)
424    /// method: post
425    /// tags: transaction
426    ///
427    /// # Parameters
428    ///
429    /// - `txid`: (string, required, example="mytxid") The transaction ID of the transaction to be returned.
430    /// - `verbose`: (number, optional, default=0, example=1) If 0, return a string of hex-encoded data, otherwise return a JSON object.
431    /// - `blockhash` (string, optional) The block in which to look for the transaction
432    #[method(name = "getrawtransaction")]
433    async fn get_raw_transaction(
434        &self,
435        txid: String,
436        verbose: Option<u8>,
437        block_hash: Option<String>,
438    ) -> Result<GetRawTransactionResponse>;
439
440    /// Returns the transaction ids made by the provided transparent addresses.
441    ///
442    /// zcashd reference: [`getaddresstxids`](https://zcash.github.io/rpc/getaddresstxids.html)
443    /// method: post
444    /// tags: address
445    ///
446    /// # Parameters
447    ///
448    /// - `request`: (required) Either:
449    ///     - A single address string (e.g., `"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"`), or
450    ///     - An object with the following named fields:
451    ///         - `addresses`: (array of strings, required) The addresses to get transactions from.
452    ///         - `start`: (numeric, optional) The lower height to start looking for transactions (inclusive).
453    ///         - `end`: (numeric, optional) The upper height to stop looking for transactions (inclusive).
454    ///
455    /// Example of the object form:
456    /// ```json
457    /// {
458    ///   "addresses": ["tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"],
459    ///   "start": 1000,
460    ///   "end": 2000
461    /// }
462    /// ```
463    ///
464    /// # Notes
465    ///
466    /// - Only the multi-argument format is used by lightwalletd and this is what we currently support:
467    /// <https://github.com/zcash/lightwalletd/blob/631bb16404e3d8b045e74a7c5489db626790b2f6/common/common.go#L97-L102>
468    /// - It is recommended that users call the method with start/end heights such that the response can't be too large.
469    /// - At most 10,000 addresses are accepted, and a query matching more than 100,000
470    ///   transactions is rejected; narrow the height range instead.
471    #[method(name = "getaddresstxids")]
472    async fn get_address_tx_ids(&self, request: GetAddressTxIdsRequest) -> Result<Vec<String>>;
473
474    /// Returns all unspent outputs for a list of addresses.
475    ///
476    /// zcashd reference: [`getaddressutxos`](https://zcash.github.io/rpc/getaddressutxos.html)
477    /// method: post
478    /// tags: address
479    ///
480    /// # Parameters
481    ///
482    /// - `request`: (required) Either:
483    ///     - A single address string (e.g., `"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ"`), or
484    ///     - An object with the following named fields:
485    ///         - `addresses`: (array, required, example=[\"tmYXBYJj1K7vhejSec5osXK2QsGa5MTisUQ\"]) The addresses to get outputs from.
486    ///         - `chaininfo`: (boolean, optional, default=false) Include chain info with results
487    ///         - `startHeight`: (numeric, optional, default=0) Only return outputs at or above this height
488    ///         - `maxEntries`: (numeric, optional, default=0) Return at most this many outputs, zero for up to 100,000
489    ///
490    /// # Notes
491    ///
492    /// `startHeight` and `maxEntries` bound the index scan, not just the response, so a client
493    /// that pages through a large address does not make the node read the whole UTXO set each
494    /// time. Callers must set both or neither: `maxEntries` alone would truncate the outputs
495    /// before the height filter ran.
496    ///
497    /// At most 10,000 addresses are accepted. Without `maxEntries`, a query matching more than
498    /// 100,000 outputs is rejected, and so is a larger `maxEntries`.
499    ///
500    /// lightwalletd always uses the multi-address request, without chaininfo:
501    /// <https://github.com/zcash/lightwalletd/blob/master/frontend/service.go#L402>
502    #[method(name = "getaddressutxos")]
503    async fn get_address_utxos(
504        &self,
505        request: GetAddressUtxosRequest,
506    ) -> Result<GetAddressUtxosResponse>;
507
508    /// Stop the running zebrad process.
509    ///
510    /// # Notes
511    ///
512    /// - Works for non windows targets only.
513    /// - Works only if the network of the running zebrad process is `Regtest`.
514    ///
515    /// zcashd reference: [`stop`](https://zcash.github.io/rpc/stop.html)
516    /// method: post
517    /// tags: control
518    #[method(name = "stop")]
519    fn stop(&self) -> Result<String>;
520
521    /// Returns the height of the most recent block in the best valid block chain (equivalently,
522    /// the number of blocks in this chain excluding the genesis block).
523    ///
524    /// zcashd reference: [`getblockcount`](https://zcash.github.io/rpc/getblockcount.html)
525    /// method: post
526    /// tags: blockchain
527    #[method(name = "getblockcount")]
528    fn get_block_count(&self) -> Result<u32>;
529
530    /// Returns the hash of the block of a given height iff the index argument correspond
531    /// to a block in the best chain.
532    ///
533    /// zcashd reference: [`getblockhash`](https://zcash-rpc.github.io/getblockhash.html)
534    /// method: post
535    /// tags: blockchain
536    ///
537    /// # Parameters
538    ///
539    /// - `index`: (numeric, required, example=1) The block index.
540    ///
541    /// # Notes
542    ///
543    /// - If `index` is positive then index = block height.
544    /// - If `index` is negative then -1 is the last known valid block.
545    #[method(name = "getblockhash")]
546    async fn get_block_hash(&self, index: i32) -> Result<GetBlockHashResponse>;
547
548    /// Returns a block template for mining new Zcash blocks.
549    ///
550    /// # Parameters
551    ///
552    /// - `jsonrequestobject`: (string, optional) A JSON object containing arguments.
553    ///
554    /// zcashd reference: [`getblocktemplate`](https://zcash-rpc.github.io/getblocktemplate.html)
555    /// method: post
556    /// tags: mining
557    ///
558    /// # Notes
559    ///
560    /// Arguments to this RPC are currently ignored.
561    /// Long polling, block proposals, server lists, and work IDs are not supported.
562    ///
563    /// Miners can make arbitrary changes to blocks, as long as:
564    /// - the data sent to `submitblock` is a valid Zcash block, and
565    /// - the parent block is a valid block that Zebra already has, or will receive soon.
566    ///
567    /// Zebra verifies blocks in parallel, and keeps recent chains in parallel,
568    /// so moving between chains and forking chains is very cheap.
569    #[method(name = "getblocktemplate")]
570    async fn get_block_template(
571        &self,
572        parameters: Option<GetBlockTemplateParameters>,
573    ) -> Result<GetBlockTemplateResponse>;
574
575    /// Submits block to the node to be validated and committed.
576    /// Returns the [`SubmitBlockResponse`] for the operation, as a JSON string.
577    ///
578    /// zcashd reference: [`submitblock`](https://zcash.github.io/rpc/submitblock.html)
579    /// method: post
580    /// tags: mining
581    ///
582    /// # Parameters
583    ///
584    /// - `hexdata`: (string, required)
585    /// - `jsonparametersobject`: (string, optional) - currently ignored
586    ///
587    /// # Notes
588    ///
589    ///  - `jsonparametersobject` holds a single field, workid, that must be included in submissions if provided by the server.
590    ///  - Returns `inconclusive` if the block isn't verified and committed within 30 seconds, for
591    ///    example because its parent block is still being verified, or never arrives. Zebra keeps
592    ///    verifying the block, and commits and announces it if it is valid.
593    #[method(name = "submitblock")]
594    async fn submit_block(
595        &self,
596        hex_data: HexData,
597        _parameters: Option<SubmitBlockParameters>,
598    ) -> Result<SubmitBlockResponse>;
599
600    /// Returns mining-related information.
601    ///
602    /// zcashd reference: [`getmininginfo`](https://zcash.github.io/rpc/getmininginfo.html)
603    /// method: post
604    /// tags: mining
605    #[method(name = "getmininginfo")]
606    async fn get_mining_info(&self) -> Result<GetMiningInfoResponse>;
607
608    /// Returns the estimated network solutions per second based on the last `num_blocks` before
609    /// `height`.
610    ///
611    /// If `num_blocks` is not supplied, uses 120 blocks. If it is 0 or -1, uses the difficulty
612    /// averaging window.
613    /// If `height` is not supplied or is -1, uses the tip height.
614    ///
615    /// zcashd reference: [`getnetworksolps`](https://zcash.github.io/rpc/getnetworksolps.html)
616    /// method: post
617    /// tags: mining
618    #[method(name = "getnetworksolps")]
619    async fn get_network_sol_ps(&self, num_blocks: Option<i32>, height: Option<i32>)
620        -> Result<u64>;
621
622    /// Returns the estimated network solutions per second based on the last `num_blocks` before
623    /// `height`.
624    ///
625    /// This method name is deprecated, use [`getnetworksolps`](Self::get_network_sol_ps) instead.
626    /// See that method for details.
627    ///
628    /// zcashd reference: [`getnetworkhashps`](https://zcash.github.io/rpc/getnetworkhashps.html)
629    /// method: post
630    /// tags: mining
631    #[method(name = "getnetworkhashps")]
632    async fn get_network_hash_ps(
633        &self,
634        num_blocks: Option<i32>,
635        height: Option<i32>,
636    ) -> Result<u64> {
637        self.get_network_sol_ps(num_blocks, height).await
638    }
639
640    /// Returns an object containing various state info regarding P2P networking.
641    ///
642    /// zcashd reference: [`getnetworkinfo`](https://zcash.github.io/rpc/getnetworkinfo.html)
643    /// method: post
644    /// tags: network
645    #[method(name = "getnetworkinfo")]
646    async fn get_network_info(&self) -> Result<GetNetworkInfoResponse>;
647
648    /// Returns data about each connected network node.
649    ///
650    /// zcashd reference: [`getpeerinfo`](https://zcash.github.io/rpc/getpeerinfo.html)
651    /// method: post
652    /// tags: network
653    #[method(name = "getpeerinfo")]
654    async fn get_peer_info(&self) -> Result<Vec<PeerInfo>>;
655
656    /// Requests that a ping be sent to all other nodes, to measure ping time.
657    ///
658    /// Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.
659    /// Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.
660    ///
661    /// zcashd reference: [`ping`](https://zcash.github.io/rpc/ping.html)
662    /// method: post
663    /// tags: network
664    #[method(name = "ping")]
665    async fn ping(&self) -> Result<()>;
666
667    /// Checks if a zcash transparent address of type P2PKH, P2SH or TEX is valid.
668    /// Returns information about the given address if valid.
669    ///
670    /// zcashd reference: [`validateaddress`](https://zcash.github.io/rpc/validateaddress.html)
671    /// method: post
672    /// tags: util
673    ///
674    /// # Parameters
675    ///
676    /// - `address`: (string, required) The zcash address to validate.
677    #[method(name = "validateaddress")]
678    async fn validate_address(&self, address: String) -> Result<ValidateAddressResponse>;
679
680    /// Checks if a zcash address of type P2PKH, P2SH, TEX, SAPLING or UNIFIED is valid.
681    /// Returns information about the given address if valid.
682    ///
683    /// zcashd reference: [`z_validateaddress`](https://zcash.github.io/rpc/z_validateaddress.html)
684    /// method: post
685    /// tags: util
686    ///
687    /// # Parameters
688    ///
689    /// - `address`: (string, required) The zcash address to validate.
690    ///
691    /// # Notes
692    ///
693    /// - No notes
694    #[method(name = "z_validateaddress")]
695    async fn z_validate_address(&self, address: String) -> Result<ZValidateAddressResponse>;
696
697    /// Converts a transparent P2PKH address to a ZIP 320 TEX address.
698    ///
699    /// zcashd reference: [`z_converttex`](https://zcash.github.io/rpc/z_converttex.html)
700    /// method: post
701    /// tags: util
702    ///
703    /// # Parameters
704    ///
705    /// - `address`: (string, required) The transparent P2PKH address to convert.
706    ///
707    /// # Notes
708    ///
709    /// - Addresses that don't decode, or are for another network, return error `-5`; addresses
710    ///   that decode but aren't transparent P2PKH return error `-8`. This follows zcashd for the
711    ///   common cases, but not exactly: zcashd returns `-8` for Sprout addresses and for unified
712    ///   addresses with unknown receivers, where Zebra returns `-5`, because Zebra's
713    ///   `primitives::Address` can't represent them at all. Zallet differs from both.
714    #[method(name = "z_converttex")]
715    async fn z_convert_tex(&self, address: String) -> Result<String>;
716
717    /// Returns the recommended standard fee per logical action, in zatoshis.
718    ///
719    /// Currently returns a fixed fee for the next block, with `version` 0:
720    /// 5000 zatoshis before Mainnet height 3,590,000, and 1000 zatoshis from that height
721    /// and on test networks. This will be replaced by a dynamic estimate without changing
722    /// the parameters or result shape.
723    ///
724    /// method: post
725    /// tags: wallet
726    #[method(name = "getstandardfee")]
727    async fn get_standard_fee(&self) -> Result<GetStandardFeeResponse>;
728
729    /// Returns the block subsidy reward of the block at `height`, taking into account the mining slow start.
730    /// Returns an error if `height` is less than the height of the first halving for the current network.
731    /// Once NSM reissuance starts, the preceding block must exist: future reserves cannot be forecast.
732    ///
733    /// zcashd reference: [`getblocksubsidy`](https://zcash.github.io/rpc/getblocksubsidy.html)
734    /// method: post
735    /// tags: mining
736    ///
737    /// # Parameters
738    ///
739    /// - `height`: (numeric, optional, example=1) A valid height; future heights are supported only
740    ///   when their subsidy does not depend on an unknown parent reserve.
741    ///
742    /// # Notes
743    ///
744    /// If `height` is not supplied, uses the tip height.
745    #[method(name = "getblocksubsidy")]
746    async fn get_block_subsidy(&self, height: Option<u32>) -> Result<GetBlockSubsidyResponse>;
747
748    /// Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
749    ///
750    /// zcashd reference: [`getdifficulty`](https://zcash.github.io/rpc/getdifficulty.html)
751    /// method: post
752    /// tags: blockchain
753    #[method(name = "getdifficulty")]
754    async fn get_difficulty(&self) -> Result<f64>;
755
756    /// Returns the list of individual payment addresses given a unified address.
757    ///
758    /// zcashd reference: [`z_listunifiedreceivers`](https://zcash.github.io/rpc/z_listunifiedreceivers.html)
759    /// method: post
760    /// tags: wallet
761    ///
762    /// # Parameters
763    ///
764    /// - `address`: (string, required) The zcash unified address to get the list from.
765    ///
766    /// # Notes
767    ///
768    /// - No notes
769    #[method(name = "z_listunifiedreceivers")]
770    async fn z_list_unified_receivers(
771        &self,
772        address: String,
773    ) -> Result<ZListUnifiedReceiversResponse>;
774
775    /// Invalidates a block if it is not yet finalized, removing it from the non-finalized
776    /// state if it is present and rejecting it during contextual validation if it is submitted.
777    ///
778    /// # Parameters
779    ///
780    /// - `block_hash`: (hex-encoded block hash, required) The block hash to invalidate.
781    // TODO: Invalidate block hashes even if they're not present in the non-finalized state (#9553).
782    #[method(name = "invalidateblock")]
783    async fn invalidate_block(&self, block_hash: String) -> Result<()>;
784
785    /// Reconsiders a previously invalidated block if it exists in the cache of previously invalidated blocks.
786    ///
787    /// # Parameters
788    ///
789    /// - `block_hash`: (hex-encoded block hash, required) The block hash to reconsider.
790    #[method(name = "reconsiderblock")]
791    async fn reconsider_block(&self, block_hash: String) -> Result<Vec<block::Hash>>;
792
793    #[method(name = "generate")]
794    /// Mine blocks immediately. Returns the block hashes of the generated blocks.
795    ///
796    /// # Parameters
797    ///
798    /// - `num_blocks`: (numeric, required, example=1) Number of blocks to be generated.
799    ///
800    /// # Notes
801    ///
802    /// Only works if the network of the running zebrad process is `Regtest`.
803    ///
804    /// zcashd reference: [`generate`](https://zcash.github.io/rpc/generate.html)
805    /// method: post
806    /// tags: generating
807    async fn generate(&self, num_blocks: u32) -> Result<Vec<GetBlockHashResponse>>;
808
809    #[method(name = "generatetoaddress")]
810    /// Mine blocks immediately, paying the coinbase to `address`. Returns the
811    /// block hashes of the generated blocks.
812    ///
813    /// # Parameters
814    ///
815    /// - `num_blocks`: (numeric, required, example=1) Number of blocks to generate.
816    /// - `address`: (string, required) The transparent or shielded address to
817    ///   pay the coinbase subsidy and fees to.
818    ///
819    /// # Notes
820    ///
821    /// Only works if the network of the running zebrad process is `Regtest`.
822    /// Unlike [`Self::generate`], the coinbase is paid to `address` instead of
823    /// the configured `mining.miner_address`, which lets a test harness fund
824    /// several wallets from one node.
825    ///
826    /// zcashd reference: [`generatetoaddress`](https://zcash.github.io/rpc/generatetoaddress.html)
827    /// method: post
828    /// tags: generating
829    async fn generate_to_address(
830        &self,
831        num_blocks: u32,
832        address: String,
833    ) -> Result<Vec<GetBlockHashResponse>> {
834        let _ = (num_blocks, address);
835        Err(ErrorObject::borrowed(
836            ErrorCode::MethodNotFound.code(),
837            "generatetoaddress is not implemented",
838            None,
839        ))
840    }
841
842    #[method(name = "addnode")]
843    /// Add or remove a node from the address book.
844    ///
845    /// # Parameters
846    ///
847    /// - `addr`: (string, required) The address of the node to add or remove.
848    /// - `command`: (string, required) The command to execute, either "add", "onetry", or "remove".
849    ///
850    /// # Notes
851    ///
852    /// Only the "add" command is currently supported.
853    ///
854    /// zcashd reference: [`addnode`](https://zcash.github.io/rpc/addnode.html)
855    /// method: post
856    /// tags: network
857    async fn add_node(&self, addr: PeerSocketAddr, command: AddNodeCommand) -> Result<()>;
858
859    /// Returns an OpenRPC schema as a description of this service.
860    #[method(name = "rpc.discover")]
861    fn openrpc(&self) -> openrpsee::openrpc::Response;
862    /// Returns details about an unspent transaction output.
863    ///
864    /// zcashd reference: [`gettxout`](https://zcash.github.io/rpc/gettxout.html)
865    /// method: post
866    /// tags: transaction
867    ///
868    /// # Parameters
869    ///
870    /// - `txid`: (string, required, example="mytxid") The transaction ID that contains the output.
871    /// - `n`: (number, required) The output index number.
872    /// - `include_mempool` (bool, optional, default=true) Whether to include the mempool in the search.
873    #[method(name = "gettxout")]
874    async fn get_tx_out(
875        &self,
876        txid: String,
877        n: u32,
878        include_mempool: Option<bool>,
879    ) -> Result<GetTxOutResponse>;
880}
881
882/// RPC method implementations.
883#[derive(Clone)]
884pub struct RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
885where
886    Mempool: MempoolService,
887    State: StateService,
888    ReadState: ReadStateService,
889    Tip: ChainTip + Clone + Send + Sync + 'static,
890    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
891    BlockVerifierRouter: BlockVerifierService,
892    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
893{
894    // Configuration
895    //
896    /// Zebra's application version, with build metadata.
897    build_version: String,
898
899    /// Zebra's RPC user agent.
900    user_agent: String,
901
902    /// The configured network for this RPC service.
903    network: Network,
904
905    /// Test-only option that makes Zebra say it is at the chain tip,
906    /// no matter what the estimated height or local clock is.
907    debug_force_finished_sync: bool,
908
909    /// The estimated last height this node release supports before its end of support halt,
910    /// if end of support is enforced on `network`. Reported by the `getdeprecationinfo` RPC.
911    end_of_support_height: Option<Height>,
912
913    /// The maximum number of results the address RPCs return before rejecting the query.
914    max_address_query_results: usize,
915
916    // Services
917    //
918    /// A handle to the mempool service.
919    mempool: Mempool,
920
921    /// A handle to the state service.
922    state: State,
923
924    /// A handle to the state service.
925    read_state: ReadState,
926
927    /// Allows efficient access to the best tip of the blockchain.
928    latest_chain_tip: Tip,
929
930    // Tasks
931    //
932    /// A sender component of a channel used to send transactions to the mempool queue.
933    queue_sender: broadcast::Sender<UnminedTx>,
934
935    /// Peer address book.
936    address_book: AddressBook,
937
938    /// The last warning or error event logged by the server.
939    last_warn_error_log_rx: LoggedLastEvent,
940
941    /// Handler for the `getblocktemplate` RPC.
942    gbt: GetBlockTemplateHandler<BlockVerifierRouter, SyncStatus>,
943
944    /// The last best tip publication a template was served for, shared by all RPC clones.
945    first_template_tip: FirstTemplateTip,
946
947    /// Per-instance wall clock for deterministic mining deadline and rollback tests.
948    #[cfg(test)]
949    template_clock: Option<Arc<std::sync::atomic::AtomicU32>>,
950}
951
952/// The last best tip publication that a block template was served for, shared by all RPC clones.
953#[derive(Clone, Debug, Default)]
954struct FirstTemplateTip(Arc<Mutex<Option<(block::Hash, Instant)>>>);
955
956impl FirstTemplateTip {
957    /// Records the time from the publication of the best tip `hash` to now, if `hash` is still
958    /// the best tip and no template was recorded for this publication yet, including a return
959    /// to an earlier tip.
960    ///
961    /// Returns whether it recorded a sample.
962    fn record(&self, chain_tip: &impl ChainTip, hash: block::Hash) -> bool {
963        // Reading the publication while holding the lock stops a clone that read an older
964        // publication from replacing a newer one that another clone recorded.
965        let mut recorded = self
966            .0
967            .lock()
968            .expect("the lock is only held to compare and replace a value, which can't panic");
969        let Some(changed_at) = chain_tip.best_tip_changed_at(hash) else {
970            return false;
971        };
972        if *recorded == Some((hash, changed_at)) {
973            return false;
974        }
975
976        metrics::histogram!("rpc.getblocktemplate.first_template.duration_seconds")
977            .record(changed_at.elapsed().as_secs_f64());
978        *recorded = Some((hash, changed_at));
979        true
980    }
981}
982
983/// A type alias for the last event logged by the server.
984pub type LoggedLastEvent = watch::Receiver<Option<(String, tracing::Level, chrono::DateTime<Utc>)>>;
985
986impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus> fmt::Debug
987    for RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
988where
989    Mempool: MempoolService,
990    State: StateService,
991    ReadState: ReadStateService,
992    Tip: ChainTip + Clone + Send + Sync + 'static,
993    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
994    BlockVerifierRouter: BlockVerifierService,
995    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
996{
997    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998        // Skip fields without Debug impls, and skip channels
999        f.debug_struct("RpcImpl")
1000            .field("build_version", &self.build_version)
1001            .field("user_agent", &self.user_agent)
1002            .field("network", &self.network)
1003            .field("debug_force_finished_sync", &self.debug_force_finished_sync)
1004            .field("getblocktemplate", &self.gbt)
1005            .finish()
1006    }
1007}
1008
1009impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
1010    RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
1011where
1012    Mempool: MempoolService,
1013    State: StateService,
1014    ReadState: ReadStateService,
1015    Tip: ChainTip + Clone + Send + Sync + 'static,
1016    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
1017    BlockVerifierRouter: BlockVerifierService,
1018    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
1019{
1020    /// Create a new instance of the RPC handler.
1021    //
1022    // TODO:
1023    // - put some of the configs or services in their own struct?
1024    #[allow(clippy::too_many_arguments)]
1025    pub fn new<VersionString, UserAgentString>(
1026        network: Network,
1027        mining_config: config::mining::Config,
1028        debug_force_finished_sync: bool,
1029        build_version: VersionString,
1030        user_agent: UserAgentString,
1031        mempool: Mempool,
1032        state: State,
1033        read_state: ReadState,
1034        block_verifier_router: BlockVerifierRouter,
1035        sync_status: SyncStatus,
1036        latest_chain_tip: Tip,
1037        address_book: AddressBook,
1038        last_warn_error_log_rx: LoggedLastEvent,
1039        mined_block_sender: Option<mpsc::Sender<(block::Hash, block::Height)>>,
1040    ) -> (Self, JoinHandle<()>)
1041    where
1042        VersionString: ToString + Clone + Send + 'static,
1043        UserAgentString: ToString + Clone + Send + 'static,
1044    {
1045        let (runner, queue_sender) = Queue::start();
1046
1047        let mut build_version = build_version.to_string();
1048        let user_agent = user_agent.to_string();
1049
1050        // Match zcashd's version format, if the version string has anything in it
1051        if !build_version.is_empty() && !build_version.starts_with('v') {
1052            build_version.insert(0, 'v');
1053        }
1054
1055        let gbt = GetBlockTemplateHandler::new(
1056            &network,
1057            mining_config.clone(),
1058            block_verifier_router,
1059            sync_status,
1060            mined_block_sender,
1061        );
1062
1063        let rpc_impl = RpcImpl {
1064            build_version,
1065            user_agent,
1066            network: network.clone(),
1067            debug_force_finished_sync,
1068            end_of_support_height: None,
1069            max_address_query_results: MAX_ADDRESS_QUERY_RESULTS,
1070            mempool: mempool.clone(),
1071            state: state.clone(),
1072            read_state: read_state.clone(),
1073            latest_chain_tip: latest_chain_tip.clone(),
1074            queue_sender,
1075            address_book,
1076            last_warn_error_log_rx,
1077            gbt,
1078            first_template_tip: Default::default(),
1079            #[cfg(test)]
1080            template_clock: None,
1081        };
1082
1083        // run the process queue
1084        let rpc_tx_queue_task_handle = tokio::spawn(
1085            runner
1086                .run(mempool, read_state, latest_chain_tip, network)
1087                .in_current_span(),
1088        );
1089
1090        (rpc_impl, rpc_tx_queue_task_handle)
1091    }
1092
1093    /// Records the first template served on the current best tip publication, then converts
1094    /// `template` into the RPC response.
1095    fn served_block_template(&self, template: BlockTemplateResponse) -> GetBlockTemplateResponse {
1096        self.first_template_tip
1097            .record(&self.latest_chain_tip, template.previous_block_hash);
1098        template.into()
1099    }
1100
1101    /// Reads wall time for template deadlines and serve-time timestamp validation.
1102    fn template_clock_now(&self) -> DateTime32 {
1103        #[cfg(test)]
1104        if let Some(clock) = &self.template_clock {
1105            return clock.load(std::sync::atomic::Ordering::SeqCst).into();
1106        }
1107
1108        DateTime32::now()
1109    }
1110
1111    /// Spawns a task that keeps a block template for the current chain tip precomputed, so
1112    /// `getblocktemplate` calls only validate the tip against the state instead of reading the
1113    /// mempool, selecting transactions, and building a coinbase transaction.
1114    ///
1115    /// The task also rebuilds the template when `mempool_changes` reports a newly verified
1116    /// transaction, and validates each template as a block proposal, so a solved template is
1117    /// not validated again when it is submitted.
1118    ///
1119    /// Returns `None` if mining isn't configured.
1120    pub fn spawn_block_template_updater(
1121        &self,
1122        mempool_changes: &MempoolTxSubscriber,
1123    ) -> Option<JoinHandle<()>> {
1124        let miner_params = self.gbt.miner_params()?.clone();
1125        let template_cache = self.gbt.template_cache()?.clone();
1126
1127        // Subscribe before the updater starts, so its first template is validated too.
1128        let validate_templates = precompute::validate_templates(
1129            template_cache.subscribe(),
1130            self.network.clone(),
1131            self.gbt.block_verifier_router(),
1132            self.gbt.proposal_transactions().clone(),
1133            self.latest_chain_tip.clone(),
1134        );
1135        let update_templates = precompute::run(
1136            self.network.clone(),
1137            miner_params,
1138            self.gbt.coinbase_cache(),
1139            template_cache,
1140            self.mempool.clone(),
1141            mempool_changes.subscribe(),
1142            self.read_state.clone(),
1143            self.latest_chain_tip.clone(),
1144            self.gbt.sync_status(),
1145        );
1146
1147        Some(tokio::spawn(
1148            async move {
1149                // The validation only ends with the task, so the task ends with the updater.
1150                tokio::select! {
1151                    () = update_templates => {}
1152                    () = validate_templates => {}
1153                }
1154            }
1155            .in_current_span(),
1156        ))
1157    }
1158
1159    /// Returns the block template that [`Self::spawn_block_template_updater()`] keeps precomputed,
1160    /// if it extends the current chain tip, and if it isn't the template the client already has.
1161    ///
1162    /// The precomputed template's mempool transactions can be a few seconds old, which only costs
1163    /// the miner the fees of the transactions that arrived in the meantime, and the next call picks
1164    /// them up. But it always extends the current tip, so miners never work on a chain that Zebra
1165    /// has already seen a block for.
1166    ///
1167    /// A long polling client waits here until the updater publishes a template it doesn't have
1168    /// yet, the chain tip changes, or its timestamp range expires during this request.
1169    ///
1170    /// # Correctness
1171    ///
1172    /// Long polling must not fall through to the synchronous path below while this cache is
1173    /// serving. That path derives its own long poll ID from a fresh state and mempool read, so
1174    /// with two independent ID sources neither side ever matches the other: the client alternates
1175    /// between a cached template and a freshly built one, each call returning immediately, and it
1176    /// never waits. Its work is cancelled on every response, so it mines nothing.
1177    ///
1178    /// Returns `None` if there is no updater task, if it hasn't caught up with a recent chain tip
1179    /// change, or if the chain tip channel closed.
1180    async fn precomputed_block_template(
1181        &self,
1182        client_long_poll_id: Option<LongPollId>,
1183        long_poll_started: DateTime32,
1184    ) -> Option<BlockTemplateResponse> {
1185        let cache = self.gbt.template_cache()?;
1186
1187        // Skip the tip read when there's nothing to serve: without an updater task, every request
1188        // builds its own template anyway.
1189        if cache.is_empty() {
1190            return None;
1191        }
1192
1193        // Subscribe before the first read below. A template published between reading the cache
1194        // and waiting on it would otherwise be marked seen and skipped, and the only other wakes
1195        // are a chain tip change and `max_time`, neither of which fires when the mempool alone
1196        // changes: the caller would wait out the updater's backstop on a template it has already
1197        // been told about.
1198        let mut template_changes = cache.subscribe();
1199
1200        // Clone the chain tip once, and mark the current tip seen: a receiver created fresh on
1201        // every iteration reports the tip it was created with as a change, so waiting on it would
1202        // return immediately and spin this loop instead of parking it.
1203        let mut tip_change = self.latest_chain_tip.clone();
1204        tip_change.mark_best_tip_seen();
1205
1206        loop {
1207            let template = self.precomputed_template_for_state_tip(cache).await?;
1208
1209            let is_client_template = Some(template.long_poll_id) == client_long_poll_id;
1210            let now = self.template_clock_now();
1211            let max_time_reached =
1212                long_poll_started <= template.max_time && now > template.max_time;
1213
1214            if !is_client_template || max_time_reached {
1215                let mut template = (*template).clone();
1216                template.submit_old = client_long_poll_id.as_ref().map(|old_long_poll_id| {
1217                    now <= template.max_time && template.long_poll_id.submit_old(old_long_poll_id)
1218                });
1219
1220                return Some(template);
1221            }
1222
1223            // The client is long polling on exactly this template, so wait for a reason to send
1224            // another one.
1225            let max_time = template.max_time;
1226
1227            // `max_time` is inclusive. Wait until the clock passes it, not for the template's
1228            // original time range again: cached `cur_time` may already be several seconds old.
1229            // If it was already expired when polling began, wait for changed work instead of
1230            // repeatedly notifying the miner (or waking this loop every second).
1231            let duration_until_max_time = max_time.saturating_duration_since(now);
1232            let wait_for_max_time =
1233                tokio::time::sleep(duration_until_max_time.to_std() + Duration::from_secs(1));
1234
1235            tokio::select! {
1236                biased;
1237
1238                tip_changed = tip_change.best_tip_changed() => {
1239                    // A closed chain tip channel means Zebra is shutting down.
1240                    tip_changed.ok()?;
1241                }
1242
1243                () = template_changes.changed() => {}
1244
1245                // Recheck wall time after waking: the monotonic timer cannot detect clock changes.
1246                () = wait_for_max_time, if long_poll_started <= max_time => {}
1247            }
1248        }
1249    }
1250
1251    /// Returns the precomputed template, if it extends the tip the state has committed.
1252    ///
1253    /// Waits up to [`precompute::new_tip_timeout()`] for the updater task to catch up with a recent
1254    /// tip change, re-reading the tip every time it publishes.
1255    async fn precomputed_template_for_state_tip(
1256        &self,
1257        cache: &precompute::TemplateCache,
1258    ) -> Option<Arc<BlockTemplateResponse>> {
1259        // Subscribe before the first read below, so a template published while this call is
1260        // deciding what to do with the previous one still wakes it.
1261        let mut template_changes = cache.subscribe();
1262
1263        // Falling back to an on-demand build costs a shielded coinbase proof per request, so a
1264        // shielded miner address waits longer for the updater than a transparent one.
1265        let timeout = precompute::new_tip_timeout(self.gbt.miner_params()?);
1266
1267        tokio::time::timeout(timeout, async move {
1268            loop {
1269                // The state publishes committed blocks before updating `latest_chain_tip`.
1270                // Read its tip on every cache publication, including after a wait, so neither
1271                // a lagging tip channel nor a tip snapshot from before the wait admits stale work.
1272                let ReadResponse::Tip(Some((_, tip_hash))) = self
1273                    .read_state
1274                    .clone()
1275                    .oneshot(ReadRequest::Tip)
1276                    .await
1277                    .ok()?
1278                else {
1279                    return None;
1280                };
1281
1282                if let Some(template) =
1283                    cache.template_for_tip(tip_hash, &self.network, self.template_clock_now())
1284                {
1285                    return Some(template);
1286                }
1287
1288                template_changes.changed().await;
1289            }
1290        })
1291        .await
1292        .ok()
1293        .flatten()
1294    }
1295
1296    /// Returns a reference to the configured network.
1297    pub fn network(&self) -> &Network {
1298        &self.network
1299    }
1300
1301    /// Sets the estimated end of support height reported by the `getdeprecationinfo` RPC.
1302    ///
1303    /// When unset, or set to `None`, `getdeprecationinfo` omits the `end_of_service` object.
1304    pub fn with_end_of_support_height(mut self, end_of_support_height: Option<Height>) -> Self {
1305        self.end_of_support_height = end_of_support_height;
1306        self
1307    }
1308
1309    /// Sets the maximum number of results the `getaddresstxids` and `getaddressutxos` RPCs return.
1310    #[cfg(test)]
1311    pub(crate) fn with_max_address_query_results(
1312        mut self,
1313        max_address_query_results: usize,
1314    ) -> Self {
1315        self.max_address_query_results = max_address_query_results;
1316        self
1317    }
1318}
1319
1320#[async_trait]
1321impl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus> RpcServer
1322    for RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>
1323where
1324    Mempool: MempoolService,
1325    State: StateService,
1326    ReadState: ReadStateService,
1327    Tip: ChainTip + Clone + Send + Sync + 'static,
1328    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
1329    BlockVerifierRouter: BlockVerifierService,
1330    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
1331{
1332    async fn get_info(&self) -> Result<GetInfoResponse> {
1333        let version = GetInfoResponse::version_from_string(&self.build_version)
1334            .expect("invalid version string");
1335
1336        let connections = read_address_book(&self.address_book, |book| {
1337            book.recently_live_peers(Utc::now()).len()
1338        })
1339        .await?;
1340
1341        let last_error_recorded = self.last_warn_error_log_rx.borrow().clone();
1342        let (last_error_log, _level, last_error_log_time) = last_error_recorded.unwrap_or((
1343            GetInfoResponse::default().errors,
1344            tracing::Level::INFO,
1345            Utc::now(),
1346        ));
1347
1348        let tip_height = self
1349            .latest_chain_tip
1350            .best_tip_height()
1351            .unwrap_or(Height::MIN);
1352        let testnet = self.network.is_a_test_network();
1353
1354        // This field is behind the `ENABLE_WALLET` feature flag in zcashd:
1355        // https://github.com/zcash/zcash/blob/v6.1.0/src/rpc/misc.cpp#L113
1356        // However it is not documented as optional:
1357        // https://github.com/zcash/zcash/blob/v6.1.0/src/rpc/misc.cpp#L70
1358        // For compatibility, we keep the field in the response, but always return 0.
1359        let pay_tx_fee = 0.0;
1360
1361        let relay_fee = zebra_chain::transaction::zip317::MIN_MEMPOOL_TX_FEE_RATE as f64
1362            / (zebra_chain::amount::COIN as f64);
1363        let difficulty = chain_tip_difficulty(self.network.clone(), self.read_state.clone(), true)
1364            .await
1365            .expect("should always be Ok when `should_use_default` is true");
1366
1367        let response = GetInfoResponse {
1368            version,
1369            build: self.build_version.clone(),
1370            subversion: self.user_agent.clone(),
1371            protocol_version: zebra_network::constants::CURRENT_NETWORK_PROTOCOL_VERSION.0,
1372            blocks: tip_height.0,
1373            connections,
1374            proxy: None,
1375            difficulty,
1376            testnet,
1377            pay_tx_fee,
1378            relay_fee,
1379            errors: last_error_log,
1380            errors_timestamp: last_error_log_time.timestamp(),
1381        };
1382
1383        Ok(response)
1384    }
1385
1386    async fn get_deprecation_info(&self) -> Result<GetDeprecationInfoResponse> {
1387        let end_of_service = self
1388            .end_of_support_height
1389            // End of support is only enforced on Mainnet, and the zcashd-compatible response
1390            // omits `end_of_service` on other networks, even if a height was configured.
1391            .filter(|_| self.network == Network::Mainnet)
1392            .map(|end_of_support_height| {
1393                // Estimate the halt time from the current tip and target block spacing. If the
1394                // tip is not available yet, fall back to the highest compiled-in checkpoint,
1395                // which is close to the network tip at release time.
1396                let tip_height = self
1397                    .latest_chain_tip
1398                    .best_tip_height()
1399                    .unwrap_or_else(|| self.network.checkpoint_list().max_height());
1400                let estimated_time = Utc::now()
1401                    .timestamp()
1402                    .saturating_add(
1403                        NetworkUpgrade::duration_between_heights(
1404                            &self.network,
1405                            tip_height,
1406                            end_of_support_height,
1407                        )
1408                        .num_seconds(),
1409                    )
1410                    .saturating_sub(END_OF_SERVICE_ESTIMATE_SAFETY_MARGIN)
1411                    .max(0);
1412
1413                EndOfService {
1414                    block_height: end_of_support_height.0,
1415                    estimated_time,
1416                }
1417            });
1418
1419        Ok(GetDeprecationInfoResponse { end_of_service })
1420    }
1421
1422    #[allow(clippy::unwrap_in_result)]
1423    async fn get_blockchain_info(&self) -> Result<GetBlockchainInfoResponse> {
1424        let debug_force_finished_sync = self.debug_force_finished_sync;
1425        let network = &self.network;
1426
1427        let (usage_info_rsp, tip_pool_values_rsp, chain_tip_difficulty) = {
1428            use zebra_state::ReadRequest::*;
1429            let state_call = |request| self.read_state.clone().oneshot(request);
1430            tokio::join!(
1431                state_call(UsageInfo),
1432                state_call(TipPoolValues),
1433                chain_tip_difficulty(network.clone(), self.read_state.clone(), true)
1434            )
1435        };
1436
1437        // The fallback tip below has no balances, so it has no NSM value balance either.
1438        let tip_pool_values_found = tip_pool_values_rsp.is_ok();
1439        let (size_on_disk, (tip_height, tip_hash), value_balance, difficulty) = {
1440            use zebra_state::ReadResponse::*;
1441
1442            let UsageInfo(size_on_disk) = usage_info_rsp.map_misc_error()? else {
1443                unreachable!("unmatched response to a TipPoolValues request")
1444            };
1445
1446            let (tip, value_balance) = match tip_pool_values_rsp {
1447                Ok(TipPoolValues {
1448                    tip_height,
1449                    tip_hash,
1450                    value_balance,
1451                }) => ((tip_height, tip_hash), value_balance),
1452                Ok(_) => unreachable!("unmatched response to a TipPoolValues request"),
1453                Err(_) => ((Height::MIN, network.genesis_hash()), Default::default()),
1454            };
1455
1456            let difficulty = chain_tip_difficulty
1457                .expect("should always be Ok when `should_use_default` is true");
1458
1459            (size_on_disk, tip, value_balance, difficulty)
1460        };
1461
1462        let now = Utc::now();
1463        let (estimated_height, verification_progress) = self
1464            .latest_chain_tip
1465            .best_tip_height_and_block_time()
1466            .map(|(tip_height, tip_block_time)| {
1467                let height =
1468                    NetworkChainTipHeightEstimator::new(tip_block_time, tip_height, network)
1469                        .estimate_height_at(now);
1470
1471                // If we're testing the mempool, force the estimated height to be the actual tip height, otherwise,
1472                // check if the estimated height is below Zebra's latest tip height, or if the latest tip's block time is
1473                // later than the current time on the local clock.
1474                let height =
1475                    if tip_block_time > now || height < tip_height || debug_force_finished_sync {
1476                        tip_height
1477                    } else {
1478                        height
1479                    };
1480
1481                (height, f64::from(tip_height.0) / f64::from(height.0))
1482            })
1483            // TODO: Add a `genesis_block_time()` method on `Network` to use here.
1484            .unwrap_or((Height::MIN, 0.0));
1485
1486        let verification_progress = if network.is_regtest() {
1487            1.0
1488        } else {
1489            verification_progress
1490        };
1491
1492        // `upgrades` object
1493        //
1494        // Get the network upgrades in height order, like `zcashd`.
1495        let mut upgrades = IndexMap::new();
1496        for (activation_height, network_upgrade) in network.full_activation_list() {
1497            // Zebra defines network upgrades based on incompatible consensus rule changes,
1498            // but zcashd defines them based on ZIPs.
1499            //
1500            // All the network upgrades with a consensus branch ID are the same in Zebra and zcashd.
1501            if let Some(branch_id) = network_upgrade.branch_id() {
1502                // zcashd's RPC seems to ignore Disabled network upgrades, so Zebra does too.
1503                let status = if tip_height >= activation_height {
1504                    NetworkUpgradeStatus::Active
1505                } else {
1506                    NetworkUpgradeStatus::Pending
1507                };
1508
1509                let upgrade = NetworkUpgradeInfo {
1510                    name: network_upgrade,
1511                    activation_height,
1512                    status,
1513                };
1514                upgrades.insert(ConsensusBranchIdHex(branch_id), upgrade);
1515            }
1516        }
1517
1518        // `consensus` object
1519        let next_block_height =
1520            (tip_height + 1).expect("valid chain tips are a lot less than Height::MAX");
1521        let consensus = TipConsensusBranch {
1522            chain_tip: ConsensusBranchIdHex(
1523                NetworkUpgrade::current(network, tip_height)
1524                    .branch_id()
1525                    .unwrap_or(ConsensusBranchId::RPC_MISSING_ID),
1526            ),
1527            next_block: ConsensusBranchIdHex(
1528                NetworkUpgrade::current(network, next_block_height)
1529                    .branch_id()
1530                    .unwrap_or(ConsensusBranchId::RPC_MISSING_ID),
1531            ),
1532        };
1533
1534        let response = GetBlockchainInfoResponse {
1535            chain: network.bip70_network_name(),
1536            blocks: tip_height,
1537            best_block_hash: tip_hash,
1538            estimated_height,
1539            chain_supply: GetBlockchainInfoBalance::chain_supply(value_balance),
1540            value_pools: GetBlockchainInfoBalance::value_pools(value_balance, None),
1541            nsm_value_balance: tip_pool_values_found.then(|| {
1542                nsm_value_balance_entry(network, tip_height, value_balance.nsm_amount(), None)
1543            }),
1544            upgrades,
1545            consensus,
1546            headers: tip_height,
1547            difficulty,
1548            verification_progress,
1549            // TODO: store work in the finalized state for each height (#7109)
1550            chain_work: 0,
1551            pruned: false,
1552            size_on_disk,
1553            // TODO: Investigate whether this needs to be implemented (it's sprout-only in zcashd)
1554            commitments: 0,
1555        };
1556
1557        Ok(response)
1558    }
1559
1560    async fn get_address_balance(
1561        &self,
1562        address_strings: GetAddressBalanceRequest,
1563    ) -> Result<GetAddressBalanceResponse> {
1564        let valid_addresses = address_strings.valid_addresses()?;
1565
1566        let request = zebra_state::ReadRequest::AddressBalance(valid_addresses);
1567        let response = self
1568            .read_state
1569            .clone()
1570            .oneshot(request)
1571            .await
1572            .map_misc_error()?;
1573
1574        match response {
1575            zebra_state::ReadResponse::AddressBalance { balance, received } => {
1576                Ok(GetAddressBalanceResponse {
1577                    balance: u64::from(balance),
1578                    received,
1579                })
1580            }
1581            _ => unreachable!("Unexpected response from state service: {response:?}"),
1582        }
1583    }
1584
1585    // TODO: use HexData or GetRawTransaction::Bytes to handle the transaction data argument
1586    async fn send_raw_transaction(
1587        &self,
1588        raw_transaction_hex: String,
1589        _allow_high_fees: Option<bool>,
1590    ) -> Result<SendRawTransactionResponse> {
1591        let mempool = self.mempool.clone();
1592        let queue_sender = self.queue_sender.clone();
1593
1594        // Reference for the legacy error code:
1595        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L1259-L1260>
1596        let raw_transaction_bytes = Vec::from_hex(raw_transaction_hex)
1597            .map_error(server::error::LegacyCode::Deserialization)?;
1598        let raw_transaction = Transaction::zcash_deserialize(&*raw_transaction_bytes)
1599            .map_error(server::error::LegacyCode::Deserialization)?;
1600
1601        let transaction_hash = raw_transaction.hash();
1602
1603        // send transaction to the rpc queue, ignore any error.
1604        let raw_transaction = Arc::new(raw_transaction);
1605        let unmined_transaction = UnminedTx::from(raw_transaction.clone());
1606        let _ = queue_sender.send(unmined_transaction);
1607
1608        let transaction_parameter = mempool::Gossip::Tx(raw_transaction.into());
1609        let request = mempool::Request::Queue(vec![transaction_parameter]);
1610
1611        let response = mempool.oneshot(request).await.map_misc_error()?;
1612
1613        let mut queue_results = match response {
1614            mempool::Response::Queued(results) => results,
1615            _ => unreachable!("incorrect response variant from mempool service"),
1616        };
1617
1618        assert_eq!(
1619            queue_results.len(),
1620            1,
1621            "mempool service returned more results than expected"
1622        );
1623
1624        let queue_result = queue_results
1625            .pop()
1626            .expect("there should be exactly one item in Vec")
1627            .inspect_err(|err| tracing::debug!("sent transaction to mempool: {:?}", &err))
1628            .map_misc_error()?
1629            .await
1630            .map_misc_error()?;
1631
1632        tracing::debug!("sent transaction to mempool: {:?}", &queue_result);
1633
1634        queue_result
1635            .map(|_| SendRawTransactionResponse(transaction_hash))
1636            // Reference for the legacy error code:
1637            // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L1290-L1301>
1638            // Note that this error code might not exactly match the one returned by zcashd
1639            // since zcashd's error code selection logic is more granular. We'd need to
1640            // propagate the error coming from the verifier to be able to return more specific
1641            // error codes.
1642            .map_error(server::error::LegacyCode::Verify)
1643    }
1644
1645    // # Performance
1646    //
1647    // `lightwalletd` calls this RPC with verosity 1 for its initial sync of 2 million blocks, the
1648    // performance of this RPC with verbosity 1 significantly affects `lightwalletd`s sync time.
1649    async fn get_block(
1650        &self,
1651        hash_or_height: String,
1652        verbosity: Option<u8>,
1653    ) -> Result<GetBlockResponse> {
1654        let verbosity = verbosity.unwrap_or(1);
1655        let network = self.network.clone();
1656
1657        let hash_or_height =
1658            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
1659                // Reference for the legacy error code:
1660                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
1661                .map_error(server::error::LegacyCode::InvalidParameter)?;
1662
1663        if verbosity == 0 {
1664            let request = zebra_state::ReadRequest::Block(hash_or_height);
1665            let response = self
1666                .read_state
1667                .clone()
1668                .oneshot(request)
1669                .await
1670                .map_misc_error()?;
1671
1672            match response {
1673                zebra_state::ReadResponse::Block(Some(block)) => {
1674                    Ok(GetBlockResponse::Raw(block.into()))
1675                }
1676                zebra_state::ReadResponse::Block(None) => {
1677                    Err("Block not found").map_error(server::error::LegacyCode::InvalidParameter)
1678                }
1679                _ => unreachable!("unmatched response to a block request"),
1680            }
1681        } else if matches!(verbosity, 1..=3) {
1682            // Reuse the already-resolved `hash_or_height` (rather than the
1683            // caller-supplied string) so `get_block_header` resolves to the same
1684            // block this call resolved above, even for tip-relative inputs like a
1685            // negative height. Resolving the caller string a second time here would
1686            // re-sample the best chain at a different instant and could pick a
1687            // different block after a reorg or tip advance. See issue #10550.
1688            let get_block_header_result: Result<GetBlockHeaderResponse> = self
1689                .get_block_header(hash_or_height.to_string(), Some(true))
1690                .await;
1691
1692            let GetBlockHeaderResponse::Object(block_header) = get_block_header_result? else {
1693                panic!("must return Object")
1694            };
1695
1696            let BlockHeaderObject {
1697                hash,
1698                confirmations,
1699                height,
1700                version,
1701                merkle_root,
1702                block_commitments,
1703                final_sapling_root,
1704                sapling_tree_size,
1705                time,
1706                nonce,
1707                solution,
1708                bits,
1709                difficulty,
1710                previous_block_hash,
1711                next_block_hash,
1712            } = *block_header;
1713
1714            // # Concurrency
1715            //
1716            // We look up by block hash so the hash, transaction IDs, and confirmations
1717            // are consistent. Bind every follow-up read to the resolved block hash
1718            // rather than the caller-supplied hash-or-height, so a reorg between the
1719            // header lookup and these reads cannot mix block A's header with block B's
1720            // contents. See issue #10550.
1721            let hash_or_height = hash.into();
1722            let transactions_request = match verbosity {
1723                1 => zebra_state::ReadRequest::TransactionIdsForBlock(hash_or_height),
1724                2 | 3 => zebra_state::ReadRequest::BlockAndSize(hash_or_height),
1725                _other => panic!("get_block_header_fut should be none"),
1726            };
1727
1728            // Confirmations is `-1` when the resolved header is no longer on the
1729            // best chain. Avoid panicking on `try_into()` in the verbosity-2 path,
1730            // and label such transactions as not in the active chain.
1731            let in_active_chain = confirmations >= 0;
1732
1733            // Verbosity 3 adds each input's prevout and the transaction fee, resolved from the
1734            // outputs spent by this block in the best chain. Fetch them before the `futs` batch
1735            // below: issuing this read while those requests are in flight would contend with them
1736            // for a bounded `read_state` buffer's slot and deadlock, because `futs` is not polled
1737            // while this future is awaited. A spent output not found in the best chain is absent
1738            // from the map, so its input gets no `prevout` and its transaction gets no `fee`.
1739            let spent_outputs = if verbosity == 3 {
1740                let response = self
1741                    .read_state
1742                    .clone()
1743                    .oneshot(zebra_state::ReadRequest::SpentOutputs(hash_or_height))
1744                    .await
1745                    .map_misc_error()?;
1746                let zebra_state::ReadResponse::SpentOutputs(spent_outputs) = response else {
1747                    unreachable!("unmatched response to a SpentOutputs request");
1748                };
1749                spent_outputs.unwrap_or_default()
1750            } else {
1751                HashMap::new()
1752            };
1753
1754            let requests = vec![
1755                // Get transaction IDs from the transaction index by block hash
1756                //
1757                // # Concurrency
1758                //
1759                // A block's transaction IDs are never modified, so all possible responses are
1760                // valid. Clients that query block heights must be able to handle chain forks,
1761                // including getting transaction IDs from any chain fork.
1762                transactions_request,
1763                // Orchard trees
1764                zebra_state::ReadRequest::OrchardTree(hash_or_height),
1765                // Ironwood trees
1766                zebra_state::ReadRequest::IronwoodTree(hash_or_height),
1767                // Block info
1768                zebra_state::ReadRequest::BlockInfo(previous_block_hash.into()),
1769                zebra_state::ReadRequest::BlockInfo(hash_or_height),
1770            ];
1771
1772            let mut futs = FuturesOrdered::new();
1773
1774            for request in requests {
1775                futs.push_back(self.read_state.clone().oneshot(request));
1776            }
1777
1778            let tx_ids_response = futs.next().await.expect("`futs` should not be empty");
1779            let (tx, size): (Vec<_>, Option<usize>) = match tx_ids_response.map_misc_error()? {
1780                zebra_state::ReadResponse::TransactionIdsForBlock(tx_ids) => (
1781                    tx_ids
1782                        .ok_or_misc_error("block not found")?
1783                        .iter()
1784                        .map(|tx_id| GetBlockTransaction::Hash(*tx_id))
1785                        .collect(),
1786                    None,
1787                ),
1788                zebra_state::ReadResponse::BlockAndSize(block_and_size) => {
1789                    let (block, size) = block_and_size.ok_or_misc_error("Block not found")?;
1790                    let block_time = block.header.time;
1791
1792                    let mut transactions = Vec::with_capacity(block.transactions.len());
1793                    for tx in block.transactions.iter() {
1794                        let mut object = TransactionObject::from_transaction(
1795                            tx.clone(),
1796                            Some(height),
1797                            Some(confirmations),
1798                            &network,
1799                            Some(block_time),
1800                            Some(hash),
1801                            Some(in_active_chain),
1802                            tx.hash(),
1803                        );
1804
1805                        if verbosity == 3 {
1806                            object.add_prevouts(tx, &spent_outputs, &network);
1807                        }
1808
1809                        transactions.push(GetBlockTransaction::Object(Box::new(object)));
1810                    }
1811                    (transactions, Some(size))
1812                }
1813                _ => unreachable!("unmatched response to a transaction_ids_for_block request"),
1814            };
1815
1816            let orchard_tree_response = futs.next().await.expect("`futs` should not be empty");
1817            let zebra_state::ReadResponse::OrchardTree(orchard_tree) =
1818                orchard_tree_response.map_misc_error()?
1819            else {
1820                unreachable!("unmatched response to a OrchardTree request");
1821            };
1822
1823            let nu5_activation = NetworkUpgrade::Nu5.activation_height(&network);
1824
1825            // This could be `None` if there's a chain reorg between state queries.
1826            let orchard_tree = orchard_tree.ok_or_misc_error("missing Orchard tree")?;
1827
1828            let final_orchard_root = match nu5_activation {
1829                Some(activation_height) if height >= activation_height => {
1830                    Some(orchard_tree.root().into())
1831                }
1832                _other => None,
1833            };
1834
1835            let sapling = SaplingTrees {
1836                size: sapling_tree_size,
1837            };
1838
1839            let orchard_tree_size = orchard_tree.count();
1840            let orchard = OrchardTrees {
1841                size: orchard_tree_size,
1842            };
1843
1844            let ironwood_tree_response = futs.next().await.expect("`futs` should not be empty");
1845            let zebra_state::ReadResponse::IronwoodTree(ironwood_tree) =
1846                ironwood_tree_response.map_misc_error()?
1847            else {
1848                unreachable!("unmatched response to an IronwoodTree request");
1849            };
1850
1851            // This could be `None` if there's a chain reorg between state queries. Before NU6.3 the
1852            // Ironwood tree is empty (size 0).
1853            let ironwood_tree = ironwood_tree.ok_or_misc_error("missing Ironwood tree")?;
1854            let ironwood = IronwoodTrees {
1855                size: ironwood_tree.count(),
1856            };
1857
1858            let trees = GetBlockTrees {
1859                sapling,
1860                orchard,
1861                ironwood,
1862            };
1863
1864            let block_info_response = futs.next().await.expect("`futs` should not be empty");
1865            let zebra_state::ReadResponse::BlockInfo(prev_block_info) =
1866                block_info_response.map_misc_error()?
1867            else {
1868                unreachable!("unmatched response to a BlockInfo request");
1869            };
1870            let block_info_response = futs.next().await.expect("`futs` should not be empty");
1871            let zebra_state::ReadResponse::BlockInfo(block_info) =
1872                block_info_response.map_misc_error()?
1873            else {
1874                unreachable!("unmatched response to a BlockInfo request");
1875            };
1876
1877            // The balances before the genesis block are zero. For other blocks, the parent's
1878            // balances can be missing if a reorg occurs between the two reads. In that case, the
1879            // change is not known, so the response does not include it.
1880            let delta = block_info.as_ref().and_then(|d| {
1881                let value_pools = d.value_pools().constrain::<NegativeAllowed>().ok()?;
1882                let prev_value_pools = match prev_block_info {
1883                    Some(prev) => prev.value_pools().constrain::<NegativeAllowed>().ok()?,
1884                    None if previous_block_hash == GENESIS_PREVIOUS_BLOCK_HASH => {
1885                        ValueBalance::<NegativeAllowed>::zero()
1886                    }
1887                    None => return None,
1888                };
1889                (value_pools - prev_value_pools).ok()
1890            });
1891            let size = size.or(block_info.as_ref().map(|d| d.size() as usize));
1892
1893            Ok(GetBlockResponse::Object(Box::new(BlockObject {
1894                hash,
1895                confirmations,
1896                height: Some(height),
1897                version: Some(version),
1898                merkle_root: Some(merkle_root),
1899                time: Some(time),
1900                nonce: Some(nonce),
1901                solution: Some(solution),
1902                bits: Some(bits),
1903                difficulty: Some(difficulty),
1904                n_tx: tx.len(),
1905                tx,
1906                trees,
1907                chain_supply: block_info
1908                    .as_ref()
1909                    .map(|d| GetBlockchainInfoBalance::chain_supply(*d.value_pools())),
1910                nsm_value_balance: block_info.as_ref().map(|d| {
1911                    nsm_value_balance_entry(
1912                        &network,
1913                        height,
1914                        d.value_pools().nsm_amount(),
1915                        delta.map(|delta| delta.nsm_amount()),
1916                    )
1917                }),
1918                value_pools: block_info
1919                    .map(|d| GetBlockchainInfoBalance::value_pools(*d.value_pools(), delta)),
1920                size: size.map(|size| size as i64),
1921                block_commitments: Some(block_commitments),
1922                final_sapling_root: Some(final_sapling_root),
1923                final_orchard_root,
1924                previous_block_hash: Some(previous_block_hash),
1925                next_block_hash,
1926            })))
1927        } else {
1928            Err("invalid verbosity value").map_error(server::error::LegacyCode::InvalidParameter)
1929        }
1930    }
1931
1932    async fn get_block_header(
1933        &self,
1934        hash_or_height: String,
1935        verbose: Option<bool>,
1936    ) -> Result<GetBlockHeaderResponse> {
1937        let verbose = verbose.unwrap_or(true);
1938        let network = self.network.clone();
1939
1940        let hash_or_height =
1941            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
1942                // Reference for the legacy error code:
1943                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
1944                .map_error(server::error::LegacyCode::InvalidParameter)?;
1945        let zebra_state::ReadResponse::BlockHeader {
1946            header,
1947            hash,
1948            height,
1949            next_block_hash,
1950        } = self
1951            .read_state
1952            .clone()
1953            .oneshot(zebra_state::ReadRequest::BlockHeader(hash_or_height))
1954            .await
1955            .map_err(|_| "block height not in best chain")
1956            .map_error(
1957                // ## Compatibility with `zcashd`.
1958                //
1959                // Since this function is reused by getblock(), we return the errors
1960                // expected by it (they differ whether a hash or a height was passed).
1961                if hash_or_height.hash().is_some() {
1962                    server::error::LegacyCode::InvalidAddressOrKey
1963                } else {
1964                    server::error::LegacyCode::InvalidParameter
1965                },
1966            )?
1967        else {
1968            panic!("unexpected response to BlockHeader request")
1969        };
1970
1971        let response = if !verbose {
1972            GetBlockHeaderResponse::Raw(HexData(header.zcash_serialize_to_vec().map_misc_error()?))
1973        } else {
1974            // Bind follow-up reads to the resolved block hash so the SaplingTree
1975            // and Depth lookups are taken from the same chain view as the header.
1976            // Using the caller-supplied `hash_or_height` here would re-sample the
1977            // best chain and could mix a header from block A with a Sapling tree
1978            // from block B at the same height. See issue #10550.
1979            let zebra_state::ReadResponse::SaplingTree(sapling_tree) = self
1980                .read_state
1981                .clone()
1982                .oneshot(zebra_state::ReadRequest::SaplingTree(hash.into()))
1983                .await
1984                .map_misc_error()?
1985            else {
1986                panic!("unexpected response to SaplingTree request")
1987            };
1988
1989            // This could be `None` if there's a chain reorg between state queries.
1990            let sapling_tree = sapling_tree.ok_or_misc_error("missing Sapling tree")?;
1991
1992            let zebra_state::ReadResponse::Depth(depth) = self
1993                .read_state
1994                .clone()
1995                .oneshot(zebra_state::ReadRequest::Depth(hash))
1996                .await
1997                .map_misc_error()?
1998            else {
1999                panic!("unexpected response to SaplingTree request")
2000            };
2001
2002            // From <https://zcash.github.io/rpc/getblock.html>
2003            // TODO: Deduplicate const definition, consider refactoring this to avoid duplicate logic
2004            const NOT_IN_BEST_CHAIN_CONFIRMATIONS: i64 = -1;
2005
2006            // Confirmations are one more than the depth.
2007            // Depth is limited by height, so it will never overflow an i64.
2008            let confirmations = depth
2009                .map(|depth| i64::from(depth) + 1)
2010                .unwrap_or(NOT_IN_BEST_CHAIN_CONFIRMATIONS);
2011
2012            let mut nonce = *header.nonce;
2013            nonce.reverse();
2014
2015            let sapling_activation = NetworkUpgrade::Sapling.activation_height(&network);
2016            let sapling_tree_size = sapling_tree.count();
2017            let final_sapling_root: [u8; 32] =
2018                if sapling_activation.is_some() && height >= sapling_activation.unwrap() {
2019                    let mut root: [u8; 32] = sapling_tree.root().into();
2020                    root.reverse();
2021                    root
2022                } else {
2023                    [0; 32]
2024                };
2025
2026            let difficulty = header.difficulty_threshold.relative_to_network(&network);
2027
2028            let block_commitments = match header.commitment(&network, height).expect(
2029                "Unexpected failure while parsing the blockcommitments field in get_block_header",
2030            ) {
2031                Commitment::PreSaplingReserved(bytes) => bytes,
2032                Commitment::FinalSaplingRoot(_) => final_sapling_root,
2033                Commitment::ChainHistoryActivationReserved => [0; 32],
2034                Commitment::ChainHistoryRoot(root) => root.bytes_in_display_order(),
2035                Commitment::ChainHistoryBlockTxAuthCommitment(hash) => {
2036                    hash.bytes_in_display_order()
2037                }
2038            };
2039
2040            let block_header = BlockHeaderObject {
2041                hash,
2042                confirmations,
2043                height,
2044                version: header.version,
2045                merkle_root: header.merkle_root,
2046                block_commitments,
2047                final_sapling_root,
2048                sapling_tree_size,
2049                time: header.time.timestamp(),
2050                nonce,
2051                solution: header.solution,
2052                bits: header.difficulty_threshold,
2053                difficulty,
2054                previous_block_hash: header.previous_block_hash,
2055                next_block_hash,
2056            };
2057
2058            GetBlockHeaderResponse::Object(Box::new(block_header))
2059        };
2060
2061        Ok(response)
2062    }
2063
2064    fn get_best_block_hash(&self) -> Result<GetBlockHashResponse> {
2065        self.latest_chain_tip
2066            .best_tip_hash()
2067            .map(GetBlockHashResponse)
2068            .ok_or_misc_error("No blocks in state")
2069    }
2070
2071    fn get_best_block_height_and_hash(&self) -> Result<GetBlockHeightAndHashResponse> {
2072        self.latest_chain_tip
2073            .best_tip_height_and_hash()
2074            .map(|(height, hash)| GetBlockHeightAndHashResponse { height, hash })
2075            .ok_or_misc_error("No blocks in state")
2076    }
2077
2078    async fn get_mempool_info(&self) -> Result<GetMempoolInfoResponse> {
2079        let mut mempool = self.mempool.clone();
2080
2081        let response = mempool
2082            .ready()
2083            .and_then(|service| service.call(mempool::Request::QueueStats))
2084            .await
2085            .map_misc_error()?;
2086
2087        if let mempool::Response::QueueStats {
2088            size,
2089            bytes,
2090            usage,
2091            fully_notified,
2092        } = response
2093        {
2094            Ok(GetMempoolInfoResponse {
2095                size,
2096                bytes,
2097                usage,
2098                fully_notified,
2099            })
2100        } else {
2101            unreachable!("unexpected response to QueueStats request")
2102        }
2103    }
2104
2105    async fn get_raw_mempool(&self, verbose: Option<bool>) -> Result<GetRawMempoolResponse> {
2106        #[allow(unused)]
2107        let verbose = verbose.unwrap_or(false);
2108
2109        use zebra_chain::block::MAX_BLOCK_BYTES;
2110
2111        let mut mempool = self.mempool.clone();
2112
2113        let request = if verbose {
2114            mempool::Request::FullTransactions
2115        } else {
2116            mempool::Request::TransactionIds
2117        };
2118
2119        // `zcashd` doesn't check if it is synced to the tip here, so we don't either.
2120        let response = mempool
2121            .ready()
2122            .and_then(|service| service.call(request))
2123            .await
2124            .map_misc_error()?;
2125
2126        match response {
2127            mempool::Response::FullTransactions {
2128                mut transactions,
2129                transaction_dependencies,
2130                last_seen_tip_hash: _,
2131            } => {
2132                if verbose {
2133                    let transactions_by_id = transactions
2134                        .iter()
2135                        .map(|unmined_tx| (unmined_tx.transaction.id.mined_id(), unmined_tx))
2136                        .collect::<HashMap<_, _>>();
2137                    let map = transactions
2138                        .iter()
2139                        .map(|unmined_tx| {
2140                            (
2141                                unmined_tx.transaction.id.mined_id().encode_hex(),
2142                                get_raw_mempool::MempoolObject::from_verified_unmined_tx(
2143                                    unmined_tx,
2144                                    &transactions_by_id,
2145                                    &transaction_dependencies,
2146                                ),
2147                            )
2148                        })
2149                        .collect::<HashMap<_, _>>();
2150                    Ok(GetRawMempoolResponse::Verbose(map))
2151                } else {
2152                    // Sort transactions in descending order by fee/size, using
2153                    // hash in serialized byte order as a tie-breaker. Note that
2154                    // this is only done in not verbose because in verbose mode
2155                    // a dictionary is returned, where order does not matter.
2156                    transactions.sort_by_cached_key(|tx| {
2157                        // zcashd uses modified fee here but Zebra doesn't currently
2158                        // support prioritizing transactions
2159                        cmp::Reverse((
2160                            i64::from(tx.miner_fee) as u128 * MAX_BLOCK_BYTES as u128
2161                                / tx.transaction.size as u128,
2162                            // transaction hashes are compared in their serialized byte-order.
2163                            tx.transaction.id.mined_id(),
2164                        ))
2165                    });
2166                    let tx_ids: Vec<String> = transactions
2167                        .iter()
2168                        .map(|unmined_tx| unmined_tx.transaction.id.mined_id().encode_hex())
2169                        .collect();
2170
2171                    Ok(GetRawMempoolResponse::TxIds(tx_ids))
2172                }
2173            }
2174
2175            mempool::Response::TransactionIds(unmined_transaction_ids) => {
2176                let mut tx_ids: Vec<String> = unmined_transaction_ids
2177                    .iter()
2178                    .map(|id| id.mined_id().encode_hex())
2179                    .collect();
2180
2181                // Sort returned transaction IDs in numeric/string order.
2182                tx_ids.sort();
2183
2184                Ok(GetRawMempoolResponse::TxIds(tx_ids))
2185            }
2186
2187            _ => unreachable!("unmatched response to a transactionids request"),
2188        }
2189    }
2190
2191    async fn get_raw_transaction(
2192        &self,
2193        txid: String,
2194        verbose: Option<u8>,
2195        block_hash: Option<String>,
2196    ) -> Result<GetRawTransactionResponse> {
2197        let mut mempool = self.mempool.clone();
2198        let verbose = verbose.unwrap_or(0) != 0;
2199
2200        // Reference for the legacy error code:
2201        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/rawtransaction.cpp#L544>
2202        let txid = transaction::Hash::from_hex(txid)
2203            .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
2204
2205        // Check the mempool first.
2206        if block_hash.is_none() {
2207            match mempool
2208                .ready()
2209                .and_then(|service| {
2210                    service.call(mempool::Request::TransactionsByMinedId([txid].into()))
2211                })
2212                .await
2213                .map_misc_error()?
2214            {
2215                mempool::Response::Transactions(txns) => {
2216                    if let Some(tx) = txns.first() {
2217                        return Ok(if verbose {
2218                            GetRawTransactionResponse::Object(Box::new(
2219                                TransactionObject::from_transaction(
2220                                    tx.transaction.clone(),
2221                                    None,
2222                                    None,
2223                                    &self.network,
2224                                    None,
2225                                    None,
2226                                    Some(false),
2227                                    txid,
2228                                ),
2229                            ))
2230                        } else {
2231                            let hex = tx.transaction.clone().into();
2232                            GetRawTransactionResponse::Raw(hex)
2233                        });
2234                    }
2235                }
2236
2237                _ => unreachable!("unmatched response to a `TransactionsByMinedId` request"),
2238            };
2239        }
2240
2241        let caller_block_context = if let Some(block_hash) = block_hash {
2242            let block_hash = block::Hash::from_hex(block_hash)
2243                .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
2244            match self
2245                .read_state
2246                .clone()
2247                .oneshot(zebra_state::ReadRequest::AnyChainTransactionIdsForBlock(
2248                    block_hash.into(),
2249                ))
2250                .await
2251                .map_misc_error()?
2252            {
2253                zebra_state::ReadResponse::AnyChainTransactionIdsForBlock(tx_ids) => {
2254                    let (ids, in_best_chain) = tx_ids.ok_or_error(
2255                        server::error::LegacyCode::InvalidAddressOrKey,
2256                        "block not found",
2257                    )?;
2258
2259                    ids.iter().find(|id| **id == txid).ok_or_error(
2260                        server::error::LegacyCode::InvalidAddressOrKey,
2261                        "txid not found",
2262                    )?;
2263
2264                    Some((block_hash, in_best_chain))
2265                }
2266                _ => {
2267                    unreachable!("unmatched response to a `AnyChainTransactionIdsForBlock` request")
2268                }
2269            }
2270        } else {
2271            None
2272        };
2273
2274        // If the tx wasn't in the mempool, check the state.
2275        match self
2276            .read_state
2277            .clone()
2278            .oneshot(zebra_state::ReadRequest::AnyChainTransaction(txid))
2279            .await
2280            .map_misc_error()?
2281        {
2282            zebra_state::ReadResponse::AnyChainTransaction(Some(tx)) => Ok(if verbose {
2283                if let Some((caller_block_hash, in_best_chain)) = caller_block_context {
2284                    // Use the caller-provided block context to avoid TOCTOU races
2285                    // between the validation query and the transaction fetch.
2286                    let (raw_tx, height, confirmations, block_time) = match &tx {
2287                        AnyTx::Mined(mined) if in_best_chain => (
2288                            mined.tx.clone(),
2289                            Some(mined.height),
2290                            Some(mined.confirmations.into()),
2291                            Some(mined.block_time),
2292                        ),
2293                        _ => {
2294                            let raw_tx: Arc<Transaction> = tx.into();
2295                            (raw_tx, None, None, None)
2296                        }
2297                    };
2298
2299                    GetRawTransactionResponse::Object(Box::new(
2300                        TransactionObject::from_transaction(
2301                            raw_tx,
2302                            height,
2303                            confirmations,
2304                            &self.network,
2305                            block_time,
2306                            Some(caller_block_hash),
2307                            Some(in_best_chain),
2308                            txid,
2309                        ),
2310                    ))
2311                } else {
2312                    match tx {
2313                        AnyTx::Mined(tx) => {
2314                            let block_hash = match self
2315                                .read_state
2316                                .clone()
2317                                .oneshot(zebra_state::ReadRequest::BestChainBlockHash(tx.height))
2318                                .await
2319                                .map_misc_error()?
2320                            {
2321                                zebra_state::ReadResponse::BlockHash(block_hash) => block_hash,
2322                                _ => {
2323                                    unreachable!(
2324                                        "unmatched response to a `BestChainBlockHash` request"
2325                                    )
2326                                }
2327                            };
2328
2329                            GetRawTransactionResponse::Object(Box::new(
2330                                TransactionObject::from_transaction(
2331                                    tx.tx.clone(),
2332                                    Some(tx.height),
2333                                    Some(tx.confirmations.into()),
2334                                    &self.network,
2335                                    // TODO: Performance gain:
2336                                    // https://github.com/ZcashFoundation/zebra/pull/9458#discussion_r2059352752
2337                                    Some(tx.block_time),
2338                                    block_hash,
2339                                    Some(true),
2340                                    txid,
2341                                ),
2342                            ))
2343                        }
2344                        AnyTx::Side((tx, block_hash)) => GetRawTransactionResponse::Object(
2345                            Box::new(TransactionObject::from_transaction(
2346                                tx.clone(),
2347                                None,
2348                                None,
2349                                &self.network,
2350                                None,
2351                                Some(block_hash),
2352                                Some(false),
2353                                txid,
2354                            )),
2355                        ),
2356                    }
2357                }
2358            } else {
2359                let tx: Arc<Transaction> = tx.into();
2360                let hex = tx.into();
2361                GetRawTransactionResponse::Raw(hex)
2362            }),
2363
2364            zebra_state::ReadResponse::AnyChainTransaction(None) => {
2365                Err("Transaction not found in mempool or best chain")
2366                    .map_error(server::error::LegacyCode::InvalidAddressOrKey)
2367            }
2368
2369            _ => unreachable!("unmatched response to a `Transaction` read request"),
2370        }
2371    }
2372
2373    async fn z_get_treestate(&self, hash_or_height: String) -> Result<GetTreestateResponse> {
2374        let mut read_state = self.read_state.clone();
2375        let network = self.network.clone();
2376
2377        let hash_or_height =
2378            HashOrHeight::new(&hash_or_height, self.latest_chain_tip.best_tip_height())
2379                // Reference for the legacy error code:
2380                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
2381                .map_error(server::error::LegacyCode::InvalidParameter)?;
2382
2383        // Fetch the block referenced by [`hash_or_height`] from the state.
2384        //
2385        // # Concurrency
2386        //
2387        // For consistency, this lookup must be performed first, then all the other lookups must
2388        // be based on the hash. The tree lookups check every chain, so a reorg that moves the
2389        // block onto a side chain after this lookup can't make its treestate disappear.
2390        //
2391        // TODO: If this RPC is called a lot, just get the block header, rather than the whole block.
2392        let block = match read_state
2393            .ready()
2394            .and_then(|service| service.call(zebra_state::ReadRequest::Block(hash_or_height)))
2395            .await
2396            .map_misc_error()?
2397        {
2398            zebra_state::ReadResponse::Block(Some(block)) => block,
2399            zebra_state::ReadResponse::Block(None) => {
2400                // Reference for the legacy error code:
2401                // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/blockchain.cpp#L629>
2402                return Err("the requested block is not in the main chain")
2403                    .map_error(server::error::LegacyCode::InvalidParameter);
2404            }
2405            _ => unreachable!("unmatched response to a block request"),
2406        };
2407
2408        let hash = hash_or_height
2409            .hash_or_else(|_| Some(block.hash()))
2410            .expect("block hash");
2411
2412        let height = hash_or_height
2413            .height_or_else(|_| block.coinbase_height())
2414            .expect("verified blocks have a coinbase height");
2415
2416        let time = u32::try_from(block.header.time.timestamp())
2417            .expect("Timestamps of valid blocks always fit into u32.");
2418
2419        let sapling = if network.is_nu_active(consensus::NetworkUpgrade::Sapling, height.into()) {
2420            match read_state
2421                .ready()
2422                .and_then(|service| {
2423                    service.call(zebra_state::ReadRequest::AnyChainSaplingTree(hash))
2424                })
2425                .await
2426                .map_misc_error()?
2427            {
2428                zebra_state::ReadResponse::SaplingTree(tree) => {
2429                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
2430                }
2431                _ => unreachable!("unmatched response to a Sapling tree request"),
2432            }
2433        } else {
2434            None
2435        };
2436        let (sapling_tree, sapling_root) =
2437            sapling.map_or((None, None), |(tree, root)| (Some(tree), Some(root)));
2438
2439        let orchard = if network.is_nu_active(consensus::NetworkUpgrade::Nu5, height.into()) {
2440            match read_state
2441                .ready()
2442                .and_then(|service| {
2443                    service.call(zebra_state::ReadRequest::AnyChainOrchardTree(hash))
2444                })
2445                .await
2446                .map_misc_error()?
2447            {
2448                zebra_state::ReadResponse::OrchardTree(tree) => {
2449                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
2450                }
2451                _ => unreachable!("unmatched response to an Orchard tree request"),
2452            }
2453        } else {
2454            None
2455        };
2456        let (orchard_tree, orchard_root) =
2457            orchard.map_or((None, None), |(tree, root)| (Some(tree), Some(root)));
2458
2459        let ironwood = if network.is_nu_active(consensus::NetworkUpgrade::Nu6_3, height.into()) {
2460            match read_state
2461                .ready()
2462                .and_then(|service| {
2463                    service.call(zebra_state::ReadRequest::AnyChainIronwoodTree(hash))
2464                })
2465                .await
2466                .map_misc_error()?
2467            {
2468                zebra_state::ReadResponse::IronwoodTree(tree) => {
2469                    tree.map(|t| (t.to_rpc_bytes(), t.root().bytes_in_display_order().to_vec()))
2470                }
2471                _ => unreachable!("unmatched response to an Ironwood tree request"),
2472            }
2473        } else {
2474            None
2475        };
2476        // Only present from NU6.3, so pre-NU6.3 responses keep the sprout/sapling/orchard shape.
2477        let ironwood = ironwood
2478            .map(|(tree, root)| Treestate::new(trees::Commitments::new(Some(root), Some(tree))));
2479
2480        Ok(GetTreestateResponse::new(
2481            hash,
2482            height,
2483            time,
2484            // We can't currently return Sprout data because we don't store it for
2485            // old heights.
2486            None,
2487            Treestate::new(trees::Commitments::new(sapling_root, sapling_tree)),
2488            Treestate::new(trees::Commitments::new(orchard_root, orchard_tree)),
2489            ironwood,
2490        ))
2491    }
2492
2493    async fn z_get_subtrees_by_index(
2494        &self,
2495        pool: String,
2496        start_index: NoteCommitmentSubtreeIndex,
2497        limit: Option<NoteCommitmentSubtreeIndex>,
2498    ) -> Result<GetSubtreesByIndexResponse> {
2499        let mut read_state = self.read_state.clone();
2500
2501        const POOL_LIST: &[&str] = &["sapling", "orchard", "ironwood"];
2502
2503        if pool == "sapling" {
2504            let request = zebra_state::ReadRequest::SaplingSubtrees { start_index, limit };
2505            let response = read_state
2506                .ready()
2507                .and_then(|service| service.call(request))
2508                .await
2509                .map_misc_error()?;
2510
2511            let subtrees = match response {
2512                zebra_state::ReadResponse::SaplingSubtrees(subtrees) => subtrees,
2513                _ => unreachable!("unmatched response to a subtrees request"),
2514            };
2515
2516            let subtrees = subtrees
2517                .values()
2518                .map(|subtree| SubtreeRpcData {
2519                    root: subtree.root.to_bytes().encode_hex(),
2520                    end_height: subtree.end_height,
2521                })
2522                .collect();
2523
2524            Ok(GetSubtreesByIndexResponse {
2525                pool,
2526                start_index,
2527                subtrees,
2528            })
2529        } else if pool == "orchard" {
2530            let request = zebra_state::ReadRequest::OrchardSubtrees { start_index, limit };
2531            let response = read_state
2532                .ready()
2533                .and_then(|service| service.call(request))
2534                .await
2535                .map_misc_error()?;
2536
2537            let subtrees = match response {
2538                zebra_state::ReadResponse::OrchardSubtrees(subtrees) => subtrees,
2539                _ => unreachable!("unmatched response to a subtrees request"),
2540            };
2541
2542            let subtrees = subtrees
2543                .values()
2544                .map(|subtree| SubtreeRpcData {
2545                    root: subtree.root.encode_hex(),
2546                    end_height: subtree.end_height,
2547                })
2548                .collect();
2549
2550            Ok(GetSubtreesByIndexResponse {
2551                pool,
2552                start_index,
2553                subtrees,
2554            })
2555        } else if pool == "ironwood" {
2556            let request = zebra_state::ReadRequest::IronwoodSubtrees { start_index, limit };
2557            let response = read_state
2558                .ready()
2559                .and_then(|service| service.call(request))
2560                .await
2561                .map_misc_error()?;
2562
2563            let subtrees = match response {
2564                zebra_state::ReadResponse::IronwoodSubtrees(subtrees) => subtrees,
2565                _ => unreachable!("unmatched response to a subtrees request"),
2566            };
2567
2568            // Ironwood reuses the Orchard note type, so the subtree root is encoded like Orchard's.
2569            let subtrees = subtrees
2570                .values()
2571                .map(|subtree| SubtreeRpcData {
2572                    root: subtree.root.encode_hex(),
2573                    end_height: subtree.end_height,
2574                })
2575                .collect();
2576
2577            Ok(GetSubtreesByIndexResponse {
2578                pool,
2579                start_index,
2580                subtrees,
2581            })
2582        } else {
2583            Err(ErrorObject::owned(
2584                server::error::LegacyCode::Misc.into(),
2585                format!("invalid pool name, must be one of: {POOL_LIST:?}").as_str(),
2586                None::<()>,
2587            ))
2588        }
2589    }
2590
2591    async fn get_address_tx_ids(&self, request: GetAddressTxIdsRequest) -> Result<Vec<String>> {
2592        let mut read_state = self.read_state.clone();
2593        let latest_chain_tip = self.latest_chain_tip.clone();
2594
2595        let height_range = build_height_range(
2596            request.start,
2597            request.end,
2598            best_chain_tip_height(&latest_chain_tip)?,
2599        )?;
2600
2601        let valid_addresses = request.valid_addresses()?;
2602
2603        // Ask for one more than the cap, so an oversized result can be detected.
2604        let cap = self.max_address_query_results;
2605        let request = zebra_state::ReadRequest::TransactionIdsByAddresses {
2606            addresses: valid_addresses,
2607            height_range,
2608            max_entries: Some(cap.saturating_add(1)),
2609        };
2610        let response = read_state
2611            .ready()
2612            .and_then(|service| service.call(request))
2613            .await
2614            .map_misc_error()?;
2615
2616        let hashes = match response {
2617            zebra_state::ReadResponse::AddressesTransactionIds(hashes) => {
2618                if hashes.len() > cap {
2619                    return Err(format!(
2620                        "more than {cap} transactions match; narrow the height range"
2621                    ))
2622                    .map_error(server::error::LegacyCode::InvalidParameter);
2623                }
2624
2625                let mut last_tx_location = TransactionLocation::from_usize(Height(0), 0);
2626
2627                hashes
2628                    .iter()
2629                    .map(|(tx_loc, tx_id)| {
2630                        // Check that the returned transactions are in chain order.
2631                        assert!(
2632                            *tx_loc > last_tx_location,
2633                            "Transactions were not in chain order:\n\
2634                                 {tx_loc:?} {tx_id:?} was after:\n\
2635                                 {last_tx_location:?}",
2636                        );
2637
2638                        last_tx_location = *tx_loc;
2639
2640                        tx_id.to_string()
2641                    })
2642                    .collect()
2643            }
2644            _ => unreachable!("unmatched response to a TransactionsByAddresses request"),
2645        };
2646
2647        Ok(hashes)
2648    }
2649
2650    async fn get_address_utxos(
2651        &self,
2652        utxos_request: GetAddressUtxosRequest,
2653    ) -> Result<GetAddressUtxosResponse> {
2654        let mut read_state = self.read_state.clone();
2655        let mut response_utxos = vec![];
2656
2657        let valid_addresses = utxos_request.valid_addresses()?;
2658
2659        // Clamp rather than error: a start height above the chain selects nothing, which is
2660        // already what the request means.
2661        let start_height = Height(
2662            u32::try_from(utxos_request.start_height)
2663                .unwrap_or(u32::MAX)
2664                .min(Height::MAX.0),
2665        );
2666        // Cast is safe: `usize` is at least 32 bits on all supported platforms.
2667        let requested_entries = utxos_request.max_entries as usize;
2668        let cap = self.max_address_query_results;
2669        if requested_entries > cap {
2670            return Err(format!("maxEntries must be at most {cap}"))
2671                .map_error(server::error::LegacyCode::InvalidParameter);
2672        }
2673
2674        // Without `maxEntries`, ask for one more than the cap, so an oversized result can be detected.
2675        let max_entries = if requested_entries > 0 {
2676            requested_entries
2677        } else {
2678            cap.saturating_add(1)
2679        };
2680
2681        // get utxos data for addresses
2682        let request = zebra_state::ReadRequest::UtxosByAddresses {
2683            addresses: valid_addresses,
2684            height_range: start_height..=Height::MAX,
2685            max_entries: Some(max_entries),
2686        };
2687        let response = read_state
2688            .ready()
2689            .and_then(|service| service.call(request))
2690            .await
2691            .map_misc_error()?;
2692        let utxos = match response {
2693            zebra_state::ReadResponse::AddressUtxos(utxos) => utxos,
2694            _ => unreachable!("unmatched response to a UtxosByAddresses request"),
2695        };
2696
2697        let mut last_output_location = OutputLocation::from_usize(Height(0), 0, 0);
2698
2699        for utxo_data in utxos.utxos() {
2700            let address = utxo_data.0;
2701            let txid = *utxo_data.1;
2702            let height = utxo_data.2.height();
2703            let output_index = utxo_data.2.output_index();
2704            let script = utxo_data.3.lock_script.clone();
2705            let satoshis = u64::from(utxo_data.3.value);
2706
2707            let output_location = *utxo_data.2;
2708            // Check that the returned UTXOs are in chain order.
2709            assert!(
2710                output_location > last_output_location,
2711                "UTXOs were not in chain order:\n\
2712                     {output_location:?} {address:?} {txid:?} was after:\n\
2713                     {last_output_location:?}",
2714            );
2715
2716            let entry = Utxo {
2717                address,
2718                txid,
2719                output_index,
2720                script,
2721                satoshis,
2722                height,
2723            };
2724            response_utxos.push(entry);
2725
2726            last_output_location = output_location;
2727        }
2728
2729        if response_utxos.len() > cap {
2730            return Err(format!(
2731                "more than {cap} unspent outputs match; page with startHeight and maxEntries"
2732            ))
2733            .map_error(server::error::LegacyCode::InvalidParameter);
2734        }
2735
2736        if !utxos_request.chain_info {
2737            Ok(GetAddressUtxosResponse::Utxos(response_utxos))
2738        } else {
2739            let (height, hash) = utxos
2740                .last_height_and_hash()
2741                .ok_or_misc_error("No blocks in state")?;
2742
2743            Ok(GetAddressUtxosResponse::UtxosAndChainInfo(
2744                GetAddressUtxosResponseObject {
2745                    utxos: response_utxos,
2746                    hash,
2747                    height,
2748                },
2749            ))
2750        }
2751    }
2752
2753    fn stop(&self) -> Result<String> {
2754        #[cfg(not(target_os = "windows"))]
2755        if self.network.is_regtest() {
2756            match nix::sys::signal::raise(nix::sys::signal::SIGINT) {
2757                Ok(_) => Ok("Zebra server stopping".to_string()),
2758                Err(error) => Err(ErrorObject::owned(
2759                    ErrorCode::InternalError.code(),
2760                    format!("Failed to shut down: {error}").as_str(),
2761                    None::<()>,
2762                )),
2763            }
2764        } else {
2765            Err(ErrorObject::borrowed(
2766                ErrorCode::MethodNotFound.code(),
2767                "stop is only available on regtest networks",
2768                None,
2769            ))
2770        }
2771        #[cfg(target_os = "windows")]
2772        Err(ErrorObject::borrowed(
2773            ErrorCode::MethodNotFound.code(),
2774            "stop is not available in windows targets",
2775            None,
2776        ))
2777    }
2778
2779    fn get_block_count(&self) -> Result<u32> {
2780        best_chain_tip_height(&self.latest_chain_tip).map(|height| height.0)
2781    }
2782
2783    async fn get_block_hash(&self, index: i32) -> Result<GetBlockHashResponse> {
2784        let mut read_state = self.read_state.clone();
2785        let latest_chain_tip = self.latest_chain_tip.clone();
2786
2787        // TODO: look up this height as part of the state request?
2788        let tip_height = best_chain_tip_height(&latest_chain_tip)?;
2789
2790        let height = height_from_signed_int(index, tip_height)?;
2791
2792        let request = zebra_state::ReadRequest::BestChainBlockHash(height);
2793        let response = read_state
2794            .ready()
2795            .and_then(|service| service.call(request))
2796            .await
2797            .map_error(server::error::LegacyCode::default())?;
2798
2799        match response {
2800            zebra_state::ReadResponse::BlockHash(Some(hash)) => Ok(GetBlockHashResponse(hash)),
2801            zebra_state::ReadResponse::BlockHash(None) => Err(ErrorObject::borrowed(
2802                server::error::LegacyCode::InvalidParameter.into(),
2803                "Block not found",
2804                None,
2805            )),
2806            _ => unreachable!("unmatched response to a block request"),
2807        }
2808    }
2809
2810    async fn get_block_template(
2811        &self,
2812        parameters: Option<GetBlockTemplateParameters>,
2813    ) -> Result<GetBlockTemplateResponse> {
2814        let long_poll_started = self.template_clock_now();
2815
2816        use types::get_block_template::{
2817            check_parameters, check_synced_to_tip, fetch_chain_info, fetch_mempool_transactions,
2818            nsm_value_balance_for_next_block, validate_block_proposal,
2819            zip317::select_mempool_transactions,
2820        };
2821
2822        // Clone Services
2823        let mempool = self.mempool.clone();
2824        let mut latest_chain_tip = self.latest_chain_tip.clone();
2825        let sync_status = self.gbt.sync_status();
2826        let read_state = self.read_state.clone();
2827
2828        if let Some(HexData(block_proposal_bytes)) = parameters
2829            .as_ref()
2830            .and_then(GetBlockTemplateParameters::block_proposal_data)
2831        {
2832            return validate_block_proposal(
2833                self.gbt.block_verifier_router(),
2834                read_state,
2835                block_proposal_bytes,
2836                &self.network,
2837                latest_chain_tip,
2838                sync_status,
2839                self.gbt.proposal_transactions(),
2840            )
2841            .await;
2842        }
2843
2844        // To implement long polling correctly, we split this RPC into multiple phases.
2845        check_parameters(&parameters)?;
2846
2847        let client_long_poll_id = parameters.as_ref().and_then(|params| params.long_poll_id);
2848
2849        let miner_params = self
2850            .gbt
2851            .miner_params()
2852            .ok_or_error(0, "miner parameters are required for get_block_template")?;
2853
2854        // - Precomputed template
2855        //
2856        // Serve the template that the block template updater task keeps ready, as long as it
2857        // extends the current chain tip.
2858        check_synced_to_tip(&self.network, latest_chain_tip.clone(), sync_status.clone())?;
2859
2860        if let Some(template) = self
2861            .precomputed_block_template(client_long_poll_id, long_poll_started)
2862            .await
2863        {
2864            return Ok(self.served_block_template(template));
2865        }
2866
2867        // - Checks and fetches that can change during long polling
2868        //
2869        // The loop returns the server long poll ID, which should be different to the client one.
2870        let (server_long_poll_id, chain_info, mempool_txs, mempool_tx_deps, submit_old) = loop {
2871            // Check if we are synced to the tip.
2872            // The result of this check can change during long polling.
2873            //
2874            // Optional TODO:
2875            // - add `async changed()` method to ChainSyncStatus (like `ChainTip`)
2876            check_synced_to_tip(&self.network, latest_chain_tip.clone(), sync_status.clone())?;
2877            // TODO: return an error if we have no peers, like `zcashd` does,
2878            //       and add a developer config that mines regardless of how many peers we have.
2879            // https://github.com/zcash/zcash/blob/6fdd9f1b81d3b228326c9826fa10696fc516444b/src/miner.cpp#L865-L880
2880
2881            // We're just about to fetch state data, then maybe wait for any changes.
2882            // Mark all the changes before the fetch as seen.
2883            // Changes are also ignored in any clones made after the mark.
2884            latest_chain_tip.mark_best_tip_seen();
2885
2886            // Fetch the state data and local time for the block template:
2887            // - if the tip block hash changes, we must return from long polling,
2888            // - if the local clock changes on testnet, we might return from long polling
2889            //
2890            // A timestamp range expiring during this request also ends the long poll, even if
2891            // the tip and mempool have not changed. Already-expired work must wait for a change.
2892            let chain_info @ zebra_state::GetBlockTemplateChainInfo {
2893                tip_hash,
2894                tip_height,
2895                max_time,
2896                cur_time,
2897                ..
2898            } = fetch_chain_info(read_state.clone()).await?;
2899
2900            // Fetch the mempool data for the block template:
2901            // - if the mempool transactions change, we might return from long polling.
2902            //
2903            // If the chain fork has just changed, miners want to get the new block as fast
2904            // as possible, rather than wait for transactions to re-verify. This increases
2905            // miner profits (and any delays can cause chain forks). So we don't wait between
2906            // the chain tip changing and getting mempool transactions.
2907            //
2908            // Optional TODO:
2909            // - add a `MempoolChange` type with an `async changed()` method (like `ChainTip`)
2910            let Some((mempool_txs, mempool_tx_deps)) =
2911                fetch_mempool_transactions(mempool.clone(), tip_hash)
2912                    .await?
2913                    // If the mempool and state responses are out of sync:
2914                    // - if we are not long polling, omit mempool transactions from the template,
2915                    // - if we are long polling, continue to the next iteration of the loop to make fresh state and mempool requests.
2916                    .or_else(|| client_long_poll_id.is_none().then(Default::default))
2917            else {
2918                continue;
2919            };
2920
2921            // - Long poll ID calculation
2922            let server_long_poll_id = LongPollInput::new(
2923                tip_height,
2924                tip_hash,
2925                max_time,
2926                mempool_txs.iter().map(|tx| tx.transaction.id),
2927            )
2928            .generate_id();
2929
2930            // Recheck after the reads: a forward clock correction can expire a live range.
2931            // Only notify if it was still valid when this request started, otherwise miners
2932            // repeatedly receive the same expired long poll ID and immediately poll again.
2933            let now = self.template_clock_now();
2934            let max_time_reached =
2935                client_long_poll_id.is_some() && long_poll_started <= max_time && now > max_time;
2936
2937            // The loop finishes if:
2938            // - the client didn't pass a long poll ID,
2939            // - the server long poll ID is different to the client long poll ID, or
2940            // - the timestamp range expired during this request.
2941            if Some(&server_long_poll_id) != client_long_poll_id.as_ref() || max_time_reached {
2942                // Expired work cannot be retained, even when only the mempool changed the ID.
2943                let submit_old = client_long_poll_id.as_ref().map(|old_long_poll_id| {
2944                    now <= max_time && server_long_poll_id.submit_old(old_long_poll_id)
2945                });
2946
2947                break (
2948                    server_long_poll_id,
2949                    chain_info,
2950                    mempool_txs,
2951                    mempool_tx_deps,
2952                    submit_old,
2953                );
2954            }
2955
2956            // - Polling wait conditions
2957            //
2958            // TODO: when we're happy with this code, split it into a function.
2959            //
2960            // Periodically check the mempool for changes.
2961            //
2962            // Optional TODO:
2963            // Remove this polling wait if we switch to using futures to detect sync status
2964            // and mempool changes.
2965            let wait_for_mempool_request =
2966                tokio::time::sleep(Duration::from_secs(MEMPOOL_LONG_POLL_INTERVAL));
2967
2968            // Return immediately if the chain tip has changed.
2969            // The clone preserves the seen status of the chain tip.
2970            let mut wait_for_new_tip = latest_chain_tip.clone();
2971            let wait_for_new_tip = wait_for_new_tip.best_tip_changed();
2972
2973            // `max_time` is inclusive. Use wall time, not the captured and clamped cur_time,
2974            // so time spent building or a clock adjustment cannot extend the long poll.
2975            let duration_until_max_time = max_time.saturating_duration_since(now);
2976            let wait_for_max_time =
2977                tokio::time::sleep(duration_until_max_time.to_std() + Duration::from_secs(1));
2978
2979            // Optional TODO:
2980            // `zcashd` generates the next coinbase transaction while waiting for changes.
2981            // The coinbase value depends on the selected transactions, so this needs
2982            // further analysis to check if it actually saves us any time.
2983
2984            tokio::select! {
2985                // Poll the futures in the listed order, for efficiency.
2986                // We put the most frequent conditions first.
2987                biased;
2988
2989                // This timer elapses every few seconds
2990                _elapsed = wait_for_mempool_request => {
2991                    tracing::debug!(
2992                        ?max_time,
2993                        ?cur_time,
2994                        ?server_long_poll_id,
2995                        ?client_long_poll_id,
2996                        MEMPOOL_LONG_POLL_INTERVAL,
2997                        "checking for a new mempool change after waiting a few seconds"
2998                    );
2999                }
3000
3001                _ = wait_for_new_tip => {
3002                    // Serve the template that the updater task precomputed for the new tip, so the
3003                    // miner doesn't waste any effort extending the shorter chain. Otherwise, loop
3004                    // around to build a template for the new tip from the state and the mempool.
3005                    if let Some(template) = self
3006                        .precomputed_block_template(client_long_poll_id, long_poll_started)
3007                        .await
3008                    {
3009                        return Ok(self.served_block_template(template));
3010                    }
3011                }
3012
3013                // The max time does not elapse during normal operation on mainnet,
3014                // and it rarely elapses on testnet.
3015                () = wait_for_max_time, if long_poll_started <= max_time => {
3016                    // This log is very rare so it's ok to be info.
3017                    tracing::info!(
3018                        ?max_time,
3019                        ?cur_time,
3020                        ?server_long_poll_id,
3021                        ?client_long_poll_id,
3022                        "rechecking long poll after the max time deadline"
3023                    );
3024
3025                    // Recheck wall time in the next iteration in case the clock moved backwards.
3026                }
3027            }
3028        };
3029
3030        // - Processing fetched data to create a transaction template
3031        //
3032        // Apart from random weighted transaction selection,
3033        // the template only depends on the previously fetched data.
3034        // This processing never fails.
3035
3036        tracing::debug!(
3037            mempool_tx_hashes = ?mempool_txs
3038                .iter()
3039                .map(|tx| tx.transaction.id.mined_id())
3040                .collect::<Vec<_>>(),
3041            "selecting transactions for the template from the mempool"
3042        );
3043
3044        let height = chain_info.tip_height.next().map_misc_error()?;
3045        let build_started = std::time::Instant::now();
3046
3047        // Randomly select some mempool transactions.
3048        let coinbase_cache = self.gbt.coinbase_cache();
3049        let parent_nsm_value_balance = nsm_value_balance_for_next_block(&self.network, &chain_info);
3050
3051        let mempool_txs = select_mempool_transactions(
3052            &self.network,
3053            height,
3054            miner_params,
3055            mempool_txs,
3056            mempool_tx_deps,
3057            Some(&coinbase_cache),
3058            parent_nsm_value_balance,
3059        );
3060
3061        tracing::debug!(
3062            selected_mempool_tx_hashes = ?mempool_txs
3063                .iter()
3064                .map(|#[cfg(not(test))] tx, #[cfg(test)] (_, tx)| tx.transaction.id.mined_id())
3065                .collect::<Vec<_>>(),
3066            "selected transactions for the template from the mempool"
3067        );
3068
3069        // Build from the fetched snapshot, then recheck the local-clock bound before serving.
3070
3071        let template = BlockTemplateResponse::new_internal(
3072            &self.network,
3073            &coinbase_cache,
3074            miner_params,
3075            &chain_info,
3076            server_long_poll_id,
3077            mempool_txs,
3078            submit_old,
3079        );
3080        metrics::histogram!("rpc.getblocktemplate.build.duration_seconds")
3081            .record(build_started.elapsed().as_secs_f64());
3082
3083        // Coinbase construction can take seconds. Recheck the whole advertised range after it,
3084        // just as the cache does, rather than returning timestamps invalidated by clock rollback.
3085        (template.max_time
3086            <= self
3087                .template_clock_now()
3088                .saturating_add(Duration32::from_hours(2)))
3089        .then(|| self.served_block_template(template))
3090        .ok_or_misc_error("local clock moved backwards while building the block template")
3091    }
3092
3093    async fn submit_block(
3094        &self,
3095        HexData(block_bytes): HexData,
3096        _parameters: Option<SubmitBlockParameters>,
3097    ) -> Result<SubmitBlockResponse> {
3098        let mut block_verifier_router = self.gbt.block_verifier_router();
3099
3100        // A solved block template has the transaction bytes of a block proposal that Zebra has
3101        // validated, so its transactions are already decoded. Large blocks decode their
3102        // transactions on Rayon, so keep that off the async executor.
3103        let block = match self
3104            .gbt
3105            .proposal_transactions()
3106            .block_with_validated_transactions(&block_bytes)
3107        {
3108            Some(block) => Ok(block),
3109            None => tokio::task::spawn_blocking(move || {
3110                Block::zcash_deserialize_parallel(&mut block_bytes.as_slice())
3111            })
3112            .await
3113            .map_misc_error()?,
3114        };
3115        let block: Block = match block {
3116            Ok(block) => block,
3117            Err(error) => {
3118                tracing::info!(
3119                    ?error,
3120                    "submit block failed: block bytes could not be deserialized into a structurally valid block"
3121                );
3122
3123                return Ok(
3124                    SubmitBlockResponse::from(SubmitBlockErrorResponse::Rejected).with_metrics(),
3125                );
3126            }
3127        };
3128
3129        let height = block
3130            .coinbase_height()
3131            .ok_or_error(0, "coinbase height not found")?;
3132        let block_hash = block.hash();
3133
3134        // The request is boxed, so it can move to another task if it outlasts this call.
3135        let mut commit = Box::pin(async move {
3136            let response = block_verifier_router
3137                .ready()
3138                .await
3139                .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?
3140                .call(zebra_consensus::Request::Commit(Arc::new(block)))
3141                .await;
3142
3143            Ok::<_, ErrorObjectOwned>(response)
3144        });
3145
3146        // The verifier doesn't answer for a block while its parent is being verified, or if its
3147        // parent never arrives.
3148        let Ok(block_verifier_router_response) =
3149            tokio::time::timeout(SUBMIT_BLOCK_TIMEOUT, &mut commit).await
3150        else {
3151            tracing::info!(
3152                ?block_hash,
3153                ?height,
3154                "submit block is still being verified, answering before it is committed"
3155            );
3156
3157            // Dropping the request would stop the verification of a block that hasn't reached
3158            // the state yet. So it carries on in the background, and the block is announced
3159            // like any other mined block if it is committed.
3160            let gbt = self.gbt.clone();
3161            tokio::spawn(async move {
3162                if let Ok(Ok(Ok(hash))) =
3163                    tokio::time::timeout(SUBMIT_BLOCK_VERIFY_TIMEOUT, commit).await
3164                {
3165                    tracing::info!(?hash, ?height, "submit block accepted after its answer");
3166
3167                    // The gossip task announces the block as a new chain tip if this fails.
3168                    let _ = gbt.advertise_mined_block(hash, height);
3169                }
3170            });
3171
3172            return Ok(
3173                SubmitBlockResponse::from(SubmitBlockErrorResponse::Inconclusive).with_metrics(),
3174            );
3175        };
3176
3177        let chain_error = match block_verifier_router_response? {
3178            // Currently, this match arm returns `null` (Accepted) for blocks committed
3179            // to any chain, but Accepted is only for blocks in the best chain.
3180            //
3181            // TODO (#5487):
3182            // - Inconclusive: check if the block is on a side-chain
3183            // The difference is important to miners, because they want to mine on the best chain.
3184            Ok(hash) => {
3185                tracing::info!(?hash, ?height, "submit block accepted");
3186
3187                self.gbt
3188                    .advertise_mined_block(hash, height)
3189                    .map_error_with_prefix(0, "failed to send mined block to gossip task")?;
3190
3191                return Ok(SubmitBlockResponse::Accepted.with_metrics());
3192            }
3193
3194            // Turns BoxError into Result<VerifyChainError, BoxError>,
3195            // by downcasting from Any to VerifyChainError.
3196            Err(box_error) => {
3197                let error = box_error
3198                    .downcast::<RouterError>()
3199                    .map(|boxed_chain_error| *boxed_chain_error);
3200
3201                tracing::info!(
3202                    ?error,
3203                    ?block_hash,
3204                    ?height,
3205                    "submit block failed verification"
3206                );
3207
3208                error
3209            }
3210        };
3211
3212        let response = match chain_error {
3213            Ok(source) if source.is_duplicate_request() => SubmitBlockErrorResponse::Duplicate,
3214
3215            // Currently, these match arms return Reject for the older duplicate in a queue,
3216            // but queued duplicates should be DuplicateInconclusive.
3217            //
3218            // Optional TODO (#5487):
3219            // - DuplicateInconclusive: turn these non-finalized state duplicate block errors
3220            //   into BlockError enum variants, and handle them as DuplicateInconclusive:
3221            //   - "block already sent to be committed to the state"
3222            //   - "replaced by newer request"
3223            // - keep the older request in the queue,
3224            //   and return a duplicate error for the newer request immediately.
3225            //   This improves the speed of the RPC response.
3226            //
3227            // Checking the download queues and BlockVerifierRouter buffer for duplicates
3228            // might require architectural changes to Zebra, so we should only do it
3229            // if mining pools really need it.
3230            Ok(_verify_chain_error) => SubmitBlockErrorResponse::Rejected,
3231
3232            // This match arm is currently unreachable, but if future changes add extra error types,
3233            // we want to turn them into `Rejected`.
3234            Err(_unknown_error_type) => SubmitBlockErrorResponse::Rejected,
3235        };
3236
3237        Ok(SubmitBlockResponse::from(response).with_metrics())
3238    }
3239
3240    async fn get_mining_info(&self) -> Result<GetMiningInfoResponse> {
3241        let network = self.network.clone();
3242        let mut read_state = self.read_state.clone();
3243
3244        let chain_tip = self.latest_chain_tip.clone();
3245        let tip_height = chain_tip.best_tip_height().unwrap_or(Height(0)).0;
3246
3247        let mut current_block_tx = None;
3248        if tip_height > 0 {
3249            let mined_tx_ids = chain_tip.best_tip_mined_transaction_ids();
3250            current_block_tx =
3251                (!mined_tx_ids.is_empty()).then(|| mined_tx_ids.len().saturating_sub(1));
3252        }
3253
3254        let solution_rate_fut = self.get_network_sol_ps(None, None);
3255        // Get the current block size.
3256        let mut current_block_size = None;
3257        if tip_height > 0 {
3258            let request = zebra_state::ReadRequest::TipBlockSize;
3259            let response: zebra_state::ReadResponse = read_state
3260                .ready()
3261                .and_then(|service| service.call(request))
3262                .await
3263                .map_error(server::error::LegacyCode::default())?;
3264            current_block_size = match response {
3265                zebra_state::ReadResponse::TipBlockSize(Some(block_size)) => Some(block_size),
3266                _ => None,
3267            };
3268        }
3269
3270        Ok(GetMiningInfoResponse::new_internal(
3271            tip_height,
3272            current_block_size,
3273            current_block_tx,
3274            network,
3275            solution_rate_fut.await?,
3276        ))
3277    }
3278
3279    async fn get_network_sol_ps(
3280        &self,
3281        num_blocks: Option<i32>,
3282        height: Option<i32>,
3283    ) -> Result<u64> {
3284        // Default number of blocks is 120 if not supplied.
3285        let num_blocks = num_blocks.unwrap_or(DEFAULT_SOLUTION_RATE_WINDOW_SIZE);
3286        // State chooses a nonpositive count's averaging window after resolving the effective
3287        // height in the same chain snapshot, including future-height clamping and reorgs.
3288        let num_blocks = (num_blocks > 0)
3289            .then(|| usize::try_from(num_blocks).expect("positive i32 fits in usize"));
3290        let height = height.and_then(|height| height.try_into_height().ok());
3291
3292        let mut read_state = self.read_state.clone();
3293
3294        let request = ReadRequest::SolutionRate { num_blocks, height };
3295
3296        let response = read_state
3297            .ready()
3298            .and_then(|service| service.call(request))
3299            .await
3300            .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?;
3301
3302        let solution_rate = match response {
3303            // zcashd returns a 0 rate when the calculation is invalid
3304            ReadResponse::SolutionRate(solution_rate) => solution_rate.unwrap_or(0),
3305
3306            _ => unreachable!("unmatched response to a solution rate request"),
3307        };
3308
3309        solution_rate.try_into().map_misc_error()
3310    }
3311
3312    async fn get_network_info(&self) -> Result<GetNetworkInfoResponse> {
3313        let version = GetInfoResponse::version_from_string(&self.build_version)
3314            .expect("invalid version string");
3315
3316        let subversion = self.user_agent.clone();
3317
3318        let protocol_version = zebra_network::constants::CURRENT_NETWORK_PROTOCOL_VERSION.0;
3319
3320        // TODO: return actual supported local services when Zebra exposes them
3321        let local_services = format!("{:016x}", PeerServices::NODE_NETWORK);
3322
3323        // Deprecated: zcashd always returns 0.
3324        let timeoffset = 0;
3325
3326        let connections = read_address_book(&self.address_book, |book| {
3327            book.recently_live_peers(Utc::now()).len()
3328        })
3329        .await?;
3330
3331        // TODO: make `limited`, `reachable`, and `proxy` dynamic if Zebra supports network filtering
3332        let networks = vec![
3333            NetworkInfo::new("ipv4".to_string(), false, true, "".to_string(), false),
3334            NetworkInfo::new("ipv6".to_string(), false, true, "".to_string(), false),
3335            NetworkInfo::new("onion".to_string(), false, false, "".to_string(), false),
3336        ];
3337
3338        let relay_fee = zebra_chain::transaction::zip317::MIN_MEMPOOL_TX_FEE_RATE as f64
3339            / (zebra_chain::amount::COIN as f64);
3340
3341        // TODO: populate local addresses when Zebra supports exposing bound or advertised addresses
3342        let local_addresses = vec![];
3343
3344        // TODO: return network-level warnings, if Zebra supports them in the future
3345        let warnings = "".to_string();
3346
3347        let response = GetNetworkInfoResponse {
3348            version,
3349            subversion,
3350            protocol_version,
3351            local_services,
3352            timeoffset,
3353            connections,
3354            networks,
3355            relay_fee,
3356            local_addresses,
3357            warnings,
3358        };
3359
3360        Ok(response)
3361    }
3362
3363    async fn get_peer_info(&self) -> Result<Vec<PeerInfo>> {
3364        read_address_book(&self.address_book, |address_book| {
3365            address_book
3366                .recently_live_peers(chrono::Utc::now())
3367                .into_iter()
3368                .map(|meta_addr| {
3369                    let banscore = address_book.misbehavior_score(meta_addr.addr());
3370                    PeerInfo::from_meta_addr(meta_addr, banscore)
3371                })
3372                .collect()
3373        })
3374        .await
3375    }
3376
3377    async fn ping(&self) -> Result<()> {
3378        tracing::debug!("Receiving ping request via RPC");
3379
3380        // TODO: Send Message::Ping(nonce) to all connected peers,
3381        // and track response round-trip time for getpeerinfo's pingtime/pingwait fields.
3382
3383        Ok(())
3384    }
3385
3386    async fn validate_address(&self, raw_address: String) -> Result<ValidateAddressResponse> {
3387        let network = self.network.clone();
3388
3389        validate_address(network, raw_address)
3390    }
3391
3392    async fn z_validate_address(&self, raw_address: String) -> Result<ZValidateAddressResponse> {
3393        let network = self.network.clone();
3394
3395        z_validate_address(network, raw_address)
3396    }
3397
3398    async fn z_convert_tex(&self, address: String) -> Result<String> {
3399        use zcash_address::{ToAddress, ZcashAddress};
3400        use zebra_chain::{parameters::NetworkKind, primitives};
3401
3402        let address = address
3403            .parse::<ZcashAddress>()
3404            .ok()
3405            .and_then(|address| address.convert::<primitives::Address>().ok())
3406            // zcashd decodes against the active chain params, so a wrong-network address is
3407            // just "invalid". Testnet and Regtest share an encoding; only Mainnet differs.
3408            .filter(|address| {
3409                (address.network() == NetworkKind::Mainnet)
3410                    == (self.network.kind() == NetworkKind::Mainnet)
3411            })
3412            .ok_or("Invalid address")
3413            .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
3414
3415        let primitives::Address::Transparent(Address::PayToPublicKeyHash { pub_key_hash, .. }) =
3416            address
3417        else {
3418            return Err("Address is not a transparent p2pkh address")
3419                .map_error(server::error::LegacyCode::InvalidParameter);
3420        };
3421
3422        // Encode for the configured network, not the parsed address's network: Testnet and
3423        // Regtest share transparent address prefixes, so a `tm...` input always decodes as
3424        // Testnet, but their TEX HRPs differ (`textest` vs `texregtest`).
3425        //
3426        // Encode via `zcash_address`: `transparent::Address`'s `Display` impl Base58Check-encodes
3427        // the `Tex` variant with the P2PKH version bytes, which would yield a `t1...` string.
3428        Ok(ZcashAddress::from_tex(self.network.kind().into(), pub_key_hash).encode())
3429    }
3430
3431    async fn get_standard_fee(&self) -> Result<GetStandardFeeResponse> {
3432        const VERSION: u32 = 0;
3433
3434        // Wallets build transactions for the next block, which is the genesis block if the
3435        // state is empty.
3436        let next_block_height = match self.latest_chain_tip.best_tip_height() {
3437            Some(tip_height) => tip_height.next().map_misc_error()?,
3438            None => Height::MIN,
3439        };
3440
3441        Ok(GetStandardFeeResponse::new(
3442            standard_fee(&self.network, next_block_height),
3443            VERSION,
3444        ))
3445    }
3446
3447    async fn get_block_subsidy(&self, height: Option<u32>) -> Result<GetBlockSubsidyResponse> {
3448        let net = self.network.clone();
3449
3450        let height = match height {
3451            Some(h) => {
3452                Height::try_from(h).map_error(server::error::LegacyCode::InvalidParameter)?
3453            }
3454            None => best_chain_tip_height(&self.latest_chain_tip)?,
3455        };
3456
3457        // From the NSM reissuance height, the block subsidy depends on the NSM
3458        // value balance after the parent block, so it is only known up to the block after the
3459        // best chain tip.
3460        let subsidy = if zebra_chain::parameters::subsidy::nsm_reissuance_is_active(height, &net) {
3461            let parent_height = (height - 1).ok_or_misc_error("height 0 has no parent block")?;
3462
3463            let zebra_state::ReadResponse::BlockInfo(parent_block_info) = self
3464                .read_state
3465                .clone()
3466                .oneshot(zebra_state::ReadRequest::BlockInfo(parent_height.into()))
3467                .await
3468                .map_misc_error()?
3469            else {
3470                unreachable!("unmatched response to a BlockInfo request")
3471            };
3472
3473            let parent_chain_value_pools = *parent_block_info
3474                .ok_or_misc_error(
3475                    "the block subsidy is only known up to the block after the best chain tip \
3476                     from the NSM reissuance height",
3477                )?
3478                .value_pools();
3479
3480            zebra_chain::parameters::subsidy::block_subsidy_with_parent_pools(
3481                height,
3482                &net,
3483                parent_chain_value_pools,
3484            )
3485            .map_misc_error()?
3486        } else {
3487            block_subsidy(height, &net).map_misc_error()?
3488        };
3489
3490        let (lockbox_streams, mut funding_streams): (Vec<_>, Vec<_>) =
3491            funding_stream_values(height, &net, subsidy)
3492                .map_misc_error()?
3493                .into_iter()
3494                // Separate the funding streams into deferred and non-deferred streams
3495                .partition(|(receiver, _)| matches!(receiver, FundingStreamReceiver::Deferred));
3496
3497        let [lockbox_total, funding_streams_total] =
3498            [&lockbox_streams, &funding_streams].map(|streams| {
3499                streams
3500                    .iter()
3501                    .map(|&(_, amount)| amount)
3502                    .sum::<std::result::Result<Amount<_>, _>>()
3503                    .map(Zec::from)
3504                    .map_misc_error()
3505            });
3506
3507        // Use the same funding stream order as zcashd
3508        funding_streams.sort_by_key(|(receiver, _funding_stream)| {
3509            ZCASHD_FUNDING_STREAM_ORDER
3510                .iter()
3511                .position(|zcashd_receiver| zcashd_receiver == receiver)
3512        });
3513
3514        // NU6.1 and later minor upgrades keep the NU6 funding stream structure (ZIP 1015).
3515        let is_post_nu6 = NetworkUpgrade::current(&net, height) >= NetworkUpgrade::Nu6;
3516
3517        // Format the funding streams and lockbox streams
3518        let [funding_streams, lockbox_streams] =
3519            [funding_streams, lockbox_streams].map(|streams| {
3520                streams
3521                    .into_iter()
3522                    .map(|(receiver, value)| {
3523                        let address = funding_stream_address(height, &net, receiver);
3524                        types::subsidy::FundingStream::new_internal(
3525                            is_post_nu6,
3526                            receiver,
3527                            value,
3528                            address,
3529                        )
3530                    })
3531                    .collect()
3532            });
3533
3534        Ok(GetBlockSubsidyResponse {
3535            miner: miner_subsidy(height, &net, subsidy)
3536                .map_misc_error()?
3537                .into(),
3538            founders: founders_reward(&net, height).into(),
3539            funding_streams,
3540            lockbox_streams,
3541            funding_streams_total: funding_streams_total?,
3542            lockbox_total: lockbox_total?,
3543            total_block_subsidy: subsidy.into(),
3544        })
3545    }
3546
3547    async fn get_difficulty(&self) -> Result<f64> {
3548        chain_tip_difficulty(self.network.clone(), self.read_state.clone(), false).await
3549    }
3550
3551    async fn z_list_unified_receivers(
3552        &self,
3553        address: String,
3554    ) -> Result<ZListUnifiedReceiversResponse> {
3555        use zcash_address::unified::Container;
3556
3557        let (network, .., unified_address) = zcash_address::unified::Address::decode(&address)
3558            .map_err(|error| ErrorObject::owned(0, error.to_string(), None::<()>))?;
3559
3560        let mut p2pkh = None;
3561        let mut p2sh = None;
3562        let mut orchard = None;
3563        let mut sapling = None;
3564
3565        for item in unified_address.items() {
3566            match item {
3567                zcash_address::unified::Receiver::Orchard(data) => {
3568                    Option::<orchard::Address>::from(orchard::Address::from_raw_address_bytes(
3569                        &data,
3570                    ))
3571                    .ok_or("Unified Address contains an invalid Orchard receiver")
3572                    .map_error(server::error::LegacyCode::InvalidParameter)?;
3573
3574                    // `zcash_keys` encodes unified addresses as ZIP 316 Revision 2, but
3575                    // zcashd returns the Revision 0 (`u`-prefixed) encoding.
3576                    let addr = zcash_address::unified::Address::try_from_items(
3577                        zcash_address::unified::Revision::R0,
3578                        vec![zcash_address::unified::Uitem::Data(
3579                            zcash_address::unified::Receiver::Orchard(data),
3580                        )],
3581                    )
3582                    .expect("a single Orchard receiver is a valid Revision 0 unified address");
3583                    orchard = Some(addr.encode(&network));
3584                }
3585                zcash_address::unified::Receiver::Sapling(data) => {
3586                    let addr = zebra_chain::primitives::Address::try_from_sapling(network, data)
3587                        .map_error(server::error::LegacyCode::InvalidParameter)?;
3588                    sapling = Some(addr.payment_address().unwrap_or_default());
3589                }
3590                zcash_address::unified::Receiver::P2pkh(data) => {
3591                    let addr =
3592                        zebra_chain::primitives::Address::try_from_transparent_p2pkh(network, data)
3593                            .expect("using data already decoded as valid");
3594                    p2pkh = Some(addr.payment_address().unwrap_or_default());
3595                }
3596                zcash_address::unified::Receiver::P2sh(data) => {
3597                    let addr =
3598                        zebra_chain::primitives::Address::try_from_transparent_p2sh(network, data)
3599                            .expect("using data already decoded as valid");
3600                    p2sh = Some(addr.payment_address().unwrap_or_default());
3601                }
3602                _ => (),
3603            }
3604        }
3605
3606        Ok(ZListUnifiedReceiversResponse::new(
3607            orchard, sapling, p2pkh, p2sh,
3608        ))
3609    }
3610
3611    async fn invalidate_block(&self, block_hash: String) -> Result<()> {
3612        let block_hash = block_hash
3613            .parse()
3614            .map_error(server::error::LegacyCode::InvalidParameter)?;
3615
3616        self.state
3617            .clone()
3618            .oneshot(zebra_state::Request::InvalidateBlock(block_hash))
3619            .await
3620            .map(|rsp| assert_eq!(rsp, zebra_state::Response::Invalidated(block_hash)))
3621            .map_misc_error()
3622    }
3623
3624    async fn reconsider_block(&self, block_hash: String) -> Result<Vec<block::Hash>> {
3625        let block_hash = block_hash
3626            .parse()
3627            .map_error(server::error::LegacyCode::InvalidParameter)?;
3628
3629        self.state
3630            .clone()
3631            .oneshot(zebra_state::Request::ReconsiderBlock(block_hash))
3632            .await
3633            .map(|rsp| match rsp {
3634                zebra_state::Response::Reconsidered(block_hashes) => block_hashes,
3635                _ => unreachable!("unmatched response to a reconsider block request"),
3636            })
3637            .map_misc_error()
3638    }
3639
3640    async fn generate(&self, num_blocks: u32) -> Result<Vec<Hash>> {
3641        let mut rpc = self.clone();
3642        let network = self.network.clone();
3643
3644        if !network.disable_pow() {
3645            return Err(ErrorObject::borrowed(
3646                0,
3647                "generate is only supported on networks where PoW is disabled",
3648                None,
3649            ));
3650        }
3651
3652        let mut block_hashes = Vec::new();
3653        for _ in 0..num_blocks {
3654            // Use random coinbase data in order to ensure the coinbase transaction is unique. This
3655            // is useful for tests that exercise forks, since otherwise the coinbase txs of blocks
3656            // with the same height across different forks would be identical.
3657            rpc.gbt.randomize_coinbase_data();
3658
3659            let block_template = rpc
3660                .get_block_template(None)
3661                .await
3662                .map_error(server::error::LegacyCode::default())?;
3663
3664            let GetBlockTemplateResponse::TemplateMode(block_template) = block_template else {
3665                return Err(ErrorObject::borrowed(
3666                    0,
3667                    "error generating block template",
3668                    None,
3669                ));
3670            };
3671
3672            let proposal_block = proposal_block_from_template(
3673                &block_template,
3674                BlockTemplateTimeSource::CurTime,
3675                &network,
3676            )
3677            .map_error(server::error::LegacyCode::default())?;
3678
3679            let hex_proposal_block = HexData(
3680                proposal_block
3681                    .zcash_serialize_to_vec()
3682                    .map_error(server::error::LegacyCode::default())?,
3683            );
3684
3685            let r = rpc
3686                .submit_block(hex_proposal_block, None)
3687                .await
3688                .map_error(server::error::LegacyCode::default())?;
3689            match r {
3690                SubmitBlockResponse::Accepted => { /* pass */ }
3691                SubmitBlockResponse::ErrorResponse(response) => {
3692                    return Err(ErrorObject::owned(
3693                        server::error::LegacyCode::Misc.into(),
3694                        format!("block was rejected: {response:?}"),
3695                        None::<()>,
3696                    ));
3697                }
3698            }
3699
3700            block_hashes.push(GetBlockHashResponse(proposal_block.hash()));
3701        }
3702
3703        Ok(block_hashes)
3704    }
3705
3706    async fn generate_to_address(
3707        &self,
3708        num_blocks: u32,
3709        address: String,
3710    ) -> Result<Vec<GetBlockHashResponse>> {
3711        if !self.network.disable_pow() {
3712            return Err(ErrorObject::borrowed(
3713                0,
3714                "generatetoaddress is only supported on networks where PoW is disabled",
3715                None,
3716            ));
3717        }
3718
3719        // Build miner parameters that pay the coinbase to the requested address,
3720        // reusing the same coinbase-data and marker handling as configured mining.
3721        let miner_address = address
3722            .parse()
3723            .map_error(server::error::LegacyCode::default())?;
3724        let miner_params = MinerParams::new(
3725            &self.network,
3726            crate::config::mining::Config {
3727                miner_address: Some(miner_address),
3728                ..Default::default()
3729            },
3730        )
3731        .map_error(server::error::LegacyCode::default())?;
3732
3733        // Override the miner params on a clone, then reuse the whole `generate`
3734        // path — it mines through its own `self.clone()`, which preserves the
3735        // override, so the configured `mining.miner_address` is untouched.
3736        let mut rpc = self.clone();
3737        rpc.gbt.set_miner_params(miner_params);
3738        rpc.generate(num_blocks).await
3739    }
3740
3741    async fn add_node(
3742        &self,
3743        addr: zebra_network::PeerSocketAddr,
3744        command: AddNodeCommand,
3745    ) -> Result<()> {
3746        if self.network.is_regtest() {
3747            match command {
3748                AddNodeCommand::Add => {
3749                    tracing::info!(?addr, "adding peer address to the address book");
3750                    if self.address_book.clone().add_peer(addr) {
3751                        Ok(())
3752                    } else {
3753                        return Err(ErrorObject::owned(
3754                            server::error::LegacyCode::ClientNodeAlreadyAdded.into(),
3755                            format!("peer address was already present in the address book: {addr}"),
3756                            None::<()>,
3757                        ));
3758                    }
3759                }
3760            }
3761        } else {
3762            return Err(ErrorObject::owned(
3763                ErrorCode::InvalidParams.code(),
3764                "addnode command is only supported on regtest",
3765                None::<()>,
3766            ));
3767        }
3768    }
3769
3770    fn openrpc(&self) -> openrpsee::openrpc::Response {
3771        let mut generator = openrpsee::openrpc::Generator::new();
3772
3773        let methods = METHODS
3774            .into_iter()
3775            .map(|(name, method)| method.generate(&mut generator, name))
3776            .collect();
3777
3778        Ok(openrpsee::openrpc::OpenRpc {
3779            openrpc: "1.3.2",
3780            info: openrpsee::openrpc::Info {
3781                title: env!("CARGO_PKG_NAME"),
3782                description: env!("CARGO_PKG_DESCRIPTION"),
3783                version: env!("CARGO_PKG_VERSION"),
3784            },
3785            methods,
3786            components: generator.into_components(),
3787        })
3788    }
3789    async fn get_tx_out(
3790        &self,
3791        txid: String,
3792        n: u32,
3793        include_mempool: Option<bool>,
3794    ) -> Result<GetTxOutResponse> {
3795        let txid = transaction::Hash::from_hex(txid)
3796            .map_error(server::error::LegacyCode::InvalidParameter)?;
3797
3798        let outpoint = transparent::OutPoint {
3799            hash: txid,
3800            index: n,
3801        };
3802
3803        // Optional mempool path
3804        if include_mempool.unwrap_or(true) {
3805            let rsp = self
3806                .mempool
3807                .clone()
3808                .oneshot(mempool::Request::UnspentOutput(outpoint))
3809                .await
3810                .map_misc_error()?;
3811
3812            match rsp {
3813                // Return the output found in the mempool
3814                mempool::Response::TransparentOutput(Some(CreatedOrSpent::Created {
3815                    output,
3816                    tx_version,
3817                    last_seen_hash,
3818                })) => {
3819                    return Ok(GetTxOutResponse(Some(
3820                        types::transaction::OutputObject::from_output(
3821                            &output,
3822                            last_seen_hash.to_string(),
3823                            0,
3824                            tx_version,
3825                            false,
3826                            self.network(),
3827                        ),
3828                    )))
3829                }
3830                mempool::Response::TransparentOutput(Some(CreatedOrSpent::Spent)) => {
3831                    return Ok(GetTxOutResponse(None))
3832                }
3833                mempool::Response::TransparentOutput(None) => {}
3834                _ => unreachable!("unmatched response to an `UnspentOutput` request"),
3835            };
3836        }
3837
3838        // Issue the Transaction query first and reuse the best-chain tip hash
3839        // captured in that same chain snapshot, instead of doing a separate Tip
3840        // query that re-samples the chain. The follow-up IsTransparentOutputSpent
3841        // query may still observe a later tip, but the response's `bestblock`
3842        // field is now anchored to the same view used to compute confirmations.
3843        // See issue #10550.
3844        let rsp = self
3845            .read_state
3846            .clone()
3847            .oneshot(zebra_state::ReadRequest::Transaction(txid))
3848            .await
3849            .map_misc_error()?;
3850
3851        match rsp {
3852            zebra_state::ReadResponse::Transaction(Some(tx)) => {
3853                let best_block_hash = tx.best_chain_tip_hash;
3854                let outputs = tx.tx.outputs();
3855                let index: usize = n.try_into().expect("u32 always fits in usize");
3856                let output = match outputs.get(index) {
3857                    Some(output) => output,
3858                    // return null if the output is not found
3859                    None => return Ok(GetTxOutResponse(None)),
3860                };
3861
3862                // Prune state outputs that are spent
3863                let is_spent = {
3864                    let rsp = self
3865                        .read_state
3866                        .clone()
3867                        .oneshot(zebra_state::ReadRequest::IsTransparentOutputSpent(outpoint))
3868                        .await
3869                        .map_misc_error()?;
3870
3871                    match rsp {
3872                        zebra_state::ReadResponse::IsTransparentOutputSpent(spent) => spent,
3873                        _ => unreachable!(
3874                            "unmatched response to an `IsTransparentOutputSpent` request"
3875                        ),
3876                    }
3877                };
3878
3879                if is_spent {
3880                    return Ok(GetTxOutResponse(None));
3881                }
3882
3883                Ok(GetTxOutResponse(Some(
3884                    types::transaction::OutputObject::from_output(
3885                        output,
3886                        best_block_hash.to_string(),
3887                        tx.confirmations,
3888                        tx.tx.version(),
3889                        tx.tx.is_coinbase(),
3890                        self.network(),
3891                    ),
3892                )))
3893            }
3894            zebra_state::ReadResponse::Transaction(None) => Ok(GetTxOutResponse(None)),
3895            _ => unreachable!("unmatched response to a `Transaction` request"),
3896        }
3897    }
3898}
3899
3900// TODO: Move the code below to separate modules.
3901
3902/// Returns the best chain tip height of `latest_chain_tip`,
3903/// or an RPC error if there are no blocks in the state.
3904pub fn best_chain_tip_height<Tip>(latest_chain_tip: &Tip) -> Result<Height>
3905where
3906    Tip: ChainTip + Clone + Send + Sync + 'static,
3907{
3908    latest_chain_tip
3909        .best_tip_height()
3910        .ok_or_misc_error("No blocks in state")
3911}
3912
3913/// Response to a `getinfo` RPC request.
3914///
3915/// See the notes for the [`Rpc::get_info` method].
3916#[allow(clippy::too_many_arguments)]
3917#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
3918pub struct GetInfoResponse {
3919    /// The node version
3920    #[getter(rename = "raw_version")]
3921    version: u64,
3922
3923    /// The node version build number
3924    build: String,
3925
3926    /// The server sub-version identifier, used as the network protocol user-agent
3927    subversion: String,
3928
3929    /// The protocol version
3930    #[serde(rename = "protocolversion")]
3931    protocol_version: u32,
3932
3933    /// The current number of blocks processed in the server
3934    blocks: u32,
3935
3936    /// The total (inbound and outbound) number of connections the node has
3937    connections: usize,
3938
3939    /// The proxy (if any) used by the server. Currently always `None` in Zebra.
3940    #[serde(skip_serializing_if = "Option::is_none")]
3941    proxy: Option<String>,
3942
3943    /// The current network difficulty
3944    difficulty: f64,
3945
3946    /// True if the server is running in testnet mode, false otherwise
3947    testnet: bool,
3948
3949    /// The minimum transaction fee in ZEC/kB
3950    #[serde(rename = "paytxfee")]
3951    pay_tx_fee: f64,
3952
3953    /// The minimum relay fee for non-free transactions in ZEC/kB
3954    #[serde(rename = "relayfee")]
3955    relay_fee: f64,
3956
3957    /// The last error or warning message, or "no errors" if there are no errors
3958    errors: String,
3959
3960    /// The time of the last error or warning message, or "no errors timestamp" if there are no errors
3961    #[serde(rename = "errorstimestamp")]
3962    errors_timestamp: i64,
3963}
3964
3965#[deprecated(note = "Use `GetInfoResponse` instead")]
3966pub use self::GetInfoResponse as GetInfo;
3967
3968impl Default for GetInfoResponse {
3969    fn default() -> Self {
3970        GetInfoResponse {
3971            version: 0,
3972            build: "some build version".to_string(),
3973            subversion: "some subversion".to_string(),
3974            protocol_version: 0,
3975            blocks: 0,
3976            connections: 0,
3977            proxy: None,
3978            difficulty: 0.0,
3979            testnet: false,
3980            pay_tx_fee: 0.0,
3981            relay_fee: 0.0,
3982            errors: "no errors".to_string(),
3983            errors_timestamp: Utc::now().timestamp(),
3984        }
3985    }
3986}
3987
3988impl GetInfoResponse {
3989    /// Constructs [`GetInfo`] from its constituent parts.
3990    #[allow(clippy::too_many_arguments)]
3991    #[deprecated(note = "Use `GetInfoResponse::new` instead")]
3992    pub fn from_parts(
3993        version: u64,
3994        build: String,
3995        subversion: String,
3996        protocol_version: u32,
3997        blocks: u32,
3998        connections: usize,
3999        proxy: Option<String>,
4000        difficulty: f64,
4001        testnet: bool,
4002        pay_tx_fee: f64,
4003        relay_fee: f64,
4004        errors: String,
4005        errors_timestamp: i64,
4006    ) -> Self {
4007        Self {
4008            version,
4009            build,
4010            subversion,
4011            protocol_version,
4012            blocks,
4013            connections,
4014            proxy,
4015            difficulty,
4016            testnet,
4017            pay_tx_fee,
4018            relay_fee,
4019            errors,
4020            errors_timestamp,
4021        }
4022    }
4023
4024    /// Returns the contents of ['GetInfo'].
4025    pub fn into_parts(
4026        self,
4027    ) -> (
4028        u64,
4029        String,
4030        String,
4031        u32,
4032        u32,
4033        usize,
4034        Option<String>,
4035        f64,
4036        bool,
4037        f64,
4038        f64,
4039        String,
4040        i64,
4041    ) {
4042        (
4043            self.version,
4044            self.build,
4045            self.subversion,
4046            self.protocol_version,
4047            self.blocks,
4048            self.connections,
4049            self.proxy,
4050            self.difficulty,
4051            self.testnet,
4052            self.pay_tx_fee,
4053            self.relay_fee,
4054            self.errors,
4055            self.errors_timestamp,
4056        )
4057    }
4058
4059    /// Create the node version number.
4060    fn version_from_string(build_string: &str) -> Option<u64> {
4061        let semver_version = semver::Version::parse(build_string.strip_prefix('v')?).ok()?;
4062        let build_number = semver_version
4063            .build
4064            .as_str()
4065            .split('.')
4066            .next()
4067            .and_then(|num_str| num_str.parse::<u64>().ok())
4068            .unwrap_or_default();
4069
4070        // https://github.com/zcash/zcash/blob/v6.1.0/src/clientversion.h#L55-L59
4071        let version_number = 1_000_000 * semver_version.major
4072            + 10_000 * semver_version.minor
4073            + 100 * semver_version.patch
4074            + build_number;
4075
4076        Some(version_number)
4077    }
4078}
4079
4080/// The number of seconds subtracted from the `end_of_service.estimated_time` reported by
4081/// `getdeprecationinfo`.
4082///
4083/// Block times vary, so the halt can happen earlier than a spacing-based estimate. Reporting the
4084/// estimate a day early gives consumers time to act before the actual halt.
4085const END_OF_SERVICE_ESTIMATE_SAFETY_MARGIN: i64 = 24 * 60 * 60;
4086
4087/// Response to a `getdeprecationinfo` RPC request.
4088///
4089/// See the notes for the [`Rpc::get_deprecation_info` method].
4090#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4091pub struct GetDeprecationInfoResponse {
4092    /// End of service information for this node release. Only present on Mainnet, where end of
4093    /// support is enforced.
4094    #[serde(skip_serializing_if = "Option::is_none")]
4095    end_of_service: Option<EndOfService>,
4096}
4097
4098/// The `end_of_service` object in a [`GetDeprecationInfoResponse`].
4099#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4100pub struct EndOfService {
4101    /// The estimated last height this server version supports, matching zcashd's threshold
4102    /// semantics. The node halts when the chain tip goes past this height.
4103    #[getter(copy)]
4104    block_height: u32,
4105
4106    /// The approximate time of the end of support halt, in seconds since epoch, estimated from
4107    /// the current chain tip height and the target block spacing.
4108    ///
4109    /// Reported 24 hours earlier than the spacing-based estimate, so consumers are warned early
4110    /// rather than late when block times vary.
4111    #[getter(copy)]
4112    estimated_time: i64,
4113}
4114
4115/// Type alias for the array of `GetBlockchainInfoBalance` objects
4116pub type BlockchainValuePoolBalances = [GetBlockchainInfoBalance; 6];
4117
4118/// Response to a `getblockchaininfo` RPC request.
4119///
4120/// See the notes for the [`Rpc::get_blockchain_info` method].
4121#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters)]
4122pub struct GetBlockchainInfoResponse {
4123    /// Current network name as defined in BIP70 (main, test, regtest)
4124    chain: String,
4125
4126    /// The current number of blocks processed in the server, numeric
4127    #[getter(copy)]
4128    blocks: Height,
4129
4130    /// The current number of headers we have validated in the best chain, that is,
4131    /// the height of the best chain.
4132    #[getter(copy)]
4133    headers: Height,
4134
4135    /// The estimated network solution rate in Sol/s.
4136    difficulty: f64,
4137
4138    /// The verification progress relative to the estimated network chain tip.
4139    #[serde(rename = "verificationprogress")]
4140    verification_progress: f64,
4141
4142    /// The total amount of work in the best chain, hex-encoded.
4143    #[serde(rename = "chainwork")]
4144    chain_work: u64,
4145
4146    /// Whether this node is pruned, currently always false in Zebra.
4147    pruned: bool,
4148
4149    /// The estimated size of the block and undo files on disk
4150    size_on_disk: u64,
4151
4152    /// The current number of note commitments in the commitment tree
4153    commitments: u64,
4154
4155    /// The hash of the currently best block, in big-endian order, hex-encoded
4156    #[serde(rename = "bestblockhash", with = "hex")]
4157    #[getter(copy)]
4158    best_block_hash: block::Hash,
4159
4160    /// If syncing, the estimated height of the chain, else the current best height, numeric.
4161    ///
4162    /// In Zebra, this is always the height estimate, so it might be a little inaccurate.
4163    #[serde(rename = "estimatedheight")]
4164    #[getter(copy)]
4165    estimated_height: Height,
4166
4167    /// Chain supply balance
4168    #[serde(rename = "chainSupply")]
4169    chain_supply: GetBlockchainInfoBalance,
4170
4171    /// Value pool balances
4172    #[serde(rename = "valuePools")]
4173    value_pools: BlockchainValuePoolBalances,
4174
4175    /// The Network Sustainability Mechanism (NSM) value balance (NU7). It is not part of the
4176    /// chain supply, so it is not in `valuePools`. It is `monitored` from the block before NU7
4177    /// activation. It is absent in responses from nodes that don't report it.
4178    #[serde(
4179        rename = "nsmValueBalance",
4180        skip_serializing_if = "Option::is_none",
4181        default
4182    )]
4183    nsm_value_balance: Option<GetBlockchainInfoBalance>,
4184
4185    /// Status of network upgrades
4186    upgrades: IndexMap<ConsensusBranchIdHex, NetworkUpgradeInfo>,
4187
4188    /// Branch IDs of the current and upcoming consensus rules
4189    #[getter(copy)]
4190    consensus: TipConsensusBranch,
4191}
4192
4193impl Default for GetBlockchainInfoResponse {
4194    fn default() -> Self {
4195        Self {
4196            chain: "main".to_string(),
4197            blocks: Height(1),
4198            best_block_hash: block::Hash([0; 32]),
4199            estimated_height: Height(1),
4200            chain_supply: GetBlockchainInfoBalance::chain_supply(Default::default()),
4201            value_pools: GetBlockchainInfoBalance::zero_pools(),
4202            nsm_value_balance: Some(GetBlockchainInfoBalance::nsm(
4203                &Network::Mainnet,
4204                Height(1),
4205                Amount::zero(),
4206                None,
4207            )),
4208            upgrades: IndexMap::new(),
4209            consensus: TipConsensusBranch {
4210                chain_tip: ConsensusBranchIdHex(ConsensusBranchId::default()),
4211                next_block: ConsensusBranchIdHex(ConsensusBranchId::default()),
4212            },
4213            headers: Height(1),
4214            difficulty: 0.0,
4215            verification_progress: 0.0,
4216            chain_work: 0,
4217            pruned: false,
4218            size_on_disk: 0,
4219            commitments: 0,
4220        }
4221    }
4222}
4223
4224impl GetBlockchainInfoResponse {
4225    /// Creates a new [`GetBlockchainInfoResponse`] instance.
4226    // We don't use derive(new) because the method already existed but the arguments
4227    // have a different order. No reason to unnecessarily break existing code.
4228    #[allow(clippy::too_many_arguments)]
4229    pub fn new(
4230        chain: String,
4231        blocks: Height,
4232        best_block_hash: block::Hash,
4233        estimated_height: Height,
4234        chain_supply: GetBlockchainInfoBalance,
4235        value_pools: BlockchainValuePoolBalances,
4236        nsm_value_balance: Option<GetBlockchainInfoBalance>,
4237        upgrades: IndexMap<ConsensusBranchIdHex, NetworkUpgradeInfo>,
4238        consensus: TipConsensusBranch,
4239        headers: Height,
4240        difficulty: f64,
4241        verification_progress: f64,
4242        chain_work: u64,
4243        pruned: bool,
4244        size_on_disk: u64,
4245        commitments: u64,
4246    ) -> Self {
4247        Self {
4248            chain,
4249            blocks,
4250            best_block_hash,
4251            estimated_height,
4252            chain_supply,
4253            value_pools,
4254            nsm_value_balance,
4255            upgrades,
4256            consensus,
4257            headers,
4258            difficulty,
4259            verification_progress,
4260            chain_work,
4261            pruned,
4262            size_on_disk,
4263            commitments,
4264        }
4265    }
4266}
4267
4268/// A request for [`RpcServer::get_address_balance`].
4269#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, serde::Serialize, JsonSchema)]
4270#[serde(from = "DGetAddressBalanceRequest")]
4271pub struct GetAddressBalanceRequest {
4272    /// A list of transparent address strings.
4273    addresses: Vec<String>,
4274}
4275
4276impl From<DGetAddressBalanceRequest> for GetAddressBalanceRequest {
4277    fn from(address_strings: DGetAddressBalanceRequest) -> Self {
4278        match address_strings {
4279            DGetAddressBalanceRequest::Addresses { addresses } => {
4280                GetAddressBalanceRequest { addresses }
4281            }
4282            DGetAddressBalanceRequest::Address(address) => GetAddressBalanceRequest {
4283                addresses: vec![address],
4284            },
4285        }
4286    }
4287}
4288
4289/// An intermediate type used to deserialize [`AddressStrings`].
4290#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, JsonSchema)]
4291#[serde(untagged)]
4292enum DGetAddressBalanceRequest {
4293    /// A list of address strings.
4294    Addresses { addresses: Vec<String> },
4295    /// A single address string.
4296    Address(String),
4297}
4298
4299/// A request to get the transparent balance of a set of addresses.
4300#[deprecated(note = "Use `GetAddressBalanceRequest` instead.")]
4301pub type AddressStrings = GetAddressBalanceRequest;
4302
4303/// The maximum number of addresses a client can send in one request.
4304pub(crate) const MAX_REQUEST_ADDRESSES: usize = 10_000;
4305
4306/// The maximum number of results `getaddresstxids` and `getaddressutxos` return before
4307/// rejecting the query; clients narrow the height range or page instead.
4308pub(crate) const MAX_ADDRESS_QUERY_RESULTS: usize = 100_000;
4309
4310/// A collection of validatable addresses
4311pub trait ValidateAddresses {
4312    /// Given a list of addresses as strings:
4313    /// - check if provided list have all valid transparent addresses.
4314    /// - return valid addresses as a set of `Address`.
4315    fn valid_addresses(&self) -> Result<HashSet<Address>> {
4316        if self.addresses().len() > MAX_REQUEST_ADDRESSES {
4317            return Err(format!(
4318                "too many addresses: the limit is {MAX_REQUEST_ADDRESSES}"
4319            ))
4320            .map_error(server::error::LegacyCode::InvalidParameter);
4321        }
4322
4323        // Reference for the legacy error code:
4324        // <https://github.com/zcash/zcash/blob/99ad6fdc3a549ab510422820eea5e5ce9f60a5fd/src/rpc/misc.cpp#L783-L784>
4325        let valid_addresses: HashSet<Address> = self
4326            .addresses()
4327            .iter()
4328            .map(|address| {
4329                let address: Address = address
4330                    .parse()
4331                    .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
4332
4333                // Reject TEX addresses, which parse but can never match an index entry.
4334                //
4335                // Transparent outputs are only ever classified as P2PKH or P2SH by
4336                // `Output::address()`, since the output script has no TEX discriminator, and the
4337                // index keys on the `Address` variant as well as the hash. So a TEX address would
4338                // silently return an empty result rather than the balance of the P2PKH address it
4339                // was derived from. zcashd's address index never sees TEX addresses at all, so an
4340                // error is also the compatible behaviour here.
4341                if matches!(address, Address::Tex { .. }) {
4342                    return Err("TEX addresses are not supported by the address index, \
4343                         use the transparent P2PKH address they were derived from")
4344                    .map_error(server::error::LegacyCode::InvalidAddressOrKey);
4345                }
4346
4347                Ok(address)
4348            })
4349            .collect::<Result<_>>()?;
4350
4351        Ok(valid_addresses)
4352    }
4353
4354    /// Returns string-encoded Zcash addresses in the type implementing this trait.
4355    fn addresses(&self) -> &[String];
4356}
4357
4358impl ValidateAddresses for GetAddressBalanceRequest {
4359    fn addresses(&self) -> &[String] {
4360        &self.addresses
4361    }
4362}
4363
4364impl GetAddressBalanceRequest {
4365    /// Creates a new `AddressStrings` given a vector.
4366    pub fn new(addresses: Vec<String>) -> GetAddressBalanceRequest {
4367        GetAddressBalanceRequest { addresses }
4368    }
4369
4370    /// Creates a new [`AddressStrings`] from a given vector, returns an error if any addresses are incorrect.
4371    #[deprecated(
4372        note = "Use `AddressStrings::new` instead. Validity will be checked by the server."
4373    )]
4374    pub fn new_valid(addresses: Vec<String>) -> Result<GetAddressBalanceRequest> {
4375        let req = Self { addresses };
4376        req.valid_addresses()?;
4377        Ok(req)
4378    }
4379}
4380
4381/// The transparent balance of a set of addresses.
4382#[derive(
4383    Clone,
4384    Copy,
4385    Debug,
4386    Default,
4387    Eq,
4388    PartialEq,
4389    Hash,
4390    serde::Serialize,
4391    serde::Deserialize,
4392    Getters,
4393    new,
4394)]
4395pub struct GetAddressBalanceResponse {
4396    /// The total transparent balance.
4397    balance: u64,
4398    /// The total received balance, including change.
4399    pub received: u64,
4400}
4401
4402#[deprecated(note = "Use `GetAddressBalanceResponse` instead.")]
4403pub use self::GetAddressBalanceResponse as AddressBalance;
4404
4405/// Parameters of [`RpcServer::get_address_utxos`] RPC method.
4406#[derive(
4407    Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, JsonSchema,
4408)]
4409#[serde(from = "DGetAddressUtxosRequest")]
4410pub struct GetAddressUtxosRequest {
4411    /// A list of addresses to get unspent outputs from.
4412    addresses: Vec<String>,
4413    /// Whether to return chain info along with the unspent outputs.
4414    #[serde(default)]
4415    #[serde(rename = "chainInfo")]
4416    chain_info: bool,
4417    /// The height to start looking for unspent outputs, or zero for the whole chain.
4418    #[serde(default)]
4419    #[serde(rename = "startHeight")]
4420    start_height: u64,
4421    /// The maximum number of unspent outputs to return, or zero for up to 100,000.
4422    #[serde(default)]
4423    #[serde(rename = "maxEntries")]
4424    max_entries: u32,
4425}
4426
4427impl GetAddressUtxosRequest {
4428    /// Creates a new request for every unspent output held by `addresses`.
4429    pub fn new(addresses: Vec<String>, chain_info: bool) -> GetAddressUtxosRequest {
4430        GetAddressUtxosRequest {
4431            addresses,
4432            chain_info,
4433            start_height: 0,
4434            max_entries: 0,
4435        }
4436    }
4437
4438    /// Limits this request to the unspent outputs at or above `start_height`, and to at most
4439    /// `max_entries` of them. Zero means "from the genesis block" and "up to 100,000".
4440    ///
4441    /// Both limits are taken together, because applying `max_entries` on its own would
4442    /// truncate the outputs before the height filter ran.
4443    pub fn with_limits(self, start_height: u64, max_entries: u32) -> GetAddressUtxosRequest {
4444        GetAddressUtxosRequest {
4445            start_height,
4446            max_entries,
4447            ..self
4448        }
4449    }
4450}
4451
4452impl From<DGetAddressUtxosRequest> for GetAddressUtxosRequest {
4453    fn from(request: DGetAddressUtxosRequest) -> Self {
4454        match request {
4455            DGetAddressUtxosRequest::Single(addr) => GetAddressUtxosRequest::new(vec![addr], false),
4456            DGetAddressUtxosRequest::Object {
4457                addresses,
4458                chain_info,
4459                start_height,
4460                max_entries,
4461            } => GetAddressUtxosRequest::new(addresses, chain_info)
4462                .with_limits(start_height, max_entries),
4463        }
4464    }
4465}
4466
4467/// An intermediate type used to deserialize [`GetAddressUtxosRequest`].
4468#[derive(Debug, serde::Deserialize, JsonSchema)]
4469#[serde(untagged)]
4470enum DGetAddressUtxosRequest {
4471    /// A single address string.
4472    Single(String),
4473    /// A full request object with an address list, a chainInfo flag, and optional limits.
4474    Object {
4475        /// A list of addresses to get unspent outputs from.
4476        addresses: Vec<String>,
4477        /// Whether to return chain info along with the unspent outputs.
4478        #[serde(default)]
4479        #[serde(rename = "chainInfo")]
4480        chain_info: bool,
4481        /// The height to start looking for unspent outputs, or zero for the whole chain.
4482        #[serde(default)]
4483        #[serde(rename = "startHeight")]
4484        start_height: u64,
4485        /// The maximum number of unspent outputs to return, or zero for no limit.
4486        #[serde(default)]
4487        #[serde(rename = "maxEntries")]
4488        max_entries: u32,
4489    },
4490}
4491
4492impl ValidateAddresses for GetAddressUtxosRequest {
4493    fn addresses(&self) -> &[String] {
4494        &self.addresses
4495    }
4496}
4497
4498/// A hex-encoded [`ConsensusBranchId`] string.
4499#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
4500pub struct ConsensusBranchIdHex(#[serde(with = "hex")] ConsensusBranchId);
4501
4502impl ConsensusBranchIdHex {
4503    /// Returns a new instance of ['ConsensusBranchIdHex'].
4504    pub fn new(consensus_branch_id: u32) -> Self {
4505        ConsensusBranchIdHex(consensus_branch_id.into())
4506    }
4507
4508    /// Returns the value of the ['ConsensusBranchId'].
4509    pub fn inner(&self) -> u32 {
4510        self.0.into()
4511    }
4512}
4513
4514/// Information about [`NetworkUpgrade`] activation.
4515#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4516pub struct NetworkUpgradeInfo {
4517    /// Name of upgrade, string.
4518    ///
4519    /// Ignored by lightwalletd, but useful for debugging.
4520    name: NetworkUpgrade,
4521
4522    /// Block height of activation, numeric.
4523    #[serde(rename = "activationheight")]
4524    activation_height: Height,
4525
4526    /// Status of upgrade, string.
4527    status: NetworkUpgradeStatus,
4528}
4529
4530impl NetworkUpgradeInfo {
4531    /// Constructs [`NetworkUpgradeInfo`] from its constituent parts.
4532    pub fn from_parts(
4533        name: NetworkUpgrade,
4534        activation_height: Height,
4535        status: NetworkUpgradeStatus,
4536    ) -> Self {
4537        Self {
4538            name,
4539            activation_height,
4540            status,
4541        }
4542    }
4543
4544    /// Returns the contents of ['NetworkUpgradeInfo'].
4545    pub fn into_parts(self) -> (NetworkUpgrade, Height, NetworkUpgradeStatus) {
4546        (self.name, self.activation_height, self.status)
4547    }
4548}
4549
4550/// The activation status of a [`NetworkUpgrade`].
4551#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4552pub enum NetworkUpgradeStatus {
4553    /// The network upgrade is currently active.
4554    ///
4555    /// Includes all network upgrades that have previously activated,
4556    /// even if they are not the most recent network upgrade.
4557    #[serde(rename = "active")]
4558    Active,
4559
4560    /// The network upgrade does not have an activation height.
4561    #[serde(rename = "disabled")]
4562    Disabled,
4563
4564    /// The network upgrade has an activation height, but we haven't reached it yet.
4565    #[serde(rename = "pending")]
4566    Pending,
4567}
4568
4569/// The [`ConsensusBranchId`]s for the tip and the next block.
4570///
4571/// These branch IDs are different when the next block is a network upgrade activation block.
4572#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4573pub struct TipConsensusBranch {
4574    /// Branch ID used to validate the current chain tip, big-endian, hex-encoded.
4575    #[serde(rename = "chaintip")]
4576    chain_tip: ConsensusBranchIdHex,
4577
4578    /// Branch ID used to validate the next block, big-endian, hex-encoded.
4579    #[serde(rename = "nextblock")]
4580    next_block: ConsensusBranchIdHex,
4581}
4582
4583impl TipConsensusBranch {
4584    /// Constructs [`TipConsensusBranch`] from its constituent parts.
4585    pub fn from_parts(chain_tip: u32, next_block: u32) -> Self {
4586        Self {
4587            chain_tip: ConsensusBranchIdHex::new(chain_tip),
4588            next_block: ConsensusBranchIdHex::new(next_block),
4589        }
4590    }
4591
4592    /// Returns the contents of ['TipConsensusBranch'].
4593    pub fn into_parts(self) -> (u32, u32) {
4594        (self.chain_tip.inner(), self.next_block.inner())
4595    }
4596}
4597
4598/// Response to a `sendrawtransaction` RPC request.
4599///
4600/// Contains the hex-encoded hash of the sent transaction.
4601///
4602/// See the notes for the [`Rpc::send_raw_transaction` method].
4603#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4604pub struct SendRawTransactionResponse(#[serde(with = "hex")] transaction::Hash);
4605
4606#[deprecated(note = "Use `SendRawTransactionResponse` instead")]
4607pub use self::SendRawTransactionResponse as SentTransactionHash;
4608
4609impl Default for SendRawTransactionResponse {
4610    fn default() -> Self {
4611        Self(transaction::Hash::from([0; 32]))
4612    }
4613}
4614
4615impl SendRawTransactionResponse {
4616    /// Constructs a new [`SentTransactionHash`].
4617    pub fn new(hash: transaction::Hash) -> Self {
4618        SendRawTransactionResponse(hash)
4619    }
4620
4621    /// Returns the contents of ['SentTransactionHash'].
4622    #[deprecated(note = "Use `SentTransactionHash::hash` instead")]
4623    pub fn inner(&self) -> transaction::Hash {
4624        self.hash()
4625    }
4626
4627    /// Returns the contents of ['SentTransactionHash'].
4628    pub fn hash(&self) -> transaction::Hash {
4629        self.0
4630    }
4631}
4632
4633/// Response to a `getblock` RPC request.
4634///
4635/// See the notes for the [`RpcServer::get_block`] method.
4636#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
4637#[serde(untagged)]
4638pub enum GetBlockResponse {
4639    /// The request block, hex-encoded.
4640    Raw(#[serde(with = "hex")] SerializedBlock),
4641    /// The block object.
4642    Object(Box<BlockObject>),
4643}
4644
4645#[deprecated(note = "Use `GetBlockResponse` instead")]
4646pub use self::GetBlockResponse as GetBlock;
4647
4648impl Default for GetBlockResponse {
4649    fn default() -> Self {
4650        GetBlockResponse::Object(Box::new(BlockObject {
4651            hash: block::Hash([0; 32]),
4652            confirmations: 0,
4653            height: None,
4654            time: None,
4655            n_tx: 0,
4656            tx: Vec::new(),
4657            trees: GetBlockTrees::default(),
4658            size: None,
4659            version: None,
4660            merkle_root: None,
4661            block_commitments: None,
4662            final_sapling_root: None,
4663            final_orchard_root: None,
4664            nonce: None,
4665            bits: None,
4666            difficulty: None,
4667            chain_supply: None,
4668            value_pools: None,
4669            nsm_value_balance: None,
4670            previous_block_hash: None,
4671            next_block_hash: None,
4672            solution: None,
4673        }))
4674    }
4675}
4676
4677/// A Block object returned by the `getblock` RPC request.
4678#[allow(clippy::too_many_arguments)]
4679#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4680pub struct BlockObject {
4681    /// The hash of the requested block.
4682    #[getter(copy)]
4683    #[serde(with = "hex")]
4684    hash: block::Hash,
4685
4686    /// The number of confirmations of this block in the best chain,
4687    /// or -1 if it is not in the best chain.
4688    confirmations: i64,
4689
4690    /// The block size. TODO: fill it
4691    #[serde(skip_serializing_if = "Option::is_none")]
4692    #[getter(copy)]
4693    size: Option<i64>,
4694
4695    /// The height of the requested block.
4696    #[serde(skip_serializing_if = "Option::is_none")]
4697    #[getter(copy)]
4698    height: Option<Height>,
4699
4700    /// The version field of the requested block.
4701    #[serde(skip_serializing_if = "Option::is_none")]
4702    #[getter(copy)]
4703    version: Option<u32>,
4704
4705    /// The merkle root of the requested block.
4706    #[serde(with = "opthex", rename = "merkleroot")]
4707    #[serde(skip_serializing_if = "Option::is_none")]
4708    #[getter(copy)]
4709    merkle_root: Option<block::merkle::Root>,
4710
4711    /// The blockcommitments field of the requested block. Its interpretation changes
4712    /// depending on the network and height.
4713    #[serde(with = "opthex", rename = "blockcommitments")]
4714    #[serde(skip_serializing_if = "Option::is_none")]
4715    #[getter(copy)]
4716    block_commitments: Option<[u8; 32]>,
4717
4718    // `authdataroot` would be here. Undocumented. TODO: decide if we want to support it
4719    //
4720    /// The root of the Sapling commitment tree after applying this block.
4721    #[serde(with = "opthex", rename = "finalsaplingroot")]
4722    #[serde(skip_serializing_if = "Option::is_none")]
4723    #[getter(copy)]
4724    final_sapling_root: Option<[u8; 32]>,
4725
4726    /// The root of the Orchard commitment tree after applying this block.
4727    #[serde(with = "opthex", rename = "finalorchardroot")]
4728    #[serde(skip_serializing_if = "Option::is_none")]
4729    #[getter(copy)]
4730    final_orchard_root: Option<[u8; 32]>,
4731
4732    // `chainhistoryroot` would be here. Undocumented. TODO: decide if we want to support it
4733    //
4734    /// The number of transactions in this block.
4735    #[serde(rename = "nTx")]
4736    n_tx: usize,
4737
4738    /// List of transactions in block order, hex-encoded if verbosity=1 or
4739    /// as objects if verbosity=2.
4740    tx: Vec<GetBlockTransaction>,
4741
4742    /// The height of the requested block.
4743    #[serde(skip_serializing_if = "Option::is_none")]
4744    #[getter(copy)]
4745    time: Option<i64>,
4746
4747    /// The nonce of the requested block header.
4748    #[serde(with = "opthex")]
4749    #[serde(skip_serializing_if = "Option::is_none")]
4750    #[getter(copy)]
4751    nonce: Option<[u8; 32]>,
4752
4753    /// The Equihash solution in the requested block header.
4754    /// Note: presence of this field in getblock is not documented in zcashd.
4755    #[serde(with = "opthex")]
4756    #[serde(skip_serializing_if = "Option::is_none")]
4757    #[getter(copy)]
4758    solution: Option<Solution>,
4759
4760    /// The difficulty threshold of the requested block header displayed in compact form.
4761    #[serde(with = "opthex")]
4762    #[serde(skip_serializing_if = "Option::is_none")]
4763    #[getter(copy)]
4764    bits: Option<CompactDifficulty>,
4765
4766    /// Floating point number that represents the difficulty limit for this block as a multiple
4767    /// of the minimum difficulty for the network.
4768    #[serde(skip_serializing_if = "Option::is_none")]
4769    #[getter(copy)]
4770    difficulty: Option<f64>,
4771
4772    // `chainwork` would be here, but we don't plan on supporting it
4773    // `anchor` would be here. Not planned to be supported.
4774    //
4775    /// Chain supply balance
4776    #[serde(rename = "chainSupply")]
4777    #[serde(skip_serializing_if = "Option::is_none")]
4778    chain_supply: Option<GetBlockchainInfoBalance>,
4779
4780    /// Value pool balances
4781    #[serde(rename = "valuePools")]
4782    #[serde(skip_serializing_if = "Option::is_none")]
4783    value_pools: Option<BlockchainValuePoolBalances>,
4784
4785    /// The Network Sustainability Mechanism (NSM) value balance (NU7) after this block, and the
4786    /// block's change to it. It is not part of the chain supply, so it is not in `valuePools`.
4787    /// It is `monitored` from the block before NU7 activation.
4788    ///
4789    /// At the block before NU7 activation, the balance and change are `INITIAL_NSM_VALUE_BALANCE`
4790    /// as [ZIP 237] defines it, not fees burned in that block.
4791    ///
4792    /// [ZIP 237]: https://zips.z.cash/zip-0237
4793    #[serde(
4794        rename = "nsmValueBalance",
4795        skip_serializing_if = "Option::is_none",
4796        default
4797    )]
4798    nsm_value_balance: Option<GetBlockchainInfoBalance>,
4799
4800    /// Information about the note commitment trees.
4801    #[getter(copy)]
4802    trees: GetBlockTrees,
4803
4804    /// The previous block hash of the requested block header.
4805    #[serde(rename = "previousblockhash", skip_serializing_if = "Option::is_none")]
4806    #[serde(with = "opthex")]
4807    #[getter(copy)]
4808    previous_block_hash: Option<block::Hash>,
4809
4810    /// The next block hash after the requested block header.
4811    #[serde(rename = "nextblockhash", skip_serializing_if = "Option::is_none")]
4812    #[serde(with = "opthex")]
4813    #[getter(copy)]
4814    next_block_hash: Option<block::Hash>,
4815}
4816
4817#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
4818#[serde(untagged)]
4819/// The transaction list in a `getblock` call. Can be a list of transaction
4820/// IDs or the full transaction details depending on verbosity.
4821pub enum GetBlockTransaction {
4822    /// The transaction hash, hex-encoded.
4823    Hash(#[serde(with = "hex")] transaction::Hash),
4824    /// The block object.
4825    Object(Box<TransactionObject>),
4826}
4827
4828/// Response to a `getblockheader` RPC request.
4829///
4830/// See the notes for the [`RpcServer::get_block_header`] method.
4831#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
4832#[serde(untagged)]
4833pub enum GetBlockHeaderResponse {
4834    /// The request block header, hex-encoded.
4835    Raw(hex_data::HexData),
4836
4837    /// The block header object.
4838    Object(Box<BlockHeaderObject>),
4839}
4840
4841#[deprecated(note = "Use `GetBlockHeaderResponse` instead")]
4842pub use self::GetBlockHeaderResponse as GetBlockHeader;
4843
4844#[allow(clippy::too_many_arguments)]
4845#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4846/// Verbose response to a `getblockheader` RPC request.
4847///
4848/// See the notes for the [`RpcServer::get_block_header`] method.
4849pub struct BlockHeaderObject {
4850    /// The hash of the requested block.
4851    #[serde(with = "hex")]
4852    #[getter(copy)]
4853    hash: block::Hash,
4854
4855    /// The number of confirmations of this block in the best chain,
4856    /// or -1 if it is not in the best chain.
4857    confirmations: i64,
4858
4859    /// The height of the requested block.
4860    #[getter(copy)]
4861    height: Height,
4862
4863    /// The version field of the requested block.
4864    version: u32,
4865
4866    /// The merkle root of the requesteed block.
4867    #[serde(with = "hex", rename = "merkleroot")]
4868    #[getter(copy)]
4869    merkle_root: block::merkle::Root,
4870
4871    /// The blockcommitments field of the requested block. Its interpretation changes
4872    /// depending on the network and height.
4873    #[serde(with = "hex", rename = "blockcommitments")]
4874    #[getter(copy)]
4875    block_commitments: [u8; 32],
4876
4877    /// The root of the Sapling commitment tree after applying this block.
4878    #[serde(with = "hex", rename = "finalsaplingroot")]
4879    #[getter(copy)]
4880    final_sapling_root: [u8; 32],
4881
4882    /// The number of Sapling notes in the Sapling note commitment tree
4883    /// after applying this block. Used by the `getblock` RPC method.
4884    #[serde(skip)]
4885    sapling_tree_size: u64,
4886
4887    /// The block time of the requested block header in non-leap seconds since Jan 1 1970 GMT.
4888    time: i64,
4889
4890    /// The nonce of the requested block header.
4891    #[serde(with = "hex")]
4892    #[getter(copy)]
4893    nonce: [u8; 32],
4894
4895    /// The Equihash solution in the requested block header.
4896    #[serde(with = "hex")]
4897    #[getter(copy)]
4898    solution: Solution,
4899
4900    /// The difficulty threshold of the requested block header displayed in compact form.
4901    #[serde(with = "hex")]
4902    #[getter(copy)]
4903    bits: CompactDifficulty,
4904
4905    /// Floating point number that represents the difficulty limit for this block as a multiple
4906    /// of the minimum difficulty for the network.
4907    difficulty: f64,
4908
4909    /// The previous block hash of the requested block header.
4910    #[serde(rename = "previousblockhash")]
4911    #[serde(with = "hex")]
4912    #[getter(copy)]
4913    previous_block_hash: block::Hash,
4914
4915    /// The next block hash after the requested block header.
4916    #[serde(rename = "nextblockhash", skip_serializing_if = "Option::is_none")]
4917    #[getter(copy)]
4918    #[serde(with = "opthex")]
4919    next_block_hash: Option<block::Hash>,
4920}
4921
4922#[deprecated(note = "Use `BlockHeaderObject` instead")]
4923pub use BlockHeaderObject as GetBlockHeaderObject;
4924
4925impl Default for GetBlockHeaderResponse {
4926    fn default() -> Self {
4927        GetBlockHeaderResponse::Object(Box::default())
4928    }
4929}
4930
4931impl Default for BlockHeaderObject {
4932    fn default() -> Self {
4933        let difficulty: ExpandedDifficulty = zebra_chain::work::difficulty::U256::one().into();
4934
4935        BlockHeaderObject {
4936            hash: block::Hash([0; 32]),
4937            confirmations: 0,
4938            height: Height::MIN,
4939            version: 4,
4940            merkle_root: block::merkle::Root([0; 32]),
4941            block_commitments: Default::default(),
4942            final_sapling_root: Default::default(),
4943            sapling_tree_size: Default::default(),
4944            time: 0,
4945            nonce: [0; 32],
4946            solution: Solution::for_proposal(),
4947            bits: difficulty.to_compact(),
4948            difficulty: 1.0,
4949            previous_block_hash: block::Hash([0; 32]),
4950            next_block_hash: Some(block::Hash([0; 32])),
4951        }
4952    }
4953}
4954
4955/// Response to a `getbestblockhash` and `getblockhash` RPC request.
4956///
4957/// Contains the hex-encoded hash of the requested block.
4958///
4959/// Also see the notes for the [`RpcServer::get_best_block_hash`] and `get_block_hash` methods.
4960#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
4961#[serde(transparent)]
4962pub struct GetBlockHashResponse(#[serde(with = "hex")] pub(crate) block::Hash);
4963
4964impl GetBlockHashResponse {
4965    /// Constructs a new [`GetBlockHashResponse`] from a block hash.
4966    pub fn new(hash: block::Hash) -> Self {
4967        GetBlockHashResponse(hash)
4968    }
4969
4970    /// Returns the contents of [`GetBlockHashResponse`].
4971    pub fn hash(&self) -> block::Hash {
4972        self.0
4973    }
4974}
4975
4976#[deprecated(note = "Use `GetBlockHashResponse` instead")]
4977pub use self::GetBlockHashResponse as GetBlockHash;
4978
4979/// A block hash used by this crate that encodes as hex by default.
4980pub type Hash = GetBlockHashResponse;
4981
4982/// Response to a `getbestblockheightandhash` RPC request.
4983#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new)]
4984pub struct GetBlockHeightAndHashResponse {
4985    /// The best chain tip block height
4986    #[getter(copy)]
4987    height: block::Height,
4988    /// The best chain tip block hash
4989    #[getter(copy)]
4990    hash: block::Hash,
4991}
4992
4993#[deprecated(note = "Use `GetBlockHeightAndHashResponse` instead.")]
4994pub use GetBlockHeightAndHashResponse as GetBestBlockHeightAndHash;
4995
4996impl Default for GetBlockHeightAndHashResponse {
4997    fn default() -> Self {
4998        Self {
4999            height: block::Height::MIN,
5000            hash: block::Hash([0; 32]),
5001        }
5002    }
5003}
5004
5005impl Default for GetBlockHashResponse {
5006    fn default() -> Self {
5007        GetBlockHashResponse(block::Hash([0; 32]))
5008    }
5009}
5010
5011/// Response to a `getrawtransaction` RPC request.
5012///
5013/// See the notes for the [`Rpc::get_raw_transaction` method].
5014#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
5015#[serde(untagged)]
5016pub enum GetRawTransactionResponse {
5017    /// The raw transaction, encoded as hex bytes.
5018    Raw(#[serde(with = "hex")] SerializedTransaction),
5019    /// The transaction object.
5020    Object(Box<TransactionObject>),
5021}
5022
5023#[deprecated(note = "Use `GetRawTransactionResponse` instead")]
5024pub use self::GetRawTransactionResponse as GetRawTransaction;
5025
5026impl Default for GetRawTransactionResponse {
5027    fn default() -> Self {
5028        Self::Object(Box::default())
5029    }
5030}
5031
5032/// Response to a `getaddressutxos` RPC request.
5033#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
5034#[serde(untagged)]
5035pub enum GetAddressUtxosResponse {
5036    /// Response when `chainInfo` is false or not provided.
5037    Utxos(Vec<Utxo>),
5038    /// Response when `chainInfo` is true.
5039    UtxosAndChainInfo(GetAddressUtxosResponseObject),
5040}
5041
5042/// Response to a `getaddressutxos` RPC request, when `chainInfo` is true.
5043#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
5044pub struct GetAddressUtxosResponseObject {
5045    utxos: Vec<Utxo>,
5046    #[serde(with = "hex")]
5047    #[getter(copy)]
5048    hash: block::Hash,
5049    #[getter(copy)]
5050    height: block::Height,
5051}
5052
5053/// A UTXO returned by the `getaddressutxos` RPC request.
5054///
5055/// See the notes for the [`Rpc::get_address_utxos` method].
5056#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
5057pub struct Utxo {
5058    /// The transparent address, base58check encoded
5059    address: transparent::Address,
5060
5061    /// The output txid, in big-endian order, hex-encoded
5062    #[serde(with = "hex")]
5063    #[getter(copy)]
5064    txid: transaction::Hash,
5065
5066    /// The transparent output index, numeric
5067    #[serde(rename = "outputIndex")]
5068    #[getter(copy)]
5069    output_index: OutputIndex,
5070
5071    /// The transparent output script, hex encoded
5072    #[serde(with = "hex")]
5073    script: transparent::Script,
5074
5075    /// The amount of zatoshis in the transparent output
5076    satoshis: u64,
5077
5078    /// The block height, numeric.
5079    ///
5080    /// We put this field last, to match the zcashd order.
5081    #[getter(copy)]
5082    height: Height,
5083}
5084
5085#[deprecated(note = "Use `Utxo` instead")]
5086pub use self::Utxo as GetAddressUtxos;
5087
5088impl Default for Utxo {
5089    fn default() -> Self {
5090        Self {
5091            address: transparent::Address::from_pub_key_hash(
5092                zebra_chain::parameters::NetworkKind::default(),
5093                [0u8; 20],
5094            ),
5095            txid: transaction::Hash::from([0; 32]),
5096            output_index: OutputIndex::from_u64(0),
5097            script: transparent::Script::new(&[0u8; 10]),
5098            satoshis: u64::default(),
5099            height: Height(0),
5100        }
5101    }
5102}
5103
5104impl Utxo {
5105    /// Constructs a new instance of [`GetAddressUtxos`].
5106    #[deprecated(note = "Use `Utxo::new` instead")]
5107    pub fn from_parts(
5108        address: transparent::Address,
5109        txid: transaction::Hash,
5110        output_index: OutputIndex,
5111        script: transparent::Script,
5112        satoshis: u64,
5113        height: Height,
5114    ) -> Self {
5115        Utxo {
5116            address,
5117            txid,
5118            output_index,
5119            script,
5120            satoshis,
5121            height,
5122        }
5123    }
5124
5125    /// Returns the contents of [`GetAddressUtxos`].
5126    pub fn into_parts(
5127        &self,
5128    ) -> (
5129        transparent::Address,
5130        transaction::Hash,
5131        OutputIndex,
5132        transparent::Script,
5133        u64,
5134        Height,
5135    ) {
5136        (
5137            self.address,
5138            self.txid,
5139            self.output_index,
5140            self.script.clone(),
5141            self.satoshis,
5142            self.height,
5143        )
5144    }
5145}
5146
5147/// Parameters of [`RpcServer::get_address_tx_ids`] RPC method.
5148///
5149/// See [`RpcServer::get_address_tx_ids`] for more details.
5150#[derive(
5151    Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new, JsonSchema,
5152)]
5153#[serde(from = "DGetAddressTxIdsRequest")]
5154pub struct GetAddressTxIdsRequest {
5155    /// A list of addresses. The RPC method will get transactions IDs that sent or received
5156    /// funds to or from these addresses.
5157    addresses: Vec<String>,
5158    // The height to start looking for transactions.
5159    start: Option<u32>,
5160    // The height to end looking for transactions.
5161    end: Option<u32>,
5162}
5163
5164impl GetAddressTxIdsRequest {
5165    /// Constructs [`GetAddressTxIdsRequest`] from its constituent parts.
5166    #[deprecated(note = "Use `GetAddressTxIdsRequest::new` instead.")]
5167    pub fn from_parts(addresses: Vec<String>, start: u32, end: u32) -> Self {
5168        GetAddressTxIdsRequest {
5169            addresses,
5170            start: Some(start),
5171            end: Some(end),
5172        }
5173    }
5174
5175    /// Returns the contents of [`GetAddressTxIdsRequest`].
5176    pub fn into_parts(&self) -> (Vec<String>, u32, u32) {
5177        (
5178            self.addresses.clone(),
5179            self.start.unwrap_or(0),
5180            self.end.unwrap_or(0),
5181        )
5182    }
5183}
5184
5185impl From<DGetAddressTxIdsRequest> for GetAddressTxIdsRequest {
5186    fn from(request: DGetAddressTxIdsRequest) -> Self {
5187        match request {
5188            DGetAddressTxIdsRequest::Single(addr) => GetAddressTxIdsRequest {
5189                addresses: vec![addr],
5190                start: None,
5191                end: None,
5192            },
5193            DGetAddressTxIdsRequest::Object {
5194                addresses,
5195                start,
5196                end,
5197            } => GetAddressTxIdsRequest {
5198                addresses,
5199                start,
5200                end,
5201            },
5202        }
5203    }
5204}
5205
5206/// An intermediate type used to deserialize [`GetAddressTxIdsRequest`].
5207#[derive(Debug, serde::Deserialize, JsonSchema)]
5208#[serde(untagged)]
5209enum DGetAddressTxIdsRequest {
5210    /// A single address string.
5211    Single(String),
5212    /// A full request object with address list and optional height range.
5213    Object {
5214        /// A list of addresses to get transactions from.
5215        addresses: Vec<String>,
5216        /// The height to start looking for transactions.
5217        start: Option<u32>,
5218        /// The height to end looking for transactions.
5219        end: Option<u32>,
5220    },
5221}
5222
5223impl ValidateAddresses for GetAddressTxIdsRequest {
5224    fn addresses(&self) -> &[String] {
5225        &self.addresses
5226    }
5227}
5228
5229/// Information about the sapling and orchard note commitment trees if any.
5230#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
5231pub struct GetBlockTrees {
5232    #[serde(skip_serializing_if = "SaplingTrees::is_empty")]
5233    sapling: SaplingTrees,
5234    #[serde(skip_serializing_if = "OrchardTrees::is_empty")]
5235    orchard: OrchardTrees,
5236    // `default` so responses and fixtures from before Ironwood (which have no `ironwood` field)
5237    // still deserialize, as the empty tree.
5238    #[serde(default, skip_serializing_if = "IronwoodTrees::is_empty")]
5239    ironwood: IronwoodTrees,
5240}
5241
5242impl Default for GetBlockTrees {
5243    fn default() -> Self {
5244        GetBlockTrees {
5245            sapling: SaplingTrees { size: 0 },
5246            orchard: OrchardTrees { size: 0 },
5247            ironwood: IronwoodTrees { size: 0 },
5248        }
5249    }
5250}
5251
5252impl GetBlockTrees {
5253    /// Constructs a new instance of ['GetBlockTrees'].
5254    pub fn new(sapling: u64, orchard: u64, ironwood: u64) -> Self {
5255        GetBlockTrees {
5256            sapling: SaplingTrees { size: sapling },
5257            orchard: OrchardTrees { size: orchard },
5258            ironwood: IronwoodTrees { size: ironwood },
5259        }
5260    }
5261
5262    /// Returns sapling data held by ['GetBlockTrees'].
5263    pub fn sapling(self) -> u64 {
5264        self.sapling.size
5265    }
5266
5267    /// Returns orchard data held by ['GetBlockTrees'].
5268    pub fn orchard(self) -> u64 {
5269        self.orchard.size
5270    }
5271
5272    /// Returns ironwood data held by ['GetBlockTrees'].
5273    pub fn ironwood(self) -> u64 {
5274        self.ironwood.size
5275    }
5276}
5277
5278/// Sapling note commitment tree information.
5279#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
5280pub struct SaplingTrees {
5281    size: u64,
5282}
5283
5284impl SaplingTrees {
5285    fn is_empty(&self) -> bool {
5286        self.size == 0
5287    }
5288}
5289
5290/// Orchard note commitment tree information.
5291#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
5292pub struct OrchardTrees {
5293    size: u64,
5294}
5295
5296impl OrchardTrees {
5297    fn is_empty(&self) -> bool {
5298        self.size == 0
5299    }
5300}
5301
5302/// Ironwood note commitment tree information. Ironwood reuses the Orchard tree type.
5303#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
5304pub struct IronwoodTrees {
5305    size: u64,
5306}
5307
5308impl IronwoodTrees {
5309    fn is_empty(&self) -> bool {
5310        self.size == 0
5311    }
5312}
5313
5314/// Returns the `nsmValueBalance` entry for the block at `height`, converting the state's stored
5315/// balance and change to [ZIP 237]'s. They differ only at NU7 - 1 and NU7: ZIP 237 sets the balance
5316/// at NU7 - 1, but the state credits it in the NU7 block ([`nsm_value_balance_before`]).
5317///
5318/// [ZIP 237]: https://zips.z.cash/zip-0237
5319//
5320// TODO: credit the seed at NU7 - 1 in the state and remove this conversion (#12556)
5321pub(crate) fn nsm_value_balance_entry(
5322    network: &Network,
5323    height: Height,
5324    stored_balance: Amount<NonNegative>,
5325    stored_change: Option<Amount<NegativeAllowed>>,
5326) -> GetBlockchainInfoBalance {
5327    // The part of `NSMValueBalance(height)` that the state credits in the next block instead.
5328    let unstored_seed = |height: Height| match height.next() {
5329        Ok(next) => nsm_value_balance_before(next, network, Amount::zero()),
5330        Err(_) => Amount::zero(),
5331    };
5332
5333    let balance = (stored_balance + unstored_seed(height))
5334        .expect("the state stores a zero NSM value balance before NU7 activation");
5335    // The balance before the genesis block is zero.
5336    let parent_unstored_seed = height
5337        .previous()
5338        .map_or_else(|_| Amount::zero(), unstored_seed);
5339
5340    // A reorg between the state reads can put the change out of range; omit it then.
5341    let change = stored_change.and_then(|stored_change| {
5342        let change = (stored_change + unstored_seed(height).constrain().ok()?).ok()?;
5343        (change - parent_unstored_seed.constrain().ok()?).ok()
5344    });
5345
5346    GetBlockchainInfoBalance::nsm(network, height, balance, change)
5347}
5348
5349/// Runs `read` against the address book on a blocking thread, so waiting on its
5350/// mutex doesn't park an async runtime worker (#11618).
5351async fn read_address_book<AddressBook, T>(
5352    address_book: &AddressBook,
5353    read: impl FnOnce(AddressBook) -> T + Send + 'static,
5354) -> Result<T>
5355where
5356    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
5357    T: Send + 'static,
5358{
5359    let address_book = address_book.clone();
5360    tokio::task::spawn_blocking(move || read(address_book))
5361        .await
5362        .map_misc_error()
5363}
5364
5365/// Build a valid height range from the given optional start and end numbers.
5366///
5367/// # Parameters
5368///
5369/// - `start`: Optional starting height. If not provided, defaults to 0.
5370/// - `end`: Optional ending height. A value of 0 or absence of a value indicates to use `chain_height`.
5371/// - `chain_height`: The maximum permissible height.
5372///
5373/// # Returns
5374///
5375/// A `RangeInclusive<Height>` from the clamped start to the clamped end.
5376///
5377/// # Errors
5378///
5379/// Returns an error if the computed start is greater than the computed end.
5380fn build_height_range(
5381    start: Option<u32>,
5382    end: Option<u32>,
5383    chain_height: Height,
5384) -> Result<RangeInclusive<Height>> {
5385    // Convert optional values to Height, using 0 (as Height(0)) when missing.
5386    // If start is above chain_height, clamp it to chain_height.
5387    let start = Height(start.unwrap_or(0)).min(chain_height);
5388
5389    // For `end`, treat a zero value or missing value as `chain_height`:
5390    let end = match end {
5391        Some(0) | None => chain_height,
5392        Some(val) => Height(val).min(chain_height),
5393    };
5394
5395    if start > end {
5396        return Err(ErrorObject::owned(
5397            ErrorCode::InvalidParams.code(),
5398            format!("start {start:?} must be less than or equal to end {end:?}"),
5399            None::<()>,
5400        ));
5401    }
5402
5403    Ok(start..=end)
5404}
5405
5406/// Given a potentially negative index, find the corresponding `Height`.
5407///
5408/// This function is used to parse the integer index argument of `get_block_hash`.
5409/// This is based on zcashd's implementation:
5410/// <https://github.com/zcash/zcash/blob/c267c3ee26510a974554f227d40a89e3ceb5bb4d/src/rpc/blockchain.cpp#L589-L618>
5411//
5412// TODO: also use this function in `get_block` and `z_get_treestate`
5413pub fn height_from_signed_int(index: i32, tip_height: Height) -> Result<Height> {
5414    if index >= 0 {
5415        let height = index.try_into().map_err(|_| {
5416            ErrorObject::borrowed(
5417                ErrorCode::InvalidParams.code(),
5418                "Index conversion failed",
5419                None,
5420            )
5421        })?;
5422        if height > tip_height.0 {
5423            return Err(ErrorObject::borrowed(
5424                ErrorCode::InvalidParams.code(),
5425                "Provided index is greater than the current tip",
5426                None,
5427            ));
5428        }
5429        Ok(Height(height))
5430    } else {
5431        // `index + 1` can't overflow, because `index` is always negative here.
5432        let height = i32::try_from(tip_height.0)
5433            .map_err(|_| {
5434                ErrorObject::borrowed(
5435                    ErrorCode::InvalidParams.code(),
5436                    "Tip height conversion failed",
5437                    None,
5438                )
5439            })?
5440            .checked_add(index + 1);
5441
5442        let sanitized_height = match height {
5443            None => {
5444                return Err(ErrorObject::borrowed(
5445                    ErrorCode::InvalidParams.code(),
5446                    "Provided index is not valid",
5447                    None,
5448                ));
5449            }
5450            Some(h) => {
5451                if h < 0 {
5452                    return Err(ErrorObject::borrowed(
5453                        ErrorCode::InvalidParams.code(),
5454                        "Provided negative index ends up with a negative height",
5455                        None,
5456                    ));
5457                }
5458                let h: u32 = h.try_into().map_err(|_| {
5459                    ErrorObject::borrowed(
5460                        ErrorCode::InvalidParams.code(),
5461                        "Height conversion failed",
5462                        None,
5463                    )
5464                })?;
5465                if h > tip_height.0 {
5466                    return Err(ErrorObject::borrowed(
5467                        ErrorCode::InvalidParams.code(),
5468                        "Provided index is greater than the current tip",
5469                        None,
5470                    ));
5471                }
5472
5473                h
5474            }
5475        };
5476
5477        Ok(Height(sanitized_height))
5478    }
5479}
5480
5481/// A helper module to serialize and deserialize `Option<T: ToHex>` as a hex string.
5482pub mod opthex {
5483    use hex::{FromHex, ToHex};
5484    use serde::{de, Deserialize, Deserializer, Serializer};
5485
5486    #[allow(missing_docs)]
5487    pub fn serialize<S, T>(data: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
5488    where
5489        S: Serializer,
5490        T: ToHex,
5491    {
5492        match data {
5493            Some(data) => {
5494                let s = data.encode_hex::<String>();
5495                serializer.serialize_str(&s)
5496            }
5497            None => serializer.serialize_none(),
5498        }
5499    }
5500
5501    #[allow(missing_docs)]
5502    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
5503    where
5504        D: Deserializer<'de>,
5505        T: FromHex,
5506    {
5507        let opt = Option::<String>::deserialize(deserializer)?;
5508        match opt {
5509            Some(s) => T::from_hex(&s)
5510                .map(Some)
5511                .map_err(|_e| de::Error::custom("failed to convert hex string")),
5512            None => Ok(None),
5513        }
5514    }
5515}
5516
5517/// A helper module to serialize and deserialize `[u8; N]` as a hex string.
5518pub mod arrayhex {
5519    use serde::{Deserializer, Serializer};
5520    use std::fmt;
5521
5522    #[allow(missing_docs)]
5523    pub fn serialize<S, const N: usize>(data: &[u8; N], serializer: S) -> Result<S::Ok, S::Error>
5524    where
5525        S: Serializer,
5526    {
5527        let hex_string = hex::encode(data);
5528        serializer.serialize_str(&hex_string)
5529    }
5530
5531    #[allow(missing_docs)]
5532    pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> Result<[u8; N], D::Error>
5533    where
5534        D: Deserializer<'de>,
5535    {
5536        struct HexArrayVisitor<const N: usize>;
5537
5538        impl<const N: usize> serde::de::Visitor<'_> for HexArrayVisitor<N> {
5539            type Value = [u8; N];
5540
5541            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
5542                write!(formatter, "a hex string representing exactly {N} bytes")
5543            }
5544
5545            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
5546            where
5547                E: serde::de::Error,
5548            {
5549                let vec = hex::decode(v).map_err(E::custom)?;
5550                vec.clone().try_into().map_err(|_| {
5551                    E::invalid_length(vec.len(), &format!("expected {N} bytes").as_str())
5552                })
5553            }
5554        }
5555
5556        deserializer.deserialize_str(HexArrayVisitor::<N>)
5557    }
5558}
5559
5560/// Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
5561pub async fn chain_tip_difficulty<State>(
5562    network: Network,
5563    mut state: State,
5564    should_use_default: bool,
5565) -> Result<f64>
5566where
5567    State: ReadStateService,
5568{
5569    let request = ReadRequest::ChainInfo;
5570
5571    // # TODO
5572    // - add a separate request like BestChainNextMedianTimePast, but skipping the
5573    //   consistency check, because any block's difficulty is ok for display
5574    // - return 1.0 for a "not enough blocks in the state" error, like `zcashd`:
5575    // <https://github.com/zcash/zcash/blob/7b28054e8b46eb46a9589d0bdc8e29f9fa1dc82d/src/rpc/blockchain.cpp#L40-L41>
5576    let response = state
5577        .ready()
5578        .and_then(|service| service.call(request))
5579        .await;
5580
5581    let response = match (should_use_default, response) {
5582        (_, Ok(res)) => res,
5583        (true, Err(_)) => {
5584            return Ok((U256::from(network.target_difficulty_limit()) >> 128).as_u128() as f64);
5585        }
5586        (false, Err(error)) => return Err(ErrorObject::owned(0, error.to_string(), None::<()>)),
5587    };
5588
5589    let chain_info = match response {
5590        ReadResponse::ChainInfo(info) => info,
5591        _ => unreachable!("unmatched response to a chain info request"),
5592    };
5593
5594    // This RPC is typically used for display purposes, so it is not consensus-critical.
5595    // But it uses the difficulty consensus rules for its calculations.
5596    //
5597    // Consensus:
5598    // https://zips.z.cash/protocol/protocol.pdf#nbits
5599    //
5600    // The zcashd implementation performs to_expanded() on f64,
5601    // and then does an inverse division:
5602    // https://github.com/zcash/zcash/blob/d6e2fada844373a8554ee085418e68de4b593a6c/src/rpc/blockchain.cpp#L46-L73
5603    //
5604    // But in Zebra we divide the high 128 bits of each expanded difficulty. This gives
5605    // a similar result, because the lower 128 bits are insignificant after conversion
5606    // to `f64` with a 53-bit mantissa.
5607    //
5608    // `pow_limit >> 128 / difficulty >> 128` is the same as the work calculation
5609    // `(2^256 / pow_limit) / (2^256 / difficulty)`, but it's a bit more accurate.
5610    //
5611    // To simplify the calculation, we don't scale for leading zeroes. (Bitcoin's
5612    // difficulty currently uses 68 bits, so even it would still have full precision
5613    // using this calculation.)
5614
5615    // Get expanded difficulties (256 bits), these are the inverse of the work
5616    let pow_limit: U256 = network.target_difficulty_limit().into();
5617    let Some(difficulty) = chain_info.expected_difficulty.to_expanded() else {
5618        return Ok(0.0);
5619    };
5620
5621    // Shift out the lower 128 bits (256 bits, but the top 128 are all zeroes)
5622    let pow_limit = pow_limit >> 128;
5623    let difficulty = U256::from(difficulty) >> 128;
5624
5625    // Convert to u128 then f64.
5626    // We could also convert U256 to String, then parse as f64, but that's slower.
5627    let pow_limit = pow_limit.as_u128() as f64;
5628    let difficulty = difficulty.as_u128() as f64;
5629
5630    // Invert the division to give approximately: `work(difficulty) / work(pow_limit)`
5631    Ok(pow_limit / difficulty)
5632}
5633
5634/// Commands for the `addnode` RPC method.
5635#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
5636pub enum AddNodeCommand {
5637    /// Add a node to the address book.
5638    #[serde(rename = "add")]
5639    Add,
5640}
5641
5642/// Response to a `gettxout` RPC request.
5643///
5644/// See the notes for the [`Rpc::get_tx_out` method].
5645#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
5646#[serde(transparent)]
5647pub struct GetTxOutResponse(Option<types::transaction::OutputObject>);