github.com/ava-labs/subnet-evm@v0.6.4/accounts/keystore/keystore_test.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2017 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package keystore
    28  
    29  import (
    30  	"math/rand"
    31  	"os"
    32  	"runtime"
    33  	"strings"
    34  	"sync"
    35  	"sync/atomic"
    36  	"testing"
    37  	"time"
    38  
    39  	"github.com/ava-labs/subnet-evm/accounts"
    40  	"github.com/ethereum/go-ethereum/common"
    41  	"github.com/ethereum/go-ethereum/crypto"
    42  	"github.com/ethereum/go-ethereum/event"
    43  	"golang.org/x/exp/slices"
    44  )
    45  
    46  var testSigData = make([]byte, 32)
    47  
    48  func TestKeyStore(t *testing.T) {
    49  	dir, ks := tmpKeyStore(t, true)
    50  
    51  	a, err := ks.NewAccount("foo")
    52  	if err != nil {
    53  		t.Fatal(err)
    54  	}
    55  	if !strings.HasPrefix(a.URL.Path, dir) {
    56  		t.Errorf("account file %s doesn't have dir prefix", a.URL)
    57  	}
    58  	stat, err := os.Stat(a.URL.Path)
    59  	if err != nil {
    60  		t.Fatalf("account file %s doesn't exist (%v)", a.URL, err)
    61  	}
    62  	if runtime.GOOS != "windows" && stat.Mode() != 0600 {
    63  		t.Fatalf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600)
    64  	}
    65  	if !ks.HasAddress(a.Address) {
    66  		t.Errorf("HasAccount(%x) should've returned true", a.Address)
    67  	}
    68  	if err := ks.Update(a, "foo", "bar"); err != nil {
    69  		t.Errorf("Update error: %v", err)
    70  	}
    71  	if err := ks.Delete(a, "bar"); err != nil {
    72  		t.Errorf("Delete error: %v", err)
    73  	}
    74  	if common.FileExist(a.URL.Path) {
    75  		t.Errorf("account file %s should be gone after Delete", a.URL)
    76  	}
    77  	if ks.HasAddress(a.Address) {
    78  		t.Errorf("HasAccount(%x) should've returned true after Delete", a.Address)
    79  	}
    80  }
    81  
    82  func TestSign(t *testing.T) {
    83  	_, ks := tmpKeyStore(t, true)
    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  	_, ks := tmpKeyStore(t, true)
   100  
   101  	pass := "passwd"
   102  	acc, err := ks.NewAccount(pass)
   103  	if err != nil {
   104  		t.Fatal(err)
   105  	}
   106  
   107  	if _, unlocked := ks.unlocked[acc.Address]; unlocked {
   108  		t.Fatal("expected account to be locked")
   109  	}
   110  
   111  	_, err = ks.SignHashWithPassphrase(acc, pass, testSigData)
   112  	if err != nil {
   113  		t.Fatal(err)
   114  	}
   115  
   116  	if _, unlocked := ks.unlocked[acc.Address]; unlocked {
   117  		t.Fatal("expected account to be locked")
   118  	}
   119  
   120  	if _, err = ks.SignHashWithPassphrase(acc, "invalid passwd", testSigData); err == nil {
   121  		t.Fatal("expected SignHashWithPassphrase to fail with invalid password")
   122  	}
   123  }
   124  
   125  func TestTimedUnlock(t *testing.T) {
   126  	t.Parallel()
   127  	_, ks := tmpKeyStore(t, true)
   128  
   129  	pass := "foo"
   130  	a1, err := ks.NewAccount(pass)
   131  	if err != nil {
   132  		t.Fatal(err)
   133  	}
   134  
   135  	// Signing without passphrase fails because account is locked
   136  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   137  	if err != ErrLocked {
   138  		t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err)
   139  	}
   140  
   141  	// Signing with passphrase works
   142  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   143  		t.Fatal(err)
   144  	}
   145  
   146  	// Signing without passphrase works because account is temp unlocked
   147  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   148  	if err != nil {
   149  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   150  	}
   151  
   152  	// Signing fails again after automatic locking
   153  	time.Sleep(250 * time.Millisecond)
   154  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   155  	if err != ErrLocked {
   156  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   157  	}
   158  }
   159  
   160  func TestOverrideUnlock(t *testing.T) {
   161  	t.Parallel()
   162  	_, ks := tmpKeyStore(t, false)
   163  
   164  	pass := "foo"
   165  	a1, err := ks.NewAccount(pass)
   166  	if err != nil {
   167  		t.Fatal(err)
   168  	}
   169  
   170  	// Unlock indefinitely.
   171  	if err = ks.TimedUnlock(a1, pass, 5*time.Minute); err != nil {
   172  		t.Fatal(err)
   173  	}
   174  
   175  	// Signing without passphrase works because account is temp unlocked
   176  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   177  	if err != nil {
   178  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   179  	}
   180  
   181  	// reset unlock to a shorter period, invalidates the previous unlock
   182  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   183  		t.Fatal(err)
   184  	}
   185  
   186  	// Signing without passphrase still works because account is temp unlocked
   187  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   188  	if err != nil {
   189  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   190  	}
   191  
   192  	// Signing fails again after automatic locking
   193  	time.Sleep(250 * time.Millisecond)
   194  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   195  	if err != ErrLocked {
   196  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   197  	}
   198  }
   199  
   200  // This test should fail under -race if signing races the expiration goroutine.
   201  func TestSignRace(t *testing.T) {
   202  	t.Parallel()
   203  	_, ks := tmpKeyStore(t, false)
   204  
   205  	// Create a test account.
   206  	a1, err := ks.NewAccount("")
   207  	if err != nil {
   208  		t.Fatal("could not create the test account", err)
   209  	}
   210  
   211  	if err := ks.TimedUnlock(a1, "", 15*time.Millisecond); err != nil {
   212  		t.Fatal("could not unlock the test account", err)
   213  	}
   214  	end := time.Now().Add(500 * time.Millisecond)
   215  	for time.Now().Before(end) {
   216  		if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked {
   217  			return
   218  		} else if err != nil {
   219  			t.Errorf("Sign error: %v", err)
   220  			return
   221  		}
   222  		time.Sleep(1 * time.Millisecond)
   223  	}
   224  	t.Errorf("Account did not lock within the timeout")
   225  }
   226  
   227  // waitForKsUpdating waits until the updating-status of the ks reaches the
   228  // desired wantStatus.
   229  // It waits for a maximum time of maxTime, and returns false if it does not
   230  // finish in time
   231  func waitForKsUpdating(t *testing.T, ks *KeyStore, wantStatus bool, maxTime time.Duration) bool {
   232  	t.Helper()
   233  	// Wait max 250 ms, then return false
   234  	for t0 := time.Now(); time.Since(t0) < maxTime; {
   235  		if ks.isUpdating() == wantStatus {
   236  			return true
   237  		}
   238  		time.Sleep(25 * time.Millisecond)
   239  	}
   240  	return false
   241  }
   242  
   243  // Tests that the wallet notifier loop starts and stops correctly based on the
   244  // addition and removal of wallet event subscriptions.
   245  func TestWalletNotifierLifecycle(t *testing.T) {
   246  	t.Parallel()
   247  	// Create a temporary keystore to test with
   248  	_, ks := tmpKeyStore(t, false)
   249  
   250  	// Ensure that the notification updater is not running yet
   251  	time.Sleep(250 * time.Millisecond)
   252  
   253  	if ks.isUpdating() {
   254  		t.Errorf("wallet notifier running without subscribers")
   255  	}
   256  	// Subscribe to the wallet feed and ensure the updater boots up
   257  	updates := make(chan accounts.WalletEvent)
   258  
   259  	subs := make([]event.Subscription, 2)
   260  	for i := 0; i < len(subs); i++ {
   261  		// Create a new subscription
   262  		subs[i] = ks.Subscribe(updates)
   263  		if !waitForKsUpdating(t, ks, true, 250*time.Millisecond) {
   264  			t.Errorf("sub %d: wallet notifier not running after subscription", i)
   265  		}
   266  	}
   267  	// Close all but one sub
   268  	for i := 0; i < len(subs)-1; i++ {
   269  		// Close an existing subscription
   270  		subs[i].Unsubscribe()
   271  	}
   272  	// Check that it is still running
   273  	time.Sleep(250 * time.Millisecond)
   274  
   275  	if !ks.isUpdating() {
   276  		t.Fatal("event notifier stopped prematurely")
   277  	}
   278  	// Unsubscribe the last one and ensure the updater terminates eventually.
   279  	subs[len(subs)-1].Unsubscribe()
   280  	if !waitForKsUpdating(t, ks, false, 4*time.Second) {
   281  		t.Errorf("wallet notifier didn't terminate after unsubscribe")
   282  	}
   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  	if os.Getenv("RUN_FLAKY_TESTS") != "true" {
   294  		t.Skip("FLAKY")
   295  	}
   296  	_, ks := tmpKeyStore(t, false)
   297  
   298  	// Subscribe to the wallet feed and collect events.
   299  	var (
   300  		events  []walletEvent
   301  		updates = make(chan accounts.WalletEvent)
   302  		sub     = ks.Subscribe(updates)
   303  	)
   304  	defer sub.Unsubscribe()
   305  	go func() {
   306  		for {
   307  			select {
   308  			case ev := <-updates:
   309  				events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   310  			case <-sub.Err():
   311  				close(updates)
   312  				return
   313  			}
   314  		}
   315  	}()
   316  
   317  	// Randomly add and remove accounts.
   318  	var (
   319  		live       = make(map[common.Address]accounts.Account)
   320  		wantEvents []walletEvent
   321  	)
   322  	for i := 0; i < 1024; i++ {
   323  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   324  			// Add a new account and ensure wallet notifications arrives
   325  			account, err := ks.NewAccount("")
   326  			if err != nil {
   327  				t.Fatalf("failed to create test account: %v", err)
   328  			}
   329  			live[account.Address] = account
   330  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletArrived}, account})
   331  		} else {
   332  			// Delete a random account.
   333  			var account accounts.Account
   334  			for _, a := range live {
   335  				account = a
   336  				break
   337  			}
   338  			if err := ks.Delete(account, ""); err != nil {
   339  				t.Fatalf("failed to delete test account: %v", err)
   340  			}
   341  			delete(live, account.Address)
   342  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletDropped}, account})
   343  		}
   344  	}
   345  
   346  	// Shut down the event collector and check events.
   347  	sub.Unsubscribe()
   348  	for ev := range updates {
   349  		events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   350  	}
   351  	checkAccounts(t, live, ks.Wallets())
   352  	checkEvents(t, wantEvents, events)
   353  }
   354  
   355  // TestImportExport tests the import functionality of a keystore.
   356  func TestImportECDSA(t *testing.T) {
   357  	_, ks := tmpKeyStore(t, true)
   358  	key, err := crypto.GenerateKey()
   359  	if err != nil {
   360  		t.Fatalf("failed to generate key: %v", key)
   361  	}
   362  	if _, err = ks.ImportECDSA(key, "old"); err != nil {
   363  		t.Errorf("importing failed: %v", err)
   364  	}
   365  	if _, err = ks.ImportECDSA(key, "old"); err == nil {
   366  		t.Errorf("importing same key twice succeeded")
   367  	}
   368  	if _, err = ks.ImportECDSA(key, "new"); err == nil {
   369  		t.Errorf("importing same key twice succeeded")
   370  	}
   371  }
   372  
   373  // TestImportECDSA tests the import and export functionality of a keystore.
   374  func TestImportExport(t *testing.T) {
   375  	_, ks := tmpKeyStore(t, true)
   376  	acc, err := ks.NewAccount("old")
   377  	if err != nil {
   378  		t.Fatalf("failed to create account: %v", acc)
   379  	}
   380  	json, err := ks.Export(acc, "old", "new")
   381  	if err != nil {
   382  		t.Fatalf("failed to export account: %v", acc)
   383  	}
   384  	_, ks2 := tmpKeyStore(t, true)
   385  	if _, err = ks2.Import(json, "old", "old"); err == nil {
   386  		t.Errorf("importing with invalid password succeeded")
   387  	}
   388  	acc2, err := ks2.Import(json, "new", "new")
   389  	if err != nil {
   390  		t.Errorf("importing failed: %v", err)
   391  	}
   392  	if acc.Address != acc2.Address {
   393  		t.Error("imported account does not match exported account")
   394  	}
   395  	if _, err = ks2.Import(json, "new", "new"); err == nil {
   396  		t.Errorf("importing a key twice succeeded")
   397  	}
   398  }
   399  
   400  // TestImportRace tests the keystore on races.
   401  // This test should fail under -race if importing races.
   402  func TestImportRace(t *testing.T) {
   403  	_, ks := tmpKeyStore(t, true)
   404  	acc, err := ks.NewAccount("old")
   405  	if err != nil {
   406  		t.Fatalf("failed to create account: %v", acc)
   407  	}
   408  	json, err := ks.Export(acc, "old", "new")
   409  	if err != nil {
   410  		t.Fatalf("failed to export account: %v", acc)
   411  	}
   412  	_, ks2 := tmpKeyStore(t, true)
   413  	var atom atomic.Uint32
   414  	var wg sync.WaitGroup
   415  	wg.Add(2)
   416  	for i := 0; i < 2; i++ {
   417  		go func() {
   418  			defer wg.Done()
   419  			if _, err := ks2.Import(json, "new", "new"); err != nil {
   420  				atom.Add(1)
   421  			}
   422  		}()
   423  	}
   424  	wg.Wait()
   425  	if atom.Load() != 1 {
   426  		t.Errorf("Import is racy")
   427  	}
   428  }
   429  
   430  // checkAccounts checks that all known live accounts are present in the wallet list.
   431  func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
   432  	if len(live) != len(wallets) {
   433  		t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live))
   434  		return
   435  	}
   436  	liveList := make([]accounts.Account, 0, len(live))
   437  	for _, account := range live {
   438  		liveList = append(liveList, account)
   439  	}
   440  	slices.SortFunc(liveList, byURL)
   441  	for j, wallet := range wallets {
   442  		if accs := wallet.Accounts(); len(accs) != 1 {
   443  			t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   444  		} else if accs[0] != liveList[j] {
   445  			t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   446  		}
   447  	}
   448  }
   449  
   450  // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times.
   451  func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
   452  	for _, wantEv := range want {
   453  		nmatch := 0
   454  		for ; len(have) > 0; nmatch++ {
   455  			if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a {
   456  				break
   457  			}
   458  			have = have[1:]
   459  		}
   460  		if nmatch == 0 {
   461  			t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address)
   462  		}
   463  	}
   464  }
   465  
   466  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   467  	d := t.TempDir()
   468  	newKs := NewPlaintextKeyStore
   469  	if encrypted {
   470  		newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   471  	}
   472  	return d, newKs(d)
   473  }