mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-08 12:19:24 +00:00
Apply an initial set of rustfmt rules
This commit is contained in:
@@ -9,13 +9,17 @@ use serde_json::json;
|
||||
|
||||
use reqwest;
|
||||
|
||||
use crate::{transaction::{Input, Timelock, Transaction}, block::Block, wallet::Fee};
|
||||
use crate::{
|
||||
transaction::{Input, Timelock, Transaction},
|
||||
block::Block,
|
||||
wallet::Fee,
|
||||
};
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct EmptyResponse {}
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct JsonRpcResponse<T> {
|
||||
result: T
|
||||
result: T,
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
@@ -31,7 +35,7 @@ pub enum RpcError {
|
||||
#[error("pruned transaction")]
|
||||
PrunedTransaction,
|
||||
#[error("invalid transaction ({0:?})")]
|
||||
InvalidTransaction([u8; 32])
|
||||
InvalidTransaction([u8; 32]),
|
||||
}
|
||||
|
||||
fn rpc_hex(value: &str) -> Result<Vec<u8>, RpcError> {
|
||||
@@ -40,8 +44,10 @@ fn rpc_hex(value: &str) -> Result<Vec<u8>, RpcError> {
|
||||
|
||||
fn rpc_point(point: &str) -> Result<EdwardsPoint, RpcError> {
|
||||
CompressedEdwardsY(
|
||||
rpc_hex(point)?.try_into().map_err(|_| RpcError::InvalidPoint(point.to_string()))?
|
||||
).decompress().ok_or(RpcError::InvalidPoint(point.to_string()))
|
||||
rpc_hex(point)?.try_into().map_err(|_| RpcError::InvalidPoint(point.to_string()))?,
|
||||
)
|
||||
.decompress()
|
||||
.ok_or(RpcError::InvalidPoint(point.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -52,10 +58,11 @@ impl Rpc {
|
||||
Rpc(daemon)
|
||||
}
|
||||
|
||||
pub async fn rpc_call<
|
||||
Params: Serialize + Debug,
|
||||
Response: DeserializeOwned + Debug
|
||||
>(&self, method: &str, params: Option<Params>) -> Result<Response, RpcError> {
|
||||
pub async fn rpc_call<Params: Serialize + Debug, Response: DeserializeOwned + Debug>(
|
||||
&self,
|
||||
method: &str,
|
||||
params: Option<Params>,
|
||||
) -> Result<Response, RpcError> {
|
||||
let client = reqwest::Client::new();
|
||||
let mut builder = client.post(&(self.0.clone() + "/" + method));
|
||||
if let Some(params) = params.as_ref() {
|
||||
@@ -65,44 +72,43 @@ impl Rpc {
|
||||
self.call_tail(method, builder).await
|
||||
}
|
||||
|
||||
pub async fn bin_call<
|
||||
Response: DeserializeOwned + Debug
|
||||
>(&self, method: &str, params: Vec<u8>) -> Result<Response, RpcError> {
|
||||
pub async fn bin_call<Response: DeserializeOwned + Debug>(
|
||||
&self,
|
||||
method: &str,
|
||||
params: Vec<u8>,
|
||||
) -> Result<Response, RpcError> {
|
||||
let client = reqwest::Client::new();
|
||||
let builder = client.post(&(self.0.clone() + "/" + method)).body(params);
|
||||
self.call_tail(method, builder.header("Content-Type", "application/octet-stream")).await
|
||||
}
|
||||
|
||||
async fn call_tail<
|
||||
Response: DeserializeOwned + Debug
|
||||
>(&self, method: &str, builder: reqwest::RequestBuilder) -> Result<Response, RpcError> {
|
||||
let res = builder
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| RpcError::ConnectionError)?;
|
||||
async fn call_tail<Response: DeserializeOwned + Debug>(
|
||||
&self,
|
||||
method: &str,
|
||||
builder: reqwest::RequestBuilder,
|
||||
) -> Result<Response, RpcError> {
|
||||
let res = builder.send().await.map_err(|_| RpcError::ConnectionError)?;
|
||||
|
||||
Ok(
|
||||
if !method.ends_with(".bin") {
|
||||
serde_json::from_str(&res.text().await.map_err(|_| RpcError::ConnectionError)?)
|
||||
.map_err(|_| RpcError::InternalError("Failed to parse JSON response".to_string()))?
|
||||
} else {
|
||||
monero_epee_bin_serde::from_bytes(&res.bytes().await.map_err(|_| RpcError::ConnectionError)?)
|
||||
.map_err(|_| RpcError::InternalError("Failed to parse binary response".to_string()))?
|
||||
}
|
||||
)
|
||||
Ok(if !method.ends_with(".bin") {
|
||||
serde_json::from_str(&res.text().await.map_err(|_| RpcError::ConnectionError)?)
|
||||
.map_err(|_| RpcError::InternalError("Failed to parse JSON response".to_string()))?
|
||||
} else {
|
||||
monero_epee_bin_serde::from_bytes(&res.bytes().await.map_err(|_| RpcError::ConnectionError)?)
|
||||
.map_err(|_| RpcError::InternalError("Failed to parse binary response".to_string()))?
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_height(&self) -> Result<usize, RpcError> {
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct HeightResponse {
|
||||
height: usize
|
||||
height: usize,
|
||||
}
|
||||
Ok(self.rpc_call::<Option<()>, HeightResponse>("get_height", None).await?.height)
|
||||
}
|
||||
|
||||
async fn get_transactions_core(
|
||||
&self,
|
||||
hashes: &[[u8; 32]]
|
||||
hashes: &[[u8; 32]],
|
||||
) -> Result<(Vec<Result<Transaction, RpcError>>, Vec<[u8; 32]>), RpcError> {
|
||||
if hashes.len() == 0 {
|
||||
return Ok((vec![], vec![]));
|
||||
@@ -112,39 +118,48 @@ impl Rpc {
|
||||
struct TransactionResponse {
|
||||
tx_hash: String,
|
||||
as_hex: String,
|
||||
pruned_as_hex: String
|
||||
pruned_as_hex: String,
|
||||
}
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct TransactionsResponse {
|
||||
#[serde(default)]
|
||||
missed_tx: Vec<String>,
|
||||
txs: Vec<TransactionResponse>
|
||||
txs: Vec<TransactionResponse>,
|
||||
}
|
||||
|
||||
let txs: TransactionsResponse = self.rpc_call("get_transactions", Some(json!({
|
||||
"txs_hashes": hashes.iter().map(|hash| hex::encode(&hash)).collect::<Vec<_>>()
|
||||
}))).await?;
|
||||
let txs: TransactionsResponse = self
|
||||
.rpc_call(
|
||||
"get_transactions",
|
||||
Some(json!({
|
||||
"txs_hashes": hashes.iter().map(|hash| hex::encode(&hash)).collect::<Vec<_>>()
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok((
|
||||
txs.txs.iter().map(|res| {
|
||||
let tx = Transaction::deserialize(
|
||||
&mut std::io::Cursor::new(
|
||||
rpc_hex(if res.as_hex.len() != 0 { &res.as_hex } else { &res.pruned_as_hex }).unwrap()
|
||||
)
|
||||
).map_err(|_| RpcError::InvalidTransaction(hex::decode(&res.tx_hash).unwrap().try_into().unwrap()))?;
|
||||
txs
|
||||
.txs
|
||||
.iter()
|
||||
.map(|res| {
|
||||
let tx = Transaction::deserialize(&mut std::io::Cursor::new(
|
||||
rpc_hex(if res.as_hex.len() != 0 { &res.as_hex } else { &res.pruned_as_hex }).unwrap(),
|
||||
))
|
||||
.map_err(|_| {
|
||||
RpcError::InvalidTransaction(hex::decode(&res.tx_hash).unwrap().try_into().unwrap())
|
||||
})?;
|
||||
|
||||
// https://github.com/monero-project/monero/issues/8311
|
||||
if res.as_hex.len() == 0 {
|
||||
match tx.prefix.inputs.get(0) {
|
||||
Some(Input::Gen { .. }) => (),
|
||||
_ => Err(RpcError::PrunedTransaction)?
|
||||
// https://github.com/monero-project/monero/issues/8311
|
||||
if res.as_hex.len() == 0 {
|
||||
match tx.prefix.inputs.get(0) {
|
||||
Some(Input::Gen { .. }) => (),
|
||||
_ => Err(RpcError::PrunedTransaction)?,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(tx)
|
||||
}).collect(),
|
||||
|
||||
txs.missed_tx.iter().map(|hash| hex::decode(&hash).unwrap().try_into().unwrap()).collect()
|
||||
Ok(tx)
|
||||
})
|
||||
.collect(),
|
||||
txs.missed_tx.iter().map(|hash| hex::decode(&hash).unwrap().try_into().unwrap()).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -158,7 +173,10 @@ impl Rpc {
|
||||
txs.iter().cloned().collect::<Result<_, _>>()
|
||||
}
|
||||
|
||||
pub async fn get_transactions_possible(&self, hashes: &[[u8; 32]]) -> Result<Vec<Transaction>, RpcError> {
|
||||
pub async fn get_transactions_possible(
|
||||
&self,
|
||||
hashes: &[[u8; 32]],
|
||||
) -> Result<Vec<Transaction>, RpcError> {
|
||||
let (txs, _) = self.get_transactions_core(hashes).await?;
|
||||
Ok(txs.iter().cloned().filter_map(|tx| tx.ok()).collect())
|
||||
}
|
||||
@@ -166,37 +184,39 @@ impl Rpc {
|
||||
pub async fn get_block(&self, height: usize) -> Result<Block, RpcError> {
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct BlockResponse {
|
||||
blob: String
|
||||
blob: String,
|
||||
}
|
||||
|
||||
let block: JsonRpcResponse<BlockResponse> = self.rpc_call("json_rpc", Some(json!({
|
||||
"method": "get_block",
|
||||
"params": {
|
||||
"height": height
|
||||
}
|
||||
}))).await?;
|
||||
let block: JsonRpcResponse<BlockResponse> = self
|
||||
.rpc_call(
|
||||
"json_rpc",
|
||||
Some(json!({
|
||||
"method": "get_block",
|
||||
"params": {
|
||||
"height": height
|
||||
}
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(
|
||||
Block::deserialize(
|
||||
&mut std::io::Cursor::new(rpc_hex(&block.result.blob)?)
|
||||
).expect("Monero returned a block we couldn't deserialize")
|
||||
Block::deserialize(&mut std::io::Cursor::new(rpc_hex(&block.result.blob)?))
|
||||
.expect("Monero returned a block we couldn't deserialize"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn get_block_transactions_core(
|
||||
&self,
|
||||
height: usize,
|
||||
possible: bool
|
||||
possible: bool,
|
||||
) -> Result<Vec<Transaction>, RpcError> {
|
||||
let block = self.get_block(height).await?;
|
||||
let mut res = vec![block.miner_tx];
|
||||
res.extend(
|
||||
if possible {
|
||||
self.get_transactions_possible(&block.txs).await?
|
||||
} else {
|
||||
self.get_transactions(&block.txs).await?
|
||||
}
|
||||
);
|
||||
res.extend(if possible {
|
||||
self.get_transactions_possible(&block.txs).await?
|
||||
} else {
|
||||
self.get_transactions(&block.txs).await?
|
||||
});
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
@@ -204,14 +224,17 @@ impl Rpc {
|
||||
self.get_block_transactions_core(height, false).await
|
||||
}
|
||||
|
||||
pub async fn get_block_transactions_possible(&self, height: usize) -> Result<Vec<Transaction>, RpcError> {
|
||||
pub async fn get_block_transactions_possible(
|
||||
&self,
|
||||
height: usize,
|
||||
) -> Result<Vec<Transaction>, RpcError> {
|
||||
self.get_block_transactions_core(height, true).await
|
||||
}
|
||||
|
||||
pub async fn get_o_indexes(&self, hash: [u8; 32]) -> Result<Vec<u64>, RpcError> {
|
||||
#[derive(Serialize, Debug)]
|
||||
struct Request {
|
||||
txid: [u8; 32]
|
||||
txid: [u8; 32],
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -221,42 +244,52 @@ impl Rpc {
|
||||
status: String,
|
||||
untrusted: bool,
|
||||
credits: usize,
|
||||
top_hash: String
|
||||
top_hash: String,
|
||||
}
|
||||
|
||||
let indexes: OIndexes = self.bin_call("get_o_indexes.bin", monero_epee_bin_serde::to_bytes(
|
||||
&Request {
|
||||
txid: hash
|
||||
}).unwrap()
|
||||
).await?;
|
||||
let indexes: OIndexes = self
|
||||
.bin_call(
|
||||
"get_o_indexes.bin",
|
||||
monero_epee_bin_serde::to_bytes(&Request { txid: hash }).unwrap(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(indexes.o_indexes)
|
||||
}
|
||||
|
||||
// from and to are inclusive
|
||||
pub async fn get_output_distribution(&self, from: usize, to: usize) -> Result<Vec<u64>, RpcError> {
|
||||
pub async fn get_output_distribution(
|
||||
&self,
|
||||
from: usize,
|
||||
to: usize,
|
||||
) -> Result<Vec<u64>, RpcError> {
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct Distribution {
|
||||
distribution: Vec<u64>
|
||||
distribution: Vec<u64>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Distributions {
|
||||
distributions: Vec<Distribution>
|
||||
distributions: Vec<Distribution>,
|
||||
}
|
||||
|
||||
let mut distributions: JsonRpcResponse<Distributions> = self.rpc_call("json_rpc", Some(json!({
|
||||
"method": "get_output_distribution",
|
||||
"params": {
|
||||
"binary": false,
|
||||
"amounts": [0],
|
||||
"cumulative": true,
|
||||
"from_height": from,
|
||||
"to_height": to
|
||||
}
|
||||
}))).await?;
|
||||
let mut distributions: JsonRpcResponse<Distributions> = self
|
||||
.rpc_call(
|
||||
"json_rpc",
|
||||
Some(json!({
|
||||
"method": "get_output_distribution",
|
||||
"params": {
|
||||
"binary": false,
|
||||
"amounts": [0],
|
||||
"cumulative": true,
|
||||
"from_height": from,
|
||||
"to_height": to
|
||||
}
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(distributions.result.distributions.swap_remove(0).distribution)
|
||||
}
|
||||
@@ -264,46 +297,62 @@ impl Rpc {
|
||||
pub async fn get_outputs(
|
||||
&self,
|
||||
indexes: &[u64],
|
||||
height: usize
|
||||
height: usize,
|
||||
) -> Result<Vec<Option<[EdwardsPoint; 2]>>, RpcError> {
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct Out {
|
||||
key: String,
|
||||
mask: String,
|
||||
txid: String
|
||||
txid: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Outs {
|
||||
outs: Vec<Out>
|
||||
outs: Vec<Out>,
|
||||
}
|
||||
|
||||
let outs: Outs = self.rpc_call("get_outs", Some(json!({
|
||||
"get_txid": true,
|
||||
"outputs": indexes.iter().map(|o| json!({
|
||||
"amount": 0,
|
||||
"index": o
|
||||
})).collect::<Vec<_>>()
|
||||
}))).await?;
|
||||
let outs: Outs = self
|
||||
.rpc_call(
|
||||
"get_outs",
|
||||
Some(json!({
|
||||
"get_txid": true,
|
||||
"outputs": indexes.iter().map(|o| json!({
|
||||
"amount": 0,
|
||||
"index": o
|
||||
})).collect::<Vec<_>>()
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let txs = self.get_transactions(
|
||||
&outs.outs.iter().map(|out|
|
||||
rpc_hex(&out.txid).expect("Monero returned an invalidly encoded hash")
|
||||
.try_into().expect("Monero returned an invalid sized hash")
|
||||
).collect::<Vec<_>>()
|
||||
).await?;
|
||||
let txs = self
|
||||
.get_transactions(
|
||||
&outs
|
||||
.outs
|
||||
.iter()
|
||||
.map(|out| {
|
||||
rpc_hex(&out.txid)
|
||||
.expect("Monero returned an invalidly encoded hash")
|
||||
.try_into()
|
||||
.expect("Monero returned an invalid sized hash")
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.await?;
|
||||
// TODO: Support time based lock times. These shouldn't be needed, and it may be painful to
|
||||
// get the median time for the given height, yet we do need to in order to be complete
|
||||
outs.outs.iter().enumerate().map(
|
||||
|(i, out)| Ok(
|
||||
Some([rpc_point(&out.key)?, rpc_point(&out.mask)?]).filter(|_| {
|
||||
outs
|
||||
.outs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, out)| {
|
||||
Ok(Some([rpc_point(&out.key)?, rpc_point(&out.mask)?]).filter(|_| {
|
||||
match txs[i].prefix.timelock {
|
||||
Timelock::Block(t_height) => (t_height <= height),
|
||||
_ => false
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
)
|
||||
).collect()
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn get_fee(&self) -> Result<Fee, RpcError> {
|
||||
@@ -311,12 +360,17 @@ impl Rpc {
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct FeeResponse {
|
||||
fee: u64,
|
||||
quantization_mask: u64
|
||||
quantization_mask: u64,
|
||||
}
|
||||
|
||||
let res: JsonRpcResponse<FeeResponse> = self.rpc_call("json_rpc", Some(json!({
|
||||
"method": "get_fee_estimate"
|
||||
}))).await?;
|
||||
let res: JsonRpcResponse<FeeResponse> = self
|
||||
.rpc_call(
|
||||
"json_rpc",
|
||||
Some(json!({
|
||||
"method": "get_fee_estimate"
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Fee { per_weight: res.result.fee, mask: res.result.quantization_mask })
|
||||
}
|
||||
@@ -335,14 +389,14 @@ impl Rpc {
|
||||
overspend: bool,
|
||||
too_big: bool,
|
||||
too_few_outputs: bool,
|
||||
reason: String
|
||||
reason: String,
|
||||
}
|
||||
|
||||
let mut buf = Vec::with_capacity(2048);
|
||||
tx.serialize(&mut buf).unwrap();
|
||||
let res: SendRawResponse = self.rpc_call("send_raw_transaction", Some(json!({
|
||||
"tx_as_hex": hex::encode(&buf)
|
||||
}))).await?;
|
||||
let res: SendRawResponse = self
|
||||
.rpc_call("send_raw_transaction", Some(json!({ "tx_as_hex": hex::encode(&buf) })))
|
||||
.await?;
|
||||
|
||||
if res.status != "OK" {
|
||||
Err(RpcError::InvalidTransaction(tx.hash()))?;
|
||||
|
||||
Reference in New Issue
Block a user