Skip to content

feat: remove btcd dependency #1201

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft

Conversation

yiweichi
Copy link
Member

@yiweichi yiweichi commented Jun 9, 2025

1. Purpose or design rationale of this PR

...

2. PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • build: Changes that affect the build system or external dependencies (example scopes: yarn, eslint, typescript)
  • ci: Changes to our CI configuration files and scripts (example scopes: vercel, github, cypress)
  • docs: Documentation-only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that doesn't fix a bug, or add a feature, or improves performance
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  • test: Adding missing tests or correcting existing tests

3. Deployment tag versioning

Has the version in params/version.go been updated?

  • This PR doesn't involve a new deployment, git tag, docker image tag, and it doesn't affect traces
  • Yes

4. Breaking change label

Does this PR have the breaking-change label?

  • This PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • New Features
    • Improved cryptographic operations by switching to a new secp256k1 implementation for enhanced compatibility and security.
  • Bug Fixes
    • Enhanced signature and public key validation to prevent malformed or invalid cryptographic data.
  • Tests
    • Expanded test coverage with fuzz testing to ensure reliability and consistency in elliptic curve operations across implementations.

Copy link

coderabbitai bot commented Jun 9, 2025

Walkthrough

The codebase transitions its secp256k1 cryptographic implementation from btcec to the Decred project's dcrd/dcrec/secp256k1/v4 library. All signature, key handling, and curve operations are updated accordingly. Tests are expanded to include fuzzing and cross-library consistency checks for elliptic curve point addition. The new dependency is added to go.mod.

Changes

File(s) Change Summary
crypto/signature_nocgo.go Migrated secp256k1 implementation from btcec to Decred's dcrd/dcrec/secp256k1/v4, updated all related cryptographic functions, added curve wrapper, and adjusted error handling.
go.mod Added dependency: github.com/decred/dcrd/dcrec/secp256k1/v4 at version v4.4.0.
tests/fuzzers/secp256k1/secp_test.go Replaced single test with fuzzing harness; added functions for fuzzing and cross-library point addition checks.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Fuzz Test
    participant Curve1 as go-ethereum secp256k1
    participant Curve2 as Decred secp256k1

    Test->>Curve1: Derive points P1, P2 via base mult (dataP1, dataP2)
    Test->>Curve2: Derive points Q1, Q2 via base mult (dataP1, dataP2)
    Test->>Curve1: Add P1 + P2 -> (x1, y1)
    Test->>Curve2: Add Q1 + Q2 -> (x2, y2)
    Test->>Test: Compare (x1, y1) with (x2, y2)
    alt Not equal
        Test->>Test: Panic and print error
    end
Loading

Poem

In fields of curves where bytes align,
A rabbit hops from old to Decred's sign.
With fuzzers wild and points that add,
It checks each sum—good or bad!
A new curve’s dance, a cryptic delight,
Secure and swift, from day to night.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
go.mod (1)

13-13: ⚠️ Potential issue

The btcd dependency was not removed.

While the Decred secp256k1 dependency was added at line 20, the github.com/btcsuite/btcd v0.20.1-beta dependency at line 13 is still present. This contradicts the PR objective of removing the btcd dependency.

Apply this diff to complete the btcd removal:

-	github.com/btcsuite/btcd v0.20.1-beta

Also applies to: 20-20

🧹 Nitpick comments (1)
tests/fuzzers/secp256k1/secp_test.go (1)

51-51: Update error message to reflect the actual library being used.

The panic message incorrectly references "btcd" when the code is using the Decred secp256k1 implementation.

-		panic(fmt.Sprintf("Addition failed: geth: %s %s btcd: %s %s", resAX, resAY, resBX, resBY))
+		panic(fmt.Sprintf("Addition failed: geth: %s %s dcred: %s %s", resAX, resAY, resBX, resBY))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7fbc35d and f30b2b1.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • crypto/signature_nocgo.go (3 hunks)
  • go.mod (1 hunks)
  • tests/fuzzers/secp256k1/secp_test.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: check
tests/fuzzers/secp256k1/secp_test.go

[failure] 38-38:
fuzz already declared through import of package fuzz ("github.com/google/gofuzz")


[failure] 32-32:
Fuzz redeclared in this block

🪛 GitHub Actions: CI
tests/fuzzers/secp256k1/secp_test.go

[error] 32-32: Fuzz redeclared in this block

🪛 Gitleaks (8.26.0)
crypto/signature_nocgo.go

85-85: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
crypto/signature_nocgo.go (5)

17-18: Good addition of platform support.

The expanded build tags to include wasip1 and tinygo improve platform compatibility.


78-97: Secure implementation with proper key handling.

The signature generation correctly validates the curve, safely converts the private key with overflow checks, and properly zeros the key material after use.

🧰 Tools
🪛 Gitleaks (8.26.0)

85-85: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


118-122: Important security enhancement for signature malleability protection.

Excellent addition of the malleability check using IsOverHalfOrder(). This ensures compatibility with libsecp256k1's behavior and prevents signature malleability attacks.


158-193:

✅ Verification successful

Verify the btCurve wrapper maintains compatibility with the original implementation.

The custom btCurve wrapper correctly implements marshaling/unmarshaling for uncompressed points. However, we should verify that this matches the exact behavior of the original btcec implementation to ensure backward compatibility.

Run this script to verify the wrapper implementation:


🏁 Script executed:

#!/bin/bash
# Description: Search for any existing usage of Marshal/Unmarshal methods to ensure compatibility

# Check for existing Marshal/Unmarshal usage patterns
rg -A 5 "\.Marshal\(" --type go
rg -A 5 "\.Unmarshal\(" --type go

# Look for any elliptic curve point serialization patterns
ast-grep --pattern 'elliptic.Marshal($$$)'
ast-grep --pattern 'elliptic.Unmarshal($$$)'

Length of output: 69777


I want to inspect the cgo‐backed implementation of Marshal/Unmarshal to ensure they produce the same uncompressed format. Let’s pull in the *_cgo.go files under crypto/ and look for the secp256k1 serialize/parse calls:


🏁 Script executed:

#!/bin/bash
# Locate any Go files under crypto/ that mention cgo in their name
CGO_FILES=$(find crypto -type f -name "*cgo*.go")
echo "Found cgo files:"
echo "$CGO_FILES"

# For each, dump the top and search for serialize/parse
for f in $CGO_FILES; do
  echo
  echo "=== $f ==="
  sed -n '1,200p' "$f"
  echo "----- looking for serialization functions -----"
  grep -n "serialize" "$f" || true
  grep -n "parse" "$f"     || true
done

Length of output: 21117


Compatibility Verified: btCurve Marshal/Unmarshal Matches Default Behavior

The custom btCurve.Marshal and Unmarshal implementations are identical to Go’s crypto/elliptic.Marshal and Unmarshal for uncompressed points:

  • Both use a 0x04 prefix and fixed 1+2*byteLen length.
  • Both pad big‐endian coordinates to byteLen bytes.
  • Neither performs additional curve‐point validity checks (matching the stdlib).

No changes required.


159-161:

✅ Verification successful

Verify API compatibility of the new EllipticCurve return type.

The S256() function now returns a custom btCurve type instead of the original curve type. While this implements the same interface, we should verify that all callers are compatible with this change.


🏁 Script executed:

#!/bin/bash
# Description: Check usage of S256() function and verify type compatibility

# Find all calls to S256() 
rg "S256\(\)" --type go -B 2 -A 2

# Look for any type assertions or comparisons with S256()
ast-grep --pattern 'S256() == $$$'
ast-grep --pattern '$$$.(type) {
  $$$
  case $$$S256()$$$:
  $$$
}'

# Check for any direct field access on the curve
rg "S256\(\)\." --type go

Length of output: 11050


I’d like to confirm how EllipticCurve and btCurve are defined to ensure Marshal (and any other methods) remain available on the new wrapper.


🏁 Script executed:

#!/bin/bash
# Find EllipticCurve interface definition
rg "type EllipticCurve" -A5 -B5

# Find btCurve type definition
rg "type btCurve" -A5 -B5

Length of output: 630


To ensure our btCurve wrapper fully satisfies the required interface, let’s locate the EllipticCurve definition and its methods:


🏁 Script executed:

#!/bin/bash
# Find where EllipticCurve is defined
rg "type EllipticCurve interface" -A5 -B5

# List all references to EllipticCurve to catch any alias or import
rg "EllipticCurve" -n

Length of output: 522


API compatibility of the S256() wrapper confirmed

I’ve verified that:

  • No callers perform type assertions or comparisons against the concrete curve type.
  • The only direct method invocation (S256().Marshal(…)) still works, since btCurve implements both the embedded secp256k1.KoblitzCurve methods and any additional EllipticCurve methods (e.g. Marshal/Unmarshal).
  • The prv.Curve != S256() check continues to succeed because secp256k1.S256() always returns the same pointer, so two calls to btCurve{secp256k1.S256()} compare equal.

There are no remaining compatibility concerns—no fixes required.

Comment on lines +32 to +36
func Fuzz(f *testing.F) {
f.Fuzz(func(t *testing.T, a, b []byte) {
fuzz(a, b)
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Resolve naming conflicts with existing fuzz package.

The function names Fuzz and fuzz conflict with identifiers from the github.com/google/gofuzz package that appears to be imported elsewhere in this package. This is causing compilation failures.

Rename the functions to avoid conflicts:

-func Fuzz(f *testing.F) {
+func FuzzSecp256k1(f *testing.F) {
 	f.Fuzz(func(t *testing.T, a, b []byte) {
-		fuzz(a, b)
+		fuzzPointAddition(a, b)
 	})
 }

-func fuzz(dataP1, dataP2 []byte) {
+func fuzzPointAddition(dataP1, dataP2 []byte) {

Update the TestFuzzer call accordingly:

 func TestFuzzer(t *testing.T) {
 	a, b := "00000000N0000000/R0000000000000000", "0U0000S0000000mkhP000000000000000U"
-	fuzz([]byte(a), []byte(b))
+	fuzzPointAddition([]byte(a), []byte(b))
 }

Also applies to: 38-53

🧰 Tools
🪛 GitHub Check: check

[failure] 32-32:
Fuzz redeclared in this block

🪛 GitHub Actions: CI

[error] 32-32: Fuzz redeclared in this block

🤖 Prompt for AI Agents
In tests/fuzzers/secp256k1/secp_test.go around lines 32 to 53, the function
names Fuzz and fuzz conflict with identifiers from the imported
github.com/google/gofuzz package, causing compilation errors. Rename the outer
Fuzz function to a unique name like RunFuzz or SecpFuzz, and rename the inner
fuzz function to a distinct name such as runFuzz or fuzzTest. Update all calls
accordingly to use the new function names to avoid naming conflicts.

@Thegaram
Copy link

@yiweichi is this PR still active?

@yiweichi yiweichi closed this Jun 26, 2025
@yiweichi yiweichi reopened this Jun 26, 2025
@yiweichi
Copy link
Member Author

yiweichi commented Jun 26, 2025

@yiweichi is this PR still active?

Yes, we will need this PR for Arweave sender, cause the btcd conflicts with an Arweave dependency.
I can mark this as draft, and un-draft it when I resume the Arweave work.

@yiweichi yiweichi marked this pull request as draft June 26, 2025 12:44
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