github.com/googgoog/go-ethereum@v1.9.7/accounts/keystore/keystore_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package keystore
    18  
    19  import (
    20  	"io/ioutil"
    21  	"math/rand"
    22  	"os"
    23  	"runtime"
    24  	"sort"
    25  	"strings"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/accounts"
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/event"
    32  )
    33  
    34  var testSigData = make([]byte, 32)
    35  
    36  func TestKeyStore(t *testing.T) {
    37  	dir, ks := tmpKeyStore(t, true)
    38  	defer os.RemoveAll(dir)
    39  
    40  	a, err := ks.NewAccount("foo")
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  	if !strings.HasPrefix(a.URL.Path, dir) {
    45  		t.Errorf("account file %s doesn't have dir prefix", a.URL)
    46  	}
    47  	stat, err := os.Stat(a.URL.Path)
    48  	if err != nil {
    49  		t.Fatalf("account file %s doesn't exist (%v)", a.URL, err)
    50  	}
    51  	if runtime.GOOS != "windows" && stat.Mode() != 0600 {
    52  		t.Fatalf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600)
    53  	}
    54  	if !ks.HasAddress(a.Address) {
    55  		t.Errorf("HasAccount(%x) should've returned true", a.Address)
    56  	}
    57  	if err := ks.Update(a, "foo", "bar"); err != nil {
    58  		t.Errorf("Update error: %v", err)
    59  	}
    60  	if err := ks.Delete(a, "bar"); err != nil {
    61  		t.Errorf("Delete error: %v", err)
    62  	}
    63  	if common.FileExist(a.URL.Path) {
    64  		t.Errorf("account file %s should be gone after Delete", a.URL)
    65  	}
    66  	if ks.HasAddress(a.Address) {
    67  		t.Errorf("HasAccount(%x) should've returned true after Delete", a.Address)
    68  	}
    69  }
    70  
    71  func TestSign(t *testing.T) {
    72  	dir, ks := tmpKeyStore(t, true)
    73  	defer os.RemoveAll(dir)
    74  
    75  	pass := "" // not used but required by API
    76  	a1, err := ks.NewAccount(pass)
    77  	if err != nil {
    78  		t.Fatal(err)
    79  	}
    80  	if err := ks.Unlock(a1, ""); err != nil {
    81  		t.Fatal(err)
    82  	}
    83  	if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err != nil {
    84  		t.Fatal(err)
    85  	}
    86  }
    87  
    88  func TestSignWithPassphrase(t *testing.T) {
    89  	dir, ks := tmpKeyStore(t, true)
    90  	defer os.RemoveAll(dir)
    91  
    92  	pass := "passwd"
    93  	acc, err := ks.NewAccount(pass)
    94  	if err != nil {
    95  		t.Fatal(err)
    96  	}
    97  
    98  	if _, unlocked := ks.unlocked[acc.Address]; unlocked {
    99  		t.Fatal("expected account to be locked")
   100  	}
   101  
   102  	_, err = ks.SignHashWithPassphrase(acc, pass, testSigData)
   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  	if _, err = ks.SignHashWithPassphrase(acc, "invalid passwd", testSigData); err == nil {
   112  		t.Fatal("expected SignHashWithPassphrase to fail with invalid password")
   113  	}
   114  }
   115  
   116  func TestTimedUnlock(t *testing.T) {
   117  	dir, ks := tmpKeyStore(t, true)
   118  	defer os.RemoveAll(dir)
   119  
   120  	pass := "foo"
   121  	a1, err := ks.NewAccount(pass)
   122  	if err != nil {
   123  		t.Fatal(err)
   124  	}
   125  
   126  	// Signing without passphrase fails because account is locked
   127  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   128  	if err != ErrLocked {
   129  		t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err)
   130  	}
   131  
   132  	// Signing with passphrase works
   133  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   134  		t.Fatal(err)
   135  	}
   136  
   137  	// Signing without passphrase works because account is temp unlocked
   138  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   139  	if err != nil {
   140  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   141  	}
   142  
   143  	// Signing fails again after automatic locking
   144  	time.Sleep(250 * time.Millisecond)
   145  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   146  	if err != ErrLocked {
   147  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   148  	}
   149  }
   150  
   151  func TestOverrideUnlock(t *testing.T) {
   152  	dir, ks := tmpKeyStore(t, false)
   153  	defer os.RemoveAll(dir)
   154  
   155  	pass := "foo"
   156  	a1, err := ks.NewAccount(pass)
   157  	if err != nil {
   158  		t.Fatal(err)
   159  	}
   160  
   161  	// Unlock indefinitely.
   162  	if err = ks.TimedUnlock(a1, pass, 5*time.Minute); err != nil {
   163  		t.Fatal(err)
   164  	}
   165  
   166  	// Signing without passphrase works because account is temp unlocked
   167  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   168  	if err != nil {
   169  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   170  	}
   171  
   172  	// reset unlock to a shorter period, invalidates the previous unlock
   173  	if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil {
   174  		t.Fatal(err)
   175  	}
   176  
   177  	// Signing without passphrase still works because account is temp unlocked
   178  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   179  	if err != nil {
   180  		t.Fatal("Signing shouldn't return an error after unlocking, got ", err)
   181  	}
   182  
   183  	// Signing fails again after automatic locking
   184  	time.Sleep(250 * time.Millisecond)
   185  	_, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData)
   186  	if err != ErrLocked {
   187  		t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err)
   188  	}
   189  }
   190  
   191  // This test should fail under -race if signing races the expiration goroutine.
   192  func TestSignRace(t *testing.T) {
   193  	dir, ks := tmpKeyStore(t, false)
   194  	defer os.RemoveAll(dir)
   195  
   196  	// Create a test account.
   197  	a1, err := ks.NewAccount("")
   198  	if err != nil {
   199  		t.Fatal("could not create the test account", err)
   200  	}
   201  
   202  	if err := ks.TimedUnlock(a1, "", 15*time.Millisecond); err != nil {
   203  		t.Fatal("could not unlock the test account", err)
   204  	}
   205  	end := time.Now().Add(500 * time.Millisecond)
   206  	for time.Now().Before(end) {
   207  		if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked {
   208  			return
   209  		} else if err != nil {
   210  			t.Errorf("Sign error: %v", err)
   211  			return
   212  		}
   213  		time.Sleep(1 * time.Millisecond)
   214  	}
   215  	t.Errorf("Account did not lock within the timeout")
   216  }
   217  
   218  // Tests that the wallet notifier loop starts and stops correctly based on the
   219  // addition and removal of wallet event subscriptions.
   220  func TestWalletNotifierLifecycle(t *testing.T) {
   221  	// Create a temporary kesytore to test with
   222  	dir, ks := tmpKeyStore(t, false)
   223  	defer os.RemoveAll(dir)
   224  
   225  	// Ensure that the notification updater is not running yet
   226  	time.Sleep(250 * time.Millisecond)
   227  	ks.mu.RLock()
   228  	updating := ks.updating
   229  	ks.mu.RUnlock()
   230  
   231  	if updating {
   232  		t.Errorf("wallet notifier running without subscribers")
   233  	}
   234  	// Subscribe to the wallet feed and ensure the updater boots up
   235  	updates := make(chan accounts.WalletEvent)
   236  
   237  	subs := make([]event.Subscription, 2)
   238  	for i := 0; i < len(subs); i++ {
   239  		// Create a new subscription
   240  		subs[i] = ks.Subscribe(updates)
   241  
   242  		// Ensure the notifier comes online
   243  		time.Sleep(250 * time.Millisecond)
   244  		ks.mu.RLock()
   245  		updating = ks.updating
   246  		ks.mu.RUnlock()
   247  
   248  		if !updating {
   249  			t.Errorf("sub %d: wallet notifier not running after subscription", i)
   250  		}
   251  	}
   252  	// Unsubscribe and ensure the updater terminates eventually
   253  	for i := 0; i < len(subs); i++ {
   254  		// Close an existing subscription
   255  		subs[i].Unsubscribe()
   256  
   257  		// Ensure the notifier shuts down at and only at the last close
   258  		for k := 0; k < int(walletRefreshCycle/(250*time.Millisecond))+2; k++ {
   259  			ks.mu.RLock()
   260  			updating = ks.updating
   261  			ks.mu.RUnlock()
   262  
   263  			if i < len(subs)-1 && !updating {
   264  				t.Fatalf("sub %d: event notifier stopped prematurely", i)
   265  			}
   266  			if i == len(subs)-1 && !updating {
   267  				return
   268  			}
   269  			time.Sleep(250 * time.Millisecond)
   270  		}
   271  	}
   272  	t.Errorf("wallet notifier didn't terminate after unsubscribe")
   273  }
   274  
   275  type walletEvent struct {
   276  	accounts.WalletEvent
   277  	a accounts.Account
   278  }
   279  
   280  // Tests that wallet notifications and correctly fired when accounts are added
   281  // or deleted from the keystore.
   282  func TestWalletNotifications(t *testing.T) {
   283  	dir, ks := tmpKeyStore(t, false)
   284  	defer os.RemoveAll(dir)
   285  
   286  	// Subscribe to the wallet feed and collect events.
   287  	var (
   288  		events  []walletEvent
   289  		updates = make(chan accounts.WalletEvent)
   290  		sub     = ks.Subscribe(updates)
   291  	)
   292  	defer sub.Unsubscribe()
   293  	go func() {
   294  		for {
   295  			select {
   296  			case ev := <-updates:
   297  				events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
   298  			case <-sub.Err():
   299  				close(updates)
   300  				return
   301  			}
   302  		}
   303  	}()
   304  
   305  	// Randomly add and remove accounts.
   306  	var (
   307  		live       = make(map[common.Address]accounts.Account)
   308  		wantEvents []walletEvent
   309  	)
   310  	for i := 0; i < 1024; i++ {
   311  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   312  			// Add a new account and ensure wallet notifications arrives
   313  			account, err := ks.NewAccount("")
   314  			if err != nil {
   315  				t.Fatalf("failed to create test account: %v", err)
   316  			}
   317  			live[account.Address] = account
   318  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletArrived}, account})
   319  		} else {
   320  			// Delete a random account.
   321  			var account accounts.Account
   322  			for _, a := range live {
   323  				account = a
   324  				break
   325  			}
   326  			if err := ks.Delete(account, ""); err != nil {
   327  				t.Fatalf("failed to delete test account: %v", err)
   328  			}
   329  			delete(live, account.Address)
   330  			wantEvents = append(wantEvents, walletEvent{accounts.WalletEvent{Kind: accounts.WalletDropped}, account})
   331  		}
   332  	}
   333  
   334  	// Shut down the event collector and check events.
   335  	sub.Unsubscribe()
   336  	<-updates
   337  	checkAccounts(t, live, ks.Wallets())
   338  	checkEvents(t, wantEvents, events)
   339  }
   340  
   341  // checkAccounts checks that all known live accounts are present in the wallet list.
   342  func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
   343  	if len(live) != len(wallets) {
   344  		t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live))
   345  		return
   346  	}
   347  	liveList := make([]accounts.Account, 0, len(live))
   348  	for _, account := range live {
   349  		liveList = append(liveList, account)
   350  	}
   351  	sort.Sort(accountsByURL(liveList))
   352  	for j, wallet := range wallets {
   353  		if accs := wallet.Accounts(); len(accs) != 1 {
   354  			t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   355  		} else if accs[0] != liveList[j] {
   356  			t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   357  		}
   358  	}
   359  }
   360  
   361  // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times.
   362  func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
   363  	for _, wantEv := range want {
   364  		nmatch := 0
   365  		for ; len(have) > 0; nmatch++ {
   366  			if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a {
   367  				break
   368  			}
   369  			have = have[1:]
   370  		}
   371  		if nmatch == 0 {
   372  			t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address)
   373  		}
   374  	}
   375  }
   376  
   377  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   378  	d, err := ioutil.TempDir("", "eth-keystore-test")
   379  	if err != nil {
   380  		t.Fatal(err)
   381  	}
   382  	newKs := NewPlaintextKeyStore
   383  	if encrypted {
   384  		newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   385  	}
   386  	return d, newKs(d)
   387  }