-
Notifications
You must be signed in to change notification settings - Fork 1
/
account.go
68 lines (53 loc) · 1.35 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
package aptos
import (
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"fmt"
"golang.org/x/crypto/sha3"
)
type AptosAccount struct {
privateKey ed25519.PrivateKey
authKeyCached string
}
func AccountFromRandomKey() (*AptosAccount, error) {
_, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
return &AptosAccount{
privateKey: private,
}, nil
}
func AccountFromPrivateKey(privateKey string) (*AptosAccount, error) {
seed, err := hex.DecodeString(privateKey)
if err != nil {
return nil, err
}
private := ed25519.NewKeyFromSeed(seed[:32])
return &AptosAccount{
privateKey: private,
}, nil
}
func (aa *AptosAccount) pubKeyBytes() []byte {
pubKey := aa.privateKey.Public().(ed25519.PublicKey)
return []byte(pubKey)
}
func (aa *AptosAccount) PublicKey() string {
return fmt.Sprint("0x", hex.EncodeToString(aa.pubKeyBytes()))
}
func (aa *AptosAccount) Address() string {
if aa.authKeyCached == "" {
hasher := sha3.New256()
hasher.Write(aa.pubKeyBytes())
hasher.Write([]byte("\x00"))
aa.authKeyCached = fmt.Sprint("0x", hex.EncodeToString(hasher.Sum(nil)))
}
return aa.authKeyCached
}
func (aa *AptosAccount) SignMessage(msg []byte) []byte {
return ed25519.Sign(aa.privateKey, msg)
}
func (aa *AptosAccount) VerifyMessage(sig, msg []byte) bool {
return ed25519.Verify(aa.pubKeyBytes(), msg, sig)
}