Skip to content

REST parity: JVM fee statistics, unconfirmed shape, JSON errors - #34

Merged
mwaddip merged 22 commits into
mainfrom
fix/api-jvm-parity
Sep 29, 2026
Merged

mwaddip merged 22 commits into
mainfrom
fix/api-jvm-parity

Conversation

@mwaddip

@mwaddip mwaddip commented Sep 29, 2026

Copy link
Copy Markdown
Owner

The REST API answers as the JVM's does where the two overlap. getFee recommended fees below the node's own minimum (61,255 against 1,000,000 on mainnet) because the mempool computed a different statistic. It now ports the JVM's MemPoolStatistics as the JVM's doc comment describes it, without the code's reset on every invalid transaction or its snapshot-counter drift. getFee takes minutes and never answers below min_fee, waitTime answers milliseconds, and poolHistogram bins the current pool by wait, all as bare JVM values. /transactions/unconfirmed* render the JVM's shape with resolved inputs, size and the measured cost, and /blocks/{id}/transactions carries blockVersion and size.

Transaction JSON keeps context-extension order instead of sorting the keys, so re-serializing our JSON gives the transaction's id back. Every error answers the ApiError body, including bad parameters, unknown paths, wrong methods and serialization failures, and a transaction over 96 KB is refused before validation. The NiPoPoW header routes take the JVM's names (popowHeaderById, popowHeaderByHeight), and the two old routes are gone. Mempool revalidation runs in priority order on the JVM's cost budget.

Checked:

  • workspace tests 1256/1256, clippy -D warnings, fmt --check
  • mainnet node on this branch since 21:57 CEST: every block applied, no errors; getFee answered 2,669,513 for a 2 KB transaction after the first confirmations; HAMT-ordered extensions (h974999) are served unsorted

🤖 Generated with Claude Code

mwaddip and others added 22 commits September 29, 2026 20:21
…the JVM

The mempool ports the JVM's MemPoolStatistics as its doc comment describes
them: confirmations only, never reset, and the throughput window's snapshot
kept in the window's own count. getFee is floored at min_fee and takes
minutes; waitTime answers milliseconds; poolHistogram bins the current pool
by wait, as the JVM does. All three answer bare integers or JVM-shaped bins.

Pool entries keep the cost their last validation measured, and
/transactions/unconfirmed* render the JVM's shape: resolved inputs, size
and that cost. Transaction JSON keeps context-extension entries in the
order the transaction serializes them. The NiPoPoW header routes are the
JVM's popowHeaderById and popowHeaderByHeight. Framework rejections answer
the ApiError body, and the size limit shows in the openapi entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GET /transactions/getFee answered below the node's own minimum fee: 61,255
against a min_fee of 1,000,000 on the live node, so a wallet that followed it
built a transaction our pool declines. FeeStats also computed a different
statistic from the JVM's: a 1000-entry history, recommending the lowest fee
that waited no longer than asked.

FeeStats is now the JVM's MemPoolStatistics (v6.0.6) as the contract
describes it: a histogram of confirmed pool transactions by whole minutes
waited, bins 0-59, and a throughput window that may move once a minute. It
departs from the JVM's code where the JVM's own doc comment does
(facts/mempool.md § FeeStats): only confirmations are recorded, and the
snapshot follows the subtraction, so the window never empties where the
JVM's count sinks to zero.

The fee queries follow § Fee queries:
- recommended_fee(wait_minutes, tx_size): the first non-empty bin through
  min(wait_minutes, 59), as (total / n) * tx_size / 1024, never below
  min_fee.
- expected_wait_ms(fee, tx_size): the pool transactions strictly heavier
  than fee * 1024 / tx_size, over the window's rate.
- pool_histogram(bins, max_wait_ms): the pool by wait so far, bins + 1 bins.
  An index past the last bin lands in it, where the JVM fails.
fee_histogram, expected_wait_time and the old recommended_fee are gone,
with FeeBucket and the history.

apply_block records each confirmed transaction the pool held, by its created
and base fee_per_factor, and not the double-spends it removes. Each query
reads the clock once. expected_wait_ms, pool_histogram, apply_block and
revalidate have _at(now) forms, which the tests drive; recommended_fee reads
no clock.

UnconfirmedTx::validation_cost is the cost the latest successful validation
measured, before the byte-size floor the weighting cost keeps: Some at entry,
as given through return_to_pool (callers pass None), refreshed by
revalidation. Revalidation also refreshes last_checked now, the JVM's
withCost, so a pass skips what the last one checked within cleanup_interval.
Before, every pass re-validated every transaction older than that.

Breaks the three fee queries' callers in api/src/handlers.rs and the
UnconfirmedTx literal in src/bridge.rs; the API session and main adapt them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getFee takes waitTime in minutes and never answers below min_fee.
waitTime answers milliseconds and no longer requires fee. poolHistogram
bins the current pool by how long each transaction has waited, with the
JVM's maxtime. All three answer bare JSON, an integer or the
FeeHistogramBin array, and refuse with 400 a negative parameter, a zero
txSize for waitTime, and bins outside 1-1000 or maxtime below bins.

Board items 11 and 21.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ction

/transactions/unconfirmed and .../byTransactionId/{id} render each pool
transaction as the JVM's createTransactionWithResolvedInputs does: every
input merged with the box it spends, found in the UTXO set and then among
the pool's unconfirmed outputs, plus the transaction's size and the cost
its latest validation measured (null when none has run since a rollback).
A resolved input carries one boxId. A digest or light node resolves no
input, as the JVM's digest node doesn't.

The pool is copied out under the mempool lock, the output boxes the
inputs spend included, and the UTXO set is read after the lock is
released, on the blocking pool: the P2P intake waits on the same mutex.

Board item 12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The block endpoints built their JSON as a serde_json::Value, whose object
keys sort as strings, so an input's context extension came out 4 before 8
and 10 before 2. That order is part of the transaction: a client that
re-serializes the JSON as given computed a different id.
/blocks/{id}/transactions, /blocks/{id} and /blocks/modifier/{id} now
render typed sections, and ergo-lib's own serializer writes each extension
in the order the transaction holds it. The unconfirmed endpoints already
render typed since the previous commit; no other response renders a
transaction or an input.

The test that pinned sorted-key output for /blocks/{id}/transactions goes:
it guarded the defect. Its replacement renders a transaction holding
variable 8 before 4 through all five endpoints and parses each back to
the original id.

Board item 20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dget

A pass walks the pool highest weight first, so a parent comes before its
children, and spends up to CLEANUP_COST_LIMIT (7,000,000, the JVM's
CleanupWorker.CostLimit) of measured validation cost, where a removal adds
the cost its last validation measured. cost_per_block goes back to limiting
remote transactions only. TxWeight loses its created field, which nothing
reads, and its equality becomes the ordering's. The weight is computed
without overflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
axum's Query, Path, Json and Bytes extractors refuse a request with a
plain-text body: getFee?waitTime=abc answered text/plain. Every handler
now extracts through ApiQuery, ApiPath, ApiJson or ApiBytes (src/extract.rs),
which answer the ApiError JSON the contract promises. A malformed query
string or path segment, or a body that isn't valid JSON for the endpoint,
answers 400, axum's 422 for well-formed JSON of the wrong shape included.
A body over the limit keeps 413 and one not sent as application/json
keeps 415, both with the ApiError body.

/peers/connect reads its body as bytes, so the api_key check now comes
before the UTF-8 check. HEAD /transactions/unconfirmed/{id} has no body
and keeps axum's Path.

Board item 23.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/nipopow/popowHeaderById/{header_id} and /nipopow/popowHeaderByHeight/{height}
replace /nipopow/popowHeader/{header_id} and /nipopow/popowHeader/last,
which exist nowhere else. By height takes the best chain's header there
and answers as by id does: 404 when there is none, 400 for a malformed
height.

Board item 13.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /transactions and /transactions/check refuse a transaction whose
serialization is longer than ergo_mempool::MAX_TRANSACTION_SIZE with
400, as the JVM refuses one over maxTransactionSize before verifying it.
The check comes before the state-context check, so it answers 400 while
the node is syncing too, where it answered 503.

Board item 19, the API half.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Header, block transactions, AD proofs and extension are modifier bytes
101, 102, 104 and 108, the JVM's NetworkObjectTypeId values that
facts/stats.md lists, not 1, 3, 4 and 5. Transaction stays 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tension keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ake the JVM shape

A request no route matches (404), a method a path doesn't serve (405) and a
response that fails to serialize (500) answer the ApiError body like every
other error. A handler that reads the pool copies out what it needs under
the mempool lock and reads the UTXO set after releasing it. And
/blocks/{id}/transactions answers the JVM's BlockTransactions object, with
blockVersion and size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
axum::Json answers a body that fails to serialize with a plain-text 500,
and the failure is reachable: a transaction or a box re-serializes its
scripts and constants on the way out. Every handler, the stats listener's
included, now responds through crate::response::Json, which is axum's
with one difference: that failure answers 500 with the ApiError body.
/blocks/{id}/transactions serializes on the blocking pool as before,
keeps its explicit 500, and sends its bytes through the same response
constructor. axum's Json stays only as the request extractor ApiJson
wraps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A handler that answers with axum::Json instead of crate::response::Json
compiles and works until its body fails to serialize, then answers plain
text. The type system can't tell the two apart outside a shared error
type, so api/clippy.toml disallows axum::Json and the -D warnings run
refuses it. The one legitimate use, ApiJson reading a request body
through axum's extractor, carries a scoped allow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A path no route matches answered axum's empty 404, and a method a path
doesn't serve its empty 405. The router's fallback and its
method-not-allowed fallback now answer both with the ApiError body; the
405 keeps axum's Allow header. HEAD answers stay empty, whoever answers
them. The stats listener serves one path and is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A pass walked the pool in hash-map order, charged each transaction's
weighting cost before validating it, and stopped at cost_per_block, the
limit on remote transactions. It now follows the JVM's
CleanupWorker.validatePool (v6.0.6) as facts/mempool.md § Cleanup and
revalidation describes it:
- Priority order, highest weight first, so a parent comes before its
  children. The order is taken once, since the pass removes as it goes.
- A transaction is re-checked only once more than cleanup_interval has
  passed since its last_checked. Exactly the interval is skipped: the JVM
  re-checks only past its TimeLimit.
- The budget is CLEANUP_COST_LIMIT, 7,000,000, the JVM's CostLimit. The
  pass stops before a validation once it has spent the limit. A validation
  adds the cost it measured, a removal the transaction's previous
  validation_cost (0 without one), a skip nothing. cost_per_block is back
  to limiting remote transactions only.

revalidate_within, the pass on any limit, is crate-private, so its tests
are unit tests. They share tests/common with the integration tests through
#[path], and a cfg(test) `extern crate self as ergo_mempool` lets those
fixtures name the crate from inside it.

TxWeight loses created, which nothing read, and its equality is now the
ordering's, on weight and tx_id, as Ord requires; it was derived over every
field. TxWeight::new computes fee * 1024 / fee_factor in u128 and saturates
a quotient that doesn't fit: the u64 product overflowed for a fee above
about 1.8 × 10^16 nanoERG, panicking in debug and wrapping in release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…pool

POST /utxo/withPool/byIds held the mempool lock across up to 100 UTXO
reads, and the P2P transaction intake waits on that lock. It now copies
the pool outputs among the ids under the lock and reads the UTXO set
after releasing it. The answers are the same: the UTXO set first, then
the pool. /transactions/unconfirmed/transactionIds hex-encodes its ids
after releasing the lock too (facts/api.md § Invariants).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…resolution

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/blocks/{id}/transactions answered {headerId, transactions}, and echoed
the header id as the request spelled it. The JVM answers the whole
BlockTransactions object, blockVersion and size included
(BlockTransactions.scala:118-125, v6.0.6). One function now builds that
section from the stored bytes for /blocks/{id}/transactions, /blocks/{id}
as blockTransactions, and /blocks/modifier/{id}: the same object on all
three, headerId lowercase from the section, size its stored length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mwaddip
mwaddip merged commit 2fb9949 into main Sep 29, 2026
1 check passed
@mwaddip
mwaddip deleted the fix/api-jvm-parity branch September 29, 2026 20:29
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