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

     1  package hd
     2  
     3  import (
     4  	bip39 "github.com/cosmos/go-bip39"
     5  
     6  	"github.com/Finschia/finschia-sdk/crypto/keys/secp256k1"
     7  	"github.com/Finschia/finschia-sdk/crypto/types"
     8  )
     9  
    10  // PubKeyType defines an algorithm to derive key-pairs which can be used for cryptographic signing.
    11  type PubKeyType string
    12  
    13  const (
    14  	// MultiType implies that a pubkey is a multisignature
    15  	MultiType = PubKeyType("multi")
    16  	// Secp256k1Type uses the Bitcoin secp256k1 ECDSA parameters.
    17  	Secp256k1Type = PubKeyType("secp256k1")
    18  	// Ed25519Type represents the Ed25519Type signature system.
    19  	// It is currently not supported for end-user keys (wallets/ledgers).
    20  	Ed25519Type = PubKeyType("ed25519")
    21  	// Sr25519Type represents the Sr25519Type signature system.
    22  	Sr25519Type = PubKeyType("sr25519")
    23  )
    24  
    25  // Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters.
    26  var Secp256k1 = secp256k1Algo{}
    27  
    28  type (
    29  	DeriveFn   func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
    30  	GenerateFn func(bz []byte) types.PrivKey
    31  )
    32  
    33  type WalletGenerator interface {
    34  	Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
    35  	Generate(bz []byte) types.PrivKey
    36  }
    37  
    38  type secp256k1Algo struct{}
    39  
    40  func (s secp256k1Algo) Name() PubKeyType {
    41  	return Secp256k1Type
    42  }
    43  
    44  // Derive derives and returns the secp256k1 private key for the given seed and HD path.
    45  func (s secp256k1Algo) Derive() DeriveFn {
    46  	return func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) {
    47  		seed, err := bip39.NewSeedWithErrorChecking(mnemonic, bip39Passphrase)
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  
    52  		masterPriv, ch := ComputeMastersFromSeed(seed)
    53  		if len(hdPath) == 0 {
    54  			return masterPriv[:], nil
    55  		}
    56  		derivedKey, err := DerivePrivateKeyForPath(masterPriv, ch, hdPath)
    57  
    58  		return derivedKey, err
    59  	}
    60  }
    61  
    62  // Generate generates a secp256k1 private key from the given bytes.
    63  func (s secp256k1Algo) Generate() GenerateFn {
    64  	return func(bz []byte) types.PrivKey {
    65  		bzArr := make([]byte, secp256k1.PrivKeySize)
    66  		copy(bzArr, bz)
    67  
    68  		return &secp256k1.PrivKey{Key: bzArr}
    69  	}
    70  }