This repository has been archived by the owner on Dec 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwallet.go
92 lines (80 loc) · 2.25 KB
/
wallet.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/hex"
"fmt"
"strings"
"github.com/BurntSushi/toml"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/sha3"
"github.com/the729/go-libra/crypto"
"github.com/the729/go-libra/types"
)
type Account struct {
PrivateKey ed25519.PrivateKey
Address types.AccountAddress
AuthKey ed25519.PublicKey
SequenceNumber uint64
}
type AccountConfig struct {
PrivateKey crypto.PrivateKey `toml:"private_key"`
AuthKey crypto.PublicKey `toml:"auth_key"`
Address []byte `toml:"address"`
}
type WalletConfig struct {
Accounts []*AccountConfig `toml:"accounts"`
}
type SimpleWallet struct {
Accounts map[string]*Account
}
func LoadAccounts(file string) (*SimpleWallet, error) {
walletConf := &WalletConfig{}
_, err := toml.DecodeFile(file, walletConf)
if err != nil {
return nil, fmt.Errorf("toml decode file error: %v", err)
}
wallet := &SimpleWallet{
Accounts: make(map[string]*Account),
}
for _, accountConf := range walletConf.Accounts {
account := &Account{
PrivateKey: ed25519.PrivateKey(accountConf.PrivateKey),
AuthKey: ed25519.PublicKey(accountConf.AuthKey),
}
if len(accountConf.Address) == types.AccountAddressLength {
copy(account.Address[:], accountConf.Address)
}
if accountConf.PrivateKey != nil {
pubkey := account.PrivateKey.Public().(ed25519.PublicKey)
hasher := sha3.New256()
hasher.Write(pubkey)
hasher.Write([]byte{0})
account.AuthKey = hasher.Sum([]byte{})
if len(accountConf.Address) != types.AccountAddressLength {
copy(account.Address[:], account.AuthKey[16:])
}
}
wallet.Accounts[hex.EncodeToString(account.Address[:])] = account
}
return wallet, nil
}
func (w *SimpleWallet) GetAccount(prefix string) (*Account, error) {
var seen *Account
for addr, account := range w.Accounts {
if strings.HasPrefix(string(addr[:]), prefix) {
if seen != nil {
return nil, fmt.Errorf("more than 1 accounts have prefix %s", prefix)
}
seen = account
}
}
if seen != nil {
return seen, nil
}
newAddr, err := hex.DecodeString(prefix)
if err == nil && len(newAddr) == types.AccountAddressLength {
a := &Account{}
copy(a.Address[:], newAddr)
return a, nil
}
return nil, fmt.Errorf("account not present in local config file")
}