Skip to content

Commit 9bb575b

Browse files
committed
Merge pull request bnb-chain#1283 from ethersphere/frontier/accounts
Account management improvements
2 parents 6f69b4d + 1959346 commit 9bb575b

10 files changed

Lines changed: 358 additions & 174 deletions

File tree

‎accounts/account_manager.go‎

Lines changed: 74 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ This abstracts part of a user's interaction with an account she controls.
2626
It's not an abstraction of core Ethereum accounts data type / logic -
2727
for that see the core processing code of blocks / txs.
2828
29-
Currently this is pretty much a passthrough to the KeyStore2 interface,
29+
Currently this is pretty much a passthrough to the KeyStore interface,
3030
and accounts persistence is derived from stored keys' addresses
3131
3232
*/
@@ -36,6 +36,7 @@ import (
3636
"crypto/ecdsa"
3737
crand "crypto/rand"
3838
"errors"
39+
"fmt"
3940
"os"
4041
"sync"
4142
"time"
@@ -49,17 +50,12 @@ var (
4950
ErrNoKeys = errors.New("no keys in store")
5051
)
5152

52-
const (
53-
// Default unlock duration (in seconds) when an account is unlocked from the console
54-
DefaultAccountUnlockDuration = 300
55-
)
56-
5753
type Account struct {
5854
Address common.Address
5955
}
6056

6157
type Manager struct {
62-
keyStore crypto.KeyStore2
58+
keyStore crypto.KeyStore
6359
unlocked map[common.Address]*unlocked
6460
mutex sync.RWMutex
6561
}
@@ -69,7 +65,7 @@ type unlocked struct {
6965
abort chan struct{}
7066
}
7167

72-
func NewManager(keyStore crypto.KeyStore2) *Manager {
68+
func NewManager(keyStore crypto.KeyStore) *Manager {
7369
return &Manager{
7470
keyStore: keyStore,
7571
unlocked: make(map[common.Address]*unlocked),
@@ -86,19 +82,6 @@ func (am *Manager) HasAccount(addr common.Address) bool {
8682
return false
8783
}
8884

89-
func (am *Manager) Primary() (addr common.Address, err error) {
90-
addrs, err := am.keyStore.GetKeyAddresses()
91-
if os.IsNotExist(err) {
92-
return common.Address{}, ErrNoKeys
93-
} else if err != nil {
94-
return common.Address{}, err
95-
}
96-
if len(addrs) == 0 {
97-
return common.Address{}, ErrNoKeys
98-
}
99-
return addrs[0], nil
100-
}
101-
10285
func (am *Manager) DeleteAccount(address common.Address, auth string) error {
10386
return am.keyStore.DeleteKey(address, auth)
10487
}
@@ -114,28 +97,58 @@ func (am *Manager) Sign(a Account, toSign []byte) (signature []byte, err error)
11497
return signature, err
11598
}
11699

117-
// TimedUnlock unlocks the account with the given address.
118-
// When timeout has passed, the account will be locked again.
100+
// unlock indefinitely
101+
func (am *Manager) Unlock(addr common.Address, keyAuth string) error {
102+
return am.TimedUnlock(addr, keyAuth, 0)
103+
}
104+
105+
// Unlock unlocks the account with the given address. The account
106+
// stays unlocked for the duration of timeout
107+
// it timeout is 0 the account is unlocked for the entire session
119108
func (am *Manager) TimedUnlock(addr common.Address, keyAuth string, timeout time.Duration) error {
120109
key, err := am.keyStore.GetKey(addr, keyAuth)
121110
if err != nil {
122111
return err
123112
}
124-
u := am.addUnlocked(addr, key)
125-
go am.dropLater(addr, u, timeout)
113+
var u *unlocked
114+
am.mutex.Lock()
115+
defer am.mutex.Unlock()
116+
var found bool
117+
u, found = am.unlocked[addr]
118+
if found {
119+
// terminate dropLater for this key to avoid unexpected drops.
120+
if u.abort != nil {
121+
close(u.abort)
122+
}
123+
}
124+
if timeout > 0 {
125+
u = &unlocked{Key: key, abort: make(chan struct{})}
126+
go am.expire(addr, u, timeout)
127+
} else {
128+
u = &unlocked{Key: key}
129+
}
130+
am.unlocked[addr] = u
126131
return nil
127132
}
128133

129-
// Unlock unlocks the account with the given address. The account
130-
// stays unlocked until the program exits or until a TimedUnlock
131-
// timeout (started after the call to Unlock) expires.
132-
func (am *Manager) Unlock(addr common.Address, keyAuth string) error {
133-
key, err := am.keyStore.GetKey(addr, keyAuth)
134-
if err != nil {
135-
return err
134+
func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) {
135+
t := time.NewTimer(timeout)
136+
defer t.Stop()
137+
select {
138+
case <-u.abort:
139+
// just quit
140+
case <-t.C:
141+
am.mutex.Lock()
142+
// only drop if it's still the same key instance that dropLater
143+
// was launched with. we can check that using pointer equality
144+
// because the map stores a new pointer every time the key is
145+
// unlocked.
146+
if am.unlocked[addr] == u {
147+
zeroKey(u.PrivateKey)
148+
delete(am.unlocked, addr)
149+
}
150+
am.mutex.Unlock()
136151
}
137-
am.addUnlocked(addr, key)
138-
return nil
139152
}
140153

141154
func (am *Manager) NewAccount(auth string) (Account, error) {
@@ -146,6 +159,20 @@ func (am *Manager) NewAccount(auth string) (Account, error) {
146159
return Account{Address: key.Address}, nil
147160
}
148161

162+
func (am *Manager) AddressByIndex(index int) (addr string, err error) {
163+
var addrs []common.Address
164+
addrs, err = am.keyStore.GetKeyAddresses()
165+
if err != nil {
166+
return
167+
}
168+
if index < 0 || index >= len(addrs) {
169+
err = fmt.Errorf("index out of range: %d (should be 0-%d)", index, len(addrs)-1)
170+
} else {
171+
addr = addrs[index].Hex()
172+
}
173+
return
174+
}
175+
149176
func (am *Manager) Accounts() ([]Account, error) {
150177
addresses, err := am.keyStore.GetKeyAddresses()
151178
if os.IsNotExist(err) {
@@ -162,43 +189,6 @@ func (am *Manager) Accounts() ([]Account, error) {
162189
return accounts, err
163190
}
164191

165-
func (am *Manager) addUnlocked(addr common.Address, key *crypto.Key) *unlocked {
166-
u := &unlocked{Key: key, abort: make(chan struct{})}
167-
am.mutex.Lock()
168-
prev, found := am.unlocked[addr]
169-
if found {
170-
// terminate dropLater for this key to avoid unexpected drops.
171-
close(prev.abort)
172-
// the key is zeroed here instead of in dropLater because
173-
// there might not actually be a dropLater running for this
174-
// key, i.e. when Unlock was used.
175-
zeroKey(prev.PrivateKey)
176-
}
177-
am.unlocked[addr] = u
178-
am.mutex.Unlock()
179-
return u
180-
}
181-
182-
func (am *Manager) dropLater(addr common.Address, u *unlocked, timeout time.Duration) {
183-
t := time.NewTimer(timeout)
184-
defer t.Stop()
185-
select {
186-
case <-u.abort:
187-
// just quit
188-
case <-t.C:
189-
am.mutex.Lock()
190-
// only drop if it's still the same key instance that dropLater
191-
// was launched with. we can check that using pointer equality
192-
// because the map stores a new pointer every time the key is
193-
// unlocked.
194-
if am.unlocked[addr] == u {
195-
zeroKey(u.PrivateKey)
196-
delete(am.unlocked, addr)
197-
}
198-
am.mutex.Unlock()
199-
}
200-
}
201-
202192
// zeroKey zeroes a private key in memory.
203193
func zeroKey(k *ecdsa.PrivateKey) {
204194
b := k.D.Bits()
@@ -229,6 +219,19 @@ func (am *Manager) Import(path string, keyAuth string) (Account, error) {
229219
return Account{Address: key.Address}, nil
230220
}
231221

222+
func (am *Manager) Update(addr common.Address, authFrom, authTo string) (err error) {
223+
var key *crypto.Key
224+
key, err = am.keyStore.GetKey(addr, authFrom)
225+
226+
if err == nil {
227+
err = am.keyStore.StoreKey(key, authTo)
228+
if err == nil {
229+
am.keyStore.Cleanup(addr)
230+
}
231+
}
232+
return
233+
}
234+
232235
func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
233236
var key *crypto.Key
234237
key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)

‎accounts/accounts_test.go‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,46 @@ func TestTimedUnlock(t *testing.T) {
5252
t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
5353
}
5454

55+
// Signing fails again after automatic locking
56+
time.Sleep(150 * time.Millisecond)
57+
_, err = am.Sign(a1, toSign)
58+
if err != ErrLocked {
59+
t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
60+
}
61+
62+
}
63+
64+
func TestOverrideUnlock(t *testing.T) {
65+
dir, ks := tmpKeyStore(t, crypto.NewKeyStorePassphrase)
66+
defer os.RemoveAll(dir)
67+
68+
am := NewManager(ks)
69+
pass := "foo"
70+
a1, err := am.NewAccount(pass)
71+
toSign := randentropy.GetEntropyCSPRNG(32)
72+
73+
// Unlock indefinitely
74+
if err = am.Unlock(a1.Address, pass); err != nil {
75+
t.Fatal(err)
76+
}
77+
78+
// Signing without passphrase works because account is temp unlocked
79+
_, err = am.Sign(a1, toSign)
80+
if err != nil {
81+
t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
82+
}
83+
84+
// reset unlock to a shorter period, invalidates the previous unlock
85+
if err = am.TimedUnlock(a1.Address, pass, 100*time.Millisecond); err != nil {
86+
t.Fatal(err)
87+
}
88+
89+
// Signing without passphrase still works because account is temp unlocked
90+
_, err = am.Sign(a1, toSign)
91+
if err != nil {
92+
t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
93+
}
94+
5595
// Signing fails again after automatic locking
5696
time.Sleep(150 * time.Millisecond)
5797
_, err = am.Sign(a1, toSign)
@@ -60,7 +100,9 @@ func TestTimedUnlock(t *testing.T) {
60100
}
61101
}
62102

63-
func tmpKeyStore(t *testing.T, new func(string) crypto.KeyStore2) (string, crypto.KeyStore2) {
103+
//
104+
105+
func tmpKeyStore(t *testing.T, new func(string) crypto.KeyStore) (string, crypto.KeyStore) {
64106
d, err := ioutil.TempDir("", "eth-keystore-test")
65107
if err != nil {
66108
t.Fatal(err)

‎cmd/geth/js_test.go‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ import (
2020
"github.com/ethereum/go-ethereum/core/state"
2121
"github.com/ethereum/go-ethereum/crypto"
2222
"github.com/ethereum/go-ethereum/eth"
23-
"github.com/ethereum/go-ethereum/rpc/comms"
2423
"github.com/ethereum/go-ethereum/rpc/codec"
24+
"github.com/ethereum/go-ethereum/rpc/comms"
2525
)
2626

2727
const (
@@ -127,6 +127,7 @@ func TestNodeInfo(t *testing.T) {
127127
}
128128
defer ethereum.Stop()
129129
defer os.RemoveAll(tmp)
130+
130131
want := `{"DiscPort":0,"IP":"0.0.0.0","ListenAddr":"","Name":"test","NodeID":"4cb2fc32924e94277bf94b5e4c983beedb2eabd5a0bc941db32202735c6625d020ca14a5963d1738af43b6ac0a711d61b1a06de931a499fe2aa0b1a132a902b5","NodeUrl":"enode://4cb2fc32924e94277bf94b5e4c983beedb2eabd5a0bc941db32202735c6625d020ca14a5963d1738af43b6ac0a711d61b1a06de931a499fe2aa0b1a132a902b5@0.0.0.0:0","TCPPort":0,"Td":"131072"}`
131132
checkEvalJSON(t, repl, `admin.nodeInfo`, want)
132133
}
@@ -140,8 +141,7 @@ func TestAccounts(t *testing.T) {
140141
defer os.RemoveAll(tmp)
141142

142143
checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
143-
checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
144-
144+
checkEvalJSON(t, repl, `eth.coinbase`, `null`)
145145
val, err := repl.re.Run(`personal.newAccount("password")`)
146146
if err != nil {
147147
t.Errorf("expected no error, got %v", err)
@@ -151,9 +151,7 @@ func TestAccounts(t *testing.T) {
151151
t.Errorf("address not hex: %q", addr)
152152
}
153153

154-
// skip until order fixed #824
155-
// checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`", "`+addr+`"]`)
156-
// checkEvalJSON(t, repl, `eth.coinbase`, `"`+testAddress+`"`)
154+
checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`","`+addr+`"]`)
157155
}
158156

159157
func TestBlockChain(t *testing.T) {

0 commit comments

Comments
 (0)