github.com/klaytn/klaytn@v1.12.1/accounts/keystore/keystore_test.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2017 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum 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-ethereum 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-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from accounts/keystore/keystore_test.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package keystore
    22  
    23  import (
    24  	"crypto/ecdsa"
    25  	"math/big"
    26  	"math/rand"
    27  	"os"
    28  	"runtime"
    29  	"sort"
    30  	"strings"
    31  	"testing"
    32  	"time"
    33  
    34  	"github.com/klaytn/klaytn/blockchain/types"
    35  	"github.com/klaytn/klaytn/crypto"
    36  	"github.com/klaytn/klaytn/params"
    37  	"github.com/stretchr/testify/assert"
    38  
    39  	"github.com/klaytn/klaytn/accounts"
    40  	"github.com/klaytn/klaytn/common"
    41  	"github.com/klaytn/klaytn/event"
    42  )
    43  
    44  var testSigData = make([]byte, 32)
    45  
    46  func TestKeyStore(t *testing.T) {
    47  	dir, ks := tmpKeyStore(t, true)
    48  	defer os.RemoveAll(dir)
    49  
    50  	a, err := ks.NewAccount("foo")
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	if !strings.HasPrefix(a.URL.Path, dir) {
    55  		t.Errorf("account file %s doesn't have dir prefix", a.URL)
    56  	}
    57  	stat, err := os.Stat(a.URL.Path)
    58  	if err != nil {
    59  		t.Fatalf("account file %s doesn't exist (%v)", a.URL, err)
    60  	}
    61  	if runtime.GOOS != "windows" && stat.Mode() != 0o600 {
    62  		t.Fatalf("account file has wrong mode: got %o, want %o", stat.Mode(), 0o600)
    63  	}
    64  	if !ks.HasAddress(a.Address) {
    65  		t.Errorf("HasAccount(%x) should've returned true", a.Address)
    66  	}
    67  	if err := ks.Update(a, "foo", "bar"); err != nil {
    68  		t.Errorf("Update error: %v", err)
    69  	}
    70  	if err := ks.Delete(a, "bar"); err != nil {
    71  		t.Errorf("Delete error: %v", err)
    72  	}
    73  	if common.FileExist(a.URL.Path) {
    74  		t.Errorf("account file %s should be gone after Delete", a.URL)
    75  	}
    76  	if ks.HasAddress(a.Address) {
    77  		t.Errorf("HasAccount(%x) should've returned true after Delete", a.Address)
    78  	}
    79  }
    80  
    81  func TestSign(t *testing.T) {
    82  	dir, ks := tmpKeyStore(t, true)
    83  	defer os.RemoveAll(dir)
    84  
    85  	pass := "" // not used but required by API
    86  	a1, err := ks.NewAccount(pass)
    87  	if err != nil {
    88  		t.Fatal(err)
    89  	}
    90  	if err := ks.Unlock(a1, ""); err != nil {
    91  		t.Fatal(err)
    92  	}
    93  	if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err != nil {
    94  		t.Fatal(err)
    95  	}
    96  }
    97  
    98  func TestSignWithPassphrase(t *testing.T) {
    99  	dir, ks := tmpKeyStore(t, true)
   100  	defer os.RemoveAll(dir)
   101  
   102  	pass := "passwd"
   103  	acc, err := ks.NewAccount(pass)
   104  	if err != nil {
   105  		t.Fatal(err)
   106  	}
   107  
   108  	if _, unlocked := ks.unlocked[acc.Address]; unlocked {
   109  		t.Fatal("expected account to be locked")
   110  	}
   111  
   112  	_, err = ks.SignHashWithPassphrase(acc, pass, testSigData)
   113  	if err != nil {
   114  		t.Fatal(err)
   115  	}
   116  
   117  	if _, unlocked := ks.unlocked[acc.Address]; unlocked {
   118  		t.Fatal("expected account to be locked")
   119  	}
   120  
   121  	if _, err = ks.SignHashWithPassphrase(acc, "invalid passwd", testSigData); err == nil {
   122  		t.Fatal("expected SignHashWithPassphrase to fail with invalid password")
   123  	}
   124  }
   125  
   126  func TestTimedUnlock(t *testing.T) {
   127  	dir, ks := tmpKeyStore(t, true)
   128  	defer os.RemoveAll(dir)
   129  
   130  	pass := "foo"
   131  	a1, err := ks.NewAccount(pass)
   132  	if err != nil {
   133  		t.Fatal(err)
   134  	}
   135  
   136  	// Signing without passphrase fails because account is locked
   137  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   138  	if err != ErrLocked {
   139  		t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err)
   140  	}
   141  
   142  	// Signing with passphrase works
   143  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   144  		t.Fatal(err)
   145  	}
   146  
   147  	// Signing without passphrase works because account is temp unlocked
   148  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   149  	if err != nil {
   150  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   151  	}
   152  
   153  	// Signing fails again after automatic locking
   154  	time.Sleep(250 * time.Millisecond)
   155  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   156  	if err != ErrLocked {
   157  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   158  	}
   159  }
   160  
   161  func TestOverrideUnlock(t *testing.T) {
   162  	dir, ks := tmpKeyStore(t, false)
   163  	defer os.RemoveAll(dir)
   164  
   165  	pass := "foo"
   166  	a1, err := ks.NewAccount(pass)
   167  	if err != nil {
   168  		t.Fatal(err)
   169  	}
   170  
   171  	// Unlock indefinitely.
   172  	if err = ks.TimedUnlock(a1, pass, 5*time.Minute); err != nil {
   173  		t.Fatal(err)
   174  	}
   175  
   176  	// Signing without passphrase works because account is temp unlocked
   177  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   178  	if err != nil {
   179  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   180  	}
   181  
   182  	// reset unlock to a shorter period, invalidates the previous unlock
   183  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   184  		t.Fatal(err)
   185  	}
   186  
   187  	// Signing without passphrase still works because account is temp unlocked
   188  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   189  	if err != nil {
   190  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   191  	}
   192  
   193  	// Signing fails again after automatic locking
   194  	time.Sleep(250 * time.Millisecond)
   195  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   196  	if err != ErrLocked {
   197  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   198  	}
   199  }
   200  
   201  // This test should fail under -race if signing races the expiration goroutine.
   202  func TestSignRace(t *testing.T) {
   203  	dir, ks := tmpKeyStore(t, false)
   204  	defer os.RemoveAll(dir)
   205  
   206  	// Create a test account.
   207  	a1, err := ks.NewAccount("")
   208  	if err != nil {
   209  		t.Fatal("could not create the test account", err)
   210  	}
   211  
   212  	if err := ks.TimedUnlock(a1, "", 15*time.Millisecond); err != nil {
   213  		t.Fatal("could not unlock the test account", err)
   214  	}
   215  	end := time.Now().Add(500 * time.Millisecond)
   216  	for time.Now().Before(end) {
   217  		if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked {
   218  			return
   219  		} else if err != nil {
   220  			t.Errorf("Sign error: %v", err)
   221  			return
   222  		}
   223  		time.Sleep(1 * time.Millisecond)
   224  	}
   225  	t.Errorf("Account did not lock within the timeout")
   226  }
   227  
   228  // Tests that the wallet notifier loop starts and stops correctly based on the
   229  // addition and removal of wallet event subscriptions.
   230  func TestWalletNotifierLifecycle(t *testing.T) {
   231  	// Create a temporary kesytore to test with
   232  	dir, ks := tmpKeyStore(t, false)
   233  	defer os.RemoveAll(dir)
   234  
   235  	// Ensure that the notification updater is not running yet
   236  	time.Sleep(250 * time.Millisecond)
   237  	ks.mu.RLock()
   238  	updating := ks.updating
   239  	ks.mu.RUnlock()
   240  
   241  	if updating {
   242  		t.Errorf("wallet notifier running without subscribers")
   243  	}
   244  	// Subscribe to the wallet feed and ensure the updater boots up
   245  	updates := make(chan accounts.WalletEvent)
   246  
   247  	subs := make([]event.Subscription, 2)
   248  	for i := 0; i < len(subs); i++ {
   249  		// Create a new subscription
   250  		subs[i] = ks.Subscribe(updates)
   251  
   252  		// Ensure the notifier comes online
   253  		time.Sleep(250 * time.Millisecond)
   254  		ks.mu.RLock()
   255  		updating = ks.updating
   256  		ks.mu.RUnlock()
   257  
   258  		if !updating {
   259  			t.Errorf("sub %d: wallet notifier not running after subscription", i)
   260  		}
   261  	}
   262  	// Unsubscribe and ensure the updater terminates eventually
   263  	for i := 0; i < len(subs); i++ {
   264  		// Close an existing subscription
   265  		subs[i].Unsubscribe()
   266  
   267  		// Ensure the notifier shuts down at and only at the last close
   268  		for k := 0; k < int(walletRefreshCycle/(250*time.Millisecond))+2; k++ {
   269  			ks.mu.RLock()
   270  			updating = ks.updating
   271  			ks.mu.RUnlock()
   272  
   273  			if i < len(subs)-1 && !updating {
   274  				t.Fatalf("sub %d: event notifier stopped prematurely", i)
   275  			}
   276  			if i == len(subs)-1 && !updating {
   277  				return
   278  			}
   279  			time.Sleep(250 * time.Millisecond)
   280  		}
   281  	}
   282  	t.Errorf("wallet notifier didn't terminate after unsubscribe")
   283  }
   284  
   285  type walletEvent struct {
   286  	accounts.WalletEvent
   287  	a accounts.Account
   288  }
   289  
   290  // Tests that wallet notifications and correctly fired when accounts are added
   291  // or deleted from the keystore.
   292  func TestWalletNotifications(t *testing.T) {
   293  	dir, ks := tmpKeyStore(t, false)
   294  	defer os.RemoveAll(dir)
   295  
   296  	// Subscribe to the wallet feed and collect events.
   297  	var (
   298  		events  []walletEvent
   299  		updates = make(chan accounts.WalletEvent)
   300  		sub     = ks.Subscribe(updates)
   301  	)
   302  	defer sub.Unsubscribe()
   303  	go func() {
   304  		for {
   305  			select {
   306  			case ev := <-updates:
   307  				events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   308  			case <-sub.Err():
   309  				close(updates)
   310  				return
   311  			}
   312  		}
   313  	}()
   314  
   315  	// Randomly add and remove accounts.
   316  	var (
   317  		live       = make(map[common.Address]accounts.Account)
   318  		wantEvents []walletEvent
   319  	)
   320  	for i := 0; i < 1024; i++ {
   321  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   322  			// Add a new account and ensure wallet notifications arrives
   323  			account, err := ks.NewAccount("")
   324  			if err != nil {
   325  				t.Fatalf("failed to create test account: %v", err)
   326  			}
   327  			live[account.Address] = account
   328  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletArrived}, account})
   329  		} else {
   330  			// Delete a random account.
   331  			var account accounts.Account
   332  			for _, a := range live {
   333  				account = a
   334  				break
   335  			}
   336  			if err := ks.Delete(account, ""); err != nil {
   337  				t.Fatalf("failed to delete test account: %v", err)
   338  			}
   339  			delete(live, account.Address)
   340  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletDropped}, account})
   341  		}
   342  	}
   343  
   344  	// Shut down the event collector and check events.
   345  	sub.Unsubscribe()
   346  	for ev := range updates {
   347  		events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   348  	}
   349  	checkAccounts(t, live, ks.Wallets())
   350  	checkEvents(t, wantEvents, events)
   351  }
   352  
   353  // checkAccounts checks that all known live accounts are present in the wallet list.
   354  func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
   355  	if len(live) != len(wallets) {
   356  		t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live))
   357  		return
   358  	}
   359  	liveList := make([]accounts.Account, 0, len(live))
   360  	for _, account := range live {
   361  		liveList = append(liveList, account)
   362  	}
   363  	sort.Sort(accountsByURL(liveList))
   364  	for j, wallet := range wallets {
   365  		if accs := wallet.Accounts(); len(accs) != 1 {
   366  			t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   367  		} else if accs[0] != liveList[j] {
   368  			t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   369  		}
   370  	}
   371  }
   372  
   373  // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times.
   374  func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
   375  	for _, wantEv := range want {
   376  		nmatch := 0
   377  		for ; len(have) > 0; nmatch++ {
   378  			if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a {
   379  				break
   380  			}
   381  			have = have[1:]
   382  		}
   383  		if nmatch == 0 {
   384  			t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address)
   385  		}
   386  	}
   387  }
   388  
   389  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   390  	d, err := os.MkdirTemp("", "klay-keystore-test")
   391  	if err != nil {
   392  		t.Fatal(err)
   393  	}
   394  	newKs := NewPlaintextKeyStore
   395  	if encrypted {
   396  		newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   397  	}
   398  	return d, newKs(string(d))
   399  }
   400  
   401  // testTx returns a sample transaction and private keys of the sender and fee payer.
   402  func testTx() (*ecdsa.PrivateKey, *ecdsa.PrivateKey, *types.Transaction) {
   403  	// For signers
   404  	senderPrvKey, _ := crypto.HexToECDSA("95a21e86efa290d6665a9dbce06ae56319335540d13540fb1b01e28a5b2c8460")
   405  	feePayerPrvKey, _ := crypto.HexToECDSA("f45a87856d14357609ce6b99645a1a7889deafbf00848bbdace60d8cd10466fa")
   406  
   407  	values := map[types.TxValueKeyType]interface{}{
   408  		types.TxValueKeyNonce:    uint64(0),
   409  		types.TxValueKeyFrom:     common.HexToAddress("0xa7Eb6992c5FD55F43305B24Ee67150Bf4910d329"),
   410  		types.TxValueKeyTo:       common.HexToAddress("0xF9Fad0E94B216faFFfEfB99Ef02CE44F994A3DE8"),
   411  		types.TxValueKeyAmount:   new(big.Int).SetUint64(0),
   412  		types.TxValueKeyGasLimit: uint64(100000),
   413  		types.TxValueKeyGasPrice: new(big.Int).SetUint64(25 * params.Ston),
   414  		types.TxValueKeyFeePayer: common.HexToAddress("0xF9Fad0E94B216faFFfEfB99Ef02CE44F994A3DE8"),
   415  	}
   416  
   417  	tx, err := types.NewTransactionWithMap(types.TxTypeFeeDelegatedValueTransfer, values)
   418  	if err != nil {
   419  		panic("Error to generate a test tx")
   420  	}
   421  
   422  	return senderPrvKey, feePayerPrvKey, tx
   423  }
   424  
   425  // TestKeyStore_SignTx tests the tx signing function of KeyStore.
   426  func TestKeyStore_SignTx(t *testing.T) {
   427  	chainID := big.NewInt(1)
   428  
   429  	// test transaction and the private key of the sender
   430  	senderPrvKey, _, tx := testTx()
   431  
   432  	// generate a keystore and an active account
   433  	dir, ks := tmpKeyStore(t, true)
   434  	defer os.RemoveAll(dir)
   435  
   436  	password := ""
   437  	acc, err := ks.ImportECDSA(senderPrvKey, password)
   438  	if err != nil {
   439  		t.Fatal(err)
   440  	}
   441  	if err := ks.Unlock(acc, password); err != nil {
   442  		t.Fatal(err)
   443  	}
   444  
   445  	// get a signature from a signing function in KeyStore
   446  	tx, err = ks.SignTx(accounts.Account{Address: acc.Address}, tx, chainID)
   447  	if err != nil {
   448  		t.Fatal(err)
   449  	}
   450  	sig1 := tx.RawSignatureValues()
   451  
   452  	// get another signature from a signing function in types package
   453  	signer := types.LatestSignerForChainID(chainID)
   454  	if tx.SignWithKeys(signer, []*ecdsa.PrivateKey{senderPrvKey}) != nil {
   455  		t.Fatal("Error to sign")
   456  	}
   457  	sig2 := tx.RawSignatureValues()
   458  
   459  	// Two signing functions should return the same signature
   460  	assert.Equal(t, sig2, sig1)
   461  }
   462  
   463  // TestKeyStore_SignTxAsFeePayer tests the fee payer's tx signing function of KeyStore.
   464  func TestKeyStore_SignTxAsFeePayer(t *testing.T) {
   465  	chainID := big.NewInt(1)
   466  
   467  	// test transaction and the private key of the sender
   468  	_, feePayerPrvKey, tx := testTx()
   469  
   470  	// generate a keystore and an active account
   471  	dir, ks := tmpKeyStore(t, true)
   472  	defer os.RemoveAll(dir)
   473  
   474  	password := ""
   475  	acc, err := ks.ImportECDSA(feePayerPrvKey, password)
   476  	if err != nil {
   477  		t.Fatal(err)
   478  	}
   479  	if err := ks.Unlock(acc, password); err != nil {
   480  		t.Fatal(err)
   481  	}
   482  
   483  	// get a signature from a signing function in KeyStore
   484  	tx, err = ks.SignTxAsFeePayer(accounts.Account{Address: acc.Address}, tx, chainID)
   485  	if err != nil {
   486  		t.Fatal(err)
   487  	}
   488  	sig1, err := tx.GetFeePayerSignatures()
   489  	if err != nil {
   490  		t.Fatal(err)
   491  	}
   492  
   493  	// get another signature from a signing function in types package
   494  	signer := types.LatestSignerForChainID(chainID)
   495  	if tx.SignFeePayerWithKeys(signer, []*ecdsa.PrivateKey{feePayerPrvKey}) != nil {
   496  		t.Fatal("Error to sign")
   497  	}
   498  	sig2, err := tx.GetFeePayerSignatures()
   499  	if err != nil {
   500  		t.Fatal(err)
   501  	}
   502  
   503  	// Two signing functions should return the same value
   504  	assert.Equal(t, sig2, sig1)
   505  }