github.com/cosmos/cosmos-sdk@v0.50.1/crypto/keys/ed25519/ed25519.go (about)

     1  package ed25519
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/subtle"
     6  	"fmt"
     7  	"io"
     8  
     9  	"github.com/cometbft/cometbft/crypto"
    10  	"github.com/cometbft/cometbft/crypto/tmhash"
    11  	"github.com/hdevalence/ed25519consensus"
    12  
    13  	errorsmod "cosmossdk.io/errors"
    14  
    15  	"github.com/cosmos/cosmos-sdk/codec"
    16  	cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
    17  	"github.com/cosmos/cosmos-sdk/types/errors"
    18  )
    19  
    20  //-------------------------------------
    21  
    22  const (
    23  	PrivKeyName = "tendermint/PrivKeyEd25519"
    24  	PubKeyName  = "tendermint/PubKeyEd25519"
    25  	// PubKeySize is is the size, in bytes, of public keys as used in this package.
    26  	PubKeySize = 32
    27  	// PrivKeySize is the size, in bytes, of private keys as used in this package.
    28  	PrivKeySize = 64
    29  	// Size of an Edwards25519 signature. Namely the size of a compressed
    30  	// Edwards25519 point, and a field element. Both of which are 32 bytes.
    31  	SignatureSize = 64
    32  	// SeedSize is the size, in bytes, of private key seeds. These are the
    33  	// private key representations used by RFC 8032.
    34  	SeedSize = 32
    35  
    36  	keyType = "ed25519"
    37  )
    38  
    39  var (
    40  	_ cryptotypes.PrivKey  = &PrivKey{}
    41  	_ codec.AminoMarshaler = &PrivKey{}
    42  )
    43  
    44  // Bytes returns the privkey byte format.
    45  func (privKey *PrivKey) Bytes() []byte {
    46  	return privKey.Key
    47  }
    48  
    49  // Sign produces a signature on the provided message.
    50  // This assumes the privkey is wellformed in the golang format.
    51  // The first 32 bytes should be random,
    52  // corresponding to the normal ed25519 private key.
    53  // The latter 32 bytes should be the compressed public key.
    54  // If these conditions aren't met, Sign will panic or produce an
    55  // incorrect signature.
    56  func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) {
    57  	return ed25519.Sign(privKey.Key, msg), nil
    58  }
    59  
    60  // PubKey gets the corresponding public key from the private key.
    61  //
    62  // Panics if the private key is not initialized.
    63  func (privKey *PrivKey) PubKey() cryptotypes.PubKey {
    64  	// If the latter 32 bytes of the privkey are all zero, privkey is not
    65  	// initialized.
    66  	initialized := false
    67  	for _, v := range privKey.Key[32:] {
    68  		if v != 0 {
    69  			initialized = true
    70  			break
    71  		}
    72  	}
    73  
    74  	if !initialized {
    75  		panic("Expected ed25519 PrivKey to include concatenated pubkey bytes")
    76  	}
    77  
    78  	pubkeyBytes := make([]byte, PubKeySize)
    79  	copy(pubkeyBytes, privKey.Key[32:])
    80  	return &PubKey{Key: pubkeyBytes}
    81  }
    82  
    83  // Equals - you probably don't need to use this.
    84  // Runs in constant time based on length of the keys.
    85  func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
    86  	if privKey.Type() != other.Type() {
    87  		return false
    88  	}
    89  
    90  	return subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1
    91  }
    92  
    93  func (privKey *PrivKey) Type() string {
    94  	return keyType
    95  }
    96  
    97  // MarshalAmino overrides Amino binary marshaling.
    98  func (privKey PrivKey) MarshalAmino() ([]byte, error) {
    99  	return privKey.Key, nil
   100  }
   101  
   102  // UnmarshalAmino overrides Amino binary marshaling.
   103  func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {
   104  	if len(bz) != PrivKeySize {
   105  		return fmt.Errorf("invalid privkey size")
   106  	}
   107  	privKey.Key = bz
   108  
   109  	return nil
   110  }
   111  
   112  // MarshalAminoJSON overrides Amino JSON marshaling.
   113  func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) {
   114  	// When we marshal to Amino JSON, we don't marshal the "key" field itself,
   115  	// just its contents (i.e. the key bytes).
   116  	return privKey.MarshalAmino()
   117  }
   118  
   119  // UnmarshalAminoJSON overrides Amino JSON marshaling.
   120  func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error {
   121  	return privKey.UnmarshalAmino(bz)
   122  }
   123  
   124  // GenPrivKey generates a new ed25519 private key. These ed25519 keys must not
   125  // be used in SDK apps except in a tendermint validator context.
   126  // It uses OS randomness in conjunction with the current global random seed
   127  // in tendermint/libs/common to generate the private key.
   128  func GenPrivKey() *PrivKey {
   129  	return genPrivKey(crypto.CReader())
   130  }
   131  
   132  // genPrivKey generates a new ed25519 private key using the provided reader.
   133  func genPrivKey(rand io.Reader) *PrivKey {
   134  	seed := make([]byte, SeedSize)
   135  
   136  	_, err := io.ReadFull(rand, seed)
   137  	if err != nil {
   138  		panic(err)
   139  	}
   140  
   141  	return &PrivKey{Key: ed25519.NewKeyFromSeed(seed)}
   142  }
   143  
   144  // GenPrivKeyFromSecret hashes the secret with SHA2, and uses
   145  // that 32 byte output to create the private key.
   146  // NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context.
   147  // NOTE: secret should be the output of a KDF like bcrypt,
   148  // if it's derived from user input.
   149  func GenPrivKeyFromSecret(secret []byte) *PrivKey {
   150  	seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes.
   151  
   152  	return &PrivKey{Key: ed25519.NewKeyFromSeed(seed)}
   153  }
   154  
   155  //-------------------------------------
   156  
   157  var (
   158  	_ cryptotypes.PubKey   = &PubKey{}
   159  	_ codec.AminoMarshaler = &PubKey{}
   160  )
   161  
   162  // Address is the SHA256-20 of the raw pubkey bytes.
   163  // It doesn't implement ADR-28 addresses and it must not be used
   164  // in SDK except in a tendermint validator context.
   165  func (pubKey *PubKey) Address() crypto.Address {
   166  	if len(pubKey.Key) != PubKeySize {
   167  		panic("pubkey is incorrect size")
   168  	}
   169  	// For ADR-28 compatible address we would need to
   170  	// return address.Hash(proto.MessageName(pubKey), pubKey.Key)
   171  	return crypto.Address(tmhash.SumTruncated(pubKey.Key))
   172  }
   173  
   174  // Bytes returns the PubKey byte format.
   175  func (pubKey *PubKey) Bytes() []byte {
   176  	return pubKey.Key
   177  }
   178  
   179  func (pubKey *PubKey) VerifySignature(msg, sig []byte) bool {
   180  	// make sure we use the same algorithm to sign
   181  	if len(sig) != SignatureSize {
   182  		return false
   183  	}
   184  
   185  	// uses https://github.com/hdevalence/ed25519consensus.Verify to comply with zip215 verification rules
   186  	return ed25519consensus.Verify(pubKey.Key, msg, sig)
   187  }
   188  
   189  // String returns Hex representation of a pubkey with it's type
   190  func (pubKey *PubKey) String() string {
   191  	return fmt.Sprintf("PubKeyEd25519{%X}", pubKey.Key)
   192  }
   193  
   194  func (pubKey *PubKey) Type() string {
   195  	return keyType
   196  }
   197  
   198  func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool {
   199  	if pubKey.Type() != other.Type() {
   200  		return false
   201  	}
   202  
   203  	return subtle.ConstantTimeCompare(pubKey.Bytes(), other.Bytes()) == 1
   204  }
   205  
   206  // MarshalAmino overrides Amino binary marshaling.
   207  func (pubKey PubKey) MarshalAmino() ([]byte, error) {
   208  	return pubKey.Key, nil
   209  }
   210  
   211  // UnmarshalAmino overrides Amino binary marshaling.
   212  func (pubKey *PubKey) UnmarshalAmino(bz []byte) error {
   213  	if len(bz) != PubKeySize {
   214  		return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size")
   215  	}
   216  	pubKey.Key = bz
   217  
   218  	return nil
   219  }
   220  
   221  // MarshalAminoJSON overrides Amino JSON marshaling.
   222  func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) {
   223  	// When we marshal to Amino JSON, we don't marshal the "key" field itself,
   224  	// just its contents (i.e. the key bytes).
   225  	return pubKey.MarshalAmino()
   226  }
   227  
   228  // UnmarshalAminoJSON overrides Amino JSON marshaling.
   229  func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
   230  	return pubKey.UnmarshalAmino(bz)
   231  }