1use 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
145pub(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)]
181pub trait Rpc {
183 #[method(name = "getinfo")]
198 async fn get_info(&self) -> Result<GetInfoResponse>;
199
200 #[method(name = "getdeprecationinfo")]
220 async fn get_deprecation_info(&self) -> Result<GetDeprecationInfoResponse>;
221
222 #[method(name = "getblockchaininfo")]
233 async fn get_blockchain_info(&self) -> Result<GetBlockchainInfoResponse>;
234
235 #[method(name = "getaddressbalance")]
258 async fn get_address_balance(
259 &self,
260 address_strings: GetAddressBalanceRequest,
261 ) -> Result<GetAddressBalanceResponse>;
262
263 #[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 #[method(name = "getblock")]
312 async fn get_block(
313 &self,
314 hash_or_height: String,
315 verbosity: Option<u8>,
316 ) -> Result<GetBlockResponse>;
317
318 #[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 #[method(name = "getbestblockhash")]
348 fn get_best_block_hash(&self) -> Result<GetBlockHashResponse>;
349
350 #[method(name = "getbestblockheightandhash")]
356 fn get_best_block_height_and_hash(&self) -> Result<GetBlockHeightAndHashResponse>;
357
358 #[method(name = "getmempoolinfo")]
362 async fn get_mempool_info(&self) -> Result<GetMempoolInfoResponse>;
363
364 #[method(name = "getrawmempool")]
374 async fn get_raw_mempool(&self, verbose: Option<bool>) -> Result<GetRawMempoolResponse>;
375
376 #[method(name = "z_gettreestate")]
393 async fn z_get_treestate(&self, hash_or_height: String) -> Result<GetTreestateResponse>;
394
395 #[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 #[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 #[method(name = "getaddresstxids")]
472 async fn get_address_tx_ids(&self, request: GetAddressTxIdsRequest) -> Result<Vec<String>>;
473
474 #[method(name = "getaddressutxos")]
503 async fn get_address_utxos(
504 &self,
505 request: GetAddressUtxosRequest,
506 ) -> Result<GetAddressUtxosResponse>;
507
508 #[method(name = "stop")]
519 fn stop(&self) -> Result<String>;
520
521 #[method(name = "getblockcount")]
528 fn get_block_count(&self) -> Result<u32>;
529
530 #[method(name = "getblockhash")]
546 async fn get_block_hash(&self, index: i32) -> Result<GetBlockHashResponse>;
547
548 #[method(name = "getblocktemplate")]
570 async fn get_block_template(
571 &self,
572 parameters: Option<GetBlockTemplateParameters>,
573 ) -> Result<GetBlockTemplateResponse>;
574
575 #[method(name = "submitblock")]
594 async fn submit_block(
595 &self,
596 hex_data: HexData,
597 _parameters: Option<SubmitBlockParameters>,
598 ) -> Result<SubmitBlockResponse>;
599
600 #[method(name = "getmininginfo")]
606 async fn get_mining_info(&self) -> Result<GetMiningInfoResponse>;
607
608 #[method(name = "getnetworksolps")]
619 async fn get_network_sol_ps(&self, num_blocks: Option<i32>, height: Option<i32>)
620 -> Result<u64>;
621
622 #[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 #[method(name = "getnetworkinfo")]
646 async fn get_network_info(&self) -> Result<GetNetworkInfoResponse>;
647
648 #[method(name = "getpeerinfo")]
654 async fn get_peer_info(&self) -> Result<Vec<PeerInfo>>;
655
656 #[method(name = "ping")]
665 async fn ping(&self) -> Result<()>;
666
667 #[method(name = "validateaddress")]
678 async fn validate_address(&self, address: String) -> Result<ValidateAddressResponse>;
679
680 #[method(name = "z_validateaddress")]
695 async fn z_validate_address(&self, address: String) -> Result<ZValidateAddressResponse>;
696
697 #[method(name = "z_converttex")]
715 async fn z_convert_tex(&self, address: String) -> Result<String>;
716
717 #[method(name = "getstandardfee")]
727 async fn get_standard_fee(&self) -> Result<GetStandardFeeResponse>;
728
729 #[method(name = "getblocksubsidy")]
746 async fn get_block_subsidy(&self, height: Option<u32>) -> Result<GetBlockSubsidyResponse>;
747
748 #[method(name = "getdifficulty")]
754 async fn get_difficulty(&self) -> Result<f64>;
755
756 #[method(name = "z_listunifiedreceivers")]
770 async fn z_list_unified_receivers(
771 &self,
772 address: String,
773 ) -> Result<ZListUnifiedReceiversResponse>;
774
775 #[method(name = "invalidateblock")]
783 async fn invalidate_block(&self, block_hash: String) -> Result<()>;
784
785 #[method(name = "reconsiderblock")]
791 async fn reconsider_block(&self, block_hash: String) -> Result<Vec<block::Hash>>;
792
793 #[method(name = "generate")]
794 async fn generate(&self, num_blocks: u32) -> Result<Vec<GetBlockHashResponse>>;
808
809 #[method(name = "generatetoaddress")]
810 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 async fn add_node(&self, addr: PeerSocketAddr, command: AddNodeCommand) -> Result<()>;
858
859 #[method(name = "rpc.discover")]
861 fn openrpc(&self) -> openrpsee::openrpc::Response;
862 #[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#[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 build_version: String,
898
899 user_agent: String,
901
902 network: Network,
904
905 debug_force_finished_sync: bool,
908
909 end_of_support_height: Option<Height>,
912
913 max_address_query_results: usize,
915
916 mempool: Mempool,
920
921 state: State,
923
924 read_state: ReadState,
926
927 latest_chain_tip: Tip,
929
930 queue_sender: broadcast::Sender<UnminedTx>,
934
935 address_book: AddressBook,
937
938 last_warn_error_log_rx: LoggedLastEvent,
940
941 gbt: GetBlockTemplateHandler<BlockVerifierRouter, SyncStatus>,
943
944 first_template_tip: FirstTemplateTip,
946
947 #[cfg(test)]
949 template_clock: Option<Arc<std::sync::atomic::AtomicU32>>,
950}
951
952#[derive(Clone, Debug, Default)]
954struct FirstTemplateTip(Arc<Mutex<Option<(block::Hash, Instant)>>>);
955
956impl FirstTemplateTip {
957 fn record(&self, chain_tip: &impl ChainTip, hash: block::Hash) -> bool {
963 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
983pub 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 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 #[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 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 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 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 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 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 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 tokio::select! {
1151 () = update_templates => {}
1152 () = validate_templates => {}
1153 }
1154 }
1155 .in_current_span(),
1156 ))
1157 }
1158
1159 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 if cache.is_empty() {
1190 return None;
1191 }
1192
1193 let mut template_changes = cache.subscribe();
1199
1200 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 let max_time = template.max_time;
1226
1227 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 tip_changed.ok()?;
1241 }
1242
1243 () = template_changes.changed() => {}
1244
1245 () = wait_for_max_time, if long_poll_started <= max_time => {}
1247 }
1248 }
1249 }
1250
1251 async fn precomputed_template_for_state_tip(
1256 &self,
1257 cache: &precompute::TemplateCache,
1258 ) -> Option<Arc<BlockTemplateResponse>> {
1259 let mut template_changes = cache.subscribe();
1262
1263 let timeout = precompute::new_tip_timeout(self.gbt.miner_params()?);
1266
1267 tokio::time::timeout(timeout, async move {
1268 loop {
1269 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 pub fn network(&self) -> &Network {
1298 &self.network
1299 }
1300
1301 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 #[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 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 .filter(|_| self.network == Network::Mainnet)
1392 .map(|end_of_support_height| {
1393 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 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 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 .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 let mut upgrades = IndexMap::new();
1496 for (activation_height, network_upgrade) in network.full_activation_list() {
1497 if let Some(branch_id) = network_upgrade.branch_id() {
1502 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 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 chain_work: 0,
1551 pruned: false,
1552 size_on_disk,
1553 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 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 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 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 .map_error(server::error::LegacyCode::Verify)
1643 }
1644
1645 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 .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 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 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 let in_active_chain = confirmations >= 0;
1732
1733 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 transactions_request,
1763 zebra_state::ReadRequest::OrchardTree(hash_or_height),
1765 zebra_state::ReadRequest::IronwoodTree(hash_or_height),
1767 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 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 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 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 .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 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 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 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 const NOT_IN_BEST_CHAIN_CONFIRMATIONS: i64 = -1;
2005
2006 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 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 transactions.sort_by_cached_key(|tx| {
2157 cmp::Reverse((
2160 i64::from(tx.miner_fee) as u128 * MAX_BLOCK_BYTES as u128
2161 / tx.transaction.size as u128,
2162 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 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 let txid = transaction::Hash::from_hex(txid)
2203 .map_error(server::error::LegacyCode::InvalidAddressOrKey)?;
2204
2205 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 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 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 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 .map_error(server::error::LegacyCode::InvalidParameter)?;
2382
2383 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 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 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 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 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 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 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 let start_height = Height(
2662 u32::try_from(utxos_request.start_height)
2663 .unwrap_or(u32::MAX)
2664 .min(Height::MAX.0),
2665 );
2666 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 let max_entries = if requested_entries > 0 {
2676 requested_entries
2677 } else {
2678 cap.saturating_add(1)
2679 };
2680
2681 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 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 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 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 check_parameters(¶meters)?;
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 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 let (server_long_poll_id, chain_info, mempool_txs, mempool_tx_deps, submit_old) = loop {
2871 check_synced_to_tip(&self.network, latest_chain_tip.clone(), sync_status.clone())?;
2877 latest_chain_tip.mark_best_tip_seen();
2885
2886 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 let Some((mempool_txs, mempool_tx_deps)) =
2911 fetch_mempool_transactions(mempool.clone(), tip_hash)
2912 .await?
2913 .or_else(|| client_long_poll_id.is_none().then(Default::default))
2917 else {
2918 continue;
2919 };
2920
2921 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 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 if Some(&server_long_poll_id) != client_long_poll_id.as_ref() || max_time_reached {
2942 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 let wait_for_mempool_request =
2966 tokio::time::sleep(Duration::from_secs(MEMPOOL_LONG_POLL_INTERVAL));
2967
2968 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 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 tokio::select! {
2985 biased;
2988
2989 _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 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 () = wait_for_max_time, if long_poll_started <= max_time => {
3016 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 }
3027 }
3028 };
3029
3030 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 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 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 (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 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 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 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 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 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 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 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 Ok(_verify_chain_error) => SubmitBlockErrorResponse::Rejected,
3231
3232 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 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 let num_blocks = num_blocks.unwrap_or(DEFAULT_SOLUTION_RATE_WINDOW_SIZE);
3286 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 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 let local_services = format!("{:016x}", PeerServices::NODE_NETWORK);
3322
3323 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 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 let local_addresses = vec![];
3343
3344 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 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 .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 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 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 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 .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 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 let is_post_nu6 = NetworkUpgrade::current(&net, height) >= NetworkUpgrade::Nu6;
3516
3517 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 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 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 => { }
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 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 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 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 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 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 None => return Ok(GetTxOutResponse(None)),
3860 };
3861
3862 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
3900pub 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#[allow(clippy::too_many_arguments)]
3917#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
3918pub struct GetInfoResponse {
3919 #[getter(rename = "raw_version")]
3921 version: u64,
3922
3923 build: String,
3925
3926 subversion: String,
3928
3929 #[serde(rename = "protocolversion")]
3931 protocol_version: u32,
3932
3933 blocks: u32,
3935
3936 connections: usize,
3938
3939 #[serde(skip_serializing_if = "Option::is_none")]
3941 proxy: Option<String>,
3942
3943 difficulty: f64,
3945
3946 testnet: bool,
3948
3949 #[serde(rename = "paytxfee")]
3951 pay_tx_fee: f64,
3952
3953 #[serde(rename = "relayfee")]
3955 relay_fee: f64,
3956
3957 errors: String,
3959
3960 #[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 #[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 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 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 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
4080const END_OF_SERVICE_ESTIMATE_SAFETY_MARGIN: i64 = 24 * 60 * 60;
4086
4087#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4091pub struct GetDeprecationInfoResponse {
4092 #[serde(skip_serializing_if = "Option::is_none")]
4095 end_of_service: Option<EndOfService>,
4096}
4097
4098#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4100pub struct EndOfService {
4101 #[getter(copy)]
4104 block_height: u32,
4105
4106 #[getter(copy)]
4112 estimated_time: i64,
4113}
4114
4115pub type BlockchainValuePoolBalances = [GetBlockchainInfoBalance; 6];
4117
4118#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters)]
4122pub struct GetBlockchainInfoResponse {
4123 chain: String,
4125
4126 #[getter(copy)]
4128 blocks: Height,
4129
4130 #[getter(copy)]
4133 headers: Height,
4134
4135 difficulty: f64,
4137
4138 #[serde(rename = "verificationprogress")]
4140 verification_progress: f64,
4141
4142 #[serde(rename = "chainwork")]
4144 chain_work: u64,
4145
4146 pruned: bool,
4148
4149 size_on_disk: u64,
4151
4152 commitments: u64,
4154
4155 #[serde(rename = "bestblockhash", with = "hex")]
4157 #[getter(copy)]
4158 best_block_hash: block::Hash,
4159
4160 #[serde(rename = "estimatedheight")]
4164 #[getter(copy)]
4165 estimated_height: Height,
4166
4167 #[serde(rename = "chainSupply")]
4169 chain_supply: GetBlockchainInfoBalance,
4170
4171 #[serde(rename = "valuePools")]
4173 value_pools: BlockchainValuePoolBalances,
4174
4175 #[serde(
4179 rename = "nsmValueBalance",
4180 skip_serializing_if = "Option::is_none",
4181 default
4182 )]
4183 nsm_value_balance: Option<GetBlockchainInfoBalance>,
4184
4185 upgrades: IndexMap<ConsensusBranchIdHex, NetworkUpgradeInfo>,
4187
4188 #[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 #[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#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, serde::Serialize, JsonSchema)]
4270#[serde(from = "DGetAddressBalanceRequest")]
4271pub struct GetAddressBalanceRequest {
4272 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#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Deserialize, JsonSchema)]
4291#[serde(untagged)]
4292enum DGetAddressBalanceRequest {
4293 Addresses { addresses: Vec<String> },
4295 Address(String),
4297}
4298
4299#[deprecated(note = "Use `GetAddressBalanceRequest` instead.")]
4301pub type AddressStrings = GetAddressBalanceRequest;
4302
4303pub(crate) const MAX_REQUEST_ADDRESSES: usize = 10_000;
4305
4306pub(crate) const MAX_ADDRESS_QUERY_RESULTS: usize = 100_000;
4309
4310pub trait ValidateAddresses {
4312 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 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 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 fn addresses(&self) -> &[String];
4356}
4357
4358impl ValidateAddresses for GetAddressBalanceRequest {
4359 fn addresses(&self) -> &[String] {
4360 &self.addresses
4361 }
4362}
4363
4364impl GetAddressBalanceRequest {
4365 pub fn new(addresses: Vec<String>) -> GetAddressBalanceRequest {
4367 GetAddressBalanceRequest { addresses }
4368 }
4369
4370 #[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#[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 balance: u64,
4398 pub received: u64,
4400}
4401
4402#[deprecated(note = "Use `GetAddressBalanceResponse` instead.")]
4403pub use self::GetAddressBalanceResponse as AddressBalance;
4404
4405#[derive(
4407 Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, JsonSchema,
4408)]
4409#[serde(from = "DGetAddressUtxosRequest")]
4410pub struct GetAddressUtxosRequest {
4411 addresses: Vec<String>,
4413 #[serde(default)]
4415 #[serde(rename = "chainInfo")]
4416 chain_info: bool,
4417 #[serde(default)]
4419 #[serde(rename = "startHeight")]
4420 start_height: u64,
4421 #[serde(default)]
4423 #[serde(rename = "maxEntries")]
4424 max_entries: u32,
4425}
4426
4427impl GetAddressUtxosRequest {
4428 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 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#[derive(Debug, serde::Deserialize, JsonSchema)]
4469#[serde(untagged)]
4470enum DGetAddressUtxosRequest {
4471 Single(String),
4473 Object {
4475 addresses: Vec<String>,
4477 #[serde(default)]
4479 #[serde(rename = "chainInfo")]
4480 chain_info: bool,
4481 #[serde(default)]
4483 #[serde(rename = "startHeight")]
4484 start_height: u64,
4485 #[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#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
4500pub struct ConsensusBranchIdHex(#[serde(with = "hex")] ConsensusBranchId);
4501
4502impl ConsensusBranchIdHex {
4503 pub fn new(consensus_branch_id: u32) -> Self {
4505 ConsensusBranchIdHex(consensus_branch_id.into())
4506 }
4507
4508 pub fn inner(&self) -> u32 {
4510 self.0.into()
4511 }
4512}
4513
4514#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4516pub struct NetworkUpgradeInfo {
4517 name: NetworkUpgrade,
4521
4522 #[serde(rename = "activationheight")]
4524 activation_height: Height,
4525
4526 status: NetworkUpgradeStatus,
4528}
4529
4530impl NetworkUpgradeInfo {
4531 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 pub fn into_parts(self) -> (NetworkUpgrade, Height, NetworkUpgradeStatus) {
4546 (self.name, self.activation_height, self.status)
4547 }
4548}
4549
4550#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4552pub enum NetworkUpgradeStatus {
4553 #[serde(rename = "active")]
4558 Active,
4559
4560 #[serde(rename = "disabled")]
4562 Disabled,
4563
4564 #[serde(rename = "pending")]
4566 Pending,
4567}
4568
4569#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
4573pub struct TipConsensusBranch {
4574 #[serde(rename = "chaintip")]
4576 chain_tip: ConsensusBranchIdHex,
4577
4578 #[serde(rename = "nextblock")]
4580 next_block: ConsensusBranchIdHex,
4581}
4582
4583impl TipConsensusBranch {
4584 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 pub fn into_parts(self) -> (u32, u32) {
4594 (self.chain_tip.inner(), self.next_block.inner())
4595 }
4596}
4597
4598#[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 pub fn new(hash: transaction::Hash) -> Self {
4618 SendRawTransactionResponse(hash)
4619 }
4620
4621 #[deprecated(note = "Use `SentTransactionHash::hash` instead")]
4623 pub fn inner(&self) -> transaction::Hash {
4624 self.hash()
4625 }
4626
4627 pub fn hash(&self) -> transaction::Hash {
4629 self.0
4630 }
4631}
4632
4633#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
4637#[serde(untagged)]
4638pub enum GetBlockResponse {
4639 Raw(#[serde(with = "hex")] SerializedBlock),
4641 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#[allow(clippy::too_many_arguments)]
4679#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
4680pub struct BlockObject {
4681 #[getter(copy)]
4683 #[serde(with = "hex")]
4684 hash: block::Hash,
4685
4686 confirmations: i64,
4689
4690 #[serde(skip_serializing_if = "Option::is_none")]
4692 #[getter(copy)]
4693 size: Option<i64>,
4694
4695 #[serde(skip_serializing_if = "Option::is_none")]
4697 #[getter(copy)]
4698 height: Option<Height>,
4699
4700 #[serde(skip_serializing_if = "Option::is_none")]
4702 #[getter(copy)]
4703 version: Option<u32>,
4704
4705 #[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 #[serde(with = "opthex", rename = "blockcommitments")]
4714 #[serde(skip_serializing_if = "Option::is_none")]
4715 #[getter(copy)]
4716 block_commitments: Option<[u8; 32]>,
4717
4718 #[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 #[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 #[serde(rename = "nTx")]
4736 n_tx: usize,
4737
4738 tx: Vec<GetBlockTransaction>,
4741
4742 #[serde(skip_serializing_if = "Option::is_none")]
4744 #[getter(copy)]
4745 time: Option<i64>,
4746
4747 #[serde(with = "opthex")]
4749 #[serde(skip_serializing_if = "Option::is_none")]
4750 #[getter(copy)]
4751 nonce: Option<[u8; 32]>,
4752
4753 #[serde(with = "opthex")]
4756 #[serde(skip_serializing_if = "Option::is_none")]
4757 #[getter(copy)]
4758 solution: Option<Solution>,
4759
4760 #[serde(with = "opthex")]
4762 #[serde(skip_serializing_if = "Option::is_none")]
4763 #[getter(copy)]
4764 bits: Option<CompactDifficulty>,
4765
4766 #[serde(skip_serializing_if = "Option::is_none")]
4769 #[getter(copy)]
4770 difficulty: Option<f64>,
4771
4772 #[serde(rename = "chainSupply")]
4777 #[serde(skip_serializing_if = "Option::is_none")]
4778 chain_supply: Option<GetBlockchainInfoBalance>,
4779
4780 #[serde(rename = "valuePools")]
4782 #[serde(skip_serializing_if = "Option::is_none")]
4783 value_pools: Option<BlockchainValuePoolBalances>,
4784
4785 #[serde(
4794 rename = "nsmValueBalance",
4795 skip_serializing_if = "Option::is_none",
4796 default
4797 )]
4798 nsm_value_balance: Option<GetBlockchainInfoBalance>,
4799
4800 #[getter(copy)]
4802 trees: GetBlockTrees,
4803
4804 #[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 #[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)]
4819pub enum GetBlockTransaction {
4822 Hash(#[serde(with = "hex")] transaction::Hash),
4824 Object(Box<TransactionObject>),
4826}
4827
4828#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
4832#[serde(untagged)]
4833pub enum GetBlockHeaderResponse {
4834 Raw(hex_data::HexData),
4836
4837 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)]
4846pub struct BlockHeaderObject {
4850 #[serde(with = "hex")]
4852 #[getter(copy)]
4853 hash: block::Hash,
4854
4855 confirmations: i64,
4858
4859 #[getter(copy)]
4861 height: Height,
4862
4863 version: u32,
4865
4866 #[serde(with = "hex", rename = "merkleroot")]
4868 #[getter(copy)]
4869 merkle_root: block::merkle::Root,
4870
4871 #[serde(with = "hex", rename = "blockcommitments")]
4874 #[getter(copy)]
4875 block_commitments: [u8; 32],
4876
4877 #[serde(with = "hex", rename = "finalsaplingroot")]
4879 #[getter(copy)]
4880 final_sapling_root: [u8; 32],
4881
4882 #[serde(skip)]
4885 sapling_tree_size: u64,
4886
4887 time: i64,
4889
4890 #[serde(with = "hex")]
4892 #[getter(copy)]
4893 nonce: [u8; 32],
4894
4895 #[serde(with = "hex")]
4897 #[getter(copy)]
4898 solution: Solution,
4899
4900 #[serde(with = "hex")]
4902 #[getter(copy)]
4903 bits: CompactDifficulty,
4904
4905 difficulty: f64,
4908
4909 #[serde(rename = "previousblockhash")]
4911 #[serde(with = "hex")]
4912 #[getter(copy)]
4913 previous_block_hash: block::Hash,
4914
4915 #[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#[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 pub fn new(hash: block::Hash) -> Self {
4967 GetBlockHashResponse(hash)
4968 }
4969
4970 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
4979pub type Hash = GetBlockHashResponse;
4981
4982#[derive(Copy, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new)]
4984pub struct GetBlockHeightAndHashResponse {
4985 #[getter(copy)]
4987 height: block::Height,
4988 #[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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
5015#[serde(untagged)]
5016pub enum GetRawTransactionResponse {
5017 Raw(#[serde(with = "hex")] SerializedTransaction),
5019 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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
5034#[serde(untagged)]
5035pub enum GetAddressUtxosResponse {
5036 Utxos(Vec<Utxo>),
5038 UtxosAndChainInfo(GetAddressUtxosResponseObject),
5040}
5041
5042#[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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Getters, new)]
5057pub struct Utxo {
5058 address: transparent::Address,
5060
5061 #[serde(with = "hex")]
5063 #[getter(copy)]
5064 txid: transaction::Hash,
5065
5066 #[serde(rename = "outputIndex")]
5068 #[getter(copy)]
5069 output_index: OutputIndex,
5070
5071 #[serde(with = "hex")]
5073 script: transparent::Script,
5074
5075 satoshis: u64,
5077
5078 #[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 #[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 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#[derive(
5151 Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Getters, new, JsonSchema,
5152)]
5153#[serde(from = "DGetAddressTxIdsRequest")]
5154pub struct GetAddressTxIdsRequest {
5155 addresses: Vec<String>,
5158 start: Option<u32>,
5160 end: Option<u32>,
5162}
5163
5164impl GetAddressTxIdsRequest {
5165 #[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 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#[derive(Debug, serde::Deserialize, JsonSchema)]
5208#[serde(untagged)]
5209enum DGetAddressTxIdsRequest {
5210 Single(String),
5212 Object {
5214 addresses: Vec<String>,
5216 start: Option<u32>,
5218 end: Option<u32>,
5220 },
5221}
5222
5223impl ValidateAddresses for GetAddressTxIdsRequest {
5224 fn addresses(&self) -> &[String] {
5225 &self.addresses
5226 }
5227}
5228
5229#[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 #[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 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 pub fn sapling(self) -> u64 {
5264 self.sapling.size
5265 }
5266
5267 pub fn orchard(self) -> u64 {
5269 self.orchard.size
5270 }
5271
5272 pub fn ironwood(self) -> u64 {
5274 self.ironwood.size
5275 }
5276}
5277
5278#[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#[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#[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
5314pub(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 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 let parent_unstored_seed = height
5337 .previous()
5338 .map_or_else(|_| Amount::zero(), unstored_seed);
5339
5340 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
5349async 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
5365fn build_height_range(
5381 start: Option<u32>,
5382 end: Option<u32>,
5383 chain_height: Height,
5384) -> Result<RangeInclusive<Height>> {
5385 let start = Height(start.unwrap_or(0)).min(chain_height);
5388
5389 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
5406pub 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 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
5481pub 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
5517pub 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
5560pub 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 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 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 let pow_limit = pow_limit >> 128;
5623 let difficulty = U256::from(difficulty) >> 128;
5624
5625 let pow_limit = pow_limit.as_u128() as f64;
5628 let difficulty = difficulty.as_u128() as f64;
5629
5630 Ok(pow_limit / difficulty)
5632}
5633
5634#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, JsonSchema)]
5636pub enum AddNodeCommand {
5637 #[serde(rename = "add")]
5639 Add,
5640}
5641
5642#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
5646#[serde(transparent)]
5647pub struct GetTxOutResponse(Option<types::transaction::OutputObject>);