forked from b-harvest/terra_oracle_voter_deprecated
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterra_oracle_vote.py
executable file
·788 lines (664 loc) · 27 KB
/
terra_oracle_vote.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
"""
Autovoting script for Terra oracle by B-Harvest
https://github.com/b-harvest/terra_oracle_voter
WARNING : this script is for terra blockchain with version v0.3.0+ only
"""
import hashlib
import json
import logging
import multiprocessing
import concurrent.futures
import os
import subprocess
import time
# External libraries - installation required.
# Most Linux distributions have packaged python-requests.
import requests
# User setup
# Slack webhook
slackurl = os.getenv("SLACK_URL", "")
telegram_token = os.getenv("TELEGRAM_TOKEN", "")
telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID", "")
# https://fcsapi.com
fcsapi_key = os.getenv("FCSAPI_KEY", "")
# https://www.alphavantage.co/
alphavantage_key = os.getenv("ALPHAVANTAGE_KEY", "")
# stop oracle when price change exceeds stop_oracle_trigger
stop_oracle_trigger_recent_diverge = float(os.getenv("STOP_ORACLE_RECENT_DIVERGENCE", "999999999999"))
# stop oracle when price change exceeds stop_oracle_trigger
stop_oracle_trigger_exchange_diverge = float(os.getenv("STOP_ORACLE_EXCHANGE_DIVERGENCE", "0.1"))
# vote negative price when bid-ask price is wider than bid_ask_spread_max
bid_ask_spread_max = float(os.getenv("BID_ASK_SPREAD_MAX", "0.05"))
# oracle feeder address
feeder = os.getenv("FEEDER_ADDRESS", "")
# validator address
validator = os.getenv("VALIDATOR_ADDRESS", "")
key_name = os.getenv("KEY_NAME", "")
key_password = os.getenv("KEY_PASSWORD", "").encode()
fee_denom = os.getenv("FEE_DENOM", "ukrw")
fee_gas = os.getenv("FEE_GAS", "200000")
fee_amount = os.getenv("FEE_AMOUNT", "4000")
home_cli = os.getenv("HOME_CLI", "/home/ubuntu/.terracli")
# node to broadcast the txs
node = os.getenv("NODE_RPC", "tcp://127.0.0.1:26657")
# path to terracli binary
terracli = os.getenv("TERRACLI_BIN", "sudo /home/ubuntu/go/bin/terracli")
# lcd to receive swap price information
lcd_address = os.getenv("TERRA_LCD", "https://lcd.terra.dev/")
# default coinone weight
coinone_share_default = float(os.getenv("COINONE_SHARE_DEFAULT", "1.0"))
# default gopax weight
gopax_share_default = float(os.getenv("GOPAX_SHARE_DEFAULT", "0"))
# default gdac weight
gdac_share_default = float(os.getenv("GDAC_SHARE_DEFAULT", "0"))
price_divergence_alert = os.getenv("PRICE_ALERTS", "false") == "true"
vwma_period = int(os.getenv("VWMA_PERIOD", str(3 * 60))) # in seconds
misses = int(os.getenv("MISSES", "0"))
alertmisses = os.getenv("MISS_ALERTS", "true") == "true"
debug = os.getenv("DEBUG", "false") == "true"
# parameters
fx_map = {
"uusd": "USDUSD",
"ukrw": "USDKRW",
"usdr": "USDSDR",
"umnt": "USDMNT"
}
active_candidate = [
"uusd",
"ukrw",
"usdr",
"umnt"
]
# hardfix the active set. does not care about stop_oracle_trigger_recent_diverge
hardfix_active_set = [
"uusd",
"ukrw",
"usdr",
"umnt"
]
chain_id = os.getenv("CHAIN_ID", "soju-0012")
round_block_num = 5.0
# set last update time
last_height = 0
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
logger = logging.root
# By default, python-requests does not use a timeout. We need to specify
# a timeout on each call to ensure we never get stuck in network IO.
http_timeout = 2
# Separate timeout for alerting calls
alert_http_timeout = 2
# Global requests session for HTTP/1.1 keepalive
# (unfortunately, the timeout cannot be set globally)
session = requests.session()
# Be friendly to the APIs we use and specify a user-agent
session.headers['User-Agent'] = "bharvest-oracle-voter/0 (+https://github.com/b-harvest/terra_oracle_voter)"
def telegram(message):
if not telegram_token:
return
try:
requests.post(
"https://api.telegram.org/bot/{}/sendMessage".format(telegram_token),
json={
'chat_id': telegram_chat_id,
'text': message
},
timeout=alert_http_timeout
)
except:
logging.exception("Error while sending telegram alert")
def slack(message):
if not slackurl:
return
try:
requests.post(slackurl, json={"text": message}, timeout=alert_http_timeout)
except:
logging.exception("Error while sending Slack alert")
def get_current_misses():
try:
result = session.get(
"{}/oracle/voters/{}/miss".format(lcd_address, validator),
timeout=http_timeout).json()
misses = int(result["result"])
height = int(result["height"])
return misses, height
except:
logging.exception("Error in get_current_misses")
return 0, 0
def get_current_prevotes(denom):
try:
return session.get(
"{}/oracle/denoms/{}/prevotes".format(lcd_address, denom),
timeout=http_timeout).json()
except:
logging.exception("Error in get_current_prevotes")
return False
def get_current_votes(denom):
try:
result = session.get(
"{}/oracle/denoms/{}/votes".format(lcd_address, denom),
timeout=http_timeout).json()
return result
except:
logging.exception("Error in get_current_votes")
return False
def get_my_current_prevotes():
try:
result = session.get(
"{}/oracle/voters/{}/prevotes".format(lcd_address, validator),
timeout=http_timeout).json()
result_vote = []
for vote in result["result"]:
if str(vote["voter"]) == str(validator):
result_vote.append(vote)
return result_vote
except:
logging.exception("Error in get_my_current_prevotes")
return False
# get latest block info
def get_latest_block():
err_flag = False
try:
result = session.get("{}/blocks/latest".format(lcd_address), timeout=http_timeout).json()
latest_block_height = int(result["block_meta"]["header"]["height"])
latest_block_time = result["block_meta"]["header"]["time"]
except:
logger.exception("Error in get_latest_block")
err_flag = True
latest_block_height = None
latest_block_time = None
return err_flag, latest_block_height, latest_block_time
# get real fx rates
def get_fx_rate():
err_flag = False
try:
# get currency rate
api_result = session.get(
"https://fcsapi.com/api/forex/latest",
timeout=http_timeout,
params={
'symbol': 'USD/KRW,USD/EUR,USD/CNY,USD/JPY',
'access_key': fcsapi_key
}
).json()
result_real_fx = {
"USDUSD": 1.0,
"USDKRW": 1.0,
"USDEUR": 1.0,
"USDCNY": 1.0,
"USDJPY": 1.0,
"USDSDR": 1.0,
"USDMNT": 1.0
}
for currency in api_result["response"]:
result_real_fx["USD" + str(currency["symbol"][-3:])] = float(currency["price"].replace(',', ''))
mnt_api_result = session.get(
"https://www.alphavantage.co/query",
timeout=http_timeout,
params={
'function': 'CURRENCY_EXCHANGE_RATE',
'from_currency': 'USD',
'to_currency': 'MNT',
'apikey': alphavantage_key
}
).json()
result_real_fx["USDMNT"] = float(
mnt_api_result["Realtime Currency Exchange Rate"]["5. Exchange Rate"])
except:
logger.exception("Error in get_fx_rate")
err_flag = True
result_real_fx = None
return err_flag, result_real_fx
# get real sdr rates
def get_sdr_rate():
err_flag = False
try:
# get sdr
url = "https://www.imf.org/external/np/fin/data/rms_five.aspx?tsvflag=Y"
data = session.get(url, timeout=http_timeout).text
result_sdr_rate = next(filter(lambda x: x.startswith("U.S. dollar"),
data.splitlines())).split('\t')[2]
except:
logging.exception("Error in get_sdr_rate")
err_flag = True
result_sdr_rate = None
return err_flag, result_sdr_rate
# get coinone luna krw price
def get_coinone_luna_price():
err_flag = False
try:
if vwma_period > 1:
url = "https://api.coinone.co.kr/trades/?currency=luna"
luna_result = session.get(url, timeout=http_timeout).json()["completeOrders"]
hist_price = []
sum_price_volume = 0
sum_volume = 0
now_time = float(time.time())
for row in luna_result:
if now_time - float(row['timestamp']) < vwma_period:
sum_price_volume += float(row["price"]) * float(row["qty"])
sum_volume += float(row["qty"])
else:
break
askprice = sum_price_volume / sum_volume
bidprice = sum_price_volume / sum_volume
else:
url = "https://api.coinone.co.kr/orderbook/?currency=luna&format=json"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0]["price"])
bidprice = float(luna_result["bid"][0]["price"])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "coinone",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
logger.exception("Error in get_coinone_luna_price")
err_flag = True
luna_price = None
luna_base = None
luna_midprice_krw = None
return err_flag, luna_price, luna_base, luna_midprice_krw
# get gopax luna krw price
def get_gopax_luna_price():
err_flag = False
try:
# get luna/krw
url = "https://api.gopax.co.kr/trading-pairs/LUNA-KRW/book"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0][1])
bidprice = float(luna_result["bid"][0][1])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "gopax",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
logger.exception("Error in get_gopax_luna_price")
err_flag = True
# gopax_share is set to zero if an error occurs
luna_price = 0
luna_base = 0
luna_midprice_krw = 0
return err_flag, luna_price, luna_base, luna_midprice_krw
# get gdac luna krw price
def get_gdac_luna_price():
err_flag = False
try:
# get luna/krw
url = "https://partner.gdac.com/v0.4/public/orderbook?pair=LUNA%2FKRW"
luna_result = session.get(url, timeout=http_timeout).json()
askprice = float(luna_result["ask"][0]["price"])
bidprice = float(luna_result["bid"][0]["price"])
midprice = (askprice + bidprice) / 2.0
luna_price = {
"base_currency": "ukrw",
"exchange": "gdac",
"askprice": askprice,
"bidprice": bidprice,
"midprice": midprice
}
luna_base = "USDKRW"
luna_midprice_krw = float(luna_price["midprice"])
except:
logger.exception("Error in get_gdac_luna_price")
err_flag = True
# gdac_share is set to zero if an error occurs
luna_price = 0
luna_base = 0
luna_midprice_krw = 0
return err_flag, luna_price, luna_base, luna_midprice_krw
# get swap price
def get_swap_price():
err_flag = False
try:
result = session.get(
"{}/oracle/denoms/exchange_rates".format(lcd_address),
timeout=http_timeout).json()
except:
logger.exception("Error in get_swap_price")
result = []
err_flag = True
return err_flag, result
def get_hash(salt, price, denom, validator):
m = hashlib.sha256()
m.update("{}:{}:{}:{}".format(salt, price, denom, validator).encode('utf-8'))
result = m.hexdigest()[:40]
return result
def get_salt(string):
b_string = str(string).encode('utf-8')
return str(hashlib.sha256(b_string).hexdigest())[:4]
def broadcast_messages(messages):
tx_json = {
"type": "core/StdTx",
"value": {
"msg": messages,
"fee": {
"amount": [
{
"denom": fee_denom,
"amount": fee_amount
}
],
"gas": fee_gas
},
"signatures": [],
"memo": ""
}
}
logger.info("Signing...")
json.dump(tx_json, open("tx_oracle_prevote.json", 'w'))
cmd_output = subprocess.check_output([
terracli,
"tx", "sign", "tx_oracle_prevote.json",
"--from", key_name,
"--chain-id", chain_id,
"--home", home_cli,
"--node", node
], input=key_password + b'\n').decode()
tx_json_signed = json.loads(cmd_output)
json.dump(tx_json_signed, open("tx_oracle_prevote_signed.json", 'w'))
logger.info("Broadcasting...")
cmd_output = subprocess.check_output([
terracli,
"tx", "broadcast", "tx_oracle_prevote_signed.json",
"--output", "json",
"--from", key_name,
"--chain-id", chain_id,
"--home", home_cli,
"--node", node,
], input=key_password + b'\n').decode()
return json.loads(cmd_output)
def broadcast_prevote(hash):
logger.info("Prevoting...")
return broadcast_messages([
{
"type": "oracle/MsgExchangeRatePrevote",
"value": {
"hash": str(hash[denom]),
"denom": str(denom),
"feeder": feeder,
"validator": validator
}
} for denom in active
])
def broadcast_all(vote_price, vote_salt, prevote_hash):
logger.info("Prevoting and voting...")
return broadcast_messages(
[
{
"type": "oracle/MsgExchangeRateVote",
"value": {
"exchange_rate": str(vote_price[denom]),
"salt": str(vote_salt[denom]),
"denom": denom,
"feeder": feeder,
"validator": validator
}
} for denom in active
] + [
{
"type": "oracle/MsgExchangeRatePrevote",
"value": {
"hash": str(prevote_hash[denom]),
"denom": str(denom),
"feeder": feeder,
"validator": validator
}
} for denom in active
])
main_err_flag = True
while main_err_flag:
latest_block_err_flag, latest_block_height, latest_block_time = get_latest_block()
if latest_block_err_flag == False:
height = latest_block_height
if height > last_height:
main_err_flag = False
last_height = height
time.sleep(0.5)
last_prevoted_round = 0
last_active = []
last_hash = []
while True:
main_err_flag = True
while main_err_flag:
latest_block_err_flag, latest_block_height, latest_block_time = get_latest_block()
if latest_block_err_flag == False:
height = latest_block_height
if height > last_height:
main_err_flag = False
last_height = height
time.sleep(0.5)
current_round = int(float(height - 1) / round_block_num)
next_height_round = int(float(height) / round_block_num)
num_blocks_till_next_round = (current_round + 1) * round_block_num - height
logger.debug("current_round: %d", current_round)
logger.debug("next_height_round: %d", next_height_round)
logger.debug("last_prevoted_round: %d", last_prevoted_round)
logger.debug("height: %d", height)
logger.debug("num_blocks_till_next_round: %d", num_blocks_till_next_round)
if next_height_round > last_prevoted_round and (
num_blocks_till_next_round == 0 or num_blocks_till_next_round > 3):
# Get external data
all_err_flag = False
ts = time.time()
with concurrent.futures.ThreadPoolExecutor() as executor:
res_swap = executor.submit(get_swap_price)
res_fx = executor.submit(get_fx_rate)
res_sdr = executor.submit(get_sdr_rate)
res_coinone = executor.submit(get_coinone_luna_price)
res_gopax = executor.submit(get_gopax_luna_price)
res_gdac = executor.submit(get_gdac_luna_price)
# Get active set of denoms
swap_price_err_flag, swap_price = res_swap.result()
if swap_price["result"] is None:
swap_price["result"] = []
if len(hardfix_active_set) == 0:
active = []
for denom in swap_price["result"]:
active.append(denom["denom"])
else:
active = hardfix_active_set
logger.info("Active set: {}".format(active))
fx_err_flag, real_fx = res_fx.result()
sdr_err_flag, sdr_rate = res_sdr.result()
coinone_err_flag, coinone_luna_price, coinone_luna_base, coinone_luna_midprice_krw = res_coinone.result()
gopax_err_flag, gopax_luna_price, gopax_luna_base, gopax_luna_midprice_krw = res_gopax.result()
gdac_err_flag, gdac_luna_price, gdac_luna_base, gdac_luna_midprice_krw = res_gdac.result()
coinone_share = coinone_share_default
gopax_share = gopax_share_default
gdac_share = gdac_share_default
if fx_err_flag or sdr_err_flag or coinone_err_flag or swap_price_err_flag:
all_err_flag = True
if gopax_err_flag:
gopax_share = 0
if gdac_err_flag:
gdac_share = 0
if not all_err_flag:
real_fx["USDSDR"] = float(sdr_rate)
# ignore gopax if it diverge from coinone price or its bid-ask price is wider than bid_ask_spread_max
if gopax_share > 0:
if abs(1.0 - float(gopax_luna_midprice_krw) / float(
coinone_luna_midprice_krw)) > stop_oracle_trigger_exchange_diverge or float(
gopax_luna_price["askprice"]) / float(
gopax_luna_price["bidprice"]) - 1 > bid_ask_spread_max:
gopax_share = 0
if price_divergence_alert:
alarm_content = denom + " market price diversion at height " + str(
height) + "! coinone_price:" + str(
"{0:.1f}".format(coinone_luna_midprice_krw)) + ", gopax_price:" + str(
"{0:.1f}".format(gopax_luna_midprice_krw))
alarm_content += "(percent_diff:" + str("{0:.4f}".format(
(coinone_luna_midprice_krw / gopax_luna_midprice_krw - 1.0) * 100.0)) + "%)"
logger.error(alarm_content)
telegram(alarm_content)
slack(alarm_content)
# ignore gdac if it diverge from coinone price or its bid-ask price is wider than bid_ask_spread_max
if gdac_share > 0:
if abs(1.0 - float(gdac_luna_midprice_krw) / float(
coinone_luna_midprice_krw)) > stop_oracle_trigger_exchange_diverge or float(
gdac_luna_price["askprice"]) / float(
gdac_luna_price["bidprice"]) - 1 > bid_ask_spread_max:
gdac_share = 0
if price_divergence_alert:
alarm_content = denom + " market price diversion at height " + str(
height) + "! coinone_price:" + str(
"{0:.1f}".format(coinone_luna_midprice_krw)) + ", gdac_price:" + str(
"{0:.1f}".format(gdac_luna_midprice_krw))
alarm_content += "(percent_diff:" + str("{0:.4f}".format(
(coinone_luna_midprice_krw / gdac_luna_midprice_krw - 1.0) * 100.0)) + "%)"
logger.error(alarm_content)
telegram(alarm_content)
slack(alarm_content)
# vote negative price if coinone bid-ask spread is wider than "bid_ask_spread_max"
if float(coinone_luna_price["askprice"]) / float(
coinone_luna_price["bidprice"]) - 1 > bid_ask_spread_max:
all_err_flag = True
if not all_err_flag:
# Weighted average
luna_midprice_krw = (
(float(coinone_luna_midprice_krw) * coinone_share +
float(gopax_luna_midprice_krw) * gopax_share +
float(gdac_luna_midprice_krw) * gdac_share
) / (coinone_share + gopax_share + gdac_share)
)
luna_base = coinone_luna_base
# reorganize data
try:
# get swap price / market price
swap_price_compare = []
for currency in active:
market_price = float(luna_midprice_krw * (real_fx[fx_map[currency]] / real_fx[luna_base]))
this_swap_price = 0.00000001
for denom in swap_price["result"]:
if denom["denom"] == currency:
this_swap_price = float(denom["amount"])
break
swap_price_compare.append(
{"market": currency, "swap_price": this_swap_price, "market_price": market_price})
result = {
"index": int(ts / 60),
"timestamp": ts,
"block_height": latest_block_height,
"block_time": latest_block_time,
"swap_price_compare": swap_price_compare,
"real_fx": real_fx,
"luna_price_list": [coinone_luna_price, gopax_luna_price]
}
except:
# TODO: how can this fail?
logger.exception("Reorganize data error")
all_err_flag = True
this_price = {}
this_hash = {}
this_salt = {}
for denom in active:
this_price.update({denom: 0.0})
this_hash.update({denom: ""})
this_salt.update({denom: ""})
if not all_err_flag:
# prevote for current round
for denom in active:
for prices in result["swap_price_compare"]:
if prices["market"] == denom:
this_denom_err_flag = False
if abs(prices["market_price"] / prices[
"swap_price"] - 1.0) <= stop_oracle_trigger_recent_diverge:
logger.info("Prevoting " + denom + " : " + str(
prices["market_price"]) + "(percent_change:" + str("{0:.4f}".format(
(prices["market_price"] / prices["swap_price"] - 1.0) * 100.0)) + "%)")
else:
alarm_content = denom + " price diversion at height " + str(
height) + "! market_price:" + str(
"{0:.4f}".format(prices["market_price"])) + ", swap_price:" + str(
"{0:.4f}".format(prices["swap_price"]))
alarm_content += "(percent_change:" + str("{0:.4f}".format(
(prices["market_price"] / prices["swap_price"] - 1.0) * 100.0)) + "%)"
logger.info(alarm_content)
telegram(alarm_content)
slack(alarm_content)
this_denom_err_flag = True
this_salt[denom] = get_salt(str(time.time()))
if this_denom_err_flag == False: # vote negative when this_denom_err_flag == True
this_price[denom] = str("{0:.18f}".format(float(prices["market_price"])))
else:
this_price[denom] = str("{0:.18f}".format(float(-1)))
this_hash[denom] = get_hash(this_salt[denom], this_price[denom], denom, validator)
break
if all_err_flag: # vote negative when all_err_flag == True
for denom in active:
this_price[denom] = str("{0:.18f}".format(float(-1)))
this_salt[denom] = get_salt(str(time.time()))
this_hash[denom] = get_hash(this_salt[denom], this_price[denom], denom, validator)
logger.info("Start voting on height " + str(height + 1))
# check hash match
my_current_prevotes = get_my_current_prevotes()
if not last_hash:
hash_match_flag = False
else:
hash_match_flag = True
for vote_hash in last_hash:
this_hash_exist = False
for prevote in my_current_prevotes:
if str(prevote["hash"]) == vote_hash:
this_hash_exist = True
break
if not this_hash_exist:
hash_match_flag = False
break
if hash_match_flag: # if all hashes exist
# broadcast vote/prevote at the same time!
logger.info("Broadcast votes/prevotes at the same time...")
broadcast_all(last_price, last_salt, this_hash)
else:
logger.info("Broadcast prevotes only...")
broadcast_prevote(this_hash)
# update last_prevoted_round
last_prevoted_round = next_height_round
last_price = {}
last_salt = {}
last_hash = []
last_active = []
for denom in active:
last_price.update({denom: 0.0})
last_salt.update({denom: ""})
for denom in active:
last_price[denom] = this_price[denom]
last_salt[denom] = this_salt[denom]
last_active.append(denom)
last_hash.append(this_hash[denom])
last_swap_price = []
for item in swap_price:
last_swap_price.append(item)
# Get last amount of misses, if this increased message telegram
currentmisses, currentheight = get_current_misses()
if currentheight > 0:
misspercentage = round(float(currentmisses) / float(currentheight) * 100, 2)
logger.info("Current miss percentage: {}%".format(misspercentage))
if misses == 0:
misses = currentmisses
if currentmisses > misses:
# we have new misses, alert telegram
alarm_content = "Terra Oracle misses went from {} to {} ({}%)".format(
misses, currentmisses, misspercentage)
logger.error(alarm_content)
if alertmisses:
telegram(alarm_content)
slack(alarm_content)
misses = currentmisses
else:
logger.info("{height}: wait {num_blocks} blocks until this round ends...".format(
height=height,
num_blocks=num_blocks_till_next_round))
time.sleep(1)