github.com/Evanesco-Labs/go-evanesco@v1.0.1/zkpminer/keypair/keypair.go (about) 1 package keypair 2 3 import ( 4 "crypto/ecdsa" 5 "crypto/rand" 6 "errors" 7 "github.com/Evanesco-Labs/go-evanesco/common" 8 "github.com/Evanesco-Labs/go-evanesco/crypto" 9 ) 10 11 var ( 12 S256 = crypto.S256() 13 Curve = S256 14 Params = Curve.Params() 15 ) 16 17 var ( 18 ErrPointNotOnCurve = errors.New("point is not on the curve") 19 ErrPointNotCurveParam = errors.New("point param not same as curve") 20 ) 21 22 type Key struct { 23 Address common.Address 24 PrivateKey PrivateKey 25 } 26 27 type PublicKey struct { 28 *ecdsa.PublicKey 29 } 30 31 type PrivateKey struct { 32 *ecdsa.PrivateKey 33 } 34 35 func (k *PrivateKey) Public() *PublicKey { 36 return &PublicKey{&k.PublicKey} 37 } 38 39 func GenerateKeyPair() (*PublicKey, *PrivateKey) { 40 sk, err := ecdsa.GenerateKey(Curve, rand.Reader) 41 if err != nil { 42 return nil, nil 43 } 44 return &PublicKey{&sk.PublicKey}, &PrivateKey{sk} 45 } 46 47 func NewPublicKey(pk *ecdsa.PublicKey) (*PublicKey, error) { 48 if *pk.Params() != *Params { 49 return nil, ErrPointNotCurveParam 50 } 51 if !Curve.IsOnCurve(pk.X, pk.Y) { 52 return nil, ErrPointNotOnCurve 53 } 54 return &PublicKey{pk}, nil 55 } 56 57 func NewPrivateKey(sk *ecdsa.PrivateKey) (*PrivateKey, error) { 58 if *sk.Params() != *Params { 59 return nil, ErrPointNotCurveParam 60 } 61 if !Curve.IsOnCurve(sk.X, sk.Y) { 62 return nil, ErrPointNotOnCurve 63 } 64 return &PrivateKey{sk}, nil 65 } 66 67 func NewKey(sk *ecdsa.PrivateKey) (Key, error) { 68 privKey, err := NewPrivateKey(sk) 69 if err != nil { 70 return Key{}, err 71 } 72 return Key{ 73 Address: crypto.PubkeyToAddress(sk.PublicKey), 74 PrivateKey: *privKey, 75 }, nil 76 }