1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of OpenEthereum.

// OpenEthereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// OpenEthereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with OpenEthereum.  If not, see <http://www.gnu.org/licenses/>.

use parking_lot::{Mutex, RwLock};
use std::{
    collections::{BTreeMap, HashMap},
    num::NonZeroU32,
    path::PathBuf,
    time::{Duration, Instant},
};

use account::SafeAccount;
use accounts_dir::{KeyDirectory, SetKeyError, VaultKey, VaultKeyDirectory};
use crypto::publickey::{
    self, Address, ExtendedKeyPair, KeyPair, Message, Public, Secret, Signature,
};
use ethkey::Password;
use json::{self, OpaqueKeyFile, Uuid};
use presale::PresaleWallet;
use random::Random;
use Derivation;
use Error;
use OpaqueSecret;
use SecretStore;
use SecretVaultRef;
use SimpleSecretStore;
use StoreAccountRef;

lazy_static! {
    static ref KEY_ITERATIONS: NonZeroU32 =
        NonZeroU32::new(crypto::KEY_ITERATIONS as u32).expect("KEY_ITERATIONS > 0; qed");
}

/// Accounts store.
pub struct EthStore {
    store: EthMultiStore,
}

impl EthStore {
    /// Open a new accounts store with given key directory backend.
    pub fn open(directory: Box<dyn KeyDirectory>) -> Result<Self, Error> {
        Self::open_with_iterations(directory, *KEY_ITERATIONS)
    }

    /// Open a new account store with given key directory backend and custom number of iterations.
    pub fn open_with_iterations(
        directory: Box<dyn KeyDirectory>,
        iterations: NonZeroU32,
    ) -> Result<Self, Error> {
        Ok(EthStore {
            store: EthMultiStore::open_with_iterations(directory, iterations)?,
        })
    }

    /// Modify account refresh timeout - how often they are re-read from `KeyDirectory`.
    ///
    /// Setting this to low values (or 0) will cause new accounts to be picked up quickly,
    /// although it may induce heavy disk reads and is not recommended if you manage many keys (say over 10k).
    ///
    /// By default refreshing is disabled, so only accounts created using this instance of `EthStore` are taken into account.
    pub fn set_refresh_time(&self, time: Duration) {
        self.store.set_refresh_time(time)
    }

    fn get(&self, account: &StoreAccountRef) -> Result<SafeAccount, Error> {
        let mut accounts = self.store.get_accounts(account)?.into_iter();
        accounts.next().ok_or(Error::InvalidAccount)
    }
}

impl SimpleSecretStore for EthStore {
    fn insert_account(
        &self,
        vault: SecretVaultRef,
        secret: Secret,
        password: &Password,
    ) -> Result<StoreAccountRef, Error> {
        self.store.insert_account(vault, secret, password)
    }

    fn insert_derived(
        &self,
        vault: SecretVaultRef,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
    ) -> Result<StoreAccountRef, Error> {
        self.store
            .insert_derived(vault, account_ref, password, derivation)
    }

    fn generate_derived(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
    ) -> Result<Address, Error> {
        self.store
            .generate_derived(account_ref, password, derivation)
    }

    fn account_ref(&self, address: &Address) -> Result<StoreAccountRef, Error> {
        self.store.account_ref(address)
    }

    fn accounts(&self) -> Result<Vec<StoreAccountRef>, Error> {
        self.store.accounts()
    }

    fn change_password(
        &self,
        account: &StoreAccountRef,
        old_password: &Password,
        new_password: &Password,
    ) -> Result<(), Error> {
        self.store
            .change_password(account, old_password, new_password)
    }

    fn export_account(
        &self,
        account: &StoreAccountRef,
        password: &Password,
    ) -> Result<OpaqueKeyFile, Error> {
        self.store.export_account(account, password)
    }

    fn remove_account(&self, account: &StoreAccountRef, password: &Password) -> Result<(), Error> {
        self.store.remove_account(account, password)
    }

    fn sign(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        message: &Message,
    ) -> Result<Signature, Error> {
        self.get(account)?.sign(password, message)
    }

    fn sign_derived(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
        message: &Message,
    ) -> Result<Signature, Error> {
        self.store
            .sign_derived(account_ref, password, derivation, message)
    }

    fn agree(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        other: &Public,
    ) -> Result<Secret, Error> {
        self.store.agree(account, password, other)
    }

    fn decrypt(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        shared_mac: &[u8],
        message: &[u8],
    ) -> Result<Vec<u8>, Error> {
        let account = self.get(account)?;
        account.decrypt(password, shared_mac, message)
    }

    fn create_vault(&self, name: &str, password: &Password) -> Result<(), Error> {
        self.store.create_vault(name, password)
    }

    fn open_vault(&self, name: &str, password: &Password) -> Result<(), Error> {
        self.store.open_vault(name, password)
    }

    fn close_vault(&self, name: &str) -> Result<(), Error> {
        self.store.close_vault(name)
    }

    fn list_vaults(&self) -> Result<Vec<String>, Error> {
        self.store.list_vaults()
    }

    fn list_opened_vaults(&self) -> Result<Vec<String>, Error> {
        self.store.list_opened_vaults()
    }

    fn change_vault_password(&self, name: &str, new_password: &Password) -> Result<(), Error> {
        self.store.change_vault_password(name, new_password)
    }

    fn change_account_vault(
        &self,
        vault: SecretVaultRef,
        account: StoreAccountRef,
    ) -> Result<StoreAccountRef, Error> {
        self.store.change_account_vault(vault, account)
    }

    fn get_vault_meta(&self, name: &str) -> Result<String, Error> {
        self.store.get_vault_meta(name)
    }

    fn set_vault_meta(&self, name: &str, meta: &str) -> Result<(), Error> {
        self.store.set_vault_meta(name, meta)
    }
}

impl SecretStore for EthStore {
    fn raw_secret(
        &self,
        account: &StoreAccountRef,
        password: &Password,
    ) -> Result<OpaqueSecret, Error> {
        Ok(OpaqueSecret(self.get(account)?.crypto.secret(password)?))
    }

    fn import_presale(
        &self,
        vault: SecretVaultRef,
        json: &[u8],
        password: &Password,
    ) -> Result<StoreAccountRef, Error> {
        let json_wallet = json::PresaleWallet::load(json)
            .map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))?;
        let wallet = PresaleWallet::from(json_wallet);
        let keypair = wallet
            .decrypt(password)
            .map_err(|_| Error::InvalidPassword)?;
        self.insert_account(vault, keypair.secret().clone(), password)
    }

    fn import_wallet(
        &self,
        vault: SecretVaultRef,
        json: &[u8],
        password: &Password,
        gen_id: bool,
    ) -> Result<StoreAccountRef, Error> {
        let json_keyfile = json::KeyFile::load(json)
            .map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))?;
        let mut safe_account = SafeAccount::from_file(json_keyfile, None, &None)?;

        if gen_id {
            safe_account.id = Random::random();
        }

        let secret = safe_account
            .crypto
            .secret(password)
            .map_err(|_| Error::InvalidPassword)?;
        safe_account.address = KeyPair::from_secret(secret)?.address();
        self.store.import(vault, safe_account)
    }

    fn test_password(&self, account: &StoreAccountRef, password: &Password) -> Result<bool, Error> {
        let account = self.get(account)?;
        Ok(account.check_password(password))
    }

    fn copy_account(
        &self,
        new_store: &dyn SimpleSecretStore,
        new_vault: SecretVaultRef,
        account: &StoreAccountRef,
        password: &Password,
        new_password: &Password,
    ) -> Result<(), Error> {
        let account = self.get(account)?;
        let secret = account.crypto.secret(password)?;
        new_store.insert_account(new_vault, secret, new_password)?;
        Ok(())
    }

    fn public(&self, account: &StoreAccountRef, password: &Password) -> Result<Public, Error> {
        let account = self.get(account)?;
        account.public(password)
    }

    fn uuid(&self, account: &StoreAccountRef) -> Result<Uuid, Error> {
        let account = self.get(account)?;
        Ok(account.id.into())
    }

    fn name(&self, account: &StoreAccountRef) -> Result<String, Error> {
        let account = self.get(account)?;
        Ok(account.name.clone())
    }

    fn meta(&self, account: &StoreAccountRef) -> Result<String, Error> {
        let account = self.get(account)?;
        Ok(account.meta.clone())
    }

    fn set_name(&self, account_ref: &StoreAccountRef, name: String) -> Result<(), Error> {
        let old = self.get(account_ref)?;
        let mut safe_account = old.clone();
        safe_account.name = name;

        // save to file
        self.store.update(account_ref, old, safe_account)
    }

    fn set_meta(&self, account_ref: &StoreAccountRef, meta: String) -> Result<(), Error> {
        let old = self.get(account_ref)?;
        let mut safe_account = old.clone();
        safe_account.meta = meta;

        // save to file
        self.store.update(account_ref, old, safe_account)
    }

    fn local_path(&self) -> PathBuf {
        self.store.dir.path().cloned().unwrap_or_else(PathBuf::new)
    }
}

/// Similar to `EthStore` but may store many accounts (with different passwords) for the same `Address`
pub struct EthMultiStore {
    dir: Box<dyn KeyDirectory>,
    iterations: NonZeroU32,
    // order lock: cache, then vaults
    cache: RwLock<BTreeMap<StoreAccountRef, Vec<SafeAccount>>>,
    vaults: Mutex<HashMap<String, Box<dyn VaultKeyDirectory>>>,
    timestamp: Mutex<Timestamp>,
}

struct Timestamp {
    dir_hash: Option<u64>,
    last_checked: Instant,
    refresh_time: Duration,
}

impl EthMultiStore {
    /// Open new multi-accounts store with given key directory backend.
    pub fn open(directory: Box<dyn KeyDirectory>) -> Result<Self, Error> {
        Self::open_with_iterations(directory, *KEY_ITERATIONS)
    }

    /// Open new multi-accounts store with given key directory backend and custom number of iterations for new keys.
    pub fn open_with_iterations(
        directory: Box<dyn KeyDirectory>,
        iterations: NonZeroU32,
    ) -> Result<Self, Error> {
        let store = EthMultiStore {
            dir: directory,
            vaults: Mutex::new(HashMap::new()),
            iterations: iterations,
            cache: Default::default(),
            timestamp: Mutex::new(Timestamp {
                dir_hash: None,
                last_checked: Instant::now(),
                // by default we never refresh accounts
                refresh_time: Duration::from_secs(u64::max_value()),
            }),
        };
        store.reload_accounts()?;
        Ok(store)
    }

    /// Modify account refresh timeout - how often they are re-read from `KeyDirectory`.
    ///
    /// Setting this to low values (or 0) will cause new accounts to be picked up quickly,
    /// although it may induce heavy disk reads and is not recommended if you manage many keys (say over 10k).
    ///
    /// By default refreshing is disabled, so only accounts created using this instance of `EthStore` are taken into account.
    pub fn set_refresh_time(&self, time: Duration) {
        self.timestamp.lock().refresh_time = time;
    }

    fn reload_if_changed(&self) -> Result<(), Error> {
        let mut last_timestamp = self.timestamp.lock();
        let now = Instant::now();
        if now - last_timestamp.last_checked > last_timestamp.refresh_time {
            let dir_hash = Some(self.dir.unique_repr()?);
            last_timestamp.last_checked = now;
            if last_timestamp.dir_hash == dir_hash {
                return Ok(());
            }
            self.reload_accounts()?;
            last_timestamp.dir_hash = dir_hash;
        }
        Ok(())
    }

    fn reload_accounts(&self) -> Result<(), Error> {
        let mut cache = self.cache.write();

        let mut new_accounts = BTreeMap::new();
        for account in self.dir.load()? {
            let account_ref = StoreAccountRef::root(account.address);
            new_accounts
                .entry(account_ref)
                .or_insert_with(Vec::new)
                .push(account);
        }
        for (vault_name, vault) in &*self.vaults.lock() {
            for account in vault.load()? {
                let account_ref = StoreAccountRef::vault(vault_name, account.address);
                new_accounts
                    .entry(account_ref)
                    .or_insert_with(Vec::new)
                    .push(account);
            }
        }

        *cache = new_accounts;
        Ok(())
    }

    fn get_accounts(&self, account: &StoreAccountRef) -> Result<Vec<SafeAccount>, Error> {
        let from_cache = |account| {
            let cache = self.cache.read();
            if let Some(accounts) = cache.get(account) {
                if !accounts.is_empty() {
                    return Some(accounts.clone());
                }
            }

            None
        };

        match from_cache(account) {
            Some(accounts) => Ok(accounts),
            None => {
                self.reload_if_changed()?;
                from_cache(account).ok_or(Error::InvalidAccount)
            }
        }
    }

    fn get_matching(
        &self,
        account: &StoreAccountRef,
        password: &Password,
    ) -> Result<Vec<SafeAccount>, Error> {
        let accounts = self.get_accounts(account)?;

        Ok(accounts
            .into_iter()
            .filter(|acc| acc.check_password(password))
            .collect())
    }

    fn import(
        &self,
        vault: SecretVaultRef,
        account: SafeAccount,
    ) -> Result<StoreAccountRef, Error> {
        // save to file
        let account = match vault {
            SecretVaultRef::Root => self.dir.insert(account)?,
            SecretVaultRef::Vault(ref vault_name) => self
                .vaults
                .lock()
                .get_mut(vault_name)
                .ok_or(Error::VaultNotFound)?
                .insert(account)?,
        };

        // update cache
        let account_ref = StoreAccountRef::new(vault, account.address.clone());
        let mut cache = self.cache.write();
        cache
            .entry(account_ref.clone())
            .or_insert_with(Vec::new)
            .push(account);

        Ok(account_ref)
    }

    fn update(
        &self,
        account_ref: &StoreAccountRef,
        old: SafeAccount,
        new: SafeAccount,
    ) -> Result<(), Error> {
        // save to file
        let account = match account_ref.vault {
            SecretVaultRef::Root => self.dir.update(new)?,
            SecretVaultRef::Vault(ref vault_name) => self
                .vaults
                .lock()
                .get_mut(vault_name)
                .ok_or(Error::VaultNotFound)?
                .update(new)?,
        };

        // update cache
        let mut cache = self.cache.write();
        let accounts = cache.entry(account_ref.clone()).or_insert_with(Vec::new);
        // Remove old account
        accounts.retain(|acc| acc != &old);
        // And push updated to the end
        accounts.push(account);
        Ok(())
    }

    fn remove_safe_account(
        &self,
        account_ref: &StoreAccountRef,
        account: &SafeAccount,
    ) -> Result<(), Error> {
        // Remove from dir
        match account_ref.vault {
            SecretVaultRef::Root => self.dir.remove(&account)?,
            SecretVaultRef::Vault(ref vault_name) => self
                .vaults
                .lock()
                .get(vault_name)
                .ok_or(Error::VaultNotFound)?
                .remove(&account)?,
        };

        // Remove from cache
        let mut cache = self.cache.write();
        let is_empty = {
            if let Some(accounts) = cache.get_mut(account_ref) {
                if let Some(position) = accounts.iter().position(|acc| acc == account) {
                    accounts.remove(position);
                }
                accounts.is_empty()
            } else {
                false
            }
        };

        if is_empty {
            cache.remove(account_ref);
        }

        return Ok(());
    }

    fn generate(&self, secret: Secret, derivation: Derivation) -> Result<ExtendedKeyPair, Error> {
        let mut extended = ExtendedKeyPair::new(secret);
        match derivation {
            Derivation::Hierarchical(path) => {
                for path_item in path {
                    extended = extended.derive(if path_item.soft {
                        publickey::Derivation::Soft(path_item.index)
                    } else {
                        publickey::Derivation::Hard(path_item.index)
                    })?;
                }
            }
            Derivation::SoftHash(h256) => {
                extended = extended.derive(publickey::Derivation::Soft(h256))?;
            }
            Derivation::HardHash(h256) => {
                extended = extended.derive(publickey::Derivation::Hard(h256))?;
            }
        }
        Ok(extended)
    }
}

impl SimpleSecretStore for EthMultiStore {
    fn insert_account(
        &self,
        vault: SecretVaultRef,
        secret: Secret,
        password: &Password,
    ) -> Result<StoreAccountRef, Error> {
        let keypair = KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)?;
        let id: [u8; 16] = Random::random();
        let account = SafeAccount::create(
            &keypair,
            id,
            password,
            self.iterations,
            "".to_owned(),
            "{}".to_owned(),
        )?;
        self.import(vault, account)
    }

    fn insert_derived(
        &self,
        vault: SecretVaultRef,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
    ) -> Result<StoreAccountRef, Error> {
        let accounts = self.get_matching(account_ref, password)?;
        for account in accounts {
            let extended = self.generate(account.crypto.secret(password)?, derivation)?;
            return self.insert_account(vault, extended.secret().as_raw().clone(), password);
        }
        Err(Error::InvalidPassword)
    }

    fn generate_derived(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
    ) -> Result<Address, Error> {
        let accounts = self.get_matching(&account_ref, password)?;
        for account in accounts {
            let extended = self.generate(account.crypto.secret(password)?, derivation)?;
            return Ok(publickey::public_to_address(extended.public().public()));
        }
        Err(Error::InvalidPassword)
    }

    fn sign_derived(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
        derivation: Derivation,
        message: &Message,
    ) -> Result<Signature, Error> {
        let accounts = self.get_matching(&account_ref, password)?;
        for account in accounts {
            let extended = self.generate(account.crypto.secret(password)?, derivation)?;
            let secret = extended.secret().as_raw();
            return Ok(publickey::sign(&secret, message)?);
        }
        Err(Error::InvalidPassword)
    }

    fn account_ref(&self, address: &Address) -> Result<StoreAccountRef, Error> {
        let read_from_cache = |address: &Address| {
            use std::collections::Bound;
            let cache = self.cache.read();
            let mut r = cache.range((Bound::Included(*address), Bound::Included(*address)));
            r.next().map(|(k, _)| k.clone())
        };

        match read_from_cache(address) {
            Some(account) => Ok(account),
            None => {
                self.reload_if_changed()?;
                read_from_cache(address).ok_or(Error::InvalidAccount)
            }
        }
    }

    fn accounts(&self) -> Result<Vec<StoreAccountRef>, Error> {
        self.reload_if_changed()?;
        Ok(self.cache.read().keys().cloned().collect())
    }

    fn remove_account(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
    ) -> Result<(), Error> {
        let accounts = self.get_matching(account_ref, password)?;

        for account in accounts {
            return self.remove_safe_account(account_ref, &account);
        }

        Err(Error::InvalidPassword)
    }

    fn change_password(
        &self,
        account_ref: &StoreAccountRef,
        old_password: &Password,
        new_password: &Password,
    ) -> Result<(), Error> {
        let accounts = self.get_matching(account_ref, old_password)?;

        if accounts.is_empty() {
            return Err(Error::InvalidPassword);
        }

        for account in accounts {
            // Change password
            let new_account =
                account.change_password(old_password, new_password, self.iterations)?;
            self.update(account_ref, account, new_account)?;
        }

        Ok(())
    }

    fn export_account(
        &self,
        account_ref: &StoreAccountRef,
        password: &Password,
    ) -> Result<OpaqueKeyFile, Error> {
        self.get_matching(account_ref, password)?
            .into_iter()
            .nth(0)
            .map(Into::into)
            .ok_or(Error::InvalidPassword)
    }

    fn sign(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        message: &Message,
    ) -> Result<Signature, Error> {
        let accounts = self.get_matching(account, password)?;
        match accounts.first() {
            Some(ref account) => account.sign(password, message),
            None => Err(Error::InvalidPassword),
        }
    }

    fn decrypt(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        shared_mac: &[u8],
        message: &[u8],
    ) -> Result<Vec<u8>, Error> {
        let accounts = self.get_matching(account, password)?;
        match accounts.first() {
            Some(ref account) => account.decrypt(password, shared_mac, message),
            None => Err(Error::InvalidPassword),
        }
    }

    fn agree(
        &self,
        account: &StoreAccountRef,
        password: &Password,
        other: &Public,
    ) -> Result<Secret, Error> {
        let accounts = self.get_matching(account, password)?;
        match accounts.first() {
            Some(ref account) => account.agree(password, other),
            None => Err(Error::InvalidPassword),
        }
    }

    fn create_vault(&self, name: &str, password: &Password) -> Result<(), Error> {
        let is_vault_created = {
            // lock border
            let mut vaults = self.vaults.lock();
            if !vaults.contains_key(&name.to_owned()) {
                let vault_provider = self
                    .dir
                    .as_vault_provider()
                    .ok_or(Error::VaultsAreNotSupported)?;
                let vault =
                    vault_provider.create(name, VaultKey::new(password, self.iterations))?;
                vaults.insert(name.to_owned(), vault);
                true
            } else {
                false
            }
        };

        if is_vault_created {
            self.reload_accounts()?;
        }

        Ok(())
    }

    fn open_vault(&self, name: &str, password: &Password) -> Result<(), Error> {
        let is_vault_opened = {
            // lock border
            let mut vaults = self.vaults.lock();
            if !vaults.contains_key(&name.to_owned()) {
                let vault_provider = self
                    .dir
                    .as_vault_provider()
                    .ok_or(Error::VaultsAreNotSupported)?;
                let vault = vault_provider.open(name, VaultKey::new(password, self.iterations))?;
                vaults.insert(name.to_owned(), vault);
                true
            } else {
                false
            }
        };

        if is_vault_opened {
            self.reload_accounts()?;
        }

        Ok(())
    }

    fn close_vault(&self, name: &str) -> Result<(), Error> {
        let is_vault_removed = self.vaults.lock().remove(&name.to_owned()).is_some();
        if is_vault_removed {
            self.reload_accounts()?;
        }
        Ok(())
    }

    fn list_vaults(&self) -> Result<Vec<String>, Error> {
        let vault_provider = self
            .dir
            .as_vault_provider()
            .ok_or(Error::VaultsAreNotSupported)?;
        vault_provider.list_vaults()
    }

    fn list_opened_vaults(&self) -> Result<Vec<String>, Error> {
        Ok(self.vaults.lock().keys().cloned().collect())
    }

    fn change_vault_password(&self, name: &str, new_password: &Password) -> Result<(), Error> {
        let old_key = self
            .vaults
            .lock()
            .get(name)
            .map(|v| v.key())
            .ok_or(Error::VaultNotFound)?;
        let vault_provider = self
            .dir
            .as_vault_provider()
            .ok_or(Error::VaultsAreNotSupported)?;
        let vault = vault_provider.open(name, old_key)?;
        match vault.set_key(VaultKey::new(new_password, self.iterations)) {
            Ok(_) => self
                .close_vault(name)
                .and_then(|_| self.open_vault(name, new_password)),
            Err(SetKeyError::Fatal(err)) => {
                let _ = self.close_vault(name);
                Err(err)
            }
            Err(SetKeyError::NonFatalNew(err)) => {
                let _ = self
                    .close_vault(name)
                    .and_then(|_| self.open_vault(name, new_password));
                Err(err)
            }
            Err(SetKeyError::NonFatalOld(err)) => Err(err),
        }
    }

    fn change_account_vault(
        &self,
        vault: SecretVaultRef,
        account_ref: StoreAccountRef,
    ) -> Result<StoreAccountRef, Error> {
        if account_ref.vault == vault {
            return Ok(account_ref);
        }

        let account = self
            .get_accounts(&account_ref)?
            .into_iter()
            .nth(0)
            .ok_or(Error::InvalidAccount)?;
        let new_account_ref = self.import(vault, account.clone())?;
        self.remove_safe_account(&account_ref, &account)?;
        self.reload_accounts()?;
        Ok(new_account_ref)
    }

    fn get_vault_meta(&self, name: &str) -> Result<String, Error> {
        // vault meta contains password hint
        // => allow reading meta even if vault is not yet opened
        self.vaults
            .lock()
            .get(name)
            .and_then(|v| Some(v.meta()))
            .ok_or(Error::VaultNotFound)
            .or_else(|_| {
                let vault_provider = self
                    .dir
                    .as_vault_provider()
                    .ok_or(Error::VaultsAreNotSupported)?;
                vault_provider.vault_meta(name)
            })
    }

    fn set_vault_meta(&self, name: &str, meta: &str) -> Result<(), Error> {
        self.vaults
            .lock()
            .get(name)
            .ok_or(Error::VaultNotFound)
            .and_then(|v| v.set_meta(meta))
    }
}

#[cfg(test)]
mod tests {
    extern crate tempdir;

    use self::tempdir::TempDir;
    use super::{EthMultiStore, EthStore};
    use accounts_dir::{KeyDirectory, MemoryDirectory, RootDiskDirectory};
    use crypto::publickey::{Generator, KeyPair, Random};
    use ethereum_types::H256;
    use secret_store::{
        Derivation, SecretStore, SecretVaultRef, SimpleSecretStore, StoreAccountRef,
    };

    fn keypair() -> KeyPair {
        Random.generate()
    }

    fn store() -> EthStore {
        EthStore::open(Box::new(MemoryDirectory::default()))
            .expect("MemoryDirectory always load successfuly; qed")
    }

    fn multi_store() -> EthMultiStore {
        EthMultiStore::open(Box::new(MemoryDirectory::default()))
            .expect("MemoryDirectory always load successfuly; qed")
    }

    struct RootDiskDirectoryGuard {
        pub key_dir: Option<Box<dyn KeyDirectory>>,
        _path: TempDir,
    }

    impl RootDiskDirectoryGuard {
        pub fn new() -> Self {
            let temp_path = TempDir::new("").unwrap();
            let disk_dir = Box::new(RootDiskDirectory::create(temp_path.path()).unwrap());

            RootDiskDirectoryGuard {
                key_dir: Some(disk_dir),
                _path: temp_path,
            }
        }
    }

    #[test]
    fn should_insert_account_successfully() {
        // given
        let store = store();
        let keypair = keypair();

        // when
        let passwd = "test".into();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd)
            .unwrap();

        // then
        assert_eq!(address, StoreAccountRef::root(keypair.address()));
        assert!(store.get(&address).is_ok(), "Should contain account.");
        assert_eq!(
            store.accounts().unwrap().len(),
            1,
            "Should have one account."
        );
    }

    #[test]
    fn should_update_meta_and_name() {
        // given
        let store = store();
        let keypair = keypair();
        let passwd = "test".into();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd)
            .unwrap();
        assert_eq!(&store.meta(&address).unwrap(), "{}");
        assert_eq!(&store.name(&address).unwrap(), "");

        // when
        store.set_meta(&address, "meta".into()).unwrap();
        store.set_name(&address, "name".into()).unwrap();

        // then
        assert_eq!(&store.meta(&address).unwrap(), "meta");
        assert_eq!(&store.name(&address).unwrap(), "name");
        assert_eq!(store.accounts().unwrap().len(), 1);
    }

    #[test]
    fn should_remove_account() {
        // given
        let store = store();
        let passwd = "test".into();
        let keypair = keypair();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd)
            .unwrap();

        // when
        store.remove_account(&address, &passwd).unwrap();

        // then
        assert_eq!(store.accounts().unwrap().len(), 0, "Should remove account.");
    }

    #[test]
    fn should_return_true_if_password_is_correct() {
        // given
        let store = store();
        let passwd = "test".into();
        let keypair = keypair();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd)
            .unwrap();

        // when
        let res1 = store.test_password(&address, &"x".into()).unwrap();
        let res2 = store.test_password(&address, &passwd).unwrap();

        assert!(!res1, "First password should be invalid.");
        assert!(res2, "Second password should be correct.");
    }

    #[test]
    fn multistore_should_be_able_to_have_the_same_account_twice() {
        // given
        let store = multi_store();
        let passwd1 = "test".into();
        let passwd2 = "xyz".into();
        let keypair = keypair();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd1)
            .unwrap();
        let address2 = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd2)
            .unwrap();
        assert_eq!(address, address2);

        // when
        assert!(
            store.remove_account(&address, &passwd1).is_ok(),
            "First password should work."
        );
        assert_eq!(store.accounts().unwrap().len(), 1);

        assert!(
            store.remove_account(&address, &passwd2).is_ok(),
            "Second password should work too."
        );
        assert_eq!(store.accounts().unwrap().len(), 0);
    }

    #[test]
    fn should_copy_account() {
        // given
        let store = store();
        let passwd1 = "test".into();
        let passwd2 = "xzy".into();
        let multi_store = multi_store();
        let keypair = keypair();
        let message = [1u8; 32].into();
        let address = store
            .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd1)
            .unwrap();
        assert_eq!(multi_store.accounts().unwrap().len(), 0);

        // when
        store
            .copy_account(
                &multi_store,
                SecretVaultRef::Root,
                &address,
                &passwd1,
                &passwd2,
            )
            .unwrap();

        // then
        assert!(
            store.test_password(&address, &passwd1).unwrap(),
            "First password should work for store."
        );
        assert!(
            multi_store.sign(&address, &passwd2, &message).is_ok(),
            "Second password should work for second store."
        );
        assert_eq!(multi_store.accounts().unwrap().len(), 1);
    }

    #[test]
    fn should_create_and_open_vaults() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();
        let name2 = "vault2";
        let password2 = "password2".into();
        let keypair1 = keypair();
        let keypair2 = keypair();
        let keypair3 = keypair();
        let password3 = "password3".into();

        // when
        store.create_vault(name1, &password1).unwrap();
        store.create_vault(name2, &password2).unwrap();

        // then [can create vaults] ^^^

        // and when
        store
            .insert_account(
                SecretVaultRef::Vault(name1.to_owned()),
                keypair1.secret().clone(),
                &password1,
            )
            .unwrap();
        store
            .insert_account(
                SecretVaultRef::Vault(name2.to_owned()),
                keypair2.secret().clone(),
                &password2,
            )
            .unwrap();
        store
            .insert_account(SecretVaultRef::Root, keypair3.secret().clone(), &password3)
            .unwrap();
        store
            .insert_account(
                SecretVaultRef::Vault("vault3".to_owned()),
                keypair1.secret().clone(),
                &password3,
            )
            .unwrap_err();
        let accounts = store.accounts().unwrap();

        // then [can create accounts in vaults]
        assert_eq!(accounts.len(), 3);
        assert!(accounts.iter().any(|a| a.vault == SecretVaultRef::Root));
        assert!(accounts
            .iter()
            .any(|a| a.vault == SecretVaultRef::Vault(name1.to_owned())));
        assert!(accounts
            .iter()
            .any(|a| a.vault == SecretVaultRef::Vault(name2.to_owned())));

        // and when
        store.close_vault(name1).unwrap();
        store.close_vault(name2).unwrap();
        store.close_vault("vault3").unwrap();
        let accounts = store.accounts().unwrap();

        // then [can close vaults + accounts from vaults disappear]
        assert_eq!(accounts.len(), 1);
        assert!(accounts.iter().any(|a| a.vault == SecretVaultRef::Root));

        // and when
        store.open_vault(name1, &password2).unwrap_err();
        store.open_vault(name2, &password1).unwrap_err();
        store.open_vault(name1, &password1).unwrap();
        store.open_vault(name2, &password2).unwrap();
        let accounts = store.accounts().unwrap();

        // then [can check vaults on open + can reopen vaults + accounts from vaults appear]
        assert_eq!(accounts.len(), 3);
        assert!(accounts.iter().any(|a| a.vault == SecretVaultRef::Root));
        assert!(accounts
            .iter()
            .any(|a| a.vault == SecretVaultRef::Vault(name1.to_owned())));
        assert!(accounts
            .iter()
            .any(|a| a.vault == SecretVaultRef::Vault(name2.to_owned())));
    }

    #[test]
    fn should_move_vault_acounts() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();
        let name2 = "vault2";
        let password2 = "password2".into();
        let password3 = "password3".into();
        let keypair1 = keypair();
        let keypair2 = keypair();
        let keypair3 = keypair();

        // when
        store.create_vault(name1, &password1).unwrap();
        store.create_vault(name2, &password2).unwrap();
        let account1 = store
            .insert_account(
                SecretVaultRef::Vault(name1.to_owned()),
                keypair1.secret().clone(),
                &password1,
            )
            .unwrap();
        let account2 = store
            .insert_account(
                SecretVaultRef::Vault(name1.to_owned()),
                keypair2.secret().clone(),
                &password1,
            )
            .unwrap();
        let account3 = store
            .insert_account(SecretVaultRef::Root, keypair3.secret().clone(), &password3)
            .unwrap();

        // then
        let account1 = store
            .change_account_vault(SecretVaultRef::Root, account1.clone())
            .unwrap();
        let account2 = store
            .change_account_vault(SecretVaultRef::Vault(name2.to_owned()), account2.clone())
            .unwrap();
        let account3 = store
            .change_account_vault(SecretVaultRef::Vault(name2.to_owned()), account3)
            .unwrap();
        let accounts = store.accounts().unwrap();
        assert_eq!(accounts.len(), 3);
        assert!(accounts
            .iter()
            .any(|a| a == &StoreAccountRef::root(account1.address.clone())));
        assert!(accounts
            .iter()
            .any(|a| a == &StoreAccountRef::vault(name2, account2.address.clone())));
        assert!(accounts
            .iter()
            .any(|a| a == &StoreAccountRef::vault(name2, account3.address.clone())));

        // and then
        assert_eq!(
            store
                .meta(&StoreAccountRef::root(account1.address))
                .unwrap(),
            r#"{}"#
        );
        assert_eq!(
            store
                .meta(&StoreAccountRef::vault("vault2", account2.address))
                .unwrap(),
            r#"{"vault":"vault2"}"#
        );
        assert_eq!(
            store
                .meta(&StoreAccountRef::vault("vault2", account3.address))
                .unwrap(),
            r#"{"vault":"vault2"}"#
        );
    }

    #[test]
    fn should_not_remove_account_when_moving_to_self() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let password1 = "password1".into();
        let keypair1 = keypair();

        // when
        let account1 = store
            .insert_account(SecretVaultRef::Root, keypair1.secret().clone(), &password1)
            .unwrap();
        store
            .change_account_vault(SecretVaultRef::Root, account1)
            .unwrap();

        // then
        let accounts = store.accounts().unwrap();
        assert_eq!(accounts.len(), 1);
    }

    #[test]
    fn should_remove_account_from_vault() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();
        let keypair1 = keypair();

        // when
        store.create_vault(name1, &password1).unwrap();
        let account1 = store
            .insert_account(
                SecretVaultRef::Vault(name1.to_owned()),
                keypair1.secret().clone(),
                &password1,
            )
            .unwrap();
        assert_eq!(store.accounts().unwrap().len(), 1);

        // then
        store.remove_account(&account1, &password1).unwrap();
        assert_eq!(store.accounts().unwrap().len(), 0);
    }

    #[test]
    fn should_not_remove_account_from_vault_when_password_is_incorrect() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();
        let password2 = "password2".into();
        let keypair1 = keypair();

        // when
        store.create_vault(name1, &password1).unwrap();
        let account1 = store
            .insert_account(
                SecretVaultRef::Vault(name1.to_owned()),
                keypair1.secret().clone(),
                &password1,
            )
            .unwrap();
        assert_eq!(store.accounts().unwrap().len(), 1);

        // then
        store.remove_account(&account1, &password2).unwrap_err();
        assert_eq!(store.accounts().unwrap().len(), 1);
    }

    #[test]
    fn should_change_vault_password() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name = "vault";
        let password = "password".into();
        let keypair = keypair();

        // when
        store.create_vault(name, &password).unwrap();
        store
            .insert_account(
                SecretVaultRef::Vault(name.to_owned()),
                keypair.secret().clone(),
                &password,
            )
            .unwrap();

        // then
        assert_eq!(store.accounts().unwrap().len(), 1);
        let new_password = "new_password".into();
        store.change_vault_password(name, &new_password).unwrap();
        assert_eq!(store.accounts().unwrap().len(), 1);

        // and when
        store.close_vault(name).unwrap();

        // then
        store.open_vault(name, &new_password).unwrap();
        assert_eq!(store.accounts().unwrap().len(), 1);
    }

    #[test]
    fn should_have_different_passwords_for_vault_secret_and_meta() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name = "vault";
        let password = "password".into();
        let secret_password = "sec_password".into();
        let keypair = keypair();

        // when
        store.create_vault(name, &password).unwrap();
        let account_ref = store
            .insert_account(
                SecretVaultRef::Vault(name.to_owned()),
                keypair.secret().clone(),
                &secret_password,
            )
            .unwrap();

        // then
        assert_eq!(store.accounts().unwrap().len(), 1);
        let new_secret_password = "new_sec_password".into();
        store
            .change_password(&account_ref, &secret_password, &new_secret_password)
            .unwrap();
        assert_eq!(store.accounts().unwrap().len(), 1);
    }

    #[test]
    fn should_list_opened_vaults() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();
        let name2 = "vault2";
        let password2 = "password2".into();
        let name3 = "vault3";
        let password3 = "password3".into();

        // when
        store.create_vault(name1, &password1).unwrap();
        store.create_vault(name2, &password2).unwrap();
        store.create_vault(name3, &password3).unwrap();
        store.close_vault(name2).unwrap();

        // then
        let opened_vaults = store.list_opened_vaults().unwrap();
        assert_eq!(opened_vaults.len(), 2);
        assert!(opened_vaults.iter().any(|v| &*v == name1));
        assert!(opened_vaults.iter().any(|v| &*v == name3));
    }

    #[test]
    fn should_manage_vaults_meta() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name1 = "vault1";
        let password1 = "password1".into();

        // when
        store.create_vault(name1, &password1).unwrap();

        // then
        assert_eq!(store.get_vault_meta(name1).unwrap(), "{}".to_owned());
        assert!(store.set_vault_meta(name1, "Hello, world!!!").is_ok());
        assert_eq!(
            store.get_vault_meta(name1).unwrap(),
            "Hello, world!!!".to_owned()
        );

        // and when
        store.close_vault(name1).unwrap();
        store.open_vault(name1, &password1).unwrap();

        // then
        assert_eq!(
            store.get_vault_meta(name1).unwrap(),
            "Hello, world!!!".to_owned()
        );

        // and when
        store.close_vault(name1).unwrap();

        // then
        assert_eq!(
            store.get_vault_meta(name1).unwrap(),
            "Hello, world!!!".to_owned()
        );
        assert!(store.get_vault_meta("vault2").is_err());
    }

    #[test]
    fn should_store_derived_keys() {
        // given we have one account in the store
        let store = store();
        let keypair = keypair();
        let address = store
            .insert_account(
                SecretVaultRef::Root,
                keypair.secret().clone(),
                &"test".into(),
            )
            .unwrap();

        // when we deriving from that account
        let derived = store
            .insert_derived(
                SecretVaultRef::Root,
                &address,
                &"test".into(),
                Derivation::HardHash(H256::zero()),
            )
            .unwrap();

        // there should be 2 accounts in the store
        let accounts = store.accounts().unwrap();
        assert_eq!(accounts.len(), 2);

        let message = [1u8; 32].into();
        // and we can sign with the derived contract
        assert!(
            store.sign(&derived, &"test".into(), &message).is_ok(),
            "Second password should work for second store."
        );
    }

    #[test]
    fn should_save_meta_when_setting_before_password() {
        // given
        let mut dir = RootDiskDirectoryGuard::new();
        let store = EthStore::open(dir.key_dir.take().unwrap()).unwrap();
        let name = "vault";
        let password = "password1".into();
        let new_password = "password2".into();

        // when
        store.create_vault(name, &password).unwrap();
        store.set_vault_meta(name, "OldMeta").unwrap();
        store.change_vault_password(name, &new_password).unwrap();

        // then
        assert_eq!(store.get_vault_meta(name).unwrap(), "OldMeta".to_owned());
    }

    #[test]
    fn should_export_account() {
        // given
        let store = store();
        let keypair = keypair();
        let address = store
            .insert_account(
                SecretVaultRef::Root,
                keypair.secret().clone(),
                &"test".into(),
            )
            .unwrap();

        // when
        let exported = store.export_account(&address, &"test".into());

        // then
        assert!(
            exported.is_ok(),
            "Should export single account: {:?}",
            exported
        );
    }
}