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:
parent
06ec1c525c
commit
3c61116531
4 changed files with 683 additions and 23 deletions
|
|
@ -108,16 +108,31 @@ bool HasOtherReferenceShape(std::string_view folded, std::size_t foundAt,
|
|||
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
|
||||
|
||||
TransferMatch MatchCredits(std::span<const BankCredit> credits,
|
||||
std::string_view reference) {
|
||||
std::string_view reference,
|
||||
std::span<const CreditClaim> claims) {
|
||||
TransferMatch out;
|
||||
const std::string needle = Fold(reference);
|
||||
// An empty needle would match every credit on the account. Refuse rather
|
||||
// than settle the whole ledger from one payment.
|
||||
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) {
|
||||
// Only money coming IN can pay for something. A negative amount is an
|
||||
// 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::size_t at = folded.find(needle);
|
||||
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.count;
|
||||
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;
|
||||
}
|
||||
return out;
|
||||
|
|
@ -198,7 +241,22 @@ private:
|
|||
class TransferRail final : public PaymentRail {
|
||||
public:
|
||||
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
|
||||
// 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();
|
||||
if (!all) return std::nullopt; // unknown, retry — never "unpaid"
|
||||
|
||||
const TransferMatch m = MatchCredits(*all, reference);
|
||||
if (m.ambiguous) {
|
||||
// ONE order is judged at a time from here to the claim below. The
|
||||
// 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,
|
||||
"transfer: {} matched a credit that also quotes another "
|
||||
"order reference — settle this one by hand", reference);
|
||||
"transfer: {} is quoted by a payment the credits file "
|
||||
"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;
|
||||
out.method = m.method.empty() ? std::string("sepa") : m.method;
|
||||
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;
|
||||
return out;
|
||||
}
|
||||
|
|
@ -368,11 +470,130 @@ private:
|
|||
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_;
|
||||
std::unique_ptr<CreditSource> credits_;
|
||||
std::mutex mutex_;
|
||||
std::optional<std::vector<BankCredit>> cached_;
|
||||
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
|
||||
|
|
@ -381,30 +602,53 @@ std::unique_ptr<CreditSource> MakeFileCreditSource(std::filesystem::path 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,
|
||||
const BankCredit& credit) {
|
||||
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
|
||||
// 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.
|
||||
// Appending it twice would double the money against one reference —
|
||||
// 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::string line;
|
||||
while (std::getline(in, line)) {
|
||||
const std::string text((std::istreambuf_iterator<char>(in)),
|
||||
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;
|
||||
const auto doc = Json::Parse(line);
|
||||
if (!doc || !doc->IsObject()) continue;
|
||||
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);
|
||||
if (!out) {
|
||||
std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string());
|
||||
return false;
|
||||
}
|
||||
if (torn) out << '\n';
|
||||
out << std::format(
|
||||
R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n",
|
||||
EscT(credit.id), EscT(credit.reference), credit.amountMinor,
|
||||
|
|
@ -433,7 +677,19 @@ std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
|
|||
"account-holder name");
|
||||
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
|
||||
|
|
|
|||
Loading…
Reference in a new issue