taler-rust

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

db.rs (54431B)


      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 std::fmt::Display;
     18 
     19 use compact_str::CompactString;
     20 use jiff::Timestamp;
     21 use serde::{Deserialize, Serialize, de::DeserializeOwned};
     22 use sqlx::{PgConnection, PgPool, QueryBuilder, Row, postgres::PgRow};
     23 use taler_api::{
     24     db::{BindHelper, TypeHelper, history, page},
     25     serialized,
     26     subject::{IncomingKey, OutgoingSubject, fmt_out_subject},
     27 };
     28 use taler_common::{
     29     api::{
     30         HashCode, ShortHashCode,
     31         params::{History, Page},
     32         prepared::{RegistrationRequest, Unregistration},
     33         revenue::RevenueIncomingBankTransaction,
     34         wire::{
     35             IncomingBankTransaction, OutgoingBankTransaction, TransferListStatus, TransferState,
     36             TransferStatus,
     37         },
     38     },
     39     config::Config,
     40     db::IncomingType,
     41     types::{
     42         amount::{Currency, Decimal},
     43         payto::{PaytoImpl as _, PaytoURI},
     44     },
     45 };
     46 use tokio::sync::watch::{Receiver, Sender};
     47 use url::Url;
     48 
     49 use crate::{
     50     config::parse_db_cfg,
     51     payto::{CyclosAccount, CyclosId, FullCyclosPayto},
     52 };
     53 
     54 const SCHEMA: &str = "cyclos";
     55 
     56 pub async fn pool(cfg: &Config) -> anyhow::Result<PgPool> {
     57     let db = parse_db_cfg(cfg)?;
     58     let pool = taler_common::db::pool(db.cfg, SCHEMA).await?;
     59     Ok(pool)
     60 }
     61 
     62 pub async fn dbinit(cfg: &Config, reset: bool) -> anyhow::Result<PgPool> {
     63     let db_cfg = parse_db_cfg(cfg)?;
     64     let pool = taler_common::db::pool(db_cfg.cfg, SCHEMA).await?;
     65     let mut db = pool.acquire().await?;
     66     taler_common::db::dbinit(&mut db, db_cfg.sql_dir.as_ref(), SCHEMA, reset).await?;
     67     Ok(pool)
     68 }
     69 
     70 pub async fn notification_listener(
     71     pool: PgPool,
     72     in_channel: Sender<i64>,
     73     taler_in_channel: Sender<i64>,
     74     out_channel: Sender<i64>,
     75     taler_out_channel: Sender<i64>,
     76 ) {
     77     taler_api::notification::notification_listener!(&pool,
     78         "tx_in" => (row_id: i64) {
     79             in_channel.send_replace(row_id);
     80         },
     81         "taler_in" => (row_id: i64) {
     82             taler_in_channel.send_replace(row_id);
     83         },
     84         "tx_out" => (row_id: i64) {
     85             out_channel.send_replace(row_id);
     86         },
     87         "taler_out" => (row_id: i64) {
     88             taler_out_channel.send_replace(row_id);
     89         }
     90     )
     91 }
     92 
     93 #[derive(Debug, Clone)]
     94 pub struct TxIn {
     95     pub transfer_id: i64,
     96     pub tx_id: Option<i64>,
     97     pub amount: Decimal,
     98     pub subject: String,
     99     pub debtor_id: i64,
    100     pub debtor_name: CompactString,
    101     pub valued_at: Timestamp,
    102 }
    103 
    104 impl Display for TxIn {
    105     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    106         let Self {
    107             transfer_id,
    108             tx_id,
    109             amount,
    110             subject,
    111             valued_at,
    112             debtor_id,
    113             debtor_name,
    114         } = self;
    115         let tx_id = match tx_id {
    116             Some(id) => format_args!(":{}", *id),
    117             None => format_args!(""),
    118         };
    119         write!(
    120             f,
    121             "{valued_at} {transfer_id}{tx_id} {amount} ({debtor_id} {debtor_name}) '{subject}'"
    122         )
    123     }
    124 }
    125 
    126 #[derive(Debug, Clone)]
    127 pub struct TxOut {
    128     pub transfer_id: i64,
    129     pub tx_id: Option<i64>,
    130     pub amount: Decimal,
    131     pub subject: String,
    132     pub creditor_id: i64,
    133     pub creditor_name: CompactString,
    134     pub valued_at: Timestamp,
    135 }
    136 
    137 impl Display for TxOut {
    138     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    139         let Self {
    140             transfer_id,
    141             tx_id,
    142             amount,
    143             subject,
    144             creditor_id,
    145             creditor_name,
    146             valued_at,
    147         } = self;
    148         let tx_id = match tx_id {
    149             Some(id) => format_args!(":{}", *id),
    150             None => format_args!(""),
    151         };
    152         write!(
    153             f,
    154             "{valued_at} {transfer_id}{tx_id} {amount} ({creditor_id} {creditor_name}) '{subject}'"
    155         )
    156     }
    157 }
    158 
    159 #[derive(Debug, PartialEq, Eq)]
    160 pub struct Initiated {
    161     pub id: i64,
    162     pub amount: Decimal,
    163     pub subject: String,
    164     pub creditor_id: i64,
    165     pub creditor_name: CompactString,
    166 }
    167 
    168 impl Display for Initiated {
    169     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    170         let Self {
    171             id,
    172             amount,
    173             subject,
    174             creditor_id,
    175             creditor_name,
    176         } = self;
    177         write!(
    178             f,
    179             "{id} {amount} ({creditor_id} {creditor_name}) '{subject}'"
    180         )
    181     }
    182 }
    183 
    184 #[derive(Debug, Clone)]
    185 pub struct TxInAdmin {
    186     pub amount: Decimal,
    187     pub subject: String,
    188     pub debtor_id: i64,
    189     pub debtor_name: CompactString,
    190     pub metadata: IncomingKey,
    191 }
    192 
    193 #[derive(Debug, PartialEq, Eq)]
    194 pub enum AddIncomingResult {
    195     Success {
    196         new: bool,
    197         pending: bool,
    198         row_id: u64,
    199         valued_at: Timestamp,
    200     },
    201     ReservePubReuse,
    202     UnknownMapping,
    203     MappingReuse,
    204 }
    205 
    206 /// Lock the database for worker execution
    207 pub async fn worker_lock(e: &mut PgConnection) -> sqlx::Result<bool> {
    208     sqlx::query("SELECT pg_try_advisory_lock(42)")
    209         .try_map(|r: PgRow| r.try_get(0))
    210         .fetch_one(e)
    211         .await
    212 }
    213 
    214 pub async fn register_tx_in_admin(
    215     db: &PgPool,
    216     tx: &TxInAdmin,
    217     now: &Timestamp,
    218 ) -> sqlx::Result<AddIncomingResult> {
    219     serialized!(
    220         sqlx::query(
    221             "
    222             SELECT out_reserve_pub_reuse, out_mapping_reuse, out_unknown_mapping, out_tx_row_id, out_valued_at, out_new, out_pending
    223             FROM register_tx_in(NULL, NULL, $1, $2, $3, $4, $5, $6, $7, $5)
    224         ",
    225         )
    226         .bind(tx.amount)
    227         .bind(&tx.subject)
    228         .bind(tx.debtor_id)
    229         .bind(&tx.debtor_name)
    230         .bind_timestamp(now)
    231         .bind(tx.metadata.ty)
    232         .bind(tx.metadata.key)
    233        .try_map(|r: PgRow| {
    234             Ok(if r.try_get_flag(0)? {
    235                 AddIncomingResult::ReservePubReuse
    236             } else if r.try_get_flag(1)? {
    237                 AddIncomingResult::MappingReuse
    238             } else if r.try_get_flag(2)? {
    239                 AddIncomingResult::UnknownMapping
    240             } else {
    241                 AddIncomingResult::Success {
    242                     row_id: r.try_get_u64(3)?,
    243                     valued_at: r.try_get_timestamp(4)?,
    244                     new: r.try_get(5)?,
    245                     pending: r.try_get(6)?
    246                 }
    247             })
    248         })
    249         .fetch_one(db)
    250     )
    251 }
    252 
    253 pub async fn register_tx_in(
    254     db: &mut PgConnection,
    255     tx: &TxIn,
    256     subject: &Option<IncomingKey>,
    257     now: &Timestamp,
    258 ) -> sqlx::Result<AddIncomingResult> {
    259     serialized!(
    260         sqlx::query(
    261             "
    262             SELECT out_reserve_pub_reuse, out_mapping_reuse, out_unknown_mapping, out_tx_row_id, out_valued_at, out_new, out_pending
    263             FROM register_tx_in($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
    264         ",
    265         )
    266         .bind(tx.transfer_id)
    267         .bind(tx.tx_id)
    268         .bind(tx.amount)
    269         .bind(&tx.subject)
    270         .bind(tx.debtor_id)
    271         .bind(&tx.debtor_name)
    272         .bind(tx.valued_at.as_microsecond())
    273         .bind(subject.as_ref().map(|it| it.ty))
    274         .bind(subject.as_ref().map(|it| it.key))
    275         .bind(now.as_microsecond())
    276         .try_map(|r: PgRow| {
    277             Ok(if r.try_get_flag(0)? {
    278                 AddIncomingResult::ReservePubReuse
    279             } else if r.try_get_flag(1)? {
    280                 AddIncomingResult::MappingReuse
    281             } else if r.try_get_flag(2)? {
    282                 AddIncomingResult::UnknownMapping
    283             } else {
    284                 AddIncomingResult::Success {
    285                     row_id: r.try_get_u64(3)?,
    286                     valued_at: r.try_get_timestamp(4)?,
    287                     new: r.try_get(5)?,
    288                     pending: r.try_get(6)?
    289                 }
    290             })
    291         })
    292         .fetch_one(&mut *db)
    293     )
    294 }
    295 
    296 #[derive(Debug)]
    297 pub enum TxOutKind {
    298     Simple,
    299     Bounce(i64),
    300     Talerable(OutgoingSubject),
    301 }
    302 
    303 #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
    304 #[allow(non_camel_case_types)]
    305 #[sqlx(type_name = "register_result")]
    306 pub enum RegisterResult {
    307     /// Already registered
    308     idempotent,
    309     /// Initiated transaction
    310     known,
    311     /// Recovered unknown outgoing transaction
    312     recovered,
    313 }
    314 
    315 #[derive(Debug, PartialEq, Eq)]
    316 pub struct AddOutgoingResult {
    317     pub result: RegisterResult,
    318     pub row_id: i64,
    319 }
    320 
    321 pub async fn register_tx_out(
    322     db: &mut PgConnection,
    323     tx: &TxOut,
    324     kind: &TxOutKind,
    325     now: &Timestamp,
    326 ) -> sqlx::Result<AddOutgoingResult> {
    327     serialized!({
    328         let query = sqlx::query(
    329             "
    330                 SELECT out_result, out_tx_row_id
    331                 FROM register_tx_out($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
    332             ",
    333         )
    334         .bind(tx.transfer_id)
    335         .bind(tx.tx_id)
    336         .bind(tx.amount)
    337         .bind(&tx.subject)
    338         .bind(tx.creditor_id)
    339         .bind(&tx.creditor_name)
    340         .bind_timestamp(&tx.valued_at);
    341         let query = match kind {
    342             TxOutKind::Simple => query
    343                 .bind(None::<&[u8]>)
    344                 .bind(None::<&str>)
    345                 .bind(None::<&str>)
    346                 .bind(None::<i64>),
    347             TxOutKind::Bounce(bounced) => query
    348                 .bind(None::<&[u8]>)
    349                 .bind(None::<&str>)
    350                 .bind(None::<&str>)
    351                 .bind(*bounced),
    352             TxOutKind::Talerable(subject) => query
    353                 .bind(subject.wtid)
    354                 .bind(subject.exchange_base_url.as_str())
    355                 .bind(&subject.metadata)
    356                 .bind(None::<i64>),
    357         };
    358         query
    359             .bind_timestamp(now)
    360             .try_map(|r: PgRow| {
    361                 Ok(AddOutgoingResult {
    362                     result: r.try_get(0)?,
    363                     row_id: r.try_get(1)?,
    364                 })
    365             })
    366             .fetch_one(&mut *db)
    367     })
    368 }
    369 
    370 #[derive(Debug, PartialEq, Eq)]
    371 pub enum TransferResult {
    372     Success { id: u64, initiated_at: Timestamp },
    373     RequestUidReuse,
    374     WtidReuse,
    375 }
    376 
    377 #[derive(Debug, Clone)]
    378 pub struct Transfer {
    379     pub request_uid: HashCode,
    380     pub amount: Decimal,
    381     pub exchange_base_url: Url,
    382     pub metadata: Option<CompactString>,
    383     pub wtid: ShortHashCode,
    384     pub creditor_id: i64,
    385     pub creditor_name: CompactString,
    386 }
    387 
    388 pub async fn make_transfer(
    389     db: &PgPool,
    390     tx: &Transfer,
    391     now: &Timestamp,
    392 ) -> sqlx::Result<TransferResult> {
    393     let subject = fmt_out_subject(&tx.wtid, &tx.exchange_base_url, tx.metadata.as_deref());
    394     serialized!(
    395         sqlx::query(
    396             "
    397                 SELECT out_request_uid_reuse, out_wtid_reuse, out_initiated_row_id, out_initiated_at
    398                 FROM taler_transfer($1, $2, $3, $4, $5, $6, $7, $8, $9)
    399             ",
    400         )
    401         .bind(tx.request_uid)
    402         .bind(tx.wtid)
    403         .bind(&subject)
    404         .bind(tx.amount)
    405         .bind(tx.exchange_base_url.as_str())
    406         .bind(&tx.metadata)
    407         .bind(tx.creditor_id)
    408         .bind(&tx.creditor_name)
    409         .bind_timestamp(now)
    410         .try_map(|r: PgRow| {
    411             Ok(if r.try_get_flag(0)? {
    412                 TransferResult::RequestUidReuse
    413             } else if r.try_get_flag(1)? {
    414                 TransferResult::WtidReuse
    415             } else {
    416                 TransferResult::Success {
    417                     id: r.try_get_u64(2)?,
    418                     initiated_at: r.try_get_timestamp(3)?,
    419                 }
    420             })
    421         })
    422         .fetch_one(db)
    423     )
    424 }
    425 
    426 #[derive(Debug, PartialEq, Eq)]
    427 pub struct BounceResult {
    428     pub tx_id: u64,
    429     pub tx_new: bool,
    430 }
    431 
    432 pub async fn register_bounced_tx_in(
    433     db: &mut PgConnection,
    434     tx: &TxIn,
    435     chargeback_id: i64,
    436     reason: &str,
    437     now: &Timestamp,
    438 ) -> sqlx::Result<BounceResult> {
    439     serialized!(
    440         sqlx::query(
    441             "
    442                 SELECT out_tx_row_id, out_tx_new
    443                 FROM register_bounced_tx_in($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
    444             ",
    445         )
    446         .bind(tx.transfer_id)
    447         .bind(tx.tx_id)
    448         .bind(tx.amount)
    449         .bind(&tx.subject)
    450         .bind(tx.debtor_id)
    451         .bind(&tx.debtor_name)
    452         .bind_timestamp(&tx.valued_at)
    453         .bind(chargeback_id)
    454         .bind(reason)
    455         .bind_timestamp(now)
    456         .try_map(|r: PgRow| {
    457             Ok(BounceResult {
    458                 tx_id: r.try_get_u64(0)?,
    459                 tx_new: r.try_get(1)?,
    460             })
    461         })
    462         .fetch_one(&mut *db)
    463     )
    464 }
    465 
    466 pub async fn transfer_page(
    467     db: &PgPool,
    468     status: &Option<TransferState>,
    469     currency: &Currency,
    470     root: &CompactString,
    471     params: &Page,
    472 ) -> sqlx::Result<Vec<TransferListStatus>> {
    473     page(
    474         db,
    475         params,
    476         "initiated_id",
    477         || {
    478             let mut builder = QueryBuilder::new(
    479                 "
    480                     SELECT
    481                         initiated_id,
    482                         status,
    483                         amount,
    484                         credit_account,
    485                         credit_name,
    486                         initiated_at
    487                     FROM transfer
    488                     JOIN initiated USING (initiated_id)
    489                     WHERE
    490                 ",
    491             );
    492             if let Some(status) = status {
    493                 builder.push(" status = ").push_bind(status).push(" AND ");
    494             }
    495             builder
    496         },
    497         |r: PgRow| {
    498             Ok(TransferListStatus {
    499                 row_id: r.try_get_u64(0)?,
    500                 status: r.try_get(1)?,
    501                 amount: r.try_get_amount(2, currency)?,
    502                 credit_account: r.try_get_cyclos_fullpaytouri(3, 4, root)?,
    503                 timestamp: r.try_get_timestamp(5)?.into(),
    504             })
    505         },
    506     )
    507     .await
    508 }
    509 
    510 pub async fn outgoing_history(
    511     db: &PgPool,
    512     params: &History,
    513     currency: &Currency,
    514     root: &CompactString,
    515     listen: impl FnOnce() -> Receiver<i64>,
    516 ) -> sqlx::Result<Vec<OutgoingBankTransaction>> {
    517     history(
    518         db,
    519         "tx_out_id",
    520         params,
    521         listen,
    522         || {
    523             QueryBuilder::new(
    524                 "
    525                 SELECT
    526                     tx_out_id,
    527                     amount,
    528                     credit_account,
    529                     credit_name,
    530                     valued_at,
    531                     exchange_base_url,
    532                     metadata,
    533                     wtid
    534                 FROM taler_out
    535                 JOIN tx_out USING (tx_out_id)
    536                 WHERE
    537             ",
    538             )
    539         },
    540         |r: PgRow| {
    541             Ok(OutgoingBankTransaction {
    542                 row_id: r.try_get_u64(0)?,
    543                 amount: r.try_get_amount(1, currency)?,
    544                 debit_fee: None,
    545                 credit_account: r.try_get_cyclos_fullpaytouri(2, 3, root)?,
    546                 date: r.try_get_timestamp(4)?.into(),
    547                 exchange_base_url: r.try_get_url(5)?,
    548                 metadata: r.try_get(6)?,
    549                 wtid: r.try_get(7)?,
    550             })
    551         },
    552     )
    553     .await
    554 }
    555 
    556 pub async fn incoming_history(
    557     db: &PgPool,
    558     params: &History,
    559     currency: &Currency,
    560     root: &CompactString,
    561     listen: impl FnOnce() -> Receiver<i64>,
    562 ) -> sqlx::Result<Vec<IncomingBankTransaction>> {
    563     history(
    564         db,
    565         "taler_in_id",
    566         params,
    567         listen,
    568         || {
    569             QueryBuilder::new(
    570                 "
    571                 SELECT
    572                     type,
    573                     taler_in_id,
    574                     amount,
    575                     debit_account,
    576                     debit_name,
    577                     valued_at,
    578                     metadata,
    579                     authorization_pub,
    580                     authorization_sig
    581                 FROM taler_in
    582                 JOIN tx_in USING (tx_in_id)
    583                 WHERE
    584             ",
    585             )
    586         },
    587         |r: PgRow| {
    588             Ok(match r.try_get(0)? {
    589                 IncomingType::reserve => IncomingBankTransaction::Reserve {
    590                     row_id: r.try_get_u64(1)?,
    591                     amount: r.try_get_amount(2, currency)?,
    592                     credit_fee: None,
    593                     debit_account: r.try_get_cyclos_fullpaytouri(3, 4, root)?,
    594                     date: r.try_get_timestamp(5)?.into(),
    595                     reserve_pub: r.try_get(6)?,
    596                     authorization_pub: r.try_get(7)?,
    597                     authorization_sig: r.try_get(8)?,
    598                 },
    599                 IncomingType::kyc => IncomingBankTransaction::Kyc {
    600                     row_id: r.try_get_u64(1)?,
    601                     amount: r.try_get_amount(2, currency)?,
    602                     credit_fee: None,
    603                     debit_account: r.try_get_cyclos_fullpaytouri(3, 4, root)?,
    604                     date: r.try_get_timestamp(5)?.into(),
    605                     account_pub: r.try_get(6)?,
    606                     authorization_pub: r.try_get(7)?,
    607                     authorization_sig: r.try_get(8)?,
    608                 },
    609                 IncomingType::map => unimplemented!("MAP are never listed in the history"),
    610             })
    611         },
    612     )
    613     .await
    614 }
    615 
    616 pub async fn revenue_history(
    617     db: &PgPool,
    618     params: &History,
    619     currency: &Currency,
    620     root: &CompactString,
    621     listen: impl FnOnce() -> Receiver<i64>,
    622 ) -> sqlx::Result<Vec<RevenueIncomingBankTransaction>> {
    623     history(
    624         db,
    625         "tx_in_id",
    626         params,
    627         listen,
    628         || {
    629             QueryBuilder::new(
    630                 "
    631                 SELECT
    632                     tx_in_id,
    633                     valued_at,
    634                     amount,
    635                     debit_account,
    636                     debit_name,
    637                     subject
    638                 FROM tx_in
    639                 WHERE
    640             ",
    641             )
    642         },
    643         |r: PgRow| {
    644             Ok(RevenueIncomingBankTransaction {
    645                 row_id: r.try_get_u64(0)?,
    646                 date: r.try_get_timestamp(1)?.into(),
    647                 amount: r.try_get_amount(2, currency)?,
    648                 credit_fee: None,
    649                 debit_account: r.try_get_cyclos_fullpaytouri(3, 4, root)?,
    650                 subject: r.try_get(5)?,
    651             })
    652         },
    653     )
    654     .await
    655 }
    656 
    657 pub async fn transfer_by_id(
    658     db: &PgPool,
    659     id: u64,
    660     currency: &Currency,
    661     root: &CompactString,
    662 ) -> sqlx::Result<Option<TransferStatus>> {
    663     serialized!(
    664         sqlx::query(
    665             "
    666                 SELECT
    667                     status,
    668                     status_msg,
    669                     amount,
    670                     exchange_base_url,
    671                     metadata,
    672                     wtid,
    673                     credit_account,
    674                     credit_name,
    675                     initiated_at
    676                 FROM transfer
    677                 JOIN initiated USING (initiated_id)
    678                 WHERE initiated_id = $1
    679             ",
    680         )
    681         .bind(id as i64)
    682         .try_map(|r: PgRow| {
    683             Ok(TransferStatus {
    684                 status: r.try_get(0)?,
    685                 status_msg: r.try_get(1)?,
    686                 amount: r.try_get_amount(2, currency)?,
    687                 exchange_base_url: r.try_get(3)?,
    688                 metadata: r.try_get(4)?,
    689                 wtid: r.try_get(5)?,
    690                 credit_account: r.try_get_cyclos_fullpaytouri(6, 7, root)?,
    691                 timestamp: r.try_get_timestamp(8)?.into(),
    692             })
    693         })
    694         .fetch_optional(db)
    695     )
    696 }
    697 
    698 #[derive(Debug, PartialEq, Eq)]
    699 pub struct PendingBounce {
    700     pub tx_in_id: i64,
    701     pub transfer_id: i64,
    702     pub reason: String,
    703 }
    704 
    705 /** Get a batch of cancelled incoming transactions waiting to be charged back */
    706 pub async fn pending_bounces(db: &mut PgConnection) -> sqlx::Result<Vec<PendingBounce>> {
    707     serialized!(
    708         sqlx::query(
    709             "
    710             SELECT bounced.tx_in_id, tx_in.transfer_id, bounced.reason
    711             FROM bounced
    712             JOIN tx_in USING (tx_in_id)
    713             WHERE bounced.chargeback_id IS NULL
    714                 AND tx_in.transfer_id IS NOT NULL
    715             ORDER BY bounced.tx_in_id ASC
    716             LIMIT 100
    717         ",
    718         )
    719         .try_map(|r: PgRow| {
    720             Ok(PendingBounce {
    721                 tx_in_id: r.try_get(0)?,
    722                 transfer_id: r.try_get(1)?,
    723                 reason: r.try_get(2)?,
    724             })
    725         })
    726         .fetch_all(&mut *db)
    727     )
    728 }
    729 
    730 /** Record the Cyclos chargeback id for a pending bounce */
    731 pub async fn bounce_submit_success(
    732     db: &mut PgConnection,
    733     tx_in_id: i64,
    734     chargeback_id: i64,
    735 ) -> sqlx::Result<()> {
    736     serialized!(
    737         sqlx::query("UPDATE bounced SET chargeback_id = $2 WHERE tx_in_id = $1")
    738             .bind(tx_in_id)
    739             .bind(chargeback_id)
    740             .execute(&mut *db)
    741     )?;
    742     Ok(())
    743 }
    744 
    745 /** Remove an unsubmitted bounce that Cyclos reports cannot be charged back */
    746 pub async fn bounce_drop(db: &mut PgConnection, tx_in_id: i64) -> sqlx::Result<()> {
    747     serialized!(
    748         sqlx::query("DELETE FROM bounced WHERE tx_in_id = $1 AND chargeback_id IS NULL")
    749             .bind(tx_in_id)
    750             .execute(&mut *db)
    751     )?;
    752     Ok(())
    753 }
    754 
    755 /** Get a batch of pending initiated transactions not attempted since [start] */
    756 pub async fn pending_batch(
    757     db: &mut PgConnection,
    758     start: &Timestamp,
    759 ) -> sqlx::Result<Vec<Initiated>> {
    760     serialized!(
    761         sqlx::query(
    762             "
    763             SELECT initiated_id, amount, subject, credit_account, credit_name
    764             FROM initiated
    765             WHERE tx_id IS NULL
    766                 AND status='pending'
    767                 AND (last_submitted IS NULL OR last_submitted < $1)
    768             LIMIT 100
    769         ",
    770         )
    771         .bind_timestamp(start)
    772         .try_map(|r: PgRow| {
    773             Ok(Initiated {
    774                 id: r.try_get(0)?,
    775                 amount: r.try_get(1)?,
    776                 subject: r.try_get(2)?,
    777                 creditor_id: r.try_get(3)?,
    778                 creditor_name: r.try_get(4)?,
    779             })
    780         })
    781         .fetch_all(&mut *db)
    782     )
    783 }
    784 
    785 /** Update status of a successful submitted initiated transaction */
    786 pub async fn initiated_submit_success(
    787     db: &mut PgConnection,
    788     initiated_id: i64,
    789     timestamp: &Timestamp,
    790     tx_id: i64,
    791 ) -> sqlx::Result<()> {
    792     serialized!(
    793         sqlx::query(
    794             "
    795                 UPDATE initiated
    796                 SET status='pending', submission_counter=submission_counter+1, last_submitted=$1, tx_id=$2
    797                 WHERE initiated_id=$3
    798             "
    799         )
    800         .bind_timestamp(timestamp)
    801         .bind(tx_id)
    802         .bind(initiated_id)
    803         .execute(&mut *db)
    804     )?;
    805     Ok(())
    806 }
    807 
    808 /** Update status of a permanently failed initiated transaction */
    809 pub async fn initiated_submit_permanent_failure(
    810     db: &mut PgConnection,
    811     initiated_id: i64,
    812     msg: &str,
    813 ) -> sqlx::Result<()> {
    814     serialized!(
    815         sqlx::query(
    816             "
    817                 UPDATE initiated
    818                 SET status='permanent_failure', status_msg=$1
    819                 WHERE initiated_id=$2
    820             ",
    821         )
    822         .bind(msg)
    823         .bind(initiated_id)
    824         .execute(&mut *db)
    825     )?;
    826     Ok(())
    827 }
    828 
    829 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    830 pub enum ChargebackFailureResult {
    831     Unknown,
    832     Known(u64),
    833     Idempotent(u64),
    834 }
    835 
    836 /** Update status of a charged back initiated transaction */
    837 pub async fn initiated_chargeback_failure(
    838     db: &mut PgConnection,
    839     transfer_id: i64,
    840 ) -> sqlx::Result<ChargebackFailureResult> {
    841     Ok(serialized!(
    842         sqlx::query("SELECT out_initiated_id, out_new FROM register_charge_back_failure($1)")
    843             .bind(transfer_id)
    844             .try_map(|r: PgRow| {
    845                 let id = r.try_get_u64(0)?;
    846                 Ok(if id == 0 {
    847                     ChargebackFailureResult::Unknown
    848                 } else if r.try_get(1)? {
    849                     ChargebackFailureResult::Known(id)
    850                 } else {
    851                     ChargebackFailureResult::Idempotent(id)
    852                 })
    853             })
    854             .fetch_optional(&mut *db)
    855     )?
    856     .unwrap_or(ChargebackFailureResult::Unknown))
    857 }
    858 
    859 /** Get JSON value from KV table */
    860 pub async fn kv_get<T: DeserializeOwned + Unpin + Send>(
    861     db: &mut PgConnection,
    862     key: &str,
    863 ) -> sqlx::Result<Option<T>> {
    864     serialized!(
    865         sqlx::query("SELECT value FROM kv WHERE key=$1")
    866             .bind(key)
    867             .try_map(|r| Ok(r.try_get::<sqlx::types::Json<T>, _>(0)?.0))
    868             .fetch_optional(&mut *db)
    869     )
    870 }
    871 
    872 /** Set JSON value in KV table */
    873 pub async fn kv_set<T: Serialize>(db: &mut PgConnection, key: &str, value: &T) -> sqlx::Result<()> {
    874     serialized!(
    875         sqlx::query("INSERT INTO kv (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value")
    876             .bind(key)
    877             .bind(sqlx::types::Json(value))
    878             .execute(&mut *db)
    879     )?;
    880     Ok(())
    881 }
    882 
    883 pub enum RegistrationResult {
    884     Success,
    885     ReservePubReuse,
    886 }
    887 
    888 pub async fn transfer_register(
    889     db: &PgPool,
    890     req: &RegistrationRequest,
    891 ) -> sqlx::Result<RegistrationResult> {
    892     let ty: IncomingType = req.r#type.into();
    893     serialized!(
    894         sqlx::query(
    895             "SELECT out_reserve_pub_reuse FROM register_prepared_transfers($1,$2,$3,$4,$5,$6)"
    896         )
    897         .bind(ty)
    898         .bind(req.account_pub)
    899         .bind(req.authorization_pub)
    900         .bind(req.authorization_sig)
    901         .bind(req.recurrent)
    902         .bind_timestamp(&Timestamp::now())
    903         .try_map(|r: PgRow| {
    904             Ok(if r.try_get_flag("out_reserve_pub_reuse")? {
    905                 RegistrationResult::ReservePubReuse
    906             } else {
    907                 RegistrationResult::Success
    908             })
    909         })
    910         .fetch_one(db)
    911     )
    912 }
    913 
    914 pub async fn transfer_unregister(db: &PgPool, req: &Unregistration) -> sqlx::Result<bool> {
    915     serialized!(
    916         sqlx::query("SELECT out_found FROM delete_prepared_transfers($1)")
    917             .bind(req.authorization_pub)
    918             .try_map(|r: PgRow| r.try_get_flag("out_found"))
    919             .fetch_one(db)
    920     )
    921 }
    922 
    923 pub trait CyclosTypeHelper {
    924     fn try_get_cyclos_fullpayto<I: sqlx::ColumnIndex<Self>>(
    925         &self,
    926         idx: I,
    927         name: I,
    928         root: &CompactString,
    929     ) -> sqlx::Result<FullCyclosPayto>;
    930     fn try_get_cyclos_fullpaytouri<I: sqlx::ColumnIndex<Self>>(
    931         &self,
    932         idx: I,
    933         name: I,
    934         root: &CompactString,
    935     ) -> sqlx::Result<PaytoURI>;
    936 }
    937 
    938 impl CyclosTypeHelper for PgRow {
    939     fn try_get_cyclos_fullpayto<I: sqlx::ColumnIndex<Self>>(
    940         &self,
    941         idx: I,
    942         name: I,
    943         root: &CompactString,
    944     ) -> sqlx::Result<FullCyclosPayto> {
    945         let idx = self.try_get(idx)?;
    946         let name = self.try_get(name)?;
    947         Ok(FullCyclosPayto::new(
    948             CyclosAccount {
    949                 id: CyclosId(idx),
    950                 root: root.clone(),
    951             },
    952             name,
    953         ))
    954     }
    955     fn try_get_cyclos_fullpaytouri<I: sqlx::ColumnIndex<Self>>(
    956         &self,
    957         idx: I,
    958         name: I,
    959         root: &CompactString,
    960     ) -> sqlx::Result<PaytoURI> {
    961         let idx = self.try_get(idx)?;
    962         let name = self.try_get(name)?;
    963         Ok(CyclosAccount {
    964             id: CyclosId(idx),
    965             root: root.clone(),
    966         }
    967         .as_full_uri(name))
    968     }
    969 }
    970 
    971 #[cfg(test)]
    972 mod test {
    973     use compact_str::CompactString;
    974     use jiff::{Span, Timestamp};
    975     use serde_json::json;
    976     use sqlx::{PgConnection, PgPool, Row as _, postgres::PgRow};
    977     use taler_api::{
    978         db::TypeHelper,
    979         notification::dummy_listen,
    980         subject::{IncomingKey, OutgoingSubject},
    981     };
    982     use taler_common::{
    983         api::{
    984             EddsaPublicKey, HashCode, ShortHashCode,
    985             params::{History, Page},
    986             wire::TransferState,
    987         },
    988         types::{
    989             amount::{Currency, decimal},
    990             url,
    991             utils::now_sql_stable_ts,
    992         },
    993     };
    994     use taler_macros::db_test;
    995 
    996     use crate::db::{
    997         self, AddIncomingResult, AddOutgoingResult, BounceResult, ChargebackFailureResult,
    998         Transfer, TransferResult, TxIn, TxInAdmin, TxOut, TxOutKind,
    999     };
   1000 
   1001     pub const CURR: Currency = Currency::TEST;
   1002     pub const ROOT: CompactString = CompactString::const_new("localhost");
   1003 
   1004     #[db_test]
   1005     async fn kv(mut db: PgConnection) {
   1006         let value = json!({
   1007             "name": "Mr Smith",
   1008             "no way": 32
   1009         });
   1010 
   1011         assert_eq!(
   1012             db::kv_get::<serde_json::Value>(&mut db, "value")
   1013                 .await
   1014                 .unwrap(),
   1015             None
   1016         );
   1017         db::kv_set(&mut db, "value", &value).await.unwrap();
   1018         db::kv_set(&mut db, "value", &value).await.unwrap();
   1019         assert_eq!(
   1020             db::kv_get::<serde_json::Value>(&mut db, "value")
   1021                 .await
   1022                 .unwrap(),
   1023             Some(value)
   1024         );
   1025     }
   1026 
   1027     #[db_test]
   1028     async fn tx_in(mut db: PgConnection, pool: PgPool) {
   1029         let mut routine = async |first: &Option<IncomingKey>, second: &Option<IncomingKey>| {
   1030             let id = sqlx::query("SELECT count(*) + 1 FROM tx_in")
   1031                 .try_map(|r: PgRow| r.try_get_u64(0))
   1032                 .fetch_one(&mut db)
   1033                 .await
   1034                 .unwrap();
   1035             let now = now_sql_stable_ts();
   1036             let later = now + Span::new().hours(2);
   1037             let tx = TxIn {
   1038                 transfer_id: now.as_microsecond() as i64,
   1039                 tx_id: None,
   1040                 amount: decimal("10"),
   1041                 subject: "subject".to_owned(),
   1042                 debtor_id: 31000163100000000,
   1043                 debtor_name: "Name".into(),
   1044                 valued_at: now,
   1045             };
   1046             // Insert
   1047             assert_eq!(
   1048                 db::register_tx_in(&mut db, &tx, first, &now)
   1049                     .await
   1050                     .expect("register tx in"),
   1051                 AddIncomingResult::Success {
   1052                     new: true,
   1053                     pending: false,
   1054                     row_id: id,
   1055                     valued_at: now,
   1056                 }
   1057             );
   1058             // Idempotent
   1059             assert_eq!(
   1060                 db::register_tx_in(
   1061                     &mut db,
   1062                     &TxIn {
   1063                         valued_at: later,
   1064                         ..tx.clone()
   1065                     },
   1066                     first,
   1067                     &now
   1068                 )
   1069                 .await
   1070                 .expect("register tx in"),
   1071                 AddIncomingResult::Success {
   1072                     new: false,
   1073                     pending: false,
   1074                     row_id: id,
   1075                     valued_at: now
   1076                 }
   1077             );
   1078             // Many
   1079             assert_eq!(
   1080                 db::register_tx_in(
   1081                     &mut db,
   1082                     &TxIn {
   1083                         transfer_id: later.as_microsecond() as i64,
   1084                         valued_at: later,
   1085                         ..tx
   1086                     },
   1087                     second,
   1088                     &now
   1089                 )
   1090                 .await
   1091                 .expect("register tx in"),
   1092                 AddIncomingResult::Success {
   1093                     new: true,
   1094                     pending: false,
   1095                     row_id: id + 1,
   1096                     valued_at: later
   1097                 }
   1098             );
   1099         };
   1100 
   1101         // Empty db
   1102         assert_eq!(
   1103             db::revenue_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1104                 .await
   1105                 .unwrap(),
   1106             Vec::new()
   1107         );
   1108         assert_eq!(
   1109             db::incoming_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1110                 .await
   1111                 .unwrap(),
   1112             Vec::new()
   1113         );
   1114 
   1115         // Regular transaction
   1116         routine(&None, &None).await;
   1117 
   1118         let first = EddsaPublicKey::rand();
   1119         let second = EddsaPublicKey::rand();
   1120 
   1121         // Reserve transaction
   1122         routine(
   1123             &Some(IncomingKey::reserve(first)),
   1124             &Some(IncomingKey::reserve(second)),
   1125         )
   1126         .await;
   1127 
   1128         // Kyc transaction
   1129         routine(
   1130             &Some(IncomingKey::kyc(first)),
   1131             &Some(IncomingKey::kyc(first)),
   1132         )
   1133         .await;
   1134 
   1135         // History
   1136         assert_eq!(
   1137             db::revenue_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1138                 .await
   1139                 .unwrap()
   1140                 .len(),
   1141             6
   1142         );
   1143         assert_eq!(
   1144             db::incoming_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1145                 .await
   1146                 .unwrap()
   1147                 .len(),
   1148             4
   1149         );
   1150     }
   1151 
   1152     #[db_test]
   1153     async fn tx_in_admin(pool: PgPool) {
   1154         // Empty db
   1155         assert_eq!(
   1156             db::incoming_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1157                 .await
   1158                 .unwrap(),
   1159             Vec::new()
   1160         );
   1161 
   1162         let now = now_sql_stable_ts();
   1163         let later = now + Span::new().hours(2);
   1164         let tx = TxInAdmin {
   1165             amount: decimal("10"),
   1166             subject: "subject".to_owned(),
   1167             debtor_id: 31000163100000000,
   1168             debtor_name: "Name".into(),
   1169             metadata: IncomingKey::reserve(EddsaPublicKey::rand()),
   1170         };
   1171         // Insert
   1172         assert_eq!(
   1173             db::register_tx_in_admin(&pool, &tx, &now)
   1174                 .await
   1175                 .expect("register tx in"),
   1176             AddIncomingResult::Success {
   1177                 new: true,
   1178                 pending: false,
   1179                 row_id: 1,
   1180                 valued_at: now
   1181             }
   1182         );
   1183         // Many
   1184         assert_eq!(
   1185             db::register_tx_in_admin(
   1186                 &pool,
   1187                 &TxInAdmin {
   1188                     subject: "Other".to_owned(),
   1189                     metadata: IncomingKey::reserve(EddsaPublicKey::rand()),
   1190                     ..tx.clone()
   1191                 },
   1192                 &later
   1193             )
   1194             .await
   1195             .expect("register tx in"),
   1196             AddIncomingResult::Success {
   1197                 new: true,
   1198                 pending: false,
   1199                 row_id: 2,
   1200                 valued_at: later
   1201             }
   1202         );
   1203 
   1204         // History
   1205         assert_eq!(
   1206             db::incoming_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1207                 .await
   1208                 .unwrap()
   1209                 .len(),
   1210             2
   1211         );
   1212     }
   1213 
   1214     #[db_test]
   1215     async fn tx_out(mut db: PgConnection, pool: PgPool) {
   1216         let mut routine = async |first: &TxOutKind, second: &TxOutKind| {
   1217             let transfer_id = sqlx::query("SELECT count(*) + 1 FROM tx_out")
   1218                 .try_map(|r: PgRow| r.try_get(0))
   1219                 .fetch_one(&mut db)
   1220                 .await
   1221                 .unwrap();
   1222             let now = now_sql_stable_ts();
   1223             let later = now + Span::new().hours(2);
   1224             let tx = TxOut {
   1225                 transfer_id,
   1226                 tx_id: Some(transfer_id),
   1227                 amount: decimal("10"),
   1228                 subject: "subject".to_owned(),
   1229                 creditor_id: 31000163100000000,
   1230                 creditor_name: "Name".into(),
   1231                 valued_at: now,
   1232             };
   1233             // TODO revert to assert_matches! once rust-lang#82775 is stable
   1234             assert!(matches!(
   1235                 db::make_transfer(
   1236                     &pool,
   1237                     &Transfer {
   1238                         request_uid: HashCode::rand(),
   1239                         amount: decimal("10"),
   1240                         exchange_base_url: url("https://exchange.test.com/"),
   1241                         metadata: None,
   1242                         wtid: ShortHashCode::rand(),
   1243                         creditor_id: 31000163100000000,
   1244                         creditor_name: "Name".into()
   1245                     },
   1246                     &now
   1247                 )
   1248                 .await
   1249                 .unwrap(),
   1250                 TransferResult::Success { .. }
   1251             ));
   1252             db::initiated_submit_success(&mut db, 1, &Timestamp::now(), transfer_id)
   1253                 .await
   1254                 .expect("status success");
   1255 
   1256             // Insert
   1257             assert_eq!(
   1258                 db::register_tx_out(&mut db, &tx, first, &now)
   1259                     .await
   1260                     .expect("register tx out"),
   1261                 AddOutgoingResult {
   1262                     result: db::RegisterResult::known,
   1263                     row_id: transfer_id,
   1264                 }
   1265             );
   1266             // Idempotent
   1267             assert_eq!(
   1268                 db::register_tx_out(
   1269                     &mut db,
   1270                     &TxOut {
   1271                         valued_at: later,
   1272                         ..tx.clone()
   1273                     },
   1274                     first,
   1275                     &now
   1276                 )
   1277                 .await
   1278                 .expect("register tx out"),
   1279                 AddOutgoingResult {
   1280                     result: db::RegisterResult::idempotent,
   1281                     row_id: transfer_id,
   1282                 }
   1283             );
   1284             // Recovered
   1285             assert_eq!(
   1286                 db::register_tx_out(
   1287                     &mut db,
   1288                     &TxOut {
   1289                         transfer_id: transfer_id + 1,
   1290                         tx_id: Some(transfer_id + 1),
   1291                         valued_at: later,
   1292                         ..tx.clone()
   1293                     },
   1294                     second,
   1295                     &now
   1296                 )
   1297                 .await
   1298                 .expect("register tx out"),
   1299                 AddOutgoingResult {
   1300                     result: db::RegisterResult::recovered,
   1301                     row_id: transfer_id + 1,
   1302                 }
   1303             );
   1304         };
   1305 
   1306         // Empty db
   1307         assert_eq!(
   1308             db::outgoing_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1309                 .await
   1310                 .unwrap(),
   1311             Vec::new()
   1312         );
   1313 
   1314         // Regular transaction
   1315         routine(&TxOutKind::Simple, &TxOutKind::Simple).await;
   1316 
   1317         // Talerable transaction
   1318         routine(
   1319             &TxOutKind::Talerable(OutgoingSubject::rand()),
   1320             &TxOutKind::Talerable(OutgoingSubject::rand()),
   1321         )
   1322         .await;
   1323 
   1324         // Bounced transaction
   1325         routine(&TxOutKind::Bounce(21), &TxOutKind::Bounce(42)).await;
   1326 
   1327         // History
   1328         assert_eq!(
   1329             db::outgoing_history(&pool, &History::default(), &CURR, &ROOT, dummy_listen)
   1330                 .await
   1331                 .unwrap()
   1332                 .len(),
   1333             2
   1334         );
   1335     }
   1336 
   1337     // TODO tx out failure
   1338 
   1339     #[db_test]
   1340     async fn transfer(pool: PgPool) {
   1341         // Empty db
   1342         assert_eq!(
   1343             db::transfer_by_id(&pool, 0, &CURR, &ROOT).await.unwrap(),
   1344             None
   1345         );
   1346         assert_eq!(
   1347             db::transfer_page(&pool, &None, &CURR, &ROOT, &Page::default())
   1348                 .await
   1349                 .unwrap(),
   1350             Vec::new()
   1351         );
   1352 
   1353         let req = Transfer {
   1354             request_uid: HashCode::rand(),
   1355             amount: decimal("10"),
   1356             exchange_base_url: url("https://exchange.test.com/"),
   1357             metadata: None,
   1358             wtid: ShortHashCode::rand(),
   1359             creditor_id: 31000163100000000,
   1360             creditor_name: "Name".into(),
   1361         };
   1362         let now = now_sql_stable_ts();
   1363         let later = now + Span::new().hours(2);
   1364         // Insert
   1365         assert_eq!(
   1366             db::make_transfer(&pool, &req, &now)
   1367                 .await
   1368                 .expect("transfer"),
   1369             TransferResult::Success {
   1370                 id: 1,
   1371                 initiated_at: now
   1372             }
   1373         );
   1374         // Idempotent
   1375         assert_eq!(
   1376             db::make_transfer(&pool, &req, &later)
   1377                 .await
   1378                 .expect("transfer"),
   1379             TransferResult::Success {
   1380                 id: 1,
   1381                 initiated_at: now
   1382             }
   1383         );
   1384         // Request UID reuse
   1385         assert_eq!(
   1386             db::make_transfer(
   1387                 &pool,
   1388                 &Transfer {
   1389                     wtid: ShortHashCode::rand(),
   1390                     ..req.clone()
   1391                 },
   1392                 &now
   1393             )
   1394             .await
   1395             .expect("transfer"),
   1396             TransferResult::RequestUidReuse
   1397         );
   1398         // wtid reuse
   1399         assert_eq!(
   1400             db::make_transfer(
   1401                 &pool,
   1402                 &Transfer {
   1403                     request_uid: HashCode::rand(),
   1404                     ..req.clone()
   1405                 },
   1406                 &now
   1407             )
   1408             .await
   1409             .expect("transfer"),
   1410             TransferResult::WtidReuse
   1411         );
   1412         // Many
   1413         assert_eq!(
   1414             db::make_transfer(
   1415                 &pool,
   1416                 &Transfer {
   1417                     request_uid: HashCode::rand(),
   1418                     wtid: ShortHashCode::rand(),
   1419                     ..req
   1420                 },
   1421                 &later
   1422             )
   1423             .await
   1424             .expect("transfer"),
   1425             TransferResult::Success {
   1426                 id: 2,
   1427                 initiated_at: later
   1428             }
   1429         );
   1430 
   1431         // Get
   1432         assert!(
   1433             db::transfer_by_id(&pool, 1, &CURR, &ROOT)
   1434                 .await
   1435                 .unwrap()
   1436                 .is_some()
   1437         );
   1438         assert!(
   1439             db::transfer_by_id(&pool, 2, &CURR, &ROOT)
   1440                 .await
   1441                 .unwrap()
   1442                 .is_some()
   1443         );
   1444         assert!(
   1445             db::transfer_by_id(&pool, 3, &CURR, &ROOT)
   1446                 .await
   1447                 .unwrap()
   1448                 .is_none()
   1449         );
   1450         assert_eq!(
   1451             db::transfer_page(&pool, &None, &CURR, &ROOT, &Page::default())
   1452                 .await
   1453                 .unwrap()
   1454                 .len(),
   1455             2
   1456         );
   1457     }
   1458 
   1459     #[db_test]
   1460     async fn bounce(mut db: PgConnection) {
   1461         let amount = decimal("10");
   1462         let now = now_sql_stable_ts();
   1463 
   1464         // Bounce
   1465         assert_eq!(
   1466             db::register_bounced_tx_in(
   1467                 &mut db,
   1468                 &TxIn {
   1469                     transfer_id: 12,
   1470                     tx_id: None,
   1471                     amount,
   1472                     subject: "subject".to_owned(),
   1473                     debtor_id: 31000163100000000,
   1474                     debtor_name: "Name".into(),
   1475                     valued_at: now
   1476                 },
   1477                 22,
   1478                 "good reason",
   1479                 &now
   1480             )
   1481             .await
   1482             .expect("bounce"),
   1483             BounceResult {
   1484                 tx_id: 1,
   1485                 tx_new: true
   1486             }
   1487         );
   1488         // Idempotent
   1489         assert_eq!(
   1490             db::register_bounced_tx_in(
   1491                 &mut db,
   1492                 &TxIn {
   1493                     transfer_id: 12,
   1494                     tx_id: None,
   1495                     amount,
   1496                     subject: "subject".to_owned(),
   1497                     debtor_id: 31000163100000000,
   1498                     debtor_name: "Name".into(),
   1499                     valued_at: now
   1500                 },
   1501                 22,
   1502                 "good reason",
   1503                 &now
   1504             )
   1505             .await
   1506             .expect("bounce"),
   1507             BounceResult {
   1508                 tx_id: 1,
   1509                 tx_new: false
   1510             }
   1511         );
   1512 
   1513         // Many
   1514         assert_eq!(
   1515             db::register_bounced_tx_in(
   1516                 &mut db,
   1517                 &TxIn {
   1518                     transfer_id: 13,
   1519                     tx_id: None,
   1520                     amount,
   1521                     subject: "subject".to_owned(),
   1522                     debtor_id: 31000163100000000,
   1523                     debtor_name: "Name".into(),
   1524                     valued_at: now
   1525                 },
   1526                 23,
   1527                 "good reason",
   1528                 &now
   1529             )
   1530             .await
   1531             .expect("bounce"),
   1532             BounceResult {
   1533                 tx_id: 2,
   1534                 tx_new: true
   1535             }
   1536         );
   1537     }
   1538 
   1539     #[db_test]
   1540     async fn status(mut db: PgConnection, pool: PgPool) {
   1541         let check_status = async |id: u64, status: TransferState, msg: Option<&str>| {
   1542             let transfer = db::transfer_by_id(&pool, id, &CURR, &ROOT)
   1543                 .await
   1544                 .unwrap()
   1545                 .unwrap();
   1546             assert_eq!(
   1547                 (status, msg),
   1548                 (transfer.status, transfer.status_msg.as_deref())
   1549             );
   1550         };
   1551 
   1552         // Unknown transfer
   1553         db::initiated_submit_permanent_failure(&mut db, 1, "msg")
   1554             .await
   1555             .unwrap();
   1556         db::initiated_submit_success(&mut db, 1, &Timestamp::now(), 12)
   1557             .await
   1558             .unwrap();
   1559         assert_eq!(
   1560             db::initiated_chargeback_failure(&mut db, 1).await.unwrap(),
   1561             ChargebackFailureResult::Unknown
   1562         );
   1563 
   1564         // Failure
   1565         db::make_transfer(
   1566             &pool,
   1567             &Transfer {
   1568                 request_uid: HashCode::rand(),
   1569                 amount: decimal("1"),
   1570                 exchange_base_url: url("https://exchange.test.com/"),
   1571                 metadata: None,
   1572                 wtid: ShortHashCode::rand(),
   1573                 creditor_id: 31000163100000000,
   1574                 creditor_name: "Name".into(),
   1575             },
   1576             &Timestamp::now(),
   1577         )
   1578         .await
   1579         .expect("transfer");
   1580         check_status(1, TransferState::pending, None).await;
   1581         db::initiated_submit_permanent_failure(&mut db, 1, "error status")
   1582             .await
   1583             .unwrap();
   1584         check_status(1, TransferState::permanent_failure, Some("error status")).await;
   1585 
   1586         // Success
   1587         db::make_transfer(
   1588             &pool,
   1589             &Transfer {
   1590                 request_uid: HashCode::rand(),
   1591                 amount: decimal("1"),
   1592                 exchange_base_url: url("https://exchange.test.com/"),
   1593                 metadata: None,
   1594                 wtid: ShortHashCode::rand(),
   1595                 creditor_id: 31000163100000000,
   1596                 creditor_name: "Name".into(),
   1597             },
   1598             &Timestamp::now(),
   1599         )
   1600         .await
   1601         .expect("transfer");
   1602         check_status(2, TransferState::pending, None).await;
   1603         db::initiated_submit_success(&mut db, 2, &Timestamp::now(), 3)
   1604             .await
   1605             .unwrap();
   1606         check_status(2, TransferState::pending, None).await;
   1607         db::register_tx_out(
   1608             &mut db,
   1609             &TxOut {
   1610                 transfer_id: 5,
   1611                 tx_id: Some(3),
   1612                 amount: decimal("2"),
   1613                 subject: "".to_string(),
   1614                 creditor_id: 31000163100000000,
   1615                 creditor_name: "Name".into(),
   1616                 valued_at: Timestamp::now(),
   1617             },
   1618             &TxOutKind::Simple,
   1619             &Timestamp::now(),
   1620         )
   1621         .await
   1622         .unwrap();
   1623         check_status(2, TransferState::success, None).await;
   1624 
   1625         // Chargeback
   1626         assert_eq!(
   1627             db::initiated_chargeback_failure(&mut db, 5).await.unwrap(),
   1628             ChargebackFailureResult::Known(2)
   1629         );
   1630         check_status(2, TransferState::late_failure, Some("charged back")).await;
   1631         assert_eq!(
   1632             db::initiated_chargeback_failure(&mut db, 5).await.unwrap(),
   1633             ChargebackFailureResult::Idempotent(2)
   1634         );
   1635     }
   1636 
   1637     #[db_test]
   1638     async fn batch(mut db: PgConnection, pool: PgPool) {
   1639         let start = Timestamp::now();
   1640 
   1641         // Empty db
   1642         let pendings = db::pending_batch(&mut db, &start)
   1643             .await
   1644             .expect("pending_batch");
   1645         assert_eq!(pendings.len(), 0);
   1646 
   1647         // Some transfers
   1648         for i in 0..3 {
   1649             db::make_transfer(
   1650                 &pool,
   1651                 &Transfer {
   1652                     request_uid: HashCode::rand(),
   1653                     amount: decimal(format!("{}", i + 1)),
   1654                     exchange_base_url: url("https://exchange.test.com/"),
   1655                     metadata: None,
   1656                     wtid: ShortHashCode::rand(),
   1657                     creditor_id: 31000163100000000,
   1658                     creditor_name: "Name".into(),
   1659                 },
   1660                 &Timestamp::now(),
   1661             )
   1662             .await
   1663             .expect("transfer");
   1664         }
   1665         let pendings = db::pending_batch(&mut db, &start)
   1666             .await
   1667             .expect("pending_batch");
   1668         assert_eq!(pendings.len(), 3);
   1669 
   1670         // Max 100 txs in batch
   1671         for i in 0..100 {
   1672             db::make_transfer(
   1673                 &pool,
   1674                 &Transfer {
   1675                     request_uid: HashCode::rand(),
   1676                     amount: decimal(format!("{}", i + 1)),
   1677                     exchange_base_url: url("https://exchange.test.com/"),
   1678                     metadata: None,
   1679                     wtid: ShortHashCode::rand(),
   1680                     creditor_id: 31000163100000000,
   1681                     creditor_name: "Name".into(),
   1682                 },
   1683                 &Timestamp::now(),
   1684             )
   1685             .await
   1686             .expect("transfer");
   1687         }
   1688         let pendings = db::pending_batch(&mut db, &start)
   1689             .await
   1690             .expect("pending_batch");
   1691         assert_eq!(pendings.len(), 100);
   1692 
   1693         // Skip uploaded
   1694         for i in 0..=10 {
   1695             db::initiated_submit_success(&mut db, i, &Timestamp::now(), i)
   1696                 .await
   1697                 .expect("status success");
   1698         }
   1699         let pendings = db::pending_batch(&mut db, &start)
   1700             .await
   1701             .expect("pending_batch");
   1702         assert_eq!(pendings.len(), 93);
   1703 
   1704         // Skip failed
   1705         for i in 0..=10 {
   1706             db::initiated_submit_permanent_failure(&mut db, 10 + i, "failure")
   1707                 .await
   1708                 .expect("status failure");
   1709         }
   1710         let pendings = db::pending_batch(&mut db, &start)
   1711             .await
   1712             .expect("pending_batch");
   1713         assert_eq!(pendings.len(), 83);
   1714     }
   1715 
   1716     #[db_test]
   1717     async fn pending_bounces(mut db: PgConnection, pool: PgPool) {
   1718         use taler_common::{
   1719             api::{
   1720                 EddsaSignature,
   1721                 prepared::{PublicKeyAlg, RegistrationRequest, TransferType, Unregistration},
   1722             },
   1723             types::{amount::amount, time::TalerTimestamp},
   1724         };
   1725 
   1726         let now = now_sql_stable_ts();
   1727         let auth_pub = EddsaPublicKey::rand();
   1728         let req = RegistrationRequest {
   1729             credit_account: "payto://cyclos/test/exchange".parse().unwrap(),
   1730             r#type: TransferType::reserve,
   1731             recurrent: true,
   1732             credit_amount: amount("TEST:10"),
   1733             alg: PublicKeyAlg::EdDSA,
   1734             account_pub: auth_pub,
   1735             authorization_pub: auth_pub,
   1736             authorization_sig: EddsaSignature::ZEROED,
   1737         };
   1738         db::transfer_register(&pool, &req).await.unwrap();
   1739 
   1740         // First mapped tx finalizes immediately; next two become pending_recurrent_in
   1741         for transfer_id in [101_i64, 102, 103] {
   1742             db::register_tx_in(
   1743                 &mut db,
   1744                 &TxIn {
   1745                     transfer_id,
   1746                     tx_id: None,
   1747                     amount: decimal("10"),
   1748                     subject: "mapped".to_owned(),
   1749                     debtor_id: 42,
   1750                     debtor_name: "Debtor".into(),
   1751                     valued_at: now,
   1752                 },
   1753                 &Some(IncomingKey::map(auth_pub)),
   1754                 &now,
   1755             )
   1756             .await
   1757             .unwrap();
   1758         }
   1759         // Admin-added mapped tx (transfer_id = NULL) must be ignored by pending_bounces
   1760         db::register_tx_in_admin(
   1761             &pool,
   1762             &TxInAdmin {
   1763                 amount: decimal("10"),
   1764                 subject: "admin mapped".to_owned(),
   1765                 debtor_id: 42,
   1766                 debtor_name: "Debtor".into(),
   1767                 metadata: IncomingKey::map(auth_pub),
   1768             },
   1769             &now,
   1770         )
   1771         .await
   1772         .unwrap();
   1773 
   1774         assert!(db::pending_bounces(&mut db).await.unwrap().is_empty());
   1775 
   1776         // Cancel mapping -> moves pending_recurrent_in rows into bounced with chargeback_id = NULL
   1777         assert!(
   1778             db::transfer_unregister(
   1779                 &pool,
   1780                 &Unregistration {
   1781                     timestamp: TalerTimestamp::Timestamp(now),
   1782                     authorization_pub: auth_pub,
   1783                     authorization_sig: EddsaSignature::ZEROED,
   1784                 },
   1785             )
   1786             .await
   1787             .unwrap()
   1788         );
   1789 
   1790         let pending = db::pending_bounces(&mut db).await.unwrap();
   1791         assert_eq!(pending.len(), 2);
   1792         assert_eq!(pending[0].transfer_id, 102);
   1793         assert_eq!(pending[0].reason, "cancelled mapping");
   1794         assert_eq!(pending[1].transfer_id, 103);
   1795 
   1796         // Mark first bounced, drop second as non-chargebackable
   1797         db::bounce_submit_success(&mut db, pending[0].tx_in_id, 9001)
   1798             .await
   1799             .unwrap();
   1800         db::bounce_drop(&mut db, pending[1].tx_in_id).await.unwrap();
   1801 
   1802         assert!(db::pending_bounces(&mut db).await.unwrap().is_empty());
   1803     }
   1804 }
   1805 
   1806 #[derive(Debug, Default, Deserialize)]
   1807 pub struct TaskStatus {
   1808     pub last_execution: Option<Timestamp>,
   1809     pub last_success: Option<Timestamp>,
   1810 }
   1811 
   1812 pub async fn task_start(db: &mut PgConnection, key: &str) -> sqlx::Result<()> {
   1813     task_update(db, key, "last_execution").await
   1814 }
   1815 
   1816 pub async fn task_success(db: &mut PgConnection, key: &str) -> sqlx::Result<()> {
   1817     task_update(db, key, "last_success").await
   1818 }
   1819 
   1820 async fn task_update(db: &mut PgConnection, key: &str, field: &str) -> sqlx::Result<()> {
   1821     serialized!(
   1822         sqlx::query(
   1823             "INSERT INTO kv (key, value) VALUES ($1, jsonb_build_object($2::text, $3::jsonb))
   1824              ON CONFLICT (key) DO UPDATE SET value = kv.value || EXCLUDED.value",
   1825         )
   1826         .bind(key)
   1827         .bind(field)
   1828         .bind(sqlx::types::Json(Timestamp::now()))
   1829         .execute(&mut *db)
   1830     )?;
   1831     Ok(())
   1832 }