github.com/etherbanking/go-etherbanking@v1.7.1-0.20181009210156-cf649bca5aba/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/etherbanking/go-etherbanking/accounts"
    30  	"github.com/etherbanking/go-etherbanking/common"
    31  	"github.com/etherbanking/go-etherbanking/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  // Tests that wallet notifications and correctly fired when accounts are added
   276  // or deleted from the keystore.
   277  func TestWalletNotifications(t *testing.T) {
   278  	// Create a temporary kesytore to test with
   279  	dir, ks := tmpKeyStore(t, false)
   280  	defer os.RemoveAll(dir)
   281  
   282  	// Subscribe to the wallet feed
   283  	updates := make(chan accounts.WalletEvent, 1)
   284  	sub := ks.Subscribe(updates)
   285  	defer sub.Unsubscribe()
   286  
   287  	// Randomly add and remove account and make sure events and wallets are in sync
   288  	live := make(map[common.Address]accounts.Account)
   289  	for i := 0; i < 1024; i++ {
   290  		// Execute a creation or deletion and ensure event arrival
   291  		if create := len(live) == 0 || rand.Int()%4 > 0; create {
   292  			// Add a new account and ensure wallet notifications arrives
   293  			account, err := ks.NewAccount("")
   294  			if err != nil {
   295  				t.Fatalf("failed to create test account: %v", err)
   296  			}
   297  			select {
   298  			case event := <-updates:
   299  				if event.Kind != accounts.WalletArrived {
   300  					t.Errorf("non-arrival event on account creation")
   301  				}
   302  				if event.Wallet.Accounts()[0] != account {
   303  					t.Errorf("account mismatch on created wallet: have %v, want %v", event.Wallet.Accounts()[0], account)
   304  				}
   305  			default:
   306  				t.Errorf("wallet arrival event not fired on account creation")
   307  			}
   308  			live[account.Address] = account
   309  		} else {
   310  			// Select a random account to delete (crude, but works)
   311  			var account accounts.Account
   312  			for _, a := range live {
   313  				account = a
   314  				break
   315  			}
   316  			// Remove an account and ensure wallet notifiaction arrives
   317  			if err := ks.Delete(account, ""); err != nil {
   318  				t.Fatalf("failed to delete test account: %v", err)
   319  			}
   320  			select {
   321  			case event := <-updates:
   322  				if event.Kind != accounts.WalletDropped {
   323  					t.Errorf("non-drop event on account deletion")
   324  				}
   325  				if event.Wallet.Accounts()[0] != account {
   326  					t.Errorf("account mismatch on deleted wallet: have %v, want %v", event.Wallet.Accounts()[0], account)
   327  				}
   328  			default:
   329  				t.Errorf("wallet departure event not fired on account creation")
   330  			}
   331  			delete(live, account.Address)
   332  		}
   333  		// Retrieve the list of wallets and ensure it matches with our required live set
   334  		liveList := make([]accounts.Account, 0, len(live))
   335  		for _, account := range live {
   336  			liveList = append(liveList, account)
   337  		}
   338  		sort.Sort(accountsByURL(liveList))
   339  
   340  		wallets := ks.Wallets()
   341  		if len(liveList) != len(wallets) {
   342  			t.Errorf("wallet list doesn't match required accounts: have %v, want %v", wallets, liveList)
   343  		} else {
   344  			for j, wallet := range wallets {
   345  				if accs := wallet.Accounts(); len(accs) != 1 {
   346  					t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
   347  				} else if accs[0] != liveList[j] {
   348  					t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j])
   349  				}
   350  			}
   351  		}
   352  	}
   353  }
   354  
   355  func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
   356  	d, err := ioutil.TempDir("", "eth-keystore-test")
   357  	if err != nil {
   358  		t.Fatal(err)
   359  	}
   360  	new := NewPlaintextKeyStore
   361  	if encrypted {
   362  		new = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
   363  	}
   364  	return d, new(d)
   365  }