github.com/cgcardona/r-subnet-evm@v0.1.5/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  	"sort"
    34  	"strings"
    35  	"sync"
    36  	"sync/atomic"
    37  	"testing"
    38  	"time"
    39  
    40  	"github.com/cgcardona/r-subnet-evm/accounts"
    41  	"github.com/ethereum/go-ethereum/common"
    42  	"github.com/ethereum/go-ethereum/crypto"
    43  	"github.com/ethereum/go-ethereum/event"
    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  	_, ks := tmpKeyStore(t, true)
   127  
   128  	pass := "foo"
   129  	a1, err := ks.NewAccount(pass)
   130  	if err != nil {
   131  		t.Fatal(err)
   132  	}
   133  
   134  	// Signing without passphrase fails because account is locked
   135  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   136  	if err != ErrLocked {
   137  		t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err)
   138  	}
   139  
   140  	// Signing with passphrase works
   141  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   142  		t.Fatal(err)
   143  	}
   144  
   145  	// Signing without passphrase works because account is temp unlocked
   146  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   147  	if err != nil {
   148  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   149  	}
   150  
   151  	// Signing fails again after automatic locking
   152  	time.Sleep(250 * time.Millisecond)
   153  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   154  	if err != ErrLocked {
   155  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   156  	}
   157  }
   158  
   159  func TestOverrideUnlock(t *testing.T) {
   160  	_, ks := tmpKeyStore(t, false)
   161  
   162  	pass := "foo"
   163  	a1, err := ks.NewAccount(pass)
   164  	if err != nil {
   165  		t.Fatal(err)
   166  	}
   167  
   168  	// Unlock indefinitely.
   169  	if err = ks.TimedUnlock(a1, pass, 5*time.Minute); err != nil {
   170  		t.Fatal(err)
   171  	}
   172  
   173  	// Signing without passphrase works because account is temp unlocked
   174  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   175  	if err != nil {
   176  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   177  	}
   178  
   179  	// reset unlock to a shorter period, invalidates the previous unlock
   180  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   181  		t.Fatal(err)
   182  	}
   183  
   184  	// Signing without passphrase still works because account is temp unlocked
   185  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   186  	if err != nil {
   187  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   188  	}
   189  
   190  	// Signing fails again after automatic locking
   191  	time.Sleep(250 * time.Millisecond)
   192  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   193  	if err != ErrLocked {
   194  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   195  	}
   196  }
   197  
   198  // This test should fail under -race if signing races the expiration goroutine.
   199  func TestSignRace(t *testing.T) {
   200  	_, ks := tmpKeyStore(t, false)
   201  
   202  	// Create a test account.
   203  	a1, err := ks.NewAccount("")
   204  	if err != nil {
   205  		t.Fatal("could not create the test account", err)
   206  	}
   207  
   208  	if err := ks.TimedUnlock(a1, "", 15*time.Millisecond); err != nil {
   209  		t.Fatal("could not unlock the test account", err)
   210  	}
   211  	end := time.Now().Add(500 * time.Millisecond)
   212  	for time.Now().Before(end) {
   213  		if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked {
   214  			return
   215  		} else if err != nil {
   216  			t.Errorf("Sign error: %v", err)
   217  			return
   218  		}
   219  		time.Sleep(1 * time.Millisecond)
   220  	}
   221  	t.Errorf("Account did not lock within the timeout")
   222  }
   223  
   224  // Tests that the wallet notifier loop starts and stops correctly based on the
   225  // addition and removal of wallet event subscriptions.
   226  func TestWalletNotifierLifecycle(t *testing.T) {
   227  	// Create a temporary keystore to test with
   228  	_, ks := tmpKeyStore(t, false)
   229  
   230  	// Ensure that the notification updater is not running yet
   231  	time.Sleep(250 * time.Millisecond)
   232  	ks.mu.RLock()
   233  	updating := ks.updating
   234  	ks.mu.RUnlock()
   235  
   236  	if updating {
   237  		t.Errorf("wallet notifier running without subscribers")
   238  	}
   239  	// Subscribe to the wallet feed and ensure the updater boots up
   240  	updates := make(chan accounts.WalletEvent)
   241  
   242  	subs := make([]event.Subscription, 2)
   243  	for i := 0; i < len(subs); i++ {
   244  		// Create a new subscription
   245  		subs[i] = ks.Subscribe(updates)
   246  
   247  		// Ensure the notifier comes online
   248  		time.Sleep(250 * time.Millisecond)
   249  		ks.mu.RLock()
   250  		updating = ks.updating
   251  		ks.mu.RUnlock()
   252  
   253  		if !updating {
   254  			t.Errorf("sub %d: wallet notifier not running after subscription", i)
   255  		}
   256  	}
   257  	// Unsubscribe and ensure the updater terminates eventually
   258  	for i := 0; i < len(subs); i++ {
   259  		// Close an existing subscription
   260  		subs[i].Unsubscribe()
   261  
   262  		// Ensure the notifier shuts down at and only at the last close
   263  		for k := 0; k < int(walletRefreshCycle/(250*time.Millisecond))+2; k++ {
   264  			ks.mu.RLock()
   265  			updating = ks.updating
   266  			ks.mu.RUnlock()
   267  
   268  			if i < len(subs)-1 && !updating {
   269  				t.Fatalf("sub %d: event notifier stopped prematurely", i)
   270  			}
   271  			if i == len(subs)-1 && !updating {
   272  				return
   273  			}
   274  			time.Sleep(250 * time.Millisecond)
   275  		}
   276  	}
   277  	t.Errorf("wallet notifier didn't terminate after unsubscribe")
   278  }
   279  
   280  type walletEvent struct {
   281  	accounts.WalletEvent
   282  	a accounts.Account
   283  }
   284  
   285  // Tests that wallet notifications and correctly fired when accounts are added
   286  // or deleted from the keystore.
   287  func TestWalletNotifications(t *testing.T) {
   288  	if os.Getenv("RUN_FLAKY_TESTS") != "true" {
   289  		t.Skip("FLAKY")
   290  	}
   291  	_, ks := tmpKeyStore(t, false)
   292  
   293  	// Subscribe to the wallet feed and collect events.
   294  	var (
   295  		events  []walletEvent
   296  		updates = make(chan accounts.WalletEvent)
   297  		sub     = ks.Subscribe(updates)
   298  	)
   299  	defer sub.Unsubscribe()
   300  	go func() {
   301  		for {
   302  			select {
   303  			case ev := <-updates:
   304  				events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   305  			case <-sub.Err():
   306  				close(updates)
   307  				return
   308  			}
   309  		}
   310  	}()
   311  
   312  	// Randomly add and remove accounts.
   313  	var (
   314  		live       = make(map[common.Address]accounts.Account)
   315  		wantEvents []walletEvent
   316  	)
   317  	for i := 0; i < 1024; i++ {
   318  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   319  			// Add a new account and ensure wallet notifications arrives
   320  			account, err := ks.NewAccount("")
   321  			if err != nil {
   322  				t.Fatalf("failed to create test account: %v", err)
   323  			}
   324  			live[account.Address] = account
   325  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletArrived}, account})
   326  		} else {
   327  			// Delete a random account.
   328  			var account accounts.Account
   329  			for _, a := range live {
   330  				account = a
   331  				break
   332  			}
   333  			if err := ks.Delete(account, ""); err != nil {
   334  				t.Fatalf("failed to delete test account: %v", err)
   335  			}
   336  			delete(live, account.Address)
   337  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletDropped}, account})
   338  		}
   339  	}
   340  
   341  	// Shut down the event collector and check events.
   342  	sub.Unsubscribe()
   343  	for ev := range updates {
   344  		events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   345  	}
   346  	checkAccounts(t, live, ks.Wallets())
   347  	checkEvents(t, wantEvents, events)
   348  }
   349  
   350  // TestImportExport tests the import functionality of a keystore.
   351  func TestImportECDSA(t *testing.T) {
   352  	_, ks := tmpKeyStore(t, true)
   353  	key, err := crypto.GenerateKey()
   354  	if err != nil {
   355  		t.Fatalf("failed to generate key: %v", key)
   356  	}
   357  	if _, err = ks.ImportECDSA(key, "old"); err != nil {
   358  		t.Errorf("importing failed: %v", err)
   359  	}
   360  	if _, err = ks.ImportECDSA(key, "old"); err == nil {
   361  		t.Errorf("importing same key twice succeeded")
   362  	}
   363  	if _, err = ks.ImportECDSA(key, "new"); err == nil {
   364  		t.Errorf("importing same key twice succeeded")
   365  	}
   366  }
   367  
   368  // TestImportECDSA tests the import and export functionality of a keystore.
   369  func TestImportExport(t *testing.T) {
   370  	_, ks := tmpKeyStore(t, true)
   371  	acc, err := ks.NewAccount("old")
   372  	if err != nil {
   373  		t.Fatalf("failed to create account: %v", acc)
   374  	}
   375  	json, err := ks.Export(acc, "old", "new")
   376  	if err != nil {
   377  		t.Fatalf("failed to export account: %v", acc)
   378  	}
   379  	_, ks2 := tmpKeyStore(t, true)
   380  	if _, err = ks2.Import(json, "old", "old"); err == nil {
   381  		t.Errorf("importing with invalid password succeeded")
   382  	}
   383  	acc2, err := ks2.Import(json, "new", "new")
   384  	if err != nil {
   385  		t.Errorf("importing failed: %v", err)
   386  	}
   387  	if acc.Address != acc2.Address {
   388  		t.Error("imported account does not match exported account")
   389  	}
   390  	if _, err = ks2.Import(json, "new", "new"); err == nil {
   391  		t.Errorf("importing a key twice succeeded")
   392  	}
   393  }
   394  
   395  // TestImportRace tests the keystore on races.
   396  // This test should fail under -race if importing races.
   397  func TestImportRace(t *testing.T) {
   398  	_, ks := tmpKeyStore(t, true)
   399  	acc, err := ks.NewAccount("old")
   400  	if err != nil {
   401  		t.Fatalf("failed to create account: %v", acc)
   402  	}
   403  	json, err := ks.Export(acc, "old", "new")
   404  	if err != nil {
   405  		t.Fatalf("failed to export account: %v", acc)
   406  	}
   407  	_, ks2 := tmpKeyStore(t, true)
   408  	var atom uint32
   409  	var wg sync.WaitGroup
   410  	wg.Add(2)
   411  	for i := 0; i < 2; i++ {
   412  		go func() {
   413  			defer wg.Done()
   414  			if _, err := ks2.Import(json, "new", "new"); err != nil {
   415  				atomic.AddUint32(&atom, 1)
   416  			}
   417  		}()
   418  	}
   419  	wg.Wait()
   420  	if atom != 1 {
   421  		t.Errorf("Import is racy")
   422  	}
   423  }
   424  
   425  // checkAccounts checks that all known live accounts are present in the wallet list.
   426  func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
   427  	if len(live) != len(wallets) {
   428  		t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live))
   429  		return
   430  	}
   431  	liveList := make([]accounts.Account, 0, len(live))
   432  	for _, account := range live {
   433  		liveList = append(liveList, account)
   434  	}
   435  	sort.Sort(accountsByURL(liveList))
   436  	for j, wallet := range wallets {
   437  		if accs := wallet.Accounts(); len(accs) != 1 {
   438  			t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   439  		} else if accs[0] != liveList[j] {
   440  			t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   441  		}
   442  	}
   443  }
   444  
   445  // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times.
   446  func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
   447  	for _, wantEv := range want {
   448  		nmatch := 0
   449  		for ; len(have) > 0; nmatch++ {
   450  			if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a {
   451  				break
   452  			}
   453  			have = have[1:]
   454  		}
   455  		if nmatch == 0 {
   456  			t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address)
   457  		}
   458  	}
   459  }
   460  
   461  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   462  	d := t.TempDir()
   463  	newKs := NewPlaintextKeyStore
   464  	if encrypted {
   465  		newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   466  	}
   467  	return d, newKs(d)
   468  }