forked from ponponpain/nembex-v3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnemdb.py
1502 lines (1297 loc) · 51.8 KB
/
nemdb.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
import psycopg2
from datetime import datetime
from binascii import hexlify
from psycopg2.extras import RealDictConnection
from config import config
from collections import *
def tobin(x):
return bytearray(x.decode('hex'))
class Db:
def __init__(self, retDict=False):
if retDict:
self.conn = RealDictConnection(config.connection_string)
else:
self.conn = psycopg2.connect(config.connection_string)
self.createTables()
def commit(self):
self.conn.commit()
def accounts(self, fun):
cur = self.conn.cursor()
cur.execute("SELECT * FROM accounts")
for r in cur:
fun(r)
cur.close()
def delegations(self, fun):
cur = self.conn.cursor()
cur.execute("SELECT block_height,signer_id,remote_id,mode FROM delegates")
for r in cur:
fun({'block_height':r[0],'signer_id':r[1],'remote_id':r[2],'mode':r[3]})
cur.close()
def createNamespaceTables(self, cur):
cur.execute("""
CREATE TABLE IF NOT EXISTS namespaces
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
rental_sink BIGINT REFERENCES accounts(id),
rental_fee BIGINT NOT NULL,
parent_ns BIGINT,
namespace_name VARCHAR(148),
namespace_part VARCHAR(66)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaics
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
creation_sink BIGINT REFERENCES accounts(id),
creation_fee BIGINT NOT NULL,
parent_ns BIGINT REFERENCES namespaces(id),
mosaic_name VARCHAR(34),
mosaic_fqdn VARCHAR(180),
mosaic_description VARCHAR(516)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_levys
(id BIGSERIAL PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
mosaic_id BIGINT REFERENCES mosaics(id),
type INT NOT NULL,
recipient_id BIGINT REFERENCES accounts(id),
fee_mosaic_id BIGINT REFERENCES mosaics(id),
fee BIGINT NOT NULL
)""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_properties
(id BIGSERIAL PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
mosaic_id BIGINT REFERENCES mosaics(id),
name VARCHAR(64),
value VARCHAR(64)
)""")
cur.execute("""
CREATE TABLE IF NOT EXISTS transfer_attachments
(id BIGSERIAL PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
transfer_id BIGINT REFERENCES transfers(id),
type INT REFERENCES inouts_type(id),
mosaic_id BIGINT REFERENCES mosaics(id),
quantity BIGINT NOT NULL
)""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_inouts
(id BIGSERIAL PRIMARY KEY,
account_id BIGINT REFERENCES accounts(id),
block_height BIGINT REFERENCES blocks(height),
mosaic_id BIGINT REFERENCES mosaics(id),
type INT REFERENCES inouts_type(id),
tx_id BIGSERIAL,
quantity BIGINT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_amounts
(id BIGSERIAL PRIMARY KEY,
account_id BIGINT REFERENCES accounts(id),
block_height BIGINT REFERENCES blocks(height),
mosaic_id BIGINT REFERENCES mosaics(id),
amount BIGINT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_state_supply
(id BIGSERIAL PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
mosaic_id BIGINT REFERENCES mosaics(id),
quantity BIGINT
)""")
# block heights indexes
cur.execute("CREATE INDEX namespaces_blockheight_idx ON namespaces(block_height)");
cur.execute("CREATE INDEX mosaics_blockheight_idx ON mosaics(block_height)");
cur.execute('CREATE INDEX mosaic_levys_blockheight_idx ON mosaic_levys(block_height)')
cur.execute('CREATE INDEX mosaic_properties_blockheight_idx ON mosaic_properties(block_height)')
cur.execute('CREATE INDEX mosaic_inouts_blockheight_idx ON mosaic_inouts(block_height)')
cur.execute('CREATE INDEX mosaic_amounts_blockheight_idx ON mosaic_amounts(block_height)')
cur.execute('CREATE INDEX mosaic_state_supply_blockheight_idx ON mosaic_state_supply(block_height)')
cur.execute("CREATE INDEX mosaic_levys_mosaic_idx ON mosaic_levys(mosaic_id)");
cur.execute("CREATE INDEX mosaic_properties_mosaic_idx ON mosaic_properties(mosaic_id)");
cur.execute("CREATE INDEX transfer_attachments_blockheight_idx ON transfer_attachments(block_height)");
cur.execute('CREATE INDEX inouts_blockheight_idx ON inouts(block_height)')
cur.execute('CREATE INDEX inouts_account_id_idx ON inouts(account_id)')
cur.execute('CREATE INDEX inouts_account_id_3_idx ON inouts(account_id) WHERE type = 3')
cur.execute('CREATE INDEX harvests_blockheight_idx ON harvests(block_height)')
cur.execute('CREATE INDEX harvests_account_id_idx ON harvests(account_id)')
cur.execute("CREATE INDEX transfer_attachments_mosaic_idx ON transfer_attachments(mosaic_id)");
cur.execute("CREATE INDEX transfer_attachments_transfer_idx ON transfer_attachments(transfer_id)");
cur.execute("CREATE INDEX mosaic_inouts_type_idx on mosaic_inouts(type)");
cur.execute("select * from accounts where printablekey = '%s'" % config.nemesis);
nId = cur.fetchone()[0]
NA = bytearray('n/a')
cur.execute("INSERT INTO namespaces (block_height, hash, timestamp, timestamp_unix, timestamp_nem, signer_id, signature, deadline, fee, rental_sink, rental_fee, parent_ns, namespace_name, namespace_part) VALUES (%s,%s, %s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s) RETURNING id", (1,NA, '2015-03-29 00:06:25',1427587585,0,nId,NA,0, 0,nId,0,None,"nem","nem"))
nsId = cur.fetchone()[0]
print "NEM namespace ID: ", nsId
cur.execute("INSERT INTO mosaics (block_height, hash, timestamp, timestamp_unix, timestamp_nem, signer_id, signature, deadline, fee, creation_sink, creation_fee, parent_ns, mosaic_name, mosaic_fqdn, mosaic_description) VALUES (%s,%s, %s,%s,%s,%s,%s,%s, %s,%s,%s, %s,%s,%s,%s) RETURNING id", (1,NA, '2015-03-29 00:06:25',1427587585,0,nId,NA,0, 0,nId,0, nsId,"nem.xem","nem.xem", "Mosaic representing XEM"))
msId = cur.fetchone()[0]
print "NEM.XEM mosaic ID: ", msId
cur.execute("INSERT INTO mosaic_state_supply (block_height, mosaic_id, quantity) VALUES (1, %s, 8999999999000000)", (msId,))
cur.executemany("INSERT INTO mosaic_properties (block_height,mosaic_id,name,value) VALUES (%s,%s, %s,%s)",
((1,msId, 'divisibility', "6"),
(1,msId, 'initialSupply', "8999999999"),
(1,msId, 'mutableSupply', "0"),
(1,msId, 'transferable', "0")))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (11, 'levy incoming'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (12, 'levy outgoing'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (14, 'levy incoming multisig'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (15, 'levy outgoing multisig'))
def createSupplies(self, cur):
cur.execute("""
CREATE TABLE IF NOT EXISTS mosaic_supplies
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
mosaic_id BIGINT REFERENCES mosaics(id),
supply_type INT NOT NULL,
delta BIGINT NOT NULL
)""")
cur.execute("CREATE INDEX mosaic_supplies_blockheight_idx ON mosaic_supplies(block_height)");
def createTables(self):
cur = self.conn.cursor()
cur.execute("""
SELECT 0 FROM pg_class where relname = 'common_transactions_seq_id'
""")
result = cur.fetchone()
if result is None:
cur.execute(" CREATE SEQUENCE common_transactions_seq_id;")
cur.execute("""
CREATE TABLE IF NOT EXISTS accounts
(id BIGSERIAL PRIMARY KEY,
printablekey varchar UNIQUE,
publickey bytea)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS blocks
(height BIGINT PRIMARY KEY,
hash bytea NOT NULL,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id bigint REFERENCES accounts(id),
signature bytea NOT NULL,
type int NOT NULL,
difficulty bigint NOT NULL,
tx_count int NOT NULL,
fees bigint NOT NULL
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS transfers
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
recipient_id BIGINT REFERENCES accounts(id),
amount BIGINT NOT NULL,
fee BIGINT NOT NULL,
message_type int,
message_data bytea
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS modifications
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
min_cosignatories INT)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS modification_entries
(id BIGSERIAL PRIMARY KEY,
modification_id BIGINT REFERENCES modifications(id),
type int NOT NULL,
cosignatory_id BIGINT REFERENCES accounts(id)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS delegates
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
remote_id BIGINT REFERENCES accounts(id),
fee BIGINT NOT NULL,
mode int NOT NULL
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS multisigs
(id BIGINT DEFAULT nextval('common_transactions_seq_id') PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL UNIQUE,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
total_fees BIGINT NOT NULL,
signatures_count INT NOT NULL,
inner_id BIGINT NOT NULL,
inner_type INT NOT NULL
)
""")
# we don't need common seq id in this one
cur.execute("""
CREATE TABLE IF NOT EXISTS signatures
(id BIGSERIAL PRIMARY KEY,
block_height BIGINT REFERENCES blocks(height),
hash bytea NOT NULL,
timestamp varchar NOT NULL,
timestamp_unix BIGINT NOT NULL,
timestamp_nem BIGINT NOT NULL,
signer_id BIGINT REFERENCES accounts(id),
signature bytea,
deadline BIGINT NOT NULL,
fee BIGINT NOT NULL,
multisig_id BIGINT REFERENCES multisigs(id)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS inouts_type
(id INT PRIMARY KEY,
name VARCHAR NOT NULL
)
""")
cur.execute("SELECT count(id) FROM inouts_type");
ret = cur.fetchone()[0]
if ret == 0:
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (1, 'incoming'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (2, 'outgoing + fees'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (3, 'harvesting'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (4, 'incoming multisig'))
cur.execute("INSERT INTO inouts_type VALUES (%s,%s)", (5, 'outgoing multisig + fees'))
cur.execute("""
CREATE TABLE IF NOT EXISTS inouts
(id BIGSERIAL PRIMARY KEY,
account_id BIGINT REFERENCES accounts(id),
block_height BIGINT REFERENCES blocks(height),
type INT REFERENCES inouts_type(id),
tx_id BIGSERIAL,
amount BIGINT
)
""")
if ret == 0:
cur.execute("CREATE INDEX inouts_type_idx on inouts(type)");
cur.execute("CREATE INDEX transfers_blockheight_idx ON transfers(block_height)");
cur.execute("CREATE INDEX modifications_blockheight_idx ON modifications(block_height)");
cur.execute("CREATE INDEX delegates_blockheight_idx ON delegates(block_height)");
cur.execute("CREATE INDEX multisigs_blockheight_idx ON multisigs(block_height)");
cur.execute("CREATE INDEX signatures_blockheight_idx ON signatures(block_height)");
cur.execute("""
CREATE TABLE IF NOT EXISTS harvests
(id BIGSERIAL PRIMARY KEY,
account_id BIGINT REFERENCES accounts(id),
block_height BIGINT REFERENCES blocks(height)
)
""")
cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('namespaces',))
hasNamespaces = cur.fetchone()[0]
if not hasNamespaces:
self.createNamespaceTables(cur)
cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mosaic_supplies',))
hasSupplies = cur.fetchone()[0]
if not hasSupplies:
self.createSupplies(cur)
cur.close()
self.conn.commit()
def _addHarvested(self, cur, account_id, height):
sql = "INSERT INTO harvests (account_id,block_height) VALUES (%s,%s)";
obj = (account_id, height)
cur.execute(sql, obj)
def _addInout(self, cur, account_id, height, inout_type, tx_id, amount):
sql = "INSERT INTO inouts (account_id,block_height,type,tx_id,amount) VALUES (%s,%s,%s,%s,%s)";
obj = (account_id, height, inout_type, tx_id, amount)
cur.execute(sql, obj)
def _clearMosInouts(self, cur, mosDbId):
sql = "DELETE FROM mosaic_inouts where mosaic_id=%s"
cur.execute(sql, (mosDbId,))
sql = "DELETE FROM mosaic_amounts WHERE mosaic_id=%s"
cur.execute(sql, (mosDbId,))
def _getPreviousAmount(self, cur, mosDbId, account_id):
sql = "SELECT amount,block_height,id FROM mosaic_amounts WHERE mosaic_id=%s AND account_id=%s ORDER BY block_height DESC LIMIT 1"
obj = (mosDbId, account_id)
cur.execute(sql, obj)
return cur.fetchone()
def _addMosInout(self, cur, mosDbId, account_id, height, inout_type, tx_id, amount):
sql = "INSERT INTO mosaic_inouts (account_id,block_height,mosaic_id, type,tx_id,quantity) VALUES (%s,%s,%s, %s,%s,%s)";
obj = (account_id, height, mosDbId, inout_type, tx_id, amount)
cur.execute(sql, obj)
ret = self._getPreviousAmount(cur, mosDbId, account_id)
val = ret[0] if ret else 0
if inout_type in [1, 1+3, 11, 11+3]:
val += amount
elif inout_type in [2, 2+3, 12, 12+3]:
val -= amount
else:
print inout_type
raise 1
# nembex is not running postgres 9.5, so we can't take advantage of UPSERT
# but since update is running from a single process we're fine
if ret and ret[1] == height:
#print "need to update instead of insert",ret[2]
sql = "UPDATE mosaic_amounts SET amount=%s WHERE id=%s"
obj = (val, ret[2])
else:
sql = "INSERT INTO mosaic_amounts (account_id,block_height,mosaic_id, amount) VALUES (%s,%s,%s, %s)"
obj = (account_id, height, mosDbId, val)
cur.execute(sql, obj)
def addInout(self, account_id, height, inout_type, tx_id, amount):
cur = self.conn.cursor()
if amount > 0:
self._addInout(cur, account_id, height, inout_type, tx_id, amount)
self._addHarvested(cur, account_id, height)
cur.close()
@staticmethod
def _getMosaicFqdn(mosaic):
mId = mosaic['mosaicId']
return mId['namespaceId'] + '.' + mId['name']
def addInouts(self, block, txes):
def inoutTransfer(cur, height, tx, txId, fee, multi):
v = tx['version'] & 0xffffff
srcId = tx['signer_id']
dstId = tx['recipient_id']
if v == 1 or ('mosaics' not in tx):
if srcId == dstId:
self._addInout(cur, srcId, height, 2+multi, txId, fee)
else:
self._addInout(cur, srcId, height, 2+multi, txId, tx['amount']+fee)
self._addInout(cur, dstId, height, 1+multi, txId, tx['amount'])
else:
# amount doesn't mean anything, we need to process attachments
# to check if there is nem.xem, multiply it
print tx
amount = tx['amount'] / 1000000
qs = defaultdict(long)
for mosaic in tx['mosaics']:
mosName = Db._getMosaicFqdn(mosaic)
qs[mosName] += mosaic['quantity']
locdb = Db(True)
loccur = locdb.conn.cursor()
for mosFqdn,_v in qs.iteritems():
v = _v*amount
if mosFqdn == 'nem.xem':
if srcId == dstId:
self._addInout(cur, srcId, height, 2+multi, txId, fee)
else:
self._addInout(cur, srcId, height, 2+multi, txId, v+fee)
self._addInout(cur, dstId, height, 1+multi, txId, v)
else:
mosaic = locdb._getMosaic(loccur, 'mosaic_fqdn', mosFqdn)
mosId = mosaic['id']
self._addMosInout(cur, mosId, srcId, height, 2+multi, txId, v)
self._addMosInout(cur, mosId, dstId, height, 1+multi, txId, v)
if mosaic['levy']:
mosId = mosaic['levy']['fee_mosaic']['id']
dstId = mosaic['levy']['recipient_id']
levyFee = self._calculateLevy(mosaic['levy']['type'], amount, _v, mosaic['levy']['fee'])
#print "LEVY:"
#del mosaic['levy']['fee_mosaic']
#print mosaic['levy']
self._addMosInout(cur, mosId, srcId, height, 12+multi, txId, levyFee)
self._addMosInout(cur, mosId, dstId, height, 11+multi, txId, levyFee)
loccur.close()
def inoutFee(cur, height, tx, txId, fee, multi):
srcId = tx['signer_id']
self._addInout(cur, srcId, height, 2+multi, txId, fee)
def inoutSink(cur, height, tx, txId, fee, multi):
srcId = tx['signer_id']
dstId = tx['rentalFeeSink_id']
self._addInout(cur, srcId, height, 2+multi, txId, tx['rentalFee']+fee)
self._addInout(cur, dstId, height, 1+multi, txId, tx['rentalFee'])
def getPropsMap(tx):
_props = {}
for prop in tx['properties']:
_props[ prop['name'] ] = prop['value']
_props['divisibility'] = int(_props['divisibility'], 10)
_props['initialSupply'] = int(_props['initialSupply'], 10)
return _props
def supplyToValue(props, supply):
mul = 10 ** props['divisibility']
return supply * mul
def inoutSinkMosaic(cur, height, tx, txId, fee, multi):
srcId = tx['signer_id']
dstId = tx['creationFeeSink_id']
self._addInout(cur, srcId, height, 2+multi, txId, tx['creationFee']+fee)
self._addInout(cur, dstId, height, 1+multi, txId, tx['creationFee'])
#print "----"
#print tx
#print "----"
self._clearMosInouts(cur, tx['id'])
_props = getPropsMap(tx['mosaicDefinition'])
v = supplyToValue(_props, _props['initialSupply'])
self._addMosInout(cur, tx['id'], srcId, height, 1+multi, txId, v)
def inoutSupply(cur, height, tx, txId, fee, multi):
srcId = tx['signer_id']
inoutFee(cur, height, tx, txId, fee, multi)
locdb = Db(True)
loccur = locdb.conn.cursor()
mosFqdn = Db._getMosaicFqdn(tx)
mosaic = locdb._getMosaic(loccur, 'mosaic_fqdn', mosFqdn)
loccur.close()
#print mosaic
_props = getPropsMap(mosaic)
v = supplyToValue(_props, tx['delta'])
#print v
if tx['supplyType'] == 1:
self._addMosInout(cur, mosaic['id'], srcId, height, 1+multi, txId, v)
else:
self._addMosInout(cur, mosaic['id'], srcId, height, 2+multi, txId, v)
cur = self.conn.cursor()
handlers = {
257: inoutTransfer # transfer
, 2049: inoutFee # importance
, 4097: inoutFee # multisig
, 8193: inoutSink # namespace
, 16385: inoutSinkMosaic # mosic creation
, 16386: inoutSupply # mosaicSupply
}
blockHeight = block['height']
for tx in txes:
#print tx
txId = tx['id']
txType = tx['type']
fee = tx['fee']
multi = 0
# handle multisig
if txType == 4100:
fee = tx['total_fee']
txType = tx['otherTrans']['type']
tx = tx['otherTrans']
multi = 3
txid = handlers[txType](cur, blockHeight, tx, txId, fee, multi)
cur.close()
def _addMultisig(self, cur, block, tx):
handlers = {
257: self._addTransfer
, 2049: self._addDelegated
, 4097: self._addAggregateModification
, 8193: self._addNamespace
, 16385: self._addMosaic
, 16386: self._addMosaicSupply
}
#inner tx
itx = tx['otherTrans']
if itx['type'] not in handlers:
print "ITX TYPE", itx['type']
innerId = handlers[itx['type']](cur, block, itx)
itx['id'] = innerId
totalFee = tx['total_fee']
#print tx
sql = "INSERT INTO multisigs (block_height,hash,timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline, fee,total_fees,signatures_count,inner_id,inner_type) VALUES (%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s,%s,%s) RETURNING id";
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
tobin(tx['signature']),
tx['deadline'],
tx['fee'],
totalFee,
len(tx['signatures']),
innerId,
itx['type']
)
#print " [+] adding to db: ", obj,
cur.execute(sql, obj)
retId = cur.fetchone()[0]
sql = "INSERT INTO signatures (block_height,hash,timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline, fee,multisig_id) VALUES (%s,%s, %s,%s,%s, %s,%s,%s, %s,%s) RETURNING id";
for sig in tx['signatures']:
obj = (block['height'],
tobin(hexlify("N/A")), #tobin(sig['hash']),
sig['timestamp'],
sig['timestamp_unix'],
sig['timestamp_nem'],
sig['signer_id'],
tobin(sig['signature']),
sig['deadline'],
sig['fee'],
retId
)
cur.execute(sql,obj)
#
return retId
def _addDelegated(self,cur,block,tx):
sql = "INSERT INTO delegates (block_height,hash,timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline, remote_id,fee,mode) VALUES (%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s) RETURNING id";
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['remote_id'],
tx['fee'],
tx['mode']
)
#print " [+] adding to db: ", obj,
cur.execute(sql, obj)
retId = cur.fetchone()[0]
#print retId
return retId
def _addAggregateModification(self, cur, block, tx):
sql = "INSERT INTO modifications (block_height,hash,timestamp,timestamp_unix,timestamp_nem, signer_id, signature,deadline, fee, min_cosignatories) VALUES (%s,%s, %s,%s,%s, %s,%s,%s, %s, %s) RETURNING id";
locdb = Db(True)
ret = locdb.getModification('signer_id', int(tx['signer_id']))
if ('minCosignatories' in tx) and ('relativeChange' in tx['minCosignatories']):
relative = tx['minCosignatories']['relativeChange']
if ret is None:
print "MODIFICATION NO old, rel is", relative, len(tx['modifications'])
min_cosignatories = relative
else:
min_cosignatories = ret['min_cosignatories'] + relative
print "MODIFICATION has old, rel is", relative, " prev ", ret['min_cosignatories']
else:
# old txes...
min_cosignatories = 0
print "MODIFICATION OLD", min_cosignatories
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['fee'],
min_cosignatories
)
#print " [+] adding to db: ", obj,
cur.execute(sql, obj)
retId = cur.fetchone()[0]
#print retId
sql = "INSERT INTO modification_entries (modification_id,type,cosignatory_id) VALUES(%s,%s,%s)"
for modification in tx['modifications']:
obj = (retId, modification['modificationType'], modification['cosignatory_id'])
cur.execute(sql,obj)
#
return retId
def _addNamespace(self, cur, block, tx):
parent = None
if tx['parent']:
locdb = Db(True)
ret = locdb.getNamespace('namespace_name', tx['parent'])
parent = ret
fqdn = (parent['namespace_name'] + '.' if parent else '') + tx['newPart']
sql = "INSERT INTO namespaces (block_height,hash, timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline,fee, rental_sink, rental_fee, parent_ns, namespace_name, namespace_part) VALUES (%s,%s, %s,%s,%s, %s,%s,%s,%s, %s, %s, %s, %s, %s) RETURNING id"
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['fee'],
tx['rentalFeeSink_id'],
tx['rentalFee'],
parent['id'] if parent else None,
fqdn,
tx['newPart']
)
#print " [+] adding to db: ", obj,
cur.execute(sql,obj)
retId = cur.fetchone()[0]
#print retId
return retId
def _addMosaic(self, cur, block, tx):
locdb = Db(True)
ret = locdb.getNamespace('namespace_name', tx['mosaicDefinition']['id']['namespaceId'])
parent = ret
sql = "INSERT INTO mosaics (block_height,hash, timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline,fee, creation_sink, creation_fee, parent_ns, mosaic_name, mosaic_fqdn, mosaic_description) VALUES (%s,%s, %s,%s,%s, %s,%s,%s,%s, %s, %s, %s, %s, %s, %s) RETURNING id"
mosaicFqdn = parent['namespace_name'] + '.' + tx['mosaicDefinition']['id']['name']
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['fee'],
tx['creationFeeSink_id'],
tx['creationFee'],
parent['id'],
tx['mosaicDefinition']['id']['name'],
mosaicFqdn,
tx['mosaicDefinition']['description']
)
#print " [+] adding to db: ", obj,
cur.execute(sql,obj)
retId = cur.fetchone()[0]
#print retId
sql = "INSERT INTO mosaic_properties (block_height,mosaic_id,name,value) VALUES(%s,%s,%s,%s)"
quantity = 0
for prop in tx['mosaicDefinition']['properties']:
obj = (block['height'],retId, prop['name'], prop['value'])
cur.execute(sql,obj)
if prop['name'] == 'initialSupply':
quantity = int(prop['value'], 10)
sql = "INSERT INTO mosaic_state_supply (block_height, mosaic_id, quantity) VALUES (%s, %s, %s)"
obj = (block['height'], retId, quantity)
cur.execute(sql, obj)
mosLevy = tx['mosaicDefinition']['levy']
if 'recipient' in mosLevy:
levyMosFqdn = Db._getMosaicFqdn(mosLevy)
if levyMosFqdn == mosaicFqdn:
levyMosaic = {'id': retId }
else:
loccur = locdb.conn.cursor()
levyMosaic = locdb._getMosaic(loccur, 'mosaic_fqdn', levyMosFqdn)
loccur.close()
sql = "INSERT INTO mosaic_levys (block_height,mosaic_id, type,recipient_id,fee_mosaic_id,fee) VALUES(%s,%s, %s,%s,%s,%s)"
obj = (block['height'],retId, mosLevy['type'],mosLevy['recipient_id'],levyMosaic['id'],mosLevy['fee'])
cur.execute(sql,obj)
return retId
def _getPreviousStateSupply(self, cur, mosDbId):
sql = "SELECT quantity,block_height,id FROM mosaic_state_supply WHERE mosaic_id=%s ORDER BY block_height DESC LIMIT 1"
obj = (mosDbId,)
cur.execute(sql, obj)
return cur.fetchone()
def _addMosaicSupply(self, cur, block, tx):
locdb = Db(True)
mosFqdn = Db._getMosaicFqdn(tx)
loccur = locdb.conn.cursor()
mosaic = locdb._getMosaic(loccur, 'mosaic_fqdn', mosFqdn)
loccur.close()
sql = "INSERT INTO mosaic_supplies (block_height,hash, timestamp,timestamp_unix,timestamp_nem, signer_id,signature,deadline,fee, mosaic_id, supply_type, delta) VALUES (%s,%s, %s,%s,%s, %s,%s,%s,%s, %s,%s,%s) RETURNING id"
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['fee'],
mosaic['id'],
tx['supplyType'],
tx['delta']
)
#print " [+] adding to db: ", obj,
cur.execute(sql,obj)
retId = cur.fetchone()[0]
ret = self._getPreviousStateSupply(cur, mosaic['id'])
val = ret[0] if ret else 0
print "INSERTING ", val, " -> ",
if tx['supplyType'] == 1:
val += tx['delta']
elif tx['supplyType'] == 2:
val -= tx['delta']
else:
print "FAILED ON A TX:"
print tx
raise 1
print val
if ret and ret[1] == block['height']:
sql = "UPDATE mosaic_state_supply SET quantity=%s WHERE id=%s"
obj = (val, ret[2])
else:
sql = "INSERT INTO mosaic_state_supply (block_height, mosaic_id, quantity) VALUES (%s, %s, %s)"
obj = (block['height'], mosaic['id'], val)
cur.execute(sql, obj)
#print retId
return retId
def _calculateLevy(self, levyType, multiplier, quantity, levyFee):
if levyType == 1:
return levyFee
elif levyType == 2:
return multiplier * quantity * levyFee / 10000
def _addTransfer(self, cur, block, tx):
v = tx['version'] & 0xffffff
sql = "INSERT INTO transfers (block_height,hash,timestamp,timestamp_unix,timestamp_nem, signer_id, signature,deadline, recipient_id,amount,fee,message_type,message_data) VALUES (%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s,%s,%s) RETURNING id";
obj = (block['height'],
tobin(tx['hash']),
tx['timestamp'],
tx['timestamp_unix'],
tx['timestamp_nem'],
tx['signer_id'],
None if 'signature' not in tx else tobin(tx['signature']),
tx['deadline'],
tx['recipient_id'],
tx['amount'],
tx['fee'],
None if len(tx['message']) == 0 else tx['message']['type'],
None if len(tx['message']) == 0 else tobin(tx['message']['payload'])
)
#print " [+] adding to db: ", obj,
cur.execute(sql, obj)
retId = cur.fetchone()[0]
#print retId
if v == 2:
locdb = Db(True)
loccur = locdb.conn.cursor()
for a in tx['mosaics']:
mosFqdn = Db._getMosaicFqdn(a)
mosaic = locdb._getMosaic(loccur, 'mosaic_fqdn', mosFqdn)
sql = "INSERT INTO transfer_attachments (block_height,transfer_id, type,mosaic_id,quantity) VALUES(%s,%s, %s,%s,%s)"
assert (a['quantity'] * tx['amount']) % 1000000 == 0, "invalid amount in a tx"
obj = (block['height'],retId, 2, mosaic['id'], tx['amount']*a['quantity'] / 1000000 )
cur.execute(sql,obj)
if mosaic['levy']:
levyFee = self._calculateLevy(mosaic['levy']['type'], tx['amount'], a['quantity'], mosaic['levy']['fee'])
obj = (block['height'],retId, 12, mosaic['levy']['fee_mosaic']['id'], levyFee)
cur.execute(sql,obj)
loccur.close()
return retId
def _addTxes(self, cur, block, txes):
handlers = {
257: self._addTransfer
, 2049: self._addDelegated
, 4097: self._addAggregateModification
, 4100: self._addMultisig
, 8193: self._addNamespace
, 16385: self._addMosaic
, 16386: self._addMosaicSupply
}
for tx in txes:
print ('processing tx', tx['type'])
txid = handlers[tx['type']](cur, block, tx)
tx['id'] = txid
# ugly hack for multiple txes in same block :/
if tx['type'] == 8193 or tx['type'] == 16386:
cur.close()
self.commit()
cur = self.conn.cursor()
def processTxes(self, block, txes):
cur = self.conn.cursor()
self._addTxes(cur, block, txes)
cur.close()
def addBlock(self, block):
cur = self.conn.cursor()
sql = "INSERT INTO blocks (height,hash,timestamp,timestamp_unix, timestamp_nem, signer_id, signature, type, difficulty, tx_count, fees) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING height";
obj = (block['height'],
tobin(block['hash']),
block['timestamp'],
block['timestamp_unix'],
block['timestamp_nem'],
block['signer_id'],
tobin(block['signature']),
block['type'],
block['difficulty'],
block['tx_count'],
block['fees'])
#print " [+] adding to db: ", obj
cur.execute(sql, obj)
retId = cur.fetchone()[0]
cur.close()
return retId
def findBlock(self, height):
cur = self.conn.cursor()
cur.execute("SELECT * FROM blocks WHERE height = %s", (height,))
data = cur.fetchone()
cur.close()
return data
def getLastHeight(self):
cur = self.conn.cursor()
cur.execute('SELECT height FROM blocks ORDER BY height DESC LIMIT 1')
data = cur.fetchone()
cur.close()
if data is None:
return 0
return data[0]
def getBlocks(self, height):
cur = self.conn.cursor()
cur.execute('SELECT a.printablekey as "s_printablekey",a.publickey as "s_publickey",b.* FROM blocks b,accounts a WHERE b.height < %s AND b.signer_id=a.id ORDER BY height DESC LIMIT 25', (height,))
data = cur.fetchall()
cur.close()
return data
def getBlocksStats(self):
cur = self.conn.cursor()
cur.execute('SELECT height,timestamp_nem,difficulty,fees FROM blocks ORDER BY height DESC LIMIT 5000')
data = cur.fetchall()
cur.close()
return data
def getBlock(self, height):
cur = self.conn.cursor()
cur.execute('SELECT a.printablekey as "s_printablekey",a.publickey as "s_publickey",b.* FROM blocks b,accounts a WHERE b.height=%s AND b.signer_id=a.id ORDER BY height DESC LIMIT 1', (height,))
data = cur.fetchone()
cur.close()
return data
def getBlockByHash(self, blockHash):
cur = self.conn.cursor()
cur.execute('SELECT a.printablekey as "s_printablekey",a.publickey as "s_publickey",b.* FROM blocks b,accounts a WHERE b.hash=%s AND b.signer_id=a.id ORDER BY height DESC LIMIT 1', (tobin(blockHash),))
data = cur.fetchone()
cur.close()
return data
def getInouts(self, accId, txId, limit):
cur = self.conn.cursor()
cur.execute("SELECT * FROM inouts WHERE account_id = %s AND type<>3 AND id < %s ORDER BY id DESC LIMIT {}".format(limit), (accId,txId))
data = cur.fetchall()
cur.close()
return data
def getInoutsNext(self, accId, txId,limit):
cur = self.conn.cursor()