Skip to content

secp256k1 ECDSA grind signing panics for out-of-range bytes_to_grind #905

Description

@xc01

secp256k1's public ECDSA grind-signing API accepts bytes_to_grind: usize, but values greater than 71 can panic in debug/test builds due to unchecked subtraction.

I checked the nearby docs around sign_grind_r. They describe the expression 71 - bytes_to_grind, but I did not find a # Panics note or an explicit valid range for bytes_to_grind.

Version checked: secp256k1 0.32.0-beta.2

Relevant code

/// Constructs a signature for `msg` using the secret key `sk`, RFC6979 nonce
/// and "grinds" the nonce by passing extra entropy if necessary to produce
/// a signature that is less than 71 - `bytes_to_grind` bytes. The number
/// of signing operation performed by this function is exponential in the
/// number of bytes grinded.
/// Requires a signing capable context.
pub fn sign_grind_r(msg: impl Into<Message>, sk: &SecretKey, bytes_to_grind: usize) -> Signature {
    let len_check = |s: &ffi::Signature| der_length_check(s, 71 - bytes_to_grind);
    sign_grind_with_check(msg, sk, len_check)
}

Reproducer

use secp256k1::{Message, Secp256k1, SecretKey};

#[test]
#[should_panic]
fn sign_grind_r_bytes_to_grind_overflow() {
    let secp = Secp256k1::new();
    let msg = Message::from_digest([1u8; 32]);
    let sk = SecretKey::from_secret_bytes([2u8; 32]).expect("valid secret key");

    let _ = secp.sign_ecdsa_grind_r(msg, &sk, 72);
}

Observed behavior:

thread '...' panicked at src/ecdsa/mod.rs:332:62:
attempt to subtract with overflow

Impact

This is a small robustness issue in a public signing path. A caller that passes an out-of-range grind parameter gets a panic instead of a documented contract failure or a controlled error. In panic-abort deployments, this can terminate a signing workflow.

Expected behavior

Any of these would make the behavior clearer:

  • Document bytes_to_grind <= 71 in a # Panics section.
  • Explicitly assert/check the range with a clearer panic message.
  • Add a fallible API variant if invalid grind parameters should be handled without panicking.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions