github.com/kotalco/kotal@v0.3.0/helpers/node.go (about)

     1  package helpers
     2  
     3  import (
     4  	"crypto/ecdsa"
     5  	"errors"
     6  	"github.com/ethereum/go-ethereum/common/hexutil"
     7  	"github.com/ethereum/go-ethereum/crypto"
     8  )
     9  
    10  func derive(fromPrivateKey string) (publicKeyECDSA *ecdsa.PublicKey, err error) {
    11  	// private key
    12  	privateKey, err := crypto.HexToECDSA(fromPrivateKey)
    13  	if err != nil {
    14  		return
    15  	}
    16  
    17  	// public key
    18  	publicKey := privateKey.Public()
    19  	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
    20  	if !ok {
    21  		err = errors.New("publicKey is not of type *ecdsa.PublicKey")
    22  		return
    23  	}
    24  
    25  	return
    26  }
    27  
    28  // DerivePublicKey drives node public key from private key
    29  func DerivePublicKey(fromPrivateKey string) (publicKeyHex string, err error) {
    30  	publicKeyECDSA, err := derive(fromPrivateKey)
    31  	if err != nil {
    32  		return
    33  	}
    34  
    35  	publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
    36  	publicKeyHex = hexutil.Encode(publicKeyBytes)[4:]
    37  
    38  	return
    39  
    40  }
    41  
    42  // DeriveAddress drives ethereum address from private key
    43  func DeriveAddress(fromPrivateKey string) (addressHex string, err error) {
    44  	publicKeyECDSA, err := derive(fromPrivateKey)
    45  	if err != nil {
    46  		return
    47  	}
    48  
    49  	addressHex = crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    50  	return
    51  
    52  }