forked from go-chain/go-tron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
70 lines (54 loc) · 1.5 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Package account provides functionality for managing Tron network accounts.
package account
import (
"crypto/ecdsa"
"crypto/rand"
"fmt"
"github.com/MinhLoc282/go-tron"
"github.com/MinhLoc282/go-tron/address"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/ethereum/go-ethereum/crypto"
)
type Account interface {
Address() address.Address
tron.Signer
}
// LocalAccount is a private key address pair.
// TODO(271): Add more functionality to this.
type LocalAccount struct {
addr address.Address
priv *ecdsa.PrivateKey
}
func NewLocalAccount() *LocalAccount {
acc := new(LocalAccount)
privateKey, err := ecdsa.GenerateKey(btcec.S256(), rand.Reader)
if err != nil {
panic(err)
}
pub := ecdsa.PublicKey{Curve: btcec.S256(), X: privateKey.X, Y: privateKey.Y}
acc.addr = address.FromPublicKey(&pub)
acc.priv = privateKey
return acc
}
func (a *LocalAccount) PrivateKey() string {
return fmt.Sprintf("%x", a.priv.D.Bytes())
}
// FromPrivateKeyHex derives an account from a hexadecimal private key string.
func FromPrivateKeyHex(hex string) (*LocalAccount, error) {
priv, err := crypto.HexToECDSA(hex)
if err != nil {
return nil, err
}
return &LocalAccount{
addr: address.FromPublicKey(&priv.PublicKey),
priv: priv,
}, nil
}
// Address returns the address of the account.
func (a *LocalAccount) Address() address.Address {
return a.addr
}
// Sign signs a signable object with the account's private key.
func (a *LocalAccount) Sign(signable tron.Signable) error {
return signable.Sign(a.priv)
}