Credit to @luke-jr for helping uncovering this bug https://github.com/bitcoin-core/gui/pull/379#discussion_r680408927

This bug has no user-visible effects currently, but combined with PR [bitcoin-core/gui#379](https://github.com/bitcoin-core/gui/pull/379) and a corrupt `settings.json` file that is corrupted specifically by specifying the same JSON keys multiple times, it can cause some dialog text added in that PR to be misleading. This is a basically an impossible-to-hit rube goldberg bug, but is only fixable at the util level not the GUI level, so I'm tracking this outside the GUI repository.

Simplest fix would be to just change `ReadSettingsFile` to call `rw_settings.clear()` on error. It would also be nice to add a unit test for the regression.

Code path that triggers this is:

https://github.com/bitcoin/bitcoin/blob/d67330d11245b11fbdd5e2dd5343ee451186931e/src/util/system.cpp#L548
https://github.com/bitcoin/bitcoin/blob/d67330d11245b11fbdd5e2dd5343ee451186931e/src/util/settings.cpp#L89
https://github.com/bitcoin/bitcoin/blob/d67330d11245b11fbdd5e2dd5343ee451186931e/src/util/settings.cpp#L92
desc += s.write();
        }
        desc += " |";
        if (OnlyHasDefaultSectionSetting(settings, network, name)) desc += " ignored";
        desc += "\n";
        out_sha.Write(MakeUCharSpan(desc));
        if (out_file) {
            BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size());
        }
    });
    if (out_file) {
        if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed");
        out_file = nullptr;
    }
    unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE];
    out_sha.Finalize(out_sha_bytes);
    std::string out_sha_hex = HexStr(out_sha_bytes);
    
    
    
    
    
    
    
    
    
    BOOST_CHECK_EQUAL(out_sha_hex, "79db02d74e3e193196541b67c068b40ebd0c124a24b3ecbe9cbf7e85b1c4ba7a");
}
BOOST_AUTO_TEST_SUITE_END()