Skip to content

Commit 85e6c40

Browse files
committed
accounts, crypto: move keystore to package accounts
The account management API was originally implemented as a thin layer around crypto.KeyStore, on the grounds that several kinds of key stores would be implemented later on. It turns out that this won't happen so KeyStore is a superflous abstraction. In this commit crypto.KeyStore and everything related to it moves to package accounts and is unexported.
1 parent dff9b42 commit 85e6c40

19 files changed

Lines changed: 256 additions & 241 deletions

‎accounts/abi/bind/auth.go‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@
1717
package bind
1818

1919
import (
20+
"crypto/ecdsa"
2021
"errors"
2122
"io"
2223
"io/ioutil"
2324

25+
"github.com/ethereum/go-ethereum/accounts"
2426
"github.com/ethereum/go-ethereum/common"
2527
"github.com/ethereum/go-ethereum/core/types"
2628
"github.com/ethereum/go-ethereum/crypto"
@@ -33,23 +35,24 @@ func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
3335
if err != nil {
3436
return nil, err
3537
}
36-
key, err := crypto.DecryptKey(json, passphrase)
38+
key, err := accounts.DecryptKey(json, passphrase)
3739
if err != nil {
3840
return nil, err
3941
}
40-
return NewKeyedTransactor(key), nil
42+
return NewKeyedTransactor(key.PrivateKey), nil
4143
}
4244

4345
// NewKeyedTransactor is a utility method to easily create a transaction signer
44-
// from a plain go-ethereum crypto key.
45-
func NewKeyedTransactor(key *crypto.Key) *TransactOpts {
46+
// from a single private key.
47+
func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
48+
keyAddr := crypto.PubkeyToAddress(key.PublicKey)
4649
return &TransactOpts{
47-
From: key.Address,
50+
From: keyAddr,
4851
Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
49-
if address != key.Address {
52+
if address != keyAddr {
5053
return nil, errors.New("not authorized to sign this account")
5154
}
52-
signature, err := crypto.Sign(tx.SigHash().Bytes(), key.PrivateKey)
55+
signature, err := crypto.Sign(tx.SigHash().Bytes(), key)
5356
if err != nil {
5457
return nil, err
5558
}

‎accounts/abi/bind/bind_test.go‎

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,9 @@ var bindTests = []struct {
167167
`[{"constant":true,"inputs":[],"name":"transactString","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":true,"inputs":[],"name":"deployString","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"str","type":"string"}],"name":"transact","outputs":[],"type":"function"},{"inputs":[{"name":"str","type":"string"}],"type":"constructor"}]`,
168168
`
169169
// Generate a new random account and a funded simulator
170-
key := crypto.NewKey(rand.Reader)
171-
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: key.Address, Balance: big.NewInt(10000000000)})
172-
173-
// Convert the tester key to an authorized transactor for ease of use
170+
key, _ := crypto.GenerateKey()
174171
auth := bind.NewKeyedTransactor(key)
172+
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: auth.From, Balance: big.NewInt(10000000000)})
175173
176174
// Deploy an interaction tester contract and call a transaction on it
177175
_, _, interactor, err := DeployInteractor(auth, sim, "Deploy string")
@@ -210,11 +208,9 @@ var bindTests = []struct {
210208
`[{"constant":true,"inputs":[],"name":"tuple","outputs":[{"name":"a","type":"string"},{"name":"b","type":"int256"},{"name":"c","type":"bytes32"}],"type":"function"}]`,
211209
`
212210
// Generate a new random account and a funded simulator
213-
key := crypto.NewKey(rand.Reader)
214-
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: key.Address, Balance: big.NewInt(10000000000)})
215-
216-
// Convert the tester key to an authorized transactor for ease of use
211+
key, _ := crypto.GenerateKey()
217212
auth := bind.NewKeyedTransactor(key)
213+
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: auth.From, Balance: big.NewInt(10000000000)})
218214
219215
// Deploy a tuple tester contract and execute a structured call on it
220216
_, _, tupler, err := DeployTupler(auth, sim)
@@ -252,11 +248,9 @@ var bindTests = []struct {
252248
`[{"constant":true,"inputs":[{"name":"input","type":"address[]"}],"name":"echoAddresses","outputs":[{"name":"output","type":"address[]"}],"type":"function"},{"constant":true,"inputs":[{"name":"input","type":"uint24[23]"}],"name":"echoFancyInts","outputs":[{"name":"output","type":"uint24[23]"}],"type":"function"},{"constant":true,"inputs":[{"name":"input","type":"int256[]"}],"name":"echoInts","outputs":[{"name":"output","type":"int256[]"}],"type":"function"},{"constant":true,"inputs":[{"name":"input","type":"bool[]"}],"name":"echoBools","outputs":[{"name":"output","type":"bool[]"}],"type":"function"}]`,
253249
`
254250
// Generate a new random account and a funded simulator
255-
key := crypto.NewKey(rand.Reader)
256-
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: key.Address, Balance: big.NewInt(10000000000)})
257-
258-
// Convert the tester key to an authorized transactor for ease of use
251+
key, _ := crypto.GenerateKey()
259252
auth := bind.NewKeyedTransactor(key)
253+
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: auth.From, Balance: big.NewInt(10000000000)})
260254
261255
// Deploy a slice tester contract and execute a n array call on it
262256
_, _, slicer, err := DeploySlicer(auth, sim)
@@ -265,10 +259,10 @@ var bindTests = []struct {
265259
}
266260
sim.Commit()
267261
268-
if out, err := slicer.EchoAddresses(nil, []common.Address{key.Address, common.Address{}}); err != nil {
262+
if out, err := slicer.EchoAddresses(nil, []common.Address{auth.From, common.Address{}}); err != nil {
269263
t.Fatalf("Failed to call slice echoer: %v", err)
270-
} else if !reflect.DeepEqual(out, []common.Address{key.Address, common.Address{}}) {
271-
t.Fatalf("Slice return mismatch: have %v, want %v", out, []common.Address{key.Address, common.Address{}})
264+
} else if !reflect.DeepEqual(out, []common.Address{auth.From, common.Address{}}) {
265+
t.Fatalf("Slice return mismatch: have %v, want %v", out, []common.Address{auth.From, common.Address{}})
272266
}
273267
`,
274268
},
@@ -288,11 +282,9 @@ var bindTests = []struct {
288282
`[{"constant":true,"inputs":[],"name":"caller","outputs":[{"name":"","type":"address"}],"type":"function"}]`,
289283
`
290284
// Generate a new random account and a funded simulator
291-
key := crypto.NewKey(rand.Reader)
292-
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: key.Address, Balance: big.NewInt(10000000000)})
293-
294-
// Convert the tester key to an authorized transactor for ease of use
285+
key, _ := crypto.GenerateKey()
295286
auth := bind.NewKeyedTransactor(key)
287+
sim := backends.NewSimulatedBackend(core.GenesisAccount{Address: auth.From, Balance: big.NewInt(10000000000)})
296288
297289
// Deploy a default method invoker contract and execute its default method
298290
_, _, defaulter, err := DeployDefaulter(auth, sim)
@@ -306,8 +298,8 @@ var bindTests = []struct {
306298
307299
if caller, err := defaulter.Caller(nil); err != nil {
308300
t.Fatalf("Failed to call address retriever: %v", err)
309-
} else if (caller != key.Address) {
310-
t.Fatalf("Address mismatch: have %v, want %v", caller, key.Address)
301+
} else if (caller != auth.From) {
302+
t.Fatalf("Address mismatch: have %v, want %v", caller, auth.From)
311303
}
312304
`,
313305
},

‎accounts/account_manager.go‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,6 @@
1919
// This abstracts part of a user's interaction with an account she controls.
2020
package accounts
2121

22-
// Currently this is pretty much a passthrough to the KeyStore interface,
23-
// and accounts persistence is derived from stored keys' addresses
24-
2522
import (
2623
"crypto/ecdsa"
2724
crand "crypto/rand"
@@ -49,19 +46,26 @@ func (acc *Account) MarshalJSON() ([]byte, error) {
4946
}
5047

5148
type Manager struct {
52-
keyStore crypto.KeyStore
49+
keyStore keyStore
5350
unlocked map[common.Address]*unlocked
5451
mutex sync.RWMutex
5552
}
5653

5754
type unlocked struct {
58-
*crypto.Key
55+
*Key
5956
abort chan struct{}
6057
}
6158

62-
func NewManager(keyStore crypto.KeyStore) *Manager {
59+
func NewManager(keydir string, scryptN, scryptP int) *Manager {
60+
return &Manager{
61+
keyStore: newKeyStorePassphrase(keydir, scryptN, scryptP),
62+
unlocked: make(map[common.Address]*unlocked),
63+
}
64+
}
65+
66+
func NewPlaintextManager(keydir string) *Manager {
6367
return &Manager{
64-
keyStore: keyStore,
68+
keyStore: newKeyStorePlain(keydir),
6569
unlocked: make(map[common.Address]*unlocked),
6670
}
6771
}
@@ -216,19 +220,23 @@ func (am *Manager) Export(path string, addr common.Address, keyAuth string) erro
216220
}
217221

218222
func (am *Manager) Import(path string, keyAuth string) (Account, error) {
219-
privateKeyECDSA, err := crypto.LoadECDSA(path)
223+
priv, err := crypto.LoadECDSA(path)
220224
if err != nil {
221225
return Account{}, err
222226
}
223-
key := crypto.NewKeyFromECDSA(privateKeyECDSA)
224-
if err = am.keyStore.StoreKey(key, keyAuth); err != nil {
227+
return am.ImportECDSA(priv, keyAuth)
228+
}
229+
230+
func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, keyAuth string) (Account, error) {
231+
key := newKeyFromECDSA(priv)
232+
if err := am.keyStore.StoreKey(key, keyAuth); err != nil {
225233
return Account{}, err
226234
}
227235
return Account{Address: key.Address}, nil
228236
}
229237

230238
func (am *Manager) Update(addr common.Address, authFrom, authTo string) (err error) {
231-
var key *crypto.Key
239+
var key *Key
232240
key, err = am.keyStore.GetKey(addr, authFrom)
233241

234242
if err == nil {
@@ -241,8 +249,8 @@ func (am *Manager) Update(addr common.Address, authFrom, authTo string) (err err
241249
}
242250

243251
func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
244-
var key *crypto.Key
245-
key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)
252+
var key *Key
253+
key, err = importPreSaleKey(am.keyStore, keyJSON, password)
246254
if err != nil {
247255
return
248256
}

‎accounts/accounts_test.go‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,14 @@ import (
2121
"os"
2222
"testing"
2323
"time"
24-
25-
"github.com/ethereum/go-ethereum/crypto"
2624
)
2725

2826
var testSigData = make([]byte, 32)
2927

3028
func TestSign(t *testing.T) {
31-
dir, ks := tmpKeyStore(t, crypto.NewKeyStorePlain)
29+
dir, am := tmpManager(t, false)
3230
defer os.RemoveAll(dir)
3331

34-
am := NewManager(ks)
3532
pass := "" // not used but required by API
3633
a1, err := am.NewAccount(pass)
3734
am.Unlock(a1.Address, "")
@@ -43,10 +40,9 @@ func TestSign(t *testing.T) {
4340
}
4441

4542
func TestTimedUnlock(t *testing.T) {
46-
dir, ks := tmpKeyStore(t, crypto.NewKeyStorePlain)
43+
dir, am := tmpManager(t, false)
4744
defer os.RemoveAll(dir)
4845

49-
am := NewManager(ks)
5046
pass := "foo"
5147
a1, err := am.NewAccount(pass)
5248

@@ -76,10 +72,9 @@ func TestTimedUnlock(t *testing.T) {
7672
}
7773

7874
func TestOverrideUnlock(t *testing.T) {
79-
dir, ks := tmpKeyStore(t, crypto.NewKeyStorePlain)
75+
dir, am := tmpManager(t, false)
8076
defer os.RemoveAll(dir)
8177

82-
am := NewManager(ks)
8378
pass := "foo"
8479
a1, err := am.NewAccount(pass)
8580

@@ -115,11 +110,10 @@ func TestOverrideUnlock(t *testing.T) {
115110

116111
// This test should fail under -race if signing races the expiration goroutine.
117112
func TestSignRace(t *testing.T) {
118-
dir, ks := tmpKeyStore(t, crypto.NewKeyStorePlain)
113+
dir, am := tmpManager(t, false)
119114
defer os.RemoveAll(dir)
120115

121116
// Create a test account.
122-
am := NewManager(ks)
123117
a1, err := am.NewAccount("")
124118
if err != nil {
125119
t.Fatal("could not create the test account", err)
@@ -141,10 +135,14 @@ func TestSignRace(t *testing.T) {
141135
t.Errorf("Account did not lock within the timeout")
142136
}
143137

144-
func tmpKeyStore(t *testing.T, new func(string) crypto.KeyStore) (string, crypto.KeyStore) {
138+
func tmpManager(t *testing.T, encrypted bool) (string, *Manager) {
145139
d, err := ioutil.TempDir("", "eth-keystore-test")
146140
if err != nil {
147141
t.Fatal(err)
148142
}
143+
new := NewPlaintextManager
144+
if encrypted {
145+
new = func(kd string) *Manager { return NewManager(kd, LightScryptN, LightScryptP) }
146+
}
149147
return d, new(d)
150148
}

crypto/key.go renamed to accounts/key.go

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
package crypto
17+
package accounts
1818

1919
import (
2020
"bytes"
@@ -25,6 +25,7 @@ import (
2525
"strings"
2626

2727
"github.com/ethereum/go-ethereum/common"
28+
"github.com/ethereum/go-ethereum/crypto"
2829
"github.com/ethereum/go-ethereum/crypto/secp256k1"
2930
"github.com/pborman/uuid"
3031
)
@@ -42,6 +43,16 @@ type Key struct {
4243
PrivateKey *ecdsa.PrivateKey
4344
}
4445

46+
type keyStore interface {
47+
// create new key using io.Reader entropy source and optionally using auth string
48+
GenerateNewKey(io.Reader, string) (*Key, error)
49+
GetKey(common.Address, string) (*Key, error) // get key from addr and auth string
50+
GetKeyAddresses() ([]common.Address, error) // get all addresses
51+
StoreKey(*Key, string) error // store key optionally using auth string
52+
DeleteKey(common.Address, string) error // delete key by addr and auth string
53+
Cleanup(keyAddr common.Address) (err error)
54+
}
55+
4556
type plainKeyJSON struct {
4657
Address string `json:"address"`
4758
PrivateKey string `json:"privatekey"`
@@ -87,7 +98,7 @@ type scryptParamsJSON struct {
8798
func (k *Key) MarshalJSON() (j []byte, err error) {
8899
jStruct := plainKeyJSON{
89100
hex.EncodeToString(k.Address[:]),
90-
hex.EncodeToString(FromECDSA(k.PrivateKey)),
101+
hex.EncodeToString(crypto.FromECDSA(k.PrivateKey)),
91102
k.Id.String(),
92103
version,
93104
}
@@ -116,16 +127,16 @@ func (k *Key) UnmarshalJSON(j []byte) (err error) {
116127
}
117128

118129
k.Address = common.BytesToAddress(addr)
119-
k.PrivateKey = ToECDSA(privkey)
130+
k.PrivateKey = crypto.ToECDSA(privkey)
120131

121132
return nil
122133
}
123134

124-
func NewKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
135+
func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
125136
id := uuid.NewRandom()
126137
key := &Key{
127138
Id: id,
128-
Address: PubkeyToAddress(privateKeyECDSA.PublicKey),
139+
Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
129140
PrivateKey: privateKeyECDSA,
130141
}
131142
return key
@@ -143,7 +154,7 @@ func NewKey(rand io.Reader) *Key {
143154
panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
144155
}
145156

146-
return NewKeyFromECDSA(privateKeyECDSA)
157+
return newKeyFromECDSA(privateKeyECDSA)
147158
}
148159

149160
// generate key whose address fits into < 155 bits so it can fit into
@@ -160,7 +171,7 @@ func NewKeyForDirectICAP(rand io.Reader) *Key {
160171
if err != nil {
161172
panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
162173
}
163-
key := NewKeyFromECDSA(privateKeyECDSA)
174+
key := newKeyFromECDSA(privateKeyECDSA)
164175
if !strings.HasPrefix(key.Address.Hex(), "0x00") {
165176
return NewKeyForDirectICAP(rand)
166177
}

0 commit comments

Comments
 (0)