5. Accounting & Capacity (fleetmesh_core.accounting)
The fleetmesh_core.accounting package implements the economic and resource-metering
engine of Fleetmesh, including Cashu token verification, sliding-window quotas,
capacity pricing ladders, and paid fetch quotation.
5.1. Accounting Core
Receipts, their hash chain, and telling a dead peer from a lying one.
The chain is what stops a subject rewriting an earlier claim once it learns what the issuer measured. The issuer keeps the head, which is 32 bytes per window, and the most recent body, because that body is the claim the window is evaluated against and the evidence any report about it must carry.
- fleetmesh_core.accounting.accounting.canonical(receipt)[source]
constants.json canonical.form: keys sorted by code point, no whitespace - crypto.canonical, with one difference:
sig is excluded, because it is a signature over this. Excluding it means the chain link is the same value whether or not the receipt has been signed yet, so signing changes no head and breaks no chain.
- fleetmesh_core.accounting.accounting.sign_receipt(body, sk_hex)[source]
The subject signs its own claim. BIP-340 over the chain link, which is already SHA-256 of the canonical body, so no second construction is defined and the head the issuer acknowledges is the message that was signed.
This is what makes a receipt evidence. Without it a report about divergence cites a number only the reporter has ever seen the subject state, which is hearsay; with it the subject’s half of the disagreement is pinned and the reporter is trusted only for its own measurement.
- Parameters:
body (ReceiptBody)
sk_hex (str)
- Return type:
- fleetmesh_core.accounting.accounting.verify_receipt(body, subject_pubkey)[source]
True when this receipt carries the subject’s signature over its own link.
- fleetmesh_core.accounting.accounting.build_chain(grant_id, window, counter_series, start_at=1787000000, step=600)[source]
Produce a well-formed chain. Counters are cumulative and monotonic.
- fleetmesh_core.accounting.accounting.verify_chain(chain, head=None)[source]
Check every link, sequence number and monotonicity claim.
Returns a list of failures; empty means the chain holds. A subject that rewrote seq 3 after the fact cannot also produce a matching seq 4.
This is strict about sequence, and stays strict, because what it checks is a complete chain carried as evidence: a report cites what its subject signed, and a chain with a hole in it is not the artefact it claims to be. Live intake is the other case and is deliberately not this one - node.budget.on_receipt tolerates a gap, because there the missing link is the wire rather than the subject, and refusing it costs a whole window.
- fleetmesh_core.accounting.accounting.admissible_prefix(receipts)[source]
The longest gap-free, chain-verified prefix of a stored receipt list, and whether anything was cut.
Live intake (node.budget.on_receipt) tolerates a lost link: a receipt at seq 5 after seq 3 is stored, because the hole is the wire’s and refusing it costs a window. verify_chain is strict for the same reason in the opposite direction: a chain cited as evidence must be the artefact the subject signed, whole. Reporter used to attach every stored body, so an S2 about a peer that lost one receipt on the wire carried a chain a verifier would reject on sight - and a report with inadmissible evidence is discarded unread. This keeps what verifies, from seq 0 up to the first hole or broken link, so what is published is always admissible; partial is reported so the caller can say so.
- fleetmesh_core.accounting.accounting.silence(measured)[source]
Active or inactive silence, per the partition-tolerance rule.
Receipts missing while the peer moved bytes is a misreport. Receipts missing while it moved nothing is a partition, and FLP says you cannot tell a dead node from a quiet one - so the protocol does not try, and prices only the case where physical traffic contradicts the silence.
- fleetmesh_core.accounting.accounting.window_claim(receipts, measured)[source]
What a window is evaluated against, per constants.json grant.window_evaluation.
receipts are the bodies received this window, in order. The most recent one is the claim: counters are cumulative, so it already states the whole window, and the chain makes it binding. A subject that sent receipts and then went quiet is evaluated on what it last said against what was measured after - which is how a leaf that syncs and then sleeps produces no finding, and a peer that kept moving bytes after its last receipt is priced by divergence. Returns (state, counters): (‘claim’, counters), (‘active-silence’, None) or (‘not-evaluated’, None).
None means there is no claim, not that there is nothing to evaluate. A window measured with no receipt is still evaluated - against the empty claim, which is what vectors/window.json’s “no receipt at all” case does - and active silence is a floor of S2 on top of that. Skipping the arithmetic would price a peer that overran and said nothing below the same peer reporting it honestly, which is the inversion docs/mechanisms.md § 9 describes for divergence, in its other form.
- fleetmesh_core.accounting.accounting.close_is_final(close_at, window_end, window_seconds)[source]
A close arriving within the grace period is accepted as the window’s final receipt; later than that it is evaluated like any other receipt.
The grace span is half-open like the window itself: [window_end, window_end + grace). The evaluator fires once now >= window_end + grace (node budget/windows.py), so a close stamped at exactly that instant arrives at or after evaluation and is late, not final.
- fleetmesh_core.accounting.accounting.epoch(unix_seconds, window_seconds)[source]
floor(t / window). Derived from the clock, so it cannot pause.
A dormant span advances the epoch counter and simply is not evaluated: the streak neither advances nor breaks, and the next active window starts a fresh chain at seq 0. The window is [epoch * window, (epoch+1) * window).
5.2. Sliding-Window Credit & Rate Limiting
Reference implementation of the fleetmesh window evaluator and trust weighting.
Standard library only. Every constant is read from schema/constants.json rather than hardcoded, so this file and the protocol version digest cannot disagree.
Exists to make the arithmetic executable. Writing it found three things the specification referenced but never defined: class(overrun, divergence), the per-tier limit ceilings, and the divergence tolerance that triggers S2.
- fleetmesh_core.accounting.window.counter_of(limit)[source]
The receipt counter a limit is priced against. Most limits and counters share a name; grant.counter_of in constants.json names the exceptions. conn_rate was in every tier’s ceilings and priced by nothing, because the session counts sessions as conn_open and this looked a limit up by its own name - the third constant found declared and never read, after dup_ratio and max_clock_skew_seconds. The mapping is digested now, so an implementer cannot miss it the way this one did.
- fleetmesh_core.accounting.window.outranks(tier, other)[source]
Whether tier sits above other on the ladder.
The order is tier_weight’s, which is the one the specification already ranks them by - a reporter’s word is weighed by it - rather than a second list that could disagree with the first. An unknown tier ranks lowest, which is what probation means.
- fleetmesh_core.accounting.window.ceilings(tier)[source]
Limit ceilings for a tier. dup_ratio is a quality signal and does not scale.
- fleetmesh_core.accounting.window.classify(overrun, divergence)[source]
class(overrun, divergence) -> severity, for one limit.
The specification defines a window as the max over all limits of this function and never defines the function, so the shape below is a choice.
A misreport is a floor of S2 and not a ceiling. Returning S2 the moment divergence crossed its threshold - which is what this did - priced a peer that overran its limit four times over and lied about it below the same peer reporting it honestly, because honesty reaches S3 on overrun alone. fleetmesh_core/peering/badpeer.py runs both, and the inversion is what it found. Lying must never be the cheaper option, so divergence raises the class the overrun already earned rather than replacing it.
- fleetmesh_core.accounting.window.per_session(name)[source]
What one session costs of this counter.
One for almost everything: a session is one connection, one request, one of most things. Ranges are the exception and the number is not invented here - tier_limits.ranges_per_session is where it was measured on the alpha mesh and where it is already justified, and a second copy would be a second thing to keep true.
- fleetmesh_core.accounting.window.evaluate_window(limits, measured, claimed)[source]
Evaluate one closed window.
limits/measured/claimed are dicts keyed by limit name. Returns the window severity and the per-limit detail that produced it.
- fleetmesh_core.accounting.window.within(limits, tier)[source]
Hold a limit set inside the ceilings of the tier it is written at.
constants.json states the invariant plainly: a grant MAY set any limit lower than its tier ceiling and MUST NOT set one higher. _write_grant applies it at first issue and the remedy never did. S2 quarters the limits and drops the tier to probation, and max(probation, v * 0.25) is a floor, so for any peer above probation it did nothing at all: an anchor came out of an S2 holding 12,000 events an hour at a tier whose ceiling is 300 - forty times over - and held it for as long as it produced nothing measurable, because an unevaluated window never adjusts anything. The next clean window then dropped it from 12,000 to 300 in one step, which was the same defect seen from the other side.
Applied on the way out of every branch, the remedy cannot leave a grant its own tier forbids, and a grant that somehow arrived in that state is repaired by the next adjustment rather than surviving it.
- fleetmesh_core.accounting.window.strain(limit_name, limit, used)[source]
How much of one limit the closed window actually carried, in [0, 1].
An S0 window can reach 1.1 of a limit and still be clean, so the ratio is clipped: a peering is not owed extra growth for the tolerance.
- fleetmesh_core.accounting.window.step_fraction(limit_name, limit, used)[source]
The additive step for one limit, as a fraction of its tier ceiling.
Wood is laid down where the strain was. The step used to be a flat fraction of the ceiling whatever the window carried, so a peering moving one event an hour grew exactly as fast as one running at its limit: capacity was priced in windows rather than in work, and the cheapest route to a large grant was to be present and idle. It is scaled by use now, with a floor - a quiet peering still creeps upward, because a tree does grow without wind and it grows tall and slender and cannot stand.
- fleetmesh_core.accounting.window.as_limits(d)[source]
Grant limits, as integers, rounded DOWN.
canonical.numbers says it plainly: integers, written as plain decimal digits, and the only fractions anywhere in this protocol are in constants.json itself. A commitment is taken over canonical(grant), so a float in a limit is not a cosmetic problem - two implementations may serialise 3.7999999999999994 differently and the commitment stops verifying.
It never mattered until the arithmetic stopped being flat. The old step was a fixed fraction of a ceiling and always clamped to it, so every limit came out an integer by luck; a step scaled by strain, a decay, and a capacity shed all produce fractions. Found on a live node an hour after the first deploy, in a grant reading conn_rate 3.7999999999999994.
Down and not nearest, so a limit is never larger than what the ladder decided. Down means towards minus infinity for negatives too (math.floor), so -0.5 becomes -1 rather than 0: a limit is never rounded up past what was decided, whichever side of zero it sits.
Anything that is not a real number raises ValueError naming the key. A grant is committed to and verified by its canonical bytes, so a string or None that slipped through here would be signed into a commitment nobody can reason about; refusing is the honest answer.
- fleetmesh_core.accounting.window.opening_limits(tier)[source]
What a fresh grant at a tier carries.
Volume opens at a fraction of the ceiling so that carrying load is what earns the rest; a grant that opened at the full ceiling left the additive increase nothing to do, which is why nothing in this protocol grew. The structural limits open at the ceiling, because a peer needs enough plumbing to demonstrate anything at all: what is earned is volume, never the right to open a session.
- fleetmesh_core.accounting.window.decay(limits, tier, fraction=None)[source]
Give back what disuse has not earned, down to where a stranger starts.
The pair to growth, and the reason growth may be allowed to reach a ceiling at all. A limit moved up on a clean window and down on a fault and never decayed, so capacity earned in one busy week sat there a year later as surface nobody was watching.
The floor is the tier’s opening limits, never lower: what a peer has not used it gives back, and what every peering is given it keeps. The structural limits open at the ceiling, so they never decay - an error budget that wasted away would trip on the first bad hour.
- fleetmesh_core.accounting.window.adjust(limits, tier, severity, used=None)[source]
Apply the ladder’s remedy to a limit set. Returns (limits, tier, note).
used is the closed window’s measured counters, and the clean branch grows each limit in proportion to how much of it that window carried. An evaluation that offers none gets the minimum step and never the full one: absent evidence of load is not evidence of load.
Every branch returns limits inside the ceilings of the tier it returns, so a grant’s tier and the numbers beside it can never disagree.
- fleetmesh_core.accounting.window.reporter_weight(tier_of_reporter, clean_windows, contradicted=0, evaluated=0)[source]
5.3. Capacity Ladder & Shedding
Reference implementation of the node’s own ceiling and the shed ladder.
Standard library only. Every constant is read from schema/constants.json rather than hardcoded, so this file and the protocol version digest cannot disagree.
A grant bounds one peer. Nothing bounded the node. Meter is per peer and the tick loops them, so twenty anchor peerings each perfectly inside its grant is 960,000 events an hour with nobody at fault anywhere: every branch within its limit, and the trunk with none. That is the fragility this file answers.
Two decisions worth stating here rather than leaving to a reader.
The total is the operator’s number and this file states no default. The specification says connectivity and not capability is what separates one deployment from another, so a Raspberry Pi and a forty-core gateway both declare anchor and no per-class table could be honest about either. What is normative is the ladder. A node with no declared total measures its pressure and reports it and sheds nothing, because refusing an honest peer against a limit nobody chose is worse than the overload it would be avoiding. suggest exists so an operator has a number to start from rather than a blank.
Shedding is announced, and it is not adverse. Every rung says what it is doing - a decline code, a republished coverage claim, an amend carrying cause: capacity. A node that shed quietly would be read as partitioned, which is the one conclusion this protocol keeps having to unlearn, and a subject that read a capacity shed as a remedy would price its issuer for owning a small machine.
- fleetmesh_core.accounting.capacity.pressure(measured, total)[source]
(fraction, binding counter) for one window’s aggregate against a total.
The fraction is the max over counters, not a mean: a node that has run out of one thing has run out. total is a dict of the same counter names; a counter the operator did not declare is not measured, and a total of zero or less is not a declaration.
- fleetmesh_core.accounting.capacity.rungs(p)[source]
Every shed action engaged at pressure p, in ladder order.
- fleetmesh_core.accounting.capacity.engaged(p, held=())[source]
The rungs a node should be holding now, given what it holds already.
Rungs engage each at its own threshold and release together below restore_below. Releasing each at the threshold that engaged it would flap a node sitting on a boundary, and each flap costs its peers an amend.
- fleetmesh_core.accounting.capacity.shed_floor(probation)[source]
The lowest a capacity shed may take a limit, from the probation ceilings.
Deliberately not the probation ceiling itself. A peering opens at that ceiling, so a floor there would make the amend_down rung do nothing at all for exactly the peers a busy node has most of - declared and never read, which is a shape this specification keeps finding in itself. Deliberately not zero either: zero for 24 hours is what S3 does to an offender, and a shed is not a remedy. What is left is enough for a receipt and a trickle, which is what keeps a small peering accountable rather than silent.
- fleetmesh_core.accounting.capacity.reduce(limits, floor, fraction=None)[source]
Scale a grant’s limits for a capacity shed, never below the floor.
A capacity shed makes a peer smaller and never makes it a stranger: the tier does not move and the peering is not ended. That is what separates it from an S2, which is the ladder’s business and not this file’s. Pass the floor from shed_floor.
- fleetmesh_core.accounting.capacity.suggest(windows)[source]
A total to start from, per counter: the largest window observed.
windows is an iterable of aggregate measurements, one per closed window. This is a report of what the machine has already carried and not a claim about what it can. An operator raises it deliberately or lowers it after watching the box, and either way the number is theirs.
5.4. Cashu Ecash Integration
Cashu as it crosses the wire, standard library only. The portable half of a node’s e-cash: a second implementation needs exactly this and nothing of the rails that move money.
BDHKE (NUT-00..03) over secp256k1: hash_to_curve, blind, sign, unblind, verify a proof. Pinned to the NUT-00 vectors in vectors/cashu.json. Tokens: V3 (cashuA, JSON) and V4 (cashuB, CBOR); NUT-18 payment requests (creqA); NUT-11 P2PK secrets. NIP-61 Nutzaps (kind 9321): create, read the proofs, reconcile the stated amount against what the proofs are worth, and the one proof-acceptance policy (mint key, else a verifier that asks the mint, else refuse).
The curve arithmetic is fleetmesh_core.crypto’s; a node that installed a faster point_mul (meshnode’s node/curve.py) speeds this up too, since every multiplication goes through crypto.point_mul. Nothing here talks to a mint or keeps state; every parse error is a ValueError with a reason a 402 body can carry. mint_url is normalised by stripping trailing slashes, which NUT-00 requires of a V4 token and which makes an allowlist comparison a string equality.
- class fleetmesh_core.accounting.cashu.CashuProof[source]
Bases:
TypedDictOne NUT-00 proof as it arrives in a token or a Nutzap’s proof tag. Annotations only: the mint’s keyset is what makes it worth anything.
- class fleetmesh_core.accounting.cashu.CashuTokenEntry[source]
Bases:
TypedDict- proofs: list[CashuProof]
- class fleetmesh_core.accounting.cashu.CashuToken[source]
Bases:
TypedDict- token: list[CashuTokenEntry]
- class fleetmesh_core.accounting.cashu.DecodedTokenV4[source]
Bases:
TypedDict- proofs: list[CashuProof]
- class fleetmesh_core.accounting.cashu.CheckStateResult[source]
Bases:
TypedDict- states: list[ProofState]
- class fleetmesh_core.accounting.cashu.SwapResult[source]
Bases:
TypedDict- signatures: list[BlindSignature]
- fleetmesh_core.accounting.cashu.hash_to_curve(secret)[source]
Domain-separated hash-to-curve on secp256k1 per Cashu NUT-00.
Y = PublicKey(‘02’ || SHA256(msg_hash || counter)) with msg_hash = SHA256(DOMAIN_SEPARATOR || x) and a little-endian uint32 counter incremented from 0 until lift_x lands on the curve. The ‘02’ prefix means the even-y point is always chosen, so this returns the even-y lift and point_to_hex renders it as ‘02…’.
An earlier version re-hashed the digest itself until it lifted, which is the pre-2024 construction. Every proof a mint knows is indexed by this Y: NUT-07 check-state asks about Y, and NUT-03 swap recomputes Y from the secret to verify C == k*Y. With the old construction a nutshell 0.21 mint minted our blinded outputs fine (blinding never shows it Y) and then refused the resulting proofs on swap, which is the step verify depends on for finality. The NUT-00 test vectors are pinned in node/tests/test_settlement.py so this cannot drift again.
- fleetmesh_core.accounting.cashu.point_to_hex(pt)[source]
Format secp256k1 point as 33-byte compressed hex string (02/03 prefix).
- fleetmesh_core.accounting.cashu.hex_to_point(h)[source]
Parse 33-byte compressed secp256k1 point hex string.
- fleetmesh_core.accounting.cashu.blind_message(secret, r=None)[source]
Alice blinds secret x: returns (B_prime_hex, r).
B’ = Y + r*G where Y = hash_to_curve(x).
- fleetmesh_core.accounting.cashu.sign_blinded(B_prime_hex, mint_privkey_hex)[source]
Mint signs blinded point B’: returns C_prime_hex.
C’ = k * B’ where k is mint private key.
- fleetmesh_core.accounting.cashu.unblind_signature(C_prime_hex, r, mint_pubkey_hex)[source]
Alice unblinds mint signature: returns C_hex.
C = C’ - r*K = C’ + (N - r)*K where K is mint public key.
- fleetmesh_core.accounting.cashu.verify_proof(proof, mint_pubkey_hex)[source]
Structural check of a Cashu proof (secret, C) against mint public key K.
THIS IS NOT A SIGNATURE CHECK, and no caller may treat it as one. The relation a proof asserts is C == k * hash_to_curve(secret) with K = k*G, and deciding it from K alone is the decisional Diffie-Hellman problem: without the mint’s private key k, or a Chaum-Pedersen DLEQ proof carried alongside the proof (NUT-12), the holder of K cannot tell a genuine C from a random on-curve point. An earlier version of this routine computed Y = hash_to_curve(secret) and K and then used neither, which read like a verification step had been dropped; nothing was dropped - there is no step available. What can be checked without k is that the proof is well formed: the secret is a string, C parses as a compressed point on secp256k1 and K parses. That is all this returns.
Real acceptance goes through verify_proof_with_key when this node IS the mint, or through the mint’s own check-state/swap endpoint when it is not. verify_nutzap_event refuses, rather than skips, when neither is wired.
- fleetmesh_core.accounting.cashu.verify_proof_with_key(proof, mint_privkey_hex)[source]
Direct verification of proof by mint using private key k: C == k * Y.
- fleetmesh_core.accounting.cashu.serialize_cashu_token(mint_url, proofs)[source]
Serialize proofs into standard Cashu V3 token string (cashuA…).
- Parameters:
mint_url (str)
proofs (Sequence[CashuProof])
- Return type:
- fleetmesh_core.accounting.cashu.deserialize_cashu_token(token_str)[source]
Parse standard Cashu V3 token string (cashuA…).
- Parameters:
token_str (str)
- Return type:
- fleetmesh_core.accounting.cashu.create_nutzap_event(sender_sk, recipient_pk, proofs, mint_url, amount_msat, target_event_id=None, comment='', unit='msat', now=None)[source]
Create and sign a standard NIP-61 Nutzap event (Kind 9321).
- fleetmesh_core.accounting.cashu.proofs_of(event)[source]
The proof tags of a Nutzap, parsed. Raises ValueError on a malformed one.
- Parameters:
event (NostrEvent | Mapping[str, Any])
- Return type:
- fleetmesh_core.accounting.cashu.proofs_amount_msat(proofs)[source]
What the proofs are actually worth, in msat.
A Cashu proof’s amount is denominated in the keyset’s unit, and the keysets this implementation mints and accepts are sat (NUT-00’s default and what every public mint issues), so the value is sum(amount) * 1000. The Nutzap’s amount tag is a free-text claim by the sender and is NOT what the mint signed; it is reconciled against this number and never trusted on its own. Raises ValueError for an amount that is not a positive integer.
- Parameters:
proofs (Sequence[CashuProof])
- Return type:
- fleetmesh_core.accounting.cashu.stated_amount_msat(tag_map)[source]
The sender’s own amount tag, normalised to msat by the unit tag.
create_nutzap_event writes the amount in msat and says so with unit=msat; a wallet following NIP-61 literally writes sat. Either is a claim about the same proofs and is held to the same reconciliation. None when the tag is missing, not a decimal integer, or in a unit this node does not price.
- fleetmesh_core.accounting.cashu.verify_nutzap_event(event, expected_recipient=None, mint_privkey_hex=None, proof_verifier=None, allow_unverified_proofs=False)[source]
Verify NIP-61 Nutzap event: returns (valid, reason, amount_msat).
The amount returned is the sum of the proofs, never the amount tag: the tag is what the sender says, the proofs are what the mint signed, and a grant expansion priced off the tag was a budget bypass - one 1-sat proof plus an amount of a billion bought a billion msat of bytes_in.
- Proof acceptance is one of three things, in this order:
mint_privkey_hex: this node is the mint, check C == k*Y directly;
proof_verifier: a callable that asks the real mint (check-state or swap) whether these proofs are unspent and genuine;
neither: REFUSED, unless the caller passes allow_unverified_proofs=True and so says in its own code that it is accepting IOUs. Silently skipping the check - which is what this did when no key was given - meant a production node with no mint key accepted any JSON with a secret field as payment.
- fleetmesh_core.accounting.cashu.accept_proofs(proofs, mint_privkey_hex=None, proof_verifier=None, allow_unverified_proofs=False)[source]
The one proof policy (see verify_nutzap_event): mint key, else a verifier that asks the mint, else refuse unless the caller opted into unverified IOUs. Every path that takes proofs as money goes through here, whatever shape they arrived in.
- fleetmesh_core.accounting.cashu.encode_token_v4(mint_url, unit, proofs, memo=None)[source]
Proofs in the JSON shape node/payment.py uses ({amount, id, secret, C[, witness]}) become one cashuB token. Proofs are grouped by keyset id as the format requires.
- fleetmesh_core.accounting.cashu.decode_token_v4(token)[source]
A cashuB string to {mint, unit, memo, proofs: [{amount, id, secret, C[, witness]}]}.
Keyset ids come back as hex, full or short form as sent: the caller that talks to the mint resolves a short id against the mint’s keysets.
- Parameters:
token (str)
- Return type:
- fleetmesh_core.accounting.cashu.token_amount(decoded)[source]
- Parameters:
decoded (DecodedTokenV4 | Mapping[str, Any])
- Return type:
- fleetmesh_core.accounting.cashu.encode_payment_request(amount, unit, mints, payment_id=None, description=None, single_use=True, p2pk_pubkey=None)[source]
A creqA request with no transport: NUT-24 payment is in-band, in the retried request’s X-Cashu header. mints is strict (no mp): a token from any other mint is refused, which is the allowlist of §3.5. p2pk_pubkey, when given, is the 33-byte compressed key the proofs must be locked to (NUT-10 kind P2PK).
- fleetmesh_core.accounting.cashu.decode_payment_request(req)[source]
- Parameters:
req (str)
- Return type:
- fleetmesh_core.accounting.cashu.p2pk_secret(pubkey_compressed_hex, nonce=None, tags=None)[source]
The serialised well-known secret a P2PK-locked proof carries. The mint signs hash_to_curve(this string), so the string, not a parsed form, is what the proof holds and what the witness signs.
- fleetmesh_core.accounting.cashu.parse_well_known_secret(secret)[source]
(kind, data) for a NUT-10 secret, None for a plain random secret.
5.5. Paid Fetch Pricing
Paid fetch (profile paid-fetch-402): the shape of the refusal that names a price.
A Blossom GET, a sidecar session, or any other metered face answers 402 Payment Required with
X-Price-Msat: <total> X-Cashu: <NUT-24 payment request>[, <request>] (one per item, when a cashu rail is offered)
and a JSON body {sha256, size, price_msat, items[{to, payee, msat}], offers[], expires}, optionally error when the 402 follows a payment that did not settle. items is who the money is for: to is operator or account, payee a hex pubkey. price_msat is always the sum of the items. offers is one entry per rail per item, {rail, request, item}; its request is rail-specific and opaque here.
The client pays by resending the request with X-Cashu: <token>[, <token>], one cashuB token per item in item order. Settlement, trust and the free tier are a node’s business and are not pinned.
- fleetmesh_core.accounting.paidfetch.msat_to_sat_ceil(msat)[source]
Cashu quotes in sat; the edge rounds up, so 1 msat costs 1 sat.
- class fleetmesh_core.accounting.paidfetch.Item[source]
Bases:
objectItem(to: ‘str’, payee: ‘str’, msat: ‘int’)
5.6. Standing & Reputation Credits
standing/1.0: what one node tells a third party about another, if it chooses.
The specification says two things about it and both are here. Answering is discretionary and declining is not adverse, so a node answers only about subjects it holds a grant to and declines everything else without that refusal meaning anything. And a tell carries a streak, not a score: the count of clean windows since the last one that was not, which is the same number the reader’s own age factor uses in reporter_weight.
The Ledger is the per-subject record a window evaluation writes into. Nothing in it is public; a tell is a summary the holder chooses to give.
- fleetmesh_core.accounting.standing.message(kind, body, frm, to, thid=None, mid=None)[source]
- Parameters:
kind (str)
body (StandingAskBody | StandingTellBody | Mapping[str, Any])
frm (str)
to (str)
thid (str | None)
mid (str | None)
- Return type:
- class fleetmesh_core.accounting.standing.Ledger[source]
Bases:
objectPer-subject window history, as the issuer of that subject’s grant saw it.
- record(subject, epoch, severity, tier)[source]
One window’s verdict, kept in WINDOW order rather than arrival order.
Everything downstream reads this list as a history: clean_windows() takes the streak from the end of it, and the tier a subject holds is the one its newest window left. Appending made both of those mean “the most recently recorded”, which is a different thing - a window can be priced late. A contested remedy asks for one to be evaluated again, and it can arrive days after the window it is about.
On the live mesh one did. Four windows from eight days earlier were re-priced S2 when a node restarted, and because they landed at the end of the list they set the peer’s tier to probation and its clean streak to zero - behind about 170 consecutive clean windows, and against a ladder that only goes down. The ledger recorded the contradiction plainly: a window whose own severity was S0, holding a tier of probation.
Re-pricing an old window is still a finding and still reported. What it is not is news about where the subject stands now.
- forget_window(subject, epoch)[source]
Take one window back out of the history. Returns the severity it held.
A window this node no longer stands behind is not a window it priced S0: it is a window it has nothing to say about, which is what an unevaluated window already means everywhere else - evaluations() yields severity None for one and the replay skips it. Recording a retraction as a clean window would be a second false statement in place of the first.
- severity_of(subject, epoch)[source]
What this ledger holds for one window, or None if it holds none.
- amend(subject, epoch, severity)[source]
Correct one window already recorded, in place.
A window is priced when its grace ends and a receipt covering it can arrive after that: the claim was late, not absent. Recording the corrected reading as a NEW window would count one window twice and would leave the streak broken by a reading that no longer stands, which is the whole of what the correction is for. Returns the severity it replaced, or None if this subject has no such window.
- on_revocation(subject)[source]
Standing MUST NOT transfer. The subject’s record ends here and a successor starts with none, so there is nothing to move.
- Parameters:
subject (str)
- Return type:
None
- record_report(reporter, report_id, contradicted)[source]
One kind 30802 this node read and could decide about.
contradicted is True when the report is unsupported (its evidence does not resolve, or resolves to something the subject did not sign) or refuted (the evidence verifies and the published classifier run over it does not produce the outcome claimed). Anything else is a finding this reader has no grounds to dispute, which includes two honest nodes that measured different traffic.
- report_record(reporter)[source]
(contradicted, evaluated) for a reporter, as this node has seen it.
- tell(subject)[source]
The body of a tell, or None if this node has nothing to say.
- Parameters:
subject (str)
- Return type:
StandingTellBody | None
5.7. Market Rates
The compute market: what an ask commits to, and what a dispute may admit.
The ask prices the work without describing it. The commitment is what stops the buyer swapping the job after quotes come back, and the verify mode declared in the ask is what fixes, in advance, which evidence a later dispute will accept.
- fleetmesh_core.accounting.market.ask_commitment(job_payload)[source]
SHA-256 over the canonical job spec, which the public ask carries.
- fleetmesh_core.accounting.market.commitment_holds(ask_event, job_payload)[source]
The seller checks that the job it was handed is the job that was quoted.
- Parameters:
ask_event (NostrEvent | UnsignedNostrEvent | Mapping[str, Any])
job_payload (Any)
- Return type:
- fleetmesh_core.accounting.market.declared_mode(ask_event)[source]
- Parameters:
ask_event (NostrEvent | UnsignedNostrEvent | Mapping[str, Any])
- Return type:
str | None
- fleetmesh_core.accounting.market.leaks_job(ask_event)[source]
An ask naming its module or input is not a confidential job.
Enforced in the JSON Schema too; restated here because a relay operator may want to reject at ingestion without running a validator.
- Parameters:
ask_event (NostrEvent | UnsignedNostrEvent | Mapping[str, Any])
- Return type:
- fleetmesh_core.accounting.market.admissible_evidence(mode, evidence)[source]
Does this evidence support a finding under the mode the ask declared?
A refutation citing evidence the declared mode does not admit is not a finding. This is what stops a buyer choosing the cheapest verification and then litigating as though it had bought the strongest.
- fleetmesh_core.accounting.market.needs_plaintext(mode)[source]
Whether adjudicating under this mode requires holding the job.
The hinge of the confidentiality argument: only the modes that answer False let a third party adjudicate a job it was never given.
- fleetmesh_core.accounting.market.jobs_to_detect(sample_rate, cheat_fraction, confidence=0.9)[source]
ln(1-c) / ln(1-pf) - how many jobs before a cheat is caught.
Stated in the specification and worth having executable, because the honest version of “we will catch them” is a number that depends on a job rate nobody has measured.
5.8. Strain & Shed Pressure
Reference implementation of the strain record and the direction rule.
Standard library only. Every constant is read from schema/constants.json rather than hardcoded, so this file and the protocol version digest cannot disagree.
Everything a node survives is currently thrown away. A restart, a partition, an aborted session, a reconnect, a clock that drifted - each is correctly refused as a finding about a peer, because the protocol must never conclude something about a peer from an absence, and then it is discarded entirely. The accusation goes and the information goes with it.
Kept, it sets the node’s own reserves. Two rules make that safe.
Local and defensive only. A strain record never becomes a finding and never crosses the wire, and a peer’s own account of what it has weathered is a claim rather than evidence and is not read. If the whole of a node’s response to being stressed is to become better prepared for that exact stress, then an attacker who causes it has done the node a favour and there is nothing to farm. Anything that instead paid a node in reputation or authority for having been attacked would be an invitation to manufacture the attack.
Directions, never magnitude. A reserve grows with the number of independent directions the stress came from and never with how much came from any one of them. A tree grows straight because the wind turns; where the wind is strong and always from one quarter the result is a flag tree, bent and one-sided and weaker overall. Each direction is capped, and weighted by the tier this node granted that peer - probation is 0.0, so free identities buy no directions at all, and a tier is only ever raised by a person. The sybil is priced by a constant that already existed.
- fleetmesh_core.accounting.strain.direction(peer=None, shard=None, transport=None)[source]
The unit adaptation counts: one peer, one shard, one transport.
- fleetmesh_core.accounting.strain.weigh(strain_by_direction, tier_of=None)[source]
Weighted directions, saturating. Never a function of magnitude.
strain_by_direction maps a direction to how much stress came from it, in whatever unit the caller counts; only whether it crossed the cap matters, which is the whole point. tier_of answers what tier this node granted a peer, defaulting to probation - weight zero - so an unknown peer buys nothing.
- fleetmesh_core.accounting.strain.multiple(weight)[source]
What a reserve is multiplied by, from 1.0 up to max_multiple.
Linear in weighted directions and flat once saturated. A node that has been stressed from four trusted directions holds four times what it would have.
- fleetmesh_core.accounting.strain.reserve(base, strain_by_direction, tier_of=None)[source]
A local reserve, thickened by how many directions have tested it.
- fleetmesh_core.accounting.strain.external(strain_by_direction)[source]
Only the directions a node can be dependent ON.
A direction naming neither a peer nor a transport is the node’s own event. A restart names nothing, so on a node that has just started it was the whole of the strain and the flag-tree warning fired at once, against an empty direction, on a sample of one. Found on hardware within a minute of the first deploy. Dependence is something a node has on somebody else.
- fleetmesh_core.accounting.strain.dominant(strain_by_direction)[source]
(direction, share) of the external direction accounting for most strain.
A node whose stress is nearly all one direction is a flag tree: it is structurally dependent on that peer and will snap when it leaves. Reported to the operator and never a finding about the peer, which has done nothing but be the only one there.