rpc-types -> types pt. 2
Some checks are pending
Deny / audit (push) Waiting to run

This commit is contained in:
hinto.janai 2024-12-05 20:45:27 -05:00
parent 2104bb0e17
commit 568a276b7f
No known key found for this signature in database
GPG key ID: D47CE05FA175A499
35 changed files with 797 additions and 1039 deletions

4
Cargo.lock generated
View file

@ -1067,8 +1067,11 @@ version = "0.0.0"
dependencies = [ dependencies = [
"cuprate-epee-encoding", "cuprate-epee-encoding",
"cuprate-fixed-bytes", "cuprate-fixed-bytes",
"cuprate-helper",
"cuprate-p2p-core",
"cuprate-test-utils", "cuprate-test-utils",
"cuprate-types", "cuprate-types",
"hex",
"paste", "paste",
"serde", "serde",
"serde_json", "serde_json",
@ -1127,6 +1130,7 @@ name = "cuprate-types"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"bytes", "bytes",
"cfg-if",
"cuprate-epee-encoding", "cuprate-epee-encoding",
"cuprate-fixed-bytes", "cuprate-fixed-bytes",
"cuprate-helper", "cuprate-helper",

View file

@ -15,7 +15,7 @@ use cuprate_rpc_types::{
json::{GetOutputDistributionRequest, GetOutputDistributionResponse}, json::{GetOutputDistributionRequest, GetOutputDistributionResponse},
misc::RequestedInfo, misc::RequestedInfo,
}; };
use cuprate_types::{BlockCompleteEntry, PoolInfoExtent}; use cuprate_types::{rpc::PoolInfoExtent, BlockCompleteEntry};
use crate::rpc::{helper, request::blockchain, CupratedRpcHandler}; use crate::rpc::{helper, request::blockchain, CupratedRpcHandler};

View file

@ -65,9 +65,9 @@ pub(super) async fn block_header(
) )
.await?; .await?;
hex::encode(pow_hash) pow_hash
} else { } else {
String::new() [0; 32]
}; };
let block_weight = usize_to_u64(header.block_weight); let block_weight = usize_to_u64(header.block_weight);
@ -86,30 +86,28 @@ pub(super) async fn block_header(
.map(|o| o.amount.expect("coinbase is transparent")) .map(|o| o.amount.expect("coinbase is transparent"))
.sum::<u64>(); .sum::<u64>();
Ok(BlockHeader { Ok(cuprate_types::rpc::BlockHeader {
block_size: block_weight,
block_weight, block_weight,
cumulative_difficulty_top64, cumulative_difficulty_top64,
cumulative_difficulty, cumulative_difficulty,
depth, depth,
difficulty_top64, difficulty_top64,
difficulty, difficulty,
hash: hex::encode(block.hash()), hash: block.hash(),
height, height,
long_term_weight: usize_to_u64(header.long_term_weight), long_term_weight: usize_to_u64(header.long_term_weight),
major_version: header.version.as_u8(), major_version: header.version,
miner_tx_hash: hex::encode(block.miner_transaction.hash()), miner_tx_hash: block.miner_transaction.hash(),
minor_version: header.vote, minor_version: header.vote,
nonce: block.header.nonce, nonce: block.header.nonce,
num_txes: usize_to_u64(block.transactions.len()), num_txes: usize_to_u64(block.transactions.len()),
orphan_status, orphan_status,
pow_hash, pow_hash,
prev_hash: hex::encode(block.header.previous), prev_hash: block.header.previous,
reward, reward,
timestamp: block.header.timestamp, timestamp: block.header.timestamp,
wide_cumulative_difficulty: hex::encode(u128::to_le_bytes(header.cumulative_difficulty)), }
wide_difficulty, .into())
})
} }
/// Same as [`block_header`] but with the block's hash. /// Same as [`block_header`] but with the block's hash.

View file

@ -47,13 +47,13 @@ use cuprate_rpc_types::{
SetBansRequest, SetBansResponse, SubmitBlockRequest, SubmitBlockResponse, SyncInfoRequest, SetBansRequest, SetBansResponse, SubmitBlockRequest, SubmitBlockResponse, SyncInfoRequest,
SyncInfoResponse, SyncInfoResponse,
}, },
misc::{ misc::{BlockHeader, ChainInfo, Distribution, GetBan, HistogramEntry, Status, SyncInfoPeer},
AuxPow, BlockHeader, ChainInfo, Distribution, GetBan, GetMinerDataTxBacklogEntry,
HardforkEntry, HistogramEntry, Status, SyncInfoPeer, TxBacklogEntry,
},
CORE_RPC_VERSION, CORE_RPC_VERSION,
}; };
use cuprate_types::HardFork; use cuprate_types::{
rpc::{AuxPow, CoinbaseTxSum, GetMinerDataTxBacklogEntry, HardforkEntry, TxBacklogEntry},
HardFork,
};
use crate::{ use crate::{
constants::VERSION_BUILD, constants::VERSION_BUILD,
@ -699,17 +699,17 @@ async fn get_coinbase_tx_sum(
mut state: CupratedRpcHandler, mut state: CupratedRpcHandler,
request: GetCoinbaseTxSumRequest, request: GetCoinbaseTxSumRequest,
) -> Result<GetCoinbaseTxSumResponse, Error> { ) -> Result<GetCoinbaseTxSumResponse, Error> {
let sum = let CoinbaseTxSum {
blockchain::coinbase_tx_sum(&mut state.blockchain_read, request.height, request.count) emission_amount_top64,
emission_amount,
fee_amount_top64,
fee_amount,
} = blockchain::coinbase_tx_sum(&mut state.blockchain_read, request.height, request.count)
.await?; .await?;
// Formats `u128` as hexadecimal strings. // Formats `u128` as hexadecimal strings.
let wide_emission_amount = format!("{:#x}", sum.fee_amount); let wide_emission_amount = format!("{fee_amount:#x}");
let wide_fee_amount = format!("{:#x}", sum.emission_amount); let wide_fee_amount = format!("{emission_amount:#x}");
let (emission_amount, emission_amount_top64) =
split_u128_into_low_high_bits(sum.emission_amount);
let (fee_amount, fee_amount_top64) = split_u128_into_low_high_bits(sum.fee_amount);
Ok(GetCoinbaseTxSumResponse { Ok(GetCoinbaseTxSumResponse {
base: AccessResponseBase::OK, base: AccessResponseBase::OK,
@ -738,7 +738,8 @@ async fn get_version(
{ {
let entry = HardforkEntry { let entry = HardforkEntry {
height: hf.earliest_height, height: hf.earliest_height,
hf_version: hf.version, hf_version: HardFork::from_version(hf.version)
.expect("blockchain context should not be responding with invalid hardforks"),
}; };
hard_forks.push(entry); hard_forks.push(entry);
@ -780,21 +781,7 @@ async fn get_alternate_chains(
let chains = blockchain::alt_chains(&mut state.blockchain_read) let chains = blockchain::alt_chains(&mut state.blockchain_read)
.await? .await?
.into_iter() .into_iter()
.map(|info| { .map(Into::into)
let block_hashes = info.block_hashes.into_iter().map(hex::encode).collect();
let (difficulty, difficulty_top64) = split_u128_into_low_high_bits(info.difficulty);
ChainInfo {
block_hash: hex::encode(info.block_hash),
block_hashes,
difficulty,
difficulty_top64,
height: info.height,
length: info.length,
main_chain_parent_block: hex::encode(info.main_chain_parent_block),
wide_difficulty: hex::encode(u128::to_ne_bytes(info.difficulty)),
}
})
.collect(); .collect();
Ok(GetAlternateChainsResponse { Ok(GetAlternateChainsResponse {
@ -1036,19 +1023,11 @@ fn add_aux_pow_inner(
return Err(anyhow!("Empty `aux_pow` vector")); return Err(anyhow!("Empty `aux_pow` vector"));
}; };
let aux_pow = request
.aux_pow
.into_iter()
.map(|aux| {
let id = helper::hex_to_hash(aux.id)?;
let hash = helper::hex_to_hash(aux.hash)?;
Ok(cuprate_types::rpc::AuxPow { id, hash })
})
.collect::<Result<Box<[_]>, Error>>()?;
// Some of the code below requires that the // Some of the code below requires that the
// `.len()` of certain containers are the same. // `.len()` of certain containers are the same.
// Boxed slices are used over `Vec` to slightly // Boxed slices are used over `Vec` to slightly
// safe-guard against accidently pushing to it. // safe-guard against accidently pushing to it.
let aux_pow = request.aux_pow.into_boxed_slice();
// TODO: why is this here? it does nothing: // TODO: why is this here? it does nothing:
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server.cpp#L2110-L2112> // <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server.cpp#L2110-L2112>
@ -1058,7 +1037,7 @@ fn add_aux_pow_inner(
// } // }
fn find_nonce( fn find_nonce(
aux_pow: &[cuprate_types::rpc::AuxPow], aux_pow: &[AuxPow],
non_zero_len: NonZero<usize>, non_zero_len: NonZero<usize>,
aux_pow_len: usize, aux_pow_len: usize,
) -> Result<(u32, Box<[u32]>), Error> { ) -> Result<(u32, Box<[u32]>), Error> {
@ -1219,11 +1198,8 @@ fn add_aux_pow_inner(
let blockhashing_blob = hex::encode(blockhashing_blob); let blockhashing_blob = hex::encode(blockhashing_blob);
let merkle_root = hex::encode(merkle_root); let merkle_root = hex::encode(merkle_root);
let aux_pow = IntoIterator::into_iter(aux_pow) // must be explicit due to `boxed_slice_into_iter` let aux_pow = IntoIterator::into_iter(aux_pow) // must be explicit due to `boxed_slice_into_iter`
.map(|aux| AuxPow { .map(Into::into)
id: hex::encode(aux.id), .collect::<Vec<cuprate_rpc_types::misc::AuxPow>>();
hash: hex::encode(aux.hash),
})
.collect::<Vec<AuxPow>>();
Ok(AddAuxPowResponse { Ok(AddAuxPowResponse {
base: ResponseBase::OK, base: ResponseBase::OK,

View file

@ -11,7 +11,7 @@ use cuprate_helper::cast::usize_to_u64;
use cuprate_rpc_interface::RpcHandler; use cuprate_rpc_interface::RpcHandler;
use cuprate_rpc_types::{ use cuprate_rpc_types::{
base::{AccessResponseBase, ResponseBase}, base::{AccessResponseBase, ResponseBase},
misc::{KeyImageSpentStatus, OutKey, Status}, misc::{KeyImageSpentStatus, Status},
other::{ other::{
GetAltBlocksHashesRequest, GetAltBlocksHashesResponse, GetHeightRequest, GetHeightResponse, GetAltBlocksHashesRequest, GetAltBlocksHashesResponse, GetHeightRequest, GetHeightResponse,
GetLimitRequest, GetLimitResponse, GetNetStatsRequest, GetNetStatsResponse, GetOutsRequest, GetLimitRequest, GetLimitResponse, GetNetStatsRequest, GetNetStatsResponse, GetOutsRequest,
@ -30,6 +30,7 @@ use cuprate_rpc_types::{
UpdateRequest, UpdateResponse, UpdateRequest, UpdateResponse,
}, },
}; };
use cuprate_types::rpc::OutKey;
use crate::{ use crate::{
rpc::CupratedRpcHandler, rpc::CupratedRpcHandler,

View file

@ -13,10 +13,7 @@ use cuprate_txpool::{
}, },
TxEntry, TxEntry,
}; };
use cuprate_types::{ use cuprate_types::rpc::{PoolInfo, PoolInfoFull, PoolInfoIncremental, PoolTxInfo};
rpc::{PoolInfoFull, PoolInfoIncremental, PoolTxInfo},
PoolInfo,
};
// FIXME: use `anyhow::Error` over `tower::BoxError` in txpool. // FIXME: use `anyhow::Error` over `tower::BoxError` in txpool.

View file

@ -9,17 +9,21 @@ repository = "https://github.com/Cuprate/cuprate/tree/main/rpc/types"
keywords = ["cuprate", "rpc", "types", "monero"] keywords = ["cuprate", "rpc", "types", "monero"]
[features] [features]
default = ["serde", "epee"] default = ["serde", "epee", "from"]
serde = ["dep:serde", "cuprate-fixed-bytes/serde", "cuprate-types/serde"] serde = ["dep:serde", "cuprate-fixed-bytes/serde", "cuprate-types/serde"]
epee = ["dep:cuprate-epee-encoding", "cuprate-types/epee"] epee = ["dep:cuprate-epee-encoding", "cuprate-types/epee"]
from = ["dep:cuprate-helper", "cuprate-helper/map", "dep:cuprate-p2p-core", "dep:hex"]
[dependencies] [dependencies]
cuprate-epee-encoding = { workspace = true, optional = true } cuprate-epee-encoding = { workspace = true, optional = true }
cuprate-fixed-bytes = { workspace = true } cuprate-fixed-bytes = { workspace = true }
cuprate-types = { workspace = true, default-features = false } cuprate-types = { workspace = true, default-features = false }
cuprate-helper = { workspace = true, optional = true, default-features = false }
cuprate-p2p-core = { workspace = true, optional = true, default-features = false }
paste = { workspace = true } paste = { workspace = true }
serde = { workspace = true, optional = true } serde = { workspace = true, optional = true }
hex = { workspace = true, optional = true }
[dev-dependencies] [dev-dependencies]
cuprate-test-utils = { workspace = true } cuprate-test-utils = { workspace = true }

View file

@ -29,7 +29,7 @@ use crate::{macros::monero_definition_link, misc::Status};
//---------------------------------------------------------------------------------------------------- Requests //---------------------------------------------------------------------------------------------------- Requests
/// A base for RPC request types that support RPC payment. /// A base for RPC request types that support RPC payment.
/// ///
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "rpc/core_rpc_server_commands_defs.h", 114..=122)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "rpc/core_rpc_server_commands_defs.h", 114..=122)]
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct AccessRequestBase { pub struct AccessRequestBase {
@ -44,7 +44,7 @@ epee_object! {
} }
//---------------------------------------------------------------------------------------------------- Responses //---------------------------------------------------------------------------------------------------- Responses
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "rpc/core_rpc_server_commands_defs.h", 101..=112)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "rpc/core_rpc_server_commands_defs.h", 101..=112)]
/// The most common base for responses. /// The most common base for responses.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
@ -98,7 +98,7 @@ epee_object! {
untrusted: bool, untrusted: bool,
} }
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "rpc/core_rpc_server_commands_defs.h", 124..=136)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "rpc/core_rpc_server_commands_defs.h", 124..=136)]
/// A base for RPC response types that support RPC payment. /// A base for RPC response types that support RPC payment.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]

View file

@ -11,12 +11,15 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "epee")] #[cfg(feature = "epee")]
use cuprate_epee_encoding::container_as_blob::ContainerAsBlob; use cuprate_epee_encoding::container_as_blob::ContainerAsBlob;
use cuprate_types::{BlockCompleteEntry, PoolInfo}; use cuprate_types::{
rpc::{BlockOutputIndices, PoolInfo},
BlockCompleteEntry,
};
use crate::{ use crate::{
base::AccessResponseBase, base::AccessResponseBase,
macros::define_request_and_response, macros::define_request_and_response,
misc::{BlockOutputIndices, GetOutputsOut, OutKeyBin}, misc::{GetOutputsOut, OutKeyBin},
rpc_call::RpcCallValue, rpc_call::RpcCallValue,
}; };

View file

@ -24,28 +24,28 @@ use crate::macros::monero_definition_link;
// Note that these are _distinct_ from the ones in ZMQ: // Note that these are _distinct_ from the ones in ZMQ:
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/message.cpp#L40-L44>. // <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/message.cpp#L40-L44>.
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 78)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 78)]
pub const CORE_RPC_STATUS_OK: &str = "OK"; pub const CORE_RPC_STATUS_OK: &str = "OK";
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 79)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 79)]
pub const CORE_RPC_STATUS_BUSY: &str = "BUSY"; pub const CORE_RPC_STATUS_BUSY: &str = "BUSY";
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 80)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 80)]
pub const CORE_RPC_STATUS_NOT_MINING: &str = "NOT MINING"; pub const CORE_RPC_STATUS_NOT_MINING: &str = "NOT MINING";
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 81)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 81)]
pub const CORE_RPC_STATUS_PAYMENT_REQUIRED: &str = "PAYMENT REQUIRED"; pub const CORE_RPC_STATUS_PAYMENT_REQUIRED: &str = "PAYMENT REQUIRED";
//---------------------------------------------------------------------------------------------------- Versions //---------------------------------------------------------------------------------------------------- Versions
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 90)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 90)]
/// RPC major version. /// RPC major version.
pub const CORE_RPC_VERSION_MAJOR: u32 = 3; pub const CORE_RPC_VERSION_MAJOR: u32 = 3;
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 91)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 91)]
/// RPC miror version. /// RPC miror version.
pub const CORE_RPC_VERSION_MINOR: u32 = 14; pub const CORE_RPC_VERSION_MINOR: u32 = 14;
#[doc = monero_definition_link!(cc73fe71162d564ffda8e549b79a350bca53c454, "/rpc/core_rpc_server_commands_defs.h", 92..=93)] #[doc = monero_definition_link!("cc73fe71162d564ffda8e549b79a350bca53c454", "/rpc/core_rpc_server_commands_defs.h", 92..=93)]
/// RPC version. /// RPC version.
pub const CORE_RPC_VERSION: u32 = (CORE_RPC_VERSION_MAJOR << 16) | CORE_RPC_VERSION_MINOR; pub const CORE_RPC_VERSION: u32 = (CORE_RPC_VERSION_MAJOR << 16) | CORE_RPC_VERSION_MINOR;

View file

@ -1,380 +1,230 @@
//! [`From`] implementations from other crate's types into [`crate`] types. //! [`From`] implementations from other crate's types into [`crate`] types.
//!
//! Only non-crate types are imported, all crate types use `crate::`.
#![allow(unused_variables, unreachable_code, reason = "TODO")] #![allow(unused_variables, unreachable_code, reason = "TODO")]
use cuprate_types::rpc::{ use std::{
AuxPow, BlockHeader, BlockOutputIndices, ChainInfo, ConnectionInfo, GetBan, net::{Ipv4Addr, SocketAddr, SocketAddrV4},
GetMinerDataTxBacklogEntry, GetOutputsOut, HardforkEntry, HistogramEntry, OutKey, OutKeyBin, time::Duration,
OutputDistributionData, Peer, PublicNode, SetBan, Span, SpentKeyImageInfo, SyncInfoPeer,
TxBacklogEntry, TxInfo, TxOutputIndices, TxpoolHisto, TxpoolStats,
}; };
use cuprate_helper::map::combine_low_high_bits_to_u128;
use cuprate_p2p_core::{
types::{BanState, ConnectionId, ConnectionInfo, SetBan, Span},
ClearNet, NetZoneAddress, NetworkZone,
};
use cuprate_types::{
hex::Hex,
rpc::{
AuxPow, BlockHeader, BlockOutputIndices, ChainInfo, GetBan, GetMinerDataTxBacklogEntry,
GetOutputsOut, HardforkEntry, HistogramEntry, OutKey, OutKeyBin, OutputDistributionData,
Peer, PublicNode, SpentKeyImageInfo, TxBacklogEntry, TxInfo, TxOutputIndices, TxpoolHisto,
TxpoolStats,
},
};
/// <https://architecture.cuprate.org/oddities/le-ipv4.html>
const fn ipv4_from_u32(ip: u32) -> Ipv4Addr {
let [a, b, c, d] = ip.to_le_bytes();
Ipv4Addr::new(a, b, c, d)
}
/// Format two [`u64`]'s as a [`u128`] as a hexadecimal string prefixed with `0x`.
fn hex_prefix_u128(low: u64, high: u64) -> String {
format!("{:#x}", combine_low_high_bits_to_u128(low, high))
}
impl From<BlockHeader> for crate::misc::BlockHeader { impl From<BlockHeader> for crate::misc::BlockHeader {
fn from(x: BlockHeader) -> Self { fn from(x: BlockHeader) -> Self {
todo!(); Self {
block_size: x.block_weight,
// Self { block_weight: x.block_weight,
// block_size: u64, cumulative_difficulty_top64: x.cumulative_difficulty_top64,
// block_weight: u64, cumulative_difficulty: x.cumulative_difficulty,
// cumulative_difficulty_top64: u64, depth: x.depth,
// cumulative_difficulty: u64, difficulty_top64: x.difficulty_top64,
// depth: u64, difficulty: x.difficulty,
// difficulty_top64: u64, hash: Hex(x.hash),
// difficulty: u64, height: x.height,
// hash: String, long_term_weight: x.long_term_weight,
// height: u64, major_version: x.major_version,
// long_term_weight: u64, miner_tx_hash: Hex(x.miner_tx_hash),
// major_version: u8, minor_version: x.minor_version,
// miner_tx_hash: String, nonce: x.nonce,
// minor_version: u8, num_txes: x.num_txes,
// nonce: u32, orphan_status: x.orphan_status,
// num_txes: u64, pow_hash: Hex(x.pow_hash),
// orphan_status: bool, prev_hash: Hex(x.prev_hash),
// pow_hash: String, reward: x.reward,
// prev_hash: String, timestamp: x.timestamp,
// reward: u64, // FIXME: if we made a type that automatically did `hex_prefix_u128`,
// timestamp: u64, // we wouldn't need `crate::misc::BlockHeader`.
// wide_cumulative_difficulty: String, wide_cumulative_difficulty: hex_prefix_u128(
// wide_difficulty: String, x.cumulative_difficulty,
// } x.cumulative_difficulty_top64,
),
wide_difficulty: hex_prefix_u128(x.difficulty, x.difficulty_top64),
}
} }
} }
impl From<ConnectionInfo> for crate::misc::ConnectionInfo { impl<A: NetZoneAddress> From<ConnectionInfo<A>> for crate::misc::ConnectionInfo {
fn from(x: ConnectionInfo) -> Self { fn from(x: ConnectionInfo<A>) -> Self {
todo!(); let (ip, port) = match x.socket_addr {
Some(socket) => (socket.ip().to_string(), socket.port().to_string()),
None => (String::new(), String::new()),
};
// Self { Self {
// address: String, address: x.address.to_string(),
// address_type: AddressType, address_type: x.address_type,
// avg_download: u64, avg_download: x.avg_download,
// avg_upload: u64, avg_upload: x.avg_upload,
// connection_id: String, connection_id: String::from(ConnectionId::DEFAULT_STR),
// current_download: u64, current_download: x.current_download,
// current_upload: u64, current_upload: x.current_upload,
// height: u64, height: x.height,
// host: String, host: x.host,
// incoming: bool, incoming: x.incoming,
// ip: String, ip,
// live_time: u64, live_time: x.live_time,
// localhost: bool, localhost: x.localhost,
// local_ip: bool, local_ip: x.local_ip,
// peer_id: String, peer_id: hex::encode(x.peer_id.to_ne_bytes()),
// port: String, port,
// pruning_seed: u32, pruning_seed: x.pruning_seed.compress(),
// recv_count: u64, recv_count: x.recv_count,
// recv_idle_time: u64, recv_idle_time: x.recv_idle_time,
// rpc_credits_per_hash: u32, rpc_credits_per_hash: x.rpc_credits_per_hash,
// rpc_port: u16, rpc_port: x.rpc_port,
// send_count: u64, send_count: x.send_count,
// send_idle_time: u64, send_idle_time: x.send_idle_time,
// // Exists in the original definition, but isn't state: x.state,
// // used or (de)serialized for RPC purposes. support_flags: x.support_flags,
// // ssl: bool, }
// state: ConnectionState,
// support_flags: u32,
// }
} }
} }
impl From<SetBan> for crate::misc::SetBan { // TODO: support non-clearnet addresses.
fn from(x: SetBan) -> Self { impl From<crate::misc::SetBan> for SetBan<SocketAddr> {
todo!(); fn from(x: crate::misc::SetBan) -> Self {
let address = SocketAddr::V4(SocketAddrV4::new(ipv4_from_u32(x.ip), 0));
// Self { let ban = if x.ban {
// #[cfg_attr(feature = "serde", serde(default = "default_string"))] Some(Duration::from_secs(x.seconds.into()))
// host: String, } else {
// #[cfg_attr(feature = "serde", serde(default = "default_zero"))] None
// ip: u32, };
// ban: bool,
// seconds: u32, Self { address, ban }
// }
}
}
impl From<GetBan> for crate::misc::GetBan {
fn from(x: GetBan) -> Self {
todo!();
// Self {
// host: String,
// ip: u32,
// seconds: u32,
// }
} }
} }
// TODO: do we need this type?
impl From<HistogramEntry> for crate::misc::HistogramEntry { impl From<HistogramEntry> for crate::misc::HistogramEntry {
fn from(x: HistogramEntry) -> Self { fn from(x: HistogramEntry) -> Self {
todo!(); Self {
amount: x.amount,
total_instances: x.total_instances,
unlocked_instances: x.unlocked_instances,
recent_instances: x.recent_instances,
}
}
}
// impl From<HardforkEntry> for crate::misc::HardforkEntry {
// fn from(x: HardforkEntry) -> Self {
// Self { // Self {
// amount: u64, // height: x.height,
// total_instances: u64, // hf_version: x.hf_version,
// unlocked_instances: u64, // }
// recent_instances: u64,
// } // }
}
}
impl From<HardforkEntry> for crate::misc::HardforkEntry {
fn from(x: HardforkEntry) -> Self {
todo!();
// Self {
// height: u64,
// hf_version: u8,
// } // }
}
}
impl From<ChainInfo> for crate::misc::ChainInfo { impl From<ChainInfo> for crate::misc::ChainInfo {
fn from(x: ChainInfo) -> Self { fn from(x: ChainInfo) -> Self {
todo!(); Self {
block_hash: Hex(x.block_hash),
block_hashes: x.block_hashes.into_iter().map(hex::encode).collect(),
difficulty_top64: x.difficulty_top64,
difficulty: x.difficulty,
height: x.height,
length: x.length,
main_chain_parent_block: Hex(x.main_chain_parent_block),
wide_difficulty: hex_prefix_u128(x.difficulty, x.difficulty_top64),
}
}
}
// Self { // TODO: support non-clearnet addresses.
// block_hash: [u8; 32], impl From<Span<SocketAddr>> for crate::misc::Span {
// block_hashes: Vec<[u8; 32]>, fn from(x: Span<SocketAddr>) -> Self {
// difficulty_top64: u64, Self {
// difficulty_low64: u64, connection_id: String::from(ConnectionId::DEFAULT_STR),
// height: u64, nblocks: x.nblocks,
// length: u64, rate: x.rate,
// main_chain_parent_block: [u8; 32], remote_address: x.remote_address.to_string(),
size: x.size,
speed: x.speed,
start_block_height: x.start_block_height,
}
}
}
// impl From<OutputDistributionData> for crate::misc::OutputDistributionData {
// fn from(x: OutputDistributionData) -> Self {
// todo!();
// // Self {
// // distribution: Vec<u64>,
// // start_height: u64,
// // base: u64,
// // }
// } // }
}
}
impl From<SyncInfoPeer> for crate::misc::SyncInfoPeer {
fn from(x: SyncInfoPeer) -> Self {
todo!();
// Self {
// info: ConnectionInfo,
// } // }
}
}
impl From<Span> for crate::misc::Span { impl From<TxInfo> for crate::misc::TxInfo {
fn from(x: Span) -> Self { fn from(x: TxInfo) -> Self {
todo!(); Self {
blob_size: x.blob_size,
// Self { do_not_relay: x.do_not_relay,
// connection_id: String, double_spend_seen: x.double_spend_seen,
// nblocks: u64, fee: x.fee,
// rate: u32, id_hash: Hex(x.id_hash),
// remote_address: String, kept_by_block: x.kept_by_block,
// size: u64, last_failed_height: x.last_failed_height,
// speed: u32, last_failed_id_hash: Hex(x.last_failed_id_hash),
// start_block_height: u64, last_relayed_time: x.last_relayed_time,
// } max_used_block_height: x.max_used_block_height,
max_used_block_id_hash: Hex(x.max_used_block_id_hash),
receive_time: x.receive_time,
relayed: x.relayed,
tx_blob: hex::encode(x.tx_blob),
tx_json: x.tx_json,
weight: x.weight,
} }
} }
impl From<TxBacklogEntry> for crate::misc::TxBacklogEntry {
fn from(x: TxBacklogEntry) -> Self {
todo!();
// Self {
// weight: u64,
// fee: u64,
// time_in_pool: u64,
// }
}
}
impl From<OutputDistributionData> for crate::misc::OutputDistributionData {
fn from(x: OutputDistributionData) -> Self {
todo!();
// Self {
// distribution: Vec<u64>,
// start_height: u64,
// base: u64,
// }
}
}
impl From<GetMinerDataTxBacklogEntry> for crate::misc::GetMinerDataTxBacklogEntry {
fn from(x: GetMinerDataTxBacklogEntry) -> Self {
todo!();
// Self {
// id: String,
// weight: u64,
// fee: u64,
// }
}
} }
impl From<AuxPow> for crate::misc::AuxPow { impl From<AuxPow> for crate::misc::AuxPow {
fn from(x: AuxPow) -> Self { fn from(x: AuxPow) -> Self {
todo!(); Self {
id: Hex(x.id),
// Self { hash: Hex(x.hash),
// id: [u8; 32], }
// hash: [u8; 32],
// }
} }
} }
impl From<TxOutputIndices> for crate::misc::TxOutputIndices { #[cfg(test)]
fn from(x: TxOutputIndices) -> Self { mod tests {
todo!(); use super::*;
// Self { #[test]
// indices: Vec<u64>, fn hex() {
// } assert_eq!(hex_prefix_u128(0, 0), "0x0");
} assert_eq!(hex_prefix_u128(0, u64::MAX), "0x0");
} assert_eq!(hex_prefix_u128(u64::MAX, 0), "0x0");
assert_eq!(hex_prefix_u128(u64::MAX, u64::MAX), "0x0");
impl From<BlockOutputIndices> for crate::misc::BlockOutputIndices {
fn from(x: BlockOutputIndices) -> Self {
todo!();
// Self {
// indices: Vec<TxOutputIndices>,
// }
}
}
impl From<GetOutputsOut> for crate::misc::GetOutputsOut {
fn from(x: GetOutputsOut) -> Self {
todo!();
// Self {
// amount: u64,
// index: u64,
// }
}
}
impl From<OutKeyBin> for crate::misc::OutKeyBin {
fn from(x: OutKeyBin) -> Self {
todo!();
// Self {
// key: [u8; 32],
// mask: [u8; 32],
// unlocked: bool,
// height: u64,
// txid: [u8; 32],
// }
}
}
impl From<Peer> for crate::misc::Peer {
fn from(x: Peer) -> Self {
todo!();
// Self {
// id: u64,
// host: String,
// ip: u32,
// port: u16,
// #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
// rpc_port: u16 = default_zero::<u16>(),
// #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
// rpc_credits_per_hash: u32 = default_zero::<u32>(),
// last_seen: u64,
// #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
// pruning_seed: u32 = default_zero::<u32>(),
// }
}
}
impl From<PublicNode> for crate::misc::PublicNode {
fn from(x: PublicNode) -> Self {
todo!();
// Self {
// host: String,
// last_seen: u64,
// rpc_port: u16,
// rpc_credits_per_hash: u32,
// }
}
}
impl From<TxInfo> for crate::misc::TxInfo {
fn from(x: TxInfo) -> Self {
todo!();
// Self {
// blob_size: u64,
// do_not_relay: bool,
// double_spend_seen: bool,
// fee: u64,
// id_hash: String,
// kept_by_block: bool,
// last_failed_height: u64,
// last_failed_id_hash: String,
// last_relayed_time: u64,
// max_used_block_height: u64,
// max_used_block_id_hash: String,
// receive_time: u64,
// relayed: bool,
// tx_blob: String,
// tx_json: String, // TODO: this should be another struct
// #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
// weight: u64 = default_zero::<u64>(),
// }
}
}
impl From<SpentKeyImageInfo> for crate::misc::SpentKeyImageInfo {
fn from(x: SpentKeyImageInfo) -> Self {
todo!();
// Self {
// id_hash: String,
// txs_hashes: Vec<String>,
// }
}
}
impl From<TxpoolHisto> for crate::misc::TxpoolHisto {
fn from(x: TxpoolHisto) -> Self {
todo!();
// Self {
// txs: u32,
// bytes: u64,
// }
}
}
impl From<TxpoolStats> for crate::misc::TxpoolStats {
fn from(x: TxpoolStats) -> Self {
todo!();
// Self {
// bytes_max: u32,
// bytes_med: u32,
// bytes_min: u32,
// bytes_total: u64,
// fee_total: u64,
// histo_98pc: u64,
// histo: Vec<TxpoolHisto>,
// num_10m: u32,
// num_double_spends: u32,
// num_failing: u32,
// num_not_relayed: u32,
// oldest: u64,
// txs_total: u32,
// }
}
}
impl From<OutKey> for crate::misc::OutKey {
fn from(x: OutKey) -> Self {
todo!();
// Self {
// key: String,
// mask: String,
// unlocked: bool,
// height: u64,
// txid: String,
// }
} }
} }

View file

@ -6,13 +6,14 @@
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use cuprate_types::rpc::{GetMinerDataTxBacklogEntry, HardforkEntry, TxBacklogEntry};
use crate::{ use crate::{
base::{AccessResponseBase, ResponseBase}, base::{AccessResponseBase, ResponseBase},
macros::define_request_and_response, macros::define_request_and_response,
misc::{ misc::{
AuxPow, BlockHeader, ChainInfo, ConnectionInfo, Distribution, GetBan, AuxPow, BlockHeader, ChainInfo, ConnectionInfo, Distribution, GetBan, HistogramEntry,
GetMinerDataTxBacklogEntry, HardforkEntry, HistogramEntry, SetBan, Span, Status, SetBan, Span, Status, SyncInfoPeer,
SyncInfoPeer, TxBacklogEntry,
}, },
rpc_call::RpcCallValue, rpc_call::RpcCallValue,
}; };

View file

@ -9,6 +9,7 @@ mod constants;
#[cfg(any(feature = "serde", feature = "epee"))] #[cfg(any(feature = "serde", feature = "epee"))]
mod defaults; mod defaults;
mod free; mod free;
#[cfg(feature = "from")]
mod from; mod from;
mod macros; mod macros;
mod rpc_call; mod rpc_call;

View file

@ -408,13 +408,13 @@ pub(crate) use define_request_and_response_doc;
/// Output a string link to `monerod` source code. /// Output a string link to `monerod` source code.
macro_rules! monero_definition_link { macro_rules! monero_definition_link {
( (
$commit:ident, // Git commit hash $commit:literal, // Git commit hash
$file_path:literal, // File path within `monerod`'s `src/`, e.g. `rpc/core_rpc_server_commands_defs.h` $file_path:literal, // File path within `monerod`'s `src/`, e.g. `rpc/core_rpc_server_commands_defs.h`
$start:literal$(..=$end:literal)? // File lines, e.g. `0..=123` or `0` $start:literal$(..=$end:literal)? // File lines, e.g. `0..=123` or `0`
) => { ) => {
concat!( concat!(
"[Definition](https://github.com/monero-project/monero/blob/", "[Definition](https://github.com/monero-project/monero/blob/",
stringify!($commit), $commit,
"/src/", "/src/",
$file_path, $file_path,
"#L", "#L",

View file

@ -16,7 +16,7 @@ use cuprate_epee_encoding::{
/// ///
/// Used for [`Distribution::CompressedBinary::distribution`]. /// Used for [`Distribution::CompressedBinary::distribution`].
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
45..=55 45..=55
)] )]
@ -29,7 +29,7 @@ fn compress_integer_array(_: &[u64]) -> Vec<u8> {
/// ///
/// Used for [`Distribution::CompressedBinary::distribution`]. /// Used for [`Distribution::CompressedBinary::distribution`].
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
57..=72 57..=72
)] )]
@ -40,7 +40,7 @@ fn decompress_integer_array(_: &[u8]) -> Vec<u64> {
//---------------------------------------------------------------------------------------------------- Distribution //---------------------------------------------------------------------------------------------------- Distribution
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2468..=2508 2468..=2508
)] )]

View file

@ -13,7 +13,7 @@ use cuprate_epee_encoding::{
//---------------------------------------------------------------------------------------------------- KeyImageSpentStatus //---------------------------------------------------------------------------------------------------- KeyImageSpentStatus
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
456..=460 456..=460
)] )]

View file

@ -27,8 +27,6 @@ pub use requested_info::RequestedInfo;
pub use status::Status; pub use status::Status;
pub use tx_entry::TxEntry; pub use tx_entry::TxEntry;
pub use types::{ pub use types::{
AuxPow, BlockHeader, BlockOutputIndices, ChainInfo, ConnectionInfo, GetBan, AuxPow, BlockHeader, ChainInfo, ConnectionInfo, GetBan, GetOutputsOut, HistogramEntry,
GetMinerDataTxBacklogEntry, GetOutputsOut, HardforkEntry, HistogramEntry, OutKey, OutKeyBin, OutKeyBin, SetBan, Span, SpentKeyImageInfo, SyncInfoPeer, TxInfo,
OutputDistributionData, Peer, PublicNode, SetBan, Span, SpentKeyImageInfo, SyncInfoPeer,
TxBacklogEntry, TxInfo, TxOutputIndices, TxpoolHisto, TxpoolStats,
}; };

View file

@ -13,7 +13,7 @@ use cuprate_epee_encoding::{
//---------------------------------------------------------------------------------------------------- RequestedInfo //---------------------------------------------------------------------------------------------------- RequestedInfo
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
178..=183 178..=183
)] )]

View file

@ -16,7 +16,7 @@ use crate::serde::{serde_false, serde_true};
//---------------------------------------------------------------------------------------------------- TxEntry //---------------------------------------------------------------------------------------------------- TxEntry
#[doc = crate::macros::monero_definition_link!( #[doc = crate::macros::monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
389..=428 389..=428
)] )]

View file

@ -5,6 +5,8 @@
//! the [`crate::misc::ConnectionInfo`] struct defined here. //! the [`crate::misc::ConnectionInfo`] struct defined here.
//---------------------------------------------------------------------------------------------------- Import //---------------------------------------------------------------------------------------------------- Import
use cuprate_types::{hex::Hex, HardFork};
#[cfg(any(feature = "epee", feature = "serde"))] #[cfg(any(feature = "epee", feature = "serde"))]
use crate::defaults::default_zero; use crate::defaults::default_zero;
@ -60,7 +62,7 @@ macro_rules! define_struct_and_impl_epee {
//---------------------------------------------------------------------------------------------------- Type Definitions //---------------------------------------------------------------------------------------------------- Type Definitions
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
1163..=1212 1163..=1212
)] )]
@ -79,17 +81,17 @@ define_struct_and_impl_epee! {
depth: u64, depth: u64,
difficulty_top64: u64, difficulty_top64: u64,
difficulty: u64, difficulty: u64,
hash: String, hash: Hex<32>,
height: u64, height: u64,
long_term_weight: u64, long_term_weight: u64,
major_version: u8, major_version: HardFork,
miner_tx_hash: String, miner_tx_hash: Hex<32>,
minor_version: u8, minor_version: u8,
nonce: u32, nonce: u32,
num_txes: u64, num_txes: u64,
orphan_status: bool, orphan_status: bool,
pow_hash: String, pow_hash: Hex<32>,
prev_hash: String, prev_hash: Hex<32>,
reward: u64, reward: u64,
timestamp: u64, timestamp: u64,
wide_cumulative_difficulty: String, wide_cumulative_difficulty: String,
@ -99,7 +101,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"cryptonote_protocol/cryptonote_protocol_defs.h", "cryptonote_protocol/cryptonote_protocol_defs.h",
47..=116 47..=116
)] )]
@ -138,7 +140,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2034..=2047 2034..=2047
)] )]
@ -155,7 +157,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
1999..=2010 1999..=2010
)] )]
@ -169,7 +171,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2139..=2156 2139..=2156
)] )]
@ -185,40 +187,26 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h",
2180..=2191
)]
#[derive(Copy)]
/// Used in [`crate::json::GetVersionResponse`].
HardforkEntry {
height: u64,
hf_version: u8,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2289..=2310 2289..=2310
)] )]
/// Used in [`crate::json::GetAlternateChainsResponse`]. /// Used in [`crate::json::GetAlternateChainsResponse`].
ChainInfo { ChainInfo {
block_hash: String, block_hash: Hex<32>,
block_hashes: Vec<String>, block_hashes: Vec<String>, // TODO: Vec<Hex<32>> when it has epee
difficulty: u64, difficulty: u64,
difficulty_top64: u64, difficulty_top64: u64,
height: u64, height: u64,
length: u64, length: u64,
main_chain_parent_block: String, main_chain_parent_block: Hex<32>,
wide_difficulty: String, wide_difficulty: String,
} }
} }
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2393..=2400 2393..=2400
)] )]
@ -230,7 +218,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
2402..=2421 2402..=2421
)] )]
@ -248,89 +236,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h",
1637..=1642
)]
#[derive(Copy)]
/// Used in [`crate::json::GetTransactionPoolBacklogResponse`].
TxBacklogEntry {
weight: u64,
fee: u64,
time_in_pool: u64,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/rpc_handler.h",
45..=50
)]
/// Used in [`crate::json::GetOutputDistributionResponse`].
OutputDistributionData {
distribution: Vec<u64>,
start_height: u64,
base: u64,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1016..=1027
)]
/// Used in [`crate::json::GetMinerDataResponse`].
///
/// Note that this is different than [`crate::misc::TxBacklogEntry`].
GetMinerDataTxBacklogEntry {
id: String,
weight: u64,
fee: u64,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1070..=1079
)]
/// Used in [`crate::json::AddAuxPowRequest`].
AuxPow {
id: String,
hash: String,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
192..=199
)]
/// Used in [`crate::bin::GetBlocksResponse`].
TxOutputIndices {
indices: Vec<u64>,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
201..=208
)]
/// Used in [`crate::bin::GetBlocksResponse`].
BlockOutputIndices {
indices: Vec<TxOutputIndices>,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
512..=521 512..=521
)] )]
@ -347,7 +253,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
538..=553 538..=553
)] )]
@ -364,47 +270,7 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h",
1335..=1367
)]
/// Used in [`crate::other::GetPeerListResponse`].
Peer {
id: u64,
host: String,
ip: u32,
port: u16,
#[cfg_attr(feature = "serde", serde(default = "default_zero"))]
rpc_port: u16 = default_zero::<u16>(),
#[cfg_attr(feature = "serde", serde(default = "default_zero"))]
rpc_credits_per_hash: u32 = default_zero::<u32>(),
last_seen: u64,
#[cfg_attr(feature = "serde", serde(default = "default_zero"))]
pruning_seed: u32 = default_zero::<u32>(),
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1398..=1417
)]
///
/// Used in:
/// - [`crate::other::GetPeerListResponse`]
/// - [`crate::other::GetPublicNodesResponse`]
PublicNode {
host: String,
last_seen: u64,
rpc_port: u16,
rpc_credits_per_hash: u32,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
1519..=1556 1519..=1556
)] )]
@ -414,17 +280,17 @@ define_struct_and_impl_epee! {
do_not_relay: bool, do_not_relay: bool,
double_spend_seen: bool, double_spend_seen: bool,
fee: u64, fee: u64,
id_hash: String, id_hash: Hex<32>,
kept_by_block: bool, kept_by_block: bool,
last_failed_height: u64, last_failed_height: u64,
last_failed_id_hash: String, last_failed_id_hash: Hex<32>,
last_relayed_time: u64, last_relayed_time: u64,
max_used_block_height: u64, max_used_block_height: u64,
max_used_block_id_hash: String, max_used_block_id_hash: Hex<32>,
receive_time: u64, receive_time: u64,
relayed: bool, relayed: bool,
tx_blob: String, tx_blob: String,
tx_json: String, // TODO: this should be another struct tx_json: cuprate_types::json::tx::Transaction,
#[cfg_attr(feature = "serde", serde(default = "default_zero"))] #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
weight: u64 = default_zero::<u64>(), weight: u64 = default_zero::<u64>(),
} }
@ -432,68 +298,26 @@ define_struct_and_impl_epee! {
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
1558..=1567 1558..=1567
)] )]
/// Used in [`crate::other::GetTransactionPoolResponse`]. /// Used in [`crate::other::GetTransactionPoolResponse`].
SpentKeyImageInfo { SpentKeyImageInfo {
id_hash: String, id_hash: Hex<32>,
txs_hashes: Vec<String>, txs_hashes: Vec<String>, // TODO: Vec<Hex<32>> when it has epee
} }
} }
define_struct_and_impl_epee! { define_struct_and_impl_epee! {
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454, "cc73fe71162d564ffda8e549b79a350bca53c454",
"rpc/core_rpc_server_commands_defs.h", "rpc/core_rpc_server_commands_defs.h",
1666..=1675 1070..=1079
)] )]
#[derive(Copy)] AuxPow {
/// Used in [`crate::other::GetTransactionPoolStatsResponse`]. id: Hex<32>,
TxpoolHisto { hash: Hex<32>,
txs: u32,
bytes: u64,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1677..=1710
)]
/// Used in [`crate::other::GetTransactionPoolStatsResponse`].
TxpoolStats {
bytes_max: u32,
bytes_med: u32,
bytes_min: u32,
bytes_total: u64,
fee_total: u64,
histo_98pc: u64,
histo: Vec<TxpoolHisto>,
num_10m: u32,
num_double_spends: u32,
num_failing: u32,
num_not_relayed: u32,
oldest: u64,
txs_total: u32,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
582..=597
)]
/// Used in [`crate::other::GetOutsResponse`].
OutKey {
key: String,
mask: String,
unlocked: bool,
height: u64,
txid: String,
} }
} }

View file

@ -6,13 +6,12 @@
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use cuprate_types::rpc::{OutKey, Peer, PublicNode, TxpoolStats};
use crate::{ use crate::{
base::{AccessResponseBase, ResponseBase}, base::{AccessResponseBase, ResponseBase},
macros::define_request_and_response, macros::define_request_and_response,
misc::{ misc::{GetOutputsOut, SpentKeyImageInfo, Status, TxEntry, TxInfo},
GetOutputsOut, OutKey, Peer, PublicNode, SpentKeyImageInfo, Status, TxEntry, TxInfo,
TxpoolStats,
},
RpcCallValue, RpcCallValue,
}; };

View file

@ -20,7 +20,7 @@ serde = ["dep:serde", "cuprate-database/serde", "cuprate-database-service/
[dependencies] [dependencies]
cuprate-database = { workspace = true, features = ["heed"] } cuprate-database = { workspace = true, features = ["heed"] }
cuprate-database-service = { workspace = true } cuprate-database-service = { workspace = true }
cuprate-types = { workspace = true } cuprate-types = { workspace = true, features = ["rpc"] }
cuprate-helper = { workspace = true, default-features = false, features = ["constants"] } cuprate-helper = { workspace = true, default-features = false, features = ["constants"] }
monero-serai = { workspace = true, features = ["std"] } monero-serai = { workspace = true, features = ["std"] }

View file

@ -7,7 +7,7 @@ use std::{
sync::Arc, sync::Arc,
}; };
use cuprate_types::{PoolInfo, TransactionVerificationData}; use cuprate_types::{rpc::PoolInfo, TransactionVerificationData};
use crate::{ use crate::{
tx::TxEntry, tx::TxEntry,

View file

@ -9,15 +9,16 @@ repository = "https://github.com/Cuprate/cuprate/tree/main/types"
keywords = ["cuprate", "types"] keywords = ["cuprate", "types"]
[features] [features]
default = ["blockchain", "epee", "serde", "json", "hex"] default = ["blockchain", "epee", "serde", "json", "hex", "rpc"]
blockchain = [] blockchain = ["rpc"]
epee = ["dep:cuprate-epee-encoding"] epee = ["dep:cuprate-epee-encoding"]
serde = ["dep:serde", "hex"] serde = ["dep:serde", "hex"]
proptest = ["dep:proptest", "dep:proptest-derive"] proptest = ["dep:proptest", "dep:proptest-derive"]
json = ["hex", "dep:cuprate-helper"] json = ["hex", "dep:cuprate-helper"]
# We sadly have no choice but to enable serde here as otherwise we will get warnings from the `hex` dep being unused. # We sadly have no choice but to enable serde here as otherwise we will get warnings from the `hex` dep being unused.
# This isn't too bad as `HexBytes` only makes sense with serde anyway. # This isn't too bad as `Hex` only makes sense with serde anyway.
hex = ["serde", "dep:hex"] hex = ["serde", "dep:hex"]
rpc = ["hex"]
[dependencies] [dependencies]
cuprate-epee-encoding = { workspace = true, optional = true, features = ["std"] } cuprate-epee-encoding = { workspace = true, optional = true, features = ["std"] }
@ -25,6 +26,7 @@ cuprate-helper = { workspace = true, optional = true, features = ["cast"]
cuprate-fixed-bytes = { workspace = true, features = ["std", "serde"] } cuprate-fixed-bytes = { workspace = true, features = ["std", "serde"] }
bytes = { workspace = true } bytes = { workspace = true }
cfg-if = { workspace = true }
curve25519-dalek = { workspace = true } curve25519-dalek = { workspace = true }
monero-serai = { workspace = true } monero-serai = { workspace = true }
hex = { workspace = true, features = ["serde", "alloc"], optional = true } hex = { workspace = true, features = ["serde", "alloc"], optional = true }

View file

@ -7,6 +7,13 @@ use strum::{
use monero_serai::block::BlockHeader; use monero_serai::block::BlockHeader;
#[cfg(feature = "epee")]
use cuprate_epee_encoding::{
error,
macros::bytes::{Buf, BufMut},
EpeeValue, Marker,
};
/// Target block time for hf 1. /// Target block time for hf 1.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/difficulty.html#target-seconds> /// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/difficulty.html#target-seconds>
@ -51,6 +58,7 @@ pub enum HardForkError {
VariantArray, VariantArray,
)] )]
#[cfg_attr(any(feature = "proptest"), derive(proptest_derive::Arbitrary))] #[cfg_attr(any(feature = "proptest"), derive(proptest_derive::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)] #[repr(u8)]
pub enum HardFork { pub enum HardFork {
#[default] #[default]
@ -194,3 +202,19 @@ impl HardFork {
matches!(self, Self::LATEST) matches!(self, Self::LATEST)
} }
} }
#[cfg(feature = "epee")]
impl EpeeValue for HardFork {
const MARKER: Marker = u8::MARKER;
fn read<B: Buf>(r: &mut B, marker: &Marker) -> error::Result<Self> {
let u = u8::read(r, marker)?;
Self::from_repr(u).ok_or(error::Error::Format("unknown hardfork"))
}
fn write<B: BufMut>(self, w: &mut B) -> error::Result<()> {
let u = self.as_u8();
u8::write(u, w)?;
Ok(())
}
}

View file

@ -18,12 +18,12 @@ use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize))] #[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))] #[cfg_attr(feature = "serde", serde(transparent))]
#[repr(transparent)] #[repr(transparent)]
pub struct HexBytes<const N: usize>( pub struct Hex<const N: usize>(
#[cfg_attr(feature = "serde", serde(with = "hex::serde"))] pub [u8; N], #[cfg_attr(feature = "serde", serde(with = "hex::serde"))] pub [u8; N],
); );
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
impl<'de, const N: usize> Deserialize<'de> for HexBytes<N> impl<'de, const N: usize> Deserialize<'de> for Hex<N>
where where
[u8; N]: hex::FromHex, [u8; N]: hex::FromHex,
<[u8; N] as hex::FromHex>::Error: std::fmt::Display, <[u8; N] as hex::FromHex>::Error: std::fmt::Display,
@ -37,7 +37,7 @@ where
} }
#[cfg(feature = "epee")] #[cfg(feature = "epee")]
impl<const N: usize> EpeeValue for HexBytes<N> { impl<const N: usize> EpeeValue for Hex<N> {
const MARKER: Marker = <[u8; N] as EpeeValue>::MARKER; const MARKER: Marker = <[u8; N] as EpeeValue>::MARKER;
fn read<B: bytes::Buf>(r: &mut B, marker: &Marker) -> error::Result<Self> { fn read<B: bytes::Buf>(r: &mut B, marker: &Marker) -> error::Result<Self> {
@ -50,7 +50,7 @@ impl<const N: usize> EpeeValue for HexBytes<N> {
} }
// Default is not implemented for arrays >32, so we must do it manually. // Default is not implemented for arrays >32, so we must do it manually.
impl<const N: usize> Default for HexBytes<N> { impl<const N: usize> Default for Hex<N> {
fn default() -> Self { fn default() -> Self {
Self([0; N]) Self([0; N])
} }
@ -63,13 +63,13 @@ mod test {
#[test] #[test]
fn hex_bytes_32() { fn hex_bytes_32() {
let hash = [1; 32]; let hash = [1; 32];
let hex_bytes = HexBytes::<32>(hash); let hex_bytes = Hex::<32>(hash);
let expected_json = r#""0101010101010101010101010101010101010101010101010101010101010101""#; let expected_json = r#""0101010101010101010101010101010101010101010101010101010101010101""#;
let to_string = serde_json::to_string(&hex_bytes).unwrap(); let to_string = serde_json::to_string(&hex_bytes).unwrap();
assert_eq!(to_string, expected_json); assert_eq!(to_string, expected_json);
let from_str = serde_json::from_str::<HexBytes<32>>(expected_json).unwrap(); let from_str = serde_json::from_str::<Hex<32>>(expected_json).unwrap();
assert_eq!(hex_bytes, from_str); assert_eq!(hex_bytes, from_str);
} }
} }

View file

@ -8,7 +8,7 @@ use monero_serai::{block, transaction};
use cuprate_helper::cast::usize_to_u64; use cuprate_helper::cast::usize_to_u64;
use crate::{ use crate::{
hex::HexBytes, hex::Hex,
json::output::{Output, TaggedKey, Target}, json::output::{Output, TaggedKey, Target},
}; };
@ -22,10 +22,10 @@ pub struct Block {
pub major_version: u8, pub major_version: u8,
pub minor_version: u8, pub minor_version: u8,
pub timestamp: u64, pub timestamp: u64,
pub prev_id: HexBytes<32>, pub prev_id: Hex<32>,
pub nonce: u32, pub nonce: u32,
pub miner_tx: MinerTransaction, pub miner_tx: MinerTransaction,
pub tx_hashes: Vec<HexBytes<32>>, pub tx_hashes: Vec<Hex<32>>,
} }
impl From<block::Block> for Block { impl From<block::Block> for Block {
@ -34,13 +34,13 @@ impl From<block::Block> for Block {
unreachable!("input is a miner tx, this should never fail"); unreachable!("input is a miner tx, this should never fail");
}; };
let tx_hashes = b.transactions.into_iter().map(HexBytes::<32>).collect(); let tx_hashes = b.transactions.into_iter().map(Hex::<32>).collect();
Self { Self {
major_version: b.header.hardfork_version, major_version: b.header.hardfork_version,
minor_version: b.header.hardfork_signal, minor_version: b.header.hardfork_signal,
timestamp: b.header.timestamp, timestamp: b.header.timestamp,
prev_id: HexBytes::<32>(b.header.previous), prev_id: Hex::<32>(b.header.previous),
nonce: b.header.nonce, nonce: b.header.nonce,
miner_tx, miner_tx,
tx_hashes, tx_hashes,
@ -101,14 +101,14 @@ impl TryFrom<transaction::Transaction> for MinerTransaction {
let target = match o.view_tag { let target = match o.view_tag {
Some(view_tag) => { Some(view_tag) => {
let tagged_key = TaggedKey { let tagged_key = TaggedKey {
key: HexBytes::<32>(o.key.0), key: Hex::<32>(o.key.0),
view_tag: HexBytes::<1>([view_tag]), view_tag: Hex::<1>([view_tag]),
}; };
Target::TaggedKey { tagged_key } Target::TaggedKey { tagged_key }
} }
None => Target::Key { None => Target::Key {
key: HexBytes::<32>(o.key.0), key: Hex::<32>(o.key.0),
}, },
}; };
@ -222,7 +222,7 @@ mod test {
major_version: 1, major_version: 1,
minor_version: 0, minor_version: 0,
timestamp: 1415690591, timestamp: 1415690591,
prev_id: HexBytes::<32>(hex!( prev_id: Hex::<32>(hex!(
"e97a0ab6307de9b9f9a9872263ef3e957976fb227eb9422c6854e989e5d5d34c" "e97a0ab6307de9b9f9a9872263ef3e957976fb227eb9422c6854e989e5d5d34c"
)), )),
nonce: 2147484616, nonce: 2147484616,
@ -237,25 +237,25 @@ mod test {
Output { Output {
amount: 47019296802, amount: 47019296802,
target: Target::Key { target: Target::Key {
key: HexBytes::<32>(hex!("3c1dcbf5b485987ecef4596bb700e32cbc7bd05964e3888ffc05f8a46bf5fc33")), key: Hex::<32>(hex!("3c1dcbf5b485987ecef4596bb700e32cbc7bd05964e3888ffc05f8a46bf5fc33")),
} }
}, },
Output { Output {
amount: 200000000000, amount: 200000000000,
target: Target::Key { target: Target::Key {
key: HexBytes::<32>(hex!("5810afc7a1b01a1c913eb6aab15d4a851cbc4a8cf0adf90bb80ac1a7ca9928aa")), key: Hex::<32>(hex!("5810afc7a1b01a1c913eb6aab15d4a851cbc4a8cf0adf90bb80ac1a7ca9928aa")),
} }
}, },
Output { Output {
amount: 3000000000000, amount: 3000000000000,
target: Target::Key { target: Target::Key {
key: HexBytes::<32>(hex!("520f49c5f2ce8456dc1a565f35ed3a5ccfff3a1210b340870a57d2749a81a2df")), key: Hex::<32>(hex!("520f49c5f2ce8456dc1a565f35ed3a5ccfff3a1210b340870a57d2749a81a2df")),
} }
}, },
Output { Output {
amount: 10000000000000, amount: 10000000000000,
target: Target::Key { target: Target::Key {
key: HexBytes::<32>(hex!("44d7705e62c76c2e349a474df6724aa1d9932092002b03a94f9c19d9d12b9427")), key: Hex::<32>(hex!("44d7705e62c76c2e349a474df6724aa1d9932092002b03a94f9c19d9d12b9427")),
} }
} }
], ],
@ -281,7 +281,7 @@ mod test {
major_version: 16, major_version: 16,
minor_version: 16, minor_version: 16,
timestamp: 1727293028, timestamp: 1727293028,
prev_id: HexBytes::<32>(hex!( prev_id: Hex::<32>(hex!(
"41b56c273d69def3294e56179de71c61808042d54c1e085078d21dbe99e81b6f" "41b56c273d69def3294e56179de71c61808042d54c1e085078d21dbe99e81b6f"
)), )),
nonce: 311, nonce: 311,
@ -296,10 +296,10 @@ mod test {
amount: 601012280000, amount: 601012280000,
target: Target::TaggedKey { target: Target::TaggedKey {
tagged_key: TaggedKey { tagged_key: TaggedKey {
key: HexBytes::<32>(hex!( key: Hex::<32>(hex!(
"8c0b16c6df02b9944b49f375d96a958a0fc5431c048879bb5bf25f64a1163b9e" "8c0b16c6df02b9944b49f375d96a958a0fc5431c048879bb5bf25f64a1163b9e"
)), )),
view_tag: HexBytes::<1>(hex!("88")), view_tag: Hex::<1>(hex!("88")),
}, },
}, },
}], }],
@ -312,43 +312,43 @@ mod test {
rct_signatures: MinerTransactionRctSignatures { r#type: 0 }, rct_signatures: MinerTransactionRctSignatures { r#type: 0 },
}, },
tx_hashes: vec![ tx_hashes: vec![
HexBytes::<32>(hex!( Hex::<32>(hex!(
"eab76986a0cbcae690d8499f0f616f783fd2c89c6f611417f18011950dbdab2e" "eab76986a0cbcae690d8499f0f616f783fd2c89c6f611417f18011950dbdab2e"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"57b19aa8c2cdbb6836cf13dd1e321a67860965c12e4418f3c30f58c8899a851e" "57b19aa8c2cdbb6836cf13dd1e321a67860965c12e4418f3c30f58c8899a851e"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"5340185432ab6b74fb21379f7e8d8f0e37f0882b2a7121fd7c08736f079e2edc" "5340185432ab6b74fb21379f7e8d8f0e37f0882b2a7121fd7c08736f079e2edc"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"01dc6d31db56d68116f5294c1b4f80b33b048b5cdfefcd904f23e6c0de3daff5" "01dc6d31db56d68116f5294c1b4f80b33b048b5cdfefcd904f23e6c0de3daff5"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"c9fb6a2730678203948fef2a49fa155b63f35a3649f3d32ed405a6806f3bbd56" "c9fb6a2730678203948fef2a49fa155b63f35a3649f3d32ed405a6806f3bbd56"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"af965cdd2a2315baf1d4a3d242f44fe07b1fd606d5f4853c9ff546ca6c12a5af" "af965cdd2a2315baf1d4a3d242f44fe07b1fd606d5f4853c9ff546ca6c12a5af"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"97bc9e047d25fae8c14ce6ec882224e7b722f5e79b62a2602a6bacebdac8547b" "97bc9e047d25fae8c14ce6ec882224e7b722f5e79b62a2602a6bacebdac8547b"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"28c46992eaf10dc0cceb313c30572d023432b7bd26e85e679bc8fe419533a7bf" "28c46992eaf10dc0cceb313c30572d023432b7bd26e85e679bc8fe419533a7bf"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"c32e3acde2ff2885c9cc87253b40d6827d167dfcc3022c72f27084fd98788062" "c32e3acde2ff2885c9cc87253b40d6827d167dfcc3022c72f27084fd98788062"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"19e66a47f075c7cccde8a7b52803119e089e33e3a4847cace0bd1d17b0d22bab" "19e66a47f075c7cccde8a7b52803119e089e33e3a4847cace0bd1d17b0d22bab"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"8e8ac560e77a1ee72e82a5eb6887adbe5979a10cd29cb2c2a3720ce87db43a70" "8e8ac560e77a1ee72e82a5eb6887adbe5979a10cd29cb2c2a3720ce87db43a70"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"b7ff5141524b5cca24de6780a5dbfdf71e7de1e062fd85f557fb3b43b8e285dc" "b7ff5141524b5cca24de6780a5dbfdf71e7de1e062fd85f557fb3b43b8e285dc"
)), )),
HexBytes::<32>(hex!( Hex::<32>(hex!(
"f09df0f113763ef9b9a2752ac293b478102f7cab03ef803a3d9db7585aea8912" "f09df0f113763ef9b9a2752ac293b478102f7cab03ef803a3d9db7585aea8912"
)), )),
], ],

View file

@ -7,10 +7,10 @@
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::hex::HexBytes; use crate::hex::Hex;
/// JSON representation of an output. /// JSON representation of an output.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Output { pub struct Output {
pub amount: u64, pub amount: u64,
@ -22,7 +22,7 @@ pub struct Output {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))] #[cfg_attr(feature = "serde", serde(untagged))]
pub enum Target { pub enum Target {
Key { key: HexBytes<32> }, Key { key: Hex<32> },
TaggedKey { tagged_key: TaggedKey }, TaggedKey { tagged_key: TaggedKey },
} }
@ -38,6 +38,6 @@ impl Default for Target {
#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TaggedKey { pub struct TaggedKey {
pub key: HexBytes<32>, pub key: Hex<32>,
pub view_tag: HexBytes<1>, pub view_tag: Hex<1>,
} }

File diff suppressed because it is too large Load diff

View file

@ -13,19 +13,13 @@ mod address_type;
mod block_complete_entry; mod block_complete_entry;
mod connection_state; mod connection_state;
mod hard_fork; mod hard_fork;
mod pool_info;
mod pool_info_extent;
mod transaction_verification_data; mod transaction_verification_data;
mod types; mod types;
pub mod rpc;
pub use address_type::AddressType; pub use address_type::AddressType;
pub use block_complete_entry::{BlockCompleteEntry, PrunedTxBlobEntry, TransactionBlobs}; pub use block_complete_entry::{BlockCompleteEntry, PrunedTxBlobEntry, TransactionBlobs};
pub use connection_state::ConnectionState; pub use connection_state::ConnectionState;
pub use hard_fork::{HardFork, HardForkError}; pub use hard_fork::{HardFork, HardForkError};
pub use pool_info::PoolInfo;
pub use pool_info_extent::PoolInfoExtent;
pub use transaction_verification_data::{ pub use transaction_verification_data::{
CachedVerificationState, TransactionVerificationData, TxVersion, CachedVerificationState, TransactionVerificationData, TxVersion,
}; };
@ -44,4 +38,10 @@ pub mod json;
#[cfg(feature = "hex")] #[cfg(feature = "hex")]
pub mod hex; pub mod hex;
cfg_if::cfg_if! {
if #[cfg(feature = "rpc")] {
pub mod rpc;
}
}
//---------------------------------------------------------------------------------------------------- Private //---------------------------------------------------------------------------------------------------- Private

24
types/src/rpc/mod.rs Normal file
View file

@ -0,0 +1,24 @@
//! Various types (in)directly used in RPC.
//!
//! These types map very closely to types within `cuprate-rpc-types`,
//! however they use more canonical types when appropriate, for example,
//! instead of `hash: String`, this module's types would use something like
//! `hash: [u8; 32]`.
//!
//! - TODO: finish making fields canonical after <https://github.com/Cuprate/cuprate/pull/355>
//! - TODO: can epee handle `u128`? there are a lot of `(top_64 | low_64)` fields
mod pool_info;
mod pool_info_extent;
mod types;
pub use pool_info::PoolInfo;
pub use pool_info_extent::PoolInfoExtent;
pub use types::{
AddAuxPow, AuxPow, BlockHeader, BlockOutputIndices, ChainInfo, CoinbaseTxSum, ConnectionInfo,
FeeEstimate, GetBan, GetMinerDataTxBacklogEntry, GetOutputsOut, HardForkInfo, HardforkEntry,
HistogramEntry, MinerData, MinerDataTxBacklogEntry, OutKey, OutKeyBin, OutputDistributionData,
OutputHistogramEntry, OutputHistogramInput, Peer, PoolInfoFull, PoolInfoIncremental,
PoolTxInfo, PublicNode, SetBan, Span, SpentKeyImageInfo, SyncInfoPeer, TxBacklogEntry, TxInfo,
TxOutputIndices, TxpoolHisto, TxpoolStats,
};

View file

@ -2,7 +2,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(feature = "epee")] #[cfg(feature = "epee")]
use crate::pool_info_extent::PoolInfoExtent; use crate::rpc::PoolInfoExtent;
#[cfg(feature = "epee")] #[cfg(feature = "epee")]
use cuprate_epee_encoding::{ use cuprate_epee_encoding::{
error, error,

View file

@ -1,16 +1,8 @@
//! Various types (in)directly used in RPC. //! Various types (in)directly used in RPC.
//!
//! These types map very closely to types within `cuprate-rpc-types`,
//! however they use more canonical types when appropriate, for example,
//! instead of `hash: String`, this module's types would use something like
//! `hash: [u8; 32]`.
//!
//! - TODO: finish making fields canonical after <https://github.com/Cuprate/cuprate/pull/355>
//! - TODO: can epee handle `u128`? there are a lot of `(top_64 | low_64)` fields
use cuprate_fixed_bytes::ByteArrayVec; use cuprate_fixed_bytes::ByteArrayVec;
use crate::{AddressType, ConnectionState}; use crate::{hex::Hex, AddressType, ConnectionState, HardFork};
const fn default_string() -> String { const fn default_string() -> String {
String::new() String::new()
@ -96,28 +88,25 @@ define_struct_and_impl_epee! {
1163..=1212 1163..=1212
)] )]
BlockHeader { BlockHeader {
block_size: u64,
block_weight: u64, block_weight: u64,
cumulative_difficulty_top64: u64, cumulative_difficulty_top64: u64,
cumulative_difficulty: u64, cumulative_difficulty: u64,
depth: u64, depth: u64,
difficulty_top64: u64, difficulty_top64: u64,
difficulty: u64, difficulty: u64,
hash: String, hash: [u8; 32],
height: u64, height: u64,
long_term_weight: u64, long_term_weight: u64,
major_version: u8, major_version: HardFork,
miner_tx_hash: String, miner_tx_hash: [u8; 32],
minor_version: u8, minor_version: u8,
nonce: u32, nonce: u32,
num_txes: u64, num_txes: u64,
orphan_status: bool, orphan_status: bool,
pow_hash: String, pow_hash: [u8; 32],
prev_hash: String, prev_hash: [u8; 32],
reward: u64, reward: u64,
timestamp: u64, timestamp: u64,
wide_cumulative_difficulty: String,
wide_difficulty: String,
} }
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
@ -202,7 +191,7 @@ define_struct_and_impl_epee! {
#[derive(Copy)] #[derive(Copy)]
HardforkEntry { HardforkEntry {
height: u64, height: u64,
hf_version: u8, hf_version: HardFork,
} }
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
@ -214,7 +203,7 @@ define_struct_and_impl_epee! {
block_hash: [u8; 32], block_hash: [u8; 32],
block_hashes: Vec<[u8; 32]>, block_hashes: Vec<[u8; 32]>,
difficulty_top64: u64, difficulty_top64: u64,
difficulty_low64: u64, difficulty: u64,
height: u64, height: u64,
length: u64, length: u64,
main_chain_parent_block: [u8; 32], main_chain_parent_block: [u8; 32],
@ -371,17 +360,17 @@ define_struct_and_impl_epee! {
do_not_relay: bool, do_not_relay: bool,
double_spend_seen: bool, double_spend_seen: bool,
fee: u64, fee: u64,
id_hash: String, id_hash: [u8; 32],
kept_by_block: bool, kept_by_block: bool,
last_failed_height: u64, last_failed_height: u64,
last_failed_id_hash: String, last_failed_id_hash: [u8; 32],
last_relayed_time: u64, last_relayed_time: u64,
max_used_block_height: u64, max_used_block_height: u64,
max_used_block_id_hash: String, max_used_block_id_hash: [u8; 32],
receive_time: u64, receive_time: u64,
relayed: bool, relayed: bool,
tx_blob: String, tx_blob: Vec<u8>,
tx_json: String, // TODO: this should be another struct tx_json: crate::json::tx::Transaction,
#[cfg_attr(feature = "serde", serde(default = "default_zero"))] #[cfg_attr(feature = "serde", serde(default = "default_zero"))]
weight: u64 = default_zero::<u64>(), weight: u64 = default_zero::<u64>(),
} }
@ -434,11 +423,11 @@ define_struct_and_impl_epee! {
582..=597 582..=597
)] )]
OutKey { OutKey {
key: String, key: Hex<32>,
mask: String, mask: Hex<32>,
unlocked: bool, unlocked: bool,
height: u64, height: u64,
txid: String, txid: Hex<32>,
} }
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
@ -473,9 +462,9 @@ define_struct_and_impl_epee! {
)] )]
CoinbaseTxSum { CoinbaseTxSum {
emission_amount_top64: u64, emission_amount_top64: u64,
emission_amount_low64: u64, emission_amount: u64,
fee_amount_top64: u64, fee_amount_top64: u64,
fee_amount_low64: u64, fee_amount: u64,
} }
#[doc = monero_definition_link!( #[doc = monero_definition_link!(
@ -489,7 +478,7 @@ define_struct_and_impl_epee! {
prev_id: [u8; 32], prev_id: [u8; 32],
seed_hash: [u8; 32], seed_hash: [u8; 32],
difficulty_top64: u64, difficulty_top64: u64,
difficulty_low64: u64, difficulty: u64,
median_weight: u64, median_weight: u64,
already_generated_coins: u64, already_generated_coins: u64,
tx_backlog: Vec<MinerDataTxBacklogEntry>, tx_backlog: Vec<MinerDataTxBacklogEntry>,

View file

@ -5,9 +5,11 @@
//! * `json-full-chain_main` (`Vec<ChainMain>`) //! * `json-full-chain_main` (`Vec<ChainMain>`)
//! * `json-minimal-chain_main` (`ChainMainMin`) //! * `json-minimal-chain_main` (`ChainMainMin`)
//! * `json-full-miner_data` (`MinerData`) //! * `json-full-miner_data` (`MinerData`)
use cuprate_types::hex::HexBytes;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use cuprate_types::hex::Hex;
/// ZMQ `json-full-txpool_add` packets contain an array of `TxPoolAdd`. /// ZMQ `json-full-txpool_add` packets contain an array of `TxPoolAdd`.
/// ///
/// Each `TxPoolAdd` object represents a new transaction in the mempool that was /// Each `TxPoolAdd` object represents a new transaction in the mempool that was
@ -42,7 +44,7 @@ pub struct TxPoolAdd {
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct TxPoolAddMin { pub struct TxPoolAddMin {
/// transaction ID /// transaction ID
pub id: HexBytes<32>, pub id: Hex<32>,
/// size of the full transaction blob /// size of the full transaction blob
pub blob_size: u64, pub blob_size: u64,
/// metric used to calculate transaction fee /// metric used to calculate transaction fee
@ -63,13 +65,13 @@ pub struct ChainMain {
/// epoch time, decided by the miner, at which the block was mined /// epoch time, decided by the miner, at which the block was mined
pub timestamp: u64, pub timestamp: u64,
/// block id of the previous block /// block id of the previous block
pub prev_id: HexBytes<32>, pub prev_id: Hex<32>,
/// cryptographic random one-time number used in mining a Monero block /// cryptographic random one-time number used in mining a Monero block
pub nonce: u32, pub nonce: u32,
/// coinbase transaction information /// coinbase transaction information
pub miner_tx: MinerTx, pub miner_tx: MinerTx,
/// non-coinbase transaction IDs in the block (can be empty) /// non-coinbase transaction IDs in the block (can be empty)
pub tx_hashes: Vec<HexBytes<32>>, pub tx_hashes: Vec<Hex<32>>,
} }
/// ZMQ `json-minimal-chain_main` subscriber messages contain a single /// ZMQ `json-minimal-chain_main` subscriber messages contain a single
@ -80,10 +82,10 @@ pub struct ChainMainMin {
/// height of the block /// height of the block
pub first_height: u64, pub first_height: u64,
/// block id of the previous block /// block id of the previous block
pub first_prev_id: HexBytes<32>, pub first_prev_id: Hex<32>,
/// block ID of the current block is the 0th entry; additional block IDs /// block ID of the current block is the 0th entry; additional block IDs
/// will only be included if this is the topmost block of a re-org. /// will only be included if this is the topmost block of a re-org.
pub ids: Vec<HexBytes<32>>, pub ids: Vec<Hex<32>>,
} }
/// ZMQ `json-full-miner_data` subscriber messages contain a single /// ZMQ `json-full-miner_data` subscriber messages contain a single
@ -96,9 +98,9 @@ pub struct MinerData {
/// height on which to mine /// height on which to mine
pub height: u64, pub height: u64,
/// block id of the most recent block on which to mine the next block /// block id of the most recent block on which to mine the next block
pub prev_id: HexBytes<32>, pub prev_id: Hex<32>,
/// hash of block to use as seed for Random-X proof-of-work /// hash of block to use as seed for Random-X proof-of-work
pub seed_hash: HexBytes<32>, pub seed_hash: Hex<32>,
/// least-significant 64 bits of the 128-bit network difficulty /// least-significant 64 bits of the 128-bit network difficulty
#[serde(with = "hex_difficulty")] #[serde(with = "hex_difficulty")]
pub difficulty: u64, pub difficulty: u64,
@ -124,7 +126,7 @@ pub struct ToKey {
/// integer offsets for ring members /// integer offsets for ring members
pub key_offsets: Vec<u64>, pub key_offsets: Vec<u64>,
/// key image for the given input /// key image for the given input
pub key_image: HexBytes<32>, pub key_image: Hex<32>,
} }
/// Holds the block height of the coinbase transaction. /// Holds the block height of the coinbase transaction.
@ -156,9 +158,9 @@ pub struct Output {
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
pub struct ToTaggedKey { pub struct ToTaggedKey {
/// public key used to indicate the destination of a transaction output /// public key used to indicate the destination of a transaction output
pub key: HexBytes<32>, pub key: Hex<32>,
/// 1st byte of a shared secret used to reduce wallet synchronization time /// 1st byte of a shared secret used to reduce wallet synchronization time
pub view_tag: HexBytes<1>, pub view_tag: Hex<1>,
} }
/// Ring CT information used inside `TxPoolAdd` /// Ring CT information used inside `TxPoolAdd`
@ -169,7 +171,7 @@ pub struct PoolRingCt {
/// encrypted amount values of the transaction outputs /// encrypted amount values of the transaction outputs
pub encrypted: Vec<Encrypted>, pub encrypted: Vec<Encrypted>,
/// Ring CT commitments, 1 per transaction input /// Ring CT commitments, 1 per transaction input
pub commitments: Vec<HexBytes<32>>, pub commitments: Vec<Hex<32>>,
/// mining fee in piconeros /// mining fee in piconeros
pub fee: u64, pub fee: u64,
/// data to validate the transaction that can be pruned from older blocks /// data to validate the transaction that can be pruned from older blocks
@ -189,9 +191,9 @@ struct MinerRingCt {
pub struct Encrypted { pub struct Encrypted {
/// obsolete field, but present as zeros in JSON; this does not represent /// obsolete field, but present as zeros in JSON; this does not represent
/// the newer deterministically derived mask /// the newer deterministically derived mask
mask: HexBytes<32>, mask: Hex<32>,
/// encrypted amount of the transaction output /// encrypted amount of the transaction output
pub amount: HexBytes<32>, pub amount: Hex<32>,
} }
/// Data needed to validate a transaction that can optionally be pruned from /// Data needed to validate a transaction that can optionally be pruned from
@ -210,22 +212,22 @@ pub struct Prunable {
pub clsags: Vec<Clsag>, pub clsags: Vec<Clsag>,
/// Ring CT pseudo output commitments; 1 per transaction input (*not* /// Ring CT pseudo output commitments; 1 per transaction input (*not*
/// output) /// output)
pub pseudo_outs: Vec<HexBytes<32>>, pub pseudo_outs: Vec<Hex<32>>,
} }
/// Bulletproofs+ data used to validate the legitimacy of a Ring CT transaction. /// Bulletproofs+ data used to validate the legitimacy of a Ring CT transaction.
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[expect(non_snake_case)] #[expect(non_snake_case)]
pub struct BulletproofPlus { pub struct BulletproofPlus {
pub V: Vec<HexBytes<32>>, pub V: Vec<Hex<32>>,
pub A: HexBytes<32>, pub A: Hex<32>,
pub A1: HexBytes<32>, pub A1: Hex<32>,
pub B: HexBytes<32>, pub B: Hex<32>,
pub r1: HexBytes<32>, pub r1: Hex<32>,
pub s1: HexBytes<32>, pub s1: Hex<32>,
pub d1: HexBytes<32>, pub d1: Hex<32>,
pub L: Vec<HexBytes<32>>, pub L: Vec<Hex<32>>,
pub R: Vec<HexBytes<32>>, pub R: Vec<Hex<32>>,
} }
/// Placeholder element type so obsolete fields can be deserialized /// Placeholder element type so obsolete fields can be deserialized
@ -237,9 +239,9 @@ struct Obsolete;
#[expect(non_snake_case)] #[expect(non_snake_case)]
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Clsag { pub struct Clsag {
pub s: Vec<HexBytes<32>>, pub s: Vec<Hex<32>>,
pub c1: HexBytes<32>, pub c1: Hex<32>,
pub D: HexBytes<32>, pub D: Hex<32>,
} }
/// Part of the new block information in `ChainMain` /// Part of the new block information in `ChainMain`
@ -269,7 +271,7 @@ pub struct MinerTx {
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct TxBacklog { pub struct TxBacklog {
/// transaction ID /// transaction ID
pub id: HexBytes<32>, pub id: Hex<32>,
/// metric used to calculate transaction fee /// metric used to calculate transaction fee
pub weight: u64, pub weight: u64,
/// mining fee in piconeros /// mining fee in piconeros