schnorr

package
v0.2.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2026 License: ISC Imports: 4 Imported by: 0

Documentation

Overview

Package schnorr provides Schnorr signing and verification via secp256k1.

This package provides data structures and functions necessary to produce and verify deterministic canonical Schnorr signatures. The signatures and implementation are optimized specifically for the secp256k1 curve. See https://www.secg.org/sec2-v2.pdf for details on the secp256k1 standard.

It also provides functions to parse and serialize the Schnorr signatures according to the specification described in the project README.

Overview

A Schnorr signature is a digital signature scheme that is known for its simplicity, provable security and efficient generation of short signatures.

It provides many advantages over ECDSA signatures that make them ideal for use with the only real downside being that they are not well standardized at the time of this writing.

Some of the advantages over ECDSA include:

  • They are linear which makes them easier to aggregate and use in protocols that build on them such as multi-party signatures, threshold signatures, adaptor signatures, and blind signatures
  • They are provably secure with weaker assumptions than the best known security proofs for ECDSA. Specifically they are provably secure under SUF-CMA in the ROM which guarantees that as long as the hash function behaves ideally, the only way to break Schnorr signatures is by solving the ECDLP.
  • Their relatively straightforward and efficient aggregation properties make them excellent for scalability and allow them to provide some nice privacy characteristics
  • They support faster batch verification unlike the standardized version of ECDSA signatures

Signature Scheme

The scheme has the following key design features:

  • Uses signatures of the form (R, s)
  • Produces 64-byte signatures by only encoding the x coordinate of R
  • Enforces even y coordinates for R to support efficient verification by disambiguating the two possible y coordinates
  • Canonically encodes both components of the signature with 32-bytes each
  • Uses BLAKE-256 with 14 rounds for the hash function to calculate challenge e
  • Uses RFC6979 to obviate the need for an entropy source at signing time
  • Produces deterministic signatures for a given message and private key pair

See the project README for the full signing and verification algorithms.

Index

Examples

Constants

View Source
const (
	// ErrInvalidHashLen indicates that the input hash to sign or verify is not
	// the required length.
	ErrInvalidHashLen = ErrorKind("ErrInvalidHashLen")

	// ErrPrivateKeyIsZero indicates an attempt was made to sign a message with
	// a private key that is equal to zero.
	ErrPrivateKeyIsZero = ErrorKind("ErrPrivateKeyIsZero")

	// ErrSchnorrHashValue indicates that the hash of (R || m) was too large and
	// so a new nonce should be used.
	ErrSchnorrHashValue = ErrorKind("ErrSchnorrHashValue")

	// ErrPubKeyNotOnCurve indicates that a point was not on the given elliptic
	// curve.
	ErrPubKeyNotOnCurve = ErrorKind("ErrPubKeyNotOnCurve")

	// ErrSigRYIsOdd indicates that the calculated Y value of R was odd.
	ErrSigRYIsOdd = ErrorKind("ErrSigRYIsOdd")

	// ErrSigRNotOnCurve indicates that the calculated or given point R for some
	// signature was not on the curve.
	ErrSigRNotOnCurve = ErrorKind("ErrSigRNotOnCurve")

	// ErrUnequalRValues indicates that the calculated point R for some
	// signature was not the same as the given R value for the signature.
	ErrUnequalRValues = ErrorKind("ErrUnequalRValues")

	// ErrSigTooShort is returned when a signature that should be a Schnorr
	// signature is too short.
	ErrSigTooShort = ErrorKind("ErrSigTooShort")

	// ErrSigTooLong is returned when a signature that should be a Schnorr
	// signature is too long.
	ErrSigTooLong = ErrorKind("ErrSigTooLong")

	// ErrSigRTooBig is returned when a signature has r with a value that is
	// greater than or equal to the prime of the field underlying the group.
	ErrSigRTooBig = ErrorKind("ErrSigRTooBig")

	// ErrSigSTooBig is returned when a signature has s with a value that is
	// greater than or equal to the group order.
	ErrSigSTooBig = ErrorKind("ErrSigSTooBig")
)

These constants are used to identify a specific RuleError.

View Source
const (
	PubKeyBytesLen = 33
)

These constants define the lengths of serialized public keys.

View Source
const (
	// SignatureSize is the size of an encoded Schnorr signature.
	SignatureSize = 64
)

Variables

This section is empty.

Functions

func ParsePubKey

func ParsePubKey(pubKeyStr []byte) (key *secp256k1.PublicKey, err error)

ParsePubKey parses a public key for a koblitz curve from a bytestring into a ecdsa.Publickey, verifying that it is valid. It supports compressed signature formats only.

Types

type Error

type Error struct {
	Err         error
	Description string
}

Error identifies an error related to a schnorr signature. It has full support for errors.Is and errors.As, so the caller can ascertain the specific reason for the error by checking the underlying error.

func (Error) Error

func (e Error) Error() string

Error satisfies the error interface and prints human-readable errors.

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap returns the underlying wrapped error.

type ErrorKind

type ErrorKind string

ErrorKind identifies a kind of error. It has full support for errors.Is and errors.As, so the caller can directly check against an error kind when determining the reason for an error.

func (ErrorKind) Error

func (e ErrorKind) Error() string

Error satisfies the error interface and prints human-readable errors.

type Signature

type Signature struct {
	// contains filtered or unexported fields
}

Signature is a type representing a Schnorr signature.

func NewSignature

func NewSignature(r *secp256k1.FieldVal, s *secp256k1.ModNScalar) *Signature

NewSignature instantiates a new signature given some r and s values.

func ParseSignature

func ParseSignature(sig []byte) (*Signature, error)

ParseSignature parses a signature and enforces the following additional restrictions specific to secp256k1:

- The r component must be in the valid range for secp256k1 field elements - The s component must be in the valid range for secp256k1 scalars

func Sign

func Sign(privKey *secp256k1.PrivateKey, hash []byte, scheme string) (*Signature, error)

Sign generates a Schnorr signature over the secp256k1 curve for the provided hash (which should be the result of hashing a larger message) using the given private key. The produced signature is deterministic (same message and same key yield the same signature) and canonical.

The scheme parameter is a string that identifies the signing scheme and is used for RFC6979 domain separation. It is hashed through BLAKE-256 and fed as extra data to the nonce generation, ensuring that different schemes using the same key and message produce different nonces. The hash is cached so repeated calls with the same scheme are efficient.

Note that the current signing implementation has a few remaining variable time aspects which make use of the private key and the generated nonce, which can expose the signer to constant time attacks. As a result, this function should not be used in situations where there is the possibility of someone having EM field/cache/etc access.

Example

This example demonstrates signing a message with a Schnorr signature using a secp256k1 private key that is first parsed from raw bytes and serializing the generated signature.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/KarpelesLab/blake256"
	"github.com/KarpelesLab/secp256k1"
	"github.com/KarpelesLab/secp256k1/schnorr"
)

func main() {
	// Decode a hex-encoded private key.
	pkBytes, err := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2d4f8720ee6" +
		"3e502ee2869afab7de234b80c")
	if err != nil {
		fmt.Println(err)
		return
	}
	privKey := secp256k1.PrivKeyFromBytes(pkBytes)

	// Sign a message using the private key.
	message := "test message"
	messageHash := blake256.Sum256([]byte(message))
	signature, err := schnorr.Sign(privKey, messageHash[:], "EC-Schnorr-DCRv0")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Serialize and display the signature.
	fmt.Printf("Serialized Signature: %x\n", signature.Serialize())

	// Verify the signature for the message using the public key.
	pubKey := privKey.PubKey()
	verified := signature.Verify(messageHash[:], pubKey)
	fmt.Printf("Signature Verified? %v\n", verified)

}
Output:
Serialized Signature: 970603d8ccd2475b1ff66cfb3ce7e622c5938348304c5a7bc2e6015fb98e3b457d4e912fcca6ca87c04390aa5e6e0e613bbbba7ffd6f15bc59f95bbd92ba50f0
Signature Verified? true

func (Signature) IsEqual

func (sig Signature) IsEqual(otherSig *Signature) bool

IsEqual compares this Signature instance to the one passed, returning true if both Signatures are equivalent. A signature is equivalent to another, if they both have the same scalar value for R and S.

func (Signature) Serialize

func (sig Signature) Serialize() []byte

Serialize returns the Schnorr signature in the more strict format.

The signatures are encoded as:

sig[0:32]  x coordinate of the point R, encoded as a big-endian uint256
sig[32:64] s, encoded also as big-endian uint256

func (*Signature) Verify

func (sig *Signature) Verify(hash []byte, pubKey *secp256k1.PublicKey) bool

Verify returns whether or not the signature is valid for the provided hash and secp256k1 public key.

Example

This example demonstrates verifying a Schnorr signature against a public key that is first parsed from raw bytes. The signature is also parsed from raw bytes.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/KarpelesLab/blake256"
	"github.com/KarpelesLab/secp256k1/schnorr"
)

func main() {
	// Decode hex-encoded serialized public key.
	pubKeyBytes, err := hex.DecodeString("02a673638cb9587cb68ea08dbef685c6f2d" +
		"2a751a8b3c6f2a7e9a4999e6e4bfaf5")
	if err != nil {
		fmt.Println(err)
		return
	}
	pubKey, err := schnorr.ParsePubKey(pubKeyBytes)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Decode hex-encoded serialized signature.
	sigBytes, err := hex.DecodeString("970603d8ccd2475b1ff66cfb3ce7e622c59383" +
		"48304c5a7bc2e6015fb98e3b457d4e912fcca6ca87c04390aa5e6e0e613bbbba7ffd" +
		"6f15bc59f95bbd92ba50f0")
	if err != nil {
		fmt.Println(err)
		return
	}
	signature, err := schnorr.ParseSignature(sigBytes)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Verify the signature for the message using the public key.
	message := "test message"
	messageHash := blake256.Sum256([]byte(message))
	verified := signature.Verify(messageHash[:], pubKey)
	fmt.Println("Signature Verified?", verified)

}
Output:
Signature Verified? true

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL