github.com/snowblossomcoin/go-ethereum@v1.9.25/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 EIP155 or homestead
   287  	if chainID != nil {
   288  		return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
   289  	}
   290  	return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
   291  }
   292  
   293  // SignHashWithPassphrase signs hash if the private key matching the given address
   294  // can be decrypted with the given passphrase. The produced signature is in the
   295  // [R || S || V] format where V is 0 or 1.
   296  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   297  	_, key, err := ks.getDecryptedKey(a, passphrase)
   298  	if err != nil {
   299  		return nil, err
   300  	}
   301  	defer zeroKey(key.PrivateKey)
   302  	return crypto.Sign(hash, key.PrivateKey)
   303  }
   304  
   305  // SignTxWithPassphrase signs the transaction if the private key matching the
   306  // given address can be decrypted with the given passphrase.
   307  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   308  	_, key, err := ks.getDecryptedKey(a, passphrase)
   309  	if err != nil {
   310  		return nil, err
   311  	}
   312  	defer zeroKey(key.PrivateKey)
   313  
   314  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   315  	if chainID != nil {
   316  		return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
   317  	}
   318  	return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
   319  }
   320  
   321  // Unlock unlocks the given account indefinitely.
   322  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
   323  	return ks.TimedUnlock(a, passphrase, 0)
   324  }
   325  
   326  // Lock removes the private key with the given address from memory.
   327  func (ks *KeyStore) Lock(addr common.Address) error {
   328  	ks.mu.Lock()
   329  	if unl, found := ks.unlocked[addr]; found {
   330  		ks.mu.Unlock()
   331  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   332  	} else {
   333  		ks.mu.Unlock()
   334  	}
   335  	return nil
   336  }
   337  
   338  // TimedUnlock unlocks the given account with the passphrase. The account
   339  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   340  // until the program exits. The account must match a unique key file.
   341  //
   342  // If the account address is already unlocked for a duration, TimedUnlock extends or
   343  // shortens the active unlock timeout. If the address was previously unlocked
   344  // indefinitely the timeout is not altered.
   345  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
   346  	a, key, err := ks.getDecryptedKey(a, passphrase)
   347  	if err != nil {
   348  		return err
   349  	}
   350  
   351  	ks.mu.Lock()
   352  	defer ks.mu.Unlock()
   353  	u, found := ks.unlocked[a.Address]
   354  	if found {
   355  		if u.abort == nil {
   356  			// The address was unlocked indefinitely, so unlocking
   357  			// it with a timeout would be confusing.
   358  			zeroKey(key.PrivateKey)
   359  			return nil
   360  		}
   361  		// Terminate the expire goroutine and replace it below.
   362  		close(u.abort)
   363  	}
   364  	if timeout > 0 {
   365  		u = &unlocked{Key: key, abort: make(chan struct{})}
   366  		go ks.expire(a.Address, u, timeout)
   367  	} else {
   368  		u = &unlocked{Key: key}
   369  	}
   370  	ks.unlocked[a.Address] = u
   371  	return nil
   372  }
   373  
   374  // Find resolves the given account into a unique entry in the keystore.
   375  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   376  	ks.cache.maybeReload()
   377  	ks.cache.mu.Lock()
   378  	a, err := ks.cache.find(a)
   379  	ks.cache.mu.Unlock()
   380  	return a, err
   381  }
   382  
   383  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   384  	a, err := ks.Find(a)
   385  	if err != nil {
   386  		return a, nil, err
   387  	}
   388  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   389  	return a, key, err
   390  }
   391  
   392  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   393  	t := time.NewTimer(timeout)
   394  	defer t.Stop()
   395  	select {
   396  	case <-u.abort:
   397  		// just quit
   398  	case <-t.C:
   399  		ks.mu.Lock()
   400  		// only drop if it's still the same key instance that dropLater
   401  		// was launched with. we can check that using pointer equality
   402  		// because the map stores a new pointer every time the key is
   403  		// unlocked.
   404  		if ks.unlocked[addr] == u {
   405  			zeroKey(u.PrivateKey)
   406  			delete(ks.unlocked, addr)
   407  		}
   408  		ks.mu.Unlock()
   409  	}
   410  }
   411  
   412  // NewAccount generates a new key and stores it into the key directory,
   413  // encrypting it with the passphrase.
   414  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   415  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   416  	if err != nil {
   417  		return accounts.Account{}, err
   418  	}
   419  	// Add the account to the cache immediately rather
   420  	// than waiting for file system notifications to pick it up.
   421  	ks.cache.add(account)
   422  	ks.refreshWallets()
   423  	return account, nil
   424  }
   425  
   426  // Export exports as a JSON key, encrypted with newPassphrase.
   427  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   428  	_, key, err := ks.getDecryptedKey(a, passphrase)
   429  	if err != nil {
   430  		return nil, err
   431  	}
   432  	var N, P int
   433  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   434  		N, P = store.scryptN, store.scryptP
   435  	} else {
   436  		N, P = StandardScryptN, StandardScryptP
   437  	}
   438  	return EncryptKey(key, newPassphrase, N, P)
   439  }
   440  
   441  // Import stores the given encrypted JSON key into the key directory.
   442  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   443  	key, err := DecryptKey(keyJSON, passphrase)
   444  	if key != nil && key.PrivateKey != nil {
   445  		defer zeroKey(key.PrivateKey)
   446  	}
   447  	if err != nil {
   448  		return accounts.Account{}, err
   449  	}
   450  	ks.importMu.Lock()
   451  	defer ks.importMu.Unlock()
   452  
   453  	if ks.cache.hasAddress(key.Address) {
   454  		return accounts.Account{
   455  			Address: key.Address,
   456  		}, ErrAccountAlreadyExists
   457  	}
   458  	return ks.importKey(key, newPassphrase)
   459  }
   460  
   461  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   462  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   463  	ks.importMu.Lock()
   464  	defer ks.importMu.Unlock()
   465  
   466  	key := newKeyFromECDSA(priv)
   467  	if ks.cache.hasAddress(key.Address) {
   468  		return accounts.Account{
   469  			Address: key.Address,
   470  		}, ErrAccountAlreadyExists
   471  	}
   472  	return ks.importKey(key, passphrase)
   473  }
   474  
   475  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   476  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   477  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   478  		return accounts.Account{}, err
   479  	}
   480  	ks.cache.add(a)
   481  	ks.refreshWallets()
   482  	return a, nil
   483  }
   484  
   485  // Update changes the passphrase of an existing account.
   486  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   487  	a, key, err := ks.getDecryptedKey(a, passphrase)
   488  	if err != nil {
   489  		return err
   490  	}
   491  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   492  }
   493  
   494  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   495  // a key file in the key directory. The key file is encrypted with the same passphrase.
   496  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   497  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   498  	if err != nil {
   499  		return a, err
   500  	}
   501  	ks.cache.add(a)
   502  	ks.refreshWallets()
   503  	return a, nil
   504  }
   505  
   506  // zeroKey zeroes a private key in memory.
   507  func zeroKey(k *ecdsa.PrivateKey) {
   508  	b := k.D.Bits()
   509  	for i := range b {
   510  		b[i] = 0
   511  	}
   512  }