github.com/codingfuture/orig-energi3@v0.8.4/accounts/keystore/keystore_test.go (about)

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