key.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package key
  2. import (
  3. "crypto/ecdsa"
  4. "github.com/btcsuite/btcd/btcec"
  5. "github.com/ethereum/go-ethereum/common"
  6. "github.com/ethereum/go-ethereum/crypto"
  7. tronAddr "github.com/fbsobreira/gotron-sdk/pkg/address"
  8. "key-manager/hd"
  9. )
  10. type Account interface {
  11. GetIndex() uint64
  12. GetPriKey() *ecdsa.PrivateKey
  13. GetAddr() string
  14. }
  15. type TronAccount struct {
  16. Index uint64
  17. PriKey *ecdsa.PrivateKey
  18. Address tronAddr.Address
  19. }
  20. func (t *TronAccount) GetIndex() uint64 {
  21. return t.Index
  22. }
  23. func (t *TronAccount) GetPriKey() *ecdsa.PrivateKey {
  24. return t.PriKey
  25. }
  26. func (t *TronAccount) GetAddr() string {
  27. return t.Address.String()
  28. }
  29. type EthAccount struct {
  30. Index uint64
  31. PriKey *ecdsa.PrivateKey
  32. Address common.Address
  33. }
  34. func (e *EthAccount) GetIndex() uint64 {
  35. return e.Index
  36. }
  37. func (e *EthAccount) GetPriKey() *ecdsa.PrivateKey {
  38. return e.PriKey
  39. }
  40. func (e *EthAccount) GetAddr() string {
  41. return e.Address.String()
  42. }
  43. func NewEthAccount(mnemonic string, index uint64) (*EthAccount, error) {
  44. seed, err := hd.GenerateSeedFromMnemonic(mnemonic, "")
  45. if err != nil {
  46. return nil, err
  47. }
  48. path := hd.EthPath(index)
  49. extendSeed, err := hd.GetExtendSeedFromPath(path, seed)
  50. if err != nil {
  51. return nil, err
  52. }
  53. privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), extendSeed)
  54. privateKeyECDSA := privateKey.ToECDSA()
  55. return &EthAccount{
  56. Index: index,
  57. PriKey: privateKeyECDSA,
  58. Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
  59. }, nil
  60. }
  61. func NewTronAccount(mnemonic string, index uint64) (*TronAccount, error) {
  62. seed, err := hd.GenerateSeedFromMnemonic(mnemonic, "")
  63. if err != nil {
  64. return nil, err
  65. }
  66. path := hd.TronPath(index)
  67. extendSeed, err := hd.GetExtendSeedFromPath(path, seed)
  68. if err != nil {
  69. return nil, err
  70. }
  71. privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), extendSeed)
  72. privateKeyECDSA := privateKey.ToECDSA()
  73. return &TronAccount{
  74. Index: index,
  75. PriKey: privateKeyECDSA,
  76. Address: tronAddr.PubkeyToAddress(privateKeyECDSA.PublicKey),
  77. }, nil
  78. }