From 0b82bac76d0f842bd2294a290388536951fbc576 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Barbosa?= <joao.paulo.barbosa@gmail.com>
Date: Mon, 4 Jun 2018 23:15:03 +0100
Subject: bugfix: Remove dangling wallet env instance

---
 src/wallet/db.cpp                     | 5 ++++-
 test/functional/wallet_multiwallet.py | 5 +++++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp
index 410dd5009f..01b8eacccb 100644
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -694,8 +694,10 @@ void BerkeleyEnvironment::Flush(bool fShutdown)
             if (mapFileUseCount.empty()) {
                 dbenv->log_archive(&listp, DB_ARCH_REMOVE);
                 Close();
-                if (!fMockDb)
+                if (!fMockDb) {
                     fs::remove_all(fs::path(strPath) / "database");
+                }
+                g_dbenvs.erase(strPath);
             }
         }
     }
@@ -794,5 +796,6 @@ void BerkeleyDatabase::Flush(bool shutdown)
 {
     if (!IsDummy()) {
         env->Flush(shutdown);
+        if (shutdown) env = nullptr;
     }
 }
diff --git a/test/functional/wallet_multiwallet.py b/test/functional/wallet_multiwallet.py
index 8d15ef661b..e6097b5d92 100755
--- a/test/functional/wallet_multiwallet.py
+++ b/test/functional/wallet_multiwallet.py
@@ -256,5 +256,10 @@ class MultiWalletTest(BitcoinTestFramework):
         assert_equal(self.nodes[0].listwallets(), [])
         assert_raises_rpc_error(-32601, "Method not found (wallet method is disabled because no wallet is loaded)", self.nodes[0].getwalletinfo)
 
+        # Successfully load a previously unloaded wallet
+        self.nodes[0].loadwallet('w1')
+        assert_equal(self.nodes[0].listwallets(), ['w1'])
+        assert_equal(w1.getwalletinfo()['walletname'], 'w1')
+
 if __name__ == '__main__':
     MultiWalletTest().main()
-- 
cgit v1.2.3