decred.org/dcrdex@v1.0.5/server/asset/dcr/script.go (about) 1 // This code is available on the terms of the project LICENSE.md file, 2 // also available online at https://blueoakcouncil.org/license/1.0.0. 3 4 package dcr 5 6 import ( 7 "fmt" 8 9 "github.com/decred/dcrd/chaincfg/chainhash" 10 "github.com/decred/dcrd/dcrec" 11 "github.com/decred/dcrd/dcrec/edwards/v2" 12 "github.com/decred/dcrd/dcrec/secp256k1/v4" 13 "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa" 14 "github.com/decred/dcrd/dcrec/secp256k1/v4/schnorr" 15 ) 16 17 // checkSig checks the signature against the pubkey and message. 18 func checkSig(msg, pkBytes, sigBytes []byte, sigType dcrec.SignatureType) error { 19 switch sigType { 20 case dcrec.STEcdsaSecp256k1: 21 return checkSigS256(msg, pkBytes, sigBytes) 22 case dcrec.STEd25519: 23 return checkSigEdwards(msg, pkBytes, sigBytes) 24 case dcrec.STSchnorrSecp256k1: 25 return checkSigSchnorr(msg, pkBytes, sigBytes) 26 } 27 return fmt.Errorf("unsupported signature type") 28 } 29 30 // checkSigS256 checks that the message's signature was created with the 31 // private key for the provided secp256k1 public key. 32 func checkSigS256(msg, pkBytes, sigBytes []byte) error { 33 pubKey, err := secp256k1.ParsePubKey(pkBytes) 34 if err != nil { 35 return fmt.Errorf("error decoding secp256k1 PublicKey from bytes: %w", err) 36 } 37 signature, err := ecdsa.ParseDERSignature(sigBytes) 38 if err != nil { 39 return fmt.Errorf("error decoding secp256k1 Signature from bytes: %w", err) 40 } 41 hash := chainhash.HashB(msg) 42 if !signature.Verify(hash, pubKey) { 43 return fmt.Errorf("secp256k1 signature verification failed") 44 } 45 return nil 46 } 47 48 // checkSigEdwards checks that the message's signature was created with the 49 // private key for the provided edwards public key. 50 func checkSigEdwards(msg, pkBytes, sigBytes []byte) error { 51 pubKey, err := edwards.ParsePubKey(pkBytes) 52 if err != nil { 53 return fmt.Errorf("error decoding edwards PublicKey from bytes: %w", err) 54 } 55 signature, err := edwards.ParseSignature(sigBytes) 56 if err != nil { 57 return fmt.Errorf("error decoding edwards Signature from bytes: %w", err) 58 } 59 hash := chainhash.HashB(msg) 60 if !signature.Verify(hash, pubKey) { 61 return fmt.Errorf("edwards signature verification failed") 62 } 63 return nil 64 } 65 66 // checkSigSchnorr checks that the message's signature was created with the 67 // private key for the provided schnorr public key. 68 func checkSigSchnorr(msg, pkBytes, sigBytes []byte) error { 69 pubKey, err := schnorr.ParsePubKey(pkBytes) 70 if err != nil { 71 return fmt.Errorf("error decoding schnorr PublicKey from bytes: %w", err) 72 } 73 signature, err := schnorr.ParseSignature(sigBytes) 74 if err != nil { 75 return fmt.Errorf("error decoding schnorr Signature from bytes: %w", err) 76 } 77 hash := chainhash.HashB(msg) 78 if !signature.Verify(hash, pubKey) { 79 return fmt.Errorf("schnorr signature verification failed") 80 } 81 return nil 82 }