bank: a payment is spent once

A payer could place several orders and send one transfer naming all of
them. Each order looked for its own reference, found it, and saw the
full amount, so every order settled on one payment: three EUR 5 orders
on a single EUR 5 credit, reproduced. The rail logged "settle this one
by hand" and settled each of them. The README called it a known
limitation; it was a way to pay once for several orders.

The rail now records which payment settled which order, by the bank's
id, in <credits>.claims, before it reports the order paid, and a claimed
payment is left out of every other order's sum. The record cannot live
in the credits file, which the pull replaces every hour. It is read back
at start. If it cannot be written the rail settles nothing and says why;
if it is there and cannot be read the rail does not start. A claims
file that ends mid-line gets its line break before the next claim, or
that claim would be lost at the next start and the payment free again.

It does not rest on what a description looks like, because the payer
writes it. The "also quotes another reference" flag stays as a pointer
in the log and decides nothing: a name followed by a date has the same
shape. A payer who really sends one transfer for two orders gets the
first settled and the other by hand, with one line in the journal.

One payment is also counted once however many lines of the credits file
carry its id. Two lines are not meant to happen and were reproduced all
the same (one callback delivered on two connections at once passed the
id check twice), and summed they settle an order on half its price. The
callback's look-then-append is now under a lock as well.

ShouldMatchBankTransfers drives the matcher and the rail itself across
a restart, a torn claims file, an unreadable one and a duplicated line;
ShouldSettleBankTransfers shows over HTTP that one of three orders
settles.

Found in the security review of 2026-11-26; the torn claims file and
the duplicate line by the adversarial review of the first fix.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-11-26 11:05:35 +01:00
commit 3c61116531
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
4 changed files with 683 additions and 23 deletions

View file

@ -108,16 +108,31 @@ bool HasOtherReferenceShape(std::string_view folded, std::size_t foundAt,
return false; return false;
} }
// What a credit is claimed under. The bank's own id for the payment is the
// key wherever there is one, and the callback and the pull both always carry
// it. A line an operator wrote by hand may not, and is then known by what it
// says: its reduced text and its amount. Two hand-written lines saying the
// same thing share a key, which errs the safe way — spent for one order, both
// are spent for every other.
std::string ClaimKey(const BankCredit& credit, std::string_view folded) {
if (!credit.id.empty()) return credit.id;
return std::format("text:{}:{}", folded, credit.amountMinor);
}
} // namespace } // namespace
TransferMatch MatchCredits(std::span<const BankCredit> credits, TransferMatch MatchCredits(std::span<const BankCredit> credits,
std::string_view reference) { std::string_view reference,
std::span<const CreditClaim> claims) {
TransferMatch out; TransferMatch out;
const std::string needle = Fold(reference); const std::string needle = Fold(reference);
// An empty needle would match every credit on the account. Refuse rather // An empty needle would match every credit on the account. Refuse rather
// than settle the whole ledger from one payment. // than settle the whole ledger from one payment.
if (needle.size() < 4) return out; if (needle.size() < 4) return out;
// The bank's ids of the payments seen so far in this pass.
std::set<std::string_view> seen;
for (const BankCredit& c : credits) { for (const BankCredit& c : credits) {
// Only money coming IN can pay for something. A negative amount is an // Only money coming IN can pay for something. A negative amount is an
// outgoing payment that happens to quote the reference — a refund we // outgoing payment that happens to quote the reference — a refund we
@ -127,9 +142,37 @@ TransferMatch MatchCredits(std::span<const BankCredit> credits,
const std::string folded = Fold(c.reference); const std::string folded = Fold(c.reference);
const std::size_t at = folded.find(needle); const std::size_t at = folded.find(needle);
if (at == std::string::npos) continue; if (at == std::string::npos) continue;
// One payment is counted once, however many lines of the file carry
// it. The callback handler skips an id the file already holds and
// the pull writes each payment once, so a second line is not meant
// to happen. It still can: the same callback delivered on two
// connections at once, a callback landing while the pull is
// replacing the file, an address registered twice at the bank. Left
// to be summed, a second line doubles the money, and a payer who
// sent half the price finds the order settled. A line with no id
// cannot be told from another payment that says the same, so those
// are each counted.
if (!c.id.empty() && !seen.insert(c.id).second) {
++out.duplicates;
continue;
}
// Spent once. This credit quotes the reference, but if it already
// settled a DIFFERENT order its money is gone, whatever its text
// says. A claim by this same reference is the order's own and counts.
const std::string key = ClaimKey(c, folded);
const bool spent = std::ranges::any_of(claims, [&](const CreditClaim& claim) {
return claim.credit == key && Fold(claim.reference) != needle;
});
if (spent) {
++out.spentElsewhere;
continue;
}
out.paidMinor += c.amountMinor; out.paidMinor += c.amountMinor;
++out.count; ++out.count;
out.method = c.method; out.method = c.method;
if (std::ranges::find(out.credits, key) == out.credits.end()) {
out.credits.push_back(key);
}
if (HasOtherReferenceShape(folded, at, needle.size())) out.ambiguous = true; if (HasOtherReferenceShape(folded, at, needle.size())) out.ambiguous = true;
} }
return out; return out;
@ -198,7 +241,22 @@ private:
class TransferRail final : public PaymentRail { class TransferRail final : public PaymentRail {
public: public:
TransferRail(RailConfig cfg, std::unique_ptr<CreditSource> credits) TransferRail(RailConfig cfg, std::unique_ptr<CreditSource> credits)
: cfg_(std::move(cfg)), credits_(std::move(credits)) {} : cfg_(std::move(cfg)), credits_(std::move(credits)) {
// The record of which credit paid for which order hangs off the
// credits path, the way the EURC rail's cursor hangs off its pool.
// It cannot be IN the credits file: the pull replaces that every hour.
if (!cfg_.transferCreditsPath.empty()) {
claimsPath_ = cfg_.transferCreditsPath;
claimsPath_ += ".claims";
}
claimsLoaded_ = LoadClaims();
}
// False when there is a claims file and it could not be read. The rail
// must not run like that: with the claims unknown, every payment looks
// unspent, and one that named several orders would settle another of
// them. MakeTransferRail refuses to hand out a rail in that state.
bool ClaimsLoaded() const { return claimsLoaded_; }
// No network call, and nothing to reserve: unlike the EURC rail, which // No network call, and nothing to reserve: unlike the EURC rail, which
// burns a receiving address per order, a transfer reuses one IBAN forever // burns a receiving address per order, a transfer reuses one IBAN forever
@ -235,16 +293,60 @@ public:
const std::optional<std::vector<BankCredit>> all = Fetch(); const std::optional<std::vector<BankCredit>> all = Fetch();
if (!all) return std::nullopt; // unknown, retry — never "unpaid" if (!all) return std::nullopt; // unknown, retry — never "unpaid"
const TransferMatch m = MatchCredits(*all, reference); // ONE order is judged at a time from here to the claim below. The
if (m.ambiguous) { // reconciler and every buyer's arrival poll call this from their own
// threads, and two orders quoted by the same credit must not both
// look, both find it unspent, and both settle: the second has to see
// the first one's claim. Nothing under this lock touches the network
// (the credits were read above, under their own lock), so it is held
// for a comparison and at most one short file append.
std::lock_guard lock(claimsMutex_);
const TransferMatch m = MatchCredits(*all, reference, claims_);
if (m.duplicates > 0 && Once("duplicate", reference)) {
std::println(std::cerr, std::println(std::cerr,
"transfer: {} matched a credit that also quotes another " "transfer: {} is quoted by a payment the credits file "
"order reference — settle this one by hand", reference); "lists {} time(s) too many. It is counted once. If this "
"keeps happening, check that the callback address is "
"registered at the bank only once (`nostro callbacks`)",
reference, m.duplicates);
}
if (m.spentElsewhere > 0 && Once("spent", reference)) {
std::println(std::cerr,
"transfer: {} is quoted by {} payment(s) whose money "
"already settled another order, so none of it is counted "
"here: one payment pays for one order. If the payer meant "
"a single transfer for several orders, settle this one "
"with --mark-paid", reference, m.spentElsewhere);
} }
PaidStatus out; PaidStatus out;
out.method = m.method.empty() ? std::string("sepa") : m.method; out.method = m.method.empty() ? std::string("sepa") : m.method;
if (m.paidMinor >= expectedMinor) { if (m.paidMinor >= expectedMinor) {
// Claim first, report second. Done the other way round, a crash
// between the two leaves an order reported paid whose money
// nothing marks as spent, free to settle whatever else its text
// names. This way round it leaves a claim whose order is still
// awaiting, and the next poll settles that order from its own
// claim.
if (!Claim(m, reference)) {
if (Once("unrecorded", reference)) {
std::println(std::cerr,
"transfer: {} is covered, but {} cannot be "
"written, so its payment cannot be recorded as "
"spent. NOT settling it until it can: the same "
"money could otherwise settle a second order",
reference, claimsPath_.string());
}
return std::nullopt; // unknown, retry
}
if (m.ambiguous) {
std::println(std::cerr,
"transfer: {} settled on a payment that also quotes "
"what looks like another order reference. That "
"payment is spent on this order now and will not "
"count toward another; if the payer meant it for "
"both, the other one is settled by hand", reference);
}
out.state = PayState::Paid; out.state = PayState::Paid;
return out; return out;
} }
@ -368,11 +470,130 @@ private:
return cached_; return cached_;
} }
// ── claims: which credit paid for which order ─────────────────────
//
// One JSON object per line, {"credit":…,"reference":…,"at":…}, appended
// and never rewritten, like the ledger. Read once at start and kept in
// memory from then on: this process is the only thing that settles
// orders from credits, so the file is never ahead of what is held here.
// False only when there IS a claims file and it cannot be read; see
// ClaimsLoaded. No file at all is the ordinary state of a rail no order
// has settled on yet.
bool LoadClaims() {
if (claimsPath_.empty()) return true;
std::error_code ec;
const std::filesystem::file_status status =
std::filesystem::status(claimsPath_, ec);
if (!std::filesystem::exists(status)) return true;
if (!std::filesystem::is_regular_file(status)) return false;
std::ifstream in(claimsPath_, std::ios::binary);
if (!in) return false;
const std::string text((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
if (in.bad()) return false;
// A file that stops mid-line: a write cut short by a full disk or a
// crash. The next claim has to start a line of its own (see Claim).
claimsTorn_ = !text.empty() && text.back() != '\n';
int lineNo = 0;
for (std::size_t start = 0; start < text.size();) {
const std::size_t nl = text.find('\n', start);
const std::size_t end = nl == std::string::npos ? text.size() : nl;
const std::string_view line = std::string_view(text).substr(start, end - start);
start = nl == std::string::npos ? text.size() : nl + 1;
++lineNo;
if (line.empty()) continue;
const auto doc = Json::Parse(line);
CreditClaim claim;
if (doc && doc->IsObject()) {
claim.credit = std::string(doc->Str("credit"));
claim.reference = std::string(doc->Str("reference"));
}
if (claim.credit.empty() || claim.reference.empty()) {
// Said aloud and skipped, as the credits file does it: a
// line lost here is one payment that could be counted again
// for another order its text names, which is worth knowing
// about and not worth refusing every settlement over.
std::println(std::cerr, "transfer: {}:{} is not a claim, skipped",
claimsPath_.string(), lineNo);
continue;
}
claims_.push_back(std::move(claim));
}
return true;
}
// Record that the credits `m` counted are spent on `reference`. Called
// with claimsMutex_ held. False when the record could not be written, and
// then nothing is held in memory either: the caller does not settle.
//
// What "before the order is reported paid" is worth: the claim is in the
// file before this returns, so a crash of the PROCESS between the claim
// and the ledger's paid line leaves the claim. It is not fsynced, and
// neither is the ledger, so a power cut can still keep one line and lose
// the other.
bool Claim(const TransferMatch& m, const std::string& reference) {
const std::string now = std::format(
"{:%FT%TZ}", std::chrono::floor<std::chrono::seconds>(
std::chrono::system_clock::now()));
std::string lines;
std::vector<CreditClaim> fresh;
for (const std::string& key : m.credits) {
// A counted credit that already has a claim has THIS order's: one
// held by any other order was not counted. It is here again
// because the settlement it was written for never reached the
// ledger, and it needs no second line.
const bool held = std::ranges::any_of(claims_, [&](const CreditClaim& c) {
return c.credit == key;
});
if (held) continue;
lines += std::format(R"({{"credit":"{}","reference":"{}","at":"{}"}})" "\n",
EscT(key), EscT(reference), now);
fresh.push_back({ key, reference });
}
if (fresh.empty()) return true;
if (!claimsPath_.empty()) {
std::ofstream out(claimsPath_, std::ios::app | std::ios::binary);
if (!out) return false;
// A file that ends mid-line gets its line break first, for the
// reason the ledger does: written onto the end of a broken line,
// this claim would be read as part of it and skipped at the next
// start, and the payment would be free to settle a second order.
if (claimsTorn_) out << '\n';
out << lines;
out.flush();
if (!out) {
// Some of it may be on disk. Whatever is, the next write
// starts on a new line; a blank one is skipped on load.
claimsTorn_ = true;
return false;
}
claimsTorn_ = false;
}
for (CreditClaim& c : fresh) claims_.push_back(std::move(c));
return true;
}
// True the first time `what` is asked about `reference`, so a line that
// would otherwise repeat on every poll of an order nobody has settled yet
// is said once per run of the server. Called with claimsMutex_ held.
bool Once(std::string_view what, std::string_view reference) {
return told_.insert(std::format("{}/{}", what, reference)).second;
}
RailConfig cfg_; RailConfig cfg_;
std::unique_ptr<CreditSource> credits_; std::unique_ptr<CreditSource> credits_;
std::mutex mutex_; std::mutex mutex_;
std::optional<std::vector<BankCredit>> cached_; std::optional<std::vector<BankCredit>> cached_;
std::chrono::steady_clock::time_point fetchedAt_{}; std::chrono::steady_clock::time_point fetchedAt_{};
bool claimsLoaded_ = true;
bool claimsTorn_ = false; // the claims file does not end in a line break
std::filesystem::path claimsPath_;
std::mutex claimsMutex_;
std::vector<CreditClaim> claims_;
std::set<std::string> told_;
}; };
} // namespace } // namespace
@ -381,30 +602,53 @@ std::unique_ptr<CreditSource> MakeFileCreditSource(std::filesystem::path path) {
return std::make_unique<FileCreditSource>(std::move(path)); return std::make_unique<FileCreditSource>(std::move(path));
} }
namespace {
// Held from the look for the id to the append. The listener serves each
// connection on its own thread, and a bank that delivers one callback on two
// connections at once would otherwise have both look, both find the id
// absent, and both append it.
std::mutex gCreditAppendMutex;
} // namespace
bool AppendCreditTo(const std::filesystem::path& creditsPath, bool AppendCreditTo(const std::filesystem::path& creditsPath,
const BankCredit& credit) { const BankCredit& credit) {
if (credit.id.empty()) return false; if (credit.id.empty()) return false;
std::lock_guard lock(gCreditAppendMutex);
// Deduplicate on the bank's own payment id. A bank retries a callback it // Deduplicate on the bank's own payment id. A bank retries a callback it
// got no answer to, and the periodic pull ships a file that holds the same // got no answer to, and the periodic pull ships a file that holds the same
// payment again, so the SAME payment arrives more than once by design. // payment again, so the SAME payment arrives more than once by design.
// Appending it twice would double the money against one reference — // Appending it twice would double the money against one reference —
// enough, on a part-paid order, to settle it without the balance ever // enough, on a part-paid order, to settle it without the balance ever
// arriving. // arriving. (MatchCredits counts an id once regardless; this keeps the
// file itself to one line a payment where it can.)
bool torn = false;
{ {
std::ifstream in(creditsPath, std::ios::binary); std::ifstream in(creditsPath, std::ios::binary);
std::string line; const std::string text((std::istreambuf_iterator<char>(in)),
while (std::getline(in, line)) { std::istreambuf_iterator<char>());
for (std::size_t start = 0; start < text.size();) {
const std::size_t nl = text.find('\n', start);
const std::size_t end = nl == std::string::npos ? text.size() : nl;
const std::string_view line = std::string_view(text).substr(start, end - start);
start = nl == std::string::npos ? text.size() : nl + 1;
if (line.empty()) continue; if (line.empty()) continue;
const auto doc = Json::Parse(line); const auto doc = Json::Parse(line);
if (!doc || !doc->IsObject()) continue; if (!doc || !doc->IsObject()) continue;
if (doc->Str("id") == credit.id) return false; if (doc->Str("id") == credit.id) return false;
} }
// The pull writes this file over ssh, and an upload cut short leaves
// it ending mid-line. Start a new line then, so this credit is not
// read as the tail of the broken one.
torn = !text.empty() && text.back() != '\n';
} }
std::ofstream out(creditsPath, std::ios::app | std::ios::binary); std::ofstream out(creditsPath, std::ios::app | std::ios::binary);
if (!out) { if (!out) {
std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string()); std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string());
return false; return false;
} }
if (torn) out << '\n';
out << std::format( out << std::format(
R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n", R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n",
EscT(credit.id), EscT(credit.reference), credit.amountMinor, EscT(credit.id), EscT(credit.reference), credit.amountMinor,
@ -433,7 +677,19 @@ std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
"account-holder name"); "account-holder name");
return nullptr; return nullptr;
} }
return std::make_unique<TransferRail>(config, std::move(credits)); auto rail = std::make_unique<TransferRail>(config, std::move(credits));
if (!rail->ClaimsLoaded()) {
std::filesystem::path claims = config.transferCreditsPath;
claims += ".claims";
std::println(std::cerr,
"transfer: {} is there and cannot be read. It records which "
"payments have already settled an order; without it a payment "
"that named several orders could settle another of them. Fix "
"its ownership or permissions (it belongs to the user the "
"server runs as) and restart", claims.string());
return nullptr;
}
return rail;
} }
} // namespace Catcrafts::Server } // namespace Catcrafts::Server

View file

@ -542,22 +542,56 @@ export namespace Catcrafts::Server {
std::string method; // ledger `via`: "sepa", "ideal", … std::string method; // ledger `via`: "sepa", "ideal", …
}; };
// A credit that has paid for an order.
//
// MONEY IS SPENT ONCE. A payment that settled one order pays for no other,
// however many references its remittance text quotes. Without that rule a
// payer could place several orders, send ONE transfer naming all of them,
// and watch each order find the full amount against its own reference:
// every order settled, one of them paid for. (Found in review on
// 2026-11-26; three €5 orders settled on a single €5 credit.) The text is
// a stranger's to write, so the rule cannot rest on what the text looks
// like. It rests on this record instead: which credit, which order.
struct CreditClaim {
// The credit, by its key: the bank's own id for the payment, or, for
// a line written by hand without one, a key made of its text and
// amount (see MatchCredits).
std::string credit;
std::string reference; // the order it settled, "CC-2B6457"
};
// What the credits say about one order. // What the credits say about one order.
struct TransferMatch { struct TransferMatch {
std::int64_t paidMinor = 0; // summed over every credit carrying the reference std::int64_t paidMinor = 0; // summed over every credit counted
int count = 0; // how many credits carried it int count = 0; // how many credits were counted
std::string method; // the method of the last matching credit std::string method; // the method of the last one counted
// Set when a matching credit's remittance text ALSO carries something // The credits that were counted, by key, each once. What the rail
// shaped like a second order reference. One transfer quoting two // claims for the order at the moment it settles.
// references cannot be attributed by a per-order matcher, and at that std::vector<std::string> credits;
// point a human should look rather than two orders both settling on the // Credits that quote the reference and were NOT counted, because
// same money. Advisory: the caller logs it, it does not block. // their money already settled another order. Not an error, and worth
// saying aloud: it is either the trick described at CreditClaim or a
// payer who meant one transfer for several orders, and in both cases
// the order in hand is one a human settles.
int spentElsewhere = 0;
// Lines left out because an earlier line carried the same bank id:
// one payment listed more than once. Counted once, and reported so
// the log can say the file is carrying duplicates.
int duplicates = 0;
// Set when a counted credit's remittance text ALSO carries something
// shaped like a second order reference. Advisory, as it always was:
// the shape test cannot tell a second reference from a name followed
// by a date, so it decides nothing. What stops two orders settling on
// the same money is the claim, not this flag; the flag is so the log
// can say which settlement to look at.
bool ambiguous = false; bool ambiguous = false;
}; };
// Sum the credits that quote `reference`, in whatever form the payer typed // Sum the credits that quote `reference`, in whatever form the payer typed
// it. Pure, and exported for the self-test, because this is the decision // it, leaving out any that `claims` says already paid for a DIFFERENT
// that releases goods — the same reason ParseEthCallUint is exported. // order. Pure, and exported for the self-test, because this is the
// decision that releases goods — the same reason ParseEthCallUint is
// exported.
// //
// Matching is on the reference BODY ("CC2B6457") after reducing both sides // Matching is on the reference BODY ("CC2B6457") after reducing both sides
// to upper-case alphanumerics. That one choice covers every form a payer // to upper-case alphanumerics. That one choice covers every form a payer
@ -566,8 +600,20 @@ export namespace Catcrafts::Server {
// survives whatever spacing a bank puts in the field. The RF check digits // survives whatever spacing a bank puts in the field. The RF check digits
// deliberately do NO work here: their job was done at the payer's own bank, // deliberately do NO work here: their job was done at the payer's own bank,
// which refuses a mistyped reference before the transfer ever leaves. // which refuses a mistyped reference before the transfer ever leaves.
//
// A claim by the SAME reference does not exclude a credit: an order whose
// settlement was claimed but never reached the ledger (a crash between
// the two) must find its own money still there. Claims are compared on
// the reduced form too, so how a claim spells its reference is not part
// of it.
//
// A payment is also counted ONCE within a pass: credits that share a
// bank id are one payment, and only the first is summed. Two lines for
// one payment are not supposed to reach the file, but summing them would
// settle a half-paid order, so the sum does not depend on it.
TransferMatch MatchCredits(std::span<const BankCredit> credits, TransferMatch MatchCredits(std::span<const BankCredit> credits,
std::string_view reference); std::string_view reference,
std::span<const CreditClaim> claims = {});
// Where a transfer rail gets its incoming credits. The one implementation // Where a transfer rail gets its incoming credits. The one implementation
// reads a file (MakeFileCreditSource) that is filled from outside the rail: // reads a file (MakeFileCreditSource) that is filled from outside the rail:
@ -587,6 +633,17 @@ export namespace Catcrafts::Server {
// The rail itself. Takes its credit source, so that where the credits // The rail itself. Takes its credit source, so that where the credits
// come from can change without the rail being rewritten: it knows nothing // come from can change without the rail being rewritten: it knows nothing
// of any bank. // of any bank.
//
// It keeps one file of its own, "<transferCreditsPath>.claims": a line
// for each credit that settled an order, written BEFORE the order is
// reported paid and read back at start (CreditClaim has the reason). The
// credits file is replaced wholesale by the pull every hour, so the
// record of what was spent cannot live in it. A settlement whose claim
// cannot be written is not made: the answer is "unknown, retry", and the
// log says why. A claims file that is there and cannot be READ is a rail
// that cannot know what was spent, so this returns nullptr for it, with
// the reason logged. With no credits path there is nowhere to keep the
// file, and the claims then last as long as the process.
std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config, std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
std::unique_ptr<CreditSource> credits); std::unique_ptr<CreditSource> credits);

View file

@ -59,6 +59,134 @@ std::int64_t PaidFor(std::vector<BankCredit> credits, std::string_view reference
return Match(std::move(credits), reference).paidMinor; return Match(std::move(credits), reference).paidMinor;
} }
// ── the rail itself, without a server around it ───────────────────────
//
// MatchCredits is pure; what it is given is not. The rail keeps the claims in
// a file, reads them back when it starts, and writes one before it reports an
// order paid. Those three are where "a payment is spent once" can fail while
// every check on the matcher still passes, so they are driven here through
// the rail's own interface: a fixed list of credits standing in for the
// bank, a scratch directory standing in for /var/lib/catcrafts, and a NEW
// rail object wherever production would have restarted.
namespace fs = std::filesystem;
class FixedCredits final : public Server::CreditSource {
public:
explicit FixedCredits(std::vector<BankCredit> credits) : credits_(std::move(credits)) {}
std::optional<std::vector<BankCredit>> Recent() override { return credits_; }
std::string_view Name() const override { return "fixed"; }
private:
std::vector<BankCredit> credits_;
};
std::unique_ptr<Server::PaymentRail> Rail(const fs::path& creditsPath,
std::vector<BankCredit> credits) {
Server::RailConfig cfg;
cfg.mode = "transfer";
cfg.transferIban = "NL00TEST0123456789";
cfg.transferBeneficiary = "Not a real account";
cfg.transferCreditsPath = creditsPath;
cfg.transferPollSeconds = 1;
return Server::MakeTransferRail(cfg, std::make_unique<FixedCredits>(std::move(credits)));
}
// Whether the rail reports the order with this reference paid. The deadline
// in the id is far in the future, so an unpaid order reads as pending here
// and never as lapsed.
bool Settles(Server::PaymentRail& rail, std::string_view reference, std::int64_t minor) {
const auto status = rail.CheckPaid(std::format("{}@4102444800", reference), minor);
return status && status->state == Server::PayState::Paid;
}
std::string Slurp(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
void TheRailRemembersWhatWasSpent(const fs::path& work) {
const std::vector<BankCredit> oneForTwo = {
Credit("CC-AAAAAA CC-BBBBBB", 500, "sepa", "pay-1") };
// Across a restart. The first rail settles one order and is destroyed;
// the second is what a deploy leaves running, with nothing in memory.
// The same credit is still in the file the bank fills, naming the other
// order, and it must stay spent.
{
const fs::path credits = work / "restart.jsonl";
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "rail: it starts with no claims file at all");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "rail: the first order settles");
Check(!Settles(*rail, "CC-BBBBBB", 500),
"rail: the same payment does not settle the second");
}
auto again = Rail(credits, oneForTwo);
Check(again != nullptr, "rail: it starts again on the claims it wrote");
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"rail: after a restart the payment is still spent");
Check(Settles(*again, "CC-AAAAAA", 500),
"rail: and the order it was spent on still finds it");
const std::string claims = Slurp(fs::path(credits.string() + ".claims"));
Check(std::ranges::count(claims, '\n') == 1,
"rail: settling the same order again writes no second claim", claims);
}
// A claims file that stops mid-line: a write cut short by a full disk, or
// a crash. The next claim used to be written straight onto the end of the
// broken line, where the next start could not read it, and the payment
// was free to settle a second order one restart later (found in review,
// reproduced end to end).
{
const fs::path credits = work / "torn.jsonl";
const fs::path claimsFile(credits.string() + ".claims");
{
std::ofstream out(claimsFile, std::ios::binary);
out << R"({"credit":"earlier-payment","refer)"; // and no line break
}
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "torn: the rail starts on a claims file cut short");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "torn: an order settles");
}
auto again = Rail(credits, oneForTwo);
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"torn: the claim written after a broken line survives the restart",
Slurp(claimsFile));
}
// A claims file that is there and cannot be read is a rail that cannot
// know what was spent. It must not run and treat every payment as fresh.
// A directory in the file's place stands in for "unreadable" here: file
// permissions would not stop this suite when it runs as root, as in CI.
{
const fs::path credits = work / "unreadable.jsonl";
fs::create_directories(fs::path(credits.string() + ".claims"));
Check(Rail(credits, oneForTwo) == nullptr,
"rail: it refuses to start on a claims file it cannot read");
}
// One payment listed twice. Not meant to happen and reproduced in review
// all the same (one callback delivered on two connections at once). A
// payer who sent half the price must not find the order settled by it.
{
const fs::path credits = work / "twice.jsonl";
auto rail = Rail(credits, {
Credit("CC-CCCCCC", 500, "sepa", "pay-7"),
Credit("CC-CCCCCC", 500, "sepa", "pay-7") });
if (!rail) return;
Check(!Settles(*rail, "CC-CCCCCC", 1000),
"rail: half the price listed twice does not settle the order");
Check(Settles(*rail, "CC-CCCCCC", 500),
"rail: and still pays for what it is worth");
}
}
} // namespace } // namespace
int main() { int main() {
@ -133,8 +261,11 @@ int main() {
// ── the ambiguity tripwire ─────────────────────────────────────── // ── the ambiguity tripwire ───────────────────────────────────────
// One transfer quoting two orders cannot be attributed by a per-order // One transfer quoting two orders cannot be attributed by a per-order
// matcher: both orders would see the full amount and both would settle on // matcher: both orders see the full amount. The flag is advisory and
// the same money. The matcher cannot fix it, so it flags it for a human. // decides nothing (a reference shape is also what a name followed by a
// date looks like); it is there so the log can point at the settlement.
// What keeps both orders from settling on the same money is the next
// section.
{ {
const Server::TransferMatch m = const Server::TransferMatch m =
Match({ Credit("CC-2B6457 and CC-AAAAAA", 10000) }, ref); Match({ Credit("CC-2B6457 and CC-AAAAAA", 10000) }, ref);
@ -145,6 +276,138 @@ int main() {
Check(!clean.ambiguous, "an ordinary credit is not flagged"); Check(!clean.ambiguous, "an ordinary credit is not flagged");
} }
// ── money is spent once ──────────────────────────────────────────
//
// The trick this closes: place three orders, then send ONE transfer whose
// text names all three. Each order looks for its own reference, finds it,
// and sees the full amount, so with nothing recording that the money was
// used, all three settle on a single payment. The flag above cannot stop
// that (it is a guess about text a stranger wrote). The claim does: a
// payment that settled one order pays for no other.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA CC-BBBBBB", 5000, "sepa", "pay-1") };
// Unspent, every order it names sees the money. That much is right:
// which of them it pays for is decided by which settles first.
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.paidMinor == 5000, "an unspent payment counts for an order it names");
Check(Server::MatchCredits(credits, "CC-AAAAAA").paidMinor == 5000,
"and, until one of them settles, for the others it names too");
Check(first.credits == std::vector<std::string>{ "pay-1" },
"the match names the payment to claim, by the bank's id");
Check(first.spentElsewhere == 0, "nothing is reported spent before a claim");
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch other =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(other.paidMinor == 0 && other.count == 0,
"a payment that settled one order pays for no other",
std::format("{}", other.paidMinor));
Check(other.spentElsewhere == 1,
"and the match says the money was there and is spent");
Check(other.credits.empty(), "a spent payment is not offered for a second claim");
Check(Server::MatchCredits(credits, "CC-BBBBBB", claims).paidMinor == 0,
"nor for a third order");
// The order that holds the claim must still find its own money: a
// settlement that was claimed and then never reached the ledger is
// completed from exactly this.
const Server::TransferMatch own = Server::MatchCredits(credits, ref, claims);
Check(own.paidMinor == 5000 && own.spentElsewhere == 0,
"the order that claimed a payment still counts it");
const std::vector<Server::CreditClaim> spelled = { { "pay-1", "cc 2b6457" } };
Check(Server::MatchCredits(credits, ref, spelled).paidMinor == 5000,
"however the claim spells that order's reference");
Check(Server::MatchCredits(credits, "CC-AAAAAA", spelled).paidMinor == 0,
"and it still shuts the other orders out");
}
// A claim is on ONE PAYMENT, not on a reference. Another payment for the
// same order is untouched by it, which is what keeps "send the rest the
// same way" true for an order that shared its first transfer.
{
const std::vector<BankCredit> credits = {
Credit("CC-AAAAAA and CC-2B6457", 3000, "sepa", "pay-1"),
Credit("CC-AAAAAA", 2000, "ideal", "pay-2") };
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch m =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(m.paidMinor == 2000 && m.count == 1,
"only the spent payment is left out of the sum",
std::format("{} in {}", m.paidMinor, m.count));
Check(m.spentElsewhere == 1, "the spent one is counted as spent");
Check(m.credits == std::vector<std::string>{ "pay-2" },
"only the payment still unspent is offered for a claim");
Check(m.method == "ideal", "the method is that of a payment that counted", m.method);
}
// A claim for a payment the account no longer shows changes nothing: the
// pull replaces the credits file every hour and old payments leave it.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457", 5000, "sepa", "pay-9") };
const std::vector<Server::CreditClaim> claims = { { "long-gone", "CC-ZZZZZZ" } };
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"a claim on some other payment does not touch this one");
}
// A line written by hand may carry no id. It is still one payment, and
// has to be claimable like one, or the hand-written escape hatch would be
// the one place the old trick still worked.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA", 5000, "sepa", "") };
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.credits.size() == 1 && !first.credits[0].empty(),
"a credit with no id still has a key to be claimed under");
if (first.credits.size() == 1) {
const std::vector<Server::CreditClaim> claims = {
{ first.credits[0], "CC-2B6457" } };
Check(Server::MatchCredits(credits, "CC-AAAAAA", claims).paidMinor == 0,
"and is spent once like any other");
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"while its own order still counts it");
}
}
// ── one payment is counted once ──────────────────────────────────
//
// Two lines with the same bank id are one payment. Summed, they double
// the money against the reference, which settles a half-paid order.
{
const Server::TransferMatch twice = Match(
{ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-1") }, ref);
Check(twice.paidMinor == 2500 && twice.count == 1,
"a payment listed twice is counted once",
std::format("{} in {}", twice.paidMinor, twice.count));
Check(twice.duplicates == 1, "and the second line is reported as a duplicate");
Check(twice.credits == std::vector<std::string>{ "pay-1" },
"it is still one payment to claim");
// Different ids are different payments, however alike they look:
// this is the top-up the order page asks for.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-2") }, ref) == 5000,
"two payments of the same amount are both counted");
// And with no id there is nothing to tell two lines apart by, so a
// hand-written pair is taken as two payments, as it always was.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", ""),
Credit("CC-2B6457", 2500, "sepa", "") }, ref) == 5000,
"two lines without an id are each counted");
}
// ── the rail: claims on disk, across restarts ────────────────────
{
std::error_code ec;
const fs::path work = fs::temp_directory_path(ec)
/ std::format("catcrafts-transfer-{}", Server::NewOrderToken());
fs::create_directories(work, ec);
if (ec) {
std::println(std::cerr, "could not create {}: {}", work.string(), ec.message());
return 1;
}
TheRailRemembersWhatWasSpent(work);
fs::remove_all(work, ec);
}
// An empty account is a clean zero rather than anything alarming: it is // An empty account is a clean zero rather than anything alarming: it is
// simply the state of every order between checkout and payment. // simply the state of every order between checkout and payment.
Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error"); Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error");

View file

@ -275,5 +275,89 @@ int main(int argc, char** argv) {
"the order's own credit still settles it afterwards"); "the order's own credit still settles it afterwards");
} }
// ── one payment pays for one order ────────────────────────────────
//
// Three orders, then ONE transfer for the price of one whose text names
// all three. Each order looks for its own reference and finds the full
// amount against it, so before the rail recorded what a payment had been
// spent on, all three settled: three thank-you pages, three entries in
// the public donations total, one payment. Found in review on 2026-11-26.
//
// Over HTTP and not only in ShouldMatchBankTransfers, because the rule is
// not in the matcher alone: it needs the rail to write the claim when it
// settles and to judge the next order against it, across separate polls
// on separate threads. That wiring is what this proves.
{
const std::array<Order, 3> orders = {
PlaceDonation(srv, "5.00"), PlaceDonation(srv, "5.00"),
PlaceDonation(srv, "5.00") };
for (const Order& o : orders) {
if (o.token.empty()) return Finish();
}
Credit(credits, "e2e-4",
std::format("{} {} {}", orders[0].reference, orders[1].reference,
orders[2].reference),
500);
auto settled = [&](const Order& o) {
return srv.Body("/order/" + o.token).find(kPaidCopy) != std::string::npos;
};
auto settledCount = [&] {
int n = 0;
for (const Order& o : orders) n += settled(o) ? 1 : 0;
return n;
};
int paid = 0;
for (int i = 0; i < 120 && paid == 0; ++i) {
paid = settledCount();
if (paid == 0) std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
Check(paid >= 1, "a payment naming three orders settles one of them");
// Long enough for several sweeps to have judged the other two against
// the same credit, which is still sitting in the file naming them.
std::this_thread::sleep_for(std::chrono::seconds(4));
paid = settledCount();
Check(paid == 1, "and only one: the same money does not settle the others",
std::format("{} of 3 settled", paid));
// The two it did not pay for read as plainly unpaid. Not "part
// payment received": that would be counting the spent money toward
// them after all, only short of the total.
const Order* passedOver = nullptr;
for (const Order& o : orders) {
if (settled(o)) continue;
if (!passedOver) passedOver = &o;
srv.BodyHas("/order/" + o.token, "awaiting payment",
"an order the payment did not settle still reads as unpaid");
srv.BodyLacks("/order/" + o.token, "part payment received",
"and is not shown the spent money as a part payment");
}
// What was spent is on disk, next to the credits, so a restart does
// not forget it, and the log says why two orders are still waiting.
const std::string claims = ReadFile(fs::path(credits.string() + ".claims"));
Check(CountOccurrences(claims, "\"credit\":\"e2e-4\"") == 1,
"the settlement recorded one claim for that payment",
std::format("{} claim line(s) for it",
CountOccurrences(claims, "\"credit\":\"e2e-4\"")));
Check(ReadFile(srv.Work() / "server.log").find("one payment pays for one order")
!= std::string::npos,
"the log says why the other orders are not settled");
// An order that was passed over is not stuck: a payment of its own
// settles it, and the third still waits.
if (passedOver) {
Credit(credits, "e2e-4b", passedOver->reference, 500);
const std::string body =
srv.WaitForBody("/order/" + passedOver->token, kPaidCopy, 120);
Check(body.find(kPaidCopy) != std::string::npos,
"an order passed over settles on a payment of its own");
Check(settledCount() == 2, "and the third order is still unpaid",
std::format("{} of 3 settled", settledCount()));
}
}
return Finish(); return Finish();
} }