-
Notifications
You must be signed in to change notification settings - Fork 1
/
BlurtChain.py
1865 lines (1510 loc) · 60.9 KB
/
BlurtChain.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
from beem.instance import set_shared_blockchain_instance
from beem.account import Account
from beem.amount import Amount
from beem.comment import Comment
from beem.witness import Witness
from beemapi.noderpc import NodeRPC
from beem import Blurt
from config import Config
from beemgraphenebase.account import PrivateKey
from flask import Markup
from datetime import datetime, timedelta
import random
import requests
import pyrebase
import base64
import json
from markdown import markdown
from operator import itemgetter
import concurrent.futures
import cryptocode
import re
# Firebase configuration
serviceAccountCredentials = json.loads(
base64.b64decode(Config.FB_SERVICEACCOUNT.encode()).decode())
firebase_config = {
"apiKey": Config.FB_APIKEY,
"authDomain": Config.FB_AUTHDOMAIN,
"databaseURL": Config.FB_DATABASEURL,
"storageBucket": Config.FB_STORAGEBUCKET,
"serviceAccount": serviceAccountCredentials,
}
# Firebase initialization
firebase = pyrebase.initialize_app(firebase_config)
# Blurt Node List
BLURT_NODES = Config.NODE_LIST
class BlurtChain:
"""docstring for Chain"""
# Setup node list for Blurt
# Create Blurt chain object
def __init__(self, username):
self.username = username
self.account = None
self.witness = 0
self.nodes = self.get_node()
self.blurt = Blurt(node=self.nodes, num_retries=3)
self.blockchain = set_shared_blockchain_instance(self.blurt)
# Get a reference to the database service
self.firebase = firebase.database()
# Create account object
try:
self.account = Account(self.username, full=False, lazy=False)
except Exception:
self.username = None
self.account = None
try:
witness = Witness(self.username)
if witness.is_active:
self.witness = 1
except Exception:
self.witness = 0
def get_node(self):
result = BLURT_NODES[0]
random.shuffle(BLURT_NODES)
for node in BLURT_NODES:
try:
response = requests.get(node, timeout=1)
if response:
result = node
break
except requests.exceptions.RequestException as e:
print(f'GET_NODE_ERR:{node} {e}')
return result
def get_account_info(self):
self.account_info = {}
if self.username:
# GET VOTING POWER %
voting_power = self.account.get_voting_power()
self.account_info['voting_power'] = f'{voting_power:.2f}'
manabar = self.account.get_manabar()
recharge_time = self.account.get_manabar_recharge_time_str(manabar)
self.account_info['recharge_time_str'] = recharge_time
# GET ACCOUNT DETAILS
noderpc = NodeRPC(self.nodes)
account_data = noderpc.get_account(self.username)[0]
self.account_info['username'] = account_data['name']
# BLURT BALANCE
balance = float(account_data['balance'].split()[0])
self.account_info['blurt'] = f'{balance:,.3f}'
# BLURT POWER
vesting_shares = account_data['vesting_shares']
vesting_shares = float(self.vests_to_bp(vesting_shares))
self.account_info['bp'] = f'{vesting_shares:,.3f}'
# SAVINGS BALANCE
savings_balance = account_data['savings_balance']
savings_balance = float(account_data['savings_balance'].split()[0])
self.account_info['savings'] = f'{savings_balance:,.3f}'
# CURRENT REWARDS in BLURT and BLURT POWER
# BLURT REWARD
reward_blurt = float(
account_data['reward_blurt_balance'].split()[0])
self.account_info['reward_blurt'] = f'{reward_blurt:,.3f}'
# BP REWARD
reward_bp = float(
account_data['reward_vesting_blurt'].split()[0])
self.account_info['reward_bp'] = f'{reward_bp:,.3f}'
# DELEGATED BP
delegated_bp = account_data['delegated_vesting_shares']
delegated_bp = float(self.vests_to_bp(delegated_bp))
self.account_info['delegated_bp'] = f'{delegated_bp:,.3f}'
# RECEIVED BP
received_bp = account_data['received_vesting_shares']
received_bp = float(self.vests_to_bp(received_bp))
self.account_info['received_bp'] = f'{received_bp:,.3f}'
# GET EFFECTIVE BLURT POWER (staked token + delegations)
token_power = self.account.get_token_power()
self.account_info['effective'] = f'{token_power:,.3f}'
# POWERDOWN SCHEDULE
withdraw_bp = account_data['vesting_withdraw_rate']
withdraw_bp = float(self.vests_to_bp(withdraw_bp))
self.account_info['withdraw_bp'] = f'{withdraw_bp:,.3f}'
withdraw_date = account_data['next_vesting_withdrawal']
withdraw_date = datetime.strptime(
withdraw_date, '%Y-%m-%dT%H:%M:%S')
current_date = datetime.utcnow()
if current_date > withdraw_date:
self.account_info['withdraw_date'] = '--'
else:
self.account_info['withdraw_date'] = withdraw_date
# leaderboard rank
ranking = self.get_ranking(self.username)
self.account_info['ranking'] = ranking
# get upvote count and convert into stars
# 1 to 5 ⭐⭐⭐⭐⭐ ratings
stars = self.get_star_rating(self.username)
self.account_info['stars'] = stars
# check if follow trail or not
if self.get_active_follow_key(self.username):
self.account_info['trail'] = True
else:
self.account_info['trail'] = False
return self.account_info
def get_follower(self):
self.follower_data = {}
follower = []
following = []
common = []
if self.username:
follower = self.account.get_followers(self.username)
following = self.account.get_following(self.username)
common = set(follower) & set(following)
for username in follower:
if username in common:
self.follower_data[username] = 1
else:
self.follower_data[username] = 0
return self.follower_data
def get_following(self):
self.following_data = {}
follower = []
following = []
common = []
if self.username:
follower = self.account.get_followers(self.username)
following = self.account.get_following(self.username)
common = set(follower) & set(following)
for username in following:
if username in common:
self.following_data[username] = 1
else:
self.following_data[username] = 0
return self.following_data
def get_pending_posts(self):
active_posts = []
posts = self.account.blog_history(limit=50)
for post in posts:
c = Comment(post['authorperm'], blockchain_instance=self.blurt)
time_elapsed = c.time_elapsed()
# Skip old posts(7 days = 604800 sec)
if time_elapsed.total_seconds() > 604800:
break
rewards = c.get_author_rewards()
if rewards['pending_rewards']:
active_posts.append({
'title': c['title'],
'authorperm': post['authorperm'],
'pending_rewards': rewards['total_payout'],
})
return active_posts
def get_operations(self):
result = []
stop = datetime.utcnow() - timedelta(days=1)
if self.username:
operations = self.account.history_reverse(stop=stop)
for op in operations:
datetime_obj = datetime.strptime(
op["timestamp"], '%Y-%m-%dT%H:%M:%S')
timestamp = datetime_obj.strftime(
"%Y-%m-%d %H:%M:%S")
op_data = {
'timestamp': timestamp,
'type': op['type'],
'title': op['type'].replace('_', ' ').title(),
'block': op['block'],
'id': op['trx_id'],
}
if op['type'] == 'curation_reward':
vests = Amount(op['reward'])
op_data['bp'] = self.vests_to_bp(vests)
op_data['comment_author'] = op["comment_author"]
op_data['comment_permlink'] = op["comment_permlink"]
elif op['type'] == 'author_reward':
vests = Amount(op['vesting_payout'])
op_data['bp'] = self.vests_to_bp(vests)
bvests = Amount(op['blurt_payout'])
op_data['blurt'] = self.vests_to_bp(bvests)
op_data['author'] = op["author"]
op_data['permlink'] = op["permlink"]
elif op['type'] == 'producer_reward':
vests = Amount(op['vesting_shares'])
op_data['bp'] = self.vests_to_bp(vests)
elif op['type'] == 'comment_benefactor_reward':
vests = Amount(op['vesting_payout'])
op_data['bp'] = self.vests_to_bp(vests)
bvests = Amount(op['blurt_payout'])
op_data['blurt'] = self.vests_to_bp(bvests)
op_data['permlink'] = op["permlink"]
op_data['benefactor'] = op["benefactor"]
elif op['type'] == 'transfer':
vests = Amount(op['amount'])
op_data['blurt'] = self.vests_to_bp(vests)
op_data['from'] = op["from"]
op_data['to'] = op["to"]
elif op['type'] == 'delegate_vesting_shares':
vests = Amount(op['vesting_shares'])
op_data['bp'] = self.vests_to_bp(vests)
op_data['from'] = op["delegator"]
op_data['to'] = op["delegatee"]
elif op['type'] == 'transfer_to_vesting':
vests = Amount(op['amount'])
op_data['bp'] = self.vests_to_bp(vests)
op_data['from'] = op["from"]
op_data['to'] = op["to"]
elif op['type'] == 'withdraw_vesting':
vests = Amount(op['vesting_shares'])
op_data['bp'] = self.vests_to_bp(vests)
elif op['type'] == 'claim_reward_balance':
vests = Amount(op['reward_vests'])
op_data['bp'] = self.vests_to_bp(vests)
bvests = Amount(op['reward_blurt'])
op_data['blurt'] = self.vests_to_bp(bvests)
elif op['type'] == 'vote':
weight = op["weight"] / 100
op_data['weight'] = float(f'{weight:.2f}')
op_data['from'] = op["voter"]
op_data['to'] = op["author"]
op_data['permlink'] = op["permlink"]
elif op['type'] == 'comment':
op_data['from'] = op["author"]
op_data['to'] = op["parent_author"] or op["author"]
op_data['permlink'] = op["permlink"]
elif op['type'] == 'delete_comment':
op_data['permlink'] = op["permlink"]
elif op['type'] == 'account_witness_vote':
op_data['account'] = op["account"]
op_data['witness'] = op["witness"]
op_data['approve'] = op["approve"]
elif op['type'] == 'account_witness_proxy':
op_data['proxy'] = op["proxy"]
elif op['type'] == 'custom_json' and op['id'] == 'follow':
json_data = json.loads(op['json'])
if json_data[0] == 'follow':
if len(json_data[1]['what']):
op_data['type'] = 'follow'
else:
op_data['type'] = 'unfollow'
op_data['title'] = op_data['type'].replace(
'_', ' ').title()
op_data['from'] = json_data[1]['follower']
op_data['to'] = json_data[1]['following']
else:
pass
result.append(op_data)
return result
def get_vote_history(self, username):
result = {}
labels = []
permlinks = []
upvotes = []
count_data = []
weight_data = []
total_votes = 0
stop = datetime.utcnow() - timedelta(days=1)
if self.username:
history = self.account.history_reverse(
stop=stop, only_ops=['vote'])
# Count how many times voted in 7 days
for data in history:
permlink = f'@{data["author"]}/{data["permlink"]}'
weight = f"{data['weight'] * 0.01:.2f}"
timestamp = datetime.strptime(
data['timestamp'], '%Y-%m-%dT%H:%M:%S')
if self.username == data["voter"]:
link_data = {
'timestamp': timestamp,
'permlink': permlink,
'weight': weight,
}
permlinks.append(link_data)
else:
voter = data['voter']
upvote_data = {
'timestamp': timestamp,
'voter': voter,
'permlink': permlink,
'weight': weight,
}
upvotes.append(upvote_data)
result['total_votes'] = total_votes
result['labels'] = labels
result['permlinks'] = permlinks
result['upvotes'] = upvotes
result['count_data'] = count_data
result['weight_data'] = weight_data
return result
def get_mute(self):
data = {}
if self.username:
data['muter'] = self.account.get_muters()
data['muting'] = self.account.get_mutings()
return data
def get_incoming_delegation(self, username):
current_time = datetime.utcnow().strftime("%m/%d/%Y %H:%M:%S")
db_name = 'incoming_delegation'
account = Account(username, blockchain_instance=self.blurt)
fb_key = None
fb_data = None
fb_block_num = 0
# Check user data in fb
user_record = self.firebase.child(db_name).order_by_child(
"username").equal_to(str(username)).get().val()
if user_record:
record = next(iter(user_record.items()))
fb_key = record[0]
fb_data = record[1]
fb_block_num = fb_data['block_num']
else:
save_data = {
'username': username,
'block_num': 0,
'created': current_time,
}
save_result = self.firebase.child(db_name).push(save_data)
fb_key = save_result['name']
delegate_vesting_shares = account.history(
start=fb_block_num,
use_block_num=True,
only_ops=["delegate_vesting_shares"])
for op in delegate_vesting_shares:
if op['delegator'] == username:
continue
amount_vests = Amount(op['vesting_shares'])
amount = self.blurt.vests_to_bp(amount_vests)
# replace "." sign in username with "+"
delegator = op['delegator'].replace(".", "+")
delegation_data = {
'timestamp': op['timestamp'],
'amount': amount,
}
# Save/Update delegation data
if amount:
self.firebase.child(db_name).child(fb_key).child(
'delegators').child(delegator).update(delegation_data)
else:
self.firebase.child(db_name).child(fb_key).child(
'delegators').child(delegator).remove()
# Update block_num
if op['block']:
self.firebase.child(db_name).child(fb_key).update({
'block_num': op['block'],
'created': current_time
})
# Remove record if no incoming delegation
delegation_record = self.firebase.child(db_name).child(
fb_key).child('delegators').get().val()
if delegation_record is None:
self.firebase.child(db_name).child(fb_key).remove()
def get_delegation_new(self, option):
# find delegation for username
data = {}
if not self.username:
return data
# find incoming delegaton
if option == "in":
db_name = 'incoming_delegation'
data['incoming'] = []
# Get delegation data from db
user_record = self.firebase.child(db_name).order_by_child(
"username").equal_to(self.username).get().val()
if user_record:
delegators = {}
record = next(iter(user_record.items()))
fb_data = record[1]
if 'delegators' in fb_data:
delegators = fb_data["delegators"]
for username in delegators:
data['incoming'].append({
'delegator': username.replace("+", "."),
'bp': f'{delegators[username]["amount"]:,.3f}',
'timestamp': delegators[username]['timestamp'],
})
# find outgoing delegaton
elif option == "out":
data['outgoing'] = self.account.get_vesting_delegations()
for value in data['outgoing']:
value['bp'] = self.vests_to_bp(value['vesting_shares'])
# find expiring delegaton
elif option == "exp":
data['expiring'] = self.account.get_expiring_vesting_delegations()
for value in data['expiring']:
value['bp'] = self.vests_to_bp(value['vesting_shares'])
date_time = value['expiration'].split('T')
value['expiration'] = f'{date_time[0]} {date_time[-1]}'
else:
return data
return data
def vests_to_bp(self, vests):
# VESTS to BP conversion
bp = 0.000
v = Amount(vests)
if v.symbol == 'VESTS':
bp = self.blurt.vests_to_bp(v.amount)
bp = f'{bp:.3f}'
else:
bp = f'{v.amount:.3f}'
return bp
def process_data(self, count_type, data):
result = 0
if count_type in data:
result = data[count_type]
return result
def is_coal(self, username):
# check if user is in coal_list
# coal user won't be upvoted
result = False
db_name = 'coal_list'
is_coal = self.firebase.child(
db_name).order_by_child("username").equal_to(username).get().val()
if len(is_coal):
result = True
return result
def is_ignored(self, username):
# check to see if user is in ignore_list
# ignored user won't be upvoted
result = False
db_name = 'ignore_list'
ignored_users = self.firebase.child(db_name).get()
for user in ignored_users.each():
value = user.val()
if value['username'] == username:
result = True
break
return result
def is_witness_bonus(self, username):
# check if voted for openb witness
# return True if voted
result = False
witness_votes = self.witness_votes
print(f"{witness_votes=}")
bad_witness = {
'fervi', 'double-u', 'etainclub', 'joviansummer',
'jakeminlim', 'ytyeasin', 'jacobgadikian', 'gamer0815'
}
bad_matches = len(witness_votes.intersection(bad_witness))
if bad_matches:
print('BAD_WITNESS')
return result
recommended_witness = {'openb'}
matches = len(witness_votes.intersection(recommended_witness))
if matches:
result = True
return result
def is_iduvts(self, username):
# check location iduvts in json_metadata
# return True if iduvts
result = False
pattern = r'\biduvts\b'
text = ''
blurt = Blurt(node=self.nodes, num_retries=5)
account = Account(username, blockchain_instance=blurt)
if ('profile' in account.json_metadata
and 'location' in account.json_metadata['profile']):
text = account.json_metadata['profile']['location']
if ('profile' in account.json_metadata
and 'about' in account.json_metadata['profile']):
text = account.json_metadata['profile']['about']
# if text == 'iduvts':
if re.findall(pattern, text, re.I):
print(text)
result = True
return result
def is_curation_trail(self, username):
# check if user is following trail
# return True if not a follower
result = False
# check if active username exists in trail_followers
follow_key = self.get_active_follow_key(username)
if follow_key is None:
# Not following trail
result = True
return result
def check_content(self, identifier):
# Return True if no content
# False if content exists
result = {
'status': False
}
try:
c = Comment(
identifier, api='condenser',
blockchain_instance=self.blurt)
except Exception as err:
result['status'] = True
result['message'] = 'Error: Content dose not exit. \
Please check the URL'
print('CHECK_CONTENT_NOT_EXIST:', err)
return result
# check iduvts tag
if 'iduvts' in c.json_metadata['tags']:
result['status'] = True
result['message'] = 'Error: iduvts tag'
return result
def check_last_ip(self, client_ip):
print('CHECK_LAST_IP', client_ip)
# 6 hour = 21600 sec
wait_time = 21600.0
last_vote = None
result = False
# get the last upvote data
db_name = 'upvote_log'
logs = self.firebase.child(db_name).get()
for log in logs.each():
value = log.val()
if value['client_ip'] == client_ip:
last_vote = value['created']
print('FB DATA FOUND')
print(value['client_ip'])
print(value['username'])
print(value['created'])
print(value['vote_weight'])
print()
if last_vote is None:
result = True
return result
# check if last voted ip is more than wait_time
current_time = datetime.utcnow()
last_vote = datetime.strptime(last_vote, "%m/%d/%Y %H:%M:%S")
print('CURRENT_TIME', current_time)
print('LAST_VOTED', last_vote)
time_diff = current_time - last_vote
if time_diff.total_seconds() >= wait_time:
result = True
return result
def check_last_upvote(self, username):
# 24 hour = 86400 sec
# 20 hour = 72000 sec
# 21 hour = 75600 sec
wait_time = 75600.0
result = False
self.wait_time = None
# get the last upvote record
record = self.firebase.child("upvote_log").order_by_child(
"username").equal_to(username).limit_to_last(1).get()
if not record.val():
result = True
return result
# check if last upvoted is more than wait_time
for data in record.each():
val = data.val()
current_time = datetime.utcnow()
last_vote = val['created']
last_vote = datetime.strptime(last_vote, "%m/%d/%Y %H:%M:%S")
time_diff = current_time - last_vote
if time_diff.total_seconds() >= wait_time:
result = True
else:
seconds = wait_time - time_diff.total_seconds()
wait = timedelta(seconds=seconds)
# convert wait time: WAIT_TIME 11:58:20
self.wait_time = str(wait).split('.')[0]
return result
def delegation_bonus(self, username):
bonus_weight = 0.0
blurt = Blurt(node=self.nodes, num_retries=5)
account = Account(username, blockchain_instance=blurt)
# check delegation_bonus (bonus_weight 10 - 80%)
vesting_delegations = account.get_vesting_delegations()
for delegation in vesting_delegations:
if delegation["delegatee"] == "tomoyan":
vesting_shares = Amount(delegation["vesting_shares"])
delegation_bp = self.blurt.vests_to_bp(vesting_shares.amount)
if 1.0 <= delegation_bp < 100.0:
bonus_weight = round(random.uniform(0, 1), 2)
elif 100.0 <= delegation_bp < 500.0:
bonus_weight = round(random.uniform(1, 3), 2)
elif 500.0 <= delegation_bp < 1000.0:
bonus_weight = round(random.uniform(4, 8), 2)
elif 1000.0 <= delegation_bp < 3000.0:
bonus_weight = round(random.uniform(9, 12), 2)
elif 3000.0 <= delegation_bp < 5000.0:
bonus_weight = round(random.uniform(13, 15), 2)
elif 5000.0 <= delegation_bp < 10000.0:
bonus_weight = round(random.uniform(15, 20), 2)
elif 10000.0 <= delegation_bp < 30000.0:
bonus_weight = round(random.uniform(20, 25), 2)
elif 30000.0 <= delegation_bp < 50000.0:
bonus_weight = round(random.uniform(25, 30), 2)
elif 50000.0 <= delegation_bp < 100000.0:
bonus_weight = round(random.uniform(30, 35), 2)
elif 100000.0 <= delegation_bp < 200000.0:
bonus_weight = round(random.uniform(40, 45), 2)
elif 200000.0 <= delegation_bp < 300000.0:
bonus_weight = round(random.uniform(50, 55), 2)
elif 300000.0 <= delegation_bp < 400000.0:
bonus_weight = round(random.uniform(60, 65), 2)
elif 400000.0 <= delegation_bp < 500000.0:
bonus_weight = round(random.uniform(70, 75), 2)
elif delegation_bp >= 500000.0:
bonus_weight = 80.0
break
return bonus_weight
def member_bonus(self, username):
bonus_weight = 0.0
member_list = []
db_name = "user_level"
level = 100
users = self.firebase.child(db_name).child(level).get()
for user in users.each():
data = user.val()
member_list.append(data["username"])
if username in member_list:
bonus_weight = 100.0
else:
# add leaderboard upvote bonus
# check leaderboard rank
ranking = self.get_ranking(username)
if ranking == 1:
bonus_weight = 15.0
elif ranking == 2:
bonus_weight = 10.0
elif ranking == 3:
bonus_weight = 5.0
return bonus_weight
def upvote_post(self, identifier, delegation_bonus, member_bonus):
upvote_account = Config.UPVOTE_ACCOUNT
upvote_key = Config.UPVOTE_KEY
vote_result = {
"status": False,
"message": "Error"
}
blurt = Blurt(node=self.nodes, keys=[upvote_key], num_retries=5)
account = Account(upvote_account, blockchain_instance=blurt)
# Base vote weight (random 1-2%)
base_weight = round(random.uniform(1, 2), 2)
# add bonus weights
weight = base_weight + delegation_bonus + member_bonus
if weight > 100.0:
weight = 100.0
# TEMP WEIGHT ADJUSTMENT
# weight *= 0.8
try:
result = blurt.vote(weight, identifier, account=account)
print('VOTED', result['trx_id'])
vote_result["status"] = True
vote_result["message"] = f"Upvoted: {result}"
vote_result["vote_weight"] = weight
vote_result["identifier"] = identifier
except Exception as err:
print('VOTE_ERR', err, weight, identifier)
# vote_result["message"] = f"Error: Please check your URL {err}"
vote_result["message"] = f"Error: Oops something went wrong {err}"
return vote_result
def comment_post(self, vote_data):
vote_weight = f"{vote_data['vote_weight']:.2f}"
post_key = Config.UPVOTE_KEY
username = Config.UPVOTE_ACCOUNT
B = Blurt(node=self.nodes, keys=[post_key], num_retries=5)
# Get thank you image from giphy
url = (
'http://api.giphy.com/v1/gifs/search?'
'q=arigato thanks heart&'
'api_key=b2w5nCHfqrGt6tbXBD7BCcfw11plV5b1&'
'limit=100'
)
response = requests.get(url)
json_data = response.json()
# Pick a random image data from json_data
default_img = 'https://i.imgur.com/6qvr7sJ.jpg'
image_data = random.choice(json_data['data'])
gif_img = image_data['images']['original']['url']
gif_img = gif_img.split('?', 1)[0]
img_url = gif_img or default_img
comment_body = f"""
{img_url}
** Your post has been upvoted ({vote_weight} %) **
* **Curation Trail is Open!**
[Join Trail Here](https://blurtblock.herokuapp.com/blurt/trail)
* **Delegate more BP for bigger Upvote + Daily BLURT** 😉
[Delegate BP Here](https://blurtblock.herokuapp.com/blurt/delegate)
* **Upvote**
https://blurtblock.herokuapp.com/blurt/upvote
Thank you 🙂 @tomoyan
"""
# Post a reply comment
B.post(
author=username,
title='comment title',
body=comment_body,
reply_identifier=vote_data['identifier'])
def is_power_down(self, username):
# If user is powering down, return True
witness_votes = {}
result = False
noderpc = NodeRPC(self.nodes)
account_data = noderpc.get_account(username)[0]
# Check power down amount
vesting_withdraw_rate = Amount(account_data['vesting_withdraw_rate'])
if vesting_withdraw_rate.amount > 0:
print(f'{vesting_withdraw_rate.amount=}')
result = True
# set witness_votes data for witness_bonus
witness_votes = set(account_data["witness_votes"])
self.witness_votes = witness_votes
return result
def check_post_vote(self, identifier):
# check identifier (@username/permalink)
# if it is already upvoted or not(True/False)
result = False
upvote_account = Config.UPVOTE_ACCOUNT
blurt = Blurt(node=self.nodes, num_retries=5)
account = Account(upvote_account, blockchain_instance=blurt)
try:
COMMENT = Comment(identifier, api='condenser',
blockchain_instance=blurt)
result = account.has_voted(COMMENT)
except Exception as err:
print('CHECK_POST_VOTE:', err)
return result
def check_post_age(self, identifier):
# if post age is less than 5 minutes (300 secs)
# or more than 5 days (432000 secs)
# return False
duration_early = 300 # 5 minutes
duration_late = 432000 # 5 days
result = False
try:
COMMENT = Comment(identifier, api='condenser')
post_age = COMMENT.time_elapsed().total_seconds()
if duration_early < post_age < duration_late:
result = True
except Exception as err:
print('CHECK_POST_AGE:', err)
return result
def save_data_fb(self, db_name, data):
# save data into firebase database
result = self.firebase.child(db_name).push(data)
return result
def update_data_fb(self, db_name, key, data):
# replace "." sign in username with "+"
replaced_key = key.replace(".", "+")
# update data into firebase database
result = self.firebase.child(db_name).child(replaced_key).update(data)
return result
def remove_data_fb(self, db_name, key):
# remove data from firebase
result = self.firebase.child(db_name).child(key).remove()
return result
def get_reward_summary_fb(self, key):
# replace "." sign in username with "+"
replaced_key = key.replace(".", "+")
# get reward summary data and then remove from fb
result = dict()
db_name = 'reward_summary'
data = self.firebase.child(db_name).child(replaced_key).get()
if data.each():
for d in data.each():
result[d.key()] = d.val()
return result
def remove_reward_summary_fb(self, key):
# replace "." sign in username with "+"
replaced_key = key.replace(".", "+")
# remove reward summary from fb
db_name = 'reward_summary'
self.firebase.child(db_name).child(replaced_key).remove()
def get_account_history_fb(self, key):
# replace "." sign in username with "+"
replaced_key = key.replace(".", "+")
# get account history data and then remove from fb
result = dict()
db_name = 'account_history'
data = self.firebase.child(db_name).child(replaced_key).get()
if data.each():
for d in data.each():
result[d.key()] = d.val()
return result
def remove_account_history_fb(self, key):
# replace "." sign in username with "+"
replaced_key = key.replace(".", "+")
# remove account history from fb
db_name = 'account_history'
self.firebase.child(db_name).child(replaced_key).remove()
def process_upvote(self, url):
username = None
identifier = None