-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmnchecker
1697 lines (1453 loc) · 67.6 KB
/
mnchecker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
#Copyright (c) 2017 Christian Knuchel
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
#=======================================================================================
# Imports
#=======================================================================================
import os
import sys
import argparse
import time
import fnmatch
import shutil
import logging
import logging.handlers
import traceback
import datetime
import urllib.request
import random
from subprocess import Popen, PIPE
#=======================================================================================
# Configuration
#=======================================================================================
#==========================================================
# Basics
userDirName = ".mnchecker"
#==========================================================
# Currency defaults
defaultCurrencyHandle = "zeroone"
defaultCliBin = "/zeroone/zeroone-cli"
defaultDaemonBin = "/zeroone/zerooned"
defaultDataDir = os.path.join(os.path.abspath(os.path.expanduser("~")), ".zeroonecore")
#==========================================================
# Explorer URL
#=============================
# chainz.cryptoid.info
# NOTE: For this explorer, you'll have to set the user agent to "Mozilla/5.0" further below.
defaultBlockExplorerBlockCountUrlTemplate = "https://explorer.01coin.io/api/getblockcount"
#=============================
# vivo.explorerz.top:3003
# NOTE: This explorer seems to be derelict (date of notice: February 19, 2018)
#defaultBlockExplorerBlockCountUrlTemplate = "http://{currencyHandle}.explorerz.top:3003/api/getblockcount"
#=============================
# User Agent (e.g. if, for some reason, the web API's web server got misconfigured and blocks urllib)
#defaultBlockExplorerBlockCountUserAgent = None
defaultBlockExplorerBlockCountUserAgent = "Mozilla/5.0"
#==========================================================
# Auxiliary Files
blockCountCacheFileDirectoryPath = "/tmp"
blockCountCacheFileNameTemplate = "blockheightguard_{explorerName}_{currencyHandle}_blockheight"
blockCountFixLockFileName = ".blockCountFixInProgress"
#==========================================================
# Logging
logFileEnding = ".log"
logFileNameFormat = "{currencyHandle}_{currencyDataDir}{ending}"
defaultLogDirPath = os.path.join(os.path.abspath(\
os.path.expanduser("~")), ".local", "share", "mnchecker", "logs")
defaultLogLevel = logging.DEBUG
defaultLogFormat = "%(message)s"
# The below log formats aren't quite working, but that's okay for now.
defaultConsoleLogFormat = defaultLogFormat
defaultFileLogFormat = defaultLogFormat
#defaultFileLogFormat = "[%(asctime)s] [%(levelname)s] %(message)s"
#==========================================================
# Formula
#==========================================================
# When the discrepancy between the explorer's and the wallet's block count is too great,
# the wallet's blockchain data is reset. As re-synchronizing with the network takes time,
# there needs to be grace time, so the script doesn't detect an obviously critical
# discrepancy between the freshly being synced blockchain data (which is likely still to have
# a low blockcount the next time the script checks), causing it to go into an endless
# cycle of resetting the wallet's blockchain data.
#
# That grace time is determined by the formula as specified by the below function,
# for which configuration variables are provided below, with their values in seconds.
#=============================
# Minimal wait time, no matter the block count.
blockCountFixGraceTimeMin = 1800
#=============================
# By how much the explorer's block count is multiplied to increase or decrease the
# additional grace time to the minimum grace time.
blockCountFixGraceTimeMultiplier = 1.0
#=============================
# This function is provided for configurability for those who would like to change
# the very formula itself:
def blockCountFixGraceTime(explorerBlockCount):
return int(blockCountFixGraceTimeMin + explorerBlockCount * blockCountFixGraceTimeMultiplier)
#==========================================================
# Wait time until the explorer's block count value is updated to the cache file.
explorerQueryInterval = 300
#==========================================================
# Maximum block difference between the wallet's and the explorer's block count
# for the wallet's block count being considered healthy.
defaultThreshold = 3
#==========================================================
# Maximum number of blocks the explorer may be behind the wallet
# in order for mnchecker to consider there's either something wrong
# with the explorer, or the network (e.g. chainsplit).
defaultOvershotThreshold = 10
#=======================================================================================
# Crontab
#=======================================================================================
# Crontab line templates.
defaultCrontabTimingTemplate = "{minute} {hour} {dayOfTheMonth} {month} {dayOfTheWeek}"
# Note: The conf bit template needs to have a leading space.
defaultCrontabConfBitTemplate = " --currency-conf={currencyConf}"
defaultCrontabLineTemplate = "{crontabTiming} {mncheckerPath} --currency-bin-cli={cliBinPath} --currency-bin-daemon={daemonBinPath} --currency-datadir={dataDirPath}{confBit}"
#Minute timing.
defaultCrontabRandomMinuteFloor = 10
defaultCrontabRandomMinuteCeiling = 20
#==========================================================
# This function is here for the convenience of changing the algorithm
# by which the random minute value for the generated crontab entry
# is determined.
def crontabRandomMinute(floor, ceiling):
"""Determines """
return random.randint(floor, ceiling)
#=======================================================================================
# Strings
#=======================================================================================
# Some strings are simply too long, and wrapping them poses more problems than what
# it's worth. As mnchecker, at least for now, is supposed to be a one-file script,
# outsourcing the strings isn't an option either. Here, they have a place where they
# can live, and can grow as long as they want. This is the only place in this code where
# this is considered acceptable.
# For tidyness, I've also moved some smaller strings up here that are related to the code
# of the bigger ones.
_string_logStart = "\n#============================================\n#Check Cycle Started ({date})\n#======================\n"
_string_logEnd = "\n#======================\n#Check Cycle Finished ({date})\n#============================================"
# Overall state information, as presented in the .maintain method for the BlockCountHealth class.
_string_fixed = "[FIXED] The wallet's block count is [{walletBlockCount}], whilst the explorer's locally cached block count is [{explorerBlockCount}]. With the threshold at {threshold}, there's clearly a discrepancy, which suggests that the wallet has derailed. The block count fixing procedure has been initiated."
_string_inProgress = "[FIX IN PROGRESS] The block count fixing procedure has been recently initiated. Not going to do anything."
_string_noFixNeeded = "[NO FIX NEEDED] The wallet's block count is at [{walletBlockCount}], whilst the explorer's locally cached block count is at [{explorerBlockCount}]. With the threshold at [{threshold}] and the overshot threshold at [{overshotThreshold}], block count health is within parameters. There's nothing to fix."
_string_failedDeletingBlockCountFixLockFile = "Failed deleting the blockCountFixLockFile. This is very serious: Mnchecker might stop working properly until this is fixed.\nFile path: {path}\nError:\n{error}"
_string_chainSplitWarning = "[CHAIN SPLIT WARNING] The wallet's block count is at [{walletBlockCount}], whilst the explorer's locally cached block count is at [{explorerBlockCount}]. This difference exceeds the overshot threshold of [{overshotThreshold}], which is indicative of the wallet and the explorer being on seperate chains. The script can't reliably fix this; you'll have to look into this yourself (e.g. check with the appropriate news channels and communities)."
# Debug
_string_goingToDeleteTheBlockCountFixLockFile = "Going to delete the blockCountFixLockFile ({path}). If no success message follows, something's wrong."
_string_blockCountFixLockFileDeletedSuccessfully = "blockCountFixLockFile deleted successfully."
_string_noBlockCountFixLockFileToDelete = "There was no blockCountFixLockFile to delete. That's okay."
# Explorer stuff.
_string_explorerConnectionFailedGoingToRetry = "There was a problem getting the block count from the explorer. Going to wait {waitTimeUntilRetry} seconds to try again."
# Errors.
_string_fileLoggingCouldntBeInitialized = "File logging couldn't be initialized.\nError Name: {errorName}\nError Message: {errorMessage}\nTraceback: {traceback}"
_string_fileLoggingCouldntBeInitialized_ = ""
#=======================================================================================
# Library
#=======================================================================================
#==========================================================
# Base Classes
#==========================================================
#==========================================================
class Namespace (argparse.Namespace):
#=============================
"""Pure namespace class.
Basically serves as a dot-notation oriented dict.
In its current implementation, this is a simple subclass of 'argparse.Namespace'"""
#=============================
pass
#==========================================================
class Singleton(type):
#=============================
# """Classe of this class will always return the same instance upon instantiation."""
#=============================
def __init__(singletonClass, className, parentClasses, classDict):
singletonClass.singletonObject = None
def __call__(self, *args, **kwargs):
if self.singletonObject is None:
self.singletonObject = type.__call__(self, *args, **kwargs)
return self.singletonObject
#==========================================================
# Exceptions (auxiliary classes)
#==========================================================
#==========================================================
class FancyErrorMessage(object):
#=============================
# """Provides error messages that are a bit better formatted and visible for the end user."""
#=============================
def __init__(self, message, title=""):
decorTop = "[MNCHECKER ERROR]{title}".format(title=title)
decorBottom = "[MNCHECKER ERROR]"
self.string = "{eol}{decorTop}{eol}{message}{eol}{decorBottom}"\
.format(eol=os.linesep, decorTop=decorTop, message=message, decorBottom=decorBottom)
__repr__ = self.string
#==========================================================
class ErrorCodes(Namespace):
#=============================
"""Namespace class to configure error codes for execeptions."""
#=============================
pass
#==========================================================
# Exceptions
#==========================================================
#==========================================================
class Error(Exception):
#=============================
"""Exception with a fancy error message."""
#=============================
def __init__(self, message):
super().__init__(FancyErrorMessage(message).string)
class ErrorCodeError(Error):
pass
#==========================================================
class ErrorWithCodes(Error):
#=============================
"""Error with an error code for the 'errno' constructor parameter.
The possible error numbers are to be configured as class variables of the
appropriate subclass. Upon raising the error, one of these constants is
supposed to be passed to 'errno'. During error handling, checks are
supposed to use these constants as well. Never use the actual integer
value anywhere except when defining the class variable referencing it.
The convention is to use all upper case variable names for these."""
#=============================
codes = ErrorCodes()
def __init__(self, message, code):
self.code = code
super().__init__(message)
@property
def codeNames(self):
"""Returns a list of all code names associated with this error."""
return self.__dict__.keys()
@property
def codeName(self):
"""The code name for this error."""
self.getNameByCode(self.code)
raise ErrorCodeError(\
"The following error code couldn't be resolved: \"{code}\". Available error codes:\n{codeList}"\
.format(code=code, codeList=self.codeNames))
def getCodeByName(self, name):
"""Return the error code that matches the specified code name."""
return self.codes.__dict__[name]
def getNameByCode(self, code):
"""Takes an error code and returns its (variable) name.
This is a reverse dictionary lookup by the code for the name of the codes namespace object.
We expect every error code to only exist once. Break that and it'll explode in your face. :p"""
for name in self.codes.codeNames:
if code == self.getCodeByName(name):
return name
#==========================================================
class WalletError(ErrorWithCodes):
codes = ErrorCodes()
codes.CLI_ERROR = 0
codes.RPC_CONNECTION_FAILED = 21
#==========================================================
class BlockExplorerError(ErrorWithCodes):
codes = ErrorCodes()
codes.BLOCK_COUNT_INVALID = 0
codes.CACHE_INVALID = 1
#==========================================================
class DaemonStuckError(Error):
pass
#==========================================================
class PathNotFoundError(Error):
pass
#==========================================================
class FileError(ErrorWithCodes):
codes = ErrorCodes()
codes.SYSTEM_FAILURE = 0
codes.INVALID_PATH = 1
#==========================================================
# Mnchecker Classes
#==========================================================
#==========================================================
class Currency(object):
#=============================
"""Represents the wallet's currency."""
#=============================
def __init__(self, handle):
self.handle = handle
#==========================================================
class Process(object):
#=============================
"""Represents a system process started by this script.
Note: Refrain from calling .communicate() directly on the process from outside of this object."""
#=============================
def __init__(self, commandLine, run=True):
self.commandLine = commandLine
if run == True:
self.run()
self._communicated = False
self._stdout = None
self._stderr = None
def run(self):
self.process = Popen(self.commandLine, stdout=PIPE, stderr=PIPE)
return self.process
def waitAndGetOutput(self, timeout=None):
if not self._communicated:
self._stdout, self._stderr = self.process.communicate(timeout=timeout)
self._communicated = True
return (self._stdout, self._stderr)
def waitAndGetStdout(self, timeout=None):
return self.waitAndGetOutput(timeout)[0]
def waitAndGetStderr(self, timeout=None):
return self.waitAndGetOutput(timeout)[1]
#==========================================================
class BatchPathExistenceCheckPath(object):
#=============================
"""Pairs a path with an existence-check and an error message to use if it doesn't exist."""
#=============================
def __init__(self, path, errorMessage):
self.path = path
self.errorMessage = errorMessage
def exists(self):
"""Checks whether the path exists; returns 'True' if it does, 'False' if it doesn't.
This also considers executable availability through $PATH, in case the specified
'path' is not actually a path per se, but the name of an executable available through
$PATH."""
if os.path.exists(self.path):
return True
else:
if shutil.which(self.path):
return True
else:
return False
#==========================================================
class BatchPathExistenceCheck(object):
#=============================
"""Takes path+errorMessage pairs and checks whether they exist, with an optional error raised.
Raising the optional error is the default behaviour and needs to be disabled if
that is undesired."""
#=============================
def __init__(self):
self.paths = []
self.batchErrorMessage = ""
self.nonExistentPathCount = 0
def addPath(self, path, errorMessage):
self.paths.append(BatchPathExistenceCheckPath(path, errorMessage))
def checkAll(self, autoRaiseError=True):
for path in self.paths:
if not path.exists():
self.nonExistentPathCount += 1
self.batchErrorMessage\
= "{batchErrorMessage}\n{errorMessage}".format(\
batchErrorMessage=self.batchErrorMessage, errorMessage=path.errorMessage)
if autoRaiseError:
self.raiseErrorIfNonExistentPathFound()
def raiseErrorIfNonExistentPathFound(self):
if self.nonExistentPathCount > 0:
self.raiseError()
def raiseError(self):
if self.batchErrorMessage == "":
raise PathNotFoundError("Error: No non-existent paths found, but error was raised anyway.")
elif self.nonExistentPathCount == 1:
raise PathNotFoundError(\
"Error: The following path doesn't exist:{batchErrorMessage}".format(\
batchErrorMessage=self.batchErrorMessage))
elif self.nonExistentPathCount > 1:
raise PathNotFoundError(\
"Error: The following paths don't exist:{batchErrorMessage}".format(\
batchErrorMessage=self.batchErrorMessage))
#==========================================================
class Wallet(object):
#=============================
"""Represents everything this script needs related to a bitcoin derived wallet."""
#=============================
def __init__(self, currency, cliBinPath, daemonBinPath, confFilePath, dataDirPath):
self.currency = currency
self.cliBinPath = cliBinPath
self.daemonBinPath = daemonBinPath
self.confFilePath = confFilePath
self.dataDirPath = dataDirPath
# Check path sanity.
batchPathExistenceCheck = BatchPathExistenceCheck()
batchPathExistenceCheck.addPath(self.cliBinPath, "cli-bin path: {path}".format(\
path=self.cliBinPath))
batchPathExistenceCheck.addPath(self.daemonBinPath, "daemon-bin path: {path}".format(\
path=self.daemonBinPath))
batchPathExistenceCheck.addPath(self.dataDirPath, "datadir path: {path}".format(\
path=self.dataDirPath))
if not self.confFilePath == None:
# A conf file path got specified; check too.
batchPathExistenceCheck.addPath(self.confFilePath, "conf-file path: {path}".format(\
path=self.confFilePath))
batchPathExistenceCheck.checkAll()
# All paths are dandy, nice!
def runCli(self, commandLine):
"""Run the command line version of the wallet with a list of command line arguments."""
if not self.confFilePath == None:
return Process([self.cliBinPath,\
"-datadir={datadir}".format(datadir=self.dataDirPath),\
"-conf={confFilePath}".format(confFilePath=self.confFilePath)] + commandLine)
else:
return Process([self.cliBinPath,\
"-datadir={datadir}".format(datadir=self.dataDirPath)] + commandLine)
def runDaemon(self, commandLine):
"""Run the daemon. Takes a list for command line arguments to it."""
if not self.confFilePath == None:
return Process([self.daemonBinPath,\
"-daemon",\
"-datadir={datadir}".format(datadir=self.dataDirPath),\
"-conf={confFilePath}".format(confFilePath=self.confFilePath)] +commandLine)
else:
return Process([self.daemonBinPath,\
"-daemon",\
"-datadir={datadir}".format(datadir=self.dataDirPath)] +commandLine)
def runCliSafe(self, commandLine, _retrying=False):
"""A version of .runCli that checks for the wallet tripping up and responds accordingly."""
process = self.runCli(commandLine)
stdoutString, stderrString = process.waitAndGetOutput()
# Catch the wallet taking the way out because the daemon isn't running.
if stderrString.decode().strip() == "error: couldn't connect to server":
print("[DEBUG Wallet.runCliSafe WalletError: ]", WalletError.__dict__)
raise WalletError(\
"Command line wallet can't connect to the daemon. Is the daemon running?\n{info}"\
.format(info="Wallet paths:\n\tcli: {cli}\n\tdaemon: {daemon}\n\tdatadir: {datadir}"\
.format(cli=self.cliBinPath, daemon=self.daemonBinPath, datadir=self.dataDirPath)),\
WalletError.codes.RPC_CONNECTION_FAILED)
# Catch issues caused by the wallet connecting to the daemon right after the daemon started.
# As this involves retrying, we have to make sure we don't get stuck retrying forever.
if "error code: -28" in stdoutString.decode()\
or "error code: -28" in stderrString.decode()\
and not _retrying:
# Rerun this method in intervals until it works, or we decide to give up.
for retry in range(1,16):
time.sleep(5)
retriedProcess = self.runCliSafe(commandLine, _retrying=True)
retriedStdoutString, retriedStderrString = retriedProcess.waitAndGetOutput()
if "error code: -28" in retriedStdoutString.decode()\
or "error code: -28" in retriedStderrString.decode():
continue
else:
return retriedProcess
raise DaemonStuckError("Daemon stuck at error -28.")
return process
def runDaemonSafe(self, commandLine):
"""A version of .runDaemon that checks for the daemon tripping up and responds accordingly."""
process = self.runDaemon(commandLine)
stdoutString, stderrString = process.waitAndGetOutput()
#TODO: Make running the daemon safer and failures more verbose with some checks & exceptions.
return process
def startDaemon(self, commandLine=[]):
"""Start the daemon. Takes a list for command line arguments."""
return self.runDaemon(commandLine)
def stopDaemon(self, waitTimeout):
"""Stop the daemon.
The parameter 'waitTimeout' determines for how long we will wait and poll
for stop confirmation, in seconds."""
process = self.runCliSafe(["stop"])
# Wait and poll every second for daemon shutdown completion.
# Return once daemon shut down is confirmed.
if not waitTimeout == None:
for second in range(1,waitTimeout):
try:
self.getBlockCount() # We could use anything. This will do.
except WalletError as error:
if error.code == WalletError.codes.RPC_CONNECTION_FAILED:
break # The client is finally erroring out on the connection. Success.
time.sleep(1)
return process
def deleteBlockchainData(self):
for fileName in ["blocks", "chainstate", "database", "mncache.dat", "peers.dat",\
"mnpayments.dat", "banlist.dat"]:
filePath = os.path.join(self.dataDirPath, fileName)
try:
if os.path.exists(filePath):
if os.path.isdir(filePath):
shutil.rmtree(filePath)
else:
os.remove(filePath)
except OSError:
pass
def getBlockCount(self):
stdout, stderr = self.runCliSafe(["getblockcount"]).waitAndGetOutput(timeout=8)
blockCount = stdout.decode()
if not stderr.decode() == "":
print("stderr ", stderr.decode(), "||", stdout.decode())
raise WalletError(\
"The wallet produced an error when running \"getblockcount\":\n {error}"\
.format(error=stderr.decode()), WalletError.codes.CLI_ERROR)
return int(blockCount)
#==========================================================
class File(object):
#=============================
"""Basic file wrapper.
Abstracts away basic operations such as read, write, etc."""
#TODO: Make file operations safer and failures more verbose with some checks & exceptions.
#=============================
def __init__(self, path, make=False, makeDirs=False, runSetup=True):
if runSetup:
self.setUp(path, make, makeDirs)
def setUp(self, path, make=False, makeDirs=False):
"""Initialize the file. This can be called subsequently to reset which file is being handled."""
self.path = path
if not type(self.path) == str:
raise FileError("Tried to initialize file with non-string path: {path}".format(path=self.path),\
FileError.codes.INVALID_PATH)
self.dirPath, self.name = self.path.rpartition(os.sep)[0::2]
if make:
if not self.exists:
self.make(makeDirs=makeDirs)
@property
def lastModified(self):
return int(os.path.getmtime(self.path))
@property
def secondsSinceLastModification(self):
return int(time.time()) - int(self.lastModified)
@property
def exists(self):
return os.path.exists(self.path)
@property
def dirExists(self):
return os.path.exists(self.dirPath)
@property
def size(self):
return os.path.getsize(self.path)
def overwrite(self, data):
with open(self.path, "w") as fileHandler:
fileHandler.write(data)
def append(self, data):
with open(self.path, "a") as fileHandler:
fileHandler.write(data)
def read(self):
with open(self.path, "r") as fileHandler:
return fileHandler.read()
def delete(self):
"""Deletes the file from the filesystem."""
os.remove(self.path)
def wipe(self):
"""Wipes the content of the file, making it empty."""
self.overwrite("")
def move(self, newPath):
"""Moves the file to a new path."""
if os.path.isdir(newPath):
os.rename(self.path, os.path.join(newPath, self.name))
else:
os.rename(self.path, newPath)
self.setUp(newPath)
def copy(self, destPath):
"""Copy this file to another path."""
shutil.copy(self.path, destPath)
def rename(self, newName):
"""Rename the file (this doesn't change the location of the file, just the name)."""
self.move(os.path.join(self.dirPath, newName))
def make(self, makeDirs=False):
"""Write empty file to make sure it exists."""
if not self.exists:
if makeDirs:
if not self.dirExists:
os.makedirs(self.dirPath)
self.overwrite("")
class LogFile(File):
#=============================
"""A File class with features geared towards logging as required by the Log class.
Supports log rotation (custom implementation)."""
#=============================
# TODO: Deal with multiple processes attempting a rotation at the same time.
# Idea: Introduce a file modification grace time within which no additional
# rotation will be attempted (10 seconds or so). Make it configurable.
# TODO: Deal with incomplete rotation attempts.
# TODO: This is going to be a bit of a cracker: What if a WatchedFileHandler in another
# process performs a delayed write during or after a rotation?
# Perhaps I'm better off implementing a wrapper around logrotate or whatever. <,<°
def __init__(self, path, make=False, makeDirs=False, dateTimeFormat="%d-%m-%Y_%H:%M:%S",\
maxSize=1048576, maxRotations=2, rotation=None, runSetup=True):
super().__init__(path, make, makeDirs, runSetup=False)
super().setUp(path, make, makeDirs)
# Basic parameters.
self.dateTimeFormat = dateTimeFormat
self.maxSize = maxSize
self.maxRotations = maxRotations
# Basic values.
self.rotationSuffixIdentifierPrefix = ".old"
self.rotationSuffixIdentifierFormat = "{prefix}{rotation}"
self.nameElementSeparator = "_"
self.rotatedSuffixFormat = "{identifier}{separator}{date}"
# The rest of the initialization is tied to the actual file we're managing,
# so it's been moved to an overriden .setUp method.
if runSetup:
self.setUp(path, make, makeDirs, rotation)
def setUp(self, path, make=False, makeDirs=False, rotation=None):
# Initialization through auxiliary methods which will depend on above basics.
# Don't change the order of these methods willy nilly: Some depend on former calls.
self.rotation = self.getRotation(rotation)
self.active = self.isActiveOne()
self.identifier = self.getIdentifier()
self.familyName = self.getFamilyName()
self.nameDateSuffix = self.getNameDateSuffix()
self.nameDate = self.getNameDate()
self.familyNameWithIdentifier = self.getFamilyNameWithIdentifier()
self.familyNameWithIdentifierPrefix = self.getFamilyNameWithIdentifierPrefix()
#=============================
# @Property Methods.
#=============================
@property
def tooBig(self):
"""Returns 'True' if the file size exceeds the max log file size, 'False' otherwise."""
return self.size > self.maxSize
@property
def rotatedLogFiles(self):
"""Returns a list of all past, rotated instances of this log file that currently exist.
The list is sorted by rotation in ascending order."""
# The two-loop approach in this method was taken to avoid a n*n type situation.
# There might be yet better ways to solve this.
unsortedRotatedLogFiles = {}
rotatedLogFiles = []
# First, get all file names that match the pattern for rotated log file names.
for fileName in os.listdir(self.dirPath):
familyName, rotation = self.getFamilynNameAndRotationFromFileName(fileName)
if familyName == self.familyName: # Is this our own fileName or at least a rotation?
# Make sure it's not our own fileName: We want rotations:
if not rotation is None and not rotation == 0:
unsortedRotatedLogFiles[rotation] =\
LogFile(os.path.join(self.dirPath, fileName), rotation=rotation)
# Now, instantiate a LogFile object for each of these file names and add them to the
# result list in their rotation order.
for rotation in sorted(unsortedRotatedLogFiles.keys()):
rotatedLogFiles.append(unsortedRotatedLogFiles[rotation])
return rotatedLogFiles
@property
def logFileFamily(self):
"""Retrns a list with this log file at index 0 and all rotated log files after."""
return [self]+self.rotatedLogFiles
@property
def nextRotationName(self):
"""The name this file would have once it's rotated once more."""
if self.active:
date = datetime.datetime.now().strftime(self.dateTimeFormat)
else:
date = self.nameDate
return self.generateRotatedLogFileNameWithDate(self.rotation+1, date)
#=============================
# .setUp Methods.
#=============================
# These are expected to be called by .setUp and are designed towards that end.
# They could also be @property methods, but don't have to be, plus some of them
# are a bit heavy weight. To optimize runtime performance, the corresponding
# values are initialized in .setUp using these methods whenever a new file
# is being set up (at least once when __init__ is called).
def getRotation(self, specifiedRotation):
"""Receives the specified rotation and determines whether it stands. If not, it returns another.
This is expected to be called from __init__ first and foremost."""
if specifiedRotation == None:
# No rotation specified. If our name suggests we're not the active log,
# we will extract the actual rotation value from our name and use that instead.
# Otherwise, we will assume we're the active log and set it to 0.
mightBeRotationValue = self.getFamilynNameAndRotationFromFileName(self.name)[1]
if mightBeRotationValue == None:
determinedRotation = 0
else:
determinedRotation = mightBeRotationValue
else:
determinedRotation = specifiedRotation
return determinedRotation
def isActiveOne(self):
"""Determines whether this log file is the active one, not one of the rotated files.
This is expected to be called from __init__, and obviously after self.rotation
got initialized."""
return self.rotation == 0
def getIdentifier(self):
"""Returns the identifier portion of this file's name."""
return self.rotationSuffixIdentifierFormat.format(\
prefix=self.rotationSuffixIdentifierPrefix, rotation=self.rotation)
def getNameDateSuffix(self):
"""Returns the date suffix. If there is none, the return value should be an empty string."""
return self.name.rpartition(self.identifier)[2]
def getNameDate(self):
"""Returns the date portion of the name without the separator."""
return self.nameDateSuffix.partition(self.nameElementSeparator)[2]
def getFamilyName(self):
"""Gets the base log name of our log family.
Example: If the active log is called mnchecker.log, and we're called
mnchecker.log.old1-18-12-2017_20:54:25, this method
will return the following: mnchecker.log
This is expected to be called from __init__."""
familyNamePortion = self.name.rpartition(self.rotationSuffixIdentifierPrefix)[0]
if familyNamePortion == "":
return self.name
else:
return familyNamePortion
def getFamilyNameWithIdentifier(self):
"""Returns the family name and identifier portion of this file's name."""
return "{name}{identifier}".format(name=self.familyName, identifier=self.identifier)
def getFamilyNameWithIdentifierPrefix(self):
"""Returns the family name and the identifier prefix portion (no rotation ID included)
of this file's name."""
return "{name}{identifierPrefix}"\
.format(name=self.familyName, identifierPrefix=self.rotationSuffixIdentifierPrefix)
def getFamilynNameAndRotationFromFileName(self, fileName):
"""Returns the familyName portion and the rotation value in the given fileName.
'rotation' is 'None' if there is no rotation value at the beginning of the suffix portion.
Rules (if you've passed it a valid log fileName, of course):
- If there is a familyName portion but rotation is None, it's the active file.
- If there is a rotation value and a familyName portion, it's a rotated file."""
fileNameLeftPart, separator, fileNameRightPart = fileName.rpartition(self.rotationSuffixIdentifierPrefix)
if separator == "" and not fileNameRightPart == "":
# rpartition returns ("", "", fileName) if the seperator could not be found,
# which means this is either the active log file (likely) or some random file.
# Which of each it is is the concern of the caller.
familyName = fileName
rotation = 0 # Assuming we weren't fed a random file, which is for the caller to figure.
else:
familyName = fileNameLeftPart
suffix = fileNameRightPart
try:
rotationSeparator = self.nameElementSeparator
maybeARotationValue, rotationSepartor, rest = suffix.partition(rotationSeparator)
# Let's at least check whether the string we've recived is not complete garbage.
if rotationSeparator is self.nameElementSeparator:
rotation = int(maybeARotationValue)
else:
rotation = None
except (IndexError, ValueError) as error:
rotation = None
return familyName, rotation
#=============================
# Normal methods.
#=============================
def isRelatedByName(self, fileName):
"""Returns 'True' if #TODO""" #TODO: Document.
if fileName.startswith(self.familyNameWithIdentifierPrefix):
return True
else:
return False
def rotateFamily(self):
"""Rotates the log file as well as all already rotated versions."""
for logFile in self.logFileFamily[::-1]:
logFile.rotate()
def rotate(self):
"""Copies this log file to a new file and deletes the content of the original."""
newPath = os.path.join(self.dirPath, self.nextRotationName)
try:
self.copy(newPath)
except (FileNotFoundError, PermissionError, OSError, IOError):
# It's more important to keep the filesystem from filling
# than to preserve the mnchecker log file.
raise FileError("Attempted rotating \"{path}\" to \"{newPath}\"."\
.format(path=self.path, newPath=newPath), FileError.codes.SYSTEM_FAILURE)
self.delete()
def generateRotatedLogFileNameWithIdentifier(self, rotation):
"""Generate a version of our family name with an identifier with the specified rotation, but no date."""
return "{name}{identifier}".format(name=self.familyName,\
identifier=self.rotationSuffixIdentifierFormat.format(\
prefix=self.rotationSuffixIdentifierPrefix, rotation=rotation))
def generateRotatedLogFileNameWithDate(self, rotation, date):
"""Generate a version of our family name with identifier, date and all."""
return "{name}{suffix}"\
.format(name=self.familyName, suffix=self.rotatedSuffixFormat\
.format(identifier=self.rotationSuffixIdentifierFormat\
.format(prefix=self.rotationSuffixIdentifierPrefix, rotation=rotation),\
separator=self.nameElementSeparator, date=date))
def curbRotations(self):
"""Deletes all rotations that exceed 'self.maxRotations'."""
for logFile in self.rotatedLogFiles:
if logFile.rotation > self.maxRotations:
logFile.delete()
def maintainRotation(self):
"""Rotates the log file when it gets too big and deletes superfluous rotated copies."""
if self.tooBig:
self.rotateFamily()
self.curbRotations()
#==========================================================
class BlockCountCacheFile(File):
#=============================
"""Wrapper for the file the block explorer's block count data is cached in."""
#=============================
def __init__(self, path):
super().__init__(path, make=True)
#==========================================================
class BlockCountFixLockFile(File):
#=============================
"""Wrapper for the file used to determine whether the wallet has recently had its blockchain
reset by this script.
It's not really a traditional lock file, though: It contains time data to determine whether
the grace waiting period to wait for the wallet's re-sync is over yet or not."""
#=============================
def __init__(self, dataDirPath):
super().__init__(os.path.join(dataDirPath, blockCountFixLockFileName), make=False)
#==========================================================
class HttpUrl(object):
#=============================
"""Represents an HTTP url and its components.
In its current state, it's only geared towards separating the domain from the protocol
indicator and the rest of the address."""
#=============================
def __init__(self, url):
self.url = url
@property
def hasProtocolIndicator(self):
return True if "://" in self.url else False
@property
def withoutProtocolIndicator(self):
if self.hasProtocolIndicator:
return self.url[self.url.find("://")+3:]
else:
return self.url
@property
def domain(self):
return self.withoutProtocolIndicator[:self.withoutProtocolIndicator.find("/")]
#==========================================================
class BlockExplorer(object):
#=============================
"""Represents a block explorer to the extent of its relevance in terms of block count information."""
#=============================
def __init__(self):
self.name = "NONE"
def queryBlockCount(self, currency):
"""Override this with the actual code required to get the block count from a particular block explorer."""
pass # Override
def getBlockCount(self, currency):
"""Gets and caches an explorer's block count.
The values are read from the cache file for a period. That file is updated with fresh information
if this method is called and that period is exceeded."""
#NOTE: This method should better handle connection issues.
blockCountCacheFile = BlockCountCacheFile(\
os.path.join( blockCountCacheFileDirectoryPath,\
blockCountCacheFileNameTemplate.format(\
explorerName=self.name, currencyHandle=currency.handle)))
if blockCountCacheFile.secondsSinceLastModification > explorerQueryInterval\
or blockCountCacheFile.read() == "":
# Data in the cache file is old, or nothing has been written to it yet.
# Get updated block count data and write it to it.
try: # This entire handling section could use some clean up. It was slapped together hastily.
blockCountCacheFile.overwrite(str( self.queryBlockCount(currency)))
except (BlockExplorerError, ConnectionResetError) as error:
waitTimeUntilRetry = random.randint(30,60)
Log("mnchecker").critical(\
_string_explorerConnectionFailedGoingToRetry.format(waitTimeUntilRetry=waitTimeUntilRetry),\
sys.exc_info())
time.sleep(waitTimeUntilRetry)
blockCountCacheFile.overwrite(str( self.queryBlockCount(currency)))
blockCountCacheValue = blockCountCacheFile.read()
try:
return int(blockCountCacheValue)
except ValueError as error:
raise BlockExplorerError("The block count cache file contains faulty data.\n\tFile path: {path}\n\tData: {data}"\
.format(path=blockCountCacheFile.path, data=blockCountCacheFile.read()),\
BlockExplorerError.codes.CACHE_INVALID) from error
#==========================================================
class BlockExplorerByWebApi(BlockExplorer):