According to the BerkeleyDB docs, the DbEnv handle may not be accessed after close() has been called. This change ensures that we create a new handle after close() is called. This avoids a segfault when the first connection attempt fails and then a second connection attempt tries to call open() on the already closed DbEnv handle.
Without the patch, bitcoindd reliably crashes in the second call to set_lg_dir() after close() if
there is an issue with the database:
 02018-05-03T13:27:21Z Bitcoin Core version v0.16.99.0-a024a1841-dirty (debug build)
 1[...]
 22018-05-03T13:27:21Z Using wallet directory /home/tim/.bitcoin
 32018-05-03T13:27:21Z init message: Verifying wallet(s)...
 42018-05-03T13:27:21Z Using BerkeleyDB version Berkeley DB 4.8.30: (April  9, 2010)
 52018-05-03T13:27:21Z Using wallet wallet.dat
 62018-05-03T13:27:21Z BerkeleyEnvironment::Open: LogDir=/home/tim/.bitcoin/database 
 72018-05-03T13:27:21Z BerkeleyEnvironment::Open: Error -30974 opening database environment: DB_RUNRECOVERY: Fatal error, run database recovery
 82018-05-03T13:27:21Z Moved old /home/tim/.bitcoin/database to /home/tim/.bitcoin/database.1525354041.bak. Retrying.
 92018-05-03T13:27:21Z BerkeleyEnvironment::Open: LogDir=/home/tim/.bitcoin/database ErrorFile=/home/tim/.bitcoin/db.log
10[1]    14533 segmentation fault (core dumped)  ./src/bitcoind
After the fix:
 02018-05-03T17:19:32Z Bitcoin Core version v0.16.99.0-cc09e3bd0-dirty (release build)
 1[...]
 22018-05-03T17:19:32Z Using wallet directory /home/tim/.bitcoin
 32018-05-03T17:19:32Z init message: Verifying wallet(s)...
 42018-05-03T17:19:32Z Using BerkeleyDB version Berkeley DB 4.8.30: (April  9, 2010)
 52018-05-03T17:19:32Z Using wallet wallet.dat
 62018-05-03T17:19:32Z BerkeleyEnvironment::Open: LogDir=/home/tim/.bitcoin/database ErrorFile=/home/tim/.bitcoin/db.log
 72018-05-03T17:19:32Z scheduler thread start
 82018-05-03T17:19:32Z BerkeleyEnvironment::Open: Error -30974 opening database environment: DB_RUNRECOVERY: Fatal error, run database recovery
 92018-05-03T17:19:32Z Moved old /home/tim/.bitcoin/database to /home/tim/.bitcoin/database.1525367972.bak. Retrying.
102018-05-03T17:19:32Z BerkeleyEnvironment::Open: LogDir=/home/tim/.bitcoin/database ErrorFile=/home/tim/.bitcoin/db.log
112018-05-03T17:19:32Z Cache configuration:
122018-05-03T17:19:32Z * Using 2.0MiB for block index database
132018-05-03T17:19:32Z * Using 8.0MiB for chain state database
142018-05-03T17:19:32Z * Using 440.0MiB for in-memory UTXO set (plus up to 286.1MiB of unused mempool space)
152018-05-03T17:19:32Z init message: Loading block index..
16[...]