Skip to content

chore: low-risk code-quality cleanup across tBTC/beacon node - #4185

Merged
piotr-roslaniec merged 12 commits into
devfrom
chore/code-quality-cleanup
Aug 18, 2026
Merged

chore: low-risk code-quality cleanup across tBTC/beacon node#4185
piotr-roslaniec merged 12 commits into
devfrom
chore/code-quality-cleanup

Conversation

@piotr-roslaniec

@piotr-roslaniec piotr-roslaniec commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Summary

A focused, low-risk code-quality pass across the tBTC/beacon node. Almost all
changes are behavior-preserving cleanups (dedup, named types, dead-code removal,
error wrapping, naming/doc/comment consistency). Two are small, beneficial
functional fixes, called out under Behavior changes below. Net -40 lines.

Each touched package builds, vets, and passes its test suite (including the full
pkg/tbtc suite).

Changes

  • clientinfo: split the 240-line registerAllMetrics into per-type helpers
    (counters / wallet-actions / histograms / gauges), documenting the two-phase
    map-populate-then-observe concurrency invariant once per helper; remove
    field-group comments that restated field names; fix a stale ticker comment.
  • tbtc: remove the dead coordinationFailed flag (both set-true branches
    return early, so the end guard was always taken); introduce a named
    DepositKey type replacing the anonymous struct shared across tbtc/tbtcpg/
    ethereum; extract a shared movingFundsSafetyMarginChain interface; switch
    ParseWalletActionType on iota constants; collapse three identical
    frequency-window guards; wrap the final-signing-group resolution error.
  • tbtcpg / protocol: preserve the real error cause in
    EstimateDepositsSweepFee and the sync machine (was dropping / formatting the
    wrong value); rename fnLogger -> taskLogger to match convention; fix two
    interface doc comments to start with the method name.
  • spv: add and register deposit-sweep proof-submission metric constants
    (mirroring redemptions) and replace raw metric-name strings; drop the
    getGlobalMetricsRecorder passthrough wrapper; trim restating variable
    comments.
  • style: normalize the minority marshalling filenames to the majority
    marshaling spelling (git mv, no code changes); correct the tools.go
    comment to accurately describe the pinned modules as build-time-only
    dependencies (they are direct go.mod requires, not indirect).

Behavior changes

Two changes alter runtime behavior; both are intentional fixes rather than pure
cleanups:

  • EstimateDepositsSweepFee now reports the real error cause. The previous
    message formatted the zero-value sweepMaxSize (cannot get sweep max size: [0]), dropping the actual error; it now wraps err.
  • SPV deposit-sweep proof-submission metrics are now observable. The
    deposit_sweep_proof_submissions_{total,success_total,failed_total} counters
    were previously incremented but never registered as observers, so they were
    never exported. Registering them in registerCounterMetrics makes them
    observable for the first time.

Scope / follow-ups

This PR intentionally covers only safe-to-moderate cleanups. Deliberately left
out (larger blast radius, need dedicated review):

  • exported/interface signature changes (e.g. the 11-value
    GetMovingFundsParameters),
  • architectural refactors (splitting the ethereum adapter / node.go
    monoliths, pkg/tbtc package layout, metrics DI),
  • dependency migrations (dual go-log, deprecated addr-util),
  • new test coverage for untested entry points,
  • crypto-path cross-package dedup and concurrency/error-flow behavior changes.

One accepted exception to the above: DepositSweepProposal.DepositsKeys
(see the tbtc bullet under Changes) changes element type from an
anonymous struct to the new named DepositKey type. Every in-repo consumer
was updated, so go build ./... is clean, but this is a real
source-compatibility break for any code outside this module that constructs
a DepositSweepProposal directly from the old anonymous-struct literal —
that code will fail to compile against the new type. This is flagged on the
DepositKey godoc as a heads-up for downstream consumers. It's a trivial,
low-risk adaptation and doesn't need dedicated review, but it is a signature
change, not merely an internal cleanup, so it doesn't fit the "deliberately
left out" bucket above without this caveat.

Testing

  • go build ./... clean
  • go test green for every touched package (clientinfo, tbtc, tbtcpg,
    protocol, maintainer/spv, beacon/{registry,dkg,dkg/result}, protocol/inactivity)

Summary by CodeRabbit

  • New Features

    • Added protobuf-based serialization for threshold signing, membership, inactivity claims, and DKG result signatures.
    • Added clearer deposit identification in deposit sweep proposals.
    • Added deposit-sweep proof submission metrics for total, successful, and failed submissions.
  • Bug Fixes

    • Improved validation and error reporting for malformed data and fee calculations.
    • Refined deposit and redemption logging, error propagation, and metrics recording.
  • Tests

    • Added deterministic round-trip and fuzz testing for serialization.
    • Added coverage for deposit-sweep metrics and fee-calculation errors.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

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

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 555175ab-7941-49ca-a796-2b81265e3b77

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
📝 Walkthrough

Walkthrough

The changes add protobuf serialization for beacon and inactivity messages, reorganize metric registration, standardize proof metric wiring, introduce a named deposit-key type, and update tBTC coordination, logging, interfaces, and error handling.

Changes

Protobuf serialization

Layer / File(s) Summary
Threshold signer and membership serialization
pkg/beacon/dkg/*, pkg/beacon/registry/*
Adds protobuf round-trip support for threshold signers and memberships, including cryptographic shares, operators, and channel names.
DKG result and inactivity serialization
pkg/beacon/dkg/result/*, pkg/protocol/inactivity/*
Adds protobuf marshaling, index and hash validation, deterministic tests, and fuzz coverage.

Performance and proof metrics

Layer / File(s) Summary
Metric registration and exported names
pkg/clientinfo/performance.go, pkg/clientinfo/performance_test.go
Splits metric registration into dedicated helpers and registers deposit-sweep proof counters with registry tests.
SPV proof metrics recorder wiring
pkg/maintainer/spv/*
Uses shared metric constants and passes the direct metrics recorder to proof submission paths.

tBTC coordination and data flow

Layer / File(s) Summary
Coordination metrics and action scheduling
pkg/tbtc/coordination*.go
Records coordination metrics when a recorder exists and groups pre-activation actions.
Named deposit key propagation
pkg/tbtc/deposit_sweep.go, pkg/tbtc/marshaling.go, pkg/tbtcpg/deposit_sweep.go, pkg/tbtcpg/internal/test/marshaling.go
Introduces DepositKey and propagates it through proposal construction, unmarshaling, conversion, and tests.
Moving-funds interfaces and action typing
pkg/tbtc/moving_funds.go, pkg/tbtc/wallet.go
Introduces a shared safety-margin chain interface and switches action parsing on WalletActionType.
Deposit and redemption scanning
pkg/tbtcpg/deposit_sweep.go, pkg/tbtcpg/redemptions.go, pkg/tbtcpg/*_test.go
Uses task-specific loggers, struct-based redemption parameters, and tests wrapped sweep-size lookup errors.

Error and build maintenance

Layer / File(s) Summary
Error context
pkg/protocol/state/sync_machine.go, pkg/tbtc/dkg.go
Changes block-wait error handling and the signing-group error format.
Interface and build comments
pkg/tbtcpg/chain.go, tools.go
Updates public method wording and documents build-time dependency pinning.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

Suggested reviewers: lrsaturnino

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the broad, behavior-preserving code-quality cleanup across the tBTC and beacon node changes.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/code-quality-cleanup

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/beacon/dkg/marshaling.go`:
- Line 76: Validate protobuf member indices against group.MaxMemberIndex before
every uint32-to-group.MemberIndex conversion: in pkg/beacon/dkg/marshaling.go
lines 76-76, reject pbThresholdSigner.MemberIndex before assigning
ts.memberIndex; in lines 90-98, reject each oversized GroupPublicKeyShares map
key before converting it. Preserve the existing error-handling flow for invalid
input.

In `@pkg/beacon/dkg/result/marshaling_test.go`:
- Around line 34-62: Assert the result of pbutils.RoundTrip in
TestFuzzDKGResultHashSignatureMessageRoundtrip and call t.Fatal(err) when it
fails; apply the same change to the claim-signature round-trip test in
pkg/protocol/inactivity/marshaling_test.go at lines 33-61. Preserve the existing
fuzz setup and message construction.

In `@pkg/tbtcpg/deposit_sweep.go`:
- Around line 605-607: Update the error wrapping in the deposit sweep flow
around GetDepositSweepMaxSize to use `%w` instead of `%v`, preserving the
underlying error for errors.Is and errors.As while keeping the existing context
message and return behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 82ec20eb-1390-462e-9ffb-68d4184fb117

📥 Commits

Reviewing files that changed from the base of the PR and between 5245f66 and 2885b0a.

📒 Files selected for processing (28)
  • pkg/beacon/dkg/marshaling.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/beacon/dkg/result/marshaling.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/beacon/registry/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/maintainer/spv/redemptions.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/protocol/inactivity/marshaling.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/protocol/state/sync_machine.go
  • pkg/tbtc/coordination.go
  • pkg/tbtc/coordination_window_metrics.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/tbtc/dkg.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtc/wallet.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/tbtcpg/redemptions.go
  • tools.go
💤 Files with no reviewable changes (1)
  • pkg/tbtc/coordination_window_metrics.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/beacon/dkg/marshaling.go`:
- Line 76: Validate protobuf member indices against group.MaxMemberIndex before
every uint32-to-group.MemberIndex conversion: in pkg/beacon/dkg/marshaling.go
lines 76-76, reject pbThresholdSigner.MemberIndex before assigning
ts.memberIndex; in lines 90-98, reject each oversized GroupPublicKeyShares map
key before converting it. Preserve the existing error-handling flow for invalid
input.

In `@pkg/beacon/dkg/result/marshaling_test.go`:
- Around line 34-62: Assert the result of pbutils.RoundTrip in
TestFuzzDKGResultHashSignatureMessageRoundtrip and call t.Fatal(err) when it
fails; apply the same change to the claim-signature round-trip test in
pkg/protocol/inactivity/marshaling_test.go at lines 33-61. Preserve the existing
fuzz setup and message construction.

In `@pkg/tbtcpg/deposit_sweep.go`:
- Around line 605-607: Update the error wrapping in the deposit sweep flow
around GetDepositSweepMaxSize to use `%w` instead of `%v`, preserving the
underlying error for errors.Is and errors.As while keeping the existing context
message and return behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 82ec20eb-1390-462e-9ffb-68d4184fb117

📥 Commits

Reviewing files that changed from the base of the PR and between 5245f66 and 2885b0a.

📒 Files selected for processing (28)
  • pkg/beacon/dkg/marshaling.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/beacon/dkg/result/marshaling.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/beacon/registry/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/maintainer/spv/redemptions.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/protocol/inactivity/marshaling.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/protocol/state/sync_machine.go
  • pkg/tbtc/coordination.go
  • pkg/tbtc/coordination_window_metrics.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/tbtc/dkg.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtc/wallet.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/tbtcpg/redemptions.go
  • tools.go
💤 Files with no reviewable changes (1)
  • pkg/tbtc/coordination_window_metrics.go
🛑 Comments failed to post (3)
pkg/beacon/dkg/marshaling.go (1)

76-76: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate every protobuf member index before narrowing to group.MemberIndex. Both fields cross from protobuf uint32 into the uint8 domain, allowing wrapped or colliding member IDs.

  • pkg/beacon/dkg/marshaling.go#L76-L76: reject pbThresholdSigner.MemberIndex > group.MaxMemberIndex before assigning it.
  • pkg/beacon/dkg/marshaling.go#L90-L98: reject each oversized GroupPublicKeyShares map key before converting it.
📍 Affects 1 file
  • pkg/beacon/dkg/marshaling.go#L76-L76 (this comment)
  • pkg/beacon/dkg/marshaling.go#L90-L98
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/beacon/dkg/marshaling.go` at line 76, Validate protobuf member indices
against group.MaxMemberIndex before every uint32-to-group.MemberIndex
conversion: in pkg/beacon/dkg/marshaling.go lines 76-76, reject
pbThresholdSigner.MemberIndex before assigning ts.memberIndex; in lines 90-98,
reject each oversized GroupPublicKeyShares map key before converting it.
Preserve the existing error-handling flow for invalid input.
pkg/beacon/dkg/result/marshaling_test.go (1)

34-62: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert successful fuzz round-trips. Both tests discard the only failure signal from pbutils.RoundTrip, reducing them to panic smoke tests.

  • pkg/beacon/dkg/result/marshaling_test.go#L34-L62: call t.Fatal(err) when the result-signature round-trip fails.
  • pkg/protocol/inactivity/marshaling_test.go#L33-L61: call t.Fatal(err) when the claim-signature round-trip fails.
📍 Affects 2 files
  • pkg/beacon/dkg/result/marshaling_test.go#L34-L62 (this comment)
  • pkg/protocol/inactivity/marshaling_test.go#L33-L61
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/beacon/dkg/result/marshaling_test.go` around lines 34 - 62, Assert the
result of pbutils.RoundTrip in TestFuzzDKGResultHashSignatureMessageRoundtrip
and call t.Fatal(err) when it fails; apply the same change to the
claim-signature round-trip test in pkg/protocol/inactivity/marshaling_test.go at
lines 33-61. Preserve the existing fuzz setup and message construction.
pkg/tbtcpg/deposit_sweep.go (1)

605-607: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant section with line numbers.
sed -n '585,620p' pkg/tbtcpg/deposit_sweep.go

# Find similar error-wrapping patterns in the file for consistency.
rg -n 'fmt\.Errorf\(.*%[vw]' pkg/tbtcpg/deposit_sweep.go

Repository: threshold-network/keep-core

Length of output: 1569


Wrap the sweep-size error with %w. Returning %v drops the underlying error, so callers can’t use errors.Is or errors.As on this path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/tbtcpg/deposit_sweep.go` around lines 605 - 607, Update the error
wrapping in the deposit sweep flow around GetDepositSweepMaxSize to use `%w`
instead of `%v`, preserving the underlying error for errors.Is and errors.As
while keeping the existing context message and return behavior.

@lrsaturnino

Copy link
Copy Markdown
Member

Updated the PR description's "Scope / follow-ups" section: it previously listed exported/interface signature changes as entirely out of scope for this PR, but DepositSweepProposal.DepositsKeys (via the new DepositKey type) is itself a minor exported-type change — its element type moved from an anonymous struct to a named one, which breaks source compatibility for any external code that constructs DepositSweepProposal directly with the old struct literal. No in-repo consumer is affected and go build ./... stays clean, so this doesn't need to block the PR, but the description should reflect it rather than claim no exported changes occurred. Also added a godoc note on DepositKey itself flagging this for anyone building against this package.

@lrsaturnino

Copy link
Copy Markdown
Member

Two issues from review are fixed and pushed:

Exported API change not reflected in the PR descriptionDepositSweepProposal.DepositsKeys moved from an anonymous struct to the named DepositKey type, which is a source-compatibility break for any external code building DepositSweepProposal values, but the PR description didn't call this out as an accepted exception. Added a godoc note on DepositKey in pkg/tbtc/deposit_sweep.go documenting the break so downstream consumers aren't surprised on upgrade. (29dc281)

Missing test coverage for the two behavior fixes — neither the corrected error-wrapping in GetDepositSweepMaxSize nor the three new deposit-sweep proof-submission counters had test coverage; the existing fee-estimation table never exercised the depositsCount == 0 branch that reaches the error-wrapping code, and the counters weren't referenced by any test. Added LocalChain.SetDepositSweepMaxSizeError plus a depositsCount: 0 case to pkg/tbtcpg/deposit_sweep_fee_test.go asserting the wrapped error preserves its real cause, and added TestDepositSweepProofSubmissionCountersRegistered to pkg/clientinfo/performance_test.go, mirroring the existing counter-registration test pattern. (29bbc17)

No outstanding issues from this pass.

lrsaturnino
lrsaturnino previously approved these changes Jul 29, 2026

@lrsaturnino lrsaturnino left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

2 findings fixed and pushed; no outstanding issues requiring follow-up.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/beacon/dkg/marshaling.go`:
- Around line 76-80: In pkg/beacon/dkg/marshaling.go at lines 76-80, update the
protobuf signer unmarshaling to reject pbThresholdSigner.MemberIndex values
above uint8 before converting to group.MemberIndex; at lines 90-98, likewise
reject each memberID outside uint8 before converting it for insertion into the
unmarshaled public-key-share map. Propagate an appropriate unmarshaling error in
both validation paths rather than allowing truncation or key collisions.

In `@pkg/beacon/registry/marshaling.go`:
- Around line 34-37: Update the error returned by Membership.Unmarshal after
signer.Unmarshal fails to wrap the original error with %w instead of %v, and
correct “occured” to “occurred,” preserving errors.Is/errors.As inspection of
the signer decoding error.

In `@pkg/clientinfo/performance_test.go`:
- Around line 434-437: Update TestDepositSweepProofSubmissionCountersRegistered
to inspect the metrics registry output before incrementing counters, asserting
that each expected deposit-sweep proof-submission counter is exported under its
intended metric name. Keep the existing pm.counters and GetCounterValue checks,
and verify registration through pm.registry.ObserveApplicationSource.

In `@pkg/tbtcpg/deposit_sweep_fee_test.go`:
- Around line 38-40: The sweep max-size error in EstimateDepositsSweepFee must
wrap the underlying cause so errors.Is can detect it. Replace value-only
formatting with error wrapping, then retain the original sentinel in the test
case and assert errors.Is against test.sweepMaxSizeErr; keep the message
assertion only if required by the contract.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 550adaf9-d39f-4501-b981-fd7f9eafb049

📥 Commits

Reviewing files that changed from the base of the PR and between fac4b79 and 21232fe.

📒 Files selected for processing (31)
  • pkg/beacon/dkg/marshaling.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/beacon/dkg/result/marshaling.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/beacon/registry/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/clientinfo/performance_test.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/maintainer/spv/redemptions.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/protocol/inactivity/marshaling.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/protocol/state/sync_machine.go
  • pkg/tbtc/coordination.go
  • pkg/tbtc/coordination_window_metrics.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/tbtc/dkg.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtc/wallet.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtcpg/chain_test.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/tbtcpg/deposit_sweep_fee_test.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/tbtcpg/redemptions.go
  • tools.go
💤 Files with no reviewable changes (1)
  • pkg/tbtc/coordination_window_metrics.go
🚧 Files skipped from review as they are similar to previous changes (23)
  • pkg/protocol/state/sync_machine.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/wallet.go
  • tools.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtcpg/redemptions.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/tbtc/dkg.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/tbtc/coordination.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/maintainer/spv/redemptions.go

Comment thread pkg/clientinfo/performance_test.go
Comment thread pkg/tbtcpg/deposit_sweep_fee_test.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/beacon/dkg/marshaling.go`:
- Around line 76-80: In pkg/beacon/dkg/marshaling.go at lines 76-80, update the
protobuf signer unmarshaling to reject pbThresholdSigner.MemberIndex values
above uint8 before converting to group.MemberIndex; at lines 90-98, likewise
reject each memberID outside uint8 before converting it for insertion into the
unmarshaled public-key-share map. Propagate an appropriate unmarshaling error in
both validation paths rather than allowing truncation or key collisions.

In `@pkg/beacon/registry/marshaling.go`:
- Around line 34-37: Update the error returned by Membership.Unmarshal after
signer.Unmarshal fails to wrap the original error with %w instead of %v, and
correct “occured” to “occurred,” preserving errors.Is/errors.As inspection of
the signer decoding error.

In `@pkg/clientinfo/performance_test.go`:
- Around line 434-437: Update TestDepositSweepProofSubmissionCountersRegistered
to inspect the metrics registry output before incrementing counters, asserting
that each expected deposit-sweep proof-submission counter is exported under its
intended metric name. Keep the existing pm.counters and GetCounterValue checks,
and verify registration through pm.registry.ObserveApplicationSource.

In `@pkg/tbtcpg/deposit_sweep_fee_test.go`:
- Around line 38-40: The sweep max-size error in EstimateDepositsSweepFee must
wrap the underlying cause so errors.Is can detect it. Replace value-only
formatting with error wrapping, then retain the original sentinel in the test
case and assert errors.Is against test.sweepMaxSizeErr; keep the message
assertion only if required by the contract.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 550adaf9-d39f-4501-b981-fd7f9eafb049

📥 Commits

Reviewing files that changed from the base of the PR and between fac4b79 and 21232fe.

📒 Files selected for processing (31)
  • pkg/beacon/dkg/marshaling.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/beacon/dkg/result/marshaling.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/beacon/registry/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/clientinfo/performance_test.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/maintainer/spv/redemptions.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/protocol/inactivity/marshaling.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/protocol/state/sync_machine.go
  • pkg/tbtc/coordination.go
  • pkg/tbtc/coordination_window_metrics.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/tbtc/dkg.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtc/wallet.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtcpg/chain_test.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/tbtcpg/deposit_sweep_fee_test.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/tbtcpg/redemptions.go
  • tools.go
💤 Files with no reviewable changes (1)
  • pkg/tbtc/coordination_window_metrics.go
🚧 Files skipped from review as they are similar to previous changes (23)
  • pkg/protocol/state/sync_machine.go
  • pkg/maintainer/spv/redemptions_test.go
  • pkg/maintainer/spv/deposit_sweep_test.go
  • pkg/tbtcpg/chain.go
  • pkg/tbtc/marshaling_test.go
  • pkg/tbtc/wallet.go
  • tools.go
  • pkg/tbtc/marshaling.go
  • pkg/tbtc/deposit_sweep.go
  • pkg/tbtc/deposit_sweep_test.go
  • pkg/beacon/dkg/marshaling_test.go
  • pkg/tbtc/moving_funds.go
  • pkg/tbtcpg/redemptions.go
  • pkg/tbtcpg/internal/test/marshaling.go
  • pkg/beacon/registry/marshaling_test.go
  • pkg/tbtc/dkg.go
  • pkg/protocol/inactivity/marshaling_test.go
  • pkg/maintainer/spv/deposit_sweep.go
  • pkg/tbtc/coordination.go
  • pkg/beacon/dkg/result/marshaling_test.go
  • pkg/clientinfo/performance.go
  • pkg/tbtcpg/deposit_sweep.go
  • pkg/maintainer/spv/redemptions.go
🛑 Comments failed to post (2)
pkg/beacon/dkg/marshaling.go (1)

76-80: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject protobuf member indices outside uint8.

pb.ThresholdSigner stores member identifiers as uint32, but group.MemberIndex is uint8. A value such as 257 silently becomes 1. This can assign the signer to the wrong member and can overwrite a valid public-key share after map-key conversion.

  • pkg/beacon/dkg/marshaling.go#L76-L80: validate pbThresholdSigner.MemberIndex before conversion.
  • pkg/beacon/dkg/marshaling.go#L90-L98: validate every memberID before inserting it into the unmarshalled map.
Proposed fix
+	if pbThresholdSigner.MemberIndex > uint32(^uint8(0)) {
+		return fmt.Errorf("member index exceeds uint8 range")
+	}
 	ts.memberIndex = group.MemberIndex(pbThresholdSigner.MemberIndex)
 	for memberID, shareBytes := range shares {
+		if memberID > uint32(^uint8(0)) {
+			return nil, fmt.Errorf("member index exceeds uint8 range")
+		}
+
 		share := new(bn256.G2)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if pbThresholdSigner.MemberIndex > uint32(^uint8(0)) {
		return fmt.Errorf("member index exceeds uint8 range")
	}
	ts.memberIndex = group.MemberIndex(pbThresholdSigner.MemberIndex)
	ts.groupPublicKey = groupPublicKey
	ts.groupPrivateKeyShare = privateKeyShare
	ts.groupPublicKeyShares = groupPublicKeyShares
	ts.groupOperators = unmarshalGroupOperators(pbThresholdSigner.GetGroupOperators())
	for memberID, shareBytes := range shares {
		if memberID > uint32(^uint8(0)) {
			return nil, fmt.Errorf("member index exceeds uint8 range")
		}

		share := new(bn256.G2)
		_, err := share.Unmarshal(shareBytes)
		if err != nil {
			return nil, fmt.Errorf("could not unmarshal share [%v]", err)
		}

		unmarshalled[group.MemberIndex(memberID)] = share
	}
📍 Affects 1 file
  • pkg/beacon/dkg/marshaling.go#L76-L80 (this comment)
  • pkg/beacon/dkg/marshaling.go#L90-L98
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/beacon/dkg/marshaling.go` around lines 76 - 80, In
pkg/beacon/dkg/marshaling.go at lines 76-80, update the protobuf signer
unmarshaling to reject pbThresholdSigner.MemberIndex values above uint8 before
converting to group.MemberIndex; at lines 90-98, likewise reject each memberID
outside uint8 before converting it for insertion into the unmarshaled
public-key-share map. Propagate an appropriate unmarshaling error in both
validation paths rather than allowing truncation or key collisions.
pkg/beacon/registry/marshaling.go (1)

34-37: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Confirm that the declared Go version supports fmt.Errorf %w wrapping.
rg -n '^go [0-9]+\.[0-9]+' go.mod

# Find callers that may need to inspect Membership.Unmarshal errors.
rg -n -C 3 --glob '*.go' 'Membership.*Unmarshal|errors\.(Is|As)\(' pkg

Repository: threshold-network/keep-core

Length of output: 8058


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== marshaling.go =="
cat -n pkg/beacon/registry/marshaling.go

echo "== Go version =="
sed -n '1,8p' go.mod

echo "== errors import usages in pkg/beacon =="
rg -n 'errors\.|Unmarshal\(' pkg/beacon --glob '*.go'

echo "== Membership usages that handle result errors =="
rg -n -C 2 --glob '*.go' 'registry\.Membership|\.Unmarshal\(|UnmarshalBytes|MarshalBytes' pkg|cmd | sed -n '1,220p'

echo "== direct pkg/beacon/registry errors.Is/As references =="
rg -n -C 2 --glob '*.go' 'errors\.(Is|As)\(' pkg/beacon

python3 - <<'PY'
from pathlib import Path
import re
p = Path("pkg/beacon/registry/marshaling.go")
text = p.read_text()
m = re.search(r'err := signer\.Unmarshal\(pbMembership\.Signer\).*?return fmt\.Errorf\("([^"]+).*(%v|%w).*?"', text, re.S)
print("signer error line:", m.group(0) if m else "not found")
if m:
    for pat in ["%w", "%v"]:
        print(pat, "present:", pat in m.group(0))
PY

Repository: threshold-network/keep-core

Length of output: 4816


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Membership Unmarshal callers and registry storage =="
rg -n -C 3 --glob '*.go' '\.Unmarshal\(content\)|registry\.Membership|Membership\.' pkg/beacon/registry pkg | sed -n '1,220p'

echo "== errors package usage in beacon registry =="
rg -n --glob '*.go' 'errors\.(Is|As)\(' pkg/beacon/registry || true

echo "== parse formatter in pkg/beacon/registry/marshaling.go =="
python3 - <<'PY'
from pathlib import Path
import re
text = Path("pkg/beacon/registry/marshaling.go").read_text()
m = re.search(r'fmt\.Errorf\("([^"]+)', text)
print("fmt.Errorf format:", m.group(1) if m else "not found")
print("contains %w:", "%w" in text)
print("occured typo present:", "occured" in text)
PY

Repository: threshold-network/keep-core

Length of output: 7469


Preserve the signer error cause.

Membership.Unmarshal() uses %v, so callers cannot inspect the underlying signer decoding error with errors.Is() or errors.As(). The Go version supports wrapping, so use %w and fix the occured typo.

Proposed fix
-		return fmt.Errorf("unexpected error occured [%v]", err)
+		return fmt.Errorf("unexpected error occurred: %w", err)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	err := signer.Unmarshal(pbMembership.Signer)
	if err != nil {
		return fmt.Errorf("unexpected error occurred: %w", err)
	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/beacon/registry/marshaling.go` around lines 34 - 37, Update the error
returned by Membership.Unmarshal after signer.Unmarshal fails to wrap the
original error with %w instead of %v, and correct “occured” to “occurred,”
preserving errors.Is/errors.As inspection of the signer decoding error.

@piotr-roslaniec
piotr-roslaniec changed the base branch from main to dev August 18, 2026 08:48
piotr-roslaniec and others added 12 commits August 18, 2026 09:03
…ments

Extract registerAllMetrics into per-type helpers (counters, wallet actions,
histograms, gauges) to isolate responsibilities, document the two-phase
map-populate-then-observe concurrency invariant once per helper, remove
field-group comments that restated field names, and correct the stale
system-metrics ticker comment (60s).
…mments

The coordinationFailed variable was only ever set true in branches that
return immediately, so the success-metrics guard was always taken; remove
the variable and simplify the guard. Also drop track-narration comments in
coordination_window_metrics.go that restated the following line.
- add named DepositKey type replacing the anonymous struct used for
  DepositSweepProposal.DepositsKeys across tbtc, tbtcpg and ethereum
- extract movingFundsSafetyMarginChain interface shared by
  ValidateMovingFundsSafetyMargin and isWalletPendingMovingFundsTarget
- switch ParseWalletActionType on WalletActionType iota constants
- collapse three identical frequency-window guards into a single guard
- EstimateDepositsSweepFee wraps the real error (was formatting the
  zero-valued sweepMaxSize) when GetDepositSweepMaxSize fails
- sync_machine wraps the WaitForBlockHeight error with %w so callers can
  inspect the root cause
- rename fnLogger to taskLogger to match the established logger naming
- fix two Chain interface doc comments to start with the method name
- correct the tools.go comment to describe indirect-dependency pinning
Wrap the finalSigningGroup error with %w so callers can inspect the
underlying cause instead of only the outer message.
- add and register clientinfo deposit-sweep proof-submission metric
  constants, mirroring the redemption ones, and replace the raw metric
  name strings in the SPV maintainer with them
- remove the getGlobalMetricsRecorder passthrough and call
  getMetricsRecorder directly
- trim variable comments that restated the variable names in
  parseDepositSweepTransactionInputs, keeping the vault constraint note
Rename the minority marshalling.go files to the majority marshaling
spelling for consistency across packages (git mv, no code changes).
The movingFundsSafetyMarginChain interface was inserted between the
function's doc comment and its declaration, detaching the doc. Move the
interface above the doc comment so it attaches again.
All five pinned modules are direct requires in go.mod, not indirect;
describe them by what they actually are (build-time-only).
DepositKey replaced the anonymous struct previously inlined as the
element type of DepositSweepProposal.DepositsKeys. Go does not allow
assigning an anonymous-struct-typed slice literal to a
named-struct-typed slice field, so any code outside this module that
constructs a DepositSweepProposal from the old anonymous struct shape
fails to compile against the new type, even though every in-repo
consumer was already updated. Document this on the DepositKey type so
downstream consumers of this package are not surprised by a silent
compile break on upgrade.
Neither of this PR's stated behavior fixes had direct test coverage:
every EstimateDepositsSweepFee table case used depositsCount > 0, so the
branch calling GetDepositSweepMaxSize (and its corrected error-wrapping)
was never reached, and the panicking LocalChain double would have
crashed the suite had it ever been exercised.

- add LocalChain.SetDepositSweepMaxSizeError to let tests configure that
  failure without a real chain implementation
- add a depositsCount: 0 case asserting the wrapped error keeps the real
  underlying cause instead of the old zero-value formatting
- add TestDepositSweepProofSubmissionCountersRegistered, mirroring
  TestJoinFailureAndOnChainCountersRegistered, asserting the three new
  deposit-sweep proof-submission counters are pre-registered and exported
- EstimateDepositsSweepFee wrapped the sweep-max-size lookup error with
  %v instead of %w, so errors.Is could never match the underlying
  cause; switch to %w and assert errors.Is in the regression test.
- The counter-registration tests only checked pm's internal counters
  map, so a regression dropping ObserveApplicationSource (or
  registering under the wrong metric name) would pass silently. Add an
  assertion that each counter is actually exported under the registry
  by attempting to re-register the same gauge name and expecting an
  'already exists' error.
@piotr-roslaniec
piotr-roslaniec force-pushed the chore/code-quality-cleanup branch from ee28988 to b6945c3 Compare August 18, 2026 09:03
@piotr-roslaniec
piotr-roslaniec merged commit 7851945 into dev Aug 18, 2026
17 checks passed
@piotr-roslaniec
piotr-roslaniec deleted the chore/code-quality-cleanup branch August 18, 2026 09:35
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.

2 participants