github.com/vipernet-xyz/tm@v0.34.24/crypto/encoding/codec.go (about)

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