Skip to content
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

feat: Add error handling for cryptographic operations #349

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions ethereum/ethereum.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import (
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"errors"
"fmt"
)

var (
ErrInvalidPrivateKey = errors.New("недопустимый закрытый ключ")
ErrInvalidPublicKey = errors.New("недопустимый открытый ключ")
ErrInvalidSignature = errors.New("недопустимая подпись")
ErrInvalidAddress = errors.New("недопустимый адрес Ethereum")
)

func PublicKeyToAddress(publicKey []byte) common.Address {
Expand All @@ -19,3 +28,52 @@ func PublicKeyToAddress(publicKey []byte) common.Address {
func AddressFromPrivateKey(privKey *secp256k1.PrivateKey) common.Address {
return PublicKeyToAddress(privKey.PubKey().SerializeUncompressed())
}

func GenerateKey() (*ecdsa.PrivateKey, error) {
privateKey, err := crypto.GenerateKey()
if err != nil {
return nil, fmt.Errorf("не удалось сгенерировать ключ: %w", err)
}

return privateKey, nil
}

func PublicKeyToAddress(pub *ecdsa.PublicKey) (common.Address, error) {
if pub == nil {
return common.Address{}, ErrInvalidPublicKey
}

address := crypto.PubkeyToAddress(*pub)
return address, nil
}

func VerifySignature(pubKey *ecdsa.PublicKey, message, signature []byte) error {
if pubKey == nil {
return ErrInvalidPublicKey
}

if len(signature) != 65 {
return ErrInvalidSignature
}

// Checking the signature
signatureNoRecoverID := signature[:len(signature)-1]
valid := crypto.VerifySignature(
crypto.FromECDSAPub(pubKey),
message,
signatureNoRecoverID,
)

if !valid {
return ErrInvalidSignature
}

return nil
}

func ValidateAddress(address common.Address) error {
if address == common.Address{} {
return ErrInvalidAddress
}
return nil
}
Loading