github.com/Finschia/finschia-sdk@v0.48.1/crypto/codec/oc.go (about)

     1  package codec
     2  
     3  import (
     4  	tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto"
     5  
     6  	occrypto "github.com/Finschia/ostracon/crypto"
     7  	"github.com/Finschia/ostracon/crypto/encoding"
     8  
     9  	"github.com/Finschia/finschia-sdk/crypto/keys/ed25519"
    10  	"github.com/Finschia/finschia-sdk/crypto/keys/secp256k1"
    11  	cryptotypes "github.com/Finschia/finschia-sdk/crypto/types"
    12  	sdkerrors "github.com/Finschia/finschia-sdk/types/errors"
    13  )
    14  
    15  // FromOcProtoPublicKey converts a OC's tmprotocrypto.PublicKey into our own PubKey.
    16  func FromOcProtoPublicKey(protoPk tmprotocrypto.PublicKey) (cryptotypes.PubKey, error) {
    17  	switch protoPk := protoPk.Sum.(type) {
    18  	case *tmprotocrypto.PublicKey_Ed25519:
    19  		return &ed25519.PubKey{
    20  			Key: protoPk.Ed25519,
    21  		}, nil
    22  	case *tmprotocrypto.PublicKey_Secp256K1:
    23  		return &secp256k1.PubKey{
    24  			Key: protoPk.Secp256K1,
    25  		}, nil
    26  	default:
    27  		return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v from Ostracon public key", protoPk)
    28  	}
    29  }
    30  
    31  // ToOcProtoPublicKey converts our own PubKey to OC's tmprotocrypto.PublicKey.
    32  func ToOcProtoPublicKey(pk cryptotypes.PubKey) (tmprotocrypto.PublicKey, error) {
    33  	switch pk := pk.(type) {
    34  	case *ed25519.PubKey:
    35  		return tmprotocrypto.PublicKey{
    36  			Sum: &tmprotocrypto.PublicKey_Ed25519{
    37  				Ed25519: pk.Key,
    38  			},
    39  		}, nil
    40  	case *secp256k1.PubKey:
    41  		return tmprotocrypto.PublicKey{
    42  			Sum: &tmprotocrypto.PublicKey_Secp256K1{
    43  				Secp256K1: pk.Key,
    44  			},
    45  		}, nil
    46  	default:
    47  		return tmprotocrypto.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to Ostracon public key", pk)
    48  	}
    49  }
    50  
    51  // FromOcPubKeyInterface converts OC's occrypto.PubKey to our own PubKey.
    52  func FromOcPubKeyInterface(tmPk occrypto.PubKey) (cryptotypes.PubKey, error) {
    53  	ocProtoPk, err := encoding.PubKeyToProto(tmPk)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	return FromOcProtoPublicKey(ocProtoPk)
    59  }
    60  
    61  // ToOcPubKeyInterface converts our own PubKey to OC's occrypto.PubKey.
    62  func ToOcPubKeyInterface(pk cryptotypes.PubKey) (occrypto.PubKey, error) {
    63  	ocProtoPk, err := ToOcProtoPublicKey(pk)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	return encoding.PubKeyFromProto(&ocProtoPk)
    69  }