github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/accounts/keystore/keystore_test.go (about)

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