Skip to content

Commit dd72103

Browse files
author
Rahul Patni
committed
running formatter
1 parent 1075ba8 commit dd72103

File tree

8 files changed

+123
-81
lines changed

8 files changed

+123
-81
lines changed

crates/dservice/src/main.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,6 @@ async fn main() -> Result<()> {
5151
handle_signals().await?;
5252
let db_config = DbConfig::load(dbconfig).unwrap();
5353
let db_handler = PgHandler::from_config(&db_config);
54-
run_dserver(
55-
dlisten,
56-
restful,
57-
node,
58-
db_handler,
59-
server,
60-
sk_u8,
61-
pk_u8,
62-
)
63-
.await?;
54+
run_dserver(dlisten, restful, node, db_handler, server, sk_u8, pk_u8).await?;
6455
Ok(())
6556
}

crates/dworker/src/main.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,11 @@ async fn main() -> Result<()> {
2626
initialize_logger(args.verbosity);
2727
handle_signals().await?;
2828
if args.name.is_none() {
29-
args.name = Some(
30-
format!(
31-
"dworker-{:?}-{}",
32-
gethostname::gethostname(),
33-
rand::thread_rng().gen::<u8>()
34-
),
35-
);
29+
args.name = Some(format!(
30+
"dworker-{:?}-{}",
31+
gethostname::gethostname(),
32+
rand::thread_rng().gen::<u8>()
33+
));
3634
}
3735
info!(
3836
"Start connecting to scheduler: {:?} with name {:?}",

crates/networking/src/rpc_abi.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use axum::{response::IntoResponse, Json};
22
use constants::IRON_NATIVE_ASSET;
3-
use serde::{ Deserialize, Serialize};
3+
use serde::{Deserialize, Serialize};
44
use ureq::json;
55

66
use crate::orescriptions::{get_ores, is_ores_local, Ores};
@@ -13,7 +13,7 @@ pub struct RpcResponse<T> {
1313

1414
#[derive(Debug, Deserialize, Serialize)]
1515
pub struct RpcResponseStream<T> {
16-
pub data: T
16+
pub data: T,
1717
}
1818

1919
impl<T: Serialize> IntoResponse for RpcResponse<T> {

crates/networking/src/rpc_handler/handler.rs

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,18 @@ use ureq::{Agent, AgentBuilder, Error, Response};
88

99
use crate::{
1010
rpc_abi::{
11-
RpcBroadcastTxRequest, RpcBroadcastTxResponse, RpcCreateTxRequest, RpcCreateTxResponse, RpcExportAccountResponse, RpcGetAccountStatusRequest, RpcGetAccountStatusResponse, RpcGetAccountTransactionRequest, RpcGetAccountTransactionResponse, RpcGetBalancesRequest, RpcGetBalancesResponse, RpcGetBlockRequest, RpcGetBlockResponse, RpcGetBlocksRequest, RpcGetBlocksResponse, RpcGetLatestBlockResponse, RpcGetTransactionsRequest, RpcGetTransactionsResponse, RpcImportAccountRequest, RpcImportAccountResponse, RpcRemoveAccountRequest, RpcRemoveAccountResponse, RpcResetAccountRequest, RpcResponse, RpcSetAccountHeadRequest, RpcSetScanningRequest, SendTransactionRequest, SendTransactionResponse, TransactionStatus
11+
RpcBroadcastTxRequest, RpcBroadcastTxResponse, RpcCreateTxRequest, RpcCreateTxResponse,
12+
RpcExportAccountResponse, RpcGetAccountStatusRequest, RpcGetAccountStatusResponse,
13+
RpcGetAccountTransactionRequest, RpcGetAccountTransactionResponse, RpcGetBalancesRequest,
14+
RpcGetBalancesResponse, RpcGetBlockRequest, RpcGetBlockResponse, RpcGetBlocksRequest,
15+
RpcGetBlocksResponse, RpcGetLatestBlockResponse, RpcGetTransactionsRequest,
16+
RpcGetTransactionsResponse, RpcImportAccountRequest, RpcImportAccountResponse,
17+
RpcRemoveAccountRequest, RpcRemoveAccountResponse, RpcResetAccountRequest, RpcResponse,
18+
RpcSetAccountHeadRequest, RpcSetScanningRequest, SendTransactionRequest,
19+
SendTransactionResponse, TransactionStatus,
1220
},
13-
rpc_handler::RpcError, stream::RequestExt,
21+
rpc_handler::RpcError,
22+
stream::RequestExt,
1423
};
1524

1625
#[derive(Debug, Clone)]
@@ -35,7 +44,8 @@ impl RpcHandler {
3544
request: RpcImportAccountRequest,
3645
) -> Result<RpcResponse<RpcImportAccountResponse>, OreoError> {
3746
let path = format!("http://{}/wallet/importAccount", self.endpoint);
38-
let account_str = serde_json::to_string(&request).map_err(|_|OreoError::InternalRpcError("JSON serialization failed".to_string()))?;
47+
let account_str = serde_json::to_string(&request)
48+
.map_err(|_| OreoError::InternalRpcError("JSON serialization failed".to_string()))?;
3949
let resp = self
4050
.agent
4151
.clone()
@@ -129,20 +139,19 @@ impl RpcHandler {
129139
let resp = self.agent.clone().post(&path).send_json(request);
130140
handle_response(resp)
131141
}
132-
142+
133143
pub fn get_transactions(
134144
&self,
135145
request: RpcGetTransactionsRequest,
136146
) -> Result<RpcResponse<RpcGetTransactionsResponse>, OreoError> {
137147
let path = format!("http://{}/wallet/getAccountTransactions", self.endpoint);
138148
let resp = self.agent.clone().post(&path).send_json(request);
139-
149+
140150
match resp {
141151
Ok(response) => {
142-
let transactions: Result<Vec<_>, OreoError> = response
143-
.into_stream::<TransactionStatus>()
144-
.collect();
145-
152+
let transactions: Result<Vec<_>, OreoError> =
153+
response.into_stream::<TransactionStatus>().collect();
154+
146155
Ok(RpcResponse {
147156
status: 200,
148157
data: RpcGetTransactionsResponse {
@@ -201,7 +210,11 @@ impl RpcHandler {
201210
.agent
202211
.clone()
203212
.post(&path)
204-
.send_json(RpcGetBlocksRequest { start, end, serialized: true });
213+
.send_json(RpcGetBlocksRequest {
214+
start,
215+
end,
216+
serialized: true,
217+
});
205218
handle_response(resp)
206219
}
207220

crates/networking/src/stream.rs

Lines changed: 46 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -20,46 +20,54 @@ enum ResponseItem<T> {
2020
Status { status: u16 },
2121
}
2222

23-
impl<T, R> StreamReader<T, R> where T: DeserializeOwned, R: Read {
23+
impl<T, R> StreamReader<T, R>
24+
where
25+
T: DeserializeOwned,
26+
R: Read,
27+
{
2428
pub fn new(reader: R) -> Self {
25-
Self {
26-
reader: BufReader::new(reader),
27-
_marker: PhantomData,
28-
}
29+
Self {
30+
reader: BufReader::new(reader),
31+
_marker: PhantomData,
32+
}
2933
}
3034

3135
fn read_item(&mut self) -> Result<Option<Vec<u8>>, OreoError> {
32-
let mut item = Vec::new();
33-
loop {
34-
let bytes_read = self.reader.read_until(b'\x0c', &mut item)
35-
.map_err(|e| OreoError::RpcStreamError(e.to_string()))?;
36-
if bytes_read == 0 {
37-
break;
38-
}
39-
if item.last() == Some(&b'\x0c') {
40-
item.pop();
41-
break;
42-
}
43-
}
44-
match item.len() {
45-
0 => Ok(None),
46-
_ => Ok(Some(item))
47-
}
36+
let mut item = Vec::new();
37+
loop {
38+
let bytes_read = self
39+
.reader
40+
.read_until(b'\x0c', &mut item)
41+
.map_err(|e| OreoError::RpcStreamError(e.to_string()))?;
42+
if bytes_read == 0 {
43+
break;
44+
}
45+
if item.last() == Some(&b'\x0c') {
46+
item.pop();
47+
break;
48+
}
49+
}
50+
match item.len() {
51+
0 => Ok(None),
52+
_ => Ok(Some(item)),
53+
}
4854
}
4955

50-
5156
/// Parses a chunk of data into a `ResponseItem<T>`.
5257
fn parse_item(&self, chunk: &[u8]) -> Result<Option<T>, OreoError> {
53-
match serde_json::from_slice::<ResponseItem<T>>(chunk) {
54-
Ok(ResponseItem::Data(item)) => Ok(Some(item.data)),
55-
Ok(ResponseItem::Status { status: 200 }) => Ok(None),
56-
Ok(ResponseItem::Status { status }) => Err(OreoError::RpcStreamError(format!("Received error status: {}", status))),
57-
Err(e) => {
58-
let err_str = format!("Failed to parse JSON object: {:?}", e);
59-
Err(OreoError::RpcStreamError(err_str))
60-
}
61-
}
62-
}
58+
match serde_json::from_slice::<ResponseItem<T>>(chunk) {
59+
Ok(ResponseItem::Data(item)) => Ok(Some(item.data)),
60+
Ok(ResponseItem::Status { status: 200 }) => Ok(None),
61+
Ok(ResponseItem::Status { status }) => Err(OreoError::RpcStreamError(format!(
62+
"Received error status: {}",
63+
status
64+
))),
65+
Err(e) => {
66+
let err_str = format!("Failed to parse JSON object: {:?}", e);
67+
Err(OreoError::RpcStreamError(err_str))
68+
}
69+
}
70+
}
6371
}
6472

6573
impl<T, R> Iterator for StreamReader<T, R>
@@ -83,11 +91,15 @@ where
8391
}
8492

8593
pub trait RequestExt {
86-
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>>;
94+
fn into_stream<T: DeserializeOwned>(
95+
self,
96+
) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>>;
8797
}
8898

8999
impl RequestExt for Response {
90-
fn into_stream<T: DeserializeOwned>(self) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>> {
100+
fn into_stream<T: DeserializeOwned>(
101+
self,
102+
) -> StreamReader<T, Box<dyn Read + Send + Sync + 'static>> {
91103
let reader = self.into_reader();
92104
StreamReader::new(Box::new(reader))
93105
}

crates/oreo_errors/src/lib.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ impl IntoResponse for OreoError {
5555
OreoError::NoImported(_) => (StatusCode::from_u16(602).unwrap(), self.to_string()),
5656
OreoError::Scanning(_) => (StatusCode::from_u16(603).unwrap(), self.to_string()),
5757
OreoError::Syncing => (StatusCode::from_u16(604).unwrap(), self.to_string()),
58-
OreoError::InternalRpcError(_) => (StatusCode::from_u16(605).unwrap(), self.to_string()),
58+
OreoError::InternalRpcError(_) => {
59+
(StatusCode::from_u16(605).unwrap(), self.to_string())
60+
}
5961
OreoError::GenerateSpendProofFailed(_) => {
6062
(StatusCode::from_u16(606).unwrap(), self.to_string())
6163
}
@@ -73,7 +75,9 @@ impl IntoResponse for OreoError {
7375
OreoError::SeralizeError(_) => (StatusCode::from_u16(612).unwrap(), self.to_string()),
7476
OreoError::ParseError(_) => (StatusCode::from_u16(613).unwrap(), self.to_string()),
7577
OreoError::DServerError(_) => (StatusCode::from_u16(614).unwrap(), self.to_string()),
76-
OreoError::AccountStatusError(_) => (StatusCode::from_u16(615).unwrap(), self.to_string()),
78+
OreoError::AccountStatusError(_) => {
79+
(StatusCode::from_u16(615).unwrap(), self.to_string())
80+
}
7781
OreoError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
7882
OreoError::RpcStreamError(_) => (StatusCode::from_u16(615).unwrap(), self.to_string()),
7983
};

crates/server/src/handlers.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ use axum::{
88
use constants::{ACCOUNT_VERSION, MAINNET_GENESIS_SEQUENCE};
99
use db_handler::DBHandler;
1010
use networking::{
11-
decryption_message::{DecryptionMessage, ScanRequest, ScanResponse, SuccessResponse}, rpc_abi::{
11+
decryption_message::{DecryptionMessage, ScanRequest, ScanResponse, SuccessResponse},
12+
rpc_abi::{
1213
BlockInfo, OutPut, RpcBroadcastTxRequest, RpcCreateTxRequest, RpcGetAccountStatusRequest,
1314
RpcGetAccountTransactionRequest, RpcGetBalancesRequest, RpcGetBalancesResponse,
1415
RpcGetTransactionsRequest, RpcImportAccountRequest, RpcImportAccountResponse,
1516
RpcRemoveAccountRequest, RpcResetAccountRequest, RpcResponse, RpcSetScanningRequest,
16-
}, web_abi::{GetTransactionDetailResponse, ImportAccountRequest, RescanAccountResponse}
17+
},
18+
web_abi::{GetTransactionDetailResponse, ImportAccountRequest, RescanAccountResponse},
1719
};
1820
use oreo_errors::OreoError;
1921
use serde_json::json;
@@ -258,7 +260,8 @@ pub async fn update_scan_status_handler<T: DBHandler>(
258260
return e.into_response();
259261
}
260262
let account = db_account.unwrap();
261-
let reset_created_at = account.create_head.is_none() || account.create_head.unwrap() == 1;
263+
let reset_created_at =
264+
account.create_head.is_none() || account.create_head.unwrap() == 1;
262265
let reset = shared.rpc_handler.reset_account(RpcResetAccountRequest {
263266
account: account.name.clone(),
264267
reset_scanning_enabled: Some(false),

crates/server/src/lib.rs

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,21 @@
1-
use std::{env, net::SocketAddr, sync::Arc, time::Duration};
2-
use axum_extra::{headers::{authorization::Basic, Authorization}, TypedHeader};
3-
use sha2::{Sha256, Digest};
1+
use axum_extra::{
2+
headers::{authorization::Basic, Authorization},
3+
TypedHeader,
4+
};
5+
use sha2::{Digest, Sha256};
46
use std::str;
7+
use std::{env, net::SocketAddr, sync::Arc, time::Duration};
58

69
use anyhow::Result;
710
use axum::{
8-
body::Body, error_handling::HandleErrorLayer, extract::State, http::{Request, StatusCode}, middleware::{from_fn_with_state, Next}, response::IntoResponse, routing::{get, post}, BoxError, Router
11+
body::Body,
12+
error_handling::HandleErrorLayer,
13+
extract::State,
14+
http::{Request, StatusCode},
15+
middleware::{from_fn_with_state, Next},
16+
response::IntoResponse,
17+
routing::{get, post},
18+
BoxError, Router,
919
};
1020
use db_handler::{DBHandler, PgHandler};
1121
use networking::{rpc_handler::RpcHandler, server_handler::ServerHandler};
@@ -42,7 +52,13 @@ impl<T> SharedState<T>
4252
where
4353
T: DBHandler,
4454
{
45-
pub fn new(db_handler: T, endpoint: &str, scan: &str, secp: SecpKey, genesis_hash: String) -> Self {
55+
pub fn new(
56+
db_handler: T,
57+
endpoint: &str,
58+
scan: &str,
59+
secp: SecpKey,
60+
genesis_hash: String,
61+
) -> Self {
4662
Self {
4763
db_handler,
4864
rpc_handler: RpcHandler::new(endpoint.into()),
@@ -56,15 +72,20 @@ where
5672
pub async fn auth<T: DBHandler>(
5773
State(shared_state): State<Arc<SharedState<T>>>,
5874
TypedHeader(Authorization(basic)): TypedHeader<Authorization<Basic>>,
59-
req: Request<Body>,
60-
next: Next
61-
) -> impl IntoResponse
62-
where
75+
req: Request<Body>,
76+
next: Next,
77+
) -> impl IntoResponse
78+
where
6379
T: DBHandler + Send + Sync + 'static,
6480
{
65-
match shared_state.db_handler.get_account(basic.username().to_string()).await {
81+
match shared_state
82+
.db_handler
83+
.get_account(basic.username().to_string())
84+
.await
85+
{
6686
Ok(account) => {
67-
let bytes = hex::decode(account.vk).map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid token"))?;
87+
let bytes =
88+
hex::decode(account.vk).map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid token"))?;
6889
let token = Sha256::digest(bytes);
6990
let token_hex = hex::encode(token);
7091
if token_hex != basic.password() {
@@ -78,7 +99,7 @@ pub async fn auth<T: DBHandler>(
7899
}
79100
}
80101
}
81-
102+
82103
pub async fn run_server(
83104
listen: SocketAddr,
84105
rpc_server: String,
@@ -128,7 +149,7 @@ pub async fn run_server(
128149
if env::var("ENABLE_AUTH").unwrap_or_else(|_| "false".to_string()) == "true" {
129150
auth_router = auth_router.layer(auth_middleware);
130151
}
131-
152+
132153
let router = no_auth_router
133154
.merge(auth_router)
134155
.layer(

0 commit comments

Comments
 (0)