taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

api.rs (25209B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2025-2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use compact_str::CompactString;
     18 use jiff::Timestamp;
     19 use prometheus_client::{
     20     encoding::EncodeLabelSet,
     21     metrics::{family::Family, gauge::Gauge},
     22     registry::{Registry, Unit},
     23 };
     24 use sqlx::PgPool;
     25 use taler_api::{
     26     api::{
     27         TalerApi, observability::Observability, prepared::PreparedTransfer, revenue::Revenue,
     28         wire::WireGateway,
     29     },
     30     error::{ApiResult, failure, failure_code},
     31     subject::{IncomingKey, fmt_in_subject},
     32 };
     33 use taler_common::{
     34     api::{
     35         params::{History, Page},
     36         prepared::{
     37             RegistrationRequest, RegistrationResponse, SubjectFormat, TransferSubject,
     38             Unregistration,
     39         },
     40         revenue::RevenueIncomingHistory,
     41         wire::{
     42             AddIncomingRequest, AddIncomingResponse, AddKycauthRequest, AddMappedRequest,
     43             IncomingHistory, OutgoingHistory, TransferList, TransferRequest, TransferResponse,
     44             TransferState, TransferStatus,
     45         },
     46     },
     47     db::IncomingType,
     48     error_code::ErrorCode,
     49     types::{amount::Currency, payto::PaytoURI, time::TalerTimestamp},
     50 };
     51 use tokio::sync::watch::Sender;
     52 
     53 use crate::{
     54     db::{self, AddIncomingResult, Transfer, TxInAdmin},
     55     payto::{CyclosPayto, FullCyclosPayto},
     56 };
     57 
     58 pub struct CyclosApi {
     59     pub pool: sqlx::PgPool,
     60     pub currency: Currency,
     61     pub payto: FullCyclosPayto,
     62     pub in_channel: Sender<i64>,
     63     pub taler_in_channel: Sender<i64>,
     64     pub out_channel: Sender<i64>,
     65     pub taler_out_channel: Sender<i64>,
     66     pub root: CompactString,
     67     metrics: Metrics,
     68     registry: Registry,
     69 }
     70 
     71 #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
     72 struct TaskLabel {
     73     name: &'static str,
     74 }
     75 
     76 #[derive(Default)]
     77 struct Metrics {
     78     db_access: Gauge,
     79     task_execution: Family<TaskLabel, Gauge>,
     80     task_success: Family<TaskLabel, Gauge>,
     81 }
     82 
     83 impl Metrics {
     84     pub fn registry(&self) -> Registry {
     85         let mut registry = Registry::default();
     86 
     87         registry.register(
     88             "db_access",
     89             "Whether the last database metrics refresh succeeded",
     90             self.db_access.clone(),
     91         );
     92         registry.register_with_unit(
     93             "task_execution_timestamp_seconds",
     94             "Unix timestamp of the last task execution",
     95             Unit::Seconds,
     96             self.task_execution.clone(),
     97         );
     98         registry.register_with_unit(
     99             "task_success_timestamp_seconds",
    100             "Unix timestamp of the last successful task execution",
    101             Unit::Seconds,
    102             self.task_success.clone(),
    103         );
    104         registry
    105     }
    106 
    107     pub async fn sync(&self, db: &PgPool) {
    108         let result = sqlx::query_as::<_, (String, sqlx::types::Json<db::TaskStatus>)>(
    109             "SELECT key, value FROM kv WHERE key IN ('sync', 'submit')",
    110         )
    111         .fetch_all(db)
    112         .await;
    113         let success = match result {
    114             Ok(rows) => {
    115                 for name in ["sync", "submit"] {
    116                     let label = TaskLabel { name };
    117                     let status = rows.iter().find(|(key, _)| key == name).map(|(_, s)| &s.0);
    118                     if let Some(time) = status.and_then(|s| s.last_execution) {
    119                         self.task_execution
    120                             .get_or_create(&label)
    121                             .set(time.as_second());
    122                     } else {
    123                         self.task_execution.remove(&label);
    124                     }
    125                     if let Some(time) = status.and_then(|s| s.last_success) {
    126                         self.task_success
    127                             .get_or_create(&label)
    128                             .set(time.as_second());
    129                     } else {
    130                         self.task_success.remove(&label);
    131                     }
    132                 }
    133                 true
    134             }
    135             Err(_) => false,
    136         };
    137         self.db_access.set(if success { 1 } else { 0 });
    138     }
    139 }
    140 
    141 impl CyclosApi {
    142     pub fn start(
    143         pool: sqlx::PgPool,
    144         root: CompactString,
    145         payto: FullCyclosPayto,
    146         currency: Currency,
    147     ) -> Self {
    148         let in_channel = Sender::new(0);
    149         let taler_in_channel = Sender::new(0);
    150         let out_channel = Sender::new(0);
    151         let taler_out_channel = Sender::new(0);
    152 
    153         let metrics = Metrics::default();
    154 
    155         let tmp = Self {
    156             pool: pool.clone(),
    157             payto,
    158             currency,
    159             root,
    160             in_channel: in_channel.clone(),
    161             taler_in_channel: taler_in_channel.clone(),
    162             out_channel: out_channel.clone(),
    163             taler_out_channel: taler_out_channel.clone(),
    164             registry: metrics.registry(),
    165             metrics,
    166         };
    167         tokio::spawn(db::notification_listener(
    168             pool,
    169             in_channel,
    170             taler_in_channel,
    171             out_channel,
    172             taler_out_channel,
    173         ));
    174         tmp
    175     }
    176 
    177     fn parse_account(&self, uri: &PaytoURI) -> ApiResult<FullCyclosPayto> {
    178         let account = FullCyclosPayto::try_from(uri)?;
    179         if account.root != self.root {
    180             return Err(failure(
    181                 ErrorCode::GENERIC_PAYTO_URI_MALFORMED,
    182                 format!(
    183                     "wrong cyclos root, expected '{}' got '{}'",
    184                     self.root, account.root
    185                 ),
    186             ));
    187         }
    188         Ok(account)
    189     }
    190 }
    191 
    192 impl TalerApi for CyclosApi {
    193     fn currency(&self) -> Currency {
    194         self.currency
    195     }
    196 
    197     fn implementation(&self) -> &'static str {
    198         "urn:net:taler:specs:taler-cyclos:taler-rust"
    199     }
    200 }
    201 
    202 impl WireGateway for CyclosApi {
    203     async fn transfer(&self, req: TransferRequest) -> ApiResult<TransferResponse> {
    204         let creditor = self.parse_account(&req.credit_account)?;
    205         let result = db::make_transfer(
    206             &self.pool,
    207             &Transfer {
    208                 request_uid: req.request_uid,
    209                 amount: req.amount.decimal(),
    210                 exchange_base_url: req.exchange_base_url,
    211                 metadata: req.metadata,
    212                 wtid: req.wtid,
    213                 creditor_id: *creditor.id,
    214                 creditor_name: creditor.name,
    215             },
    216             &Timestamp::now(),
    217         )
    218         .await?;
    219         match result {
    220             db::TransferResult::Success { id, initiated_at } => Ok(TransferResponse {
    221                 timestamp: initiated_at.into(),
    222                 row_id: id,
    223             }),
    224             db::TransferResult::RequestUidReuse => {
    225                 Err(failure_code(ErrorCode::BANK_TRANSFER_REQUEST_UID_REUSED))
    226             }
    227             db::TransferResult::WtidReuse => {
    228                 Err(failure_code(ErrorCode::BANK_TRANSFER_WTID_REUSED))
    229             }
    230         }
    231     }
    232 
    233     async fn transfer_page(
    234         &self,
    235         page: Page,
    236         status: Option<TransferState>,
    237     ) -> ApiResult<TransferList> {
    238         Ok(TransferList {
    239             transfers: db::transfer_page(&self.pool, &status, &self.currency, &self.root, &page)
    240                 .await?,
    241             debit_account: self.payto.as_uri(),
    242         })
    243     }
    244 
    245     async fn transfer_by_id(&self, id: u64) -> ApiResult<Option<TransferStatus>> {
    246         Ok(db::transfer_by_id(&self.pool, id, &self.currency, &self.root).await?)
    247     }
    248 
    249     async fn outgoing_history(&self, params: History) -> ApiResult<OutgoingHistory> {
    250         Ok(OutgoingHistory {
    251             outgoing_transactions: db::outgoing_history(
    252                 &self.pool,
    253                 &params,
    254                 &self.currency,
    255                 &self.root,
    256                 || self.taler_out_channel.subscribe(),
    257             )
    258             .await?,
    259             debit_account: self.payto.as_uri(),
    260         })
    261     }
    262 
    263     async fn incoming_history(&self, params: History) -> ApiResult<IncomingHistory> {
    264         Ok(IncomingHistory {
    265             incoming_transactions: db::incoming_history(
    266                 &self.pool,
    267                 &params,
    268                 &self.currency,
    269                 &self.root,
    270                 || self.taler_in_channel.subscribe(),
    271             )
    272             .await?,
    273             credit_account: self.payto.as_uri(),
    274         })
    275     }
    276 
    277     async fn add_incoming_reserve(
    278         &self,
    279         req: AddIncomingRequest,
    280     ) -> ApiResult<AddIncomingResponse> {
    281         let debtor = self.parse_account(&req.debit_account)?;
    282         let res = db::register_tx_in_admin(
    283             &self.pool,
    284             &TxInAdmin {
    285                 amount: req.amount.decimal(),
    286                 subject: format!("Admin incoming {}", req.reserve_pub),
    287                 debtor_id: *debtor.id,
    288                 debtor_name: debtor.name,
    289                 metadata: IncomingKey::reserve(req.reserve_pub),
    290             },
    291             &Timestamp::now(),
    292         )
    293         .await?;
    294         match res {
    295             AddIncomingResult::Success {
    296                 row_id, valued_at, ..
    297             } => Ok(AddIncomingResponse {
    298                 row_id,
    299                 timestamp: valued_at.into(),
    300             }),
    301             AddIncomingResult::ReservePubReuse => {
    302                 Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT))
    303             }
    304             AddIncomingResult::UnknownMapping | AddIncomingResult::MappingReuse => {
    305                 unreachable!("mapping unused")
    306             }
    307         }
    308     }
    309 
    310     async fn add_incoming_kyc(&self, req: AddKycauthRequest) -> ApiResult<AddIncomingResponse> {
    311         let debtor = self.parse_account(&req.debit_account)?;
    312         let res = db::register_tx_in_admin(
    313             &self.pool,
    314             &TxInAdmin {
    315                 amount: req.amount.decimal(),
    316                 subject: format!("Admin incoming KYC:{}", req.account_pub),
    317                 debtor_id: *debtor.id,
    318                 debtor_name: debtor.name,
    319                 metadata: IncomingKey::kyc(req.account_pub),
    320             },
    321             &Timestamp::now(),
    322         )
    323         .await?;
    324         match res {
    325             AddIncomingResult::Success {
    326                 row_id, valued_at, ..
    327             } => Ok(AddIncomingResponse {
    328                 row_id,
    329                 timestamp: valued_at.into(),
    330             }),
    331             AddIncomingResult::ReservePubReuse => {
    332                 Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT))
    333             }
    334             AddIncomingResult::UnknownMapping | AddIncomingResult::MappingReuse => {
    335                 unreachable!("mapping unused")
    336             }
    337         }
    338     }
    339 
    340     async fn add_incoming_mapped(&self, req: AddMappedRequest) -> ApiResult<AddIncomingResponse> {
    341         let debtor = self.parse_account(&req.debit_account)?;
    342         let res = db::register_tx_in_admin(
    343             &self.pool,
    344             &TxInAdmin {
    345                 amount: req.amount.decimal(),
    346                 subject: format!("Admin incoming MAP:{}", req.authorization_pub),
    347                 debtor_id: *debtor.id,
    348                 debtor_name: debtor.name,
    349                 metadata: IncomingKey::map(req.authorization_pub),
    350             },
    351             &Timestamp::now(),
    352         )
    353         .await?;
    354         match res {
    355             AddIncomingResult::Success {
    356                 row_id, valued_at, ..
    357             } => Ok(AddIncomingResponse {
    358                 row_id,
    359                 timestamp: valued_at.into(),
    360             }),
    361             AddIncomingResult::ReservePubReuse => {
    362                 Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT))
    363             }
    364             AddIncomingResult::UnknownMapping => {
    365                 Err(failure_code(ErrorCode::BANK_TRANSFER_MAPPING_UNKNOWN))
    366             }
    367             AddIncomingResult::MappingReuse => {
    368                 Err(failure_code(ErrorCode::BANK_TRANSFER_MAPPING_REUSED))
    369             }
    370         }
    371     }
    372 
    373     fn support_account_check(&self) -> bool {
    374         false
    375     }
    376 }
    377 
    378 impl Revenue for CyclosApi {
    379     async fn history(&self, params: History) -> ApiResult<RevenueIncomingHistory> {
    380         Ok(RevenueIncomingHistory {
    381             incoming_transactions: db::revenue_history(
    382                 &self.pool,
    383                 &params,
    384                 &self.currency,
    385                 &self.root,
    386                 || self.in_channel.subscribe(),
    387             )
    388             .await?,
    389             credit_account: self.payto.as_uri(),
    390         })
    391     }
    392 }
    393 
    394 impl PreparedTransfer for CyclosApi {
    395     fn supported_formats(&self) -> &[SubjectFormat] {
    396         &[SubjectFormat::SIMPLE]
    397     }
    398 
    399     async fn registration(&self, req: RegistrationRequest) -> ApiResult<RegistrationResponse> {
    400         let creditor = CyclosPayto::try_from(&req.credit_account)?;
    401         if *creditor != *self.payto {
    402             return Err(failure_code(ErrorCode::BANK_UNKNOWN_CREDITOR));
    403         }
    404         match db::transfer_register(&self.pool, &req).await? {
    405             db::RegistrationResult::Success => {
    406                 let simple = TransferSubject::Simple {
    407                     credit_amount: req.credit_amount,
    408                     subject: if req.authorization_pub == req.account_pub && !req.recurrent {
    409                         fmt_in_subject(req.r#type.into(), &req.account_pub).to_string()
    410                     } else {
    411                         fmt_in_subject(IncomingType::map, &req.authorization_pub).to_string()
    412                     },
    413                 };
    414                 ApiResult::Ok(RegistrationResponse {
    415                     subjects: vec![simple],
    416                     expiration: TalerTimestamp::Never,
    417                 })
    418             }
    419             db::RegistrationResult::ReservePubReuse => {
    420                 ApiResult::Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT))
    421             }
    422         }
    423     }
    424 
    425     async fn unregistration(&self, req: Unregistration) -> ApiResult<bool> {
    426         Ok(db::transfer_unregister(&self.pool, &req).await?)
    427     }
    428 }
    429 
    430 impl Observability for CyclosApi {
    431     async fn metrics(&self) -> ApiResult<&Registry> {
    432         self.metrics.sync(&self.pool).await;
    433         Ok(&self.registry)
    434     }
    435 }
    436 
    437 #[cfg(test)]
    438 mod test {
    439     use std::sync::{
    440         LazyLock,
    441         atomic::{AtomicI64, Ordering},
    442     };
    443 
    444     use compact_str::CompactString;
    445     use jiff::Timestamp;
    446     use sqlx::{PgPool, Row as _, postgres::PgRow};
    447     use taler_api::{
    448         Serve,
    449         api::TalerRouter as _,
    450         config::{ApiCfg, AuthCfg, WireGatewayCfg},
    451         db::TypeHelper as _,
    452         subject::{IncomingKey, OutgoingSubject},
    453     };
    454     use taler_common::{
    455         api::{
    456             EddsaPublicKey,
    457             observability::Config,
    458             prepared::PreparedTransferConfig,
    459             revenue::RevenueConfig,
    460             wire::{TransferState, WireConfig},
    461         },
    462         db::IncomingType,
    463         types::{
    464             amount::{Currency, decimal},
    465             payto::{PaytoURI, payto},
    466         },
    467     };
    468     use taler_macros::db_test;
    469     use taler_test_utils::{
    470         Router,
    471         routine::{
    472             Status, admin_add_incoming_routine, in_history_routine, out_history_routine,
    473             registration_routine, revenue_routine, transfer_routine,
    474         },
    475         server::TestServer as _,
    476         tasks,
    477     };
    478 
    479     use crate::{
    480         build_router,
    481         config::ServeCfg,
    482         db::{self, TxIn, TxOutKind},
    483         payto::{FullCyclosPayto, cyclos_payto},
    484     };
    485 
    486     static PAYTO: LazyLock<FullCyclosPayto> = LazyLock::new(|| {
    487         cyclos_payto("payto://cyclos/localhost/7762070814178012479?receiver-name=Smith")
    488     });
    489     static EXCHANGE: LazyLock<PaytoURI> = LazyLock::new(|| PAYTO.as_uri());
    490     static UNKNOWN: LazyLock<PaytoURI> = LazyLock::new(|| {
    491         payto("payto://cyclos/localhost/7762070814178012478?receiver-name=Unknown")
    492     });
    493 
    494     async fn setup(pool: &PgPool) -> Router {
    495         let cfg = ServeCfg {
    496             payto: PAYTO.clone(),
    497             root: CompactString::const_new("localhost"),
    498             currency: Currency::TEST,
    499             serve: Serve::Systemd,
    500             wire_gateway: Some(WireGatewayCfg {
    501                 auth: AuthCfg::None,
    502                 enable_admin_endpoints: true,
    503             }),
    504             revenue: Some(ApiCfg {
    505                 auth: AuthCfg::None,
    506             }),
    507             observability: Some(ApiCfg {
    508                 auth: AuthCfg::None,
    509             }),
    510         };
    511         build_router(&cfg, pool.clone()).await.finalize()
    512     }
    513 
    514     #[db_test]
    515     async fn config(pool: PgPool) {
    516         let server = setup(&pool).await;
    517         server
    518             .get("/taler-wire-gateway/config")
    519             .await
    520             .assert_ok_json::<WireConfig>();
    521         server
    522             .get("/taler-prepared-transfer/config")
    523             .await
    524             .assert_ok_json::<PreparedTransferConfig>();
    525         server
    526             .get("/taler-revenue/config")
    527             .await
    528             .assert_ok_json::<RevenueConfig>();
    529         server
    530             .get("/taler-observability/config")
    531             .await
    532             .assert_ok_json::<Config>();
    533         server.get("/taler-observability/metrics").await.assert_ok();
    534     }
    535 
    536     #[db_test]
    537     async fn transfer(pool: PgPool) {
    538         let server = setup(&pool).await;
    539         transfer_routine(
    540             &server.prefix("/taler-wire-gateway"),
    541             TransferState::pending,
    542             &EXCHANGE,
    543         )
    544         .await;
    545     }
    546 
    547     #[db_test]
    548     async fn reject_wrong_root(pool: PgPool) {
    549         use taler_common::{
    550             api::{
    551                 HashCode, ShortHashCode,
    552                 wire::{AddIncomingRequest, AddKycauthRequest, AddMappedRequest, TransferRequest},
    553             },
    554             error_code::ErrorCode,
    555             types::{amount::amount, url},
    556         };
    557 
    558         let server = setup(&pool).await;
    559         let wrong_root =
    560             payto("payto://cyclos/other.example/7762070814178012479?receiver-name=Smith");
    561 
    562         server
    563             .post("/taler-wire-gateway/transfer")
    564             .json(TransferRequest {
    565                 request_uid: HashCode::rand(),
    566                 amount: amount("TEST:1"),
    567                 exchange_base_url: url("https://exchange.example/"),
    568                 wtid: ShortHashCode::rand(),
    569                 credit_account: wrong_root.clone(),
    570                 metadata: None,
    571             })
    572             .await
    573             .assert_error(ErrorCode::GENERIC_PAYTO_URI_MALFORMED);
    574 
    575         server
    576             .post("/taler-wire-gateway/admin/add-incoming")
    577             .json(AddIncomingRequest {
    578                 amount: amount("TEST:1"),
    579                 reserve_pub: EddsaPublicKey::rand(),
    580                 debit_account: wrong_root.clone(),
    581             })
    582             .await
    583             .assert_error(ErrorCode::GENERIC_PAYTO_URI_MALFORMED);
    584 
    585         server
    586             .post("/taler-wire-gateway/admin/add-kycauth")
    587             .json(AddKycauthRequest {
    588                 amount: amount("TEST:1"),
    589                 account_pub: EddsaPublicKey::rand(),
    590                 debit_account: wrong_root.clone(),
    591             })
    592             .await
    593             .assert_error(ErrorCode::GENERIC_PAYTO_URI_MALFORMED);
    594 
    595         server
    596             .post("/taler-wire-gateway/admin/add-mapped")
    597             .json(AddMappedRequest {
    598                 amount: amount("TEST:1"),
    599                 authorization_pub: EddsaPublicKey::rand(),
    600                 debit_account: wrong_root,
    601             })
    602             .await
    603             .assert_error(ErrorCode::GENERIC_PAYTO_URI_MALFORMED);
    604     }
    605 
    606     static CODE: AtomicI64 = AtomicI64::new(0);
    607 
    608     async fn r#in(db: &PgPool, subject: Option<IncomingKey>) {
    609         let now = Timestamp::now();
    610         db::register_tx_in(
    611             &mut db.acquire().await.unwrap(),
    612             &TxIn {
    613                 transfer_id: CODE.fetch_add(1, Ordering::Relaxed),
    614                 tx_id: None,
    615                 amount: decimal("10"),
    616                 subject: "subject".to_owned(),
    617                 debtor_id: 31000163100000000,
    618                 debtor_name: "Name".into(),
    619                 valued_at: Timestamp::now(),
    620             },
    621             &subject,
    622             &now,
    623         )
    624         .await
    625         .unwrap();
    626     }
    627 
    628     async fn in_malformed(db: &PgPool) {
    629         r#in(db, None).await
    630     }
    631 
    632     async fn in_talerable(db: &PgPool) {
    633         r#in(db, Some(IncomingKey::reserve(EddsaPublicKey::rand()))).await
    634     }
    635 
    636     async fn out(db: &PgPool, kind: &TxOutKind) {
    637         let i = CODE.fetch_add(1, Ordering::Relaxed);
    638         let now = Timestamp::now();
    639         db::register_tx_out(
    640             &mut db.acquire().await.unwrap(),
    641             &db::TxOut {
    642                 transfer_id: i,
    643                 tx_id: if i % 2 == 0 { Some(i % 2) } else { None },
    644                 amount: decimal("10"),
    645                 subject: "subject".to_owned(),
    646                 creditor_id: 31000163100000000,
    647                 creditor_name: "Name".into(),
    648                 valued_at: now,
    649             },
    650             kind,
    651             &now,
    652         )
    653         .await
    654         .unwrap();
    655     }
    656 
    657     async fn out_talerable(db: &PgPool) {
    658         out(db, &TxOutKind::Talerable(OutgoingSubject::rand())).await
    659     }
    660 
    661     async fn out_bounce(db: &PgPool) {
    662         out(db, &TxOutKind::Bounce(CODE.load(Ordering::Relaxed))).await
    663     }
    664 
    665     async fn out_malformed(db: &PgPool) {
    666         out(db, &TxOutKind::Simple).await
    667     }
    668 
    669     #[db_test]
    670     async fn outgoing_history(db: PgPool) {
    671         let db = &db;
    672         let server = setup(db).await;
    673 
    674         out_history_routine(
    675             &server.prefix("/taler-wire-gateway"),
    676             tasks!({ out_talerable(db).await }),
    677             tasks!(
    678                 { out_bounce(db).await },
    679                 { out_malformed(db).await },
    680                 { in_malformed(db).await },
    681                 { in_talerable(db).await }
    682             ),
    683         )
    684         .await;
    685     }
    686 
    687     #[db_test]
    688     async fn admin_add_incoming(db: PgPool) {
    689         let server = setup(&db).await;
    690         admin_add_incoming_routine(
    691             &server.prefix("/taler-wire-gateway"),
    692             &server.prefix("/taler-prepared-transfer"),
    693             &EXCHANGE,
    694             &EXCHANGE,
    695         )
    696         .await;
    697     }
    698 
    699     #[db_test]
    700     async fn in_history(db: PgPool) {
    701         let db = &db;
    702         let server = setup(db).await;
    703         in_history_routine(
    704             &server.prefix("/taler-wire-gateway"),
    705             &server.prefix("/taler-prepared-transfer"),
    706             &EXCHANGE,
    707             &EXCHANGE,
    708             tasks!({ in_talerable(db).await }),
    709             tasks!(
    710                 { out_malformed(db).await },
    711                 { out_talerable(db).await },
    712                 { out_bounce(db).await },
    713                 { in_malformed(db).await }
    714             ),
    715         )
    716         .await;
    717     }
    718 
    719     #[db_test]
    720     async fn revenue(db: PgPool) {
    721         let db = &db;
    722         let server = setup(db).await;
    723         revenue_routine(
    724             &server.prefix("/taler-wire-gateway"),
    725             &server.prefix("/taler-revenue"),
    726             &EXCHANGE,
    727             tasks!({ in_malformed(db).await }, { in_talerable(db).await },),
    728             tasks!({ out_malformed(db).await }, { out_talerable(db).await }, {
    729                 out_bounce(db).await
    730             }),
    731         )
    732         .await;
    733     }
    734 
    735     async fn check_in(pool: &PgPool) -> Vec<Status> {
    736         sqlx::query(
    737             "
    738             SELECT pending_recurrent_in.authorization_pub IS NOT NULL, bounced.tx_in_id IS NOT NULL, type, metadata
    739             FROM tx_in
    740                 LEFT JOIN taler_in USING (tx_in_id)
    741                 LEFT JOIN pending_recurrent_in USING (tx_in_id)
    742                 LEFT JOIN bounced USING (tx_in_id)
    743             ORDER BY tx_in.tx_in_id
    744         ",
    745         )
    746         .try_map(|r: PgRow| {
    747             Ok(
    748                 if r.try_get_flag(0)? {
    749                     Status::Pending
    750                 } else if r.try_get_flag(1)? {
    751                     Status::Bounced
    752                 } else {
    753                     match r.try_get(2)? {
    754                         None => Status::Simple,
    755                         Some(IncomingType::reserve) => Status::Reserve(r.try_get(3)?),
    756                         Some(IncomingType::kyc) => Status::Kyc(r.try_get(3)?),
    757                         Some(e) => unreachable!("{e:?}")
    758                     }
    759                 }
    760             )
    761         })
    762         .fetch_all(pool)
    763         .await
    764         .unwrap()
    765     }
    766 
    767     #[db_test]
    768     async fn registration(pool: PgPool) {
    769         let server = setup(&pool).await;
    770         registration_routine(
    771             &server.prefix("/taler-wire-gateway"),
    772             &server.prefix("/taler-prepared-transfer"),
    773             &EXCHANGE,
    774             &EXCHANGE,
    775             &UNKNOWN,
    776             true,
    777             || check_in(&pool),
    778         )
    779         .await;
    780     }
    781 }