github.com/amazechain/amc@v0.1.3/accounts/keystore/keystore_test.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package keystore 18 19 import ( 20 "math/rand" 21 "os" 22 "runtime" 23 "sort" 24 "strings" 25 "sync" 26 "sync/atomic" 27 "testing" 28 "time" 29 30 "github.com/amazechain/amc/accounts" 31 "github.com/amazechain/amc/common/crypto" 32 "github.com/amazechain/amc/common/types" 33 "github.com/amazechain/amc/internal/avm/common" 34 event "github.com/amazechain/amc/modules/event/v2" 35 ) 36 37 var testSigData = make([]byte, 32) 38 39 func TestKeyStore(t *testing.T) { 40 dir, ks := tmpKeyStore(t, true) 41 42 a, err := ks.NewAccount("foo") 43 if err != nil { 44 t.Fatal(err) 45 } 46 if !strings.HasPrefix(a.URL.Path, dir) { 47 t.Errorf("account file %s doesn't have dir prefix", a.URL) 48 } 49 stat, err := os.Stat(a.URL.Path) 50 if err != nil { 51 t.Fatalf("account file %s doesn't exist (%v)", a.URL, err) 52 } 53 if runtime.GOOS != "windows" && stat.Mode() != 0600 { 54 t.Fatalf("account file has wrong mode: got %o, want %o", stat.Mode(), 0600) 55 } 56 if !ks.HasAddress(a.Address) { 57 t.Errorf("HasAccount(%x) should've returned true", a.Address) 58 } 59 if err := ks.Update(a, "foo", "bar"); err != nil { 60 t.Errorf("Update error: %v", err) 61 } 62 if err := ks.Delete(a, "bar"); err != nil { 63 t.Errorf("Delete error: %v", err) 64 } 65 if common.FileExist(a.URL.Path) { 66 t.Errorf("account file %s should be gone after Delete", a.URL) 67 } 68 if ks.HasAddress(a.Address) { 69 t.Errorf("HasAccount(%x) should've returned true after Delete", a.Address) 70 } 71 } 72 73 func TestSign(t *testing.T) { 74 _, ks := tmpKeyStore(t, true) 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, ""); 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 _, ks := tmpKeyStore(t, true) 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 _, ks := tmpKeyStore(t, true) 118 119 pass := "foo" 120 a1, err := ks.NewAccount(pass) 121 if err != nil { 122 t.Fatal(err) 123 } 124 125 // Signing without passphrase fails because account is locked 126 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 127 if err != ErrLocked { 128 t.Fatal("Signing should've failed with ErrLocked before unlocking, got ", err) 129 } 130 131 // Signing with passphrase works 132 if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil { 133 t.Fatal(err) 134 } 135 136 // Signing without passphrase works because account is temp unlocked 137 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 138 if err != nil { 139 t.Fatal("Signing shouldn't return an error after unlocking, got ", err) 140 } 141 142 // Signing fails again after automatic locking 143 time.Sleep(250 * time.Millisecond) 144 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 145 if err != ErrLocked { 146 t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) 147 } 148 } 149 150 func TestOverrideUnlock(t *testing.T) { 151 _, ks := tmpKeyStore(t, false) 152 153 pass := "foo" 154 a1, err := ks.NewAccount(pass) 155 if err != nil { 156 t.Fatal(err) 157 } 158 159 // Unlock indefinitely. 160 if err = ks.TimedUnlock(a1, pass, 5*time.Minute); err != nil { 161 t.Fatal(err) 162 } 163 164 // Signing without passphrase works because account is temp unlocked 165 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 166 if err != nil { 167 t.Fatal("Signing shouldn't return an error after unlocking, got ", err) 168 } 169 170 // reset unlock to a shorter period, invalidates the previous unlock 171 if err = ks.TimedUnlock(a1, pass, 100*time.Millisecond); err != nil { 172 t.Fatal(err) 173 } 174 175 // Signing without passphrase still works because account is temp unlocked 176 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 177 if err != nil { 178 t.Fatal("Signing shouldn't return an error after unlocking, got ", err) 179 } 180 181 // Signing fails again after automatic locking 182 time.Sleep(250 * time.Millisecond) 183 _, err = ks.SignHash(accounts.Account{Address: a1.Address}, testSigData) 184 if err != ErrLocked { 185 t.Fatal("Signing should've failed with ErrLocked timeout expired, got ", err) 186 } 187 } 188 189 // This test should fail under -race if signing races the expiration goroutine. 190 func TestSignRace(t *testing.T) { 191 _, ks := tmpKeyStore(t, false) 192 193 // Create a test account. 194 a1, err := ks.NewAccount("") 195 if err != nil { 196 t.Fatal("could not create the test account", err) 197 } 198 199 if err := ks.TimedUnlock(a1, "", 15*time.Millisecond); err != nil { 200 t.Fatal("could not unlock the test account", err) 201 } 202 end := time.Now().Add(500 * time.Millisecond) 203 for time.Now().Before(end) { 204 if _, err := ks.SignHash(accounts.Account{Address: a1.Address}, testSigData); err == ErrLocked { 205 return 206 } else if err != nil { 207 t.Errorf("Sign error: %v", err) 208 return 209 } 210 time.Sleep(1 * time.Millisecond) 211 } 212 t.Errorf("Account did not lock within the timeout") 213 } 214 215 // Tests that the wallet notifier loop starts and stops correctly based on the 216 // addition and removal of wallet event subscriptions. 217 func TestWalletNotifierLifecycle(t *testing.T) { 218 // Create a temporary keystore to test with 219 _, ks := tmpKeyStore(t, false) 220 221 // Ensure that the notification updater is not running yet 222 time.Sleep(250 * time.Millisecond) 223 ks.mu.RLock() 224 updating := ks.updating 225 ks.mu.RUnlock() 226 227 if updating { 228 t.Errorf("wallet notifier running without subscribers") 229 } 230 // Subscribe to the wallet feed and ensure the updater boots up 231 updates := make(chan accounts.WalletEvent) 232 233 subs := make([]event.Subscription, 2) 234 for i := 0; i < len(subs); i++ { 235 // Create a new subscription 236 subs[i] = ks.Subscribe(updates) 237 238 // Ensure the notifier comes online 239 time.Sleep(250 * time.Millisecond) 240 ks.mu.RLock() 241 updating = ks.updating 242 ks.mu.RUnlock() 243 244 if !updating { 245 t.Errorf("sub %d: wallet notifier not running after subscription", i) 246 } 247 } 248 // Unsubscribe and ensure the updater terminates eventually 249 for i := 0; i < len(subs); i++ { 250 // Close an existing subscription 251 subs[i].Unsubscribe() 252 253 // Ensure the notifier shuts down at and only at the last close 254 for k := 0; k < int(walletRefreshCycle/(250*time.Millisecond))+2; k++ { 255 ks.mu.RLock() 256 updating = ks.updating 257 ks.mu.RUnlock() 258 259 if i < len(subs)-1 && !updating { 260 t.Fatalf("sub %d: event notifier stopped prematurely", i) 261 } 262 if i == len(subs)-1 && !updating { 263 return 264 } 265 time.Sleep(250 * time.Millisecond) 266 } 267 } 268 t.Errorf("wallet notifier didn't terminate after unsubscribe") 269 } 270 271 type walletEvent struct { 272 accounts.WalletEvent 273 a accounts.Account 274 } 275 276 // Tests that wallet notifications and correctly fired when accounts are added 277 // or deleted from the keystore. 278 func TestWalletNotifications(t *testing.T) { 279 _, ks := tmpKeyStore(t, false) 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[types.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 for ev := range updates { 332 events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]}) 333 } 334 checkAccounts(t, live, ks.Wallets()) 335 checkEvents(t, wantEvents, events) 336 } 337 338 // TestImportExport tests the import functionality of a keystore. 339 func TestImportECDSA(t *testing.T) { 340 _, ks := tmpKeyStore(t, true) 341 key, err := crypto.GenerateKey() 342 if err != nil { 343 t.Fatalf("failed to generate key: %v", key) 344 } 345 if _, err = ks.ImportECDSA(key, "old"); err != nil { 346 t.Errorf("importing failed: %v", err) 347 } 348 if _, err = ks.ImportECDSA(key, "old"); err == nil { 349 t.Errorf("importing same key twice succeeded") 350 } 351 if _, err = ks.ImportECDSA(key, "new"); err == nil { 352 t.Errorf("importing same key twice succeeded") 353 } 354 } 355 356 // TestImportECDSA tests the import and export functionality of a keystore. 357 func TestImportExport(t *testing.T) { 358 _, ks := tmpKeyStore(t, true) 359 acc, err := ks.NewAccount("old") 360 if err != nil { 361 t.Fatalf("failed to create account: %v", acc) 362 } 363 json, err := ks.Export(acc, "old", "new") 364 if err != nil { 365 t.Fatalf("failed to export account: %v", acc) 366 } 367 _, ks2 := tmpKeyStore(t, true) 368 if _, err = ks2.Import(json, "old", "old"); err == nil { 369 t.Errorf("importing with invalid password succeeded") 370 } 371 acc2, err := ks2.Import(json, "new", "new") 372 if err != nil { 373 t.Errorf("importing failed: %v", err) 374 } 375 if acc.Address != acc2.Address { 376 t.Error("imported account does not match exported account") 377 } 378 if _, err = ks2.Import(json, "new", "new"); err == nil { 379 t.Errorf("importing a key twice succeeded") 380 } 381 } 382 383 // TestImportRace tests the keystore on races. 384 // This test should fail under -race if importing races. 385 func TestImportRace(t *testing.T) { 386 _, ks := tmpKeyStore(t, true) 387 acc, err := ks.NewAccount("old") 388 if err != nil { 389 t.Fatalf("failed to create account: %v", acc) 390 } 391 json, err := ks.Export(acc, "old", "new") 392 if err != nil { 393 t.Fatalf("failed to export account: %v", acc) 394 } 395 _, ks2 := tmpKeyStore(t, true) 396 var atom uint32 397 var wg sync.WaitGroup 398 wg.Add(2) 399 for i := 0; i < 2; i++ { 400 go func() { 401 defer wg.Done() 402 if _, err := ks2.Import(json, "new", "new"); err != nil { 403 atomic.AddUint32(&atom, 1) 404 } 405 }() 406 } 407 wg.Wait() 408 if atom != 1 { 409 t.Errorf("Import is racy") 410 } 411 } 412 413 // checkAccounts checks that all known live accounts are present in the wallet list. 414 func checkAccounts(t *testing.T, live map[types.Address]accounts.Account, wallets []accounts.Wallet) { 415 if len(live) != len(wallets) { 416 t.Errorf("wallet list doesn't match required accounts: have %d, want %d", len(wallets), len(live)) 417 return 418 } 419 liveList := make([]accounts.Account, 0, len(live)) 420 for _, account := range live { 421 liveList = append(liveList, account) 422 } 423 sort.Sort(accountsByURL(liveList)) 424 for j, wallet := range wallets { 425 if accs := wallet.Accounts(); len(accs) != 1 { 426 t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs)) 427 } else if accs[0] != liveList[j] { 428 t.Errorf("wallet %d: account mismatch: have %v, want %v", j, accs[0], liveList[j]) 429 } 430 } 431 } 432 433 // checkEvents checks that all events in 'want' are present in 'have'. Events may be present multiple times. 434 func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) { 435 for _, wantEv := range want { 436 nmatch := 0 437 for ; len(have) > 0; nmatch++ { 438 if have[0].Kind != wantEv.Kind || have[0].a != wantEv.a { 439 break 440 } 441 have = have[1:] 442 } 443 if nmatch == 0 { 444 t.Fatalf("can't find event with Kind=%v for %x", wantEv.Kind, wantEv.a.Address) 445 } 446 } 447 } 448 449 func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) { 450 d := t.TempDir() 451 newKs := NewPlaintextKeyStore 452 if encrypted { 453 newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) } 454 } 455 return d, newKs(d) 456 }