This repository has been archived by the owner on Apr 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
clock.py
41 lines (35 loc) · 1.55 KB
/
clock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from apscheduler.schedulers.blocking import BlockingScheduler
from rq import Queue
from api import redis_db as conn
from api.blockchain import storeLatestBlockInDB, getBlockCount, blockchain_db, storeBlockInDB, checkSeeds, get_highest_node
q = Queue(connection=conn)
sched = BlockingScheduler()
#check for the latest block every 5 seconds
@sched.scheduled_job('interval', seconds=10, max_instances=3)
def pollNode():
q.enqueue(storeLatestBlockInDB)
# check for the latest block every 5 seconds
@sched.scheduled_job('interval', seconds=30)
def pollNode():
q.enqueue(checkSeeds)
# intermittantly check for any blocks we missed by polling
@sched.scheduled_job('interval', seconds=30, max_instances=3)
def syncBlockchain():
nodeAPI = get_highest_node()
currBlock = getBlockCount(nodeAPI)["result"]
lastTrustedBlock = blockchain_db["meta"].find_one({"name":"lastTrustedBlock"})["value"]
laterBlocks = set([block["index"] for block in blockchain_db["blockchain"].find({"index": {"$gt": lastTrustedBlock}})])
hash_set = {x:x for x in laterBlocks}
newLastTrusted = lastTrustedBlock
stopTrust = False
for i in range(lastTrustedBlock+1, currBlock):
if not i in hash_set:
print("repairing {}".format(i))
q.enqueue(storeBlockInDB, i, nodeAPI)
stopTrust = True
if not stopTrust:
newLastTrusted = i
print("newLastTrusted", newLastTrusted)
blockchain_db['meta'].update_one({"name":"lastTrustedBlock"}, {"$set": {"value": newLastTrusted}}, upsert=True)
print("done")
sched.start()