[electrum] always close the socket object in is_tor_port
Summary:
Previously the socket object could be left unclosed if something in the try:... except:... block failed before reaching the s.close() line.
In theory this should not cause any issue, as the documentation of the socket library states that:
Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them.
But it resulted in worrying warnings being logged.
electrum/electrumabc_plugins/fusion/plugin.py:426: ResourceWarning: unclosed <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 60508)> if is_tor_port(host, port): ResourceWarning: Enable tracemalloc to get the object allocation traceback
Also move code lines that are never expected to error out of the try: except: scope, and use hasattr to detect the socket monkeypatching.
Test Plan:
Run the unit tests and check that there is no warning being logged about unclosed sockets. Locally I could not reproduce the warning, but on CI is seemed to happen every time.
Run the application and verify that CashFusion still works.
Reviewers: #bitcoin_abc, Fabien
Reviewed By: #bitcoin_abc, Fabien
Differential Revision: https://reviews.bitcoinabc.org/D14287