-
Notifications
You must be signed in to change notification settings - Fork 106
/
signature.go
69 lines (56 loc) · 1.69 KB
/
signature.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//go:build !libsecp256k1
package nostr
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
)
// CheckSignature checks if the signature is valid for the id
// (which is a hash of the serialized event content).
// returns an error if the signature itself is invalid.
func (evt Event) CheckSignature() (bool, error) {
// read and check pubkey
pk, err := hex.DecodeString(evt.PubKey)
if err != nil {
return false, fmt.Errorf("event pubkey '%s' is invalid hex: %w", evt.PubKey, err)
}
pubkey, err := schnorr.ParsePubKey(pk)
if err != nil {
return false, fmt.Errorf("event has invalid pubkey '%s': %w", evt.PubKey, err)
}
// read signature
s, err := hex.DecodeString(evt.Sig)
if err != nil {
return false, fmt.Errorf("signature '%s' is invalid hex: %w", evt.Sig, err)
}
sig, err := schnorr.ParseSignature(s)
if err != nil {
return false, fmt.Errorf("failed to parse signature: %w", err)
}
// check signature
hash := sha256.Sum256(evt.Serialize())
return sig.Verify(hash[:], pubkey), nil
}
// Sign signs an event with a given privateKey.
func (evt *Event) Sign(secretKey string) error {
s, err := hex.DecodeString(secretKey)
if err != nil {
return fmt.Errorf("Sign called with invalid secret key '%s': %w", secretKey, err)
}
if evt.Tags == nil {
evt.Tags = make(Tags, 0)
}
sk, pk := btcec.PrivKeyFromBytes(s)
pkBytes := pk.SerializeCompressed()
evt.PubKey = hex.EncodeToString(pkBytes[1:])
h := sha256.Sum256(evt.Serialize())
sig, err := schnorr.Sign(sk, h[:], schnorr.FastSign())
if err != nil {
return err
}
evt.ID = hex.EncodeToString(h[:])
evt.Sig = hex.EncodeToString(sig.Serialize())
return nil
}