You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.8 KiB

  1. package cryptostore
  2. import (
  3. "github.com/pkg/errors"
  4. crypto "github.com/tendermint/go-crypto"
  5. "github.com/tendermint/go-crypto/nano"
  6. )
  7. var (
  8. // GenEd25519 produces Ed25519 private keys
  9. GenEd25519 Generator = GenFunc(genEd25519)
  10. // GenSecp256k1 produces Secp256k1 private keys
  11. GenSecp256k1 Generator = GenFunc(genSecp256)
  12. // GenLedger used Ed25519 keys stored on nano ledger s with cosmos app
  13. GenLedger Generator = GenFunc(genLedger)
  14. )
  15. // Generator determines the type of private key the keystore creates
  16. type Generator interface {
  17. Generate(secret []byte) crypto.PrivKey
  18. }
  19. // GenFunc is a helper to transform a function into a Generator
  20. type GenFunc func(secret []byte) crypto.PrivKey
  21. func (f GenFunc) Generate(secret []byte) crypto.PrivKey {
  22. return f(secret)
  23. }
  24. func genEd25519(secret []byte) crypto.PrivKey {
  25. return crypto.GenPrivKeyEd25519FromSecret(secret).Wrap()
  26. }
  27. func genSecp256(secret []byte) crypto.PrivKey {
  28. return crypto.GenPrivKeySecp256k1FromSecret(secret).Wrap()
  29. }
  30. // secret is completely ignored for the ledger...
  31. // just for interface compatibility
  32. func genLedger(secret []byte) crypto.PrivKey {
  33. key, err := nano.NewPrivKeyLedger()
  34. if err != nil {
  35. // TODO: cleaner error handling
  36. panic(err)
  37. }
  38. return key
  39. }
  40. func getGenerator(algo string) (Generator, error) {
  41. switch algo {
  42. case crypto.NameEd25519:
  43. return GenEd25519, nil
  44. case crypto.NameSecp256k1:
  45. return GenSecp256k1, nil
  46. case nano.NameLedger:
  47. return GenLedger, nil
  48. default:
  49. return nil, errors.Errorf("Cannot generate keys for algorithm: %s", algo)
  50. }
  51. }
  52. func getGeneratorByType(typ byte) (Generator, error) {
  53. switch typ {
  54. case crypto.TypeEd25519:
  55. return GenEd25519, nil
  56. case crypto.TypeSecp256k1:
  57. return GenSecp256k1, nil
  58. case nano.TypeLedger:
  59. return GenLedger, nil
  60. default:
  61. return nil, errors.Errorf("Cannot generate keys for algorithm: %X", typ)
  62. }
  63. }