fixing up functions and trying to clean up code

master
lza_menace 4 years ago
parent d8d53b810c
commit d2c7d912e6

@ -36,9 +36,9 @@ impl Default for RPCParams {
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)]
pub struct GetInfo { pub struct GetInfo {
pub jsonrpc: String, pub jsonrpc: Option<String>,
pub id: String, pub id: Option<String>,
pub result: GetInfoResult pub result: Option<GetInfoResult>
} }
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)]
@ -140,7 +140,7 @@ impl GetTransactionsTxs {
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)]
pub struct GetBlock { pub struct GetBlock {
pub id: String, pub id: i32,
pub jsonrpc: String, pub jsonrpc: String,
pub result: GetBlockResult pub result: GetBlockResult
} }
@ -202,7 +202,7 @@ pub struct TransactionJSON {
pub vin: Vec<TransactionInputs>, pub vin: Vec<TransactionInputs>,
pub vout: Vec<TransactionOutputs>, pub vout: Vec<TransactionOutputs>,
pub extra: Vec<u32>, pub extra: Vec<u32>,
pub rct_signatures: RingSignatures pub rct_signatures: Option<RingSignatures>
} }
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug, Clone)]

@ -8,87 +8,77 @@ mod data_types;
use rocket::http::RawStr; use rocket::http::RawStr;
use rocket::response::Redirect; use rocket::response::Redirect;
use rocket_contrib::json::{Json,JsonValue}; use rocket_contrib::json::JsonValue;
use rocket_contrib::templates::Template; use rocket_contrib::templates::Template;
use rocket_contrib::serve::StaticFiles; use rocket_contrib::serve::StaticFiles;
use reqwest::blocking::{RequestBuilder, Client}; use reqwest::blocking::{RequestBuilder, Client};
use reqwest::Error; use reqwest::Error;
use qrcode_generator::QrCodeEcc; use qrcode_generator::QrCodeEcc;
use std::env; use std::env;
use std::clone;
use data_types::*; use data_types::*;
// fn issue_rpc(method: &str, params: Option<RPCParams>) -> RequestBuilder { fn build_rpc(method: &str, raw_data: Option<JsonValue>, raw: bool) -> RequestBuilder {
// let http_client = Client::new();
// let url = format!(
// "{}/json_rpc",
// env::var("DAEMON_URI").unwrap()
// );
// let post_data = RPCPayload {
// method: Some(method.to_string()),
// params: params,
// ..Default::default()
// };
// http_client.post(&url).json(&post_data)
// }
// fn issue_raw_rpc(method: &str, params: JsonValue) -> RequestBuilder {
// let http_client = Client::new();
// let url = format!(
// "{}/{}",
// env::var("DAEMON_URI").unwrap(),
// &method
// );
// http_client.post(&url).json(&params)
// }
//
fn build_rpc(method: &str, data: Option<JsonValue>, raw: bool) -> RequestBuilder {
let http_client = Client::new(); let http_client = Client::new();
let daemon_uri = env::var("DAEMON_URI").unwrap(); let daemon_uri = env::var("DAEMON_URI").unwrap();
match raw { match raw {
true => { true => {
let uri = format!("{}/{}", &daemon_uri, &method); let uri = format!("{}/{}", &daemon_uri, &method);
if let None = data { if let None = raw_data {
http_client.post(&uri) http_client.post(&uri)
} else { } else {
http_client.post(&uri).json(&data) http_client.post(&uri).json(&raw_data)
} }
}, },
false => { false => {
let uri = format!("{}/json_rpc", &daemon_uri); let uri = format!("{}/json_rpc", &daemon_uri);
let data = RPCPayload { if let None = raw_data {
method: Some(method.to_string()), http_client.post(&uri)
..Default::default() } else {
}; http_client.post(&uri).json(&raw_data)
http_client.post(&uri).json(&data) }
} }
} }
} }
//
// #[get("/block/hash/<block_hash>")] #[get("/block/hash/<block_hash>")]
// fn get_block_by_hash(block_hash: String) -> Template { fn get_block_by_hash(block_hash: String) -> Template {
// let params = RPCParams { // https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_block
// hash: Some(block_hash), // http POST crypto.int.lzahq.tech:34568/json_rpc method=get_block params:='{"hash": "83faf32a04708bead3e712947b8ad8e1e6ab50f3093948bfb3e71fb0089a7b68"}'
// ..Default::default() let payload: JsonValue = json!({
// }; "method": "get_block",
// let res: GetBlock = issue_rpc(&"get_block", Some(params)) "params": {
// .send().unwrap().json().unwrap(); "hash": block_hash
// Template::render("block", &res.result) }
// } });
//
// #[get("/block/height/<block_height>")] let res: GetBlock = build_rpc(
// fn get_block_by_height(block_height: String) -> Template { &"get_block", Some(payload), false
// let params = RPCParams { ).send().unwrap().json().unwrap();
// height: Some(block_height), Template::render("block", &res.result)
// ..Default::default() }
// };
// let res: GetBlock = issue_rpc(&"get_block", Some(params)) #[get("/block/height/<block_height>")]
// .send().unwrap().json().unwrap(); fn get_block_by_height(block_height: String) -> Template {
// Template::render("block", &res.result) // https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_block
// } // http POST crypto.int.lzahq.tech:34568/json_rpc method=get_block params:='{"height": 225460}'
let payload: JsonValue = json!({
"method": "get_block",
"params": {
"height": block_height
}
});
let res: GetBlock = build_rpc(
&"get_block", Some(payload), false
).send().unwrap().json().unwrap();
Template::render("block", &res.result)
}
#[get("/transaction/<tx_hash>")] #[get("/transaction/<tx_hash>")]
fn get_transaction_by_hash(tx_hash: String) -> Template { fn get_transaction_by_hash(tx_hash: String) -> Template {
// https://www.getmonero.org/resources/developer-guides/daemon-rpc.html#get_transactions
// echo '{"txs_hashes": ["98f68768d258544856e0b6c3a3aac8773a094fe184f9b9daba1554a9d8fc2e02"], "decode_as_json": true}' \
// | http POST crypto.int.lzahq.tech:34568/get_transactions
let params: JsonValue = json!({ let params: JsonValue = json!({
"txs_hashes": [&tx_hash], "txs_hashes": [&tx_hash],
"decode_as_json": true "decode_as_json": true
@ -137,69 +127,73 @@ fn show_wallet_address(
Template::render("address", context) Template::render("address", context)
} }
// #[get("/search?<value>")] #[get("/search?<value>")]
// fn search(value: &RawStr) -> Redirect { fn search(value: &RawStr) -> Redirect {
// // This search implementation is not ideal but it works. // This search implementation is not ideal but it works.
// // We basically check the length of the search value and // We basically check the length of the search value and
// // attempt to redirect to the appropriate route. // attempt to redirect to the appropriate route.
// let sl: usize = value.len(); let sl: usize = value.len();
// if sl == 0 { if sl == 0 {
// return Redirect::found(uri!(index)); return Redirect::found(uri!(index));
// } else if sl < 8 { } else if sl < 8 {
// // Less than 8 characters is probably a block height. If it can // Less than 8 characters is probably a block height. If it can
// // be parsed as valid u32 then redirect to `get_block_by_height`, // be parsed as valid u32 then redirect to `get_block_by_height`,
// // otherwise redirect to the error response. // otherwise redirect to the error response.
// match value.parse::<u32>() { match value.parse::<u32>() {
// Ok(_) => return Redirect::found(uri!(get_block_by_height: value.as_str())), Ok(_) => return Redirect::found(uri!(get_block_by_height: value.as_str())),
// Err(_) => return Redirect::found(uri!(error)) Err(_) => return Redirect::found(uri!(error))
// } }
// } else if sl == 64 { } else if sl == 64 {
// // Equal to 64 characters is probably a hash; block or tx. // Equal to 64 characters is probably a hash; block or tx.
// // For this we attempt to query for a block with // For this we attempt to query for a block with
// // given hash. If we don't receive a valid/expected // given hash. If we don't receive a valid/expected
// // response then we attempt to query for a transaction hash. // response then we attempt to query for a transaction hash.
// // If neither works then redirect to error response. // If neither works then redirect to error response.
// let block_hash_params = RPCParams {
// hash: Some(value.to_string()), let block_hash_params: JsonValue = json!({
// ..Default::default() "method": "get_block",
// }; "params": {
// let check_valid_block_hash: Result<GetBlock, Error> = issue_rpc( "hash": value.to_string()
// &"get_block", Some(block_hash_params) }
// ).send().unwrap().json(); });
//
// match check_valid_block_hash { let check_valid_block_hash: Result<GetBlock, Error> = build_rpc(
// Ok(_) => return Redirect::found(uri!(get_block_by_hash: value.as_str())), &"get_block", Some(block_hash_params), false
// Err(_) => { ).send().unwrap().json();
// let tx_hash_params: JsonValue = json!({"txs_hashes": [&value.as_str()]});
// let check_valid_tx_hash: Result<GetTransactions, Error> = issue_raw_rpc( match check_valid_block_hash {
// &"get_transactions", tx_hash_params Ok(_) => return Redirect::found(uri!(get_block_by_hash: value.as_str())),
// ).send().unwrap().json(); Err(_) => {
// let tx_hash_params: JsonValue = json!({"txs_hashes": [&value.as_str()]});
// match check_valid_tx_hash { let check_valid_tx_hash: Result<GetTransactions, Error> = build_rpc(
// Ok(_) => return Redirect::found(uri!(get_transaction_by_hash: value.as_str())), &"get_transactions", Some(tx_hash_params), true
// Err(_) => return Redirect::found(uri!(error)) ).send().unwrap().json();
// }
// } match check_valid_tx_hash {
// } Ok(_) => return Redirect::found(uri!(get_transaction_by_hash: value.as_str())),
// } else if sl == 95 { Err(_) => return Redirect::found(uri!(error))
// // Equal to 95 characters is probably a wallet address. }
// // For this let's just redirect to the `show_wallet_address` route. }
// return Redirect::found(uri!(show_wallet_address: value.as_str(), "", "", "", "")) }
// } else if sl == 105 { } else if sl == 97 {
// // Equal to 105 characters is probably an integrated address. // Equal to 95 characters is probably a wallet address.
// // For this let's just redirect to the `show_wallet_address` route. // For this let's just redirect to the `show_wallet_address` route.
// return Redirect::found(uri!(show_wallet_address: value.as_str(), "", "", "", "")) return Redirect::found(uri!(show_wallet_address: value.as_str(), "", "", "", ""))
// } else { } else if sl == 105 {
// // Anything else hasn't been implemented yet // Equal to 105 characters is probably an integrated address.
// // so redirect to error response. // For this let's just redirect to the `show_wallet_address` route.
// return Redirect::found(uri!(error)); return Redirect::found(uri!(show_wallet_address: value.as_str(), "", "", "", ""))
// }; } else {
// } // Anything else hasn't been implemented yet
// // so redirect to error response.
return Redirect::found(uri!(error));
};
}
// #[get("/tx_pool")] // #[get("/tx_pool")]
// fn show_tx_pool() -> Json<GetTransactionPool> { // fn show_tx_pool() -> Json<GetTransactionPool> {
// let mut tx_pool: GetTransactionPool = build_rpc( // let mut tx_pool: GetTransactionPool = build_rpc(
// &"get_transaction_pool", None, true // &"get_transaction_pool", None, None, true
// ).send().unwrap().json().unwrap(); // ).send().unwrap().json().unwrap();
// //
// for f in &mut tx_pool.transactions { // for f in &mut tx_pool.transactions {
@ -211,14 +205,16 @@ fn show_wallet_address(
#[get("/")] #[get("/")]
fn index() -> Template { fn index() -> Template {
let daemon_info: GetInfo = build_rpc( let daemon_info: GetInfoResult = build_rpc(
&"get_info", None, false &"get_info", None, true
).send().unwrap().json().unwrap(); ).send().unwrap().json().unwrap();
let tx_pool: GetTransactionPool = build_rpc( let tx_pool: GetTransactionPool = build_rpc(
&"get_transaction_pool", None, true &"get_transaction_pool", None, true
).send().unwrap().json().unwrap(); ).send().unwrap().json().unwrap();
println!("{:#?}", tx_pool);
// let mut tx_pool_txs = tx_pool.transactions; // let mut tx_pool_txs = tx_pool.transactions;
// //
// match tx_pool_txs { // match tx_pool_txs {
@ -235,7 +231,7 @@ fn index() -> Template {
// }; // };
let context: JsonValue = json!({ let context: JsonValue = json!({
"daemon_info": daemon_info.result, "daemon_info": daemon_info,
"tx_pool_txs": tx_pool.transactions "tx_pool_txs": tx_pool.transactions
}); });
@ -265,10 +261,10 @@ fn main() {
rocket::ignite() rocket::ignite()
.mount("/", routes![ .mount("/", routes![
index, index,
// search, search,
// show_tx_pool, // show_tx_pool,
// get_block_by_height, get_block_by_height,
// get_block_by_hash, get_block_by_hash,
get_transaction_by_hash, get_transaction_by_hash,
show_wallet_address, show_wallet_address,
error error