mirror of https://github.com/ethereum/go-ethereum
parent
564b60520c
commit
833e4d1319
@ -1,350 +0,0 @@ |
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package accounts implements encrypted storage of secp256k1 private keys.
|
||||
//
|
||||
// Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
|
||||
// See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
|
||||
package accounts |
||||
|
||||
import ( |
||||
"crypto/ecdsa" |
||||
crand "crypto/rand" |
||||
"encoding/json" |
||||
"errors" |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
"runtime" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/ethereum/go-ethereum/common" |
||||
"github.com/ethereum/go-ethereum/crypto" |
||||
) |
||||
|
||||
var ( |
||||
ErrLocked = errors.New("account is locked") |
||||
ErrNoMatch = errors.New("no key for given address or file") |
||||
ErrDecrypt = errors.New("could not decrypt key with given passphrase") |
||||
) |
||||
|
||||
// Account represents a stored key.
|
||||
// When used as an argument, it selects a unique key file to act on.
|
||||
type Account struct { |
||||
Address common.Address // Ethereum account address derived from the key
|
||||
|
||||
// File contains the key file name.
|
||||
// When Acccount is used as an argument to select a key, File can be left blank to
|
||||
// select just by address or set to the basename or absolute path of a file in the key
|
||||
// directory. Accounts returned by Manager will always contain an absolute path.
|
||||
File string |
||||
} |
||||
|
||||
func (acc *Account) MarshalJSON() ([]byte, error) { |
||||
return []byte(`"` + acc.Address.Hex() + `"`), nil |
||||
} |
||||
|
||||
func (acc *Account) UnmarshalJSON(raw []byte) error { |
||||
return json.Unmarshal(raw, &acc.Address) |
||||
} |
||||
|
||||
// Manager manages a key storage directory on disk.
|
||||
type Manager struct { |
||||
cache *addrCache |
||||
keyStore keyStore |
||||
mu sync.RWMutex |
||||
unlocked map[common.Address]*unlocked |
||||
} |
||||
|
||||
type unlocked struct { |
||||
*Key |
||||
abort chan struct{} |
||||
} |
||||
|
||||
// NewManager creates a manager for the given directory.
|
||||
func NewManager(keydir string, scryptN, scryptP int) *Manager { |
||||
keydir, _ = filepath.Abs(keydir) |
||||
am := &Manager{keyStore: &keyStorePassphrase{keydir, scryptN, scryptP}} |
||||
am.init(keydir) |
||||
return am |
||||
} |
||||
|
||||
// NewPlaintextManager creates a manager for the given directory.
|
||||
// Deprecated: Use NewManager.
|
||||
func NewPlaintextManager(keydir string) *Manager { |
||||
keydir, _ = filepath.Abs(keydir) |
||||
am := &Manager{keyStore: &keyStorePlain{keydir}} |
||||
am.init(keydir) |
||||
return am |
||||
} |
||||
|
||||
func (am *Manager) init(keydir string) { |
||||
am.unlocked = make(map[common.Address]*unlocked) |
||||
am.cache = newAddrCache(keydir) |
||||
// TODO: In order for this finalizer to work, there must be no references
|
||||
// to am. addrCache doesn't keep a reference but unlocked keys do,
|
||||
// so the finalizer will not trigger until all timed unlocks have expired.
|
||||
runtime.SetFinalizer(am, func(m *Manager) { |
||||
m.cache.close() |
||||
}) |
||||
} |
||||
|
||||
// HasAddress reports whether a key with the given address is present.
|
||||
func (am *Manager) HasAddress(addr common.Address) bool { |
||||
return am.cache.hasAddress(addr) |
||||
} |
||||
|
||||
// Accounts returns all key files present in the directory.
|
||||
func (am *Manager) Accounts() []Account { |
||||
return am.cache.accounts() |
||||
} |
||||
|
||||
// Delete deletes the key matched by account if the passphrase is correct.
|
||||
// If the account contains no filename, the address must match a unique key.
|
||||
func (am *Manager) Delete(a Account, passphrase string) error { |
||||
// Decrypting the key isn't really necessary, but we do
|
||||
// it anyway to check the password and zero out the key
|
||||
// immediately afterwards.
|
||||
a, key, err := am.getDecryptedKey(a, passphrase) |
||||
if key != nil { |
||||
zeroKey(key.PrivateKey) |
||||
} |
||||
if err != nil { |
||||
return err |
||||
} |
||||
// The order is crucial here. The key is dropped from the
|
||||
// cache after the file is gone so that a reload happening in
|
||||
// between won't insert it into the cache again.
|
||||
err = os.Remove(a.File) |
||||
if err == nil { |
||||
am.cache.delete(a) |
||||
} |
||||
return err |
||||
} |
||||
|
||||
// Sign calculates a ECDSA signature for the given hash. The produced signature
|
||||
// is in the [R || S || V] format where V is 0 or 1.
|
||||
func (am *Manager) Sign(addr common.Address, hash []byte) ([]byte, error) { |
||||
am.mu.RLock() |
||||
defer am.mu.RUnlock() |
||||
|
||||
unlockedKey, found := am.unlocked[addr] |
||||
if !found { |
||||
return nil, ErrLocked |
||||
} |
||||
return crypto.Sign(hash, unlockedKey.PrivateKey) |
||||
} |
||||
|
||||
// SignWithPassphrase signs hash if the private key matching the given address
|
||||
// can be decrypted with the given passphrase. The produced signature is in the
|
||||
// [R || S || V] format where V is 0 or 1.
|
||||
func (am *Manager) SignWithPassphrase(a Account, passphrase string, hash []byte) (signature []byte, err error) { |
||||
_, key, err := am.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer zeroKey(key.PrivateKey) |
||||
return crypto.Sign(hash, key.PrivateKey) |
||||
} |
||||
|
||||
// Unlock unlocks the given account indefinitely.
|
||||
func (am *Manager) Unlock(a Account, passphrase string) error { |
||||
return am.TimedUnlock(a, passphrase, 0) |
||||
} |
||||
|
||||
// Lock removes the private key with the given address from memory.
|
||||
func (am *Manager) Lock(addr common.Address) error { |
||||
am.mu.Lock() |
||||
if unl, found := am.unlocked[addr]; found { |
||||
am.mu.Unlock() |
||||
am.expire(addr, unl, time.Duration(0)*time.Nanosecond) |
||||
} else { |
||||
am.mu.Unlock() |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// TimedUnlock unlocks the given account with the passphrase. The account
|
||||
// stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
|
||||
// until the program exits. The account must match a unique key file.
|
||||
//
|
||||
// If the account address is already unlocked for a duration, TimedUnlock extends or
|
||||
// shortens the active unlock timeout. If the address was previously unlocked
|
||||
// indefinitely the timeout is not altered.
|
||||
func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Duration) error { |
||||
a, key, err := am.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
am.mu.Lock() |
||||
defer am.mu.Unlock() |
||||
u, found := am.unlocked[a.Address] |
||||
if found { |
||||
if u.abort == nil { |
||||
// The address was unlocked indefinitely, so unlocking
|
||||
// it with a timeout would be confusing.
|
||||
zeroKey(key.PrivateKey) |
||||
return nil |
||||
} else { |
||||
// Terminate the expire goroutine and replace it below.
|
||||
close(u.abort) |
||||
} |
||||
} |
||||
if timeout > 0 { |
||||
u = &unlocked{Key: key, abort: make(chan struct{})} |
||||
go am.expire(a.Address, u, timeout) |
||||
} else { |
||||
u = &unlocked{Key: key} |
||||
} |
||||
am.unlocked[a.Address] = u |
||||
return nil |
||||
} |
||||
|
||||
// Find resolves the given account into a unique entry in the keystore.
|
||||
func (am *Manager) Find(a Account) (Account, error) { |
||||
am.cache.maybeReload() |
||||
am.cache.mu.Lock() |
||||
a, err := am.cache.find(a) |
||||
am.cache.mu.Unlock() |
||||
return a, err |
||||
} |
||||
|
||||
func (am *Manager) getDecryptedKey(a Account, auth string) (Account, *Key, error) { |
||||
a, err := am.Find(a) |
||||
if err != nil { |
||||
return a, nil, err |
||||
} |
||||
key, err := am.keyStore.GetKey(a.Address, a.File, auth) |
||||
return a, key, err |
||||
} |
||||
|
||||
func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) { |
||||
t := time.NewTimer(timeout) |
||||
defer t.Stop() |
||||
select { |
||||
case <-u.abort: |
||||
// just quit
|
||||
case <-t.C: |
||||
am.mu.Lock() |
||||
// only drop if it's still the same key instance that dropLater
|
||||
// was launched with. we can check that using pointer equality
|
||||
// because the map stores a new pointer every time the key is
|
||||
// unlocked.
|
||||
if am.unlocked[addr] == u { |
||||
zeroKey(u.PrivateKey) |
||||
delete(am.unlocked, addr) |
||||
} |
||||
am.mu.Unlock() |
||||
} |
||||
} |
||||
|
||||
// NewAccount generates a new key and stores it into the key directory,
|
||||
// encrypting it with the passphrase.
|
||||
func (am *Manager) NewAccount(passphrase string) (Account, error) { |
||||
_, account, err := storeNewKey(am.keyStore, crand.Reader, passphrase) |
||||
if err != nil { |
||||
return Account{}, err |
||||
} |
||||
// Add the account to the cache immediately rather
|
||||
// than waiting for file system notifications to pick it up.
|
||||
am.cache.add(account) |
||||
return account, nil |
||||
} |
||||
|
||||
// AccountByIndex returns the ith account.
|
||||
func (am *Manager) AccountByIndex(i int) (Account, error) { |
||||
accounts := am.Accounts() |
||||
if i < 0 || i >= len(accounts) { |
||||
return Account{}, fmt.Errorf("account index %d out of range [0, %d]", i, len(accounts)-1) |
||||
} |
||||
return accounts[i], nil |
||||
} |
||||
|
||||
// Export exports as a JSON key, encrypted with newPassphrase.
|
||||
func (am *Manager) Export(a Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { |
||||
_, key, err := am.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
var N, P int |
||||
if store, ok := am.keyStore.(*keyStorePassphrase); ok { |
||||
N, P = store.scryptN, store.scryptP |
||||
} else { |
||||
N, P = StandardScryptN, StandardScryptP |
||||
} |
||||
return EncryptKey(key, newPassphrase, N, P) |
||||
} |
||||
|
||||
// Import stores the given encrypted JSON key into the key directory.
|
||||
func (am *Manager) Import(keyJSON []byte, passphrase, newPassphrase string) (Account, error) { |
||||
key, err := DecryptKey(keyJSON, passphrase) |
||||
if key != nil && key.PrivateKey != nil { |
||||
defer zeroKey(key.PrivateKey) |
||||
} |
||||
if err != nil { |
||||
return Account{}, err |
||||
} |
||||
return am.importKey(key, newPassphrase) |
||||
} |
||||
|
||||
// ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
|
||||
func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Account, error) { |
||||
key := newKeyFromECDSA(priv) |
||||
if am.cache.hasAddress(key.Address) { |
||||
return Account{}, fmt.Errorf("account already exists") |
||||
} |
||||
|
||||
return am.importKey(key, passphrase) |
||||
} |
||||
|
||||
func (am *Manager) importKey(key *Key, passphrase string) (Account, error) { |
||||
a := Account{Address: key.Address, File: am.keyStore.JoinPath(keyFileName(key.Address))} |
||||
if err := am.keyStore.StoreKey(a.File, key, passphrase); err != nil { |
||||
return Account{}, err |
||||
} |
||||
am.cache.add(a) |
||||
return a, nil |
||||
} |
||||
|
||||
// Update changes the passphrase of an existing account.
|
||||
func (am *Manager) Update(a Account, passphrase, newPassphrase string) error { |
||||
a, key, err := am.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
return am.keyStore.StoreKey(a.File, key, newPassphrase) |
||||
} |
||||
|
||||
// ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
|
||||
// a key file in the key directory. The key file is encrypted with the same passphrase.
|
||||
func (am *Manager) ImportPreSaleKey(keyJSON []byte, passphrase string) (Account, error) { |
||||
a, _, err := importPreSaleKey(am.keyStore, keyJSON, passphrase) |
||||
if err != nil { |
||||
return a, err |
||||
} |
||||
am.cache.add(a) |
||||
return a, nil |
||||
} |
||||
|
||||
// zeroKey zeroes a private key in memory.
|
||||
func zeroKey(k *ecdsa.PrivateKey) { |
||||
b := k.D.Bits() |
||||
for i := range b { |
||||
b[i] = 0 |
||||
} |
||||
} |
@ -0,0 +1,179 @@ |
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package accounts implements high level Ethereum account management.
|
||||
package accounts |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"errors" |
||||
"math/big" |
||||
"reflect" |
||||
"sync" |
||||
|
||||
"github.com/ethereum/go-ethereum/common" |
||||
"github.com/ethereum/go-ethereum/core/types" |
||||
) |
||||
|
||||
// ErrUnknownAccount is returned for any requested operation for which no backend
|
||||
// provides the specified account.
|
||||
var ErrUnknownAccount = errors.New("unknown account") |
||||
|
||||
// ErrNotSupported is returned when an operation is requested from an account
|
||||
// backend that it does not support.
|
||||
var ErrNotSupported = errors.New("not supported") |
||||
|
||||
// Account represents a stored key.
|
||||
// When used as an argument, it selects a unique key to act on.
|
||||
type Account struct { |
||||
Address common.Address // Ethereum account address derived from the key
|
||||
URL string // Optional resource locator within a backend
|
||||
backend Backend // Backend where this account originates from
|
||||
} |
||||
|
||||
func (acc *Account) MarshalJSON() ([]byte, error) { |
||||
return []byte(`"` + acc.Address.Hex() + `"`), nil |
||||
} |
||||
|
||||
func (acc *Account) UnmarshalJSON(raw []byte) error { |
||||
return json.Unmarshal(raw, &acc.Address) |
||||
} |
||||
|
||||
// Manager is an overarching account manager that can communicate with various
|
||||
// backends for signing transactions.
|
||||
type Manager struct { |
||||
backends []Backend // List of currently registered backends (ordered by registration)
|
||||
index map[reflect.Type]Backend // Set of currently registered backends
|
||||
lock sync.RWMutex |
||||
} |
||||
|
||||
// NewManager creates a generic account manager to sign transaction via various
|
||||
// supported backends.
|
||||
func NewManager(backends ...Backend) *Manager { |
||||
am := &Manager{ |
||||
backends: backends, |
||||
index: make(map[reflect.Type]Backend), |
||||
} |
||||
for _, backend := range backends { |
||||
am.index[reflect.TypeOf(backend)] = backend |
||||
} |
||||
return am |
||||
} |
||||
|
||||
// Backend retrieves the backend with the given type from the account manager.
|
||||
func (am *Manager) Backend(backend reflect.Type) Backend { |
||||
return am.index[backend] |
||||
} |
||||
|
||||
// Accounts returns all signer accounts registered under this account manager.
|
||||
func (am *Manager) Accounts() []Account { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
var all []Account |
||||
for _, backend := range am.backends { // TODO(karalabe): cache these after subscriptions are in
|
||||
accounts := backend.Accounts() |
||||
for i := 0; i < len(accounts); i++ { |
||||
accounts[i].backend = backend |
||||
} |
||||
all = append(all, accounts...) |
||||
} |
||||
return all |
||||
} |
||||
|
||||
// HasAddress reports whether a key with the given address is present.
|
||||
func (am *Manager) HasAddress(addr common.Address) bool { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
for _, backend := range am.backends { |
||||
if backend.HasAddress(addr) { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
|
||||
// SignHash requests the account manager to get the hash signed with an arbitrary
|
||||
// signing backend holding the authorization for the specified account.
|
||||
func (am *Manager) SignHash(acc Account, hash []byte) ([]byte, error) { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
if err := am.ensureBackend(&acc); err != nil { |
||||
return nil, err |
||||
} |
||||
return acc.backend.SignHash(acc, hash) |
||||
} |
||||
|
||||
// SignTx requests the account manager to get the transaction signed with an
|
||||
// arbitrary signing backend holding the authorization for the specified account.
|
||||
func (am *Manager) SignTx(acc Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
if err := am.ensureBackend(&acc); err != nil { |
||||
return nil, err |
||||
} |
||||
return acc.backend.SignTx(acc, tx, chainID) |
||||
} |
||||
|
||||
// SignHashWithPassphrase requests the account manager to get the hash signed with
|
||||
// an arbitrary signing backend holding the authorization for the specified account.
|
||||
func (am *Manager) SignHashWithPassphrase(acc Account, passphrase string, hash []byte) ([]byte, error) { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
if err := am.ensureBackend(&acc); err != nil { |
||||
return nil, err |
||||
} |
||||
return acc.backend.SignHashWithPassphrase(acc, passphrase, hash) |
||||
} |
||||
|
||||
// SignTxWithPassphrase requests the account manager to get the transaction signed
|
||||
// with an arbitrary signing backend holding the authorization for the specified
|
||||
// account.
|
||||
func (am *Manager) SignTxWithPassphrase(acc Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { |
||||
am.lock.RLock() |
||||
defer am.lock.RUnlock() |
||||
|
||||
if err := am.ensureBackend(&acc); err != nil { |
||||
return nil, err |
||||
} |
||||
return acc.backend.SignTxWithPassphrase(acc, passphrase, tx, chainID) |
||||
} |
||||
|
||||
// ensureBackend ensures that the account has a correctly set backend and that
|
||||
// it is still alive.
|
||||
//
|
||||
// Please note, this method assumes the manager lock is held!
|
||||
func (am *Manager) ensureBackend(acc *Account) error { |
||||
// If we have a backend, make sure it's still live
|
||||
if acc.backend != nil { |
||||
if _, exists := am.index[reflect.TypeOf(acc.backend)]; !exists { |
||||
return ErrUnknownAccount |
||||
} |
||||
return nil |
||||
} |
||||
// If we don't have a known backend, look up one that can service it
|
||||
for _, backend := range am.backends { |
||||
if backend.HasAddress(acc.Address) { // TODO(karalabe): this assumes unique addresses per backend
|
||||
acc.backend = backend |
||||
return nil |
||||
} |
||||
} |
||||
return ErrUnknownAccount |
||||
} |
@ -0,0 +1,88 @@ |
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package accounts |
||||
|
||||
import ( |
||||
"math/big" |
||||
|
||||
"github.com/ethereum/go-ethereum/common" |
||||
"github.com/ethereum/go-ethereum/core/types" |
||||
) |
||||
|
||||
// Backend is an "account provider" that can specify a batch of accounts it can
|
||||
// sign transactions with and upon request, do so.
|
||||
type Backend interface { |
||||
// Accounts retrieves the list of signing accounts the backend is currently aware of.
|
||||
Accounts() []Account |
||||
|
||||
// HasAddress reports whether an account with the given address is present.
|
||||
HasAddress(addr common.Address) bool |
||||
|
||||
// SignHash requests the backend to sign the given hash.
|
||||
//
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
//
|
||||
// If the backend requires additional authentication to sign the request (e.g.
|
||||
// a password to decrypt the account, or a PIN code o verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
SignHash(acc Account, hash []byte) ([]byte, error) |
||||
|
||||
// SignTx requests the backend to sign the given transaction.
|
||||
//
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
//
|
||||
// If the backend requires additional authentication to sign the request (e.g.
|
||||
// a password to decrypt the account, or a PIN code o verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
SignTx(acc Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) |
||||
|
||||
// SignHashWithPassphrase requests the backend to sign the given transaction with
|
||||
// the given passphrase as extra authentication information.
|
||||
//
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
SignHashWithPassphrase(acc Account, passphrase string, hash []byte) ([]byte, error) |
||||
|
||||
// SignTxWithPassphrase requests the backend to sign the given transaction, with the
|
||||
// given passphrase as extra authentication information.
|
||||
//
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
SignTxWithPassphrase(acc Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) |
||||
|
||||
// TODO(karalabe,fjl): watching and caching needs the Go subscription system
|
||||
// Watch requests the backend to send a notification to the specified channel whenever
|
||||
// an new account appears or an existing one disappears.
|
||||
//Watch(chan AccountEvent) error
|
||||
|
||||
// Unwatch requests the backend stop sending notifications to the given channel.
|
||||
//Unwatch(chan AccountEvent) error
|
||||
} |
||||
|
||||
// TODO(karalabe,fjl): watching and caching needs the Go subscription system
|
||||
// type AccountEvent struct {
|
||||
// Account Account
|
||||
// Added bool
|
||||
// }
|
@ -0,0 +1,41 @@ |
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package accounts |
||||
|
||||
import "fmt" |
||||
|
||||
// AuthNeededError is returned by backends for signing requests where the user
|
||||
// is required to provide further authentication before signing can succeed.
|
||||
//
|
||||
// This usually means either that a password needs to be supplied, or perhaps a
|
||||
// one time PIN code displayed by some hardware device.
|
||||
type AuthNeededError struct { |
||||
Needed string // Extra authentication the user needs to provide
|
||||
} |
||||
|
||||
// NewAuthNeededError creates a new authentication error with the extra details
|
||||
// about the needed fields set.
|
||||
func NewAuthNeededError(needed string) error { |
||||
return &AuthNeededError{ |
||||
Needed: needed, |
||||
} |
||||
} |
||||
|
||||
// Error implements the standard error interfacel.
|
||||
func (err *AuthNeededError) Error() string { |
||||
return fmt.Sprintf("authentication needed: %s", err.Needed) |
||||
} |
@ -0,0 +1,362 @@ |
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package keystore implements encrypted storage of secp256k1 private keys.
|
||||
//
|
||||
// Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
|
||||
// See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
|
||||
package keystore |
||||
|
||||
import ( |
||||
"crypto/ecdsa" |
||||
crand "crypto/rand" |
||||
"errors" |
||||
"fmt" |
||||
"math/big" |
||||
"os" |
||||
"path/filepath" |
||||
"reflect" |
||||
"runtime" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/ethereum/go-ethereum/accounts" |
||||
"github.com/ethereum/go-ethereum/common" |
||||
"github.com/ethereum/go-ethereum/core/types" |
||||
"github.com/ethereum/go-ethereum/crypto" |
||||
) |
||||
|
||||
var ( |
||||
ErrNeedPasswordOrUnlock = accounts.NewAuthNeededError("password or unlock") |
||||
ErrNoMatch = errors.New("no key for given address or file") |
||||
ErrDecrypt = errors.New("could not decrypt key with given passphrase") |
||||
) |
||||
|
||||
// BackendType can be used to query the account manager for encrypted keystores.
|
||||
var BackendType = reflect.TypeOf(new(KeyStore)) |
||||
|
||||
// KeyStore manages a key storage directory on disk.
|
||||
type KeyStore struct { |
||||
cache *addressCache |
||||
keyStore keyStore |
||||
mu sync.RWMutex |
||||
unlocked map[common.Address]*unlocked |
||||
} |
||||
|
||||
type unlocked struct { |
||||
*Key |
||||
abort chan struct{} |
||||
} |
||||
|
||||
// NewKeyStore creates a keystore for the given directory.
|
||||
func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore { |
||||
keydir, _ = filepath.Abs(keydir) |
||||
ks := &KeyStore{keyStore: &keyStorePassphrase{keydir, scryptN, scryptP}} |
||||
ks.init(keydir) |
||||
return ks |
||||
} |
||||
|
||||
// NewPlaintextKeyStore creates a keystore for the given directory.
|
||||
// Deprecated: Use NewKeyStore.
|
||||
func NewPlaintextKeyStore(keydir string) *KeyStore { |
||||
keydir, _ = filepath.Abs(keydir) |
||||
ks := &KeyStore{keyStore: &keyStorePlain{keydir}} |
||||
ks.init(keydir) |
||||
return ks |
||||
} |
||||
|
||||
func (ks *KeyStore) init(keydir string) { |
||||
ks.unlocked = make(map[common.Address]*unlocked) |
||||
ks.cache = newAddrCache(keydir) |
||||
// TODO: In order for this finalizer to work, there must be no references
|
||||
// to ks. addressCache doesn't keep a reference but unlocked keys do,
|
||||
// so the finalizer will not trigger until all timed unlocks have expired.
|
||||
runtime.SetFinalizer(ks, func(m *KeyStore) { |
||||
m.cache.close() |
||||
}) |
||||
} |
||||
|
||||
// HasAddress reports whether a key with the given address is present.
|
||||
func (ks *KeyStore) HasAddress(addr common.Address) bool { |
||||
return ks.cache.hasAddress(addr) |
||||
} |
||||
|
||||
// Accounts returns all key files present in the directory.
|
||||
func (ks *KeyStore) Accounts() []accounts.Account { |
||||
return ks.cache.accounts() |
||||
} |
||||
|
||||
// Delete deletes the key matched by account if the passphrase is correct.
|
||||
// If the account contains no filename, the address must match a unique key.
|
||||
func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error { |
||||
// Decrypting the key isn't really necessary, but we do
|
||||
// it anyway to check the password and zero out the key
|
||||
// immediately afterwards.
|
||||
a, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if key != nil { |
||||
zeroKey(key.PrivateKey) |
||||
} |
||||
if err != nil { |
||||
return err |
||||
} |
||||
// The order is crucial here. The key is dropped from the
|
||||
// cache after the file is gone so that a reload happening in
|
||||
// between won't insert it into the cache again.
|
||||
err = os.Remove(a.URL) |
||||
if err == nil { |
||||
ks.cache.delete(a) |
||||
} |
||||
return err |
||||
} |
||||
|
||||
// SignHash calculates a ECDSA signature for the given hash. The produced
|
||||
// signature is in the [R || S || V] format where V is 0 or 1.
|
||||
func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) { |
||||
// Look up the key to sign with and abort if it cannot be found
|
||||
ks.mu.RLock() |
||||
defer ks.mu.RUnlock() |
||||
|
||||
unlockedKey, found := ks.unlocked[a.Address] |
||||
if !found { |
||||
return nil, ErrNeedPasswordOrUnlock |
||||
} |
||||
// Sign the hash using plain ECDSA operations
|
||||
return crypto.Sign(hash, unlockedKey.PrivateKey) |
||||
} |
||||
|
||||
// SignTx signs the given transaction with the requested account.
|
||||
func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { |
||||
// Look up the key to sign with and abort if it cannot be found
|
||||
ks.mu.RLock() |
||||
defer ks.mu.RUnlock() |
||||
|
||||
unlockedKey, found := ks.unlocked[a.Address] |
||||
if !found { |
||||
return nil, ErrNeedPasswordOrUnlock |
||||
} |
||||
// Depending on the presence of the chain ID, sign with EIP155 or homestead
|
||||
if chainID != nil { |
||||
return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey) |
||||
} |
||||
return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey) |
||||
} |
||||
|
||||
// SignHashWithPassphrase signs hash if the private key matching the given address
|
||||
// can be decrypted with the given passphrase. The produced signature is in the
|
||||
// [R || S || V] format where V is 0 or 1.
|
||||
func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) { |
||||
_, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer zeroKey(key.PrivateKey) |
||||
return crypto.Sign(hash, key.PrivateKey) |
||||
} |
||||
|
||||
// SignTxWithPassphrase signs the transaction if the private key matching the
|
||||
// given address can be decrypted with the given passphrase.
|
||||
func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { |
||||
_, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer zeroKey(key.PrivateKey) |
||||
|
||||
// Depending on the presence of the chain ID, sign with EIP155 or homestead
|
||||
if chainID != nil { |
||||
return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey) |
||||
} |
||||
return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey) |
||||
} |
||||
|
||||
// Unlock unlocks the given account indefinitely.
|
||||
func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error { |
||||
return ks.TimedUnlock(a, passphrase, 0) |
||||
} |
||||
|
||||
// Lock removes the private key with the given address from memory.
|
||||
func (ks *KeyStore) Lock(addr common.Address) error { |
||||
ks.mu.Lock() |
||||
if unl, found := ks.unlocked[addr]; found { |
||||
ks.mu.Unlock() |
||||
ks.expire(addr, unl, time.Duration(0)*time.Nanosecond) |
||||
} else { |
||||
ks.mu.Unlock() |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// TimedUnlock unlocks the given account with the passphrase. The account
|
||||
// stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
|
||||
// until the program exits. The account must match a unique key file.
|
||||
//
|
||||
// If the account address is already unlocked for a duration, TimedUnlock extends or
|
||||
// shortens the active unlock timeout. If the address was previously unlocked
|
||||
// indefinitely the timeout is not altered.
|
||||
func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error { |
||||
a, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
ks.mu.Lock() |
||||
defer ks.mu.Unlock() |
||||
u, found := ks.unlocked[a.Address] |
||||
if found { |
||||
if u.abort == nil { |
||||
// The address was unlocked indefinitely, so unlocking
|
||||
// it with a timeout would be confusing.
|
||||
zeroKey(key.PrivateKey) |
||||
return nil |
||||
} else { |
||||
// Terminate the expire goroutine and replace it below.
|
||||
close(u.abort) |
||||
} |
||||
} |
||||
if timeout > 0 { |
||||
u = &unlocked{Key: key, abort: make(chan struct{})} |
||||
go ks.expire(a.Address, u, timeout) |
||||
} else { |
||||
u = &unlocked{Key: key} |
||||
} |
||||
ks.unlocked[a.Address] = u |
||||
return nil |
||||
} |
||||
|
||||
// Find resolves the given account into a unique entry in the keystore.
|
||||
func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) { |
||||
ks.cache.maybeReload() |
||||
ks.cache.mu.Lock() |
||||
a, err := ks.cache.find(a) |
||||
ks.cache.mu.Unlock() |
||||
return a, err |
||||
} |
||||
|
||||
func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) { |
||||
a, err := ks.Find(a) |
||||
if err != nil { |
||||
return a, nil, err |
||||
} |
||||
key, err := ks.keyStore.GetKey(a.Address, a.URL, auth) |
||||
return a, key, err |
||||
} |
||||
|
||||
func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) { |
||||
t := time.NewTimer(timeout) |
||||
defer t.Stop() |
||||
select { |
||||
case <-u.abort: |
||||
// just quit
|
||||
case <-t.C: |
||||
ks.mu.Lock() |
||||
// only drop if it's still the same key instance that dropLater
|
||||
// was launched with. we can check that using pointer equality
|
||||
// because the map stores a new pointer every time the key is
|
||||
// unlocked.
|
||||
if ks.unlocked[addr] == u { |
||||
zeroKey(u.PrivateKey) |
||||
delete(ks.unlocked, addr) |
||||
} |
||||
ks.mu.Unlock() |
||||
} |
||||
} |
||||
|
||||
// NewAccount generates a new key and stores it into the key directory,
|
||||
// encrypting it with the passphrase.
|
||||
func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) { |
||||
_, account, err := storeNewKey(ks.keyStore, crand.Reader, passphrase) |
||||
if err != nil { |
||||
return accounts.Account{}, err |
||||
} |
||||
// Add the account to the cache immediately rather
|
||||
// than waiting for file system notifications to pick it up.
|
||||
ks.cache.add(account) |
||||
return account, nil |
||||
} |
||||
|
||||
// Export exports as a JSON key, encrypted with newPassphrase.
|
||||
func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { |
||||
_, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
var N, P int |
||||
if store, ok := ks.keyStore.(*keyStorePassphrase); ok { |
||||
N, P = store.scryptN, store.scryptP |
||||
} else { |
||||
N, P = StandardScryptN, StandardScryptP |
||||
} |
||||
return EncryptKey(key, newPassphrase, N, P) |
||||
} |
||||
|
||||
// Import stores the given encrypted JSON key into the key directory.
|
||||
func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) { |
||||
key, err := DecryptKey(keyJSON, passphrase) |
||||
if key != nil && key.PrivateKey != nil { |
||||
defer zeroKey(key.PrivateKey) |
||||
} |
||||
if err != nil { |
||||
return accounts.Account{}, err |
||||
} |
||||
return ks.importKey(key, newPassphrase) |
||||
} |
||||
|
||||
// ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
|
||||
func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) { |
||||
key := newKeyFromECDSA(priv) |
||||
if ks.cache.hasAddress(key.Address) { |
||||
return accounts.Account{}, fmt.Errorf("account already exists") |
||||
} |
||||
|
||||
return ks.importKey(key, passphrase) |
||||
} |
||||
|
||||
func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) { |
||||
a := accounts.Account{Address: key.Address, URL: ks.keyStore.JoinPath(keyFileName(key.Address))} |
||||
if err := ks.keyStore.StoreKey(a.URL, key, passphrase); err != nil { |
||||
return accounts.Account{}, err |
||||
} |
||||
ks.cache.add(a) |
||||
return a, nil |
||||
} |
||||
|
||||
// Update changes the passphrase of an existing account.
|
||||
func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { |
||||
a, key, err := ks.getDecryptedKey(a, passphrase) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
return ks.keyStore.StoreKey(a.URL, key, newPassphrase) |
||||
} |
||||
|
||||
// ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
|
||||
// a key file in the key directory. The key file is encrypted with the same passphrase.
|
||||
func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) { |
||||
a, _, err := importPreSaleKey(ks.keyStore, keyJSON, passphrase) |
||||
if err != nil { |
||||
return a, err |
||||
} |
||||
ks.cache.add(a) |
||||
return a, nil |
||||
} |
||||
|
||||
// zeroKey zeroes a private key in memory.
|
||||
func zeroKey(k *ecdsa.PrivateKey) { |
||||
b := k.D.Bits() |
||||
for i := range b { |
||||
b[i] = 0 |
||||
} |
||||
} |
Loading…
Reference in new issue