Skip to content

fix(tokens): privacy-token security hardening across consensus, txpool, wallet and RPC - #243

Merged
victor-tucci merged 61 commits into
Beldex-Coin:feature-privacy-tokenfrom
victor-tucci:feature-privacy-token
Dec 1, 2026
Merged

victor-tucci merged 61 commits into
Beldex-Coin:feature-privacy-tokenfrom
victor-tucci:feature-privacy-token

Conversation

@victor-tucci

Copy link
Copy Markdown
Member

No description provided.

Agatha-luna and others added 30 commits November 13, 2026 17:33
A coinbase carries no proofs, so its outputs must be plain txout_to_key
outputs whose commitment the node derives from the visible amount.
prevalidate_miner_transaction never checked the output target, and in a
mined (non-POS) block the miner's own output is not covered by
verify_coinbase_tx_output. Since privacy tokens were added, add_output
also accepts tx_out_zyphora and stores its amount_commitment and
blinded_token_id as given, so such a coinbase output would enter the
amount-0 output set with no proof behind it.

Reject any non-txout_to_key coinbase output in
prevalidate_miner_transaction, which runs for both main-chain and
alt-chain blocks. No fork gate is needed: before privacy tokens,
add_output threw on every other target, so no existing block can
contain one.

As defence in depth, BlockchainDB::add_transaction now refuses a
tx_out_zyphora output in a miner transaction, so a path that skips
block validation cannot store one either.

Tests: TokenCoinbase.PrevalidationRejectsNonKeyOutputs covers token,
script and scripthash targets at every output position on both sides
of the HF22 fork, with a key-only control.
TokenOutputIndex.CoinbaseTokenOutputIsRejected checks that the write is
refused, nothing is stored and the database stays usable. Both fail
without this change and are added to the token_security ctest filter.
The PUBLIC tag was dropped in 7ab6f70, so daemons running with
--restricted-rpc refused this call. Wallets depend on it in
is_transfer_unlocked(); when it fails they assume nothing is
blacklisted and also skip the staked-contribution check, which
inflates unlocked balance and can pick unspendable outputs.
get_master_node_blacklisted_key_images public again
- reject tx_out_zyphora outputs, zy_sig and token_proofs in coinbase txs
- reject token inputs/outputs/proofs in stake and other non-token tx types
- decode stake amounts with the native-output index, since
  rct ecdhInfo/outPk hold native outputs only
The wallet RPC mint_token built a tx without checking anything the daemon
would reject, and the CLI minted to a different destination.

- RPC: reject a null token id or zero amount, check that the wallet owns
  the token, and check the amount against remaining_mintable before
  building the tx.
- CLI: mint to the wallet's primary address, as the RPC does, instead of
  subaddress (account, 0). A single-subaddress token destination cannot
  currently be found by the recipient scan. The current account now only
  selects the BDX outputs that pay the fee.
- Document on MINT_TOKEN that amount is in atomic units and where the
  minted tokens go.
get_or_calculate_token_id returned any explicit token_id an operation
carried, and otherwise hashed whatever descriptor was embedded. A register
could not choose its own id only because separate validators rejected it
before the id was used.

The function now decides by operation type:
- register_token: always derived from the descriptor and salt; an explicit
  token_id field is ignored.
- mint/update/burn: the explicit token_id field is required; the id is
  never re-derived from an embedded descriptor.
- any other type: null id.

A mint, update or burn without the token_id field is now rejected. The
wallets already set it on these operations.
… collateral

- add a per-family domain tag to the Schnorr (G, X), linear composition,
  double Schnorr and aggregation challenges, so an owner proof is no longer
  a valid wallet message signature (consensus change: older token proofs
  no longer verify)
- include zy_sig in the Boost transaction serialiser
- use the testnet registration collateral on devnet
- remove a debug std::cout from wallet2 output selection
- correct comments: 3-layer ring and double-Schnorr balance proof, HF22,
  and the fan-out rule applying to register only
fix(core): require txout_to_key outputs in coinbase transactions
Clear zy_sig and token_proofs at the start of full and pruned deserialization so the result depends only on the bytes being parsed. Use a fresh transaction object per blob in handle_notify_new_fluffy_block. Wire format, tx hashes and prunable hashes are unchanged.

Add a TokenSecurity regression test that parses a native tx into an object holding token proofs and checks that it parses, round-trips and carries no token sections.
The token_proofs vector is part of the prunable hash but is not covered by any signature or proof, so any relay could change a token transaction's hash without invalidating it: by reordering the proofs, by setting undefined bits in token_operation_proof.flags, or by adding a zy_balance_proof to a transaction with no zyphora inputs, where it is never verified.

Require proofs in the order the wallet emits them (surjection, balance, range, amount-commitment, ownership), which also rejects duplicates; require token_operation_proof.flags to be exactly 1, both when deserializing and in verTokenProofs; and reject a zy_balance_proof when the transaction has no zyphora inputs. Transactions built by the wallet already satisfy these rules.

Add a TokenSecurity regression test covering reordering, duplicates, undefined flag bits on the wire and in memory, and an unused balance proof on register, mint and update transactions.
Blockchain::init pops blocks whose stored version no longer matches the fork table, but it called BlockchainDB::pop_block directly and never rewound the token state applied for those blocks. Registrations, supply and undo records from the removed blocks stayed in the database, so the node could later reject valid blocks or accept invalid token operations. pop_block_from_blockchain had a related gap: it only rewound when the current fork table placed the height at or after the privacy-token fork, which is not true after that fork is moved later.

Add pop_block_and_rewind_tokens, which pops the top block and undoes the token state recorded for its height. Use it in the startup pop loop, inside a write batch so the block and its token state are removed together. Rewind unconditionally in pop_block_from_blockchain; the undo record is keyed by height and is absent where no token operations were applied, so this is a no-op for those blocks.

Add a TokenSecurity regression test that applies token operations for a block, pops it through the new helper and checks that the token state and undo record are restored.
Each token operation is validated against committed state in check_tx_inputs, which cannot see earlier transactions in the same block. Block-level validation re-applied supply and existence rules but not ownership, so a block producer could include an update_token that transfers ownership followed by a mint_token signed by the previous owner, and both were accepted. The mempool already refuses a second register/mint/update on a token, but that check is skipped for transactions arriving inside a block, so it did not bind other producers.

Add check_block_token_op_exclusivity, which applies the mempool's rule to a block: at most one register, mint or update per token id, with burn exempt. Reject blocks that violate it in handle_block_to_main_chain. Blocks built from the mempool already satisfy this rule.

Add a TokenSecurity regression test covering an ownership transfer followed by a mint, every ordered pair of mint/update on one token, and that burns, other tokens and native transactions are unaffected.
A register_privacy_token tx needed no signature from the key it
declared as descriptor.owner, and every proof it carries can be rebuilt
from secrets local to the transaction. A mempool watcher could
therefore re-issue an observed registration verbatim (same descriptor,
same derived token_id, owner still the victim) with the initial-supply
outputs redirected to themselves, outbid it on fees, and get mined
first; the victim's own registration was then rejected as a duplicate,
leaving them the nominal owner of a token whose entire supply the
attacker holds. Zano, the reference design, has the same consensus gap
and only blunts it off-chain (non-unique tickers, wallet whitelists,
re-registration salt), so there was no upstream fix to adopt.

Require every registration to carry a token_operation_ownership_proof:
a Schnorr signature by the DECLARED owner over the tx prefix hash. The
prefix hash covers vout, so the signature binds the supply
destinations; a copied registration has a different prefix hash, which
the victim's signature does not match and the attacker cannot re-sign
without the owner's spend secret.

 - token_history_utils: verify the proof for register_token against
   op.descriptor.owner (no stored state exists yet); mint/update keep
   verifying against the registered owner.
 - blockchain: the structural pre-check on register_privacy_token now
   requires the proof's presence, as mint already did.
 - rctSigs: verTokenProofs allows the ownership proof on registration
   txs instead of rejecting it as out-of-place.
 - cryptonote_tx_utils: the wallet attaches the signature when
   constructing a registration, signing with its spend key (the RPC
   already requires descriptor.owner to equal that key).

No fork gate is needed: privacy tokens are not live on mainnet and the
testnet is being reset, so no existing block contains an unsigned
registration.

Tests: TokenSecurity.RegistrationCannotBeFrontRunToRedirectSupply
rejects a registration with the proof stripped, one signed by a
non-owner key, and a full front-run (same descriptor, supply redirected
to attacker stealth addresses, all tx-local proofs regenerated, the
victim's signature transplanted), and checks nothing is written to the
token database. The harness now signs registrations, so the existing
suites exercise the new rule on every valid register tx.
meta_info was only length-checked, and a mint or burn operation could carry a descriptor that is never validated or used. Either could put invalid UTF-8 on chain, which made get_token_info and get_transactions with tx_extra return an internal error for the affected token or transaction, and blocked the owner's own update_token since it reads get_token_info first.

Require meta_info to be strict UTF-8 when validating a descriptor for registration or update. In validate_token_descriptor_operation, reject any field an operation does not use alongside the existing required-field checks (register: descriptor, salt, amount commitment; mint and burn: token id, amount, amount commitment; update: descriptor, token id), matching what the wallet builds.

Add TokenSecurity regression tests for invalid UTF-8 meta_info on registration and update, and for fields outside each operation's allowlist.
The descriptor's owner key was only compared against null (M7). Two
consequences: a degenerate ed25519 point (identity, small order, or a
torsion component) as owner makes the Schnorr ownership check
forgeable, letting anyone mint or update as "owner"; and the JSON
owner field accepted raw hex with no redundancy, so one mistyped
character became a valid-looking owner key nobody holds, locking the
token's mint/update forever.

Weak keys: token_owner_key_ok requires a canonical encoding of a
point in the prime-order subgroup, not null and not the identity.
Consensus enforces it on registration and on every owner change
(apply_token_operation_to_state); the shared descriptor validator
enforces it in the wallet, so a bad descriptor fails before any fee
is spent.

Typos: parse_owner now accepts only a wallet address (mainnet,
testnet or devnet; subaddresses still rejected) and derives the owner
key from the address's spend public key. The base58 checksum catches
a mistyped owner at parse time; the raw-hex form had no such
protection and is rejected with an error saying why. Registration
typos were already impossible since the registration must be signed
by the declared owner, but an ownership transfer via update_token had
no such safeguard.

Tests: TokenSecurity.WeakOrMalformedOwnerKeysRejected pushes the five
canonical degenerate point encodings through registration and
ownership transfer and checks each is rejected.
TokenSecurity.JsonOwnerMustBeAChecksummedAddress checks a valid
address yields its spend key, and that a one-character typo and a raw
hex key are both rejected.
The token id is derived from the descriptor and salt, both public once a
register tx is broadcast, and a register needed no signature from the
owner. Anyone could re-register the same id first with the initial
supply paid to themselves.

A register must now carry the ownership proof that mint and update
already use: a Schnorr signature by descriptor.owner over the tx prefix
hash, which covers the outputs. The wallet attaches it when building a
register tx.

Consensus change: register txs from earlier builds are rejected.
Only the native range proof was capped. With 17 or more token outputs
the Bulletproof+ verifier accepted one round too many and read past the
end of its generator tables before rejecting the proof.

- A tx with token outputs may have at most
  TX_BULLETPROOF_PLUS_MAX_OUTPUTS outputs, native and token together.
  Checked in check_tx_semantic and at the top of verTokenProofs.
- The Bulletproof+ verifier rejects a proof over more than maxM
  commitments, whoever calls it.
- The weight clawback counts native outputs only, and
  get_pruned_transaction_weight handles token inputs and outputs
  instead of failing or throwing. The token part of the pruned weight
  is an estimate.
- The wallet refuses to build a token tx over the limit.

Consensus change: token txs with more than 16 outputs are rejected.
A privacy-token tx must keep the plain tx pubkey R = s*G, but a single
subaddress destination was still treated as needing no additional tx
keys. The sender derived with s*C and the recipient with a*R, so the
output was never found: an exact-amount token send or a token sweep to
one subaddress was invisible to the recipient.

Additional tx keys are now required whenever a token tx pays a
subaddress. The condition is shared by the two places that decide it.
get_payments, get_bulk_payments and incoming_transfers returned token
outputs with the token amount in 'amount' and nothing to tell them
from BDX, so a caller crediting by payment id could book a token as
BDX.

- The three calls return BDX entries only unless the request sets
  include_tokens.
- Every entry carries token_id, empty for BDX.
- The wallet API TransactionInfo gains tokenId().
A tx delivered inside a block message is stored even when its input
check fails, and it was still indexed as the pending operation for its
token id. The ownership proof is verified in that input check, so
anyone could send a junk block carrying a mint or update with a garbage
proof and have the node refuse the owner's real operation as 'already
pending', for up to 7 days and across restarts, without paying a fee.

- add_tx no longer indexes a tx whose input check failed.
- init indexes only txs that have a recorded max_used_block_id, which
  a tx gets only by passing the input check.

fill_block_template already keeps two operations on one token out of
the same block, so an unindexed tx that later becomes valid is safe.
get_output_distribution cached only the native amount-0 distribution and
never the per-output index list, so every token request, and every request
that needed indices, rebuilt a chain-length answer from the database. A
request that repeated the same amount rebuilt it once per repetition.

- keep one cache per output kind (native and token), each holding the
  distribution together with its output indices
- extend the cache with new blocks and follow a reorg instead of rebuilding
- do not serve a cache built without indices to a caller that needs them
- answer each distinct amount in a request once; the number of amounts in
  a request is not limited
- share one code path between the JSON and binary handlers
tokens: privacy-token security fixes
Both branches added the owner signature on register_privacy_token. Kept
this PR's version of the shared logic (blockchain, tx utils, token
history, rctSigs) and the test harness signing kinds 0-2; kept both
token_descriptor changes (meta_info UTF-8 check and owner key checks).

Also closes OperationsCarryOnlyTheirOwnFields, which was missing its
closing brace on feature-privacy-token and broke the unit_tests build.
fix(core): require an owner signature on privacy-token registration, validate token owner keys and take owners as addresses only
Agatha-luna and others added 28 commits November 20, 2026 18:48
get_outs trusted the two parallel arrays the daemon returns for each rct
bucket (cumulative offsets and rank-to-global-index translations) to be
consistent. They were never cross-checked, so a malicious or buggy
daemon could send fewer indices than the distribution claims and drive
reads past the end of the indices vector (ring bound and direct
enumeration), or spin the decoy-picking loops forever: the rank retry
loop had no bound, and the outer loop's exit counts distinct picks
against an offsets-derived total the short list can never supply.

Reject the response instead: both index lists must be strictly
increasing, the indices must cover every rank the gamma picker can draw,
and the pick retry is capped (generously, since the picker's occasional
out-of-range "bad pick" is expected). Every inconsistent case now fails
with a clear get_output_distribution error instead of a hang, an
out-of-range read, or a skewed ring.
…he pool

When a pending tx vanishes from the pool and is marked failed, the
wallet resets the spent status of its inputs so they become spendable
again -- but the loop only matched txin_to_key, so a failed token spend
released its native fee inputs while every txin_zy_input stayed marked
spent. The tokens then disappeared from the usable balance until a
manual rescan_spent or full rescan, which looks like lost funds after
any dropped token tx (made more common by nodes now evicting
invalidated token operations).

Extract the key image from either input variant and release both; token
and native key images share one space, so the transfer matching is
unchanged.
add_rings and remove_rings only walked txin_to_key, so the rings used by
token spends (txin_zy_input) were never saved to the ring database. If a
token output ever had to be spent again -- a dropped tx retried, a
reorg, a spend on a fork -- the wallet drew fresh decoys, publishing two
rings whose intersection is the real output and breaking the ring
signature for that spend. Token ring reuse is especially cheap to
exploit while the token output pool is small.

Store and remove rings for both input variants; they carry the same key
image and relative offsets in the same global index space, so the record
format and the reuse path in get_outs are unchanged. Adds a round-trip
regression test covering a tx with one native and one token input.
fix: stop third-party burns from censoring token owner operations and evict token operations a new block has invalidated
… fork

Before the privacy-token fork an upgraded node rejected any tx whose
tx_extra parsed to a token descriptor operation or a collateral lock.
Releases from before the fork do not know those two tags and treat
tx_extra as free-form, so they accept such a tx. A standard tx carrying
those bytes, mined by a pre-fork node, was therefore rejected by every
upgraded node and split the chain during the rollout.

Dropping the check is not enough on its own. A pre-fork node fails to
parse an extra that holds either tag, so it reads every field of that
extra as absent, including the burn amount that sets the miner fee. An
upgraded node that parsed the extra would compute a different miner
reward for the same block.

- parse_tx_extra fails on an extra holding either token field while the
  chain is before the fork, as a pre-fork node does. Blockchain switches
  this whenever the chain tip changes; it is on by default, so wallets
  and tools are unaffected.
- tx_has_privacy_token_content no longer inspects tx_extra. It still
  rejects token tx types, inputs, outputs and proof sections, which a
  pre-fork node cannot parse either.
- validate_tx_token_operations_against_db no longer rejects a token
  operation in tx_extra before the fork.

The switch is process-wide and follows the main-chain tip.

Tests: TokenSecurity.TokenFieldsInTxExtraAreInertBeforeTheFork. The unit
test runner resets the switch before each test, and the TokenPool
fixture turns it on because it runs token txs on an hf1 chain.
…G, X)

The balance proof forced the G-component of the commitment residual to
zero by deterministically setting one pseudo-output's amount mask to the
sum of the token output masks (plus the burn commitment's mask for
burns). Token output masks are derivation-bound, so the recipient of a
transfer with no token change could recompute every output mask, strip
the known mask*G from the public pseudo_out_amount_commitment, and match
the remaining amount*T_real against each ring member's public blinded
token id, unmasking the real spend. A full burn was worse: subtracting
the public burn commitment cancelled the G-component outright, leaking
the real ring member to any observer.

Pseudo-output amount masks now stay fresh random scalars and the
residual's G-component travels as a secret instead: zy_balance_proof
replaces its double Schnorr (secret_x over X, tx_key over G) with a
linear composition proof of P = mask_delta*G + secret_x*X. Soundness is
unchanged -- token ids are hash-to-point with no known discrete log to
G or X, so P in span(G, X) still forces per-token conservation, and the
range proofs still bound amounts. Binding to the transaction is kept by
the challenge message (get_hf21_token_proof_message hashes the
finalized tx, prefix hash included), making the explicit tx-key leg
redundant. The ZY_sig needs no change: its layer-1 secret
f = real_mask - pseudo_mask is valid for any pseudo mask.

The zy_balance_proof wire change (dss -> lcp) only affects token
transactions, which have not been live on any chain.

Adds a regression test showing the old construction is unmasked by the
recipient's attack, the new one is not, and the new statement verifies
with the signer's exact sign conventions.
A sender fully controls the one-time output key and consensus does not
reject duplicates, so the same key can arrive once as a native BDX
output and again as a token output. The duplicate-key handling in
process_new_transaction compared the two records' amounts as if they
were the same currency and, when replacing, overwrote m_amount and
m_mask while leaving m_token_id and m_token_mask behind -- so a large
worthless-token output could overwrite a 1-atomic-BDX record and show
up as BDX balance (or the reverse), and a genuine receipt in the other
asset could be silently discarded. The corrupted record then fails at
spend time since its stored opening no longer matches the on-chain
commitment.

Outputs on a reused key are now only compared and replaced within the
same asset; a cross-asset newcomer is ignored with a loud log and its
payment-record entry is dropped (both outputs share one key image, so
at most one is spendable anyway). The same-asset replace path now also
carries over m_token_id and m_token_mask, since the token-id blinding
scalar is per-output.
The TDO's token_id and amount_commitment, and the zyphora outputs'
amount_commitments, are attacker-supplied bytes that reach rct point
arithmetic (scalarmultKey/subKeys/addKeys) in
verify_token_amount_commitment. Those helpers throw std::runtime_error
on an invalid point encoding, and nothing between there and the network
entry points catches: an RPC submit returned a generic exception error
with tvc never set, and on the p2p path the throw unwound levin
processing up to the TCP worker loop, aborting fluffy-block handling
without penalizing the peer or recording the tx as invalid.

Validate both TDO fields as main-subgroup points in
validate_token_descriptor_operation (matching the torsion policy of the
PT proofs, since they enter unscaled arithmetic), and wrap
verify_token_amount_commitment in try/catch returning false so the
output-commitment sum can never throw either, mirroring verTokenProofs.

Adds TokenSecurity.MalformedPointsAreRejectedWithoutThrowing covering a
non-decodable encoding and a small-order point through both the field
validator and validate_tx_token_operations_against_db.
fix(core): reject malformed token-operation points instead of throwing
- Initialize commitment sums with the elliptic curve identity point
- Securely erase temporary secret scalars after token proof generation
Cold signing trusted the watch-only wallet's labels: accept_loaded_tx
credited change from the supplied change_dts without checking the
address was ours, and never showed the transaction type. A compromised
online wallet could present a payment to a third party as the user's own
change, or disguise a mint/burn/ownership transfer as a fee-only send.

- accept_loaded_tx: verify the native and token change addresses resolve
  to one of this wallet's subaddresses, and show the operation in the
  confirmation prompt.
- sign_tx: before producing any signature, re-derive each output with the
  wallet's own keys and require the outputs that are actually ours to
  match, by (account, subaddress, native/token, token id), the ones the
  construction data claims are ours. Matching by identity (not count)
  prevents a falsely claimed change output from being masked by an
  unrelated owned output; the token id is un-blinded so a token-A-claimed
  / token-B-built swap at the same subaddress is also rejected.

Multisig signing (sign_multisig_tx) is a separate path and is unaffected.
Fix commitment initialization and wipe token proof secrets
- Validate token inputs and outputs per token ID in `construct_tx`.
- Prevent token change outputs from being confused with native BDX change.
- Include privacy token inputs in spend proof generation.
- Include privacy token inputs (`txin_zy_input`) in spend proof verification.
- Separate BDX and privacy token amounts in `describe_transfer()`.
- Exclude frozen outputs from `token_balances()`.
- Ensure burn amounts and new token owners are properly validated and confirmed.
Fix privacy token balance validation, change handling, spend proofs,  balance reporting and burn validation
W1 made get_payments, get_bulk_payments and incoming_transfers omit
privacy-token payments unless the caller sets include_tokens, so a
token-unaware exchange can't mistake a token amount for BDX. get_transfers
and get_transfers_csv -- the endpoints integrations poll most -- were not
covered and returned token transfers with the token amount in `amount`.

Add include_tokens (default false) to the GET_TRANSFERS request and skip
token entries in both get_transfers and get_transfers_csv unless it is set,
matching the other endpoints. Token-aware callers opt in and still get the
token_id marker on each entry.
When a transaction contained a duplicate output key, process_new_transaction
removed the output's entry from tx_money_got_in_outs by matching subaddress,
amount and unlock time, but not the asset. An attacker could send one tx with
a token output of N and a native output of N reusing an earlier key: the
duplicate native output was ignored, but the entry removed was the token one,
so the wallet recorded N BDX it never received (the consistency check sums
token and BDX amounts, so it did not catch the swap).

Match token_id as well in all four duplicate-handling branches (entries are
already inserted with token_id set, so the stricter match always finds the
correct entry). A duplicate native output now removes the native record and
leaves the token record intact.
have_duplicated_non_standard_tx looped over a token tx's descriptor
operations with get_token_descriptor_operation_from_tx_extra, which
re-parses the whole tx_extra on every call -- O(n^2) in the number of
fields. A tx packed with minimal token fields (up to the weight limit)
could stall the pool for ~90s under the pool lock, and this runs before
check_tx_inputs, so the tx could be otherwise invalid and cost nothing.

Parse tx_extra once and require exactly one token descriptor operation
(consensus already enforces this via validate_token_transaction_fees),
rejecting any other count after a single O(n) parse. Block validation is
unaffected: it runs check_tx_inputs (which rejects >1 op) before its own
token-op loop.
fix(core): parse tx_extra once in pool token-dedup check and fix(wallet): verify cold-sign change outputs belong to this wallet
Reapply "fix(mint-token): Burns reopening mint headroom"
The CLI scaled a typed token amount by the decimal point returned from
the daemon's get_token_info RPC, and formatted the confirmation with the
same value. A malicious node could misreport the decimal, shifting the
real atomic amount by powers of ten while the prompt still showed what
the user typed -- draining a token balance or mis-sizing a transfer/burn
undetectably.

The decimal is committed into the token_id (get_or_calculate_token_id
hashes the full descriptor), so it can be trusted without the RPC:

- Record a token's descriptor (decimal point, ticker) when the wallet
  scans its registration, keyed by the token_id recomputed from that
  descriptor. Persist it in the wallet cache (version 31 -> 32; old
  caches load with an empty map and repopulate on rescan).
- get_token_display_info prefers this validated store and only falls
  back to the unauthenticated RPC for tokens whose registration the
  wallet has not scanned -- logging a warning when it does.
Native and token amount==0 outputs share one index space, so a native
(BDX) ring could reference a token output as a decoy. Such a decoy is
trivially recognisable (different output type and commitment basis), so
an observer discards it, shrinking the real ring. The reference wallet
avoided this by selecting decoys per type, but consensus did not forbid
it, so any other wallet could build -- and the network would accept --
a weakened ring.

Reject a native input whose resolved ring member is a privacy-token
output (non-null blinded_token_id) in scan_outputkeys_for_indexes, which
runs in both mempool and block validation. Legacy outputs are all
null_tid after the v7->v8 migration, so this only triggers once tokens
exist; pre-fork blocks are unaffected.
get_output_distribution cached a single result keyed on the request's
from_height, so a caller that alternated from_height missed the cache on
every call and forced a fresh full-chain scan -- a cheap, unauthenticated
way to load a public node.

Always compute and cache the distribution from genesis and slice the
result down to the caller's from_height afterwards. The cache is then
keyed only on the chain tip, so changing from_height can no longer force
a recompute. Callers using from_height=0 (the normal case) are
unaffected; a from_height>0 request is served from the same cache and
sliced to the exact distribution/base/indices it would have produced
before.
Strip the internal audit reference tags (N3, N4, N5, N6, M7, M9, M10,
M13, M14, C-1) from code comments, keeping the explanatory text. These
tags only referenced an external audit document and carry no meaning in
the codebase. No code changes; comments only.
Harden privacy tokens: trusted wallet decimals, native-ring token rejection, and from_height-independent output-distribution cache
@coderabbitai

coderabbitai Bot commented Dec 1, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 9bdb4044-1bfa-4492-8d32-10a5109aa819

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@victor-tucci
victor-tucci merged commit 81a3335 into Beldex-Coin:feature-privacy-token Dec 1, 2026
2 checks passed
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.

5 participants