2019-12-20 07:24:38 +00:00
|
|
|
"""
|
|
|
|
Onionr - Private P2P Communication.
|
2019-07-10 22:38:20 +00:00
|
|
|
|
2019-12-20 07:24:38 +00:00
|
|
|
pick online peers in a communicator instance
|
|
|
|
"""
|
|
|
|
import secrets
|
2020-07-26 03:28:32 +00:00
|
|
|
from typing import TYPE_CHECKING
|
2019-12-20 07:24:38 +00:00
|
|
|
|
|
|
|
import onionrexceptions
|
2020-07-26 03:28:32 +00:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from deadsimplekv import DeadSimpleKV
|
2019-12-20 07:24:38 +00:00
|
|
|
"""
|
2019-07-10 22:38:20 +00:00
|
|
|
This program 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.
|
|
|
|
|
|
|
|
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
|
2019-12-20 07:24:38 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2020-08-08 17:38:14 +00:00
|
|
|
def pick_online_peer(kv: 'DeadSimpleKV'):
|
2019-12-20 07:24:38 +00:00
|
|
|
"""Randomly picks peer from pool without bias (using secrets module)."""
|
2019-08-07 22:46:57 +00:00
|
|
|
ret_data = ''
|
2020-07-26 03:28:32 +00:00
|
|
|
peer_length = len(kv.get('onlinePeers'))
|
2019-12-20 07:24:38 +00:00
|
|
|
if peer_length <= 0:
|
|
|
|
raise onionrexceptions.OnlinePeerNeeded
|
|
|
|
|
2019-07-10 22:38:20 +00:00
|
|
|
while True:
|
2020-07-26 03:28:32 +00:00
|
|
|
peer_length = len(kv.get('onlinePeers'))
|
2019-12-20 07:24:38 +00:00
|
|
|
|
2019-07-10 22:38:20 +00:00
|
|
|
try:
|
2019-12-20 07:24:38 +00:00
|
|
|
# Get a random online peer, securely.
|
2019-12-20 08:34:52 +00:00
|
|
|
# May get stuck in loop if network is lost
|
2020-07-26 03:28:32 +00:00
|
|
|
ret_data = kv.get('onlinePeers')[secrets.randbelow(peer_length)]
|
2019-07-10 22:38:20 +00:00
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
break
|
2019-12-20 08:34:52 +00:00
|
|
|
return ret_data
|