github.com/adoriasoft/tendermint@v0.34.0-dev1.0.20200722151356-96d84601a75a/crypto/encoding/codec.go (about)

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