github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/accounts/keystore/keystore.go (about)

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