github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/keystore/keystore.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Package keystore implements encrypted storage of secp256k1 private keys.
    19  //
    20  // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
    21  // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
    22  package keystore
    23  
    24  import (
    25  	"crypto/ecdsa"
    26  	crand "crypto/rand"
    27  	"errors"
    28  	"fmt"
    29  	"math/big"
    30  	"os"
    31  	"path/filepath"
    32  	"reflect"
    33  	"runtime"
    34  	"sync"
    35  	"time"
    36  
    37  	"github.com/AigarNetwork/aigar/accounts"
    38  	"github.com/AigarNetwork/aigar/common"
    39  	"github.com/AigarNetwork/aigar/core/types"
    40  	"github.com/AigarNetwork/aigar/crypto"
    41  	"github.com/AigarNetwork/aigar/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 password")
    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  	var (
   142  		wallets = make([]accounts.Wallet, 0, len(accs))
   143  		events  []accounts.WalletEvent
   144  	)
   145  
   146  	for _, account := range accs {
   147  		// Drop wallets while they were in front of the next account
   148  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   149  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   150  			ks.wallets = ks.wallets[1:]
   151  		}
   152  		// If there are no more wallets or the account is before the next, wrap new wallet
   153  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   154  			wallet := &keystoreWallet{account: account, keystore: ks}
   155  
   156  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   157  			wallets = append(wallets, wallet)
   158  			continue
   159  		}
   160  		// If the account is the same as the first wallet, keep it
   161  		if ks.wallets[0].Accounts()[0] == account {
   162  			wallets = append(wallets, ks.wallets[0])
   163  			ks.wallets = ks.wallets[1:]
   164  			continue
   165  		}
   166  	}
   167  	// Drop any leftover wallets and set the new batch
   168  	for _, wallet := range ks.wallets {
   169  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   170  	}
   171  	ks.wallets = wallets
   172  	ks.mu.Unlock()
   173  
   174  	// Fire all wallet events and return
   175  	for _, event := range events {
   176  		ks.updateFeed.Send(event)
   177  	}
   178  }
   179  
   180  // Subscribe implements accounts.Backend, creating an async subscription to
   181  // receive notifications on the addition or removal of keystore wallets.
   182  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   183  	// We need the mutex to reliably start/stop the update loop
   184  	ks.mu.Lock()
   185  	defer ks.mu.Unlock()
   186  
   187  	// Subscribe the caller and track the subscriber count
   188  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   189  
   190  	// Subscribers require an active notification loop, start it
   191  	if !ks.updating {
   192  		ks.updating = true
   193  		go ks.updater()
   194  	}
   195  	return sub
   196  }
   197  
   198  // updater is responsible for maintaining an up-to-date list of wallets stored in
   199  // the keystore, and for firing wallet addition/removal events. It listens for
   200  // account change events from the underlying account cache, and also periodically
   201  // forces a manual refresh (only triggers for systems where the filesystem notifier
   202  // is not running).
   203  func (ks *KeyStore) updater() {
   204  	for {
   205  		// Wait for an account update or a refresh timeout
   206  		select {
   207  		case <-ks.changes:
   208  		case <-time.After(walletRefreshCycle):
   209  		}
   210  		// Run the wallet refresher
   211  		ks.refreshWallets()
   212  
   213  		// If all our subscribers left, stop the updater
   214  		ks.mu.Lock()
   215  		if ks.updateScope.Count() == 0 {
   216  			ks.updating = false
   217  			ks.mu.Unlock()
   218  			return
   219  		}
   220  		ks.mu.Unlock()
   221  	}
   222  }
   223  
   224  // HasAddress reports whether a key with the given address is present.
   225  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   226  	return ks.cache.hasAddress(addr)
   227  }
   228  
   229  // Accounts returns all key files present in the directory.
   230  func (ks *KeyStore) Accounts() []accounts.Account {
   231  	return ks.cache.accounts()
   232  }
   233  
   234  // Delete deletes the key matched by account if the passphrase is correct.
   235  // If the account contains no filename, the address must match a unique key.
   236  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   237  	// Decrypting the key isn't really necessary, but we do
   238  	// it anyway to check the password and zero out the key
   239  	// immediately afterwards.
   240  	a, key, err := ks.getDecryptedKey(a, passphrase)
   241  	if key != nil {
   242  		zeroKey(key.PrivateKey)
   243  	}
   244  	if err != nil {
   245  		return err
   246  	}
   247  	// The order is crucial here. The key is dropped from the
   248  	// cache after the file is gone so that a reload happening in
   249  	// between won't insert it into the cache again.
   250  	err = os.Remove(a.URL.Path)
   251  	if err == nil {
   252  		ks.cache.delete(a)
   253  		ks.refreshWallets()
   254  	}
   255  	return err
   256  }
   257  
   258  // SignHash calculates a ECDSA signature for the given hash. The produced
   259  // signature is in the [R || S || V] format where V is 0 or 1.
   260  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   261  	// Look up the key to sign with and abort if it cannot be found
   262  	ks.mu.RLock()
   263  	defer ks.mu.RUnlock()
   264  
   265  	unlockedKey, found := ks.unlocked[a.Address]
   266  	if !found {
   267  		return nil, ErrLocked
   268  	}
   269  	// Sign the hash using plain ECDSA operations
   270  	return crypto.Sign(hash, unlockedKey.PrivateKey)
   271  }
   272  
   273  // SignTx signs the given transaction with the requested account.
   274  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   275  	// Look up the key to sign with and abort if it cannot be found
   276  	ks.mu.RLock()
   277  	defer ks.mu.RUnlock()
   278  
   279  	unlockedKey, found := ks.unlocked[a.Address]
   280  	if !found {
   281  		return nil, ErrLocked
   282  	}
   283  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   284  	if chainID != nil {
   285  		return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
   286  	}
   287  	return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
   288  }
   289  
   290  // SignHashWithPassphrase signs hash if the private key matching the given address
   291  // can be decrypted with the given passphrase. The produced signature is in the
   292  // [R || S || V] format where V is 0 or 1.
   293  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   294  	_, key, err := ks.getDecryptedKey(a, passphrase)
   295  	if err != nil {
   296  		return nil, err
   297  	}
   298  	defer zeroKey(key.PrivateKey)
   299  	return crypto.Sign(hash, key.PrivateKey)
   300  }
   301  
   302  // SignTxWithPassphrase signs the transaction if the private key matching the
   303  // given address can be decrypted with the given passphrase.
   304  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   305  	_, key, err := ks.getDecryptedKey(a, passphrase)
   306  	if err != nil {
   307  		return nil, err
   308  	}
   309  	defer zeroKey(key.PrivateKey)
   310  
   311  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   312  	if chainID != nil {
   313  		return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
   314  	}
   315  	return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
   316  }
   317  
   318  // Unlock unlocks the given account indefinitely.
   319  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
   320  	return ks.TimedUnlock(a, passphrase, 0)
   321  }
   322  
   323  // Lock removes the private key with the given address from memory.
   324  func (ks *KeyStore) Lock(addr common.Address) error {
   325  	ks.mu.Lock()
   326  	if unl, found := ks.unlocked[addr]; found {
   327  		ks.mu.Unlock()
   328  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   329  	} else {
   330  		ks.mu.Unlock()
   331  	}
   332  	return nil
   333  }
   334  
   335  // TimedUnlock unlocks the given account with the passphrase. The account
   336  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   337  // until the program exits. The account must match a unique key file.
   338  //
   339  // If the account address is already unlocked for a duration, TimedUnlock extends or
   340  // shortens the active unlock timeout. If the address was previously unlocked
   341  // indefinitely the timeout is not altered.
   342  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
   343  	a, key, err := ks.getDecryptedKey(a, passphrase)
   344  	if err != nil {
   345  		return err
   346  	}
   347  
   348  	ks.mu.Lock()
   349  	defer ks.mu.Unlock()
   350  	u, found := ks.unlocked[a.Address]
   351  	if found {
   352  		if u.abort == nil {
   353  			// The address was unlocked indefinitely, so unlocking
   354  			// it with a timeout would be confusing.
   355  			zeroKey(key.PrivateKey)
   356  			return nil
   357  		}
   358  		// Terminate the expire goroutine and replace it below.
   359  		close(u.abort)
   360  	}
   361  	if timeout > 0 {
   362  		u = &unlocked{Key: key, abort: make(chan struct{})}
   363  		go ks.expire(a.Address, u, timeout)
   364  	} else {
   365  		u = &unlocked{Key: key}
   366  	}
   367  	ks.unlocked[a.Address] = u
   368  	return nil
   369  }
   370  
   371  // Find resolves the given account into a unique entry in the keystore.
   372  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   373  	ks.cache.maybeReload()
   374  	ks.cache.mu.Lock()
   375  	a, err := ks.cache.find(a)
   376  	ks.cache.mu.Unlock()
   377  	return a, err
   378  }
   379  
   380  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   381  	a, err := ks.Find(a)
   382  	if err != nil {
   383  		return a, nil, err
   384  	}
   385  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   386  	return a, key, err
   387  }
   388  
   389  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   390  	t := time.NewTimer(timeout)
   391  	defer t.Stop()
   392  	select {
   393  	case <-u.abort:
   394  		// just quit
   395  	case <-t.C:
   396  		ks.mu.Lock()
   397  		// only drop if it's still the same key instance that dropLater
   398  		// was launched with. we can check that using pointer equality
   399  		// because the map stores a new pointer every time the key is
   400  		// unlocked.
   401  		if ks.unlocked[addr] == u {
   402  			zeroKey(u.PrivateKey)
   403  			delete(ks.unlocked, addr)
   404  		}
   405  		ks.mu.Unlock()
   406  	}
   407  }
   408  
   409  // NewAccount generates a new key and stores it into the key directory,
   410  // encrypting it with the passphrase.
   411  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   412  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   413  	if err != nil {
   414  		return accounts.Account{}, err
   415  	}
   416  	// Add the account to the cache immediately rather
   417  	// than waiting for file system notifications to pick it up.
   418  	ks.cache.add(account)
   419  	ks.refreshWallets()
   420  	return account, nil
   421  }
   422  
   423  // Export exports as a JSON key, encrypted with newPassphrase.
   424  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   425  	_, key, err := ks.getDecryptedKey(a, passphrase)
   426  	if err != nil {
   427  		return nil, err
   428  	}
   429  	var N, P int
   430  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   431  		N, P = store.scryptN, store.scryptP
   432  	} else {
   433  		N, P = StandardScryptN, StandardScryptP
   434  	}
   435  	return EncryptKey(key, newPassphrase, N, P)
   436  }
   437  
   438  // Import stores the given encrypted JSON key into the key directory.
   439  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   440  	key, err := DecryptKey(keyJSON, passphrase)
   441  	if key != nil && key.PrivateKey != nil {
   442  		defer zeroKey(key.PrivateKey)
   443  	}
   444  	if err != nil {
   445  		return accounts.Account{}, err
   446  	}
   447  	return ks.importKey(key, newPassphrase)
   448  }
   449  
   450  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   451  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   452  	key := newKeyFromECDSA(priv)
   453  	if ks.cache.hasAddress(key.Address) {
   454  		return accounts.Account{}, fmt.Errorf("account already exists")
   455  	}
   456  	return ks.importKey(key, passphrase)
   457  }
   458  
   459  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   460  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   461  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   462  		return accounts.Account{}, err
   463  	}
   464  	ks.cache.add(a)
   465  	ks.refreshWallets()
   466  	return a, nil
   467  }
   468  
   469  // Update changes the passphrase of an existing account.
   470  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   471  	a, key, err := ks.getDecryptedKey(a, passphrase)
   472  	if err != nil {
   473  		return err
   474  	}
   475  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   476  }
   477  
   478  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   479  // a key file in the key directory. The key file is encrypted with the same passphrase.
   480  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   481  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   482  	if err != nil {
   483  		return a, err
   484  	}
   485  	ks.cache.add(a)
   486  	ks.refreshWallets()
   487  	return a, nil
   488  }
   489  
   490  // zeroKey zeroes a private key in memory.
   491  func zeroKey(k *ecdsa.PrivateKey) {
   492  	b := k.D.Bits()
   493  	for i := range b {
   494  		b[i] = 0
   495  	}
   496  }