github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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  	"math/big"
    28  	"os"
    29  	"path/filepath"
    30  	"reflect"
    31  	"runtime"
    32  	"sync"
    33  	"time"
    34  
    35  	"github.com/ethereum/go-ethereum/accounts"
    36  	"github.com/ethereum/go-ethereum/common"
    37  	"github.com/ethereum/go-ethereum/core/types"
    38  	"github.com/ethereum/go-ethereum/crypto"
    39  	"github.com/ethereum/go-ethereum/event"
    40  )
    41  
    42  var (
    43  	ErrLocked  = accounts.NewAuthNeededError("password or unlock")
    44  	ErrNoMatch = errors.New("no key for given address or file")
    45  	ErrDecrypt = errors.New("could not decrypt key with given password")
    46  
    47  	// ErrAccountAlreadyExists is returned if an account attempted to import is
    48  	// already present in the keystore.
    49  	ErrAccountAlreadyExists = errors.New("account already exists")
    50  )
    51  
    52  // KeyStoreType is the reflect type of a keystore backend.
    53  var KeyStoreType = reflect.TypeOf(&KeyStore{})
    54  
    55  // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
    56  const KeyStoreScheme = "keystore"
    57  
    58  // Maximum time between wallet refreshes (if filesystem notifications don't work).
    59  const walletRefreshCycle = 3 * time.Second
    60  
    61  // KeyStore manages a key storage directory on disk.
    62  type KeyStore struct {
    63  	storage  keyStore                     // Storage backend, might be cleartext or encrypted
    64  	cache    *accountCache                // In-memory account cache over the filesystem storage
    65  	changes  chan struct{}                // Channel receiving change notifications from the cache
    66  	unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)
    67  
    68  	wallets     []accounts.Wallet       // Wallet wrappers around the individual key files
    69  	updateFeed  event.Feed              // Event feed to notify wallet additions/removals
    70  	updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
    71  	updating    bool                    // Whether the event notification loop is running
    72  
    73  	mu       sync.RWMutex
    74  	importMu sync.Mutex // Import Mutex locks the import to prevent two insertions from racing
    75  }
    76  
    77  type unlocked struct {
    78  	*Key
    79  	abort chan struct{}
    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  	var (
   145  		wallets = make([]accounts.Wallet, 0, len(accs))
   146  		events  []accounts.WalletEvent
   147  	)
   148  
   149  	for _, account := range accs {
   150  		// Drop wallets while they were in front of the next account
   151  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   152  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   153  			ks.wallets = ks.wallets[1:]
   154  		}
   155  		// If there are no more wallets or the account is before the next, wrap new wallet
   156  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   157  			wallet := &keystoreWallet{account: account, keystore: ks}
   158  
   159  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   160  			wallets = append(wallets, wallet)
   161  			continue
   162  		}
   163  		// If the account is the same as the first wallet, keep it
   164  		if ks.wallets[0].Accounts()[0] == account {
   165  			wallets = append(wallets, ks.wallets[0])
   166  			ks.wallets = ks.wallets[1:]
   167  			continue
   168  		}
   169  	}
   170  	// Drop any leftover wallets and set the new batch
   171  	for _, wallet := range ks.wallets {
   172  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   173  	}
   174  	ks.wallets = wallets
   175  	ks.mu.Unlock()
   176  
   177  	// Fire all wallet events and return
   178  	for _, event := range events {
   179  		ks.updateFeed.Send(event)
   180  	}
   181  }
   182  
   183  // Subscribe implements accounts.Backend, creating an async subscription to
   184  // receive notifications on the addition or removal of keystore wallets.
   185  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   186  	// We need the mutex to reliably start/stop the update loop
   187  	ks.mu.Lock()
   188  	defer ks.mu.Unlock()
   189  
   190  	// Subscribe the caller and track the subscriber count
   191  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   192  
   193  	// Subscribers require an active notification loop, start it
   194  	if !ks.updating {
   195  		ks.updating = true
   196  		go ks.updater()
   197  	}
   198  	return sub
   199  }
   200  
   201  // updater is responsible for maintaining an up-to-date list of wallets stored in
   202  // the keystore, and for firing wallet addition/removal events. It listens for
   203  // account change events from the underlying account cache, and also periodically
   204  // forces a manual refresh (only triggers for systems where the filesystem notifier
   205  // is not running).
   206  func (ks *KeyStore) updater() {
   207  	for {
   208  		// Wait for an account update or a refresh timeout
   209  		select {
   210  		case <-ks.changes:
   211  		case <-time.After(walletRefreshCycle):
   212  		}
   213  		// Run the wallet refresher
   214  		ks.refreshWallets()
   215  
   216  		// If all our subscribers left, stop the updater
   217  		ks.mu.Lock()
   218  		if ks.updateScope.Count() == 0 {
   219  			ks.updating = false
   220  			ks.mu.Unlock()
   221  			return
   222  		}
   223  		ks.mu.Unlock()
   224  	}
   225  }
   226  
   227  // HasAddress reports whether a key with the given address is present.
   228  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   229  	return ks.cache.hasAddress(addr)
   230  }
   231  
   232  // Accounts returns all key files present in the directory.
   233  func (ks *KeyStore) Accounts() []accounts.Account {
   234  	return ks.cache.accounts()
   235  }
   236  
   237  // Delete deletes the key matched by account if the passphrase is correct.
   238  // If the account contains no filename, the address must match a unique key.
   239  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   240  	// Decrypting the key isn't really necessary, but we do
   241  	// it anyway to check the password and zero out the key
   242  	// immediately afterwards.
   243  	a, key, err := ks.getDecryptedKey(a, passphrase)
   244  	if key != nil {
   245  		zeroKey(key.PrivateKey)
   246  	}
   247  	if err != nil {
   248  		return err
   249  	}
   250  	// The order is crucial here. The key is dropped from the
   251  	// cache after the file is gone so that a reload happening in
   252  	// between won't insert it into the cache again.
   253  	err = os.Remove(a.URL.Path)
   254  	if err == nil {
   255  		ks.cache.delete(a)
   256  		ks.refreshWallets()
   257  	}
   258  	return err
   259  }
   260  
   261  // SignHash calculates a ECDSA signature for the given hash. The produced
   262  // signature is in the [R || S || V] format where V is 0 or 1.
   263  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   264  	// Look up the key to sign with and abort if it cannot be found
   265  	ks.mu.RLock()
   266  	defer ks.mu.RUnlock()
   267  
   268  	unlockedKey, found := ks.unlocked[a.Address]
   269  	if !found {
   270  		return nil, ErrLocked
   271  	}
   272  	// Sign the hash using plain ECDSA operations
   273  	return crypto.Sign(hash, unlockedKey.PrivateKey)
   274  }
   275  
   276  // SignTx signs the given transaction with the requested account.
   277  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   278  	// Look up the key to sign with and abort if it cannot be found
   279  	ks.mu.RLock()
   280  	defer ks.mu.RUnlock()
   281  
   282  	unlockedKey, found := ks.unlocked[a.Address]
   283  	if !found {
   284  		return nil, ErrLocked
   285  	}
   286  	// Depending on the presence of the chain ID, sign with 2718 or homestead
   287  	signer := types.LatestSignerForChainID(chainID)
   288  	return types.SignTx(tx, signer, unlockedKey.PrivateKey)
   289  }
   290  
   291  // SignHashWithPassphrase signs hash if the private key matching the given address
   292  // can be decrypted with the given passphrase. The produced signature is in the
   293  // [R || S || V] format where V is 0 or 1.
   294  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   295  	_, key, err := ks.getDecryptedKey(a, passphrase)
   296  	if err != nil {
   297  		return nil, err
   298  	}
   299  	defer zeroKey(key.PrivateKey)
   300  	return crypto.Sign(hash, key.PrivateKey)
   301  }
   302  
   303  // SignTxWithPassphrase signs the transaction if the private key matching the
   304  // given address can be decrypted with the given passphrase.
   305  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   306  	_, key, err := ks.getDecryptedKey(a, passphrase)
   307  	if err != nil {
   308  		return nil, err
   309  	}
   310  	defer zeroKey(key.PrivateKey)
   311  	// Depending on the presence of the chain ID, sign with or without replay protection.
   312  	signer := types.LatestSignerForChainID(chainID)
   313  	return types.SignTx(tx, signer, key.PrivateKey)
   314  }
   315  
   316  // Unlock unlocks the given account indefinitely.
   317  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
   318  	return ks.TimedUnlock(a, passphrase, 0)
   319  }
   320  
   321  // Lock removes the private key with the given address from memory.
   322  func (ks *KeyStore) Lock(addr common.Address) error {
   323  	ks.mu.Lock()
   324  	if unl, found := ks.unlocked[addr]; found {
   325  		ks.mu.Unlock()
   326  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   327  	} else {
   328  		ks.mu.Unlock()
   329  	}
   330  	return nil
   331  }
   332  
   333  // TimedUnlock unlocks the given account with the passphrase. The account
   334  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   335  // until the program exits. The account must match a unique key file.
   336  //
   337  // If the account address is already unlocked for a duration, TimedUnlock extends or
   338  // shortens the active unlock timeout. If the address was previously unlocked
   339  // indefinitely the timeout is not altered.
   340  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
   341  	a, key, err := ks.getDecryptedKey(a, passphrase)
   342  	if err != nil {
   343  		return err
   344  	}
   345  
   346  	ks.mu.Lock()
   347  	defer ks.mu.Unlock()
   348  	u, found := ks.unlocked[a.Address]
   349  	if found {
   350  		if u.abort == nil {
   351  			// The address was unlocked indefinitely, so unlocking
   352  			// it with a timeout would be confusing.
   353  			zeroKey(key.PrivateKey)
   354  			return nil
   355  		}
   356  		// Terminate the expire goroutine and replace it below.
   357  		close(u.abort)
   358  	}
   359  	if timeout > 0 {
   360  		u = &unlocked{Key: key, abort: make(chan struct{})}
   361  		go ks.expire(a.Address, u, timeout)
   362  	} else {
   363  		u = &unlocked{Key: key}
   364  	}
   365  	ks.unlocked[a.Address] = u
   366  	return nil
   367  }
   368  
   369  // Find resolves the given account into a unique entry in the keystore.
   370  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   371  	ks.cache.maybeReload()
   372  	ks.cache.mu.Lock()
   373  	a, err := ks.cache.find(a)
   374  	ks.cache.mu.Unlock()
   375  	return a, err
   376  }
   377  
   378  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   379  	a, err := ks.Find(a)
   380  	if err != nil {
   381  		return a, nil, err
   382  	}
   383  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   384  	return a, key, err
   385  }
   386  
   387  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   388  	t := time.NewTimer(timeout)
   389  	defer t.Stop()
   390  	select {
   391  	case <-u.abort:
   392  		// just quit
   393  	case <-t.C:
   394  		ks.mu.Lock()
   395  		// only drop if it's still the same key instance that dropLater
   396  		// was launched with. we can check that using pointer equality
   397  		// because the map stores a new pointer every time the key is
   398  		// unlocked.
   399  		if ks.unlocked[addr] == u {
   400  			zeroKey(u.PrivateKey)
   401  			delete(ks.unlocked, addr)
   402  		}
   403  		ks.mu.Unlock()
   404  	}
   405  }
   406  
   407  // NewAccount generates a new key and stores it into the key directory,
   408  // encrypting it with the passphrase.
   409  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   410  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   411  	if err != nil {
   412  		return accounts.Account{}, err
   413  	}
   414  	// Add the account to the cache immediately rather
   415  	// than waiting for file system notifications to pick it up.
   416  	ks.cache.add(account)
   417  	ks.refreshWallets()
   418  	return account, nil
   419  }
   420  
   421  // Export exports as a JSON key, encrypted with newPassphrase.
   422  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   423  	_, key, err := ks.getDecryptedKey(a, passphrase)
   424  	if err != nil {
   425  		return nil, err
   426  	}
   427  	var N, P int
   428  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   429  		N, P = store.scryptN, store.scryptP
   430  	} else {
   431  		N, P = StandardScryptN, StandardScryptP
   432  	}
   433  	return EncryptKey(key, newPassphrase, N, P)
   434  }
   435  
   436  // Import stores the given encrypted JSON key into the key directory.
   437  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   438  	key, err := DecryptKey(keyJSON, passphrase)
   439  	if key != nil && key.PrivateKey != nil {
   440  		defer zeroKey(key.PrivateKey)
   441  	}
   442  	if err != nil {
   443  		return accounts.Account{}, err
   444  	}
   445  	ks.importMu.Lock()
   446  	defer ks.importMu.Unlock()
   447  
   448  	if ks.cache.hasAddress(key.Address) {
   449  		return accounts.Account{
   450  			Address: key.Address,
   451  		}, ErrAccountAlreadyExists
   452  	}
   453  	return ks.importKey(key, newPassphrase)
   454  }
   455  
   456  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   457  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   458  	ks.importMu.Lock()
   459  	defer ks.importMu.Unlock()
   460  
   461  	key := newKeyFromECDSA(priv)
   462  	if ks.cache.hasAddress(key.Address) {
   463  		return accounts.Account{
   464  			Address: key.Address,
   465  		}, ErrAccountAlreadyExists
   466  	}
   467  	return ks.importKey(key, passphrase)
   468  }
   469  
   470  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   471  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   472  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   473  		return accounts.Account{}, err
   474  	}
   475  	ks.cache.add(a)
   476  	ks.refreshWallets()
   477  	return a, nil
   478  }
   479  
   480  // Update changes the passphrase of an existing account.
   481  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   482  	a, key, err := ks.getDecryptedKey(a, passphrase)
   483  	if err != nil {
   484  		return err
   485  	}
   486  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   487  }
   488  
   489  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   490  // a key file in the key directory. The key file is encrypted with the same passphrase.
   491  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   492  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   493  	if err != nil {
   494  		return a, err
   495  	}
   496  	ks.cache.add(a)
   497  	ks.refreshWallets()
   498  	return a, nil
   499  }
   500  
   501  // zeroKey zeroes a private key in memory.
   502  func zeroKey(k *ecdsa.PrivateKey) {
   503  	b := k.D.Bits()
   504  	for i := range b {
   505  		b[i] = 0
   506  	}
   507  }