Skip to content

feat(identity): use proven owner balances and keep identity balances ordered by block height - #1110

Merged
lklimek merged 12 commits into
v1.0-devfrom
feat/proof-owner-balance
Oct 30, 2026
Merged

lklimek merged 12 commits into
v1.0-devfrom
feat/proof-owner-balance

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: When you register a username, Dash Evo Tool now reads your new credit balance straight from the network's proof, with no extra lookup. Every stored identity balance also records which block it came from, so an older reading can no longer overwrite a newer balance. An older reading comes from a slow node, or from a screen saving an out-of-date copy.

User story

As a wallet user, I want my identity balance to always show the newest value the network has confirmed, so that I never see an old balance after a payment or registration.

Scenario

Actual behavior

After a username registration, the app makes an extra network request to read the new balance. Balances are stored without the block they were read at, so a lagging node or a screen saving a stale copy of the identity can roll the balance back.

Expected behavior

The balance after registration comes from the registration's own proof. Each stored balance carries its block height, and only a strictly newer observation replaces it.

Detailed discussion

Based on v1.0-dev (Platform v5.1-dev 575d961f). This replaces #1110, whose branch carried the #1015 remainder; this branch holds only that PR's four commits, cherry-picked with -x.

  • Model (src/model/identity_balance.rs): adds BalanceWatermark, BalanceProvenance and reconcile_balance. Only a strictly higher height wins, the same rule as platform-wallet's balance_snapshot_is_newer.
  • Storage (src/context/identity_db/balance_watermark.rs): one DetKv slot per identity, det:identity_balance_watermark:v1. It is enforced at the identity write chokepoint, under the existing record lock.
    • An identity's first stored record records the height its balance was observed at, so an older reading right after loading cannot replace it.
    • No database migration: an identity without the slot behaves as before.
    • Untagged writes are pinned to the watermark, and logged at WARN when that changes the value.
    • Removing an identity clears its slot.
  • DPNS: registration uses register_dpns_name_with_owner_balance_and_metadata. The proven balance settles the fee and is stored at the proof height. Proofs made before protocol 14 carry no balance, so the app falls back to a tagged read-back.
  • Other writers tagged: transfer (sender and receiver), withdraw, add key, refresh, identity loading and discovery, and top-ups.
    • A top-up of another wallet's identity has no metadata variant upstream. It is stored as confirmed, without a height (TODO(upstream)).

Known limitations

  • Document creates still report an estimated fee. Moving them to the proven-balance variant changes create behaviour, so it is a follow-up.
  • DashPay profile writes go through platform-wallet, which records the proven balance only in its own store.
  • The height plumbing in the transfer, withdraw, add-key, top-up, refresh and load paths has no dedicated tests, because they would need network mocks. The ordering logic they rely on is covered.

Follow-ups

Testing

  • New tests:
    • balance reconciliation (7);
    • watermark storage (8);
    • DPNS proven balance and fallback (2).
    • The storage and DPNS behaviour tests were shown failing first.
  • On the replayed branch:
    • cargo clippy --all-features --all-targets -- -D warnings is clean;
    • library tests for identity tasks, identity storage, balance model, identity ops and migrations pass (380).

🤖 Co-authored by Claudius the Magnificent AI Agent

🤖 Generated with Claude Code

https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q

PR Hygiene · ba048d2

  • Bots — coderabbitai ✓ · thepastaclaw skipped after the window
  • Self-review — not asked of a bot author
  • Build green
  • Approvals
    • files with no dedicated owner (src/backend_task/identity/add_key_to_identity.rs, src/backend_task/identity/discover_identities.rs, src/backend_task/identity/load_identity.rs and 15 more) — approved by lklimek

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

Summary by CodeRabbit

  • Bug Fixes
    • Improved identity balance accuracy across refreshes, imports, transfers, withdrawals, and top-ups.
    • Older or incomplete network results are less likely to overwrite a newer balance, helping keep displayed balances consistent.
    • Registration fees are calculated from confirmed post-registration balances when available; otherwise, the app continues to estimate the fee.

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 19747b8 and ba048d2.

Files selected for processing: 18
  • src/backend_task/identity/add_key_to_identity.rs
  • src/backend_task/identity/discover_identities.rs
  • src/backend_task/identity/load_identity.rs
  • src/backend_task/identity/load_identity_by_dpns_name.rs
  • src/backend_task/identity/load_identity_from_wallet.rs
  • src/backend_task/identity/mod.rs
  • src/backend_task/identity/refresh_identity.rs
  • src/backend_task/identity/register_dpns_name.rs
  • src/backend_task/identity/register_identity.rs
  • src/backend_task/identity/top_up_identity.rs
  • src/backend_task/identity/transfer.rs
  • src/backend_task/identity/withdraw_from_identity.rs
  • src/backend_task/migration/finish_unwire.rs
  • src/context/identity_db.rs
  • src/context/identity_db/balance_watermark.rs
  • src/model/identity_balance.rs
  • src/model/mod.rs
  • src/wallet_backend/identity_ops.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

Identity balance writes now carry provenance from fetches and balance-changing operations. Persistence reconciles balances using per-identity block-height watermarks, preserving newer stored balances when older or unobserved copies arrive.

Changes: Identity balance persistence

Layer / File(s) Summary
Balance provenance and reconciliation
src/model/identity_balance.rs, src/model/mod.rs
Adds balance provenance and watermark types, plus reconciliation rules that compare observed heights.
Watermark-aware identity storage
src/context/identity_db.rs, src/context/identity_db/balance_watermark.rs
Identity writes reconcile incoming balances under the record lock. Watermarks are seeded after writes and removed when identity scopes are purged.
Fetch, import, and discovery observations
src/backend_task/identity/discover_identities.rs, src/backend_task/identity/load_identity*.rs, src/backend_task/identity/refresh_identity.rs, src/backend_task/identity/register_identity.rs, src/backend_task/migration/finish_unwire.rs
Identity fetch and creation paths pass observed heights to storage. Legacy discovery callers pass unobserved provenance.
Balance-changing operations and key updates
src/backend_task/identity/add_key_to_identity.rs, src/backend_task/identity/mod.rs, src/backend_task/identity/top_up_identity.rs, src/backend_task/identity/transfer.rs, src/backend_task/identity/withdraw_from_identity.rs, src/wallet_backend/identity_ops.rs
Top-ups, transfers, withdrawals, and key updates pass balance provenance to local identity writes.
DPNS registration balance finalization
src/backend_task/identity/register_dpns_name.rs
Registration uses a proof-provided balance and height when available, or fetches the identity and its metadata as a fallback.

Priority: Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant IdentityTask
  participant IdentitySDK
  participant AppContext
  participant balance_watermark
  participant IdentityRecord
  IdentityTask->>IdentitySDK: fetch_with_metadata
  IdentitySDK->>IdentityTask: identity and metadata height
  IdentityTask->>AppContext: write identity with BalanceProvenance
  AppContext->>balance_watermark: reconcile balance and provenance
  balance_watermark->>IdentityRecord: persist retained balance and seed watermark
Loading

Possibly related issues

  • dashpay/dash-evo-tool#1105: This PR changes how top-up balances are persisted and records provenance for identity creation, which overlaps with the issue’s top-up and identity-creation objectives.

Possibly related PRs

  • dashpay/dash-evo-tool#1109: Both PRs update withdrawal, refresh, and load paths that write identity balances using observed provenance.
  • dashpay/dash-evo-tool#1149: Both PRs use the identity balance write contract and the username-registration proof balance path.

Suggested reviewers: lklimek

Merge Risk: Low · up to ba048

Rejected or superseded identity loads can leave the balance watermark ahead of the stored identity record. A later write can then show a balance the identity record did not originally hold. This is a narrow, self-correcting edge case, so owners should be aware of it and can follow up after merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 73.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the feature area (identity) and both main themes of the changeset: proven owner balances from proofs and per-identity balance watermarks ordered by block height. The changes add Balanc…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the feature area (identity) and both main themes of the changeset: proven owner balances from proofs and per-identity balance watermarks ordered by block height. The changes add BalanceProvenance, reconcile_balance, and balance watermark storage, and wire observed heights into identity load, discovery, transfer, withdraw, top-up, refresh, and DPNS registration paths. The title is specific and accurate, though the 'feat(identity)' prefix plus a long clause makes it slightly long at 92 characters.

Full details: Docstring Coverage

Explanation

Docstring coverage is 73.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 42 functions across 18 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • 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

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

⛔ Final review complete — 1 blocking finding(s) (commit ba048d2) · triage: critical · Phase 2 only (no Phase 1 for this repository)

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 2 only (no Phase 1 for this repository)

The reviewed commit only restructures existing control flow in the DPNS registration and identity top-up paths. The local identity reference, route resolution, validation, wallet calls, balance provenance, arguments, and error propagation remain behaviorally equivalent; CI reports successful Clippy and Test Suite checks for this head.

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a large cross-cutting identity balance and storage-ordering change, but it does not itself alter consensus, cryptography, key handling, coin selection, or a storage migration.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer

lklimek and others added 6 commits October 26, 2026 21:09
Each stored identity gets a balance watermark slot next to its record: the
balance and Platform block height of the newest verified observation.
Every record write reconciles against it under the record lock, so an
older observation, or a copy of a balance read earlier, never replaces a
newer one. Identities without a watermark take every balance as before,
so no migration is needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f5e35e0)
…roof

From protocol version 14 the name document's proof carries the identity's
balance after the registration. Use it to settle the fee and store it at
the proof's height instead of fetching the identity again; proofs made
before protocol version 14 carry none and keep the read-back, now tagged
with its response height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8473919)
…eight

Transfers, withdrawals, key additions, top-ups, refreshes, loads and
discovery now store the identity balance they observed with the height
of the response that carried it (the SDK's metadata variants, or the
height platform-wallet recorded for a wallet top-up). Writes with no
height to give (a top-up of another wallet's identity, a fee pot claim)
are kept as confirmed but cannot advance the watermark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f83910b)
…s overlap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8cad672)
The first record stored for an identity (load, load by username, discovery,
or a key added before the identity was stored) kept no balance watermark,
so the height it was observed at was lost: a lagging node's older balance
read right after loading replaced the newer one. A balance observed before
the identity has a record now hands back its watermark, which is stored
once that first record is written, and only if it was written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q
…balance

`update_local_qualified_identity` carries no block height, so a balance
other than the newest one observed is replaced by it. State that on the API
so a future writer that changes the balance uses the observed variant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q
@lklimek
lklimek force-pushed the feat/proof-owner-balance branch from 8cad672 to fbf193a Compare October 26, 2026 23:31
@Claudius-Maginificent
Claudius-Maginificent changed the base branch from chore/bump-platform-v4.3 to v1.0-dev October 26, 2026 23:31
@Claudius-Maginificent
Claudius-Maginificent marked this pull request as ready for review October 28, 2026 10:25
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet · thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Oct 28, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 2 only (no Phase 1 for this repository)

The balance watermark model is sound, but three identity persistence paths still undermine the PR’s ordering guarantee. Address-funded identity creation discards the proof height, observed writes can advance the watermark before the identity blob is committed, and explicit DPNS loads bypass unload-marker retirement and related lifecycle handling. CI reports successful tests and lint checks, but the address-funded creation defect is blocking.

🔴 1 blocking | 🟡 2 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Address-funded identity creation can leave its first balance without a watermark
src/backend_task/identity/register_identity.rs:360-375

The successful address-funded registration branch receives the proof height as the third value from put_with_address_funding, but binds it to _height and then calls the unobserved insert_local_qualified_identity path. The newly stored identity therefore has no balance watermark even though its balance came from a verified response. A later identity fetch from a node at a lower height can then become the first recorded observation and overwrite the balance from the creation proof, defeating the ordering guarantee. Preserve the returned height and insert through insert_local_qualified_identity_observed with BalanceProvenance::ObservedAt(height).

source: gpt-6.1-sol (phase2-reviewer: general, rust-quality)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a broad cross-cutting identity-balance and persistence change, but it does not directly modify consensus, funds movement execution, cryptography, signatures, network deserialization, or storage migrations.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/backend_task/identity/register_identity.rs`:
- [BLOCKING] src/backend_task/identity/register_identity.rs:360-375: Address-funded identity creation can leave its first balance without a watermark
  The successful address-funded registration branch receives the proof height as the third value from `put_with_address_funding`, but binds it to `_height` and then calls the unobserved `insert_local_qualified_identity` path. The newly stored identity therefore has no balance watermark even though its balance came from a verified response. A later identity fetch from a node at a lower height can then become the first recorded observation and overwrite the balance from the creation proof, defeating the ordering guarantee. Preserve the returned height and insert through `insert_local_qualified_identity_observed` with `BalanceProvenance::ObservedAt(height)`.

In `src/context/identity_db/balance_watermark.rs`:
- [SUGGESTION] src/context/identity_db/balance_watermark.rs:38-46: Do not commit the watermark before the identity record
  For an identity that already has a record, `reconcile_stored_balance` writes the new watermark immediately. Its callers invoke it before encoding and writing the identity blob, so a subsequent vault failure, key-retention failure, storage failure, or declined write can leave the watermark describing a balance that was never persisted in the identity record. Future unobserved writes will then be pinned against that uncommitted balance, leaving the stored blob and watermark inconsistent. Return the accepted watermark as pending state and commit it only after the corresponding identity blob write succeeds, or otherwise make the two updates recovery-safe; add a failure-path test.

In `src/backend_task/identity/load_identity_by_dpns_name.rs`:
- [SUGGESTION] src/backend_task/identity/load_identity_by_dpns_name.rs:74-79: Retire the unload marker during an explicit DPNS identity load
  The new observed insertion path calls `insert_local_qualified_identity_under_lock` directly, bypassing the deliberate-import lifecycle in `insert_local_qualified_identity`. If a user unloads an identity and then explicitly loads it by DPNS name, the record and roster entry are written but the global unload marker remains. Automatic discovery will continue treating that identity as deliberately unloaded, and the insertion also skips DPNS vote cancellation and voter-lifecycle restart. Add the same marker-retirement and lifecycle handling to the observed insertion path while retaining the existing record lock rather than reacquiring the non-reentrant lock.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. and removed waiting-bots Waiting for the review bots to report on this head labels Oct 28, 2026
lklimek and others added 3 commits October 28, 2026 18:11
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s creation proof

The address-funded registration dropped the proof height that
`put_with_address_funding` returns and stored the new identity unobserved,
so a later fetch from a lagging node could replace its balance. Store it
through `insert_local_qualified_identity_observed` at that height.

Also pin that an observed insert (the explicit DPNS load path) retires a
prior unload marker.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet · thepastaclaw requested changes — dismiss the review or push a fix, 1 thread unresolved — resolve it. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. labels Oct 28, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

register_identity.rs:360: Fixed in f9819a8. Address-funded registration now stores the identity through insert_local_qualified_identity_observed at the creation proof's height, so a lagging fetch can't replace its first balance.

🤖 Co-authored by Claudius the Magnificent AI Agent

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 2 only (no Phase 1 for this repository)

The PR improves balance provenance across most identity paths, but the exact head still has three in-scope ordering gaps. Core-funded registration and first-record watermark seeding can leave balances unprotected, while direct identity-blob rewrites can restore a stale balance; foreign-wallet top-ups also remain an untracked limitation. Test Suite and Clippy are still in progress, but the code findings independently require changes.

🔴 3 blocking | 🟡 1 suggestion(s)

2 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Core-funded registration still inserts an unwatermarked balance
src/backend_task/identity/register_identity.rs:244-247

The wallet-funded registration path persists qualified_identity through insert_local_qualified_identity, so the initial balance returned by WalletBackend::register_identity receives no BalanceProvenance::ObservedAt watermark. The pinned upstream registration API returns only the identity, not response metadata containing the creation height. Consequently, a lagging discovery or refresh response can be accepted while no watermark exists and replace the newly registered balance with an older observation. This path must obtain and preserve the creation height, or perform a height-tagged read before the first local insert.

source: gpt-6.1-sol (phase2-reviewer: general)

🔴 Blocking: Alias updates bypass balance reconciliation
src/context/identity_db.rs:1053-1081

set_identity_alias reads and rewrites the stored identity blob directly, without applying with_reconciled_balance or the normal write chokepoint. The PR deliberately persists a newly accepted watermark before the corresponding blob write, so a failed blob write can leave the watermark newer than the blob. A subsequent alias edit can read that stale blob and write its old balance back unchanged, temporarily restoring an older balance despite the newer watermark. The startup key-migration helper has the same direct-rewrite pattern. Every identity-blob rewrite must preserve the balance accepted by the watermark before encoding.

source: gpt-6.1-sol (phase2-reviewer: general)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a large cross-cutting identity balance and persistence change, but it does not itself alter consensus, key handling, coin selection, or storage migrations.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/backend_task/identity/register_identity.rs`:
- [BLOCKING] src/backend_task/identity/register_identity.rs:244-247: Core-funded registration still inserts an unwatermarked balance
  The wallet-funded registration path persists `qualified_identity` through `insert_local_qualified_identity`, so the initial balance returned by `WalletBackend::register_identity` receives no `BalanceProvenance::ObservedAt` watermark. The pinned upstream registration API returns only the identity, not response metadata containing the creation height. Consequently, a lagging discovery or refresh response can be accepted while no watermark exists and replace the newly registered balance with an older observation. This path must obtain and preserve the creation height, or perform a height-tagged read before the first local insert.

In `src/context/identity_db/balance_watermark.rs`:
- [BLOCKING] src/context/identity_db/balance_watermark.rs:163-168: Do not leave the first-record balance unwatermarked after a seed failure
  For a first observed record, `insert_local_qualified_identity_observed` writes the identity blob through `insert_local_qualified_identity_under_lock` and then persists the pending watermark separately. If the blob write succeeds but `seed_balance_watermark_locked` fails, this method returns an error while leaving a valid observed balance on disk with no watermark. A later stale untagged or height-tagged write then sees no watermark and can replace that balance, defeating the ordering guarantee. The same record-then-seed ordering exists in `store_discovered_identity`; the first-record watermark needs an atomic or recovery-safe persistence strategy, or the record must be repaired/removed when seeding fails, with failure-path coverage.

In `src/context/identity_db.rs`:
- [BLOCKING] src/context/identity_db.rs:1053-1081: Alias updates bypass balance reconciliation
  `set_identity_alias` reads and rewrites the stored identity blob directly, without applying `with_reconciled_balance` or the normal write chokepoint. The PR deliberately persists a newly accepted watermark before the corresponding blob write, so a failed blob write can leave the watermark newer than the blob. A subsequent alias edit can read that stale blob and write its old balance back unchanged, temporarily restoring an older balance despite the newer watermark. The startup key-migration helper has the same direct-rewrite pattern. Every identity-blob rewrite must preserve the balance accepted by the watermark before encoding.

In `src/backend_task/identity/top_up_identity.rs`:
- [SUGGESTION] src/backend_task/identity/top_up_identity.rs:174-181: Track the ordering gap for foreign identity top-ups
  The foreign-identity path calls the upstream private-key API that returns only a balance, then stores it as `ConfirmedUnordered`. With no existing watermark, that accepts the balance without creating one, so a later stale fetch can replace the confirmed top-up. With an existing watermark, `ConfirmedUnordered` reuses the old height, allowing a later response at a higher but still stale height to replace the top-up balance. The comment correctly identifies the pinned upstream API limitation, but the PR has no tracking issue or PR for the required metadata-returning API; record that follow-up explicitly or provide a local ordering mechanism.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Oct 28, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Body findings:

  • register_identity.rs:244 (Core-funded registration): upstream. WalletBackend::register_identity returns no metadata. The identity did not exist before its creation height, so any later response that contains it is at or after that height, and the first observed write stores a slot.
  • identity_db.rs:1053 (alias updates): false positive. set_identity_alias re-encodes the stored blob with the stored balance unchanged, so it cannot restore an older balance. Reads apply no watermark, and the next write reconciles via with_reconciled_balance.

🤖 Co-authored by Claudius the Magnificent AI Agent

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 2 only (no Phase 1 for this repository)

The balance provenance implementation is integrated across the relevant identity writers, and six prior findings are fixed, withdrawn, or otherwise resolved. One blocking failure-path defect remains: a successful first identity record write followed by a failed watermark seed leaves an observed balance without protection, allowing a later stale write to replace it. Clippy and Test Suite checks were still queued at the captured head.

🔴 1 blocking

1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a broad cross-cutting identity balance and persistence change with substantial ordering logic and network-task updates, but it does not directly modify consensus, funds movement, cryptography, signatures, peer-facing deserialization, or storage migrations.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/context/identity_db/balance_watermark.rs`:
- [BLOCKING] src/context/identity_db/balance_watermark.rs:163-168: Do not leave the first-record balance unwatermarked after a seed failure
  (existing thread: https://github.com/dashpay/dash-evo-tool/pull/1110#discussion_r4405708726)
  For a first observed record, `adopt_balance_observation_locked` returns a pending watermark without persisting it. `insert_local_qualified_identity_under_lock` then writes the identity blob, and `seed_balance_watermark_locked` performs a separate KV write afterward. If that seed write fails, this method returns an error but leaves a valid observed identity record with no watermark. A later ordinary write calls `reconcile_stored_balance` with no slot and can accept a stale balance; a later height-tagged write can also establish a watermark from that stale observation. The lack of a multi-key transaction in `DetKv` does not make this state safe. Roll back or repair the record on seed failure, retry through a durable recovery mechanism, or add another recovery-safe marker that prevents unwatermarked fallback, with failure-path coverage.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. and removed waiting-bots Waiting for the review bots to report on this head labels Oct 29, 2026
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai ✓ · thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. labels Oct 29, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Review-body finding (balance_watermark.rs:163-168, first-record seed failure): Not changed here, by design, and a correction to our earlier answer. A first record's watermark can't be stored before the record: the record write itself drops a watermark that has no record (the orphan cleanup in reconcile_stored_balance), so it would be erased again. Making "watermark first" work would need extra machinery that only stands in for an atomic write. The proper fix is an atomic multi-key write in platform-wallet-storage, filed as dashpay/platform#5666 and linked in a TODO(upstream) (ba048d2). Until then, a failed seed returns an error and the identity falls back to the pre-PR behaviour (no watermark accepts any balance) until the next height-tagged write.

🤖 Co-authored by Claudius the Magnificent AI Agent

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 2 only (no Phase 1 for this repository)

The balance provenance and height ordering changes are coherent, and the available CI checks are green. One blocking persistence hole remains: alias updates bypass the reconciliation chokepoint and can make a stale identity blob durable after an observed write advanced the watermark but failed to persist the blob.

🔴 1 blocking

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Alias updates bypass balance reconciliation
src/context/identity_db.rs:1071-1081

This method decodes the stored identity and writes it directly with kv.put, bypassing with_reconciled_balance. An observed writer advances the watermark before encoding and writing the identity blob, so a vault or blob-write failure can leave the blob carrying the old balance while the watermark records a newer verified balance. A later alias edit reads that stale blob and writes it unchanged, restoring the older balance without consulting the watermark and defeating the ordering guarantee. Reconcile the decoded identity before encoding, and add a failure-path regression test.

let mut qi = decode_stored_identity(&stored.qi_bytes, self.network)?;
qi.alias = new_alias.map(str::to_string);
let reconciled = with_reconciled_balance(&kv, &id, true, &qi)?;
let reconciled_id = reconciled.as_ref().identity.id();
// Re-encode vault-first so an alias edit on a not-yet-migrated blob does
// not rewrite resident plaintext keys back to disk.
stored.qi_bytes = encode_identity_blob_vault_first(
    &self.secret_store,
    &id,
    reconciled.as_ref(),
    self.retained_identity_import_keys(&reconciled_id)?,
)?;
kv.put(scope, IDENTITY_KEY, &stored).map_err(identity_err)

source: gpt-6.1-sol (phase2-reviewer: general, rust-quality)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change that alters identity registration, transfer, withdrawal, and top-up balance handling plus persistent watermark storage in src/context/identity_db/balance_watermark.rs, directly affecting funds-related state and fee settlement.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/context/identity_db.rs`:
- [BLOCKING] src/context/identity_db.rs:1071-1081: Alias updates bypass balance reconciliation
  This method decodes the stored identity and writes it directly with `kv.put`, bypassing `with_reconciled_balance`. An observed writer advances the watermark before encoding and writing the identity blob, so a vault or blob-write failure can leave the blob carrying the old balance while the watermark records a newer verified balance. A later alias edit reads that stale blob and writes it unchanged, restoring the older balance without consulting the watermark and defeating the ordering guarantee. Reconcile the decoded identity before encoding, and add a failure-path regression test.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Oct 29, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

On "Alias updates bypass balance reconciliation" (identity_db.rs:1071-1081): the premise does not hold. set_identity_alias is unchanged from v1.0-dev. It re-encodes the balance that the blob already holds, and it leaves the watermark alone. Take the case described: an observed write moves the watermark forward and then fails to write the blob. The blob already holds the older balance at that point, and the alias edit only writes the same value again. It does not restore anything, and the watermark still records the newer verified balance. The next record write, observed or not, goes through with_reconciled_balance / reconcile_stored_balance and keeps the watermark's balance, so the ordering guarantee holds. Reconciling in the alias path would repair the blob one write earlier. That is optional hardening, not a regression in this PR.

🤖 Co-authored by Claudius the Magnificent AI Agent

@lklimek
lklimek dismissed thepastaclaw’s stale review October 30, 2026 10:04

Dismissed by the maintainer's decision. The remaining finding (alias update restores a stale balance) does not hold: see the PR comment with the evidence.

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Ready for review — files with no dedicated owner: lklimek.
Full checklist in the description.

@github-actions github-actions Bot added ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human. bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. and removed waiting-self-review Waiting for the author to post /self-reviewed labels Oct 30, 2026
@github-actions
github-actions Bot requested a review from lklimek October 30, 2026 10:05
@github-actions

Copy link
Copy Markdown
Contributor

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human. label Oct 30, 2026
@lklimek
lklimek merged commit b12e5a5 into v1.0-dev Oct 30, 2026
14 checks passed
@lklimek
lklimek deleted the feat/proof-owner-balance branch October 30, 2026 11:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-review-skipped A required review bot did not report; it was skipped by the window or by a person.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants