Compare commits

...

10 commits

Author SHA1 Message Date
hinto.janai
fd9cde1e51
other: StopDaemon 2024-07-07 20:47:02 -04:00
hinto.janai
06265877cf
other: GetTransactionPoolStats 2024-07-07 20:42:31 -04:00
hinto.janai
416e2c4928
bin: GetTransactionPoolHashes 2024-07-07 20:37:36 -04:00
hinto.janai
5b765ed796
other: SetLogCategories, SetBootstrapDaemon, GetTransactionPool 2024-07-07 20:32:35 -04:00
hinto.janai
e6d5709963
other: StartMining, StopMining, MiningStatus, GetPeerList, SetLogHashRate, SetLogLevel 2024-07-07 20:22:26 -04:00
hinto.janai
d826c4f15b
other: IsKeyImageSpent, SendRawTransaction 2024-07-07 18:24:37 -04:00
hinto.janai
113c27b8d3
other: GetTransactions 2024-07-07 18:06:56 -04:00
hinto.janai
a694ac5667
bin: GetOuts 2024-07-07 16:54:11 -04:00
hinto.janai
e60afa53fb
bin: GetBlocks, GetBlocksByHeight, GetHashes, GetOutputIndexes 2024-07-07 16:44:11 -04:00
hinto.janai
3557ee63bf
add misc module, start bin and other 2024-07-07 16:29:24 -04:00
8 changed files with 941 additions and 62 deletions

View file

@ -10,17 +10,17 @@ This crate ports the types used in Monero's RPC interface, including:
# Modules
This crate's types are split in the following manner:
This crate has 5 modules:
- The root module - miscellaneous items
- [`json`] - JSON types from the `/json_rpc` endpoint
- [`bin`] - Binary types from the binary endpoints
- [`other`] - Misc JSON types from other endpoints
- [`base`] - Base response types
| Module | Purpose |
|--------|---------|
| The root module | Miscellaneous items, e.g. constants.
| [`json`] | Contains JSON request/response (some mixed with binary) that all share the common `/json_rpc` endpoint. |
| [`bin`] | Contains request/response types that are expected to be fully in binary (`cuprate_epee_encoding`) in `monerod` and `cuprated`'s RPC interface. These are called at a custom endpoint instead of `/json_rpc`, e.g. `/get_blocks.bin`. |
| [`other`] | Contains request/response types that are JSON, but aren't called at `/json_rpc` (e.g. [`crate::other::GetHeightRequest`]). |
| [`misc`] | Contains miscellaneous types, e.g. [`crate::misc::Status`]. Many of types here are found and used in request/response types, for example, [`crate::misc::BlockHeader`] is used in [`crate::json::GetLastBlockHeaderResponse`]. |
| [`base`] | Contains base types flattened into many request/response types.
Each type in `{json,bin,other}` come in pairs and have identical names, but are suffixed with either `Request` or `Response`. e.g. [`GetBlockCountRequest`](crate::json::GetBlockCountRequest) & [`GetBlockCountResponse`](crate::json::GetBlockCountResponse).
Miscellaneous types are found in the root module, e.g. [`crate::Status`]. Many of types here are found and used in request/response types, for example, [`crate::BlockHeader`] is used in [`crate::json::GetLastBlockHeaderResponse`].
# Documentation
The documentation for types within `{json,bin,other}` are omitted, as they can be found in [Monero's RPC documentation](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html).
@ -39,15 +39,14 @@ For example:
| Endpoint/method | Crate location and name |
|-----------------|-------------------------|
| [`get_block_count`](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_block_count) | [`json::GetBlockCountRequest`] & [`json::GetBlockCountResponse`]
| [`/get_blocks.bin`](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_blockbin) | `bin::GetBlocksRequest` & `bin::GetBlocksResponse`
| [`/get_blocks.bin`](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_blockbin) | [`bin::GetBlocksRequest`] & [`bin::GetBlocksResponse`]
| [`/get_height`](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_height) | `other::GetHeightRequest` & `other::GetHeightResponse`
TODO: fix doc links when types are ready.
# Mixed types
Note that some types within [`other`] mix JSON & binary together, i.e.,
the message overall is JSON, however some fields contain binary
values inside JSON strings, for example:
Note that some types mix JSON & binary together, i.e., the message overall is JSON,
however some fields contain binary values inside JSON strings, for example:
```json
{

View file

@ -24,7 +24,7 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "epee")]
use cuprate_epee_encoding::epee_object;
use crate::{macros::monero_definition_link, Status};
use crate::{macros::monero_definition_link, misc::Status};
//---------------------------------------------------------------------------------------------------- Requests
/* no types here... yet */

View file

@ -1,8 +1,124 @@
//! Binary types from [binary](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_blocksbin) endpoints.
//!
//! Most (if not all) of these types are defined here:
//! - <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server_commands_defs.h>
//---------------------------------------------------------------------------------------------------- Import
use crate::{
base::{AccessResponseBase, ResponseBase},
defaults::{
default_bool, default_height, default_string, default_u64, default_u8, default_vec,
},
free::{is_one, is_zero},
macros::define_request_and_response,
misc::{
AuxPow, BlockCompleteEntry, BlockHeader, BlockOutputIndices, ChainInfo, ConnectionInfo,
GetBan, GetOutputsOut, HardforkEntry, HistogramEntry, OutKey, OutputDistributionData, Peer,
PoolTxInfo, SetBan, Span, Status, TxBacklogEntry,
},
};
//---------------------------------------------------------------------------------------------------- TODO
define_request_and_response! {
get_blocksbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 162..=262,
GetBlocks,
Request {
#[cfg_attr(feature = "serde", serde(default = "default_u8"))]
requested_info: u8 = default_u8(),
// TODO: This is a `std::list` in `monerod` because...?
block_ids: Vec<[u8; 32]>,
start_height: u64,
prune: bool,
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
no_miner_tx: bool = default_bool(),
#[cfg_attr(feature = "serde", serde(default = "default_u64"))]
pool_info_since: u64 = default_u64(),
},
// TODO: this has custom epee (de)serialization.
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server_commands_defs.h#L242-L259>
ResponseBase {
blocks: Vec<BlockCompleteEntry>,
start_height: u64,
current_height: u64,
output_indices: Vec<BlockOutputIndices>,
daemon_time: u64,
pool_info_extent: u8,
added_pool_txs: Vec<PoolTxInfo>,
remaining_added_pool_txids: Vec<[u8; 32]>,
removed_pool_txids: Vec<[u8; 32]>,
}
}
define_request_and_response! {
get_blocks_by_heightbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 264..=286,
GetBlocksByHeight,
Request {
heights: Vec<u64>,
},
AccessResponseBase {
blocks: Vec<BlockCompleteEntry>,
}
}
define_request_and_response! {
get_hashesbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 309..=338,
GetHashes,
Request {
block_ids: Vec<[u8; 32]>,
start_height: u64,
},
AccessResponseBase {
m_blocks_ids: Vec<[u8; 32]>,
start_height: u64,
current_height: u64,
}
}
define_request_and_response! {
get_o_indexesbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 487..=510,
GetOutputIndexes,
#[derive(Copy)]
Request {
txid: [u8; 32],
},
AccessResponseBase {
o_indexes: Vec<u64>,
}
}
define_request_and_response! {
get_outsbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 512..=565,
GetOuts,
Request {
outputs: Vec<GetOutputsOut>,
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
get_txid: bool = default_bool(),
},
AccessResponseBase {
outs: Vec<OutKey>,
}
}
define_request_and_response! {
get_transaction_pool_hashesbin,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1593..=1613,
GetTransactionPoolHashes,
Request {},
AccessResponseBase {
tx_hashes: Vec<[u8; 32]>,
}
}
//---------------------------------------------------------------------------------------------------- Tests
#[cfg(test)]

View file

@ -11,12 +11,18 @@
use std::borrow::Cow;
//---------------------------------------------------------------------------------------------------- TODO
/// Default [`bool`] type used in request/response types.
/// Default [`bool`] type used in request/response types, `false`.
#[inline]
pub(crate) const fn default_bool() -> bool {
false
}
/// Default [`bool`] type used in _some_ request/response types, `true`.
#[inline]
pub(crate) const fn default_bool_true() -> bool {
true
}
/// Default `Cow<'static, str` type used in request/response types.
#[inline]
pub(crate) const fn default_cow_str() -> Cow<'static, str> {
@ -47,6 +53,24 @@ pub(crate) const fn default_u64() -> u64 {
0
}
/// Default [`u8`] used in request/response types.
#[inline]
pub(crate) const fn default_u32() -> u32 {
0
}
/// Default [`u8`] used in request/response types.
#[inline]
pub(crate) const fn default_u16() -> u16 {
0
}
/// Default [`u8`] used in request/response types.
#[inline]
pub(crate) const fn default_u8() -> u8 {
0
}
//---------------------------------------------------------------------------------------------------- Tests
#[cfg(test)]
mod test {

View file

@ -11,9 +11,8 @@ use crate::{
macros::define_request_and_response,
misc::{
AuxPow, BlockHeader, ChainInfo, ConnectionInfo, GetBan, HardforkEntry, HistogramEntry,
Peer, SetBan, Span, TxBacklogEntry,
OutputDistributionData, SetBan, Span, Status, SyncInfoPeer, TxBacklogEntry,
},
OutputDistributionData, Status,
};
//---------------------------------------------------------------------------------------------------- Struct definitions
@ -532,7 +531,7 @@ define_request_and_response! {
next_needed_pruning_seed: u32,
overview: String,
// TODO: This is a `std::list` in `monerod` because...?
peers: Vec<Peer>,
peers: Vec<SyncInfoPeer>,
// TODO: This is a `std::list` in `monerod` because...?
spans: Vec<Span>,
target_height: u64,
@ -627,6 +626,7 @@ define_request_and_response! {
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 2774..=2796,
FlushCache,
#[derive(Copy)]
Request {
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
bad_txs: bool = default_bool(),

View file

@ -82,7 +82,15 @@
clippy::option_if_let_else,
)]
// Allow some lints when running in debug mode.
#![cfg_attr(debug_assertions, allow(clippy::todo, clippy::multiple_crate_versions))]
#![cfg_attr(
debug_assertions,
allow(
clippy::todo,
clippy::multiple_crate_versions,
unused_imports,
unused_variables
)
)]
// Allow some lints in tests.
#![cfg_attr(
test,
@ -102,7 +110,6 @@ mod constants;
mod defaults;
mod free;
mod macros;
mod status;
pub use binary_string::BinaryString;
pub use constants::{
@ -110,7 +117,6 @@ pub use constants::{
CORE_RPC_STATUS_PAYMENT_REQUIRED, CORE_RPC_STATUS_UNKNOWN, CORE_RPC_VERSION,
CORE_RPC_VERSION_MAJOR, CORE_RPC_VERSION_MINOR,
};
pub use status::Status;
pub mod base;
#[cfg(feature = "bin")]
@ -119,12 +125,7 @@ pub mod bin;
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub mod json;
pub mod misc;
#[cfg(feature = "other")]
#[cfg_attr(docsrs, doc(cfg(feature = "other")))]
pub mod other;
mod misc;
pub use misc::{
AuxPow, BlockHeader, ChainInfo, ConnectionInfo, GetBan, GetMinerDataTxBacklogEntry,
HardforkEntry, HistogramEntry, OutputDistributionData, Peer, SetBan, Span, TxBacklogEntry,
};

View file

@ -3,8 +3,6 @@
//! These are `struct`s that appear in request/response types.
//! For example, [`crate::json::GetConnectionsResponse`] contains
//! the [`crate::misc::ConnectionInfo`] struct defined here.
//!
//! These types are re-exported to the root module.
//---------------------------------------------------------------------------------------------------- Lints
#![allow(
@ -13,13 +11,26 @@
)]
//---------------------------------------------------------------------------------------------------- Import
use std::fmt::Display;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "epee")]
use cuprate_epee_encoding::epee_object;
use cuprate_epee_encoding::{
epee_object,
macros::bytes::{Buf, BufMut},
EpeeValue, Marker,
};
use crate::macros::monero_definition_link;
use crate::{
constants::{
CORE_RPC_STATUS_BUSY, CORE_RPC_STATUS_NOT_MINING, CORE_RPC_STATUS_OK,
CORE_RPC_STATUS_PAYMENT_REQUIRED, CORE_RPC_STATUS_UNKNOWN,
},
defaults::{default_u16, default_u32, default_u64},
macros::monero_definition_link,
};
//---------------------------------------------------------------------------------------------------- Macros
/// This macro (local to this file) defines all the misc types.
@ -40,11 +51,14 @@ macro_rules! define_struct_and_impl_epee {
// And any fields.
$(
$( #[$field_attr:meta] )* // Field attributes
$field_name:ident: $field_type:ty,
// Field name => the type => optional `epee_object` default value.
$field_name:ident: $field_type:ty $(= $field_default:expr)?,
)*
}
) => {
$( #[$struct_attr] )*
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct $struct_name {
$(
$( #[$field_attr] )*
@ -56,7 +70,7 @@ macro_rules! define_struct_and_impl_epee {
epee_object! {
$struct_name,
$(
$field_name: $field_type,
$field_name: $field_type $(= $field_default)?,
)*
}
};
@ -76,8 +90,6 @@ define_struct_and_impl_epee! {
/// - [`crate::json::GetBlockHeaderByHeightResponse`]
/// - [`crate::json::GetBlockHeadersRangeResponse`]
/// - [`crate::json::GetBlockResponse`]
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
BlockHeader {
block_size: u64,
block_weight: u64,
@ -111,8 +123,6 @@ define_struct_and_impl_epee! {
47..=116
)]
/// Used in [`crate::json::GetConnectionsResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
ConnectionInfo {
address: String,
address_type: u8,
@ -150,8 +160,6 @@ define_struct_and_impl_epee! {
2034..=2047
)]
/// Used in [`crate::json::SetBansRequest`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
SetBan {
host: String,
ip: u32,
@ -167,8 +175,6 @@ define_struct_and_impl_epee! {
1999..=2010
)]
/// Used in [`crate::json::GetBansResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
GetBan {
host: String,
ip: u32,
@ -182,9 +188,8 @@ define_struct_and_impl_epee! {
"rpc/core_rpc_server_commands_defs.h",
2139..=2156
)]
#[derive(Copy)]
/// Used in [`crate::json::GetOutputHistogramResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
HistogramEntry {
amount: u64,
total_instances: u64,
@ -199,9 +204,8 @@ define_struct_and_impl_epee! {
"rpc/core_rpc_server_commands_defs.h",
2180..=2191
)]
#[derive(Copy)]
/// Used in [`crate::json::GetVersionResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
HardforkEntry {
height: u64,
hf_version: u8,
@ -215,8 +219,6 @@ define_struct_and_impl_epee! {
2289..=2310
)]
/// Used in [`crate::json::GetAlternateChainsResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
ChainInfo {
block_hash: String,
block_hashes: Vec<String>,
@ -236,9 +238,7 @@ define_struct_and_impl_epee! {
2393..=2400
)]
/// Used in [`crate::json::SyncInfoResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Peer {
SyncInfoPeer {
info: ConnectionInfo,
}
}
@ -250,8 +250,6 @@ define_struct_and_impl_epee! {
2402..=2421
)]
/// Used in [`crate::json::SyncInfoResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Span {
connection_id: String,
nblocks: u64,
@ -269,9 +267,8 @@ define_struct_and_impl_epee! {
"rpc/core_rpc_server_commands_defs.h",
1637..=1642
)]
#[derive(Copy)]
/// Used in [`crate::json::GetTransactionPoolBacklogResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
TxBacklogEntry {
weight: u64,
fee: u64,
@ -286,8 +283,6 @@ define_struct_and_impl_epee! {
45..=50
)]
/// Used in [`crate::json::GetOutputDistributionResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
OutputDistributionData {
distribution: Vec<u64>,
start_height: u64,
@ -304,8 +299,6 @@ define_struct_and_impl_epee! {
/// Used in [`crate::json::GetMinerDataResponse`].
///
/// Note that this is different than [`crate::misc::TxBacklogEntry`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
GetMinerDataTxBacklogEntry {
id: String,
weight: u64,
@ -320,16 +313,512 @@ define_struct_and_impl_epee! {
1070..=1079
)]
/// Used in [`crate::json::AddAuxPowRequest`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
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",
210..=221
)]
/// Used in [`crate::bin::GetBlocksResponse`].
PoolTxInfo {
tx_hash: [u8; 32],
tx_blob: String,
double_spend_seen: bool,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"cryptonote_protocol/cryptonote_protocol_defs.h",
121..=131
)]
/// Used in [`crate::bin::GetBlocksResponse`].
TxBlobEntry {
blob: String,
prunable_hash: [u8; 32],
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
512..=521
)]
#[derive(Copy)]
/// Used in [`crate::bin::GetOutsRequest`].
GetOutputsOut {
amount: u64,
index: u64,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
538..=553
)]
#[derive(Copy)]
/// Used in [`crate::bin::GetOutsRequest`].
OutKey {
key: u8, // TODO: crypto::public_key,
mask: u8, // TODO: rct::key,
unlocked: bool,
height: u64,
txid: [u8; 32],
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
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_u16"))]
rpc_port: u16 = default_u16(),
#[cfg_attr(feature = "serde", serde(default = "default_u32"))]
rpc_credits_per_hash: u32 = default_u32(),
last_seen: u64,
#[cfg_attr(feature = "serde", serde(default = "default_u32"))]
pruning_seed: u32 = default_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`].
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",
1519..=1556
)]
/// Used in [`crate::other::GetTransactionPoolResponse`].
TxInfo {
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_u64"))]
weight: u64 = default_u64(),
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1558..=1567
)]
/// Used in [`crate::other::GetTransactionPoolResponse`].
SpentKeyImageInfo {
id_hash: String,
txs_hashes: Vec<String>,
}
}
define_struct_and_impl_epee! {
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
1666..=1675
)]
#[derive(Copy)]
/// Used in [`crate::other::GetTransactionPoolStatsResponse`].
TxpoolHisto {
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,
}
}
//---------------------------------------------------------------------------------------------------- TODO
// TODO - weird types.
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
210..=221
)]
/// Used in [`crate::bin::GetBlocksResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BlockCompleteEntry {
pub pruned: bool,
pub block: String,
pub block_weight: u64,
pub txs: Vec<TxBlobEntry>,
}
// TODO: custom epee
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/cryptonote_protocol/cryptonote_protocol_defs.h#L138-L163>
#[cfg(feature = "epee")]
epee_object! {
BlockCompleteEntry,
pruned: bool,
block: String,
block_weight: u64,
txs: Vec<TxBlobEntry>,
}
/// Used in [`crate::bin::GetBlocksResponse`].
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum PoolInfoExtent {
None = 0,
Incremental = 1,
Full = 2,
}
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/cryptonote_protocol/cryptonote_protocol_defs.h#L138-L163>
#[cfg(feature = "epee")]
impl EpeeValue for PoolInfoExtent {
const MARKER: Marker = <String as EpeeValue>::MARKER;
fn read<B: Buf>(r: &mut B, marker: &Marker) -> cuprate_epee_encoding::Result<Self> {
todo!()
}
fn should_write(&self) -> bool {
todo!()
}
fn epee_default_value() -> Option<Self> {
todo!()
}
fn write<B: BufMut>(self, w: &mut B) -> cuprate_epee_encoding::Result<()> {
todo!()
}
}
#[doc = monero_definition_link!(
cc73fe71162d564ffda8e549b79a350bca53c454,
"rpc/core_rpc_server_commands_defs.h",
389..=428
)]
/// Used in [`crate::other::GetTransactionsResponse`].
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TxEntry {
pub as_hex: String,
pub as_json: String,
pub block_height: u64,
pub block_timestamp: u64,
pub confirmations: u64,
pub double_spend_seen: bool,
pub in_pool: bool,
pub output_indices: Vec<u64>,
pub prunable_as_hex: String,
pub prunable_hash: String,
pub pruned_as_hex: String,
pub received_timestamp: u64,
pub relayed: bool,
pub tx_hash: String,
}
// TODO: custom epee
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/cryptonote_protocol/cryptonote_protocol_defs.h#L406-427>
#[cfg(feature = "epee")]
epee_object! {
TxEntry,
as_hex: String,
as_json: String, // TODO: should be its own struct
block_height: u64,
block_timestamp: u64,
confirmations: u64,
double_spend_seen: bool,
in_pool: bool,
output_indices: Vec<u64>,
prunable_as_hex: String,
prunable_hash: String,
pruned_as_hex: String,
received_timestamp: u64,
relayed: bool,
tx_hash: String,
}
//---------------------------------------------------------------------------------------------------- TODO
/// Used in [`crate::other::IsKeyImageSpentResponse`].
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum KeyImageSpentStatus {
Unspent = 0,
SpentInBlockchain = 1,
SpentInPool = 2,
}
#[cfg(feature = "epee")]
impl EpeeValue for KeyImageSpentStatus {
const MARKER: Marker = <String as EpeeValue>::MARKER;
fn read<B: Buf>(r: &mut B, marker: &Marker) -> cuprate_epee_encoding::Result<Self> {
todo!()
}
fn should_write(&self) -> bool {
todo!()
}
fn epee_default_value() -> Option<Self> {
todo!()
}
fn write<B: BufMut>(self, w: &mut B) -> cuprate_epee_encoding::Result<()> {
todo!()
}
}
//---------------------------------------------------------------------------------------------------- Status
/// RPC response status.
///
/// This type represents `monerod`'s frequently appearing string field, `status`.
///
/// This field appears within RPC [JSON response](crate::json) types.
///
/// Reference: <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server_commands_defs.h#L78-L81>.
///
/// ## Serialization and string formatting
/// ```rust
/// use cuprate_rpc_types::{
/// misc::Status,
/// CORE_RPC_STATUS_BUSY, CORE_RPC_STATUS_NOT_MINING, CORE_RPC_STATUS_OK,
/// CORE_RPC_STATUS_PAYMENT_REQUIRED, CORE_RPC_STATUS_UNKNOWN
/// };
/// use serde_json::to_string;
///
/// let unknown = Status::Unknown;
///
/// assert_eq!(to_string(&Status::Ok).unwrap(), r#""OK""#);
/// assert_eq!(to_string(&Status::Busy).unwrap(), r#""BUSY""#);
/// assert_eq!(to_string(&Status::NotMining).unwrap(), r#""NOT MINING""#);
/// assert_eq!(to_string(&Status::PaymentRequired).unwrap(), r#""PAYMENT REQUIRED""#);
/// assert_eq!(to_string(&unknown).unwrap(), r#""UNKNOWN""#);
///
/// assert_eq!(Status::Ok.as_ref(), CORE_RPC_STATUS_OK);
/// assert_eq!(Status::Busy.as_ref(), CORE_RPC_STATUS_BUSY);
/// assert_eq!(Status::NotMining.as_ref(), CORE_RPC_STATUS_NOT_MINING);
/// assert_eq!(Status::PaymentRequired.as_ref(), CORE_RPC_STATUS_PAYMENT_REQUIRED);
/// assert_eq!(unknown.as_ref(), CORE_RPC_STATUS_UNKNOWN);
///
/// assert_eq!(format!("{}", Status::Ok), CORE_RPC_STATUS_OK);
/// assert_eq!(format!("{}", Status::Busy), CORE_RPC_STATUS_BUSY);
/// assert_eq!(format!("{}", Status::NotMining), CORE_RPC_STATUS_NOT_MINING);
/// assert_eq!(format!("{}", Status::PaymentRequired), CORE_RPC_STATUS_PAYMENT_REQUIRED);
/// assert_eq!(format!("{}", unknown), CORE_RPC_STATUS_UNKNOWN);
///
/// assert_eq!(format!("{:?}", Status::Ok), "Ok");
/// assert_eq!(format!("{:?}", Status::Busy), "Busy");
/// assert_eq!(format!("{:?}", Status::NotMining), "NotMining");
/// assert_eq!(format!("{:?}", Status::PaymentRequired), "PaymentRequired");
/// assert_eq!(format!("{:?}", unknown), "Unknown");
/// ```
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Status {
// FIXME:
// `#[serde(rename = "")]` only takes raw string literals?
// We have to re-type the constants here...
/// Successful RPC response, everything is OK; [`CORE_RPC_STATUS_OK`].
#[cfg_attr(feature = "serde", serde(rename = "OK"))]
#[default]
Ok,
/// The daemon is busy, try later; [`CORE_RPC_STATUS_BUSY`].
#[cfg_attr(feature = "serde", serde(rename = "BUSY"))]
Busy,
/// The daemon is not mining; [`CORE_RPC_STATUS_NOT_MINING`].
#[cfg_attr(feature = "serde", serde(rename = "NOT MINING"))]
NotMining,
/// Payment is required for RPC; [`CORE_RPC_STATUS_PAYMENT_REQUIRED`].
#[cfg_attr(feature = "serde", serde(rename = "PAYMENT REQUIRED"))]
PaymentRequired,
/// Some unknown other string; [`CORE_RPC_STATUS_UNKNOWN`].
///
/// This exists to act as a catch-all if `monerod` adds
/// a string and a Cuprate node hasn't updated yet.
///
/// The reason this isn't `Unknown(String)` is because that
/// disallows [`Status`] to be [`Copy`], and thus other types
/// that contain it.
#[cfg_attr(feature = "serde", serde(other))]
#[cfg_attr(feature = "serde", serde(rename = "UNKNOWN"))]
Unknown,
}
impl From<String> for Status {
fn from(s: String) -> Self {
match s.as_str() {
CORE_RPC_STATUS_OK => Self::Ok,
CORE_RPC_STATUS_BUSY => Self::Busy,
CORE_RPC_STATUS_NOT_MINING => Self::NotMining,
CORE_RPC_STATUS_PAYMENT_REQUIRED => Self::PaymentRequired,
_ => Self::Unknown,
}
}
}
impl AsRef<str> for Status {
fn as_ref(&self) -> &str {
match self {
Self::Ok => CORE_RPC_STATUS_OK,
Self::Busy => CORE_RPC_STATUS_BUSY,
Self::NotMining => CORE_RPC_STATUS_NOT_MINING,
Self::PaymentRequired => CORE_RPC_STATUS_PAYMENT_REQUIRED,
Self::Unknown => CORE_RPC_STATUS_UNKNOWN,
}
}
}
impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_ref())
}
}
// [`Status`] is essentially a [`String`] when it comes to
// (de)serialization, except when writing we usually have
// access to a `&'static str` and don't need to allocate.
//
// See below for more impl info:
// <https://github.com/Cuprate/cuprate/blob/bef2a2cbd4e1194991751d1fbc96603cba8c7a51/net/epee-encoding/src/value.rs#L366-L392>.
#[cfg(feature = "epee")]
impl EpeeValue for Status {
const MARKER: Marker = <String as EpeeValue>::MARKER;
fn read<B: Buf>(r: &mut B, marker: &Marker) -> cuprate_epee_encoding::Result<Self> {
let string = <String as EpeeValue>::read(r, marker)?;
Ok(Self::from(string))
}
fn should_write(&self) -> bool {
true
}
fn epee_default_value() -> Option<Self> {
// <https://github.com/Cuprate/cuprate/pull/147#discussion_r1654992559>
Some(Self::Unknown)
}
fn write<B: BufMut>(self, w: &mut B) -> cuprate_epee_encoding::Result<()> {
cuprate_epee_encoding::write_bytes(self.as_ref(), w)
}
}
//---------------------------------------------------------------------------------------------------- Tests
#[cfg(test)]
mod test {
// use super::*;
use super::*;
// Test epee (de)serialization works.
#[test]
#[cfg(feature = "epee")]
fn epee() {
for status in [
Status::Ok,
Status::Busy,
Status::NotMining,
Status::PaymentRequired,
Status::Unknown,
] {
let mut buf = vec![];
<Status as EpeeValue>::write(status, &mut buf).unwrap();
let status2 =
<Status as EpeeValue>::read(&mut buf.as_slice(), &<Status as EpeeValue>::MARKER)
.unwrap();
assert_eq!(status, status2);
}
}
}

View file

@ -1,11 +1,155 @@
//! JSON types from the [`other`](https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#other-daemon-rpc-calls) endpoints.
//!
//! <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/daemon_messages.h>.
//! Most (if not all) of these types are defined here:
//! - <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server_commands_defs.h>
//---------------------------------------------------------------------------------------------------- Import
use crate::{base::ResponseBase, macros::define_request_and_response};
use crate::{
base::{AccessResponseBase, ResponseBase},
defaults::{default_bool, default_bool_true, default_string},
macros::define_request_and_response,
misc::{Peer, SpentKeyImageInfo, Status, TxEntry, TxInfo, TxpoolStats},
};
//---------------------------------------------------------------------------------------------------- TODO
define_request_and_response! {
get_height,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 138..=160,
GetHeight,
Request {},
ResponseBase {
hash: String,
height: u64,
}
}
define_request_and_response! {
get_transactions,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 370..=451,
GetTransactions,
Request {
txs_hashes: Vec<String>,
// FIXME: this is documented as optional but it isn't serialized as an optional
// but it is set _somewhere_ to false in `monerod`
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server_commands_defs.h#L382>
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
decode_as_json: bool = default_bool(),
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
prune: bool = default_bool(),
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
split: bool = default_bool(),
},
AccessResponseBase {
txs_as_hex: Vec<String>,
txs_as_json: Vec<String>,
missed_tx: Vec<String>,
txs: Vec<TxEntry>,
}
}
define_request_and_response! {
get_alt_blocks_hashes,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 370..=451,
GetAltBlocksHashes,
Request {},
AccessResponseBase {
blks_hashes: Vec<String>,
}
}
define_request_and_response! {
is_key_image_spent,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 370..=451,
IsKeyImageSpent,
Request {
key_images: Vec<String>,
},
AccessResponseBase {
spent_status: Vec<u8>, // TODO: should be `KeyImageSpentStatus`.
}
}
define_request_and_response! {
send_raw_transaction,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 370..=451,
SendRawTransaction,
Request {
tx_as_hex: String,
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
do_not_relay: bool = default_bool(),
#[cfg_attr(feature = "serde", serde(default = "default_bool_true"))]
do_sanity_checks: bool = default_bool_true(),
},
AccessResponseBase {
double_spend: bool,
fee_too_low: bool,
invalid_input: bool,
invalid_output: bool,
low_mixin: bool,
nonzero_unlock_time: bool,
not_relayed: bool,
overspend: bool,
reason: String,
sanity_check_failed: bool,
too_big: bool,
too_few_outputs: bool,
tx_extra_too_big: bool,
}
}
define_request_and_response! {
start_mining,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 665..=691,
StartMining,
Request {
miner_address: String,
threads_count: u64,
do_background_mining: bool,
ignore_battery: bool,
},
ResponseBase {}
}
define_request_and_response! {
stop_mining,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 825..=843,
StopMining,
Request {},
ResponseBase {}
}
define_request_and_response! {
mining_status,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 846..=895,
MiningStatus,
Request {},
ResponseBase {
active: bool,
address: String,
bg_idle_threshold: u8,
bg_ignore_battery: bool,
bg_min_idle_seconds: u8,
bg_target: u8,
block_reward: u64,
block_target: u32,
difficulty: u64,
difficulty_top64: u64,
is_background_mining_enabled: bool,
pow_algorithm: String,
speed: u64,
threads_count: u32,
wide_difficulty: String,
}
}
define_request_and_response! {
save_bc,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
@ -15,6 +159,112 @@ define_request_and_response! {
ResponseBase {}
}
define_request_and_response! {
get_peer_list,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1369..=1417,
GetPeerList,
Request {
#[cfg_attr(feature = "serde", serde(default = "default_bool_true"))]
public_only: bool = default_bool_true(),
#[cfg_attr(feature = "serde", serde(default = "default_bool"))]
include_blocked: bool = default_bool(),
},
ResponseBase {
white_list: Vec<Peer>,
gray_list: Vec<Peer>,
}
}
define_request_and_response! {
set_log_hash_rate,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1450..=1470,
SetLogHashRate,
#[derive(Copy)]
Request {
visible: bool,
},
ResponseBase {}
}
define_request_and_response! {
set_log_level,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1450..=1470,
SetLogLevel,
#[derive(Copy)]
Request {
level: u8,
},
ResponseBase {}
}
define_request_and_response! {
set_log_categories,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1494..=1517,
SetLogCategories,
Request {
#[cfg_attr(feature = "serde", serde(default = "default_string"))]
categories: String = default_string(),
},
ResponseBase {
categories: String,
}
}
define_request_and_response! {
set_bootstrap_daemon,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1785..=1812,
SetBootstrapDaemon,
Request {
address: String,
username: String,
password: String,
proxy: String,
},
#[derive(Copy)]
Response {
status: Status,
}
}
define_request_and_response! {
get_transaction_pool,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1569..=1591,
GetTransactionPool,
Request {},
AccessResponseBase {
transactions: Vec<TxInfo>,
spent_key_images: Vec<SpentKeyImageInfo>,
}
}
define_request_and_response! {
get_transaction_pool_stats,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1712..=1732,
GetTransactionPoolStats,
Request {},
AccessResponseBase {
pool_stats: TxpoolStats,
}
}
define_request_and_response! {
stop_daemon,
cc73fe71162d564ffda8e549b79a350bca53c454 =>
core_rpc_server_commands_defs.h => 1814..=1831,
StopDaemon,
Request {},
ResponseBase {
status: Status,
}
}
//---------------------------------------------------------------------------------------------------- Tests
#[cfg(test)]
mod test {