-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestUtils.py
executable file
·1499 lines (1278 loc) · 58.7 KB
/
testUtils.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 subprocess
import time
import glob
import shutil
import time
import os
from collections import namedtuple
import re
import string
import signal
import time
import datetime
import inspect
import sys
import random
import io
import json
###########################################################################################
class Utils:
Debug=False
FNull = open(os.devnull, 'w')
EosServerName="eosiod"
EosClientPath="programs/eosioc/eosioc"
EosWalletPath="programs/eosiowd/eosiowd"
EosServerName="eosiod"
EosServerPath="programs/eosiod/%s" % (EosServerName)
EosLauncherPath="programs/eosio-launcher/eosio-launcher"
MongoPath="mongo"
@staticmethod
def Print(*args, **kwargs):
stackDepth=len(inspect.stack())-2
str=' '*stackDepth
sys.stdout.write(str)
print(*args, **kwargs)
SyncStrategy=namedtuple("ChainSyncStrategy", "name id arg")
SyncNoneTag="none"
SyncReplayTag="replay"
SyncResyncTag="resync"
SigKillTag="kill"
SigTermTag="term"
# mongoSyncTime: eosiod mongodb plugin seems to sync with a 10-15 seconds delay. This will inject
# a wait period before the 2nd DB check (if first check fails)
mongoSyncTime=25
amINoon=True
# Configure for the NOON branch
@staticmethod
def iAmNotNoon():
Utils.amINoon=False
Utils.EosServerName="eosd"
Utils.EosClientPath="programs/eosc/eosc"
Utils.EosWalletPath="programs/eos-walletd/eos-walletd"
Utils.EosServerPath="programs/eosd/%s" % (Utils.EosServerName)
@staticmethod
def setMongoSyncTime(syncTime):
Utils.mongoSyncTime=syncTime
@staticmethod
def getChainStrategies():
chainSyncStrategies={}
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncNoneTag, 0, "")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStrategy
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncReplayTag, 1, "--replay-blockchain")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStrategy
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncResyncTag, 2, "--resync-blockchain")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStrategy
return chainSyncStrategies
###########################################################################################
class Table(object):
def __init__(self, name):
self.name=name
self.keys=[]
self.data=[]
###########################################################################################
class Transaction(object):
def __init__(self, transId):
self.transId=transId
self.tType=None
self.amount=0
###########################################################################################
class Account(object):
def __init__(self, name):
self.name=name
self.balance=0
self.ownerPrivateKey=None
self.ownerPublicKey=None
self.activePrivateKey=None
self.activePublicKey=None
def __str__(self):
return "Name; %s" % (self.name)
###########################################################################################
class Node(object):
def __init__(self, host, port, pid=None, cmd=None, alive=None, enableMongo=False, mongoHost="localhost", mongoPort=27017, mongoDb="EOStest"):
self.host=host
self.port=port
self.pid=pid
self.cmd=cmd
self.alive=alive
self.enableMongo=enableMongo
self.mongoSyncTime=None if Utils.mongoSyncTime < 1 else Utils.mongoSyncTime
self.mongoHost=mongoHost
self.mongoPort=mongoPort
self.mongoDb=mongoDb
self.endpointArgs="--host %s --port %d" % (self.host, self.port)
self.mongoEndpointArgs=""
if self.enableMongo:
self.mongoEndpointArgs += "--host %s --port %d %s" % (mongoHost, mongoPort, mongoDb)
def __str__(self):
#return "Host: %s, Port:%d, Pid:%s, Alive:%s, Cmd:\"%s\"" % (self.host, self.port, self.pid, self.alive, self.cmd)
return "Host: %s, Port:%d" % (self.host, self.port)
@staticmethod
def runCmdReturnJson(cmd, trace=False):
retStr=Node.__checkOutput(cmd.split())
jStr=Node.filterJsonObject(retStr)
trace and Utils.Print ("RAW > %s"% retStr)
trace and Utils.Print ("JSON> %s"% jStr)
jsonData=json.loads(jStr)
return jsonData
@staticmethod
def __runCmdArrReturnJson(cmdArr, trace=False):
retStr=Node.__checkOutput(cmdArr)
jStr=Node.filterJsonObject(retStr)
trace and Utils.Print ("RAW > %s"% retStr)
trace and Utils.Print ("JSON> %s"% jStr)
jsonData=json.loads(jStr)
return jsonData
@staticmethod
def filterJsonObject(data):
firstIdx=data.find('{')
lastIdx=data.rfind('}')
retStr=data[firstIdx:lastIdx+1]
return retStr
@staticmethod
def __checkOutput(cmd):
retStr=subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
#retStr=subprocess.check_output(cmd).decode("utf-8")
return retStr
# Passes input to stdin, executes cmd. Returns tuple with return code(int),
# stdout(byte stream) and stderr(byte stream).
@staticmethod
def stdinAndCheckOutput(cmd, subcommand):
outs=None
errs=None
try:
popen=subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outs,errs=popen.communicate(input=subcommand.encode("utf-8"))
ret=popen.wait()
except subprocess.CalledProcessError as ex:
msg=ex.output
return (ex.returncode, msg, None)
return (0, outs, errs)
@staticmethod
def normalizeJsonObject(extJStr):
tmpStr=extJStr
tmpStr=re.sub(r'ObjectId\("(\w+)"\)', r'"ObjectId-\1"', tmpStr)
tmpStr=re.sub(r'ISODate\("([\w|\-|\:|\.]+)"\)', r'"ISODate-\1"', tmpStr)
return tmpStr
@staticmethod
def runMongoCmdReturnJson(cmdArr, subcommand, trace=False):
retId,outs,errs=Node.stdinAndCheckOutput(cmdArr, subcommand)
if retId is not 0:
return None
outStr=Node.byteArrToStr(outs)
if not outStr:
return None
extJStr=Node.filterJsonObject(outStr)
if not extJStr:
return None
jStr=Node.normalizeJsonObject(extJStr)
if not jStr:
return None
trace and Utils.Print ("RAW > %s"% outStr)
#trace and Utils.Print ("JSON> %s"% jStr)
jsonData=json.loads(jStr)
return jsonData
@staticmethod
def getTransId(trans):
transId=trans["transaction_id"]
return transId
@staticmethod
def byteArrToStr(arr):
return arr.decode("utf-8")
def setWalletEndpointArgs(self, args):
self.endpointArgs="--host %s --port %d %s" % (self.host, self.port, args)
def getBlock(self, blockNum, retry=True, silentErrors=False):
if not self.enableMongo:
cmd="%s %s get block %s" % (Utils.EosClientPath, self.endpointArgs, blockNum)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get block. %s" % (msg))
return None
else:
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Blocks.findOne( { "block_num": %s } )' % (blockNum)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get block. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def getBlockById(self, blockId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Blocks.findOne( { "block_id": "%s" } )' % (blockId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during db get block by id. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def doesNodeHaveBlockNum(self, blockNum):
if self.alive is False:
return False
block=self.getBlock(blockNum, silentErrors=True)
if block is None:
return False
else:
return True
def getTransaction(self, transId, retry=True, silentErrors=False):
if not self.enableMongo:
cmd="%s %s get transaction %s" % (Utils.EosClientPath, self.endpointArgs, transId)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during account by transaction retrieval. %s" % (msg))
return None
else:
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Transactions.findOne( { "transaction_id": "%s" } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get trans. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def getTransByBlockId(self, blockId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Transactions.find( { "block_id": "%s" } )' % (blockId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand, True)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during db get trans by blockId. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def getActionFromDb(self, transId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Actions.findOne( { "transaction_id": "%s" } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get message. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def getMessageFromDb(self, transId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Messages.findOne( { "transaction_id": "%s" } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get message. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def doesNodeHaveTransId(self, transId):
trans=self.getTransaction(transId, silentErrors=True)
if trans is not None:
return True
else:
return False
# Create account and return creation transactions. Return transaction json object
# waitForTransBlock: wait on creation transaction id to appear in a block
def createAccount(self, account, creatorAccount, stakedDeposit=1000, waitForTransBlock=False):
cmd=None
if Utils.amINoon:
cmd="%s %s create account --staked-deposit %d %s %s %s %s" % (
Utils.EosClientPath, self.endpointArgs, stakedDeposit, creatorAccount.name, account.name,
account.ownerPublicKey, account.activePublicKey)
else:
cmd="%s %s create account %s %s %s %s" % (Utils.EosClientPath, self.endpointArgs,
creatorAccount.name, account.name,
account.ownerPublicKey, account.activePublicKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
transId=Node.getTransId(trans)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during account creation. %s" % (msg))
return None
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getEosAccount(self, name):
cmd="%s %s get account %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get account. %s" % (msg))
return None
def getEosAccountFromDb(self, name):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Accounts.findOne({"name" : "%s"})' % (name)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get account from db. %s" % (msg))
return None
# Verifies account. Returns "get account" json return object
def verifyAccount(self, account):
if not self.enableMongo:
ret=self.getEosAccount(account.name)
if ret is not None:
stakedBalance=ret["staked_balance"]
if stakedBalance is None:
Utils.Print("ERROR: Failed to verify account creation.", account.name)
return None
return ret
else:
for i in range(2):
ret=self.getEosAccountFromDb(account.name)
if ret is not None:
stakedBalance=ret["staked_balance"]
if stakedBalance is None:
Utils.Print("ERROR: Failed to verify account creation.", account.name)
return None
return ret
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
return None
def waitForBlockNumOnNode(self, blockNum, timeout=60):
startTime=time.time()
remainingTime=timeout
while time.time()-startTime < timeout:
if self.doesNodeHaveBlockNum(blockNum):
return True
sleepTime=3 if remainingTime > 3 else (3 - remainingTime)
remainingTime -= sleepTime
time.sleep(sleepTime)
return False
def waitForTransIdOnNode(self, transId, timeout=60):
startTime=time.time()
remainingTime=timeout
while time.time()-startTime < timeout:
if self.doesNodeHaveTransId(transId):
return True
sleepTime=3 if remainingTime > 3 else (3 - remainingTime)
remainingTime -= sleepTime
time.sleep(sleepTime)
return False
def waitForNextBlock(self, timeout=60):
startTime=time.time()
remainingTime=timeout
num=self.getHeadBlockNum()
Utils.Debug and Utils.Print("Current block number: %s" % (num))
while time.time()-startTime < timeout:
nextNum=self.getHeadBlockNum()
if nextNum > num:
Utils.Debug and Utils.Print("Next block number: %s" % (nextNum))
return True
sleepTime=.5 if remainingTime > .5 else (.5 - remainingTime)
remainingTime -= sleepTime
time.sleep(sleepTime)
return False
# Trasfer funds. Returns "transfer" json return object
def transferFunds(self, source, destination, amount, memo="memo", force=False):
cmd="%s %s transfer %s %s %d" % (
Utils.EosClientPath, self.endpointArgs, source.name, destination.name, amount)
cmdArr=cmd.split()
cmdArr.append(memo)
if force:
cmdArr.append("-f")
Utils.Debug and Utils.Print("cmd: %s" % (cmdArr))
trans=None
try:
trans=Node.__runCmdArrReturnJson(cmdArr)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during funds transfer. %s" % (msg))
return None
def validateSpreadFundsOnNode(self, adminAccount, accounts, expectedTotal):
actualTotal=self.getAccountBalance(adminAccount.name)
for account in accounts:
fund = self.getAccountBalance(account.name)
if fund != account.balance:
Utils.Print("ERROR: validateSpreadFunds> Expected: %d, actual: %d for account %s" %
(account.balance, fund, account.name))
return False
actualTotal += fund
if actualTotal != expectedTotal:
Utils.Print("ERROR: validateSpreadFunds> Expected total: %d , actual: %d" % (
expectedTotal, actualTotal))
return False
return True
def getSystemBalance(self, adminAccount, accounts):
balance=self.getAccountBalance(adminAccount.name)
for account in accounts:
balance += self.getAccountBalance(account.name)
return balance
# Gets accounts mapped to key. Returns json object
def getAccountsByKey(self, key):
cmd="%s %s get accounts %s" % (Utils.EosClientPath, self.endpointArgs, key)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during accounts by key retrieval. %s" % (msg))
return None
# Gets accounts mapped to key. Returns array
def getAccountsArrByKey(self, key):
trans=self.getAccountsByKey(key)
accounts=trans["account_names"]
return accounts
def getServants(self, name):
cmd="%s %s get servants %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during servants retrieval. %s" % (msg))
return None
def getServantsArr(self, name):
trans=self.getServants(name)
servants=trans["controlled_accounts"]
return servants
def getAccountBalance(self, name):
if not self.enableMongo:
account=self.getEosAccount(name)
field=account["eos_balance"]
balanceStr=field.split()[0]
balance=int(float(balanceStr)*10000)
return balance
else:
if self.mongoSyncTime is not None:
time.sleep(self.mongoSyncTime)
account=self.getEosAccountFromDb(name)
if account is not None:
field=account["eos_balance"]
balanceStr=field.split()[0]
balance=int(float(balanceStr)*10000)
return balance
return None
# transactions lookup by id. Returns json object
def getTransactionsByAccount(self, name):
cmd="%s %s get transactions %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during transactions by account retrieval. %s" % (msg))
return None
# transactions lookup by id. Returns list of transaction ids
def getTransactionsArrByAccount(self, name):
trans=self.getTransactionsByAccount(name)
transactions=trans["transactions"]
transArr=[]
for transaction in transactions:
id=transaction["transaction_id"]
transArr.append(id)
return transArr
def getAccountCodeHash(self, account):
cmd="%s %s get code %s" % (Utils.EosClientPath, self.endpointArgs, account)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
retStr=Node.__checkOutput(cmd.split())
#Utils.Print ("get code> %s"% retStr)
p=re.compile('code\shash: (\w+)\n', re.MULTILINE)
m=p.search(retStr)
if m is None:
msg="Failed to parse code hash."
Utils.Print("ERROR: "+ msg)
return None
return m.group(1)
trans=Node.runCmdReturnJson(cmd, True)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during code hash retrieval. %s" % (msg))
return None
# publish contract and return transaction as json object
def publishContract(self, account, wastFile, abiFile, waitForTransBlock=False, shouldFail=False):
cmd="%s %s set contract %s %s %s" % (Utils.EosClientPath, self.endpointArgs, account, wastFile, abiFile)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
if not shouldFail:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during code hash retrieval. %s" % (msg))
return None
else:
retMap={}
retMap["returncode"]=ex.returncode
retMap["cmd"]=ex.cmd
retMap["output"]=ex.output
# commented below as they are available only in Python3.5 and above
# retMap["stdout"]=ex.stdout
# retMap["stderr"]=ex.stderr
return retMap
if shouldFail:
Utils.Print("ERROR: The publish contract did not fail as expected.")
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
# create producer and retrun transaction as json object
def createProducer(self, account, ownerPublicKey, waitForTransBlock=False):
cmd="%s %s create producer %s %s" % (Utils.EosClientPath, self.endpointArgs, account, ownerPublicKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during producer creation. %s" % (msg))
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getTable(self, account, contract, table):
cmd="%s %s get table %s %s %s" % (Utils.EosClientPath, self.endpointArgs, account, contract, table)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during table retrieval. %s" % (msg))
return None
def getTableRows(self, account, contract, table):
jsonData=self.getTable(account, contract, table)
if jsonData is None:
return None
rows=jsonData["rows"]
return rows
def getTableRow(self, account, contract, table, idx):
if idx < 0:
Utils.Print("ERROR: Table index cannot be negative. idx: %d" % (idx))
return None
rows=self.getTableRows(account, contract, table)
if rows is None or idx >= len(rows):
Utils.Print("ERROR: Retrieved table does not contain row %d" % idx)
return None
row=rows[idx]
return row
def getTableColumns(self, account, contract, table):
row=self.getTableRow(account, contract, table, 0)
keys=list(row.keys())
return keys
def pushMessage(self, contract, action, data, opts):
cmd=None
if Utils.amINoon:
cmd="%s %s push action %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, action)
else:
cmd="%s %s push message %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, action)
cmdArr=cmd.split()
if data is not None:
cmdArr.append(data)
if opts is not None:
cmdArr += opts.split()
Utils.Debug and Utils.Print("cmd: %s" % (cmdArr))
try:
trans=Node.__runCmdArrReturnJson(cmdArr)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during push message. %s" % (msg))
return None
def setPermission(self, account, code, pType, requirement, waitForTransBlock=False):
cmd="%s %s set action permission %s %s %s %s" % (
Utils.EosClientPath, self.endpointArgs, account, code, pType, requirement)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during set permission. %s" % (msg))
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getInfo(self, silentErrors=False):
cmd="%s %s get info" % (Utils.EosClientPath, self.endpointArgs)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get info. %s" % (msg))
return None
def getBlockFromDb(self, idx):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand="db.Blocks.find().sort({\"_id\":%d}).limit(1).pretty()" % (idx)
Utils.Debug and Utils.Print("cmd: echo \"%s\" | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db block. %s" % (msg))
return None
def checkPulse(self):
info=self.getInfo(True)
if info is not None:
self.alive=True
return True
else:
self.alive=False
return False
def getHeadBlockNum(self):
if not self.enableMongo:
info=self.getInfo()
if info is not None:
headBlockNumTag="head_block_num"
return info[headBlockNumTag]
else:
block=self.getBlockFromDb(-1)
if block is not None:
blockNum=block["block_num"]
return blockNum
return None
###########################################################################################
Wallet=namedtuple("Wallet", "name password host port")
class WalletMgr(object):
__walletLogFile="test_walletd_output.log"
__walletDataDir="test_wallet_0"
# walletd [True|False] Will wallet me in a standalone process
def __init__(self, walletd, eosiodPort=8888, eosiodHost="localhost", port=8899, host="localhost"):
self.walletd=walletd
self.eosiodPort=eosiodPort
self.eosiodHost=eosiodHost
self.port=port
self.host=host
self.wallets={}
self.__walletPid=None
self.endpointArgs="--host %s --port %d" % (self.eosiodHost, self.eosiodPort)
if self.walletd:
self.endpointArgs += " --wallet-host %s --wallet-port %d" % (self.host, self.port)
def launch(self):
if not self.walletd:
Utils.Print("ERROR: Wallet Manager wasn't configured to launch walletd")
return False
cmd="%s --data-dir %s --http-server-address=%s:%d" % (
Utils.EosWalletPath, WalletMgr.__walletDataDir, self.host, self.port)
Utils.Print("cmd: %s" % (cmd))
with open(WalletMgr.__walletLogFile, 'w') as sout, open(WalletMgr.__walletLogFile, 'w') as serr:
popen=subprocess.Popen(cmd.split(), stdout=sout, stderr=serr)
self.__walletPid=popen.pid
# Give walletd time to warm up
time.sleep(1)
return True
def create(self, name):
wallet=self.wallets.get(name)
if wallet is not None:
Utils.Debug and Utils.Print("Wallet \"%s\" already exists. Returning same." % name)
return wallet
p = re.compile('\n\"(\w+)\"\n', re.MULTILINE)
cmd="%s %s wallet create --name %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
retStr=subprocess.check_output(cmd.split()).decode("utf-8")
#Utils.Print("create: %s" % (retStr))
m=p.search(retStr)
if m is None:
Utils.Print("ERROR: wallet password parser failure")
return None
p=m.group(1)
wallet=Wallet(name, p, self.host, self.port)
self.wallets[name] = wallet
return wallet
def importKey(self, account, wallet):
warningMsg="This key is already imported into the wallet"
cmd="%s %s wallet import --name %s %s" % (
Utils.EosClientPath, self.endpointArgs, wallet.name, account.ownerPrivateKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
retStr=subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
if warningMsg in msg:
Utils.Print("WARNING: This key is already imported into the wallet.")
else:
Utils.Print("ERROR: Failed to import account owner key %s. %s" % (account.ownerPrivateKey, msg))
return False
if account.activePrivateKey is None:
Utils.Print("WARNING: Active private key is not defined for account \"%s\"" % (account.name))
else:
cmd="%s %s wallet import --name %s %s" % (
Utils.EosClientPath, self.endpointArgs, wallet.name, account.activePrivateKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
retStr=subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT).decode("utf-8")
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
if warningMsg in msg:
Utils.Print("WARNING: This key is already imported into the wallet.")
else:
Utils.Print("ERROR: Failed to import account active key %s. %s" %
(account.activePrivateKey, msg))
return False
return True
def lockWallet(self, wallet):
cmd="%s %s wallet lock --name %s" % (Utils.EosClientPath, self.endpointArgs, wallet.name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull):
Utils.Print("ERROR: Failed to lock wallet %s." % (wallet.name))
return False
return True
def unlockWallet(self, wallet):
cmd="%s %s wallet unlock --name %s" % (Utils.EosClientPath, self.endpointArgs, wallet.name)
#Utils.Debug and Utils.Print("cmd: %s" % (cmd))
popen=subprocess.Popen(cmd.split(), stdout=Utils.FNull, stdin=subprocess.PIPE)
outs, errs = popen.communicate(input=wallet.password.encode("utf-8"))
if 0 != popen.wait():
Utils.Print("ERROR: Failed to unlock wallet %s: %s" % (wallet.name, errs.decode("utf-8")))
return False
return True
def lockAllWallets(self):
cmd="%s %s wallet lock_all" % (Utils.EosClientPath, self.endpointArgs)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull):
Utils.Print("ERROR: Failed to lock all wallets.")
return False
return True
def getOpenWallets(self):
wallets=[]
p = re.compile('\s+\"(\w+)\s\*\",?\n', re.MULTILINE)
cmd="%s %s wallet list" % (Utils.EosClientPath, self.endpointArgs)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
retStr=subprocess.check_output(cmd.split()).decode("utf-8")
#Utils.Print("retStr: %s" % (retStr))
m=p.findall(retStr)
if m is None:
Utils.Print("ERROR: wallet list parser failure")
return None
wallets=m
return wallets
def getKeys(self):
keys=[]
p = re.compile('\n\s+\"(\w+)\"\n', re.MULTILINE)
cmd="%s %s wallet keys" % (Utils.EosClientPath, self.endpointArgs)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
retStr=subprocess.check_output(cmd.split()).decode("utf-8")
#Utils.Print("retStr: %s" % (retStr))
m=p.findall(retStr)
if m is None:
Utils.Print("ERROR: wallet keys parser failure")
return None
keys=m
return keys
def dumpErrorDetails(self):
Utils.Print("=================================================================")
if self.__walletPid is not None:
Utils.Print("Contents of %s:" % (WalletMgr.__walletLogFile))
Utils.Print("=================================================================")
with open(WalletMgr.__walletLogFile, "r") as f:
shutil.copyfileobj(f, sys.stdout)
def killall(self):
if self.__walletPid is not None:
os.kill(self.__walletPid, signal.SIGKILL)
def cleanup(self):
dataDir=WalletMgr.__walletDataDir
if os.path.isdir(dataDir) and os.path.exists(dataDir):
shutil.rmtree(WalletMgr.__walletDataDir)
###########################################################################################
class Cluster(object):
__chainSyncStrategies=Utils.getChainStrategies()
__WalletName="MyWallet"
__localHost="localhost"
__lastTrans=None
# init accounts
initaAccount=Account("inita")
initaAccount.ownerPrivateKey="5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3";
initbAccount=Account("initb")
initbAccount.ownerPrivateKey="5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3";
# walletd [True|False] Is walletd running. If not load the wallet plugin
def __init__(self, walletd=False, localCluster=True, host="localhost", port=8888, walletHost="localhost", walletPort=8899, enableMongo=False, mongoHost="localhost", mongoPort=27017, mongoDb="EOStest", initaPrvtKey=initaAccount.ownerPrivateKey, initbPrvtKey=initbAccount.ownerPrivateKey):
self.accounts={}
self.nodes={}
self.localCluster=localCluster
self.wallet=None
self.walletd=walletd