Skip to content

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

Open
piotr-roslaniec wants to merge 9 commits into
mainfrom
chore/code-quality-cleanup
Open

chore: low-risk code-quality cleanup across tBTC/beacon node#4185
piotr-roslaniec wants to merge 9 commits into
mainfrom
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.

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 reliable serialization and restoration for threshold signing, membership, inactivity, and coordination messages.
    • Introduced clearer deposit identification for deposit sweep proposals.
    • Added metrics for total, successful, and failed deposit-sweep proof submissions.
  • Bug Fixes

    • Improved error details when synchronization, deposit scanning, fee estimation, and signer registration fail.
    • Improved validation for message member indexes and malformed cryptographic data.
    • Corrected logging during deposit and redemption processing.
  • Tests

    • Added round-trip and fuzz testing for newly supported message serialization.

…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).
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

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 and inactivity message serialization
pkg/beacon/dkg/result/*, pkg/protocol/inactivity/*
Adds protobuf marshaling, validation, deterministic tests, and fuzz coverage for DKG result and inactivity claim signature messages.

Performance and proof metrics

Layer / File(s) Summary
Metric registration and exported names
pkg/clientinfo/performance.go
Splits metric registration into dedicated helpers, initializes maps before observers, and registers deposit-sweep proof counters.
SPV proof metrics recorder wiring
pkg/maintainer/spv/*
Uses named metric constants and the direct metrics recorder for deposit-sweep and redemption proof submission paths.

tBTC coordination updates

Layer / File(s) Summary
Coordination metrics and action scheduling
pkg/tbtc/coordination*.go
Records coordination metrics whenever a recorder exists and groups pre-activation actions in one append.
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 interface 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
Uses task-specific loggers throughout scanning and corrects deposit sweep fee error formatting.

Error and documentation cleanup

Layer / File(s) Summary
Preserved error context
pkg/protocol/state/sync_machine.go, pkg/tbtc/dkg.go
Wraps underlying errors from block waiting and final signing-group resolution.
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

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Membership
  participant ThresholdSigner
  participant Protobuf
  Caller->>Membership: Marshal membership
  Membership->>ThresholdSigner: Marshal signer
  ThresholdSigner->>Protobuf: Encode signer fields
  Protobuf-->>Membership: Return serialized bytes
  Caller->>Membership: Unmarshal membership
  Membership->>Protobuf: Decode membership bytes
  Membership->>ThresholdSigner: Unmarshal embedded signer
  ThresholdSigner-->>Membership: Restore signer state
Loading

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 45.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 cleanup across tBTC and the beacon node.
✨ Finishing Touches
📝 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.

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).

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant