github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/accounts/keystore/keystore.go (about)

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