github.com/codingfuture/orig-energi3@v0.8.4/accounts/keystore/keystore.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2017 The go-ethereum Authors
     3  // This file is part of the Energi Core library.
     4  //
     5  // The Energi Core library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The Energi Core library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Package keystore implements encrypted storage of secp256k1 private keys.
    19  //
    20  // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
    21  // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
    22  package keystore
    23  
    24  import (
    25  	"crypto/ecdsa"
    26  	crand "crypto/rand"
    27  	"errors"
    28  	"fmt"
    29  	"math/big"
    30  	"os"
    31  	"path/filepath"
    32  	"reflect"
    33  	"runtime"
    34  	"sync"
    35  	"time"
    36  
    37  	"github.com/ethereum/go-ethereum/accounts"
    38  	"github.com/ethereum/go-ethereum/common"
    39  	"github.com/ethereum/go-ethereum/core/types"
    40  	"github.com/ethereum/go-ethereum/crypto"
    41  	"github.com/ethereum/go-ethereum/event"
    42  )
    43  
    44  var (
    45  	ErrLocked  = accounts.NewAuthNeededError("password or unlock")
    46  	ErrStaking = accounts.NewAuthNeededError("only staking")
    47  	ErrNoMatch = errors.New("no key for given address or file")
    48  	ErrDecrypt = errors.New("could not decrypt key with given passphrase")
    49  )
    50  
    51  // KeyStoreType is the reflect type of a keystore backend.
    52  var KeyStoreType = reflect.TypeOf(&KeyStore{})
    53  
    54  // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
    55  const KeyStoreScheme = "keystore"
    56  
    57  // Maximum time between wallet refreshes (if filesystem notifications don't work).
    58  const walletRefreshCycle = 3 * time.Second
    59  
    60  // KeyStore manages a key storage directory on disk.
    61  type KeyStore struct {
    62  	storage  keyStore                     // Storage backend, might be cleartext or encrypted
    63  	cache    *accountCache                // In-memory account cache over the filesystem storage
    64  	changes  chan struct{}                // Channel receiving change notifications from the cache
    65  	unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)
    66  
    67  	wallets     []accounts.Wallet       // Wallet wrappers around the individual key files
    68  	updateFeed  event.Feed              // Event feed to notify wallet additions/removals
    69  	updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
    70  	updating    bool                    // Whether the event notification loop is running
    71  
    72  	mu sync.RWMutex
    73  }
    74  
    75  type unlocked struct {
    76  	*Key
    77  	abort chan struct{}
    78  
    79  	stakingOnly bool
    80  }
    81  
    82  // NewKeyStore creates a keystore for the given directory.
    83  func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
    84  	keydir, _ = filepath.Abs(keydir)
    85  	ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}}
    86  	ks.init(keydir)
    87  	return ks
    88  }
    89  
    90  // NewPlaintextKeyStore creates a keystore for the given directory.
    91  // Deprecated: Use NewKeyStore.
    92  func NewPlaintextKeyStore(keydir string) *KeyStore {
    93  	keydir, _ = filepath.Abs(keydir)
    94  	ks := &KeyStore{storage: &keyStorePlain{keydir}}
    95  	ks.init(keydir)
    96  	return ks
    97  }
    98  
    99  func (ks *KeyStore) init(keydir string) {
   100  	// Lock the mutex since the account cache might call back with events
   101  	ks.mu.Lock()
   102  	defer ks.mu.Unlock()
   103  
   104  	// Initialize the set of unlocked keys and the account cache
   105  	ks.unlocked = make(map[common.Address]*unlocked)
   106  	ks.cache, ks.changes = newAccountCache(keydir)
   107  
   108  	// TODO: In order for this finalizer to work, there must be no references
   109  	// to ks. addressCache doesn't keep a reference but unlocked keys do,
   110  	// so the finalizer will not trigger until all timed unlocks have expired.
   111  	runtime.SetFinalizer(ks, func(m *KeyStore) {
   112  		m.cache.close()
   113  	})
   114  	// Create the initial list of wallets from the cache
   115  	accs := ks.cache.accounts()
   116  	ks.wallets = make([]accounts.Wallet, len(accs))
   117  	for i := 0; i < len(accs); i++ {
   118  		ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks}
   119  	}
   120  }
   121  
   122  // Wallets implements accounts.Backend, returning all single-key wallets from the
   123  // keystore directory.
   124  func (ks *KeyStore) Wallets() []accounts.Wallet {
   125  	// Make sure the list of wallets is in sync with the account cache
   126  	ks.refreshWallets()
   127  
   128  	ks.mu.RLock()
   129  	defer ks.mu.RUnlock()
   130  
   131  	cpy := make([]accounts.Wallet, len(ks.wallets))
   132  	copy(cpy, ks.wallets)
   133  	return cpy
   134  }
   135  
   136  // refreshWallets retrieves the current account list and based on that does any
   137  // necessary wallet refreshes.
   138  func (ks *KeyStore) refreshWallets() {
   139  	// Retrieve the current list of accounts
   140  	ks.mu.Lock()
   141  	accs := ks.cache.accounts()
   142  
   143  	// Transform the current list of wallets into the new one
   144  	wallets := make([]accounts.Wallet, 0, len(accs))
   145  	events := []accounts.WalletEvent{}
   146  
   147  	for _, account := range accs {
   148  		// Drop wallets while they were in front of the next account
   149  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   150  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   151  			ks.wallets = ks.wallets[1:]
   152  		}
   153  		// If there are no more wallets or the account is before the next, wrap new wallet
   154  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   155  			wallet := &keystoreWallet{account: account, keystore: ks}
   156  
   157  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   158  			wallets = append(wallets, wallet)
   159  			continue
   160  		}
   161  		// If the account is the same as the first wallet, keep it
   162  		if ks.wallets[0].Accounts()[0] == account {
   163  			wallets = append(wallets, ks.wallets[0])
   164  			ks.wallets = ks.wallets[1:]
   165  			continue
   166  		}
   167  	}
   168  	// Drop any leftover wallets and set the new batch
   169  	for _, wallet := range ks.wallets {
   170  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   171  	}
   172  	ks.wallets = wallets
   173  	ks.mu.Unlock()
   174  
   175  	// Fire all wallet events and return
   176  	for _, event := range events {
   177  		ks.updateFeed.Send(event)
   178  	}
   179  }
   180  
   181  // Subscribe implements accounts.Backend, creating an async subscription to
   182  // receive notifications on the addition or removal of keystore wallets.
   183  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   184  	// We need the mutex to reliably start/stop the update loop
   185  	ks.mu.Lock()
   186  	defer ks.mu.Unlock()
   187  
   188  	// Subscribe the caller and track the subscriber count
   189  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   190  
   191  	// Subscribers require an active notification loop, start it
   192  	if !ks.updating {
   193  		ks.updating = true
   194  		go ks.updater()
   195  	}
   196  	return sub
   197  }
   198  
   199  // updater is responsible for maintaining an up-to-date list of wallets stored in
   200  // the keystore, and for firing wallet addition/removal events. It listens for
   201  // account change events from the underlying account cache, and also periodically
   202  // forces a manual refresh (only triggers for systems where the filesystem notifier
   203  // is not running).
   204  func (ks *KeyStore) updater() {
   205  	for {
   206  		// Wait for an account update or a refresh timeout
   207  		select {
   208  		case <-ks.changes:
   209  		case <-time.After(walletRefreshCycle):
   210  		}
   211  		// Run the wallet refresher
   212  		ks.refreshWallets()
   213  
   214  		// If all our subscribers left, stop the updater
   215  		ks.mu.Lock()
   216  		if ks.updateScope.Count() == 0 {
   217  			ks.updating = false
   218  			ks.mu.Unlock()
   219  			return
   220  		}
   221  		ks.mu.Unlock()
   222  	}
   223  }
   224  
   225  // HasAddress reports whether a key with the given address is present.
   226  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   227  	return ks.cache.hasAddress(addr)
   228  }
   229  
   230  // Accounts returns all key files present in the directory.
   231  func (ks *KeyStore) Accounts() []accounts.Account {
   232  	return ks.cache.accounts()
   233  }
   234  
   235  // Delete deletes the key matched by account if the passphrase is correct.
   236  // If the account contains no filename, the address must match a unique key.
   237  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   238  	// Decrypting the key isn't really necessary, but we do
   239  	// it anyway to check the password and zero out the key
   240  	// immediately afterwards.
   241  	a, key, err := ks.getDecryptedKey(a, passphrase)
   242  	if key != nil {
   243  		zeroKey(key.PrivateKey)
   244  	}
   245  	if err != nil {
   246  		return err
   247  	}
   248  	// The order is crucial here. The key is dropped from the
   249  	// cache after the file is gone so that a reload happening in
   250  	// between won't insert it into the cache again.
   251  	err = os.Remove(a.URL.Path)
   252  	if err == nil {
   253  		ks.cache.delete(a)
   254  		ks.refreshWallets()
   255  	}
   256  	return err
   257  }
   258  
   259  // SignHash calculates a ECDSA signature for the given hash. The produced
   260  // signature is in the [R || S || V] format where V is 0 or 1.
   261  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   262  	// Look up the key to sign with and abort if it cannot be found
   263  	ks.mu.RLock()
   264  	defer ks.mu.RUnlock()
   265  
   266  	unlockedKey, found := ks.unlocked[a.Address]
   267  	if !found {
   268  		return nil, ErrLocked
   269  	}
   270  	// Sign the hash using plain ECDSA operations
   271  	return crypto.Sign(hash, unlockedKey.PrivateKey)
   272  }
   273  
   274  // SignTx signs the given transaction with the requested account.
   275  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   276  	// Look up the key to sign with and abort if it cannot be found
   277  	ks.mu.RLock()
   278  	defer ks.mu.RUnlock()
   279  
   280  	unlockedKey, found := ks.unlocked[a.Address]
   281  	if !found {
   282  		return nil, ErrLocked
   283  	}
   284  	if unlockedKey.stakingOnly {
   285  		return nil, ErrStaking
   286  	}
   287  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   288  	if chainID != nil {
   289  		return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
   290  	}
   291  	return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
   292  }
   293  
   294  // SignHashWithPassphrase signs hash if the private key matching the given address
   295  // can be decrypted with the given passphrase. The produced signature is in the
   296  // [R || S || V] format where V is 0 or 1.
   297  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   298  	_, key, err := ks.getDecryptedKey(a, passphrase)
   299  	if err != nil {
   300  		return nil, err
   301  	}
   302  	defer zeroKey(key.PrivateKey)
   303  	return crypto.Sign(hash, key.PrivateKey)
   304  }
   305  
   306  // SignTxWithPassphrase signs the transaction if the private key matching the
   307  // given address can be decrypted with the given passphrase.
   308  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   309  	_, key, err := ks.getDecryptedKey(a, passphrase)
   310  	if err != nil {
   311  		return nil, err
   312  	}
   313  	defer zeroKey(key.PrivateKey)
   314  
   315  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   316  	if chainID != nil {
   317  		return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
   318  	}
   319  	return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
   320  }
   321  
   322  // Unlock unlocks the given account indefinitely.
   323  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string, stakingOnly bool) error {
   324  	return ks.TimedUnlock(a, passphrase, 0, stakingOnly)
   325  }
   326  
   327  // Lock removes the private key with the given address from memory.
   328  func (ks *KeyStore) Lock(addr common.Address) error {
   329  	ks.mu.Lock()
   330  	if unl, found := ks.unlocked[addr]; found {
   331  		ks.mu.Unlock()
   332  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   333  	} else {
   334  		ks.mu.Unlock()
   335  	}
   336  	return nil
   337  }
   338  
   339  // TimedUnlock unlocks the given account with the passphrase. The account
   340  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   341  // until the program exits. The account must match a unique key file.
   342  //
   343  // If the account address is already unlocked for a duration, TimedUnlock extends or
   344  // shortens the active unlock timeout. If the address was previously unlocked
   345  // indefinitely the timeout is not altered.
   346  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration, stakingOnly bool) error {
   347  	a, key, err := ks.getDecryptedKey(a, passphrase)
   348  	if err != nil {
   349  		return err
   350  	}
   351  
   352  	ks.mu.Lock()
   353  	defer ks.mu.Unlock()
   354  	u, found := ks.unlocked[a.Address]
   355  	if found {
   356  		if u.abort == nil {
   357  			// The address was unlocked indefinitely, so unlocking
   358  			// it with a timeout would be confusing.
   359  			zeroKey(key.PrivateKey)
   360  
   361  			// Allow to easy protection level
   362  			if !stakingOnly {
   363  				ks.unlocked[a.Address].stakingOnly = stakingOnly
   364  			}
   365  			return nil
   366  		}
   367  		// Terminate the expire goroutine and replace it below.
   368  		close(u.abort)
   369  	}
   370  	if timeout > 0 {
   371  		u = &unlocked{Key: key, abort: make(chan struct{}), stakingOnly: stakingOnly}
   372  		go ks.expire(a.Address, u, timeout)
   373  	} else {
   374  		u = &unlocked{Key: key, stakingOnly: stakingOnly}
   375  	}
   376  	ks.unlocked[a.Address] = u
   377  	return nil
   378  }
   379  
   380  // Find resolves the given account into a unique entry in the keystore.
   381  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   382  	ks.cache.maybeReload()
   383  	ks.cache.mu.Lock()
   384  	a, err := ks.cache.find(a)
   385  	ks.cache.mu.Unlock()
   386  	return a, err
   387  }
   388  
   389  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   390  	a, err := ks.Find(a)
   391  	if err != nil {
   392  		return a, nil, err
   393  	}
   394  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   395  	return a, key, err
   396  }
   397  
   398  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   399  	t := time.NewTimer(timeout)
   400  	defer t.Stop()
   401  	select {
   402  	case <-u.abort:
   403  		// just quit
   404  	case <-t.C:
   405  		ks.mu.Lock()
   406  		// only drop if it's still the same key instance that dropLater
   407  		// was launched with. we can check that using pointer equality
   408  		// because the map stores a new pointer every time the key is
   409  		// unlocked.
   410  		if ks.unlocked[addr] == u {
   411  			zeroKey(u.PrivateKey)
   412  			delete(ks.unlocked, addr)
   413  		}
   414  		ks.mu.Unlock()
   415  	}
   416  }
   417  
   418  // NewAccount generates a new key and stores it into the key directory,
   419  // encrypting it with the passphrase.
   420  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   421  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   422  	if err != nil {
   423  		return accounts.Account{}, err
   424  	}
   425  	// Add the account to the cache immediately rather
   426  	// than waiting for file system notifications to pick it up.
   427  	ks.cache.add(account)
   428  	ks.refreshWallets()
   429  	return account, nil
   430  }
   431  
   432  // Export exports as a JSON key, encrypted with newPassphrase.
   433  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   434  	_, key, err := ks.getDecryptedKey(a, passphrase)
   435  	if err != nil {
   436  		return nil, err
   437  	}
   438  	var N, P int
   439  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   440  		N, P = store.scryptN, store.scryptP
   441  	} else {
   442  		N, P = StandardScryptN, StandardScryptP
   443  	}
   444  	return EncryptKey(key, newPassphrase, N, P)
   445  }
   446  
   447  // Import stores the given encrypted JSON key into the key directory.
   448  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   449  	key, err := DecryptKey(keyJSON, passphrase)
   450  	if key != nil && key.PrivateKey != nil {
   451  		defer zeroKey(key.PrivateKey)
   452  	}
   453  	if err != nil {
   454  		return accounts.Account{}, err
   455  	}
   456  	return ks.importKey(key, newPassphrase)
   457  }
   458  
   459  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   460  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   461  	key := newKeyFromECDSA(priv)
   462  	if ks.cache.hasAddress(key.Address) {
   463  		return accounts.Account{}, fmt.Errorf("account already exists")
   464  	}
   465  	return ks.importKey(key, passphrase)
   466  }
   467  
   468  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   469  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   470  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   471  		return accounts.Account{}, err
   472  	}
   473  	ks.cache.add(a)
   474  	ks.refreshWallets()
   475  	return a, nil
   476  }
   477  
   478  // Update changes the passphrase of an existing account.
   479  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   480  	a, key, err := ks.getDecryptedKey(a, passphrase)
   481  	if err != nil {
   482  		return err
   483  	}
   484  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   485  }
   486  
   487  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   488  // a key file in the key directory. The key file is encrypted with the same passphrase.
   489  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   490  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   491  	if err != nil {
   492  		return a, err
   493  	}
   494  	ks.cache.add(a)
   495  	ks.refreshWallets()
   496  	return a, nil
   497  }
   498  
   499  // zeroKey zeroes a private key in memory.
   500  func zeroKey(k *ecdsa.PrivateKey) {
   501  	b := k.D.Bits()
   502  	for i := range b {
   503  		b[i] = 0
   504  	}
   505  }