summaryrefslogtreecommitdiff
path: root/wire-gateway/src/main.rs
blob: 6e81ef25038d8d8950919e5bf588fa1206943026 (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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use deadpool_postgres::{Pool, Runtime};
use error::{CatchResult, ServerError};
use hyper::{
    http::request::Parts,
    service::{make_service_fn, service_fn},
    Body, Method, Response, Server, StatusCode,
};
use json::{encode_body, parse_body};
use listenfd::ListenFd;
use std::{convert::Infallible, str::FromStr, time::Instant};
use taler_api::{
    api_common::{Amount, SafeUint64, ShortHashCode, Timestamp},
    api_wire::{
        HistoryParams, IncomingBankTransaction, IncomingHistory, OutgoingBankTransaction,
        OutgoingHistory, TransferRequest, TransferResponse,
    },
    error_codes::ErrorCode,
    url::Url,
};
use taler_log::log::{error, info, log, Level};
use tokio_postgres::{config::Host, NoTls};

mod error;
mod json;

struct ServerState {
    pool: Pool,
    config: taler_config::Config,
}

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

    let conf = taler_config::Config::from_path("test.conf");

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

    // Parse postgres url
    let config = tokio_postgres::Config::from_str(&conf.db_url).unwrap();
    // TODO find a way to clean this ugly mess
    let mut cfg = deadpool_postgres::Config::new();
    cfg.user = config.get_user().map(|it| it.to_string());
    cfg.password = config
        .get_password()
        .map(|it| String::from_utf8(it.to_vec()).unwrap());
    cfg.dbname = config.get_dbname().map(|it| it.to_string());
    cfg.options = config.get_options().map(|it| it.to_string());
    cfg.host = Some(
        config
            .get_hosts()
            .into_iter()
            .map(|it| match it {
                Host::Tcp(it) => it.to_string(),
                #[cfg(target_os = "linux")]
                Host::Unix(it) => it.to_str().unwrap().to_string(),
            })
            .collect(),
    );
    cfg.ports = Some(config.get_ports().to_vec());
    cfg.application_name = config.get_application_name().map(|it| it.to_string());
    cfg.connect_timeout = config.get_connect_timeout().cloned();

    let pool = cfg.create_pool(Some(Runtime::Tokio1), NoTls).unwrap();
    let state = ServerState { pool, config: conf };
    let state: &'static ServerState = Box::leak(Box::new(state));
    let make_service = make_service_fn(move |_| async move {
        Ok::<_, Infallible>(service_fn(move |req| async move {
            let start = Instant::now();
            let (parts, body) = req.into_parts();
            let (response, msg) = match router(&parts, body, state).await {
                Ok(resp) => (resp, String::new()),
                Err(err) => err.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,
                "{} {} {}ms {} - {}",
                parts.method,
                status,
                start.elapsed().as_millis(),
                parts.uri.path(),
                msg
            );
            Ok::<Response<Body>, Infallible>(response)
        }))
    });

    let mut listenfd = ListenFd::from_env();
    let server = if let Some(listener) = listenfd.take_tcp_listener(0).unwrap() {
        info!(
            "Server listening on activated socket {}",
            listener.local_addr().unwrap()
        );
        Server::from_tcp(listener).unwrap().serve(make_service)
    } else {
        let addr = ([0, 0, 0, 0], state.config.port).into();
        info!("Server listening on http://{}", &addr);
        Server::bind(&addr).serve(make_service)
    };

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

/// 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 db = state.pool.get().await.catch_code(
                StatusCode::GATEWAY_TIMEOUT,
                ErrorCode::GENERIC_DB_FETCH_FAILED,
            )?;
            // Handle idempotence, check previous transaction with the same request_uid
            let row = db.query_opt("SELECT amount, exchange_url, wtid, credit_acc, id, _date FROM tx_out WHERE request_uid = $1", &[&request.request_uid.as_ref()])
                .await?;
            if let Some(row) = row {
                let prev = TransferRequest {
                    request_uid: request.request_uid.clone(),
                    amount: Amount::from_str(row.get(0)).unwrap(),
                    exchange_base_url: Url::parse(row.get(1)).unwrap(),
                    wtid: {
                        let slice: &[u8] = row.get(2);
                        let array: [u8; 32] = slice.try_into().unwrap();
                        ShortHashCode::from(array)
                    },
                    credit_account: Url::parse(row.get(3)).unwrap(),
                };
                if prev == request {
                    // Idempotence
                    return encode_body(
                        parts,
                        StatusCode::OK,
                        &TransferResponse {
                            timestamp: Timestamp::Time(row.get(5)),
                            row_id: {
                                let id: i32 = row.get(4);
                                SafeUint64::try_from(id as u64).unwrap()
                            },
                        },
                    )
                    .await
                    .unexpected();
                } else {
                    return Err(ServerError::status(StatusCode::CONFLICT));
                }
            }

            let timestamp = Timestamp::now();
            let row = db.query_one("INSERT INTO tx_out (_date, amount, wtid, debit_acc, credit_acc, exchange_url, status, request_uid) VALUES (now(), $1, $2, $3, $4, $5, $6, $7) RETURNING id", &[
                &request.amount.to_string(), &request.wtid.as_ref(), &state.config.payto.as_ref(),  &request.credit_account.as_ref(), &request.exchange_base_url.as_ref(), &0i16, &request.request_uid.as_ref()
            ]).await?;
            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 db = state.pool.get().await.catch_code(
                StatusCode::GATEWAY_TIMEOUT,
                ErrorCode::GENERIC_DB_FETCH_FAILED,
            )?;
            let transactions = db
                .query(
                    &format!("SELECT id, _date, amount, reserve_pub, debit_acc, credit_acc FROM tx_in {}", filter),
                    &[],
                )
                .await.catch_code(
                    StatusCode::BAD_GATEWAY,
                    ErrorCode::GENERIC_DB_FETCH_FAILED,
                )?
                .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 db = state.pool.get().await.catch_code(
                StatusCode::GATEWAY_TIMEOUT,
                ErrorCode::GENERIC_DB_FETCH_FAILED,
            )?;
            let transactions = db
                .query(
                    &format!("SELECT id, _date, amount, wtid, debit_acc, credit_acc, exchange_url FROM tx_out {}",filter),
                    &[],
                )
                .await.catch_code(
                    StatusCode::BAD_GATEWAY,
                    ErrorCode::GENERIC_DB_FETCH_FAILED,
                )?
                .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: taler_api::api_wire::AddIncomingRequest =
                parse_body(&parts, body).await.unwrap();
            let timestamp = Timestamp::now();
            let db = state.pool.get().await.catch_code(
                StatusCode::GATEWAY_TIMEOUT,
                ErrorCode::GENERIC_DB_FETCH_FAILED,
            )?;
            let row = db.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.as_ref(), &"payto://bitcoin/bcrt1qgkgxkjj27g3f7s87mcvjjsghay7gh34cx39prj"
            ]).await.catch_code(
                StatusCode::BAD_GATEWAY,
                ErrorCode::GENERIC_DB_FETCH_FAILED,
            )?;
            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);
}