Skip to content

server/auth: Meshify auth - #3629

Open
martonp wants to merge 32 commits into
decred:masterfrom
martonp:mesh-auth
Open

martonp wants to merge 32 commits into
decred:masterfrom
martonp:mesh-auth

Conversation

@martonp

@martonp martonp commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

This PR builds on #3628 and integrates server/auth with mesh. It adds 17 commits, (+5,699, -1,787).

It adds command handlers and event appliers for:

  • Posting on-chain bonds and redeeming prepaid bonds: postbond and bond_posted.
  • Creating prepaid bond tokens: create_prepaid_bonds and prepaid_bonds_created.
  • Forgiving reputation penalties for an account or a single match: forgive_reputation and reputation_forgiven. Single-match forgiveness will remain restricted to single-server mode in the full mesh conversion.

The mesh conversion also required some design changes in how auth manages reputation and communicates with clients.

  • Previously, connected users' reputation was calculated using bonds and recent outcomes held with their local client state. To support users connecting to either node, reputation is calculated from stored outcomes and bonds, with calculated scores and bond data kept in an LRU cache. A database hook invalidates affected cache entries when reputation inputs change and sends updated reputation to locally connected users.

  • Periodic bond-expiry checks and their notifications are removed. Clients will need to track bond expiry themselves. BondExpiryThreshold is added to account.Reputation so clients can determine which bonds were included in the reported tier.

  • Legacy reputation is converted to points during the v9 database upgrade instead of when an account's reputation is first loaded. Snapshots can omit older order and match history needed for this conversion, so converting lazily could produce different scores on different nodes.

  • Auth also gains support for sending requests, responses, and notifications to clients through the mesh peer, and relaying their replies.

This PR replaces the functions called by the market and swap packages to record reputation outcomes with stubs. These stubs will be removed when those packages are updated to record outcomes through mesh events. Timers that unbook users’ orders when they remain disconnected for an extended period are also removed. This functionality will be restored in the upcoming PRs.

### server/db: Return account lookup errors

Return account lookup errors separately from an unknown account, and update auth
callers to handle them. This prevents database failures from being treated as
missing accounts or empty bond lists when connecting, posting bonds, or
calculating reputation. This is needed for mesh because a failed database lookup
must not be cached as though the account does not exist.

Pass the caller's context through account and bond queries so cancellation and
deadlines cover the entire lookup.
### server/meshevents: Add bond and reputation event payloads

Introduce the `server/meshevents` package as the catalog of mesh events shared
by the database and application packages. Define events for bond posting,
prepaid bond creation, and reputation forgiveness. Add JSON decoding for order
and match IDs to complement their existing JSON encoding.
### server/auth: Add reputation cache

Adds `repCache`, an LRU cache for account scores and bonds, to reduce repeated
database reads.

Previously, reputation calculations used active bonds and recent match,
preimage, and order outcomes held in memory for connected users. With mesh, both
nodes need to calculate reputation regardless of which node a user is connected
to.

The cache accepts a caller-supplied function that loads calculated scores and
bond data. Integration with database reads and reputation lookups is added in
subsequent commits.
### server/auth,db: Convert legacy reputation during the v9 upgrade

Previously, legacy reputation was converted to `points` when an account's
reputation was first loaded. With mesh, snapshots can omit older order and match
history needed for that conversion, so converting lazily could produce different
scores on different nodes.

Converts all remaining version-0 accounts during the v9 database upgrade
instead, before mesh starts. This completes the conversion once, so reputation
lookups can read directly from `points` and snapshots include the converted
data.
### server/auth: Calculate reputation from stored outcomes and bonds

Previously, reputation lookups used bonds and recent outcomes held in memory for
locally connected users. Updates these lookups to calculate reputation from
stored outcomes and bonds, using `repCache` to cache calculated scores and bond
data. This allows reputation to be calculated independently of which mesh node
the user connects to, without active users repeatedly querying the database.

Adds `UserReputationAt` to calculate reputation with bond expiry evaluated at a
supplied time. Stops periodic bond-expiry checks and retains expired bonds so
their contribution can still be calculated when replaying earlier events.

Adds `BondExpiryThreshold` to `account.Reputation` so clients can determine
which bonds were included in the reported tier. With periodic bond-expiry
notifications disabled, clients will need to track expiry themselves.

Adds `AcctRepStatus` with an error return so callers can distinguish a failed
reputation lookup from an unknown account or a zero tier. This will be required
by the unbooking logic to avoid removing orders when reputation cannot be
retrieved.
### server/auth: Add reputation input change hook

Adds `SetReputationInputsListener` and registers an auth callback that
invalidates affected cache entries when notified. The callback refreshes
reputation and sends score-change notifications to locally connected user.

The event appliers added in subsequent commits will invoke the listener after
updating reputation inputs.
### server/auth: Stub reputation outcome recording

Replaces the functions called by the market and swap packages to record
reputation outcomes with stubs. These stubs will be removed when those packages
are updated to record outcomes through mesh events.
### server/auth: Remove legacy unbooking and bond expiry handling
### server/auth: Add mesh client-message proxy support

Adds support for delivering requests and notifications to clients connected
through a mesh peer, routing responses back to their handlers, and expiring
unanswered requests. Keeps local-only delivery available for node-local
notifications.
### server/db/pg: Apply posted bond events

Adds `ApplyBondPostedEvent` to store posted bonds, create accounts when needed,
and consume prepaid bond tokens. Returns the account's bonds and latest
reputation outcomes from the same transaction so auth can calculate the
reputation returned with the bond response.
### server/auth: Process bond posting through mesh

Adds the `postbond` command, which validates on-chain bonds and prepaid-token
redemptions, waits for any missing confirmations, and emits a `bond_posted`
event for newly accepted bonds. Adds the `bond_posted` event handler, which
stores the account and bond and consumes the prepaid token when redeeming one.

Adds the initial mesh setup in the `dex` package. Since dcrdex configuration
options for mesh have not been added yet, the service runs in single-server
mode.
### server/db/pg: Apply prepaid bond creation events

Adds `ApplyPrepaidBondsCreatedEvent` to store newly created prepaid bond tokens.
### server/auth: Create prepaid bonds through mesh

Adds the `create_prepaid_bonds` command, which generates prepaid bond tokens
with the requested strength and lifetime and emits a `prepaid_bonds_created`
event. Adds the event handler, which stores the tokens in the db.
### server/db/pg: Apply reputation forgiveness events

Adds `ApplyReputationForgivenEvent` to forgive all penalties on an account or
the penalties associated with a single match.
### server/auth: Process reputation forgiveness through mesh

Adds the `forgive_reputation` command, which validates requests to forgive all
penalties for a user or a single match failure and emits a `reputation_forgiven`
event. Adds the event handler, which applies the forgiveness and checks whether
the user can resume trading.
### server/auth,db: Remove obsolete reputation state and storage

Create the event log table to store each event's sequence number, kind,
payload, transaction data, and tip hash.

Add `applyEventTx` to run an event's database changes and append its log
entry in one transaction. Both are committed together, and a mismatch
with a supplied sequence number or expected tip hash rolls back the
changes. This helper is for use by event appliers.

Add `EventLogFrontier` and `EventLogEntriesAfter` so the mesh package can
query the event log table.
Define which tables are included in snapshots, which must be empty
before loading a snapshot, and which are preserved as local configuration.
Check at startup that every table in `public` and the stored market schemas
has a classification to avoid future developers adding tables without
considering how snapshotting will be affected.

Add `HasNoEventSourcedState` to check whether all event-sourced data is
absent, as required before loading a snapshot. Add `WipeEventSourcedState`
to clear all event-sourced data before restoring from a peer.
Add `WriteSnapshot`, used by the master to create a snapshot that is
sent to the slave, and also add `LoadSnapshot`, used by the slave to
populate its DB with the master's data.

The snapshot includes:

- The event-log sequence number and tip hash corresponding to the snapshot.
- All accounts, bonds, prepaid bonds, and reputation points.

For configured markets, it also includes:

- Market lifecycle state.
- Active orders, cancels, and matches.
- The past 30 days of archived orders, archived cancels, and matches, plus
  older archived orders referenced by included matches or archived cancels.
- The latest 1,000 candles from each candle table.
- Recent epoch reports needed to rebuild unfinished candles.
Add the v9 upgrade and update table schemas. The upgrade makes the
following changes:

- Create the `event_log` table.
- Create the `market_lifecycle` table to store market state, scheduled
  suspensions and resumptions, epoch progress, and trading parameters.
- Remove the legacy `accounts.fee_asset` column.
- Remove commitment and preimage uniqueness constraints from
  `orders_archived` and `cancels_archived`. Nodes may retain different
  archived histories, so these constraints could make archiving the same
  order succeed on one node and fail on another.
- Add non-unique commitment indexes to `orders_archived` and
  `cancels_archived` for lookups.
- Add indexes on `makerOrder` and `takerOrder` for active matches, to
  support finding an order's active matches during future swap processing.
- Add a genesis event when a database has existing event-sourced data and
  an empty event log. It includes a random nonce, so each legacy database
  initialized this way has a distinct history. Databases with no
  event-sourced data do not receive a genesis event.
Return account lookup errors separately from an unknown account, and update auth
callers to handle them. This prevents database failures from being treated as
missing accounts or empty bond lists when connecting, posting bonds, or
calculating reputation. This is needed for mesh because a failed database lookup
must not be cached as though the account does not exist.

Pass the caller's context through account and bond queries so cancellation and
deadlines cover the entire lookup.
Introduce the `server/meshevents` package as the catalog of mesh events shared
by the database and application packages. Define events for bond posting,
prepaid bond creation, and reputation forgiveness. Add JSON decoding for order
and match IDs to complement their existing JSON encoding.
Adds `repCache`, an LRU cache for account scores and bonds, to reduce repeated
database reads.

Previously, reputation calculations used active bonds and recent match,
preimage, and order outcomes held in memory for connected users. With mesh, both
nodes need to calculate reputation regardless of which node a user is connected
to.

The cache accepts a caller-supplied function that loads calculated scores and
bond data. Integration with database reads and reputation lookups is added in
subsequent commits.
Previously, legacy reputation was converted to `points` when an account's
reputation was first loaded. With mesh, snapshots can omit older order and match
history needed for that conversion, so converting lazily could produce different
scores on different nodes.

Converts all remaining version-0 accounts during the v9 database upgrade
instead, before mesh starts. This completes the conversion once, so reputation
lookups can read directly from `points` and snapshots include the converted
data.
Previously, reputation lookups used bonds and recent outcomes held in memory for
locally connected users. Updates these lookups to calculate reputation from
stored outcomes and bonds, using `repCache` to cache calculated scores and bond
data. This allows reputation to be calculated independently of which mesh node
the user connects to, without active users repeatedly querying the database.

Adds `UserReputationAt` to calculate reputation with bond expiry evaluated at a
supplied time. Stops periodic bond-expiry checks and retains expired bonds so
their contribution can still be calculated when replaying earlier events.

Adds `BondExpiryThreshold` to `account.Reputation` so clients can determine
which bonds were included in the reported tier. With periodic bond-expiry
notifications disabled, clients will need to track expiry themselves.

Adds `AcctRepStatus` with an error return so callers can distinguish a failed
reputation lookup from an unknown account or a zero tier. This will be required
by the unbooking logic to avoid removing orders when reputation cannot be
retrieved.
Adds `SetReputationInputsListener` and registers an auth callback that
invalidates affected cache entries when notified. The callback refreshes
reputation and sends score-change notifications to locally connected user.

The event appliers added in subsequent commits will invoke the listener after
updating reputation inputs.
Replaces the functions called by the market and swap packages to record
reputation outcomes with stubs. These stubs will be removed when those packages
are updated to record outcomes through mesh events.
Adds support for delivering requests and notifications to clients connected
through a mesh peer, routing responses back to their handlers, and expiring
unanswered requests. Keeps local-only delivery available for node-local
notifications.
Adds `ApplyBondPostedEvent` to store posted bonds, create accounts when needed,
and consume prepaid bond tokens. Returns the account's bonds and latest
reputation outcomes from the same transaction so auth can calculate the
reputation returned with the bond response.
Adds the `postbond` command, which validates on-chain bonds and prepaid-token
redemptions, waits for any missing confirmations, and emits a `bond_posted`
event for newly accepted bonds. Adds the `bond_posted` event handler, which
stores the account and bond and consumes the prepaid token when redeeming one.

Adds the initial mesh setup in the `dex` package. Since dcrdex configuration
options for mesh have not been added yet, the service runs in single-server
mode.
Adds `ApplyPrepaidBondsCreatedEvent` to store newly created prepaid bond tokens.
Adds the `create_prepaid_bonds` command, which generates prepaid bond tokens
with the requested strength and lifetime and emits a `prepaid_bonds_created`
event. Adds the event handler, which stores the tokens in the db.
Adds `ApplyReputationForgivenEvent` to forgive all penalties on an account or
the penalties associated with a single match.
Adds the `forgive_reputation` command, which validates requests to forgive all
penalties for a user or a single match failure and emits a `reputation_forgiven`
event. Adds the event handler, which applies the forgiveness and checks whether
the user can resume trading.
@martonp
martonp force-pushed the mesh-auth branch 3 times, most recently from cad6c76 to 240291c Compare September 22, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant