2017-10-19 08:52:44 +02:00
|
|
|
import os
|
2018-05-03 12:05:49 +02:00
|
|
|
import pickle
|
2017-02-08 13:41:56 +01:00
|
|
|
import threading
|
|
|
|
|
2017-02-09 11:53:33 +01:00
|
|
|
import state
|
2018-05-03 12:05:49 +02:00
|
|
|
from bmconfigparser import BMConfigParser
|
2017-02-09 11:53:33 +01:00
|
|
|
|
2017-02-08 13:41:56 +01:00
|
|
|
knownNodesLock = threading.Lock()
|
|
|
|
knownNodes = {}
|
|
|
|
|
2017-02-27 23:31:12 +01:00
|
|
|
knownNodesTrimAmount = 2000
|
|
|
|
|
2017-10-19 08:52:44 +02:00
|
|
|
# forget a node after rating is this low
|
|
|
|
knownNodesForgetRating = -0.5
|
|
|
|
|
2018-05-03 12:05:49 +02:00
|
|
|
|
|
|
|
def saveKnownNodes(dirName=None):
|
2017-02-09 11:53:33 +01:00
|
|
|
if dirName is None:
|
|
|
|
dirName = state.appdata
|
|
|
|
with knownNodesLock:
|
2017-10-19 08:52:44 +02:00
|
|
|
with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output:
|
2017-02-09 11:53:33 +01:00
|
|
|
pickle.dump(knownNodes, output)
|
2017-02-27 23:31:12 +01:00
|
|
|
|
2018-05-03 12:05:49 +02:00
|
|
|
|
2017-07-05 09:17:01 +02:00
|
|
|
def increaseRating(peer):
|
|
|
|
increaseAmount = 0.1
|
|
|
|
maxRating = 1
|
|
|
|
with knownNodesLock:
|
|
|
|
for stream in knownNodes.keys():
|
|
|
|
try:
|
2018-05-03 12:05:49 +02:00
|
|
|
knownNodes[stream][peer]["rating"] = min(
|
|
|
|
knownNodes[stream][peer]["rating"] + increaseAmount,
|
|
|
|
maxRating
|
|
|
|
)
|
2017-07-05 09:17:01 +02:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
2018-05-03 12:05:49 +02:00
|
|
|
|
2017-07-05 09:17:01 +02:00
|
|
|
def decreaseRating(peer):
|
|
|
|
decreaseAmount = 0.1
|
|
|
|
minRating = -1
|
|
|
|
with knownNodesLock:
|
|
|
|
for stream in knownNodes.keys():
|
|
|
|
try:
|
2018-05-03 12:05:49 +02:00
|
|
|
knownNodes[stream][peer]["rating"] = max(
|
|
|
|
knownNodes[stream][peer]["rating"] - decreaseAmount,
|
|
|
|
minRating
|
|
|
|
)
|
2017-07-05 09:17:01 +02:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
2018-05-03 12:05:49 +02:00
|
|
|
|
|
|
|
def trimKnownNodes(recAddrStream=1):
|
|
|
|
if len(knownNodes[recAddrStream]) < \
|
|
|
|
BMConfigParser().safeGetInt("knownnodes", "maxnodes"):
|
2017-02-27 23:31:12 +01:00
|
|
|
return
|
|
|
|
with knownNodesLock:
|
2018-05-03 12:05:49 +02:00
|
|
|
oldestList = sorted(
|
|
|
|
knownNodes[recAddrStream],
|
|
|
|
key=lambda x: x['lastseen']
|
|
|
|
)[:knownNodesTrimAmount]
|
2017-02-27 23:31:12 +01:00
|
|
|
for oldest in oldestList:
|
|
|
|
del knownNodes[recAddrStream][oldest]
|