keypair.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package crypto
  2. import (
  3. "strings"
  4. "github.com/ethereum/go-ethereum/common"
  5. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  6. )
  7. type KeyPair struct {
  8. PrivateKey []byte
  9. PublicKey []byte
  10. address []byte
  11. mnemonic string
  12. // The associated account
  13. // account *StateObject
  14. }
  15. func GenerateNewKeyPair() *KeyPair {
  16. _, prv := secp256k1.GenerateKeyPair()
  17. keyPair, _ := NewKeyPairFromSec(prv) // swallow error, this one cannot err
  18. return keyPair
  19. }
  20. func NewKeyPairFromSec(seckey []byte) (*KeyPair, error) {
  21. pubkey, err := secp256k1.GeneratePubKey(seckey)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return &KeyPair{PrivateKey: seckey, PublicKey: pubkey}, nil
  26. }
  27. func (k *KeyPair) Address() []byte {
  28. if k.address == nil {
  29. k.address = Sha3(k.PublicKey[1:])[12:]
  30. }
  31. return k.address
  32. }
  33. func (k *KeyPair) Mnemonic() string {
  34. if k.mnemonic == "" {
  35. k.mnemonic = strings.Join(MnemonicEncode(common.Bytes2Hex(k.PrivateKey)), " ")
  36. }
  37. return k.mnemonic
  38. }
  39. func (k *KeyPair) AsStrings() (string, string, string, string) {
  40. return k.Mnemonic(), common.Bytes2Hex(k.Address()), common.Bytes2Hex(k.PrivateKey), common.Bytes2Hex(k.PublicKey)
  41. }