github.com/theQRL/go-zond@v0.2.1/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  	"errors"
    25  	"math/big"
    26  	"os"
    27  	"path/filepath"
    28  	"reflect"
    29  	"runtime"
    30  	"sync"
    31  	"time"
    32  
    33  	"github.com/theQRL/go-qrllib/dilithium"
    34  	"github.com/theQRL/go-zond/accounts"
    35  	"github.com/theQRL/go-zond/common"
    36  	"github.com/theQRL/go-zond/core/types"
    37  	"github.com/theQRL/go-zond/crypto/pqcrypto"
    38  	"github.com/theQRL/go-zond/event"
    39  )
    40  
    41  var (
    42  	ErrLocked  = accounts.NewAuthNeededError("password or unlock")
    43  	ErrNoMatch = errors.New("no key for given address or file")
    44  	ErrDecrypt = errors.New("could not decrypt key with given password")
    45  
    46  	// ErrAccountAlreadyExists is returned if an account attempted to import is
    47  	// already present in the keystore.
    48  	ErrAccountAlreadyExists = errors.New("account already exists")
    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  	importMu sync.Mutex // Import Mutex locks the import to prevent two insertions from racing
    74  }
    75  
    76  type unlocked struct {
    77  	*Key
    78  	abort chan struct{}
    79  }
    80  
    81  // NewKeyStore creates a keystore for the given directory.
    82  func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
    83  	keydir, _ = filepath.Abs(keydir)
    84  	ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}}
    85  	ks.init(keydir)
    86  	return ks
    87  }
    88  
    89  func (ks *KeyStore) init(keydir string) {
    90  	// Lock the mutex since the account cache might call back with events
    91  	ks.mu.Lock()
    92  	defer ks.mu.Unlock()
    93  
    94  	// Initialize the set of unlocked keys and the account cache
    95  	ks.unlocked = make(map[common.Address]*unlocked)
    96  	ks.cache, ks.changes = newAccountCache(keydir)
    97  
    98  	// TODO: In order for this finalizer to work, there must be no references
    99  	// to ks. addressCache doesn't keep a reference but unlocked keys do,
   100  	// so the finalizer will not trigger until all timed unlocks have expired.
   101  	runtime.SetFinalizer(ks, func(m *KeyStore) {
   102  		m.cache.close()
   103  	})
   104  	// Create the initial list of wallets from the cache
   105  	accs := ks.cache.accounts()
   106  	ks.wallets = make([]accounts.Wallet, len(accs))
   107  	for i := 0; i < len(accs); i++ {
   108  		ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks}
   109  	}
   110  }
   111  
   112  // Wallets implements accounts.Backend, returning all single-key wallets from the
   113  // keystore directory.
   114  func (ks *KeyStore) Wallets() []accounts.Wallet {
   115  	// Make sure the list of wallets is in sync with the account cache
   116  	ks.refreshWallets()
   117  
   118  	ks.mu.RLock()
   119  	defer ks.mu.RUnlock()
   120  
   121  	cpy := make([]accounts.Wallet, len(ks.wallets))
   122  	copy(cpy, ks.wallets)
   123  	return cpy
   124  }
   125  
   126  // refreshWallets retrieves the current account list and based on that does any
   127  // necessary wallet refreshes.
   128  func (ks *KeyStore) refreshWallets() {
   129  	// Retrieve the current list of accounts
   130  	ks.mu.Lock()
   131  	accs := ks.cache.accounts()
   132  
   133  	// Transform the current list of wallets into the new one
   134  	var (
   135  		wallets = make([]accounts.Wallet, 0, len(accs))
   136  		events  []accounts.WalletEvent
   137  	)
   138  
   139  	for _, account := range accs {
   140  		// Drop wallets while they were in front of the next account
   141  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   142  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   143  			ks.wallets = ks.wallets[1:]
   144  		}
   145  		// If there are no more wallets or the account is before the next, wrap new wallet
   146  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   147  			wallet := &keystoreWallet{account: account, keystore: ks}
   148  
   149  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   150  			wallets = append(wallets, wallet)
   151  			continue
   152  		}
   153  		// If the account is the same as the first wallet, keep it
   154  		if ks.wallets[0].Accounts()[0] == account {
   155  			wallets = append(wallets, ks.wallets[0])
   156  			ks.wallets = ks.wallets[1:]
   157  			continue
   158  		}
   159  	}
   160  	// Drop any leftover wallets and set the new batch
   161  	for _, wallet := range ks.wallets {
   162  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   163  	}
   164  	ks.wallets = wallets
   165  	ks.mu.Unlock()
   166  
   167  	// Fire all wallet events and return
   168  	for _, event := range events {
   169  		ks.updateFeed.Send(event)
   170  	}
   171  }
   172  
   173  // Subscribe implements accounts.Backend, creating an async subscription to
   174  // receive notifications on the addition or removal of keystore wallets.
   175  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   176  	// We need the mutex to reliably start/stop the update loop
   177  	ks.mu.Lock()
   178  	defer ks.mu.Unlock()
   179  
   180  	// Subscribe the caller and track the subscriber count
   181  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   182  
   183  	// Subscribers require an active notification loop, start it
   184  	if !ks.updating {
   185  		ks.updating = true
   186  		go ks.updater()
   187  	}
   188  	return sub
   189  }
   190  
   191  // updater is responsible for maintaining an up-to-date list of wallets stored in
   192  // the keystore, and for firing wallet addition/removal events. It listens for
   193  // account change events from the underlying account cache, and also periodically
   194  // forces a manual refresh (only triggers for systems where the filesystem notifier
   195  // is not running).
   196  func (ks *KeyStore) updater() {
   197  	for {
   198  		// Wait for an account update or a refresh timeout
   199  		select {
   200  		case <-ks.changes:
   201  		case <-time.After(walletRefreshCycle):
   202  		}
   203  		// Run the wallet refresher
   204  		ks.refreshWallets()
   205  
   206  		// If all our subscribers left, stop the updater
   207  		ks.mu.Lock()
   208  		if ks.updateScope.Count() == 0 {
   209  			ks.updating = false
   210  			ks.mu.Unlock()
   211  			return
   212  		}
   213  		ks.mu.Unlock()
   214  	}
   215  }
   216  
   217  // HasAddress reports whether a key with the given address is present.
   218  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   219  	return ks.cache.hasAddress(addr)
   220  }
   221  
   222  // Accounts returns all key files present in the directory.
   223  func (ks *KeyStore) Accounts() []accounts.Account {
   224  	return ks.cache.accounts()
   225  }
   226  
   227  // Delete deletes the key matched by account if the passphrase is correct.
   228  // If the account contains no filename, the address must match a unique key.
   229  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   230  	// Decrypting the key isn't really necessary, but we do
   231  	// it anyway to check the password and zero out the key
   232  	// immediately afterwards.
   233  	a, key, err := ks.getDecryptedKey(a, passphrase)
   234  	if key != nil {
   235  		key.Dilithium = nil
   236  	}
   237  	if err != nil {
   238  		return err
   239  	}
   240  	// The order is crucial here. The key is dropped from the
   241  	// cache after the file is gone so that a reload happening in
   242  	// between won't insert it into the cache again.
   243  	err = os.Remove(a.URL.Path)
   244  	if err == nil {
   245  		ks.cache.delete(a)
   246  		ks.refreshWallets()
   247  	}
   248  	return err
   249  }
   250  
   251  // SignHash returns the Dilithium signature for the given hash.
   252  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   253  	// Look up the key to sign with and abort if it cannot be found
   254  	ks.mu.RLock()
   255  	defer ks.mu.RUnlock()
   256  
   257  	unlockedKey, found := ks.unlocked[a.Address]
   258  	if !found {
   259  		return nil, ErrLocked
   260  	}
   261  
   262  	signature, err := unlockedKey.Dilithium.Sign(hash)
   263  
   264  	return signature[:], err
   265  }
   266  
   267  func (ks *KeyStore) GetPublicKey(a accounts.Account) ([]byte, error) {
   268  	// Look up the key to sign with and abort if it cannot be found
   269  	ks.mu.RLock()
   270  	defer ks.mu.RUnlock()
   271  
   272  	unlockedKey, found := ks.unlocked[a.Address]
   273  	if !found {
   274  		return nil, ErrLocked
   275  	}
   276  
   277  	pk := unlockedKey.Dilithium.GetPK()
   278  
   279  	return pk[:], nil
   280  }
   281  
   282  // SignTx signs the given transaction with the requested account.
   283  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   284  	// Look up the key to sign with and abort if it cannot be found
   285  	ks.mu.RLock()
   286  	defer ks.mu.RUnlock()
   287  
   288  	unlockedKey, found := ks.unlocked[a.Address]
   289  	if !found {
   290  		return nil, ErrLocked
   291  	}
   292  	signer := types.LatestSignerForChainID(chainID)
   293  	return types.SignTx(tx, signer, unlockedKey.Dilithium)
   294  }
   295  
   296  // SignHashWithPassphrase signs hash if the private key matching the given address
   297  // can be decrypted with the given passphrase. The produced signature is in the
   298  // [R || S || V] format where V is 0 or 1.
   299  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   300  	_, key, err := ks.getDecryptedKey(a, passphrase)
   301  	if err != nil {
   302  		return nil, err
   303  	}
   304  	defer zeroKey(&key.Dilithium)
   305  	return pqcrypto.Sign(hash, key.Dilithium)
   306  }
   307  
   308  // SignTxWithPassphrase signs the transaction if the private key matching the
   309  // given address can be decrypted with the given passphrase.
   310  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   311  	_, key, err := ks.getDecryptedKey(a, passphrase)
   312  	if err != nil {
   313  		return nil, err
   314  	}
   315  	defer zeroKey(&key.Dilithium)
   316  	// Depending on the presence of the chain ID, sign with or without replay protection.
   317  	signer := types.LatestSignerForChainID(chainID)
   318  	return types.SignTx(tx, signer, key.Dilithium)
   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.Dilithium)
   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.Dilithium)
   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, 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.Dilithium != nil {
   445  		defer zeroKey(&key.Dilithium)
   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  // ImportDilithium stores the given key into the key directory, encrypting it with the passphrase.
   462  func (ks *KeyStore) ImportDilithium(d *dilithium.Dilithium, passphrase string) (accounts.Account, error) {
   463  	ks.importMu.Lock()
   464  	defer ks.importMu.Unlock()
   465  
   466  	key := newKeyFromDilithium(d)
   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  // isUpdating returns whether the event notification loop is running.
   495  // This method is mainly meant for tests.
   496  func (ks *KeyStore) isUpdating() bool {
   497  	ks.mu.RLock()
   498  	defer ks.mu.RUnlock()
   499  	return ks.updating
   500  }
   501  
   502  // zeroKey nil to dilithium key in memory.
   503  func zeroKey(k **dilithium.Dilithium) {
   504  	*k = nil
   505  }