github.com/MetalBlockchain/subnet-evm@v0.4.9/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/MetalBlockchain/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  	t.Skip("FLAKY")
   289  	_, ks := tmpKeyStore(t, false)
   290  
   291  	// Subscribe to the wallet feed and collect events.
   292  	var (
   293  		events  []walletEvent
   294  		updates = make(chan accounts.WalletEvent)
   295  		sub     = ks.Subscribe(updates)
   296  	)
   297  	defer sub.Unsubscribe()
   298  	go func() {
   299  		for {
   300  			select {
   301  			case ev := <-updates:
   302  				events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   303  			case <-sub.Err():
   304  				close(updates)
   305  				return
   306  			}
   307  		}
   308  	}()
   309  
   310  	// Randomly add and remove accounts.
   311  	var (
   312  		live       = make(map[common.Address]accounts.Account)
   313  		wantEvents []walletEvent
   314  	)
   315  	for i := 0; i < 1024; i++ {
   316  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   317  			// Add a new account and ensure wallet notifications arrives
   318  			account, err := ks.NewAccount("")
   319  			if err != nil {
   320  				t.Fatalf("failed to create test account: %v", err)
   321  			}
   322  			live[account.Address] = account
   323  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletArrived}, account})
   324  		} else {
   325  			// Delete a random account.
   326  			var account accounts.Account
   327  			for _, a := range live {
   328  				account = a
   329  				break
   330  			}
   331  			if err := ks.Delete(account, ""); err != nil {
   332  				t.Fatalf("failed to delete test account: %v", err)
   333  			}
   334  			delete(live, account.Address)
   335  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletDropped}, account})
   336  		}
   337  	}
   338  
   339  	// Shut down the event collector and check events.
   340  	sub.Unsubscribe()
   341  	for ev := range updates {
   342  		events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   343  	}
   344  	checkAccounts(t, live, ks.Wallets())
   345  	checkEvents(t, wantEvents, events)
   346  }
   347  
   348  // TestImportExport tests the import functionality of a keystore.
   349  func TestImportECDSA(t *testing.T) {
   350  	_, ks := tmpKeyStore(t, true)
   351  	key, err := crypto.GenerateKey()
   352  	if err != nil {
   353  		t.Fatalf("failed to generate key: %v", key)
   354  	}
   355  	if _, err = ks.ImportECDSA(key, "old"); err != nil {
   356  		t.Errorf("importing failed: %v", err)
   357  	}
   358  	if _, err = ks.ImportECDSA(key, "old"); err == nil {
   359  		t.Errorf("importing same key twice succeeded")
   360  	}
   361  	if _, err = ks.ImportECDSA(key, "new"); err == nil {
   362  		t.Errorf("importing same key twice succeeded")
   363  	}
   364  }
   365  
   366  // TestImportECDSA tests the import and export functionality of a keystore.
   367  func TestImportExport(t *testing.T) {
   368  	_, ks := tmpKeyStore(t, true)
   369  	acc, err := ks.NewAccount("old")
   370  	if err != nil {
   371  		t.Fatalf("failed to create account: %v", acc)
   372  	}
   373  	json, err := ks.Export(acc, "old", "new")
   374  	if err != nil {
   375  		t.Fatalf("failed to export account: %v", acc)
   376  	}
   377  	_, ks2 := tmpKeyStore(t, true)
   378  	if _, err = ks2.Import(json, "old", "old"); err == nil {
   379  		t.Errorf("importing with invalid password succeeded")
   380  	}
   381  	acc2, err := ks2.Import(json, "new", "new")
   382  	if err != nil {
   383  		t.Errorf("importing failed: %v", err)
   384  	}
   385  	if acc.Address != acc2.Address {
   386  		t.Error("imported account does not match exported account")
   387  	}
   388  	if _, err = ks2.Import(json, "new", "new"); err == nil {
   389  		t.Errorf("importing a key twice succeeded")
   390  	}
   391  }
   392  
   393  // TestImportRace tests the keystore on races.
   394  // This test should fail under -race if importing races.
   395  func TestImportRace(t *testing.T) {
   396  	_, ks := tmpKeyStore(t, true)
   397  	acc, err := ks.NewAccount("old")
   398  	if err != nil {
   399  		t.Fatalf("failed to create account: %v", acc)
   400  	}
   401  	json, err := ks.Export(acc, "old", "new")
   402  	if err != nil {
   403  		t.Fatalf("failed to export account: %v", acc)
   404  	}
   405  	_, ks2 := tmpKeyStore(t, true)
   406  	var atom uint32
   407  	var wg sync.WaitGroup
   408  	wg.Add(2)
   409  	for i := 0; i < 2; i++ {
   410  		go func() {
   411  			defer wg.Done()
   412  			if _, err := ks2.Import(json, "new", "new"); err != nil {
   413  				atomic.AddUint32(&atom, 1)
   414  			}
   415  		}()
   416  	}
   417  	wg.Wait()
   418  	if atom != 1 {
   419  		t.Errorf("Import is racy")
   420  	}
   421  }
   422  
   423  // checkAccounts checks that all known live accounts are present in the wallet list.
   424  func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
   425  	if len(live) != len(wallets) {
   426  		t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live))
   427  		return
   428  	}
   429  	liveList := make([]accounts.Account, 0, len(live))
   430  	for _, account := range live {
   431  		liveList = append(liveList, account)
   432  	}
   433  	sort.Sort(accountsByURL(liveList))
   434  	for j, wallet := range wallets {
   435  		if accs := wallet.Accounts(); len(accs) != 1 {
   436  			t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   437  		} else if accs[0] != liveList[j] {
   438  			t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   439  		}
   440  	}
   441  }
   442  
   443  // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times.
   444  func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
   445  	for _, wantEv := range want {
   446  		nmatch := 0
   447  		for ; len(have) > 0; nmatch++ {
   448  			if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a {
   449  				break
   450  			}
   451  			have = have[1:]
   452  		}
   453  		if nmatch == 0 {
   454  			t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address)
   455  		}
   456  	}
   457  }
   458  
   459  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   460  	d := t.TempDir()
   461  	newKs := NewPlaintextKeyStore
   462  	if encrypted {
   463  		newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   464  	}
   465  	return d, newKs(d)
   466  }