-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmsc_validate.py
1699 lines (1465 loc) · 86.2 KB
/
msc_validate.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/python
#######################################################
# #
# Copyright Masterchain Grazcoin Grimentz 2013-2014 #
# https://github.com/grazcoin/mastercoin-tools #
# https://masterchain.info #
# masterchain@@bitmessage.ch #
# License AGPLv3 #
# #
#######################################################
import os
from optparse import OptionParser
from msc_utils_validating import *
# alarm to release funds if accept not paid on time
# format is {block:[accept_tx1, accept_tx2, ..], ..}
alarm={}
# create address dict that holds all details per address
addr_dict={}
tx_dict={}
# create dict that holds statistics per coin
coin_stats_dict={}
# invalidate tx due to "avoid changing history" issues
invalidate_tx_list=[]
# prepare lists for mastercoin and test
sorted_currency_tx_list={}
sorted_currency_sell_tx_list={}
sorted_currency_accept_tx_list={}
filtered_tx_list={}
for c in coins_list:
sorted_currency_tx_list[c]=[]
sorted_currency_sell_tx_list[c]=[]
sorted_currency_accept_tx_list[c]=[]
filtered_tx_list[c]=[]
# all available properties of a transaction
tx_properties=\
['tx_hash', 'invalid', 'tx_time', \
'exodus_scan', \
'amount', 'formatted_amount', \
'from_address', 'to_address', 'transactionType', \
'icon', 'icon_text', 'color', \
'block', 'index', \
'details', 'tx_type_str', \
'baseCoin', 'dataSequenceNum', 'method', 'tx_method_str', \
'bitcoin_amount_desired', 'block_time_limit', 'fee', \
'sell_offer_txid', 'accept_txid', 'btc_offer_txid', \
'prev_payment_txid', 'next_payment_txid', 'accomulated_payment', \
'action', 'action_str', \
'amount_available', 'formatted_amount_available', \
'formatted_amount_accepted', 'formatted_amount_bought', \
'formatted_amount_requested', 'formatted_price_per_coin', 'bitcoin_required', \
'payment_done', 'payment_expired', \
'updating', 'updated_by', \
'status']
# all available properties of a currency in address
addr_properties=['balance', 'reserved', 'received', 'sent', 'bought', 'sold', 'offer', 'accept', 'reward',\
'in_tx', 'out_tx', 'bought_tx', 'sold_tx', 'offer_tx', 'accept_tx', 'exodus_tx']
# all available properties of coin statistics
coin_stats_properties=['total_sold', 'total_paid', 'last_price', 'previous_last_price']
# create modified tx dict which would be used to modify tx files
offers_dict={}
# global last block on the net
last_height=get_last_height()
def sorted_ls(path):
mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
return list(sorted(os.listdir(path), key=mtime))
def initial_tx_dict_load():
# run on all files in tx
tx_files=sorted_ls('tx')
# load dict of each
for filename in tx_files:
if filename.endswith('.json'):
tx_hash=filename.split('.')[0]
update_tx_dict(tx_hash)
def get_sorted_tx_list():
# run on all files in tx
tx_files=sorted_ls('tx')
# load dict of each
tx_list=[]
for k in tx_dict.keys():
tx_list+=tx_dict[k] # append the list of tx for each key (incl. exodus)
# sort according to time
return sorted(tx_list, key=lambda k: (int(k['block']),int(k['index'])))
def add_alarm(tx_hash):
t=tx_dict[tx_hash][-1] # last tx on the list
tx_block=int(t['block'])
sell_offer_txid=t['sell_offer_txid']
sell_offer_tx=tx_dict[sell_offer_txid][-1]
payment_timeframe=int(sell_offer_tx['formatted_block_time_limit'])
alarm_block=tx_block+payment_timeframe
if alarm.has_key(alarm_block):
alarm[alarm_block].append(t)
debug('added alarm in block '+str(alarm_block)+' for '+tx_hash)
else:
alarm[alarm_block]=[t]
debug('added first alarm in block '+str(alarm_block)+' for '+tx_hash)
def remove_alarm(tx_hash):
t=tx_dict[tx_hash][-1] # last tx on the list
tx_block=int(t['block'])
sell_offer_txid=t['sell_offer_txid']
sell_offer_tx=tx_dict[sell_offer_txid][-1]
payment_timeframe=int(sell_offer_tx['formatted_block_time_limit'])
alarm_block=tx_block+payment_timeframe
if alarm.has_key(alarm_block):
try:
alarm[alarm_block].remove(t)
debug('removed alarm at block '+str(alarm_block)+' for '+tx_hash)
except ValueError:
info('failed removing alarm for '+tx_hash)
else:
info('failed removing alarm for '+tx_hash+' since no alarm block '+alarm_block)
def check_alarm(t, last_block, current_block):
# check alarms for all blocks since last check
# if late - mark expired
for b in range(last_block, current_block):
if alarm.has_key(b):
debug('alarm for block '+str(b))
debug('transaction checked in alarm for block are '+str(alarm[b]))
for a in alarm[b]:
debug('verify payment for tx '+str(a['tx_hash']))
tx_hash=a['tx_hash']
amount=float(a['formatted_amount'])
amount_accepted=float(a['formatted_amount_accepted'])
amount_bought=float(a['formatted_amount_bought'])
# not paid case
if not a.has_key('btc_offer_txid') or a['btc_offer_txid']=='unknown': # accept with no payment
# update accept transaction with expired note
debug('accept offer expired '+tx_hash)
update_tx_dict(tx_hash, payment_expired=True, color='bgc-expired', \
icon_text='Payment expired', formatted_amount_bought='0.0', status='Expired')
# update the sell side for expired payment
if a.has_key('sell_offer_txid'):
# get sell transaction details
sell_tx_hash=a['sell_offer_txid']
sell_tx=tx_dict[sell_tx_hash][-1]
amount_available=float(sell_tx['formatted_amount_available'])
# amount available grows when an accept expires
updated_amount_available=float(amount_available)+float(amount_accepted)
formatted_updated_amount_available=formatted_decimal(updated_amount_available)
debug('update sell transaction '+sell_tx_hash+' and address '+sell_tx['from_address']+ \
' with amount available '+str(updated_amount_available)+' after payment expired')
# update sell transaction - amount_available increases
update_tx_dict(sell_tx_hash, amount_available=updated_amount_available, \
formatted_amount_available=formatted_updated_amount_available)
# check if sell offer got updated for later updates
try:
sell_tx_updated_by=sell_tx['updated_by']
if sell_tx_updated_by == None or sell_tx_updated_by == 'unknown':
sell_tx_updated=False
else:
sell_tx_updated=True
except KeyError:
sell_tx_updated=False
# heavy debug
debug_address(a['from_address'], a['currency_str'], 'before alarm expired')
debug_address(a['to_address'], a['currency_str'], 'before alarm expired')
# update buyer address - accept decreases
update_addr_dict(a['from_address'], True, a['currency_str'], accept=-to_satoshi(amount_accepted))
# if sell offer got updated during the accept, drop the reserved due to that accept
current_sell_tx=addr_dict[a['to_address']][a['currency_str']]['offer_tx'][-1]
if sell_tx['tx_hash'] != current_sell_tx['tx_hash']:
# update seller address - offer change isn't relevant to current sell offer.
# reserved moves to balance.
# but only if sell tx did not get upated
if not sell_tx_updated:
update_addr_dict(a['to_address'], True, a['currency_str'], reserved=-to_satoshi(amount_accepted), \
balance=to_satoshi(amount_accepted))
else:
update_addr_dict(a['to_address'], True, a['currency_str'], balance=to_satoshi(amount_accepted))
debug('skip updating reserved on '+a['to_address']+' as payment expired and it got already updated')
else:
# update seller address - offer increases (reserved stays)
update_addr_dict(a['to_address'], True, a['currency_str'], offer=to_satoshi(amount_accepted))
# heavy debug
debug_address(a['from_address'], a['currency_str'], 'after alarm expired')
debug_address(a['to_address'], a['currency_str'], 'after alarm expired')
# update icon colors of sell
try:
# depracated
if sell_tx['updated_by'] != None:
update_tx_dict(sell_tx['tx_hash'], icon_text='Depracated sell offer', color='bgc-expired')
except KeyError:
# back to new
if updated_amount_available == amount:
update_tx_dict(sell_tx['tx_hash'], color='bgc-new', icon_text='Sell offer')
else:
if updated_amount_available == 0:
# fully accepted
update_tx_dict(sell_tx['tx_hash'], color='bgc-accepted', icon_text='Sell offer accepted')
else:
# partially accepted
update_tx_dict(sell_tx['tx_hash'], color='bgc-new-accepted', icon_text='Sell offer partially accepted')
else:
info('BUG: remove alarm for accept without sell_offer_txid '+a['tx_hash'])
# no need to check this accept any more, but leave on alarms dict
debug('checked alarm for expired '+tx_hash)
else:
debug('accept offer '+tx_hash+' was already paid with '+a['btc_offer_txid'])
# update left over accept on buyer side
left_over_accept=amount_accepted-amount_bought
debug('reduce left over accept from buyer accept value due to accept expire of '+tx_hash)
update_addr_dict(a['from_address'], True, a['currency_str'], accept=-to_satoshi(left_over_accept))
def check_bitcoin_payment(t):
if t['invalid']==[True, 'bitcoin payment']:
from_address=t['from_address']
if from_address.find(';') >= 0: # there are multiple inputs
from_address=from_address.split(';')[0] # take the first one
current_block=int(t['block'])
# was there accept from this address to any of the payment addresses?
to_multi_address_and_amount=t['to_address'].split(';')
for address_and_amount in to_multi_address_and_amount:
(address,amount)=address_and_amount.split(':')
if address!=exodus_address:
debug('is that a '+amount+' payment to '+address+' ?')
# check if it fits to a sell offer in address
# first check if msc sell offer exists
sell_offer_tx=None
sell_accept_tx=None
required_btc=0
for c in coins_list: # check for offers of all coins (FIXME: order per birth)
try:
sell_offer_tx_list=addr_dict[address][c]['offer_tx']
except (IndexError,KeyError):
sell_offer_tx_list=[]
reversed_sell_offer_tx_list=list(reversed(sell_offer_tx_list))
for sell_offer_tx in reversed_sell_offer_tx_list:
# any relevant sell offer found?
if sell_offer_tx != None:
debug('found! checking:')
debug('bitcoin payment: '+t['tx_hash'])
debug('for sell offer: '+sell_offer_tx['tx_hash'])
try:
required_btc=float(sell_offer_tx['formatted_bitcoin_amount_desired'])
whole_sell_amount=float(sell_offer_tx['formatted_amount'])
amount_available=float(sell_offer_tx['formatted_amount_available'])
block_time_limit=int(sell_offer_tx['formatted_block_time_limit'])
except KeyError:
info('BUG: sell offer with missing details: '+sell_offer_tx['tx_hash'])
continue
# get the reserved on the sell address
amount_reserved=from_satoshi(addr_dict[address][c]['reserved'])
# now find the relevant accept and verify details (also partial purchase)
try:
sell_accept_tx_list=addr_dict[from_address][c]['accept_tx']
except KeyError:
debug('no accept_tx on '+from_address)
continue
debug('run over sell accept list ...')
for sell_accept_tx in sell_accept_tx_list: # go over all accepts
debug('... check accept '+sell_accept_tx['tx_hash'])
sell_offer_accepted=sell_accept_tx['sell_offer_txid']
if sell_offer_accepted != sell_offer_tx['tx_hash']:
debug('... sell accept is for a different sell offer ('+sell_offer_accepted+')')
continue
accept_buyer=sell_accept_tx['from_address']
payment_sender=from_address
if payment_sender != accept_buyer:
debug('not correct accept since payment sender and accept buyer are different')
continue
accept_seller=sell_accept_tx['to_address']
sell_seller=sell_offer_tx['from_address']
if accept_seller != sell_seller:
debug('not correct accept since accept seller and sell offer seller are different')
continue
# calculate the amount accepted
try:
amount_accepted=float(sell_accept_tx['formatted_amount_accepted'])
except KeyError:
info('BUG: continue to next accept, since no formatted_amount_accepted on '+sell_accept_tx['tx_hash'])
# this was not the right accept
continue
# get the amount bought
try:
amount_bought=float(sell_accept_tx['formatted_amount_bought'])
except KeyError:
amount_bought=0.0
# is accept exhausted?
if amount_accepted == amount_bought:
debug('... skip this accept since it is already fully paid '+sell_accept_tx['tx_hash'])
continue
# now check if block time limit is as required
sell_accept_block=int(sell_accept_tx['block'])
# if sell accept is valid, then fee is OK - no need to re-check
if sell_accept_block+block_time_limit >= current_block:
debug('... payment timing fits ('+str(sell_accept_block)+'+'+str(block_time_limit)+' >= '+str(current_block)+')')
# heavy debug
debug_address(address, c, 'before bitcoin payment')
debug_address(from_address, c, 'before bitcoin payment')
accomulated_payment=0
payments_list=[]
# check if accept got already paid
btc_offer_txid=None
try:
btc_offer_txid=sell_accept_tx['btc_offer_txid']
except KeyError:
pass
debug(btc_offer_txid)
# was there already a payment?
if btc_offer_txid != None and btc_offer_txid != 'unknown':
# there was at least one payment
# let's chain this payment to previous payments
# build the chain of payments
debug('build the chain of payments')
payments_list.append(btc_offer_txid)
# get/set accomulated payment
try:
accomulated_payment=tx_dict[btc_offer_txid][-1]['accomulated_payment']
except (KeyError, IndexError):
# if not accomulated_payment field on btc_offer_txid, then it is the first
info('BUG: no accomulated amount on first bitcoin payment for accept '+sell_accept_tx['tx_hash']+' on '+btc_offer_txid)
break
# running until this payment is in the payments list
while payments_list[-1] != t['tx_hash']:
# take care with endless loop here
# is this payment the last, or are there other previous payments?
next_payment_txid=None
try:
next_payment_txid=tx_dict[payments_list[-1]][-1]['next_payment_txid']
except (KeyError,IndexError):
pass
if next_payment_txid == None or next_payment_txid == 'unknwon':
# This payment is the last one.
# connect it to the chain of payments.
next_payment_txid=t['tx_hash']
debug('adding payment '+next_payment_txid+' to payment chain for accept '+sell_accept_tx['tx_hash'])
payments_list.append(next_payment_txid)
if payments_list[-2] == payments_list[-1]:
info('BUG: loop of payments on last payment in accept '+sell_accept_tx['tx_hash']+'. First is '+btc_offer_txid+' and additional is '+t['tx_hash'])
break
debug('update payment '+payments_list[-2]+' with next payment '+payments_list[-1])
update_tx_dict(payments_list[-2], next_payment_txid=payments_list[-1])
debug('update payment '+payments_list[-1]+' with prev payment '+payments_list[-2])
update_tx_dict(payments_list[-1], prev_payment_txid=payments_list[-2])
# calculate accomulated payment (sum of amounts of all payments for this accept)
try:
accomulated_payment=float(tx_dict[payments_list[-2]][-1]['accomulated_payment'])+float(amount)
except (KeyError, IndexError):
info('BUG: no accomulated amount on later bitcoin payment for accept '+sell_accept_tx['tx_hash']+' on '+payments_list[-2])
break
debug('update accomulated payment to '+str(accomulated_payment))
update_tx_dict(payments_list[-1], accomulated_payment=accomulated_payment)
else:
debug('add payment to the chain '+next_payment_txid)
payments_list.append(next_payment_txid)
# get stored accomulated payment (amount was added on previous run)
try:
accomulated_payment=float(tx_dict[payments_list[-1]][-1]['accomulated_payment'])
except (KeyError,IndexError):
info('BUG: no accomulated amount on stored bitcoin payment for accept '+sell_accept_tx['tx_hash']+' on '+payments_list[-1])
# check for trivial loop, but there can be more complicated loops
try:
if payments_list[-2] == payments_list[-1]:
info('BUG: loop of payments on accept '+sell_accept_tx['tx_hash']+'. First is '+btc_offer_txid+' and additional is '+t['tx_hash'])
break
except IndexError:
pass
# skip to the next payment on the chain
continue
else:
# This is the first payment
update_tx_dict(sell_accept_tx['tx_hash'], btc_offer_txid=t['tx_hash'])
accomulated_payment=float(amount)
update_tx_dict(t['tx_hash'], accomulated_payment=accomulated_payment)
debug('first bitcoin payment '+t['tx_hash']+' for accept '+sell_accept_tx['tx_hash']+' is '+str(accomulated_payment))
part_bought=float(accomulated_payment)/required_btc
amount_closed=min((part_bought*float(whole_sell_amount)+0.0), amount_accepted, amount_reserved)
debug('... amount_accepted is '+str(amount_accepted))
debug('... amount_reserved is '+str(amount_reserved))
debug('... amount_available is '+str(amount_available))
debug('... amount_closed is '+str(amount_closed))
if part_bought>0:
# mark accept as closed if part bought is 100%
if float(amount_closed) < 0:
info('BUG: negative amount closed for accept '+sell_accept_tx['tx_hash'])
if float(accomulated_payment) == float(amount): # first payment
# update seller address - reserved decreases, balance stays, offer updates (decreased at accept).
satoshi_amount_closed=to_satoshi(amount_closed)
satoshi_amount_accepted=to_satoshi(amount_accepted)
satoshi_amount_reserved=to_satoshi(amount_reserved)
# keep reserved at least zero
satoshi_reserved_update=min(satoshi_amount_closed, satoshi_amount_reserved)
update_addr_dict(address, True, c, reserved=-satoshi_reserved_update, sold=satoshi_amount_closed, \
sold_tx=sell_accept_tx, offer=-satoshi_amount_closed+satoshi_amount_accepted)
# update buyer address - balance increases, accept decreases.
update_addr_dict(from_address, True, c, accept=-satoshi_amount_closed, \
balance=satoshi_amount_closed, bought=satoshi_amount_closed, bought_tx=t)
# update sell available (less closed - accepted)
updated_amount_available = float(amount_available) + float(amount_accepted) - float(amount_closed)
if float(updated_amount_available) < 0:
info('BUG: negative updated amount available after '+sell_accept_tx['tx_hash'])
debug('... update sell offer amount available '+formatted_decimal(updated_amount_available)+' at '+sell_offer_tx['tx_hash'])
update_tx_dict(sell_offer_tx['tx_hash'], amount_available=updated_amount_available, \
formatted_amount_available=formatted_decimal(updated_amount_available))
# update sell accept tx (with bitcoin payment etc)
update_tx_dict(sell_accept_tx['tx_hash'], status='Closed', \
payment_done=True, formatted_amount_bought=formatted_decimal(amount_closed), \
color='bgc-done', icon_text='Accept offer paid')
# update sell and accept offer in bitcoin payment
update_tx_dict(t['tx_hash'], sell_offer_txid=sell_offer_tx['tx_hash'], accept_txid=sell_accept_tx['tx_hash'])
# update purchased amount on bitcoin payment
update_tx_dict(t['tx_hash'], formatted_amount=formatted_decimal(amount_closed))
else:
# later payment
debug('additional payment')
additional_payment=amount
additional_part=float(additional_payment)/required_btc
prev_closed=min(((part_bought-additional_part)*float(whole_sell_amount)+0.0), amount_accepted, amount_reserved)
diff_closed=amount_closed-prev_closed
satoshi_diff_closed=to_satoshi(diff_closed)
satoshi_amount_reserved=to_satoshi(amount_reserved)
# keep reserved at least zero
satoshi_reserved_update=min(satoshi_diff_closed, satoshi_amount_reserved)
# update seller address
update_addr_dict(address, True, c, reserved=-satoshi_reserved_update, sold=satoshi_diff_closed, \
offer=-satoshi_diff_closed)
# update buyer address - balance increases, accept decreases.
update_addr_dict(from_address, True, c, accept=-satoshi_diff_closed, \
balance=satoshi_diff_closed, bought=satoshi_diff_closed, bought_tx=t)
# update sell available (less diff_closed)
updated_amount_available = float(amount_available) - float(diff_closed)
if float(updated_amount_available) < 0:
info('BUG: negative updated amount available on later payment '+t['tx_hash'])
debug('... update sell offer amount available '+formatted_decimal(updated_amount_available)+' at '+sell_offer_tx['tx_hash'])
update_tx_dict(sell_offer_tx['tx_hash'], amount_available=updated_amount_available, \
formatted_amount_available=formatted_decimal(updated_amount_available))
# update sell accept tx (only amount bought changed)
update_tx_dict(sell_accept_tx['tx_hash'], formatted_amount_bought=formatted_decimal(amount_closed))
# update sell and accept offer in bitcoin payment
update_tx_dict(t['tx_hash'], sell_offer_txid=sell_offer_tx['tx_hash'], accept_txid=sell_accept_tx['tx_hash'])
# update purchased amount on bitcoin payment
update_tx_dict(t['tx_hash'], formatted_amount=formatted_decimal(diff_closed))
# update coin stats
try:
update_coin_stats_dict(c, False, previous_last_price=coin_stats_dict[c]['last_price'])
except KeyError:
debug('not yet last_price')
update_coin_stats_dict(c, False, last_price=sell_offer_tx['formatted_price_per_coin'])
update_coin_stats_dict(c, True, total_sold=formatted_decimal(amount_closed), total_paid=accomulated_payment)
# if accept fully paid - close accept
if part_bought >= 1.0:
debug('... 100% paid accept '+sell_accept_tx['tx_hash']+'. closing accept for payments. remove alarm.')
# remove alarm for accept
remove_alarm(sell_accept_tx['tx_hash'])
# if not more left in the offer (and it is not updated) - close sell
sell_tx_updated=False
try:
if tx_dict[sell_offer_tx['tx_hash']][-1]['updated_by'] != None and tx_dict[sell_offer_tx['tx_hash']][-1]['updated_by'] != "unknown":
sell_tx_updated=True
except KeyError: # sell tx was not updated
pass
if not sell_tx_updated:
if addr_dict[address][c]['offer'] == 0:
debug('... sell offer closed for '+address)
update_tx_dict(sell_offer_tx['tx_hash'], color='bgc-done', icon_text='Sell offer done')
# remove alarm for accept
debug('remove alarm for paid '+sell_accept_tx['tx_hash'])
remove_alarm(sell_accept_tx['tx_hash'])
else:
debug('... sell offer is still open on '+address)
update_tx_dict(sell_offer_tx['tx_hash'], color='bgc-accepted-done', icon_text='Sell offer partially done')
else:
debug('skip updating an updated sell offer on '+address)
# remove alarm for accept
debug('remove alarm for updated sell offer for paid '+sell_accept_tx['tx_hash'])
remove_alarm(sell_accept_tx['tx_hash'])
# heavy debug
debug_address(address, c, 'after bitcoin payment')
debug_address(from_address, c, 'after bitcoin payment')
return True # hidden assumption: payment is for a single accept
else:
info('BUG: non positive part bought on bitcoin payment: '+t['tx_hash'])
else:
debug('payment does not fit to accept: '+sell_accept_tx['tx_hash'])
return False
# A fresh initialized address entry
def new_addr_entry():
entry={}
# for each currency
for c in coins_list+['Bitcoin']:
currency_dict={}
# initialize all properties
for property in addr_properties:
if property.endswith('_tx'):
currency_dict[property]=[]
else:
currency_dict[property]=0
entry[c]=currency_dict
entry['exodus']={'bought':0}
return entry
# update the coins statistics database
# example call:
# update_coin_stats_dict(coin, True, last_price=1.0)
# accomulate True means add on top of previous values
# accomulate False means replace previous values
def update_coin_stats_dict(coin, accomulate, *arguments, **keywords):
# coin is first arg
# accomulate is seccond arg
# then come the keywords and values to be modified
# is there already entry for this tx_hash?
if not coin_stats_dict.has_key(coin):
# no - so create a new one
# remark: loading all tx for that tx_hash
coin_stats_dict[coin]={'total_paid':0.0, 'total_sold':0.0, 'last_price':0.0}
# update all given fields with new values
keys = sorted(keywords.keys())
# allow only keys from coin_stats_properties
for kw in keys:
try:
prop_index=coin_stats_properties.index(kw)
except ValueError:
info('BUG: unsupported property of coin stats: '+kw)
return False
if accomulate:
coin_stats_dict[coin][kw]+=float(keywords[kw])
else:
coin_stats_dict[coin][kw]=float(keywords[kw])
return True
# update the main tx database
# example call:
# update_tx_dict(tx_hash, icon='simplesend', color='bgc_done')
def update_tx_dict(tx_hash, *arguments, **keywords):
# tx_hash is first arg
# then come the keywords and values to be modified
# is there already entry for this tx_hash?
if not tx_dict.has_key(tx_hash):
# no - so create a new one
# remark: loading all tx for that tx_hash
# for simplesend which is exodus, the last one is simplesend (#1)
tx_dict[tx_hash]=load_dict_from_file('tx/'+tx_hash+'.json', all_list=True)
# the last tx on the list is the one to modify
n=-1
# get the update_fs from tx_dict for that tx
if tx_dict[tx_hash][n].has_key('update_fs'):
update_fs=tx_dict[tx_hash][n]['update_fs']
else:
# start with default "no need to update fs"
tx_dict[tx_hash][n]['update_fs']=False
update_fs=False
# update all given fields with new values
keys = sorted(keywords.keys())
# allow only keys from tx_properties
for kw in keys:
try:
prop_index=tx_properties.index(kw)
except ValueError:
info('BUG: unsupported property of tx: '+kw)
return False
# set update_fs flag if necessary (if something really changed)
try:
update_fs = tx_dict[tx_hash][n][kw]!=keywords[kw] or update_fs
except KeyError:
update_fs = True
tx_dict[tx_hash][n][kw]=keywords[kw]
tx_dict[tx_hash][n]['update_fs']=update_fs
return True
def is_valid_currency(name):
try:
if coins_list.index(name)>=0:
return True
except ValueError:
return False
# debug dump of address values
def debug_address(addr,c, message="-"):
if msc_globals.heavy_debug == True:
debug('######## '+str(addr)+' '+str(c)+' '+str(message)+' >>>>>>>>')
try:
d=addr_dict[addr][c]
except KeyError:
debug('address does not exist in database')
debug('>>>>>>>> '+str(addr)+' '+str(c)+' '+str(message)+' ########')
return False
debug('balance: '+str(d['balance']))
debug('reserved: '+str(d['reserved']))
debug('offer: '+str(d['offer']))
debug('accept: '+str(d['accept']))
debug('bought: '+str(d['bought']))
debug('sold: '+str(d['sold']))
debug('sent: '+str(d['sent']))
debug('received: '+str(d['received']))
debug('>>>>>>>> '+str(addr)+' '+str(c)+' '+str(message)+' ########')
# update the main address database
# example call:
# update_addr_dict('1address', True, 'Mastercoin', balance=10, bought=2, bought_tx=t)
# accomulate True means add on top of previous values
# accomulate False means replace previous values
def update_addr_dict(addr, accomulate, *arguments, **keywords):
# update specific currency fields within address
# address is first arg
# accomulate is seccond arg
# currency is third arg:
# 'Mastercoin', 'Test Mastercoin', 'Bitcoin' or 'exodus' for exodus purchases
# then come the keywords and values to be updated
c=arguments[0]
if not is_valid_currency(name):
info('BUG: update_addr_dict called with unsupported currency: '+c)
return False
# is there already entry for this address?
if not addr_dict.has_key(addr):
# no - so create a new one
addr_dict[addr]=new_addr_entry()
# update all given fields with new values
keys = sorted(keywords.keys())
# allow only keys from addr_properties
for kw in keys:
try:
prop_index=addr_properties.index(kw)
except ValueError:
info('unsupported property of addr: '+kw)
return False
if accomulate == True: # just add the tx or value
if kw.endswith('_tx'):
addr_dict[addr][c][kw].append(keywords[kw])
else: # values are in satoshi
addr_dict[addr][c][kw]+=int(keywords[kw])
if addr_dict[addr][c][kw]<0:
# exodus address keeps only the expenses, and calculates dynamic balance on demand
if addr != exodus_address:
info('BUG: field '+kw+' on accomulated '+addr+' has '+str(addr_dict[addr][c][kw]))
return False
else:
if kw.endswith('_tx'): # replace the tx or value
addr_dict[addr][c][kw]=[keywords[kw]]
else: # values are in satoshi
addr_dict[addr][c][kw]=int(keywords[kw])
if addr_dict[addr][c][kw]<0:
# exodus address keeps only the expenses, and calculates dynamic balance on demand
if addr != exodus_address:
info('BUG: field '+kw+' on '+addr+' has '+str(addr_dict[addr][c][kw]))
return False
return True
def update_initial_icon_details(t):
# update fields icon, details
update_tx_dict(t['tx_hash'], color='bgc-new')
try:
if t['transactionType']=='0000':
update_tx_dict(t['tx_hash'], icon='simplesend', details=t['to_address'])
else:
if t['transactionType']=='0014':
update_tx_dict(t['tx_hash'], icon='selloffer', details=t['formatted_price_per_coin'])
else:
if t['transactionType']=='0016':
update_tx_dict(t['tx_hash'], icon='sellaccept', details='unknown_price')
else:
update_tx_dict(t['tx_hash'], icon='unknown', details='unknown')
except KeyError as e:
# The only *valid* mastercoin tx without transactionType is exodus and mint
try:
tx_type_str=t['tx_type_str']
except KeyError:
info('BUG: no tx_type_str field on '+t['tx_hash'])
tx_type_str='unknown'
if t['tx_type_str']=='exodus' or t['tx_type_str']=='mint':
try:
update_tx_dict(t['tx_hash'], icon='exodus', details=t['to_address'])
except KeyError:
info('BUG: exodus tx with no to_address: '+str(t))
return False
else:
info('BUG: non exodus/mint valid msc tx without '+str(e)+' ('+t['tx_type_str']+') on '+tx_hash)
return False
return True
def mark_tx_invalid(tx_hash, reason):
# mark tx as invalid
update_tx_dict(tx_hash, invalid=(True,reason), color='bgc-invalid')
# add another sell tx to the modified dict
def add_offers(key, t):
if offers_dict.has_key(key):
offers_dict[key].append(t['tx_hash'])
else:
offers_dict[key]=[t['tx_hash']]
# write back to fs all tx which got modified
def write_back_modified_tx():
n=-1 # relevant is last tx on the list
for k in tx_dict.keys():
if tx_dict[k][n]['update_fs'] == True:
# remove update fs marker
del tx_dict[k][n]['update_fs']
# save back to filesystem
atomic_json_dump(tx_dict[k], 'tx/'+k+'.json', add_brackets=False)
# create offers json
def update_offers():
for tx_hash in offers_dict.keys():
# generate tx list for each tx_hash
offers=[]
for b_hash in offers_dict[tx_hash]:
offers.append(tx_dict[b_hash][-1])
# write updated offers
atomic_json_dump(offers, 'offers/offers-'+tx_hash+'.json', add_brackets=False)
def update_bitcoin_balances():
if msc_globals.b == True:
# skip balance retrieval
info('skip balance retrieval')
return
chunk=100
addresses=addr_dict.keys()
# load general/address_btc_balance.json
# get the list of missing addresses
# get balances for the missing
# update back general/address_btc_balance.json
# on the next block, update all addresses (optimize to update according to tx on that block)
# cut into chunks
for i in range(int(round(len(addresses)/chunk+0.5))):
addr_batch=addresses[i*chunk:(i+1)*chunk]
# create the string of all addresses
addr_batch_str=''
for a in addr_batch:
if a != "unknown":
addr_batch_str=addr_batch_str+a+' '
# get the balances
balances=get_balance(addr_batch_str)
# update addr_dict with bitcoin balance
for b in balances:
update_addr_dict(b['address'], False, 'Bitcoin', balance=b['pending'])
def add_mchain_donators_addresses():
# load 1Mchain donators list
mchain_donors_list=load_dict_from_file('general/mchain_donors.json', skip_error=True)
special_addr_list=[]
for donor in mchain_donors_list:
if donor['value'] >= 0.001:
special_addr_list.append(donor['address'])
debug('adding mchain donor addresses '+str(special_addr_list))
# for each address, if not in addr_dict, add empty entry
for addr in special_addr_list:
if not addr_dict.has_key(addr):
debug('add mchain donor: '+addr)
update_addr_dict(addr, False, 'Bitcoin', 0.0)
def add_manual_addresses():
manual_addresses_list=load_dict_from_file('general/manual_addresses.json', skip_error=True)
special_addr_list=[]
for man in manual_addresses_list:
special_addr_list.append(man['address'])
debug('adding manual addresses '+str(special_addr_list))
# for each address, if not in addr_dict, add empty entry
for addr in special_addr_list:
if not addr_dict.has_key(addr):
debug('add manual address: '+addr)
update_addr_dict(addr, False, 'Bitcoin', 0.0)
# generate api json
# address
# general files (10 in a page)
# mastercoin_verify
def generate_api_jsons():
# prepare updated snapshot of bitcoin balances for all addresses
update_bitcoin_balances()
# create file for each address
for addr in addr_dict.keys():
balances_list=[]
addr_dict_api={}
addr_dict_api['address']=addr
for c in coins_list:
sub_dict={}
sub_dict['received_transactions']=addr_dict[addr][c]['in_tx']
sub_dict['received_transactions'].reverse()
sub_dict['sent_transactions']=addr_dict[addr][c]['out_tx']
sub_dict['sent_transactions'].reverse()
sub_dict['bought_transactions']=addr_dict[addr][c]['bought_tx']
sub_dict['bought_transactions'].reverse()
sub_dict['sold_transactions']=addr_dict[addr][c]['sold_tx']
sub_dict['sold_transactions'].reverse()
sub_dict['offer_transactions']=addr_dict[addr][c]['offer_tx']
sub_dict['offer_transactions'].reverse()
sub_dict['accept_transactions']=addr_dict[addr][c]['accept_tx']
sub_dict['accept_transactions'].reverse()
sub_dict['total_received']=from_satoshi(addr_dict[addr][c]['received'])
sub_dict['total_sent']=from_satoshi(addr_dict[addr][c]['sent'])
sub_dict['total_sold']=from_satoshi(addr_dict[addr][c]['sold'])
sub_dict['total_bought']=from_satoshi(addr_dict[addr][c]['bought'])
sub_dict['total_sell_accept']=from_satoshi(addr_dict[addr][c]['accept'])
sub_dict['total_sell_offer']=from_satoshi(addr_dict[addr][c]['offer'])
if addr==exodus_address: # This is only for Mastercoin
available_reward=get_available_reward(last_height, c)
sub_dict['balance']=from_satoshi(available_reward+addr_dict[addr][c]['balance'])
else:
sub_dict['balance']=from_satoshi(addr_dict[addr][c]['balance'])
sub_dict['total_reserved']=from_satoshi(addr_dict[addr][c]['reserved'])
sub_dict['exodus_transactions']=addr_dict[addr][c]['exodus_tx']
sub_dict['exodus_transactions'].reverse()
sub_dict['total_exodus']=from_satoshi(addr_dict[addr]['exodus']['bought'])
balances_list.append({"symbol":currencies_per_name_dict[c]['symbol'],"value":sub_dict['balance']})
addr_dict_api[coins_dict[c]]=sub_dict
addr_dict_api['balance']=balances_list
atomic_json_dump(addr_dict_api, 'addr/'+addr+'.json', add_brackets=False)
# create files for msc and files for test_msc
for k in tx_dict.keys():
# take all tx list for this txid
for t in tx_dict[k]:
if t['invalid'] != False:
continue
if t['tx_type_str']=='exodus':
sorted_currency_tx_list['Mastercoin'].append(t)
else:
try:
sorted_currency_tx_list[t['currency_str']].append(t)
except KeyError: # unknown currency
pass
# and reverse sort
for c in coins_list:
sorted_currency_tx_list[c]=sorted(sorted_currency_tx_list[c], \
key=lambda k: (-int(k['block']),-int(k['index'])))
chunk=10
# create the latest transactions pages
pages={}
sell_pages={}
accept_pages={}
for c in coins_list:
pages[c]=0
sell_pages[c]=0
accept_pages[c]=0
for c in coins_list:
for i in range(int(round(len(sorted_currency_tx_list[c])/chunk+0.5))):
atomic_json_dump(sorted_currency_tx_list[c][i*chunk:(i+1)*chunk], \
'general/'+currencies_per_name_dict[c]['symbol']+'_'+'{0:04}'.format(i+1)+'.json', add_brackets=False)
pages[c]+=1
# create the latest sell and accept transactions page
for c in coins_list:
for t in sorted_currency_tx_list[c]:
if t['tx_type_str']=='Sell offer':
sorted_currency_sell_tx_list[c].append(t)
if t['tx_type_str']=='Sell accept':
sorted_currency_accept_tx_list[c].append(t)
# sort sells according to price
for c in coins_list:
sorted_currency_sell_tx_list[c]=sorted(sorted_currency_sell_tx_list[c], \
key=lambda k: float(k['formatted_price_per_coin']))
# filter the closed sell offers
try:
filtered_tx_list[c] = [t for t in sorted_currency_sell_tx_list[c] \
if t['icon_text'] != 'Sell offer done' and t['icon_text'] != 'Depracated sell offer' and \
t['icon_text'] != 'Cancel request' and t['icon_text'] != 'Sell offer cancelled']
except KeyError:
error('tx without icon_text '+t['tx_hash'])
sorted_currency_sell_tx_list[c] = filtered_tx_list[c]
for c in coins_list:
for i in range(int(round(len(sorted_currency_sell_tx_list[c])/chunk+0.5))):
atomic_json_dump(sorted_currency_sell_tx_list[c][i*chunk:(i+1)*chunk], \
'general/'+currencies_per_name_dict[c]['symbol']+'_sell_'+'{0:04}'.format(i+1)+'.json', add_brackets=False)
sell_pages[c]+=1
for i in range(int(round(len(sorted_currency_accept_tx_list[c])/chunk+0.5))):
atomic_json_dump(sorted_currency_accept_tx_list[c][i*chunk:(i+1)*chunk], \
'general/'+currencies_per_name_dict[c]['symbol']+'_accept_'+'{0:04}'.format(i+1)+'.json', add_brackets=False)
accept_pages[c]+=1
sorted_coins_list=coins_list[:] # real copy
# FIXME: sort by theoretically paid
# enforce Mastercoin to be the first
sorted_coins_list.remove("Mastercoin")
sorted_coins_list.insert(0, "Mastercoin")
info(coins_list)
info(sorted_coins_list)
# update values.json
values_list=[]
for c in sorted_coins_list:
if not c.startswith("Test ") and not c == "Bitcoin":
trend="flat"
trend2="rgb(200,200,200)"
try:
if coin_stats_dict[c]['last_price'] > coin_stats_dict[c]['previous_last_price']:
trend="up"
trend2="rgb(13,157,51)"
else:
if coin_stats_dict[c]['last_price'] < coin_stats_dict[c]['previous_last_price']:
trend="down"
trend2="rgb(212,48,48)"
except KeyError:
debug('no last_price or previous_last_price')
values_list.append({"currency": currencies_per_name_dict[c]['symbol'], "name": c, "name2": "", "pages": 1, "trend": trend, "trend2": trend2})
updated_values_list=[]
for v in values_list:
v['pages']=pages[v['name']]
v['accept_pages']=accept_pages[v['name']]