-
Notifications
You must be signed in to change notification settings - Fork 3
crypto: add support for BIP-340 #32
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
Open
MichaelMure
wants to merge
1
commit into
master
Choose a base branch
from
bip340
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package bip340 | ||
|
|
||
| import ( | ||
| "github.com/decred/dcrd/dcrec/secp256k1/v4" | ||
| ) | ||
|
|
||
| const ( | ||
| // PublicKeyBytesSize is the size, in bytes, of public keys as x-only (BIP-340 format). | ||
| PublicKeyBytesSize = 32 | ||
| // PrivateKeyBytesSize is the size, in bytes, of private keys in raw bytes. | ||
| PrivateKeyBytesSize = secp256k1.PrivKeyBytesLen | ||
| // SignatureBytesSize is the size, in bytes, of BIP-340 signatures. | ||
| SignatureBytesSize = 64 | ||
|
|
||
| // code waiting for approval: https://github.com/multiformats/multicodec/pull/398 | ||
| MultibaseCode = uint64(0x1340) | ||
| ) | ||
|
|
||
| // GenerateKeyPair generates a new BIP-340 keypair. | ||
| // The private key is normalized so the public key always has an even Y coordinate, | ||
| // enabling lossless x-only serialization. | ||
| func GenerateKeyPair() (*PublicKey, *PrivateKey, error) { | ||
| priv, err := secp256k1.GeneratePrivateKey() | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| if priv.PubKey().Y().Bit(0) != 0 { | ||
| priv.Key.Negate() | ||
| } | ||
| return &PublicKey{k: priv.PubKey()}, &PrivateKey{k: priv}, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| package bip340 | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
|
|
||
| testsuite "github.com/MetaMask/go-did-it/crypto/_testsuite" | ||
| "github.com/MetaMask/go-did-it/crypto/bip340/testvectors" | ||
| ) | ||
|
|
||
| var harness = testsuite.TestHarness[*PublicKey, *PrivateKey]{ | ||
| Name: "secp256k1-bip340", | ||
| GenerateKeyPair: GenerateKeyPair, | ||
| PublicKeyFromBytes: PublicKeyFromBytes, | ||
| PublicKeyFromPublicKeyMultibase: PublicKeyFromPublicKeyMultibase, | ||
| PrivateKeyFromBytes: PrivateKeyFromBytes, | ||
| MultibaseCode: MultibaseCode, | ||
| DefaultHash: 0, // BIP-340 passes messages raw to its internal tagged hashes; no pre-hashing. | ||
| PublicKeyBytesSize: PublicKeyBytesSize, | ||
| PrivateKeyBytesSize: PrivateKeyBytesSize, | ||
| SignatureBytesSize: SignatureBytesSize, | ||
| } | ||
|
|
||
| func TestSuite(t *testing.T) { | ||
| testsuite.TestSuite(t, harness) | ||
| } | ||
|
|
||
| func BenchmarkSuite(b *testing.B) { | ||
| testsuite.BenchSuite(b, harness) | ||
| } | ||
|
|
||
| func TestBIP340Vectors(t *testing.T) { | ||
| vectors, err := testvectors.Load() | ||
| require.NoError(t, err) | ||
|
|
||
| for _, v := range vectors { | ||
| t.Run(vectorName(v), func(t *testing.T) { | ||
| // Verification via public API. | ||
| pub, err := PublicKeyFromBytes(v.PublicKey) | ||
| if err != nil { | ||
| require.False(t, v.Valid, "unexpected parse error: %v", err) | ||
| return | ||
| } | ||
|
|
||
| got := pub.VerifyBytes(v.Message, v.Signature) | ||
| require.Equal(t, v.Valid, got, "verification mismatch") | ||
|
|
||
| // Signing (only when secret key and aux_rand are provided). | ||
| if v.SecretKey == nil { | ||
| return | ||
| } | ||
|
|
||
| priv, err := PrivateKeyFromBytes(v.SecretKey) | ||
| require.NoError(t, err, "failed to parse private key") | ||
|
|
||
| // Inject the known aux_rand for deterministic comparison against the vector. | ||
| gotSig, err := bip340Sign(&priv.k.Key, priv.k.PubKey(), v.Message, v.AuxRand) | ||
| require.NoError(t, err, "signing failed") | ||
| require.Equal(t, v.Signature, gotSig, "signature mismatch") | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func vectorName(v testvectors.Vector) string { | ||
| if v.Comment != "" { | ||
| return fmt.Sprintf("%d-%s", v.Index, v.Comment) | ||
| } | ||
| return fmt.Sprintf("%d", v.Index) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| package bip340 | ||
|
|
||
| import ( | ||
| "crypto/rand" | ||
| "crypto/sha256" | ||
| "fmt" | ||
|
|
||
| "github.com/decred/dcrd/dcrec/secp256k1/v4" | ||
|
|
||
| "github.com/MetaMask/go-did-it/crypto" | ||
| ) | ||
|
|
||
| var _ crypto.PrivateKeySigningBytes = &PrivateKey{} | ||
| var _ crypto.PrivateKeyToBytes = &PrivateKey{} | ||
|
|
||
| type PrivateKey struct { | ||
| k *secp256k1.PrivateKey | ||
| } | ||
|
|
||
| // PrivateKeyFromBytes parses a 32-byte private key and normalizes it so the | ||
| // corresponding public key has an even Y coordinate. | ||
| func PrivateKeyFromBytes(b []byte) (*PrivateKey, error) { | ||
| if len(b) != PrivateKeyBytesSize { | ||
| return nil, fmt.Errorf("bip340: invalid private key size: expected %d bytes, got %d", PrivateKeyBytesSize, len(b)) | ||
| } | ||
| priv := secp256k1.PrivKeyFromBytes(b) | ||
| if priv.PubKey().Y().Bit(0) != 0 { | ||
| priv.Key.Negate() | ||
| } | ||
| return &PrivateKey{k: priv}, nil | ||
| } | ||
|
|
||
| func (p *PrivateKey) Equal(other crypto.PrivateKey) bool { | ||
| if other, ok := other.(*PrivateKey); ok { | ||
| return p.k.PubKey().IsEqual(other.k.PubKey()) | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func (p *PrivateKey) Public() crypto.PublicKey { | ||
| return &PublicKey{k: p.k.PubKey()} | ||
| } | ||
|
|
||
| func (p *PrivateKey) ToBytes() []byte { | ||
| return p.k.Serialize() | ||
| } | ||
|
|
||
| // SignToBytes signs the message using BIP-340 Schnorr and returns a 64-byte signature. | ||
| // Signing options are not supported as BIP-340 uses a fixed internal hash function. | ||
| func (p *PrivateKey) SignToBytes(message []byte, opts ...crypto.SigningOption) ([]byte, error) { | ||
| if len(opts) != 0 { | ||
| return nil, fmt.Errorf("bip340: SignToBytes does not support any options") | ||
| } | ||
| var auxRand [32]byte | ||
| if _, err := rand.Read(auxRand[:]); err != nil { | ||
| return nil, fmt.Errorf("bip340: failed to generate auxiliary randomness: %w", err) | ||
| } | ||
|
|
||
| return bip340Sign(&p.k.Key, p.k.PubKey(), message, auxRand) | ||
| } | ||
|
|
||
| // Unwrap returns the underlying secp256k1 private key. | ||
| func (p *PrivateKey) Unwrap() *secp256k1.PrivateKey { | ||
| return p.k | ||
| } | ||
|
|
||
| // bip340Sign implements BIP-340 signing. | ||
| // Spec: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#default-signing | ||
| // Reference: https://github.com/btcsuite/btcd/blob/3a0df88/btcec/schnorr/signature.go#L393 | ||
| // | ||
| // Preconditions: pubKey has even Y (enforced at key import/generation in this package), | ||
| // meaning d is already the normalized secret scalar — step 5 (negate if odd Y) is a no-op. | ||
| func bip340Sign(d *secp256k1.ModNScalar, pubKey *secp256k1.PublicKey, msg []byte, auxRand [32]byte) ([]byte, error) { | ||
| // Step 1: let d' = int(d) | ||
| // Step 2-3: validity checks (d != 0, d < n) guaranteed by secp256k1.PrivKeyFromBytes. | ||
| // Step 4: let P = d'*G — pubKey is already computed and stored. | ||
| // Step 5: negate d if has_odd_y(P) — no-op: caller guarantees even Y. | ||
| var pubKeyBytes [32]byte | ||
| pubKey.X().FillBytes(pubKeyBytes[:]) | ||
|
|
||
| // Serialize d to bytes; zero after use. | ||
| var privBytes [32]byte | ||
| d.PutBytes(&privBytes) | ||
| defer func() { | ||
| for i := range privBytes { | ||
| privBytes[i] = 0 | ||
| } | ||
| }() | ||
|
|
||
| // Step 6: let t = bytes(d) XOR tagged_hash("BIP0340/aux", a) | ||
| auxHash := taggedHash("BIP0340/aux", auxRand[:]) | ||
| var t [32]byte | ||
| for i := range t { | ||
| t[i] = privBytes[i] ^ auxHash[i] | ||
| } | ||
| defer func() { | ||
| for i := range t { | ||
| t[i] = 0 | ||
| } | ||
| }() | ||
|
|
||
| // Step 7: let rand = tagged_hash("BIP0340/nonce", t || bytes(P) || m) | ||
| // Step 8: let k' = int(rand) mod n | ||
| nonceHash := taggedHash("BIP0340/nonce", t[:], pubKeyBytes[:], msg) | ||
| defer func() { | ||
| for i := range nonceHash { | ||
| nonceHash[i] = 0 | ||
| } | ||
| }() | ||
| var k secp256k1.ModNScalar | ||
| var nonceArr [32]byte | ||
| copy(nonceArr[:], nonceHash) | ||
| k.SetBytes(&nonceArr) | ||
|
|
||
| // Step 9: fail if k' = 0 | ||
| if k.IsZero() { | ||
| return nil, fmt.Errorf("bip340: generated nonce is zero") | ||
| } | ||
|
|
||
| // Step 10: let R = k'*G | ||
| var R secp256k1.JacobianPoint | ||
| secp256k1.ScalarBaseMultNonConst(&k, &R) | ||
| R.ToAffine() | ||
|
|
||
| // Step 11: let k = k' if has_even_y(R), otherwise k = n - k' | ||
| if R.Y.IsOdd() { | ||
| k.Negate() | ||
| } | ||
|
|
||
| // Step 12: let e = int(tagged_hash("BIP0340/challenge", bytes(R) || bytes(P) || m)) mod n | ||
| var rBytes [32]byte | ||
| R.X.PutBytes(&rBytes) | ||
| commitment := taggedHash("BIP0340/challenge", rBytes[:], pubKeyBytes[:], msg) | ||
| var e secp256k1.ModNScalar | ||
| var commitmentArr [32]byte | ||
| copy(commitmentArr[:], commitment) | ||
| e.SetBytes(&commitmentArr) | ||
|
|
||
| // Step 13: let sig = bytes(R.x) || bytes((k + e*d) mod n) | ||
| s := new(secp256k1.ModNScalar).Mul2(&e, d).Add(&k) | ||
| k.Zero() | ||
| var sig [SignatureBytesSize]byte | ||
| R.X.PutBytes((*[32]byte)(sig[:32])) | ||
| s.PutBytes((*[32]byte)(sig[32:])) | ||
|
|
||
| // Step 14: if Verify(bytes(P), m, sig) fails, abort. | ||
| // Required by the spec as a fault-attack guard. | ||
| var rField secp256k1.FieldVal | ||
| rField.SetByteSlice(sig[:32]) | ||
| rField.Normalize() | ||
| var sScalar secp256k1.ModNScalar | ||
| sScalar.SetByteSlice(sig[32:]) | ||
| if !bip340Verify(&rField, &sScalar, pubKey, msg) { | ||
| return nil, fmt.Errorf("bip340: produced signature failed verification") | ||
| } | ||
|
|
||
| return sig[:], nil | ||
| } | ||
|
|
||
| // taggedHash computes the BIP-340 tagged hash: | ||
| // SHA256(SHA256(tag) || SHA256(tag) || data...) | ||
| func taggedHash(tag string, data ...[]byte) []byte { | ||
| tagHash := sha256.Sum256([]byte(tag)) | ||
| h := sha256.New() | ||
| h.Write(tagHash[:]) | ||
| h.Write(tagHash[:]) | ||
| for _, d := range data { | ||
| h.Write(d) | ||
| } | ||
| return h.Sum(nil) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.