-
Notifications
You must be signed in to change notification settings - Fork 4
/
sent.py
1835 lines (1537 loc) · 72 KB
/
sent.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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import flask
import string
import time
import oxenc
import sqlite3
import re
import nacl.hash
import nacl.bindings as sodium
import eth_utils
import subprocess
import config
import datetime
from itertools import chain
from eth_typing import ChecksumAddress
from typing import TypedDict, Callable, Any, Union
from functools import partial
from werkzeug.routing import BaseConverter
from nacl.signing import VerifyKey
from omq import FutureJSON, omq_connection
from timer import timer
from contracts.reward_rate_pool import RewardRatePoolInterface
from contracts.service_node_contribution import ContributorContractInterface
from contracts.service_node_contribution_factory import ServiceNodeContributionFactory
from contracts.service_node_rewards import ServiceNodeRewardsInterface, ServiceNodeRewardsRecipient
TOKEN_NAME = "SENT"
class WalletInfo():
def __init__(self):
self.rewards = 0 # Atomic SENT
self.contract_rewards = 0
self.contract_claimed = 0
def oxen_rpc_get_accrued_rewards(omq, oxend) -> FutureJSON:
result = FutureJSON(omq, oxend, 'rpc.get_accrued_rewards', args={'addresses': []})
return result
def oxen_rpc_bls_rewards_request(omq, oxend, eth_address: str) -> FutureJSON:
eth_address_for_rpc = eth_address.lower()
if eth_address_for_rpc.startswith("0x"):
eth_address_for_rpc = eth_address_for_rpc[2:]
result = FutureJSON(omq, oxend, 'rpc.bls_rewards_request', args={'address': eth_address_for_rpc})
return result
def oxen_rpc_bls_exit_liquidation(omq, oxend, ed25519_pubkey: bytes, liquidate: bool) -> FutureJSON:
return FutureJSON(omq, oxend, 'rpc.bls_exit_liquidation_request', args={'pubkey': ed25519_pubkey.hex(), 'liquidate': liquidate})
def get_oxen_rpc_bls_exit_liquidation_list(omq, oxend):
return FutureJSON(omq, oxend, 'rpc.bls_exit_liquidation_list')
class App(flask.Flask):
def __init__(self):
super().__init__(__name__)
self.logger.setLevel(config.backend.log_level)
self.service_node_rewards = ServiceNodeRewardsInterface(config.backend.provider_url, config.backend.sn_rewards_addr)
self.reward_rate_pool = RewardRatePoolInterface(config.backend.provider_url, config.backend.reward_rate_pool_addr)
self.service_node_contribution_factory = ServiceNodeContributionFactory(config.backend.provider_url, config.backend.sn_contrib_factory_addr)
self.service_node_contribution = ContributorContractInterface(config.backend.provider_url)
self.bls_pubkey_to_contract_id_map: dict[str, int] = {} # (BLS public key -> contract_id)
self.wallet_to_sn_map: dict[ChecksumAddress, set[int]] = {} # (0x wallet address -> Set of contract_id's of stakes they are contributors to)
self.contract_id_to_sn_map: dict[int, dict] = {} # (contract_id -> Oxen RPC get_service_nodes result (augmented w/ extra metadata like SN contract ID))
self.wallet_to_exitable_sn_map: dict[ChecksumAddress, set[int]] = {} # (0x wallet address -> Set of contract_id's of SN's they can liquidate/exit)
self.contract_id_to_exitable_sn_map: dict[int, dict] = {} # (contract_id -> SNInfo)
self.tmp_db_trigger_wallet_addresses: set[ChecksumAddress] = set() # Wallet addresses that have triggered a db get between scheduled times
self.tracked_wallet_addresses: set[ChecksumAddress] = set() # Tracked wallet addresses to fetch data from the db for
self.wallet_to_historical_stakes_map: dict[ChecksumAddress, set[int]] = {} # (0x wallet address -> Set of contract_ids)
self.contract_id_to_historical_stakes_map: dict[int, Stake] = {} # (contract_id -> Stake Info)
self.contributors = {}
self.contracts = {}
self.wallet_map = {} # (Binary ETH wallet address -> WalletInfo)
git_rev = subprocess.run(["git", "rev-parse", "--short=9", "HEAD"], stdout=subprocess.PIPE, text=True)
self.git_rev = git_rev.stdout.strip() if git_rev.returncode == 0 else "(unknown)"
sql = sqlite3.connect(config.backend.sqlite_db)
cursor = sql.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA foreign_keys=ON")
cursor.execute("""
CREATE TABLE IF NOT EXISTS registrations (
id INTEGER PRIMARY KEY NOT NULL,
pubkey_ed25519 BLOB NOT NULL,
pubkey_bls BLOB NOT NULL,
sig_ed25519 BLOB NOT NULL,
sig_bls BLOB NOT NULL,
operator BLOB NOT NULL,
contract BLOB,
timestamp FLOAT NOT NULL DEFAULT ((julianday('now') - 2440587.5)*86400.0), /* unix epoch */
CHECK(length(pubkey_ed25519) == 32),
CHECK(length(pubkey_bls) == 64),
CHECK(length(sig_ed25519) == 64),
CHECK(length(sig_bls) == 128),
CHECK(length(operator) == 20),
CHECK(contract IS NULL OR length(contract) == 20)
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS registrations_operator_idx ON registrations(operator);
""")
cursor.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS registration_pk_multi_idx ON registrations(pubkey_ed25519, contract IS NULL);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS contribution_contracts (
id INTEGER PRIMARY KEY NOT NULL,
contract_address TEXT NOT NULL,
status INTEGER DEFAULT 1,
timestamp FLOAT NOT NULL DEFAULT ((julianday('now') - 2440587.5)*86400.0), /* unix epoch */
CHECK(length(contract_address) == 42) -- Assuming Ethereum addresses
);
""")
cursor.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS contribution_contract_address_idx ON contribution_contracts(contract_address);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS stakes (
id INTEGER PRIMARY KEY NOT NULL, /* Contract ID */
last_updated INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
pubkey_bls BLOB NOT NULL,
deregistration_unlock_height INTEGER,
earned_downtime_blocks INTEGER,
last_reward_block_height INTEGER,
last_uptime_proof INTEGER,
operator_address BLOB NOT NULL,
operator_fee INTEGER,
requested_unlock_height INTEGER,
service_node_pubkey BLOB NOT NULL,
state TEXT NOT NULL
CHECK(length(operator_address) == 20)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS stake_contributions (
contract_id INTEGER NOT NULL,
address BLOB NOT NULL,
amount INTEGER NOT NULL,
reserved INTEGER,
CHECK(length(address) == 20),
FOREIGN KEY (contract_id) REFERENCES stakes(id),
PRIMARY KEY (contract_id, address)
);
""")
cursor.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS idx_stake_contributions_contract_id_address ON stake_contributions(contract_id, address);
""")
cursor.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS idx_stake_contributions_contract_id_address_amount ON stake_contributions(contract_id, address, amount);
""")
cursor.close()
sql.close()
app = App()
def get_sql():
if "db" not in flask.g:
flask.g.sql = sqlite3.connect(config.backend.sqlite_db)
return flask.g.sql
def date_now_str() -> str:
result = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
return result
# Validates that input is 64 hex bytes and converts it to 32 bytes.
class Hex64Converter(BaseConverter):
def __init__(self, url_map):
super().__init__(url_map)
self.regex = "[0-9a-fA-F]{64}"
def to_python(self, value):
return bytes.fromhex(value)
def to_url(self, value):
return value.hex()
eth_regex = "0x[0-9a-fA-F]{40}"
class EthConverter(BaseConverter):
def __init__(self, url_map):
super().__init__(url_map)
self.regex = eth_regex
class OxenConverter(BaseConverter):
def __init__(self, url_map):
super().__init__(url_map)
self.regex = config.backend.oxen_wallet_regex
class OxenEthConverter(BaseConverter):
def __init__(self, url_map):
super().__init__(url_map)
self.regex = f"{eth_regex}|{config.backend.oxen_wallet_regex}"
app.url_map.converters["hex64"] = Hex64Converter
app.url_map.converters["eth_wallet"] = EthConverter
app.url_map.converters["oxen_wallet"] = OxenConverter
app.url_map.converters["either_wallet"] = OxenEthConverter
def get_sns_future(omq, oxend) -> FutureJSON:
return FutureJSON(
omq,
oxend,
"rpc.get_service_nodes",
args={
"all": False,
"fields": {
x: True
for x in (
"service_node_pubkey",
"requested_unlock_height",
"last_reward_block_height",
"active",
"pubkey_bls",
"funded",
"earned_downtime_blocks",
"service_node_version",
"contributors",
"total_contributed",
"total_reserved",
"staking_requirement",
"portions_for_operator",
"operator_address",
"pubkey_ed25519",
"last_uptime_proof",
"state_height",
"swarm_id",
"is_removable",
"is_liquidatable",
)
},
},
)
def get_sns(sns_future, info_future):
info = info_future.get()
awaiting_sns, active_sns, inactive_sns = [], [], []
sn_states = sns_future.get()
sn_states = (
sn_states["service_node_states"] if "service_node_states" in sn_states else []
)
for sn in sn_states:
sn["contribution_open"] = sn["staking_requirement"] - sn["total_reserved"]
sn["contribution_required"] = (
sn["staking_requirement"] - sn["total_contributed"]
)
sn["num_contributions"] = sum(
len(x["locked_contributions"])
for x in sn["contributors"]
if "locked_contributions" in x
)
if sn["active"]:
active_sns.append(sn)
elif sn["funded"]:
sn["decomm_blocks_remaining"] = max(sn["earned_downtime_blocks"], 0)
sn["decomm_blocks"] = info["height"] - sn["state_height"]
inactive_sns.append(sn)
else:
awaiting_sns.append(sn)
return awaiting_sns, active_sns, inactive_sns
def hexify(container):
"""
Takes a dict or list and mutates it to change any `bytes` values in it to str hex representation
of the bytes, recursively.
"""
if isinstance(container, dict):
it = container.items()
elif isinstance(container, list):
it = enumerate(container)
else:
return
for i, v in it:
if isinstance(v, bytes):
container[i] = v.hex()
else:
hexify(v)
def get_timers_hours(network_type: str):
match network_type:
case 'testnet' | 'stagenet' | 'devnet' | 'localdev' | 'fakechain':
return {
'deregistration_lock_duration_hours': 48,
'unlock_duration_hours': 24,
}
case 'mainnet':
return {
'deregistration_lock_duration_hours': 30 * 24,
'unlock_duration_hours': 15 * 24,
}
case _:
raise ValueError(f"Unknown network type {network_type}")
@app.route("/timers/<network_type>")
def fetch_network_timers(network_type: str = None):
if network_type is None:
return json_response(get_timers_hours(get_info().get('nettype')))
else:
return json_response(get_timers_hours(network_type))
# Target block time in seconds
TARGET_BLOCK_TIME = 120
def blocks_in(seconds: int):
"""
Mimics the behavior of the oxend `blocks_in` function.
"""
return int(seconds / TARGET_BLOCK_TIME)
def get_info() -> dict:
omq, oxend = omq_connection()
info: dict | None = FutureJSON(omq, oxend, "rpc.get_info").get()
blk_header_result: dict | None = FutureJSON(omq, oxend, 'rpc.get_last_block_header', args={'fill_pow_hash': False, 'get_tx_hashes': False }).get()
result: dict = {}
result['nettype'] = info['nettype']
result['hard_fork'] = info['hard_fork']
result['version'] = info['version']
result['block_hash'] = info['top_block_hash']
result['staking_requirement'] = info['staking_requirement']
result['max_stakers'] = info['max_contributors']
result['min_operator_contribution'] = info['min_operator_contribution']
blk_header = blk_header_result['block_header']
result['block_timestamp'] = blk_header['timestamp']
result['block_height'] = blk_header['height']
result['block_hash'] = blk_header['hash']
return result
def json_response(vals):
"""
Takes a dict, adds some general info fields to it, and jsonifies it for a flask route function
return value. The dict gets passed through `hexify` first to convert any bytes values to hex.
"""
hexify(vals)
return flask.jsonify({**vals, "network": get_info(), "t": time.time()})
@timer(10, target="worker1")
def fetch_contribution_contracts(signum):
app.logger.info("{} Fetch contribution contracts start".format(date_now_str()))
with app.app_context(), get_sql() as sql:
cursor = sql.cursor()
new_contracts = app.service_node_contribution_factory.get_latest_contribution_contract_events()
for event in new_contracts:
contract_address = event.args.contributorContract
cursor.execute(
"""
INSERT INTO contribution_contracts (contract_address) VALUES (?)
ON CONFLICT (contract_address) DO NOTHING
""",
(contract_address,)
)
sql.commit()
app.logger.info("{} Fetch contribution contracts finish".format(date_now_str()))
@timer(30)
def fetch_contract_statuses(signum):
app.logger.info("{} Update Contract Statuses Start".format(date_now_str()))
with app.app_context(), get_sql() as sql:
cursor = sql.cursor()
cursor.execute("SELECT contract_address FROM contribution_contracts")
app.contributors = {}
app.contracts = {}
for (contract_address,) in cursor:
contract_interface = app.service_node_contribution.get_contract_instance(contract_address)
# Fetch statuses and other details
is_finalized = contract_interface.is_finalized()
is_cancelled = contract_interface.is_cancelled()
pubkey_bls = contract_interface.get_bls_pubkey()
service_node_params = contract_interface.get_service_node_params()
#contributor_addresses = contract_interface.get_contributor_addresses()
total_contributions = contract_interface.total_contribution()
contributions = contract_interface.get_individual_contributions()
operator = contract_interface.get_operator()
app.contracts[contract_address] = {
'contract_state': 'finalized' if is_finalized else 'cancelled' if is_cancelled else 'awaiting_contributors',
'finalized': is_finalized,
'cancelled': is_cancelled,
'pubkey_bls': pubkey_bls,
'fee': service_node_params['fee'],
'service_node_pubkey': service_node_params['serviceNodePubkey'],
'service_node_signature': service_node_params['serviceNodeSignature'],
'contributions': [
{"address": addr, "amount": amt} for addr, amt in contributions.items()
],
'operator': operator,
'total_contributions': total_contributions,
}
for address in contributions.keys():
wallet_key = eth_format(address)
if address not in app.contributors:
app.contributors[wallet_key] = []
if contract_address not in app.contributors[wallet_key]:
app.contributors[wallet_key].append(contract_address)
app.logger.info("{} Update Contract Statuses Finish".format(date_now_str()))
@timer(10)
def fetch_service_nodes(signum):
app.logger.info("{} Update SN Start".format(date_now_str()))
omq, oxend = omq_connection()
# Generate new state
sn_info_list = get_sns_future(omq, oxend).get()["service_node_states"]
wallet_to_sn_map = {}
sn_map = {}
if len(app.bls_pubkey_to_contract_id_map) == 0:
app.logger.warning("{} bls_pubkey_to_contract_id_map is empty, fetching contract ids".format(date_now_str()))
update_service_node_contract_ids(None)
for sn_info in sn_info_list:
# Add the SN contract ID to the sn_info dict
pubkey_bls = sn_info.get('pubkey_bls')
if pubkey_bls is None:
app.logger.warning(f"pubkey_bls is None for sn_info SN: {sn_info}")
continue
contract_id = app.bls_pubkey_to_contract_id_map.get(pubkey_bls)
if contract_id is None:
app.logger.warning(f"Contract ID not found for sn_info SN with BLS pubkey: {pubkey_bls}")
continue
sn_info["contract_id"] = contract_id
requested_unlock_height = sn_info.get('requested_unlock_height')
sn_info['requested_unlock_height'] = requested_unlock_height if requested_unlock_height != 0 else None
sn_map[contract_id] = sn_info
contributors = {c["address"]: c["amount"] for c in sn_info["contributors"]}
# Creating (wallet -> [SN's the wallet owns]) table
for wallet_key in contributors.keys():
# TODO: Validate we want to allow wallet_key to not go through eth_format if len == 40
formatted_wallet_key = eth_format(wallet_key) if len(wallet_key) == 40 else wallet_key
if formatted_wallet_key is None:
app.logger.warning(f"Wallet key is None for sn_info SN: {sn_info}")
continue
wallet_to_sn_map.setdefault(formatted_wallet_key, []).append(contract_id)
# Apply the new state if there are any
if len(sn_map) > 0:
app.logger.debug(f"Adding {len(sn_map)} service node info to the contract_id_to_sn_map")
app.contract_id_to_sn_map = sn_map
app.logger.debug(f"Adding {len(wallet_to_sn_map)} wallet to service node map")
app.wallet_to_sn_map = wallet_to_sn_map
# Get list of SNs that can be liquidated/exited
exit_liquidation_list_json = get_oxen_rpc_bls_exit_liquidation_list(omq, oxend).get()
exitable_sns = {}
wallet_to_exitable_sn_map = {}
if exit_liquidation_list_json is not None:
net_info = get_info()
net_type = net_info.get('nettype')
timers = get_timers_hours(net_type)
for entry in exit_liquidation_list_json:
sn_info = entry.get('info')
pubkey_bls = sn_info.get('bls_public_key')
if pubkey_bls is None:
app.logger.warning(f"bls_public_key is None for exit_liquidation_list_json SN: {sn_info}")
continue
contract_id = app.bls_pubkey_to_contract_id_map.get(pubkey_bls)
if contract_id is None:
# If there is no contract ID it means this node has exited the smart contract and this event is being
# confirmed by oxend. This is the last state we'll get for this node from oxend.
# TODO: look at implementing some logic to add the node data to a dict that checks to make sure the db
# is properly updated with the final data we'll receive from oxend about this node.
app.logger.warning(f"Contract ID not found for exit_liquidation_list_json SN with BLS pubkey: {pubkey_bls}")
continue
sn_info['pubkey_bls'] = pubkey_bls
sn_info['contract_id'] = contract_id
for item in sn_info.get('contributors'):
item.pop('version')
exit_type = entry.get('type')
sn_info['exit_type'] = exit_type
sn_info['deregistration_unlock_height'] = entry.get('height') + blocks_in(
timers.get('unlock_duration_hours') * 3600) if exit_type == 'deregister' else None
requested_unlock_height = sn_info.get('requested_unlock_height')
sn_info['requested_unlock_height'] = requested_unlock_height if requested_unlock_height != 0 else None
sn_info['service_node_pubkey'] = entry.get('service_node_pubkey')
sn_info['liquidation_height'] = entry.get('liquidation_height')
exitable_sns[contract_id] = sn_info
for contributor in sn_info.get('contributors'):
wallet_str = eth_format(contributor.get('address'))
if wallet_str is None:
app.logger.warning(f"Wallet str is None for exit_liquidation_list_json SN: {sn_info}")
continue
wallet_to_exitable_sn_map.setdefault(wallet_str, set()).add(contract_id)
# Apply the new state if there are any
if len(exitable_sns) > 0:
app.logger.debug(f"Adding {len(exitable_sns)} exitable SN info to the contract_id_to_exitable_sn_map")
app.contract_id_to_exitable_sn_map = exitable_sns
app.logger.debug(f"Adding {len(wallet_to_exitable_sn_map)} wallet to exitable SN map")
app.wallet_to_exitable_sn_map = wallet_to_exitable_sn_map
# Get the accrued rewards values for each wallet
accrued_rewards_json = oxen_rpc_get_accrued_rewards(omq, oxend).get()
if accrued_rewards_json['status'] != 'OK':
app.logger.warning("{} Update SN early exit, accrued rewards request failed: {}".format(
date_now_str(),
accrued_rewards_json))
return
balances_key = 'balances'
if balances_key not in accrued_rewards_json:
app.logger.warning("{} Update SN early exit, accrued rewards request failed, 'balances' key was missing: {}".format(
date_now_str(),
accrued_rewards_json))
return
# Populate (Binary ETH wallet address -> accrued_rewards) table
for address_hex, rewards in accrued_rewards_json[balances_key].items():
# Ignore non-ethereum addresses (e.g. left oxen rewards, not relevant)
trimmed_address_hex = address_hex[2:] if address_hex.startswith('0x') else address_hex
if len(trimmed_address_hex) != 40:
continue
# Convert the address to bytes
address_key = bytes.fromhex(trimmed_address_hex)
# Create the info for the wallet if it doesn't exist
if address_key not in app.wallet_map:
app.wallet_map[address_key] = WalletInfo()
# We only update the rewards queried from the Oxen network
# Contract rewards are loaded on demand and cached.
#
# TODO It appears that doing the contract call is quite slow.
app.wallet_map[address_key].rewards = rewards
app.logger.info("{} Update SN finished".format(date_now_str()))
@app.route("/info")
def network_info():
"""
Do-nothing endpoint that can be called to get just the "network" and "t" values that are
included in every actual endpoint when you don't have any other endpoint to invoke.
"""
return json_response({})
def get_rewards_dict_for_wallet(eth_wal):
wallet_str = eth_format(eth_wal)
# Convert the wallet string into bytes if it is a hex (eth address)
wallet_key = wallet_str
if eth_wal is not None:
trimmed_wallet_str = wallet_str[2:] if wallet_str.startswith('0x') else wallet_str
wallet_key = bytes.fromhex(str(trimmed_wallet_str))
# Retrieve the rewards earned by the wallet
result = app.wallet_map[wallet_key] if wallet_key in app.wallet_map else WalletInfo()
# Query the amount of rewards committed/claimed currently on the contract
#
# NOTE: This is done on demand because it appears to be quite slow,
# iterating the list of wallets in one shot is quite expensive. The result
# is cached in the contract layer to avoid these expensive calls.
#
# This call is completely bypassed if the wallet is not in our wallet map
# which is populated from the Oxen rewards DB. The Oxen DB is the
# authoritative list and this prevents an actor from spamming random
# wallets to bloat out the python runtime memory usage.
if result.rewards > 0:
contract_recipient = app.service_node_rewards.recipients(wallet_key)
app.wallet_map[wallet_key].contract_rewards = contract_recipient.rewards
app.wallet_map[wallet_key].contract_claimed = contract_recipient.claimed
return result
class Contributor(TypedDict):
address: bytes
amount: int
reserved: int
class Stake(TypedDict):
contract_id: int | None
contributors: list[Contributor]
deregistration_unlock_height: int | None
earned_downtime_blocks: int
last_reward_block_height: int | None
last_uptime_proof: int | None
operator_address: bytes
operator_fee: int | None
pubkey_bls: bytes
requested_unlock_height: int | None
service_node_pubkey: bytes
staked_balance: int | None
state: str
class ErrorResponse:
def __init__(self, message: str):
self.error = message
def parse_stake_info(
stake: dict,
wallet_address: ChecksumAddress,
confirmed_exited: bool = False,
) -> Stake | ErrorResponse:
"""
Parses stake information and returns a standardised dictionary of stake info.
Args:
stake (dict): The stake data containing various stake attributes.
wallet_address (str): The wallet address of the user.
confirmed_exited (bool, optional): Flag indicating if the stake has been confirmed as exited. Defaults to False.
Exceptions:
ValueError: If the stake state cannot be determined.
Returns:
dict: A dictionary containing the parsed stake information.
"""
state = None
deregistration_unlock_height = None
try:
# Handles exit events
if 'exit_type' in stake:
exit_type = stake.get('exit_type')
if exit_type == 'exit':
state = (
"Awaiting Exit"
if stake.get('contract_id') and not confirmed_exited
else "Exited"
)
elif exit_type == 'deregister':
state = "Deregistered"
deregistration_unlock_height = stake.get('deregistration_unlock_height')
else:
raise ValueError(f"Invalid exit type {exit_type}")
# Handles contract events
elif 'contract_state' in stake:
contract_state = stake.get('contract_state')
if contract_state == 'awaiting_contributors':
state = "Awaiting Contributors"
elif contract_state == 'cancelled':
state = "Cancelled"
elif contract_state == 'finalized':
raise ValueError("Finalized nodes must be filtered out before reaching this point")
else:
raise ValueError(f"Invalid contract state {contract_state}")
# Handles running node info
elif 'active' in stake and 'funded' in stake:
state = (
'Decommissioned'
if not stake.get("active") and stake.get("funded")
else 'Running'
)
elif 'state' in stake:
current_state = stake.get('state')
if current_state == 'Deregistered':
deregistration_unlock_height = stake.get('deregistration_unlock_height')
if confirmed_exited and current_state == 'Awaiting Exit':
state = 'Exited'
else:
state = current_state
else:
raise ValueError("Unable to determine node state")
except ValueError as e:
base_msg = f"Value Error while parsing stake state for stake: \n {stake}"
app.logger.error(f"{base_msg} \n Exception: {e}")
return ErrorResponse(base_msg)
except Exception as e:
base_msg = f"Exception while parsing stake state for stake: \n {stake}"
app.logger.error(f"{base_msg} \n Exception: {e}")
return ErrorResponse(base_msg)
# Process contributors and calculate staked balance
contributors = stake.get('contributors', [])
staked_balance = sum(
contributor.get('amount')
for contributor in contributors
if eth_format(contributor.get('address')) == wallet_address
) or None
return {
'contract_id': stake.get('contract_id'),
'contributors': contributors,
'deregistration_unlock_height': deregistration_unlock_height,
'earned_downtime_blocks': stake.get('earned_downtime_blocks'),
'last_reward_block_height': stake.get('last_reward_block_height'),
'last_uptime_proof': stake.get('last_uptime_proof'),
'liquidation_height': stake.get('liquidation_height'),
'operator_address': stake.get('operator_address'),
'operator_fee': stake.get('portions_for_operator'),
'pubkey_bls': stake.get('pubkey_bls'),
'requested_unlock_height': stake.get('requested_unlock_height'),
'service_node_pubkey': stake.get('service_node_pubkey'),
'staked_balance': staked_balance,
'state': state,
'exited': confirmed_exited or state == 'Exited',
}
@app.route("/stakes/<eth_wallet:eth_wal>")
def get_stakes(eth_wal: str):
try:
if not eth_wal or not eth_utils.is_address(eth_wal):
raise ValueError("Invalid wallet address")
wallet_address = eth_format(eth_wal)
app.tracked_wallet_addresses.add(wallet_address)
# A contract id can only appear once across the lists
added_contract_ids = set()
parse_errors = []
app.logger.debug(f"Fetching stakes for {wallet_address}")
app.logger.debug(f"wallet_to_sn_map len: {len(app.wallet_to_sn_map)}")
app.logger.debug(f"contract_id_to_sn_map len: {len(app.contract_id_to_sn_map)}")
app.logger.debug(f"wallet_to_exitable_sn_map len: {len(app.wallet_to_exitable_sn_map)}")
app.logger.debug(f"contract_id_to_exitable_sn_map len: {len(app.contract_id_to_exitable_sn_map)}")
def handle_stakes(
address_to_stakes_map: dict[ChecksumAddress, set[int]],
contract_id_to_stake_map: dict[int, Stake],
output_list: list[Stake],
confirmed_exited=False,
):
app.logger.debug(f"added_contract_ids: {added_contract_ids}")
for contract_id in address_to_stakes_map.get(wallet_address, []):
app.logger.debug(f"contract_id: {contract_id}")
if contract_id not in added_contract_ids:
stake = contract_id_to_stake_map.get(contract_id)
parsed_stake = parse_stake_info(stake, wallet_address, confirmed_exited)
if isinstance(parsed_stake, ErrorResponse):
parse_errors.append({
'contract_id': contract_id,
'error': parsed_stake.error
})
else:
output_list.append(parsed_stake)
added_contract_ids.add(contract_id)
stakes = []
handle_stakes(app.wallet_to_exitable_sn_map, app.contract_id_to_exitable_sn_map, stakes)
handle_stakes(app.wallet_to_sn_map, app.contract_id_to_sn_map, stakes)
if wallet_address not in app.wallet_to_historical_stakes_map:
# NOTE: This db call is only triggered once per wallet address, this is reset after the scheduled db read.
get_db_stakes_for_wallet(wallet_address)
historical_stakes = []
handle_stakes(app.wallet_to_historical_stakes_map, app.contract_id_to_historical_stakes_map, historical_stakes,
confirmed_exited=True)
contracts = []
for contract_address in app.contributors.get(wallet_address, []):
details = app.contracts[contract_address]
contracts.append({
'contract_address': contract_address,
'details': details
})
if not details["finalized"]:
stakes.append(parse_stake_info(details, wallet_address))
return json_response({
"contracts": contracts,
"historical_stakes": historical_stakes,
"stakes": stakes,
"wallet": vars(get_rewards_dict_for_wallet(wallet_address)),
"error_stakes": parse_errors if len(parse_errors) > 0 else None
})
except ValueError as e:
app.logger.error(f"Exception: {e}")
return flask.abort(400, e)
except Exception as e:
app.logger.error(f"Exception: {e}")
return flask.abort(500, e)
@app.route("/nodes")
def get_nodes():
"""
Returns a list of all nodes that are running.
"""
nodes = []
for node in app.contract_id_to_sn_map.values():
nodes.append(parse_stake_info(node, node['operator_address']))
return json_response({"nodes": nodes})
# export enum NODE_STATE {
# RUNNING = 'Running',
# AWAITING_CONTRIBUTORS = 'Awaiting Contributors',
# CANCELLED = 'Cancelled',
# DECOMMISSIONED = 'Decommissioned',
# DEREGISTERED = 'Deregistered',
# AWAITING_EXIT = 'Awaiting Exit',
# EXITED = 'Exited',
# }
@app.route("/nodes/<oxen_wallet:oxen_wal>")
@app.route("/nodes/<eth_wallet:eth_wal>")
def get_nodes_for_wallet(oxen_wal=None, eth_wal=None):
assert oxen_wal is not None or eth_wal is not None
wallet_str = eth_format(eth_wal) if eth_wal is not None else oxen_wal
sns = []
nodes = []
for sn_index in app.wallet_to_sn_map.get(wallet_str, []):
sn_info = app.contract_id_to_sn_map[sn_index]
sns.append(sn_info)
balance = {c["address"]: c["amount"] for c in sn_info["contributors"]}.get(wallet_str, 0)
state = 'Decommissioned' if not sn_info["active"] and sn_info["funded"] else 'Running'
nodes.append({
'balance': balance,
'contributors': sn_info["contributors"],
'last_uptime_proof': sn_info["last_uptime_proof"],
'contract_id': sn_info["contract_id"],
'operator_address': sn_info["operator_address"],
'operator_fee': sn_info["portions_for_operator"],
'requested_unlock_height': sn_info["requested_unlock_height"],
'last_reward_block_height':sn_info["last_reward_block_height"],
'service_node_pubkey': sn_info["service_node_pubkey"],
'pubkey_bls': sn_info["pubkey_bls"],
'decomm_blocks_remaining': max(sn_info["earned_downtime_blocks"], 0),
'state': state,
})
contracts = []
if wallet_str in app.contributors:
for address in app.contributors[wallet_str]:
details = app.contracts[address]
contracts.append({
'contract_address': address,
'details': details
})
# Setup the result
result = json_response({
"wallet": vars(get_rewards_dict_for_wallet(wallet_str)),
"service_nodes": sns,
"contracts": contracts,
"nodes": nodes,
})
return result
@app.route("/nodes/open")
def get_contributable_contracts():
return json_response({
"nodes": [
{
"contract": addr,
**details
}
for addr, details in app.contracts.items()
if not details['finalized'] and not details['cancelled']
# FIXME: we should also filter out reserved contracts
]
})
@app.route("/rewards/<eth_wallet:eth_wal>", methods=["GET", "POST"])
def get_rewards(eth_wal: str):
if flask.request.method == "GET":
result = json_response({
"wallet": vars(get_rewards_dict_for_wallet(eth_wal)),
})
return result
if flask.request.method == "POST":
omq, oxend = omq_connection()
try:
response = oxen_rpc_bls_rewards_request(omq, oxend, eth_format(eth_wal)).get()
if response is None:
return flask.abort(504) # Gateway timeout
if 'status' in response:
response.pop('status')
if 'address' in response:
response.pop('address')
result = json_response({
'result': response
})
return result
except TimeoutError:
return flask.abort(408) # Request timeout
return flask.abort(405) # Method not allowed
@app.route("/exit/<hex64:ed25519_pubkey>")
def get_exit(ed25519_pubkey: bytes):
omq, oxend = omq_connection()
try:
response = oxen_rpc_bls_exit_liquidation(omq, oxend, ed25519_pubkey, liquidate=False).get()
if response is None:
return flask.abort(504) # Gateway timeout
if 'status' in response:
response.pop('status')
result = json_response({
'result': response
})
return result
except TimeoutError:
return flask.abort(408) # Request timeout
@app.route("/exit_liquidation_list")
def get_exit_liquidation_list():
try:
array = []
for item in app.contract_id_to_exitable_sn_map.values():
array.append(item)
result = json_response({
'result': array
})
return result
except TimeoutError:
return flask.abort(408) # Request timeout
@app.route("/liquidation/<hex64:ed25519_pubkey>")
def get_liquidation(ed25519_pubkey: bytes):
omq, oxend = omq_connection()
try:
response = oxen_rpc_bls_exit_liquidation(omq, oxend, ed25519_pubkey, liquidate=True).get()
if response is None:
return flask.abort(504) # Gateway timeout
if 'status' in response:
response.pop('status')
result = json_response({
'result': response
})
return result
except TimeoutError:
return flask.abort(408) # Request timeout
def handle_stakes_row(
wallet_to_historical_stakes_map: dict[ChecksumAddress, set[int]],
contract_id_to_historical_stakes_map: dict[int, Stake],
sql_cur: sqlite3.Cursor,
):
for row in sql_cur:
(
contract_id,