Skip to content

utils/MuSig2Sign: validate signer inputs and accept raw keys#1110

Draft
starius wants to merge 2 commits intolightninglabs:masterfrom
starius:musig2sign-refactor
Draft

utils/MuSig2Sign: validate signer inputs and accept raw keys#1110
starius wants to merge 2 commits intolightninglabs:masterfrom
starius:musig2sign-refactor

Conversation

@starius
Copy link
Copy Markdown
Collaborator

@starius starius commented Apr 5, 2026

This fixes some issues discovered in #1109 and before that by Gemini AI in #1108

  • make sure there are at least 2 keys (lnd/input already rejects fewer than two signer pubkeys)
  • accepts keys as raw keys to make it more convenient
  • make it compatible with MuSig2 v0.4 which accepts x-only pubkeys
  • fix a typo in an error message

Pull Request Checklist

  • Update release_notes.md if your PR contains major features, breaking changes or bugfixes

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the MuSig2 signing utility to improve robustness and developer experience. By enforcing stricter input validation and simplifying the key handling interface, it ensures safer and more flexible interactions with the MuSig2 signing flow, while also addressing compatibility requirements for different protocol versions.

Highlights

  • Input Validation: Added a check to ensure at least two signing keys are provided to the MuSig2Sign function.
  • API Improvement: Updated MuSig2Sign to accept raw 32-byte keys instead of private key objects for better convenience.
  • Compatibility: Added support for MuSig2 v0.4 by handling x-only public key parsing.
  • Bug Fix: Corrected a typo in an error message within the MuSig2 signing logic.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the MuSig2Sign utility to accept raw private keys, implements x-only public key support for MuSig2 v0.4, fixes a typo, and adds unit tests. Feedback identifies a critical logic error where private keys must be negated for x-only public keys with odd Y coordinates in v0.4. Additionally, the reviewer suggested failing fast by moving input validation to the start of the function and improving test coverage by verifying signatures against aggregate public keys.

Comment on lines +26 to +35
if version == input.MuSig2Version040 {
pubKey := pubKeys[i].SerializeCompressed()
xOnlyPubKey, err := schnorr.ParsePubKey(pubKey[1:])
if err != nil {
return nil, fmt.Errorf("error parsing x-only "+
"pubkey: %v", err)
}

pubKeys[i] = xOnlyPubKey
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-critical critical

When using MuSig2 v0.4 with x-only public keys, if the original public key has an odd Y coordinate, the corresponding private key must be negated to match the x-only public key (which is assumed to have an even Y coordinate). Failing to do so will result in an invalid signature because the signer will be using a private key that does not correspond to the public key used in the MuSig2 aggregation. You should check the parity of the public key and negate the private key if necessary.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I don't think we need to add an extra private-key negation in our wrapper for review item 1.

For MuSig2Version040, our helper calls input.MuSig2CreateContext, which passes the private key into the v0.4 implementation.

Inside that implementation, musig2v040.NewContext already normalizes the local signer public key to x-only by calling schnorr.ParsePubKey(schnorr.SerializePubKey(signingKey.PubKey())).

Then, during signing, musig2v040.Sign checks whether the original local public key has odd Y, sets paritySignKey.Negate() when needed, and multiplies the private scalar by that parity factor before producing the partial signature.

So the odd-Y to x-only adjustment is already handled by lnd/input for the v0.4 path. Adding another manual negation in our helper would duplicate that logic and risks over-correcting the signer key.

I added a test case to make sure that odd Y keys work.

Comment on lines +17 to +18
privKeys := make([]*btcec.PrivateKey, len(keys))
pubKeys := make([]*btcec.PublicKey, len(keys))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

It is more efficient to validate the input length before performing any cryptographic operations or memory allocations. Moving the check for at least two signing keys to the beginning of the function will allow it to fail fast.

	if len(keys) < 2 {
		return nil, fmt.Errorf("need at least two signing keys")
	}

	privKeys := make([]*btcec.PrivateKey, len(keys))
	pubKeys := make([]*btcec.PublicKey, len(keys))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I put the check after the translation to reduce the diff size. In the real use case the check never fires, so this has no performance impact.

Comment on lines +46 to +51
sig, err := MuSig2Sign(
version, rawKeys(1, 2), &input.MuSig2Tweaks{},
[32]byte{},
)
require.NoError(t, err)
require.Len(t, sig, 64)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The test currently only checks that a 64-byte signature is returned without error. It should also verify that the generated signature is valid against the aggregate public key to ensure the MuSig2 flow is correctly implemented, especially for different versions and key parities.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added signature verification to the test.

@starius starius force-pushed the musig2sign-refactor branch from de6e154 to d0b88fd Compare April 5, 2026 21:54
@starius
Copy link
Copy Markdown
Collaborator Author

starius commented Apr 5, 2026

@gemini-code-assist review

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the MuSig2Sign utility to accept raw private keys, centralizing public key derivation and x-only conversion logic for MuSig2 v0.4. It also fixes a typo in an error message and adds a new test suite for version compatibility. A review comment suggests moving the input validation for the number of keys to the beginning of the function to avoid unnecessary allocations.

Comment on lines +17 to +40
privKeys := make([]*btcec.PrivateKey, len(keys))
pubKeys := make([]*btcec.PublicKey, len(keys))

// First parse the raw private keys and also create the corresponding
// public keys.
for i, key := range keys {
privKeys[i], pubKeys[i] = btcec.PrivKeyFromBytes(key[:])

// MuSig2 v0.4 expects x-only public keys.
if version == input.MuSig2Version040 {
pubKey := pubKeys[i].SerializeCompressed()
xOnlyPubKey, err := schnorr.ParsePubKey(pubKey[1:])
if err != nil {
return nil, fmt.Errorf("error parsing x-only "+
"pubkey: %v", err)
}

pubKeys[i] = xOnlyPubKey
}
}

if len(privKeys) < 2 {
return nil, fmt.Errorf("need at least two signing keys")
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The check for the minimum number of signing keys should be performed at the beginning of the function. This avoids unnecessary allocations and processing (such as parsing keys and performing x-only conversions) when the input is invalid.

	if len(keys) < 2 {
		return nil, fmt.Errorf("need at least two signing keys")
	}

	privKeys := make([]*btcec.PrivateKey, len(keys))
	pubKeys := make([]*btcec.PublicKey, len(keys))

	// First parse the raw private keys and also create the corresponding
	// public keys.
	for i, key := range keys {
		privKeys[i], pubKeys[i] = btcec.PrivKeyFromBytes(key[:])

		// MuSig2 v0.4 expects x-only public keys.
		if version == input.MuSig2Version040 {
			pubKey := pubKeys[i].SerializeCompressed()
			xOnlyPubKey, err := schnorr.ParsePubKey(pubKey[1:])
			if err != nil {
				return nil, fmt.Errorf("error parsing x-only "+
					"pubkey: %v", err)
			}

			pubKeys[i] = xOnlyPubKey
		}
	}

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