-
Notifications
You must be signed in to change notification settings - Fork 88
/
accounts.go
51 lines (42 loc) · 894 Bytes
/
accounts.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
package web3
import (
"crypto/ecdsa"
"encoding/hex"
"strings"
"github.com/gochain/gochain/v4/common"
"github.com/gochain/gochain/v4/crypto"
)
func CreateAccount() (*Account, error) {
key, err := crypto.GenerateKey()
if err != nil {
return nil, err
}
return &Account{
key: key,
}, nil
}
func ParsePrivateKey(pkHex string) (*Account, error) {
fromPK := strings.TrimPrefix(pkHex, "0x")
key, err := crypto.HexToECDSA(fromPK)
if err != nil {
return nil, err
}
return &Account{
key: key,
}, nil
}
type Account struct {
key *ecdsa.PrivateKey
}
func (a *Account) Key() *ecdsa.PrivateKey {
return a.key
}
func (a *Account) Address() common.Address {
return crypto.PubkeyToAddress(a.key.PublicKey)
}
func (a *Account) PublicKey() string {
return a.Address().Hex()
}
func (a *Account) PrivateKey() string {
return "0x" + hex.EncodeToString(crypto.FromECDSA(a.key))
}