summaryrefslogtreecommitdiff
path: root/wire-gateway/src/main.rs
blob: 59eb6dd0efd185b6367845bfe3bd5d92e391d479 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use error::{CatchResult, ServerError};
use hyper::{
    http::request::Parts,
    service::{make_service_fn, service_fn},
    Body, Error, Method, Response, Server, StatusCode,
};
use json::parse_body;
use std::{process::exit, str::FromStr, time::Instant};
use taler_log::log::{error, info, log, Level};
use tokio_postgres::{Client, NoTls};
use url::Url;
use wire_gateway::{
    api_common::{Amount, SafeUint64, ShortHashCode, Timestamp},
    api_wire::{
        HistoryParams, IncomingBankTransaction, IncomingHistory, OutgoingBankTransaction,
        OutgoingHistory, TransferRequest, TransferResponse,
    },
    error_codes::ErrorCode,
};

use crate::json::encode_body;

mod error;
mod json;

const SELF_PAYTO: &str = "payto://bitcoin/bcrt1qgkgxkjj27g3f7s87mcvjjsghay7gh34cx39prj";
#[cfg(target_family = "windows")]
const DB_URL: &str = "postgres://localhost/wire_gateway?user=postgres";
#[cfg(target_family = "unix")]
const DB_URL: &str = "postgres://localhost?user=postgres&password=password";

#[tokio::main]
async fn main() {
    taler_log::init();

    #[cfg(feature = "test")]
    taler_log::log::warn!("Running with test admin endpoint unsuitable for production");

    let (client, connection) = tokio_postgres::connect(DB_URL, NoTls).await.unwrap();

    tokio::spawn(async move {
        if let Err(e) = connection.await {
            error!("DB: {}", e);
            exit(1);
        }
    });
    let state = ServerState { client };
    let state: &'static ServerState = Box::leak(Box::new(state));
    let addr = ([0, 0, 0, 0], 8080).into();
    let make_service = make_service_fn(move |_| async move {
        Ok::<_, Error>(service_fn(move |req| async move {
            let start = Instant::now();
            let (parts, body) = req.into_parts();
            let response = match router(&parts, body, state).await {
                Ok(resp) => resp,
                Err(err) => err.response(),
            };
            // TODO log error message inlined into response log OR use a request id to link error message and response
            let status = response.status().as_u16();
            let level = if status >= 500 {
                Level::Error
            } else if status >= 400 {
                Level::Warn
            } else {
                Level::Info
            };
            log!(
                level,
                "{} {} {:>2}ms {}",
                parts.method,
                status,
                start.elapsed().as_millis(),
                parts.uri.path()
            );
            Ok::<Response<Body>, Error>(response)
        }))
    });

    let server = Server::bind(&addr).serve(make_service);

    info!("Server listening on http://{}", addr);

    if let Err(e) = server.await {
        error!("server: {}", e);
    }
}

struct ServerState {
    client: Client,
}

/// Check if an url is a valid bitcoin payto url
fn check_pay_to(url: &Url) -> bool {
    return url.domain() == Some("bitcoin")
        && url.scheme() == "payto"
        && url.username() == ""
        && url.password().is_none()
        && url.query().is_none()
        && url.fragment().is_none()
        && bitcoin::Address::from_str(url.path().trim_start_matches('/')).is_ok();
}

/// Assert request method match expected
fn assert_method(parts: &Parts, method: Method) -> Result<(), ServerError> {
    if parts.method == method {
        Ok(())
    } else {
        Err(ServerError::code(
            StatusCode::METHOD_NOT_ALLOWED,
            ErrorCode::GENERIC_METHOD_INVALID,
        ))
    }
}

/// Parse history params from request
fn history_params(parts: &Parts) -> Result<HistoryParams, ServerError> {
    let params: HistoryParams = serde_urlencoded::from_str(parts.uri.query().unwrap_or(""))
        .catch_code(
            StatusCode::BAD_REQUEST,
            ErrorCode::GENERIC_PARAMETER_MALFORMED,
        )?;
    if params.delta == 0 {
        return Err(ServerError::code(
            StatusCode::BAD_REQUEST,
            ErrorCode::GENERIC_PARAMETER_MALFORMED,
        ));
    }
    Ok(params)
}

/// Generate sql query filter from history params
fn sql_history_filter(params: &HistoryParams) -> String {
    let asc = params.delta > 0;
    let limit = params.delta.abs();
    let order_sql = if asc { "ASC" } else { "DESC" };
    let where_sql = if let Some(start) = params.start {
        format!("WHERE id {} {}", if asc { '>' } else { '<' }, start)
    } else {
        String::new()
    };
    format!("{} ORDER BY id {} LIMIT {}", where_sql, order_sql, limit)
}

async fn router(
    parts: &Parts,
    body: Body,
    state: &'static ServerState,
) -> Result<Response<Body>, ServerError> {
    let response = match parts.uri.path() {
        "/transfer" => {
            assert_method(&parts, Method::POST)?;
            let request: TransferRequest = parse_body(&parts, body).await.catch_code(
                StatusCode::BAD_REQUEST,
                ErrorCode::GENERIC_PARAMETER_MALFORMED,
            )?;
            if !check_pay_to(&request.credit_account) {
                return Err(ServerError::code(
                    StatusCode::BAD_REQUEST,
                    ErrorCode::GENERIC_PAYTO_URI_MALFORMED,
                ));
            }
            if request.amount.currency != "BTC" {
                return Err(ServerError::code(
                    StatusCode::BAD_REQUEST,
                    ErrorCode::GENERIC_PARAMETER_MALFORMED,
                ));
            }
            let timestamp = Timestamp::now();
            let row = state.client.query_one("INSERT INTO tx_out (_date, amount, wtid, debit_acc, credit_acc, exchange_url, status) VALUES (now(), $1, $2, $3, $4, $5, $6) RETURNING id", &[
                &request.amount.to_string(), &request.wtid.as_ref(), &SELF_PAYTO,  &request.credit_account.to_string(), &request.exchange_base_url.to_string(), &0i16
            ]).await.unwrap();
            encode_body(
                parts,
                StatusCode::OK,
                &TransferResponse {
                    timestamp,
                    row_id: {
                        let id: i32 = row.get(0);
                        SafeUint64::try_from(id as u64).unwrap()
                    },
                },
            )
            .await
            .unexpected()?
        }
        "/history/incoming" => {
            assert_method(&parts, Method::GET)?;
            let params = history_params(&parts)?;
            let filter = sql_history_filter(&params);

            let transactions = state
                .client
                .query(
                    &format!("SELECT id, _date, amount, reserve_pub, debit_acc, credit_acc FROM tx_in {}", filter),
                    &[],
                )
                .await
                .unwrap()
                .into_iter()
                .map(|row| IncomingBankTransaction::IncomingReserveTransaction {
                    row_id: {
                        let id: i32 = row.get(0);
                        SafeUint64::try_from(id as u64).unwrap()
                    },
                    date: Timestamp::Time(row.get(1)),
                    amount: Amount::from_str(row.get(2)).unwrap(),
                    reserve_pub: {
                        let slice: &[u8] = row.get(3);
                        let array: [u8; 32] = slice.try_into().unwrap();
                        ShortHashCode::from(array)
                    },
                    debit_account: Url::parse(row.get(4)).unwrap(),
                    credit_account: Url::parse(row.get(5)).unwrap(),
                })
                .collect();
            encode_body(
                parts,
                StatusCode::OK,
                &IncomingHistory {
                    incoming_transactions: transactions,
                },
            )
            .await
            .unexpected()?
        }
        "/history/outgoing" => {
            assert_method(&parts, Method::GET)?;
            let params = history_params(&parts)?;
            let filter = sql_history_filter(&params);

            let transactions = state
                .client
                .query(
                    &format!("SELECT id, _date, amount, wtid, debit_acc, credit_acc, exchange_url FROM tx_out {}",filter),
                    &[],
                )
                .await
                .unwrap()
                .into_iter()
                .map(|row| OutgoingBankTransaction {
                    row_id: {
                        let id: i32 = row.get(0);
                        SafeUint64::try_from(id as u64).unwrap()
                    },
                    date: Timestamp::Time(row.get(1)),
                    amount: Amount::from_str(row.get(2)).unwrap(),
                    wtid: {
                        let slice : &[u8] = row.get(3);
                        let array: [u8; 32] = slice.try_into().unwrap();
                        ShortHashCode::from(array)
                    },
                    debit_account: Url::parse(row.get(4)).unwrap(),
                    credit_account: Url::parse(row.get(5)).unwrap(),
                    exchange_base_url: Url::parse(row.get(6)).unwrap(),
                })
                .collect();
            encode_body(
                parts,
                StatusCode::OK,
                &OutgoingHistory {
                    outgoing_transactions: transactions,
                },
            )
            .await
            .unexpected()?
        }
        #[cfg(feature = "test")]
        "/admin/add-incoming" => {
            // We do not check input as this is a test admin endpoint
            assert_method(&parts, Method::POST).unwrap();
            let request: wire_gateway::api_wire::AddIncomingRequest =
                parse_body(&parts, body).await.unwrap();
            let timestamp = Timestamp::now();
            let row = state.client.query_one("INSERT INTO tx_in (_date, amount, reserve_pub, debit_acc, credit_acc) VALUES (now(), $1, $2, $3, $4) RETURNING id", &[
                &request.amount.to_string(), &request.reserve_pub.as_ref(), &request.debit_account.to_string(), &"payto://bitcoin/bcrt1qgkgxkjj27g3f7s87mcvjjsghay7gh34cx39prj"
            ]).await.unwrap();
            encode_body(
                parts,
                StatusCode::OK,
                &TransferResponse {
                    timestamp,
                    row_id: {
                        let id: i32 = row.get(0);
                        SafeUint64::try_from(id as u64).unwrap()
                    },
                },
            )
            .await
            .unexpected()?
        }
        _ => {
            return Err(ServerError::code(
                StatusCode::NOT_FOUND,
                ErrorCode::GENERIC_ENDPOINT_UNKNOWN,
            ))
        }
    };
    return Ok(response);
}