github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/accounts/keystore/keystore.go (about)

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