account_cache_test.go 13 KB

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