github.com/theQRL/go-zond@v0.1.1/accounts/keystore/account_cache_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  	"errors"
    21  	"fmt"
    22  	"math/rand"
    23  	"os"
    24  	"path/filepath"
    25  	"reflect"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/cespare/cp"
    30  	"github.com/davecgh/go-spew/spew"
    31  	"github.com/theQRL/go-zond/accounts"
    32  	"github.com/theQRL/go-zond/common"
    33  	"golang.org/x/exp/slices"
    34  )
    35  
    36  var (
    37  	cachetestDir, _   = filepath.Abs(filepath.Join("testdata", "keystore"))
    38  	cachetestAccounts = []accounts.Account{
    39  		{
    40  			Address: common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"),
    41  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(cachetestDir, "UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8")},
    42  		},
    43  		{
    44  			Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"),
    45  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(cachetestDir, "aaa")},
    46  		},
    47  		{
    48  			Address: common.HexToAddress("289d485d9771714cce91d3393d764e1311907acc"),
    49  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(cachetestDir, "zzz")},
    50  		},
    51  	}
    52  )
    53  
    54  // waitWatcherStarts waits up to 1s for the keystore watcher to start.
    55  func waitWatcherStart(ks *KeyStore) bool {
    56  	// On systems where file watch is not supported, just return "ok".
    57  	if !ks.cache.watcher.enabled() {
    58  		return true
    59  	}
    60  	// The watcher should start, and then exit.
    61  	for t0 := time.Now(); time.Since(t0) < 1*time.Second; time.Sleep(100 * time.Millisecond) {
    62  		if ks.cache.watcherStarted() {
    63  			return true
    64  		}
    65  	}
    66  	return false
    67  }
    68  
    69  func waitForAccounts(wantAccounts []accounts.Account, ks *KeyStore) error {
    70  	var list []accounts.Account
    71  	for t0 := time.Now(); time.Since(t0) < 5*time.Second; time.Sleep(200 * time.Millisecond) {
    72  		list = ks.Accounts()
    73  		if reflect.DeepEqual(list, wantAccounts) {
    74  			// ks should have also received change notifications
    75  			select {
    76  			case <-ks.changes:
    77  			default:
    78  				return errors.New("wasn't notified of new accounts")
    79  			}
    80  			return nil
    81  		}
    82  	}
    83  	return fmt.Errorf("\ngot  %v\nwant %v", list, wantAccounts)
    84  }
    85  
    86  func TestWatchNewFile(t *testing.T) {
    87  	t.Parallel()
    88  
    89  	dir, ks := tmpKeyStore(t, false)
    90  
    91  	// Ensure the watcher is started before adding any files.
    92  	ks.Accounts()
    93  	if !waitWatcherStart(ks) {
    94  		t.Fatal("keystore watcher didn't start in time")
    95  	}
    96  	// Move in the files.
    97  	wantAccounts := make([]accounts.Account, len(cachetestAccounts))
    98  	for i := range cachetestAccounts {
    99  		wantAccounts[i] = accounts.Account{
   100  			Address: cachetestAccounts[i].Address,
   101  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, filepath.Base(cachetestAccounts[i].URL.Path))},
   102  		}
   103  		if err := cp.CopyFile(wantAccounts[i].URL.Path, cachetestAccounts[i].URL.Path); err != nil {
   104  			t.Fatal(err)
   105  		}
   106  	}
   107  
   108  	// ks should see the accounts.
   109  	if err := waitForAccounts(wantAccounts, ks); err != nil {
   110  		t.Error(err)
   111  	}
   112  }
   113  
   114  func TestWatchNoDir(t *testing.T) {
   115  	t.Parallel()
   116  	// Create ks but not the directory that it watches.
   117  	dir := filepath.Join(os.TempDir(), fmt.Sprintf("zond-keystore-watchnodir-test-%d-%d", os.Getpid(), rand.Int()))
   118  	ks := NewKeyStore(dir, LightScryptN, LightScryptP)
   119  	list := ks.Accounts()
   120  	if len(list) > 0 {
   121  		t.Error("initial account list not empty:", list)
   122  	}
   123  	// The watcher should start, and then exit.
   124  	if !waitWatcherStart(ks) {
   125  		t.Fatal("keystore watcher didn't start in time")
   126  	}
   127  	// Create the directory and copy a key file into it.
   128  	os.MkdirAll(dir, 0700)
   129  	defer os.RemoveAll(dir)
   130  	file := filepath.Join(dir, "aaa")
   131  	if err := cp.CopyFile(file, cachetestAccounts[0].URL.Path); err != nil {
   132  		t.Fatal(err)
   133  	}
   134  
   135  	// ks should see the account.
   136  	wantAccounts := []accounts.Account{cachetestAccounts[0]}
   137  	wantAccounts[0].URL = accounts.URL{Scheme: KeyStoreScheme, Path: file}
   138  	for d := 200 * time.Millisecond; d < 8*time.Second; d *= 2 {
   139  		list = ks.Accounts()
   140  		if reflect.DeepEqual(list, wantAccounts) {
   141  			// ks should have also received change notifications
   142  			select {
   143  			case <-ks.changes:
   144  			default:
   145  				t.Fatalf("wasn't notified of new accounts")
   146  			}
   147  			return
   148  		}
   149  		time.Sleep(d)
   150  	}
   151  	t.Errorf("\ngot  %v\nwant %v", list, wantAccounts)
   152  }
   153  
   154  func TestCacheInitialReload(t *testing.T) {
   155  	cache, _ := newAccountCache(cachetestDir)
   156  	accounts := cache.accounts()
   157  	if !reflect.DeepEqual(accounts, cachetestAccounts) {
   158  		t.Fatalf("got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachetestAccounts))
   159  	}
   160  }
   161  
   162  func TestCacheAddDeleteOrder(t *testing.T) {
   163  	cache, _ := newAccountCache("testdata/no-such-dir")
   164  	cache.watcher.running = true // prevent unexpected reloads
   165  
   166  	accs := []accounts.Account{
   167  		{
   168  			Address: common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"),
   169  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "-309830980"},
   170  		},
   171  		{
   172  			Address: common.HexToAddress("2cac1adea150210703ba75ed097ddfe24e14f213"),
   173  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "ggg"},
   174  		},
   175  		{
   176  			Address: common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"),
   177  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "zzzzzz-the-very-last-one.keyXXX"},
   178  		},
   179  		{
   180  			Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"),
   181  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "SOMETHING.key"},
   182  		},
   183  		{
   184  			Address: common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"),
   185  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "UTC--2016-03-22T12-57-55.920751759Z--7ef5a6135f1fd6a02593eedc869c6d41d934aef8"},
   186  		},
   187  		{
   188  			Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"),
   189  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "aaa"},
   190  		},
   191  		{
   192  			Address: common.HexToAddress("289d485d9771714cce91d3393d764e1311907acc"),
   193  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: "zzz"},
   194  		},
   195  	}
   196  	for _, a := range accs {
   197  		cache.add(a)
   198  	}
   199  	// Add some of them twice to check that they don't get reinserted.
   200  	cache.add(accs[0])
   201  	cache.add(accs[2])
   202  
   203  	// Check that the account list is sorted by filename.
   204  	wantAccounts := make([]accounts.Account, len(accs))
   205  	copy(wantAccounts, accs)
   206  	slices.SortFunc(wantAccounts, byURL)
   207  	list := cache.accounts()
   208  	if !reflect.DeepEqual(list, wantAccounts) {
   209  		t.Fatalf("got accounts: %s\nwant %s", spew.Sdump(accs), spew.Sdump(wantAccounts))
   210  	}
   211  	for _, a := range accs {
   212  		if !cache.hasAddress(a.Address) {
   213  			t.Errorf("expected hasAccount(%x) to return true", a.Address)
   214  		}
   215  	}
   216  	if cache.hasAddress(common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e")) {
   217  		t.Errorf("expected hasAccount(%x) to return false", common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e"))
   218  	}
   219  
   220  	// Delete a few keys from the cache.
   221  	for i := 0; i < len(accs); i += 2 {
   222  		cache.delete(wantAccounts[i])
   223  	}
   224  	cache.delete(accounts.Account{Address: common.HexToAddress("fd9bd350f08ee3c0c19b85a8e16114a11a60aa4e"), URL: accounts.URL{Scheme: KeyStoreScheme, Path: "something"}})
   225  
   226  	// Check content again after deletion.
   227  	wantAccountsAfterDelete := []accounts.Account{
   228  		wantAccounts[1],
   229  		wantAccounts[3],
   230  		wantAccounts[5],
   231  	}
   232  	list = cache.accounts()
   233  	if !reflect.DeepEqual(list, wantAccountsAfterDelete) {
   234  		t.Fatalf("got accounts after delete: %s\nwant %s", spew.Sdump(list), spew.Sdump(wantAccountsAfterDelete))
   235  	}
   236  	for _, a := range wantAccountsAfterDelete {
   237  		if !cache.hasAddress(a.Address) {
   238  			t.Errorf("expected hasAccount(%x) to return true", a.Address)
   239  		}
   240  	}
   241  	if cache.hasAddress(wantAccounts[0].Address) {
   242  		t.Errorf("expected hasAccount(%x) to return false", wantAccounts[0].Address)
   243  	}
   244  }
   245  
   246  func TestCacheFind(t *testing.T) {
   247  	dir := filepath.Join("testdata", "dir")
   248  	cache, _ := newAccountCache(dir)
   249  	cache.watcher.running = true // prevent unexpected reloads
   250  
   251  	accs := []accounts.Account{
   252  		{
   253  			Address: common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"),
   254  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, "a.key")},
   255  		},
   256  		{
   257  			Address: common.HexToAddress("2cac1adea150210703ba75ed097ddfe24e14f213"),
   258  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, "b.key")},
   259  		},
   260  		{
   261  			Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"),
   262  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, "c.key")},
   263  		},
   264  		{
   265  			Address: common.HexToAddress("d49ff4eeb0b2686ed89c0fc0f2b6ea533ddbbd5e"),
   266  			URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, "c2.key")},
   267  		},
   268  	}
   269  	for _, a := range accs {
   270  		cache.add(a)
   271  	}
   272  
   273  	nomatchAccount := accounts.Account{
   274  		Address: common.HexToAddress("f466859ead1932d743d622cb74fc058882e8648a"),
   275  		URL:     accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Join(dir, "something")},
   276  	}
   277  	tests := []struct {
   278  		Query      accounts.Account
   279  		WantResult accounts.Account
   280  		WantError  error
   281  	}{
   282  		// by address
   283  		{Query: accounts.Account{Address: accs[0].Address}, WantResult: accs[0]},
   284  		// by file
   285  		{Query: accounts.Account{URL: accs[0].URL}, WantResult: accs[0]},
   286  		// by basename
   287  		{Query: accounts.Account{URL: accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Base(accs[0].URL.Path)}}, WantResult: accs[0]},
   288  		// by file and address
   289  		{Query: accs[0], WantResult: accs[0]},
   290  		// ambiguous address, tie resolved by file
   291  		{Query: accs[2], WantResult: accs[2]},
   292  		// ambiguous address error
   293  		{
   294  			Query: accounts.Account{Address: accs[2].Address},
   295  			WantError: &AmbiguousAddrError{
   296  				Addr:    accs[2].Address,
   297  				Matches: []accounts.Account{accs[2], accs[3]},
   298  			},
   299  		},
   300  		// no match error
   301  		{Query: nomatchAccount, WantError: ErrNoMatch},
   302  		{Query: accounts.Account{URL: nomatchAccount.URL}, WantError: ErrNoMatch},
   303  		{Query: accounts.Account{URL: accounts.URL{Scheme: KeyStoreScheme, Path: filepath.Base(nomatchAccount.URL.Path)}}, WantError: ErrNoMatch},
   304  		{Query: accounts.Account{Address: nomatchAccount.Address}, WantError: ErrNoMatch},
   305  	}
   306  	for i, test := range tests {
   307  		a, err := cache.find(test.Query)
   308  		if !reflect.DeepEqual(err, test.WantError) {
   309  			t.Errorf("test %d: error mismatch for query %v\ngot %q\nwant %q", i, test.Query, err, test.WantError)
   310  			continue
   311  		}
   312  		if a != test.WantResult {
   313  			t.Errorf("test %d: result mismatch for query %v\ngot %v\nwant %v", i, test.Query, a, test.WantResult)
   314  			continue
   315  		}
   316  	}
   317  }
   318  
   319  // TestUpdatedKeyfileContents tests that updating the contents of a keystore file
   320  // is noticed by the watcher, and the account cache is updated accordingly
   321  func TestUpdatedKeyfileContents(t *testing.T) {
   322  	t.Parallel()
   323  
   324  	// Create a temporary keystore to test with
   325  	dir := filepath.Join(os.TempDir(), fmt.Sprintf("zond-keystore-updatedkeyfilecontents-test-%d-%d", os.Getpid(), rand.Int()))
   326  	ks := NewKeyStore(dir, LightScryptN, LightScryptP)
   327  
   328  	list := ks.Accounts()
   329  	if len(list) > 0 {
   330  		t.Error("initial account list not empty:", list)
   331  	}
   332  	if !waitWatcherStart(ks) {
   333  		t.Fatal("keystore watcher didn't start in time")
   334  	}
   335  	// Create the directory and copy a key file into it.
   336  	os.MkdirAll(dir, 0700)
   337  	defer os.RemoveAll(dir)
   338  	file := filepath.Join(dir, "aaa")
   339  
   340  	// Place one of our testfiles in there
   341  	if err := cp.CopyFile(file, cachetestAccounts[0].URL.Path); err != nil {
   342  		t.Fatal(err)
   343  	}
   344  
   345  	// ks should see the account.
   346  	wantAccounts := []accounts.Account{cachetestAccounts[0]}
   347  	wantAccounts[0].URL = accounts.URL{Scheme: KeyStoreScheme, Path: file}
   348  	if err := waitForAccounts(wantAccounts, ks); err != nil {
   349  		t.Error(err)
   350  		return
   351  	}
   352  	// needed so that modTime of `file` is different to its current value after forceCopyFile
   353  	time.Sleep(time.Second)
   354  
   355  	// Now replace file contents
   356  	if err := forceCopyFile(file, cachetestAccounts[1].URL.Path); err != nil {
   357  		t.Fatal(err)
   358  		return
   359  	}
   360  	wantAccounts = []accounts.Account{cachetestAccounts[1]}
   361  	wantAccounts[0].URL = accounts.URL{Scheme: KeyStoreScheme, Path: file}
   362  	if err := waitForAccounts(wantAccounts, ks); err != nil {
   363  		t.Errorf("First replacement failed")
   364  		t.Error(err)
   365  		return
   366  	}
   367  
   368  	// needed so that modTime of `file` is different to its current value after forceCopyFile
   369  	time.Sleep(time.Second)
   370  
   371  	// Now replace file contents again
   372  	if err := forceCopyFile(file, cachetestAccounts[2].URL.Path); err != nil {
   373  		t.Fatal(err)
   374  		return
   375  	}
   376  	wantAccounts = []accounts.Account{cachetestAccounts[2]}
   377  	wantAccounts[0].URL = accounts.URL{Scheme: KeyStoreScheme, Path: file}
   378  	if err := waitForAccounts(wantAccounts, ks); err != nil {
   379  		t.Errorf("Second replacement failed")
   380  		t.Error(err)
   381  		return
   382  	}
   383  
   384  	// needed so that modTime of `file` is different to its current value after os.WriteFile
   385  	time.Sleep(time.Second)
   386  
   387  	// Now replace file contents with crap
   388  	if err := os.WriteFile(file, []byte("foo"), 0600); err != nil {
   389  		t.Fatal(err)
   390  		return
   391  	}
   392  	if err := waitForAccounts([]accounts.Account{}, ks); err != nil {
   393  		t.Errorf("Emptying account file failed")
   394  		t.Error(err)
   395  		return
   396  	}
   397  }
   398  
   399  // forceCopyFile is like cp.CopyFile, but doesn't complain if the destination exists.
   400  func forceCopyFile(dst, src string) error {
   401  	data, err := os.ReadFile(src)
   402  	if err != nil {
   403  		return err
   404  	}
   405  	return os.WriteFile(dst, data, 0644)
   406  }