github.com/devwanda/aphelion-staking@v0.33.9/crypto/encoding/codec.go (about)

     1  package encoding
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/devwanda/aphelion-staking/crypto"
     8  	"github.com/devwanda/aphelion-staking/crypto/ed25519"
     9  	pc "github.com/devwanda/aphelion-staking/proto/crypto/keys"
    10  )
    11  
    12  // PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey
    13  func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
    14  	if k == nil {
    15  		return pc.PublicKey{}, errors.New("nil PublicKey")
    16  	}
    17  	var kp pc.PublicKey
    18  	switch k := k.(type) {
    19  	case ed25519.PubKeyEd25519:
    20  		kp = pc.PublicKey{
    21  			Sum: &pc.PublicKey_Ed25519{
    22  				Ed25519: k[:],
    23  			},
    24  		}
    25  	default:
    26  		return kp, fmt.Errorf("toproto: key type %v is not supported", k)
    27  	}
    28  	return kp, nil
    29  }
    30  
    31  // PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey
    32  func PubKeyFromProto(k *pc.PublicKey) (crypto.PubKey, error) {
    33  	if k == nil {
    34  		return nil, errors.New("nil PublicKey")
    35  	}
    36  	switch k := k.Sum.(type) {
    37  	case *pc.PublicKey_Ed25519:
    38  		if len(k.Ed25519) != ed25519.PubKeyEd25519Size {
    39  			return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
    40  				len(k.Ed25519), ed25519.PubKeyEd25519Size)
    41  		}
    42  		var pk ed25519.PubKeyEd25519
    43  		copy(pk[:], k.Ed25519)
    44  		return pk, nil
    45  	default:
    46  		return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
    47  	}
    48  }
    49  
    50  // PrivKeyToProto takes crypto.PrivKey and transforms it to a protobuf PrivKey
    51  func PrivKeyToProto(k crypto.PrivKey) (pc.PrivateKey, error) {
    52  	var kp pc.PrivateKey
    53  	switch k := k.(type) {
    54  	case ed25519.PrivKeyEd25519:
    55  		kp = pc.PrivateKey{
    56  			Sum: &pc.PrivateKey_Ed25519{
    57  				Ed25519: k[:],
    58  			},
    59  		}
    60  	default:
    61  		return kp, errors.New("toproto: key type is not supported")
    62  	}
    63  	return kp, nil
    64  }
    65  
    66  // PrivKeyFromProto takes a protobuf PrivateKey and transforms it to a crypto.PrivKey
    67  func PrivKeyFromProto(k pc.PrivateKey) (crypto.PrivKey, error) {
    68  	switch k := k.Sum.(type) {
    69  	case *pc.PrivateKey_Ed25519:
    70  
    71  		if len(k.Ed25519) != ed25519.PubKeyEd25519Size {
    72  			return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
    73  				len(k.Ed25519), ed25519.PubKeyEd25519Size)
    74  		}
    75  		var pk ed25519.PrivKeyEd25519
    76  		copy(pk[:], k.Ed25519)
    77  		return pk, nil
    78  	default:
    79  		return nil, errors.New("fromproto: key type not supported")
    80  	}
    81  }