chore: low-risk code-quality cleanup across tBTC/beacon node - #4185
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThe 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. ChangesProtobuf serialization
Performance and proof metrics
tBTC coordination and data flow
Error and build maintenance
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (28)
pkg/beacon/dkg/marshaling.gopkg/beacon/dkg/marshaling_test.gopkg/beacon/dkg/result/marshaling.gopkg/beacon/dkg/result/marshaling_test.gopkg/beacon/registry/marshaling.gopkg/beacon/registry/marshaling_test.gopkg/clientinfo/performance.gopkg/maintainer/spv/deposit_sweep.gopkg/maintainer/spv/deposit_sweep_test.gopkg/maintainer/spv/redemptions.gopkg/maintainer/spv/redemptions_test.gopkg/protocol/inactivity/marshaling.gopkg/protocol/inactivity/marshaling_test.gopkg/protocol/state/sync_machine.gopkg/tbtc/coordination.gopkg/tbtc/coordination_window_metrics.gopkg/tbtc/deposit_sweep.gopkg/tbtc/deposit_sweep_test.gopkg/tbtc/dkg.gopkg/tbtc/marshaling.gopkg/tbtc/marshaling_test.gopkg/tbtc/moving_funds.gopkg/tbtc/wallet.gopkg/tbtcpg/chain.gopkg/tbtcpg/deposit_sweep.gopkg/tbtcpg/internal/test/marshaling.gopkg/tbtcpg/redemptions.gotools.go
💤 Files with no reviewable changes (1)
- pkg/tbtc/coordination_window_metrics.go
There was a problem hiding this comment.
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
📒 Files selected for processing (28)
pkg/beacon/dkg/marshaling.gopkg/beacon/dkg/marshaling_test.gopkg/beacon/dkg/result/marshaling.gopkg/beacon/dkg/result/marshaling_test.gopkg/beacon/registry/marshaling.gopkg/beacon/registry/marshaling_test.gopkg/clientinfo/performance.gopkg/maintainer/spv/deposit_sweep.gopkg/maintainer/spv/deposit_sweep_test.gopkg/maintainer/spv/redemptions.gopkg/maintainer/spv/redemptions_test.gopkg/protocol/inactivity/marshaling.gopkg/protocol/inactivity/marshaling_test.gopkg/protocol/state/sync_machine.gopkg/tbtc/coordination.gopkg/tbtc/coordination_window_metrics.gopkg/tbtc/deposit_sweep.gopkg/tbtc/deposit_sweep_test.gopkg/tbtc/dkg.gopkg/tbtc/marshaling.gopkg/tbtc/marshaling_test.gopkg/tbtc/moving_funds.gopkg/tbtc/wallet.gopkg/tbtcpg/chain.gopkg/tbtcpg/deposit_sweep.gopkg/tbtcpg/internal/test/marshaling.gopkg/tbtcpg/redemptions.gotools.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 protobufuint32into theuint8domain, allowing wrapped or colliding member IDs.
pkg/beacon/dkg/marshaling.go#L76-L76: rejectpbThresholdSigner.MemberIndex > group.MaxMemberIndexbefore assigning it.pkg/beacon/dkg/marshaling.go#L90-L98: reject each oversizedGroupPublicKeySharesmap 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: callt.Fatal(err)when the result-signature round-trip fails.pkg/protocol/inactivity/marshaling_test.go#L33-L61: callt.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.goRepository: threshold-network/keep-core
Length of output: 1569
Wrap the sweep-size error with
%w. Returning%vdrops the underlying error, so callers can’t useerrors.Isorerrors.Ason 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.
|
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 |
|
Two issues from review are fixed and pushed: Exported API change not reflected in the PR description — Missing test coverage for the two behavior fixes — neither the corrected error-wrapping in No outstanding issues from this pass. |
lrsaturnino
left a comment
There was a problem hiding this comment.
2 findings fixed and pushed; no outstanding issues requiring follow-up.
29bbc17 to
21232fe
Compare
|
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. |
There was a problem hiding this comment.
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
📒 Files selected for processing (31)
pkg/beacon/dkg/marshaling.gopkg/beacon/dkg/marshaling_test.gopkg/beacon/dkg/result/marshaling.gopkg/beacon/dkg/result/marshaling_test.gopkg/beacon/registry/marshaling.gopkg/beacon/registry/marshaling_test.gopkg/clientinfo/performance.gopkg/clientinfo/performance_test.gopkg/maintainer/spv/deposit_sweep.gopkg/maintainer/spv/deposit_sweep_test.gopkg/maintainer/spv/redemptions.gopkg/maintainer/spv/redemptions_test.gopkg/protocol/inactivity/marshaling.gopkg/protocol/inactivity/marshaling_test.gopkg/protocol/state/sync_machine.gopkg/tbtc/coordination.gopkg/tbtc/coordination_window_metrics.gopkg/tbtc/deposit_sweep.gopkg/tbtc/deposit_sweep_test.gopkg/tbtc/dkg.gopkg/tbtc/marshaling.gopkg/tbtc/marshaling_test.gopkg/tbtc/moving_funds.gopkg/tbtc/wallet.gopkg/tbtcpg/chain.gopkg/tbtcpg/chain_test.gopkg/tbtcpg/deposit_sweep.gopkg/tbtcpg/deposit_sweep_fee_test.gopkg/tbtcpg/internal/test/marshaling.gopkg/tbtcpg/redemptions.gotools.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
There was a problem hiding this comment.
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
📒 Files selected for processing (31)
pkg/beacon/dkg/marshaling.gopkg/beacon/dkg/marshaling_test.gopkg/beacon/dkg/result/marshaling.gopkg/beacon/dkg/result/marshaling_test.gopkg/beacon/registry/marshaling.gopkg/beacon/registry/marshaling_test.gopkg/clientinfo/performance.gopkg/clientinfo/performance_test.gopkg/maintainer/spv/deposit_sweep.gopkg/maintainer/spv/deposit_sweep_test.gopkg/maintainer/spv/redemptions.gopkg/maintainer/spv/redemptions_test.gopkg/protocol/inactivity/marshaling.gopkg/protocol/inactivity/marshaling_test.gopkg/protocol/state/sync_machine.gopkg/tbtc/coordination.gopkg/tbtc/coordination_window_metrics.gopkg/tbtc/deposit_sweep.gopkg/tbtc/deposit_sweep_test.gopkg/tbtc/dkg.gopkg/tbtc/marshaling.gopkg/tbtc/marshaling_test.gopkg/tbtc/moving_funds.gopkg/tbtc/wallet.gopkg/tbtcpg/chain.gopkg/tbtcpg/chain_test.gopkg/tbtcpg/deposit_sweep.gopkg/tbtcpg/deposit_sweep_fee_test.gopkg/tbtcpg/internal/test/marshaling.gopkg/tbtcpg/redemptions.gotools.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.ThresholdSignerstores member identifiers asuint32, butgroup.MemberIndexisuint8. A value such as257silently becomes1. 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: validatepbThresholdSigner.MemberIndexbefore conversion.pkg/beacon/dkg/marshaling.go#L90-L98: validate everymemberIDbefore 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)\(' pkgRepository: 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)) PYRepository: 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) PYRepository: 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 witherrors.Is()orerrors.As(). The Go version supports wrapping, so use%wand fix theoccuredtypo.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.
…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.
ee28988 to
b6945c3
Compare
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/tbtcsuite).Changes
registerAllMetricsinto 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.
coordinationFailedflag (both set-true branchesreturn early, so the end guard was always taken); introduce a named
DepositKeytype replacing the anonymous struct shared across tbtc/tbtcpg/ethereum; extract a shared
movingFundsSafetyMarginChaininterface; switchParseWalletActionTypeon iota constants; collapse three identicalfrequency-window guards; wrap the final-signing-group resolution error.
EstimateDepositsSweepFeeand the sync machine (was dropping / formatting thewrong value); rename
fnLogger->taskLoggerto match convention; fix twointerface doc comments to start with the method name.
(mirroring redemptions) and replace raw metric-name strings; drop the
getGlobalMetricsRecorderpassthrough wrapper; trim restating variablecomments.
marshallingfilenames to the majoritymarshalingspelling (git mv, no code changes); correct thetools.gocomment to accurately describe the pinned modules as build-time-only
dependencies (they are direct
go.modrequires, not indirect).Behavior changes
Two changes alter runtime behavior; both are intentional fixes rather than pure
cleanups:
EstimateDepositsSweepFeenow reports the real error cause. The previousmessage formatted the zero-value
sweepMaxSize(cannot get sweep max size: [0]), dropping the actual error; it now wrapserr.deposit_sweep_proof_submissions_{total,success_total,failed_total}counterswere previously incremented but never registered as observers, so they were
never exported. Registering them in
registerCounterMetricsmakes themobservable 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):
GetMovingFundsParameters),node.gomonoliths,
pkg/tbtcpackage layout, metrics DI),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
DepositKeytype. Every in-repo consumerwas updated, so
go build ./...is clean, but this is a realsource-compatibility break for any code outside this module that constructs
a
DepositSweepProposaldirectly from the old anonymous-struct literal —that code will fail to compile against the new type. This is flagged on the
DepositKeygodoc 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 ./...cleango testgreen for every touched package (clientinfo, tbtc, tbtcpg,protocol, maintainer/spv, beacon/{registry,dkg,dkg/result}, protocol/inactivity)
Summary by CodeRabbit
New Features
Bug Fixes
Tests