예제 #1
0
def run():
    log.startLogging(sys.stdout)
    parser = argparse.ArgumentParser()
    parser.add_argument('-manage', '--manage', action='store_true', default=False, dest='manage', help='run manage')
    parser.add_argument('-initdb', '--initdb', action='store_true', default=False, dest='initdb', help='run initdb')
    parser.add_argument('-debug', '--debug', action='store_true', default=False, dest='debug', help='debug option')
    parser.add_argument('-c', '--conf', type=str, default="/etc/toughradius.json", dest='conf', help='config file')
    args = parser.parse_args(sys.argv[1:])

    config = iconfig.find_config(args.conf)
    syslog = logger.Logger(config)

    update_timezone(config)
    check_env(config)

    if args.debug:
        config.defaults.debug = True

    if args.manage:
        webserver.run(config,log=syslog)
        reactor.run()
        
    elif args.initdb:
        run_initdb(config)
    else:
        parser.print_help()
예제 #2
0
 def run(self):
     framelog = os.path.join(self.basedir, "driver.log")
     log.startLogging(open(framelog, "a"), setStdout=False)
     log.msg("CHECK_MEMORY(mode=%s) STARTING" % self.mode)
     #logfile = open(os.path.join(self.testdir, "log"), "w")
     #flo = log.FileLogObserver(logfile)
     #log.startLoggingWithObserver(flo.emit, setStdout=False)
     d = fireEventually()
     d.addCallback(lambda res: self.setUp())
     d.addCallback(lambda res: self.record_initial_memusage())
     d.addCallback(lambda res: self.make_nodes())
     d.addCallback(lambda res: self.wait_for_client_connected())
     d.addCallback(lambda res: self.do_test())
     d.addBoth(self.tearDown)
     def _err(err):
         self.failed = err
         log.err(err)
         print err
     d.addErrback(_err)
     def _done(res):
         reactor.stop()
         return res
     d.addBoth(_done)
     reactor.run()
     if self.failed:
         # raiseException doesn't work for CopiedFailures
         self.failed.raiseException()
예제 #3
0
 def initializeWebSocket(self):##Starts the WebSocket
     log.startLogging(sys.stdout)##Create a logfile (not necessary)
     self.factory = WebSocketServerFactory(hostip, debug = False)
     self.factory.protocol = EchoServerProtocol ##assign our Protocol to send/receive Messages
     listenWS(self.factory)
     
     reactor.run(installSignalHandlers=0)##"installSignalHandlers=0" Necessary for Multithreading
def agent_main(collector):
    to_file(sys.stdout)
    startLogging(sys.stdout)
    return react(
        run_agent, [
            environ.get(
                "FLOCKER_CONFIGURATION_PATH",
                "/etc/flocker",
            ).decode("ascii"),
            environ.get(
                "CATALOG_FIREHOSE_PROTOCOL",
                DEFAULT_FIREHOSE_PROTOCOL,
            ).decode("ascii"),
            environ.get(
                "CATALOG_FIREHOSE_HOSTNAME",
                DEFAULT_FIREHOSE_HOSTNAME,
            ).decode("ascii"),
            int(
                environ.get(
                    "CATALOG_FIREHOSE_PORT",
                    unicode(DEFAULT_FIREHOSE_PORT).encode("ascii"),
                ).decode("ascii")
            ),
            # Base64 encoded
            environ["CATALOG_FIREHOSE_SECRET"].decode("ascii"),
            collector,
        ],
    )
예제 #5
0
파일: karmabot.py 프로젝트: drd/karmabot
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="usage: %prog [options] channels")

    # IRC connection options
    parser.add_option("-s", "--server",
                      action="store", dest="server",
                      default="irc.freenode.net",
                      help="IRC server to connect to")
    parser.add_option("-p", "--port",
                      action="store", type="int", dest="port", default=None,
                      help="IRC server to connect to")
    parser.add_option("--ssl",
                      action="store_true", dest="ssl", default=False,
                      help="use SSL")
    parser.add_option("--password",
                      action="store", dest="password", default=None,
                      help="server password")
    parser.add_option("-n", "--nick",
                      action="store", dest="nick", default="karmabot",
                      help="nickname to use")
    # Bot options
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="enable verbose output")
    parser.add_option("-d", "--data",
                      action="store", dest="filename", default="karma.json",
                      help="karma data file name")
    parser.add_option("-t", "--trust",
                      action="append", dest="trusted", default=[],
                      help="trusted hostmasks")
    parser.add_option("-f", "--facets",
                      action="append", dest="facets", default=[],
                      help="additional facets to load")

    (options, channels) = parser.parse_args()

    if not channels:
        parser.error("You must supply some channels to join.")
    else:
        log.msg("Channels to join: %s" % channels)

    if options.verbose:
        log.startLogging(sys.stdout)

    if not options.port:
        options.port = 6667 if not options.ssl else 9999
    
    # FIXME: this needs to be replaced with a real facet manager
    for facet_path in options.facets:
        execfile(facet_path, globals())

    factory = KarmaBotFactory(options.filename, options.nick,
                              channels, options.trusted, options.password)
    if not options.ssl:
        reactor.connectTCP(options.server, options.port, factory)
    else:
        reactor.connectSSL(options.server, options.port,
                           factory, ssl.ClientContextFactory())
    reactor.run()
예제 #6
0
    def _init_local(self):
        from p2p import commands
        from lib import net_misc
        from lib import misc
        from system import tmpfile
        from system import run_upnpc
        from raid import eccmap
        from userid import my_id

        my_id.init()
        if settings.enableWebStream():
            from logs import weblog

            weblog.init(settings.getWebStreamPort())
        if settings.enableWebTraffic():
            from logs import webtraffic

            webtraffic.init(port=settings.getWebTrafficPort())
        misc.init()
        commands.init()
        tmpfile.init(settings.getTempDir())
        net_misc.init()
        settings.update_proxy_settings()
        run_upnpc.init()
        eccmap.init()
        if sys.argv.count("--twisted"):
            from twisted.python import log as twisted_log

            twisted_log.startLogging(MyTwistedOutputLog(), setStdout=0)
            # import twisted.python.failure as twisted_failure
            # twisted_failure.startDebugMode()
            # twisted_log.defaultObserver.stop()
        if settings.getDebugLevel() > 10:
            defer.setDebugging(True)
예제 #7
0
def main():
    
    import optparse

    parser = optparse.OptionParser(usage='Insert usage string here')
    parser.add_option('-m', '--mqttbroker', dest='mqttBroker', default=None, type='string',
                       help='Specify the MQTT broker to run on')
    parser.add_option('-x', '--xmppserver', dest='xmppServer', default=None, type='string',
                       help='Specify the XMPP pubsub server to run on')
    parser.add_option('-i', '--gatewayid', dest='gatewayId', default=None, type='string',
                       help='Specify the ID of the gateway on the MQTT and XMPP networks')
    parser.add_option('-t', '--registrationtopic', dest='registrationTopic', default=None,
                       type='string', help='Specify the MQTT topic that the gateway will listen for registration messages on')
    parser.add_option('-j', '--gatewayjid', dest='gatewayJid', default=None, type='string',
                       help='Specify the JID used to publish and subscribe to XMPP messages')
    parser.add_option('-p', '--gatewaypassword', dest='gatewayPassword', default=None, type='string',
                       help='Specify the password used to connect using the specified JID')
    
    (options, args) = parser.parse_args()
    
    # CHECK THIS AT SOME POINT
    gateway = GatewayService(options.gatewayId, options.registrationTopic, options.xmppServer, 
                             options.gatewayJid, options.gatewayPassword, options.mqttBroker)
    import sys
    log.startLogging(sys.stdout)
    
    reactor.run()
예제 #8
0
def run(**settings):
    """Start the application.

    Parameters:

    host: Interface to listen on. [default: 0.0.0.0]

    port: TCP port to listen on. [default: 8888]

    log: The log file to use, the default is sys.stdout.

    base_handler: The class or factory for request handlers. The default
                  is cyclone.web.RequestHandler.

    more_handlers: A regular list of tuples containing regex -> handler

    All other parameters are passed directly to the `cyclone.web.Application`
    constructor.
    """

    port = settings.get("port", 8888)
    interface = settings.get("host", "0.0.0.0")
    log.startLogging(settings.pop("log", sys.stdout))
    reactor.listenTCP(port, create_app(**settings), interface=interface)
    reactor.run(installSignalHandlers = False)
예제 #9
0
def main(argv):
    options = parse_options(argv[1:])
    if options.log:
        log.startLogging(sys.stdout)
    factory = FtpServerFactory(options.root_path, options.port)
    factory.makeListener()
    twisted.internet.reactor.run()
예제 #10
0
파일: catalog.py 프로젝트: mysoftpro/pc
 def pr(self, fail):
     log.startLogging(sys.stdout)
     log.msg(fail)
     send_email('*****@*****.**',
                u'Ошибка обновления каталога',
                unicode(fail),
                sender=u'Компьютерный магазин <*****@*****.**>')
예제 #11
0
def main():
    users = {'testadmin': 'x'}

    log.startLogging(sys.stderr)

    MockSSH.runServer(
        commands, prompt="hostname>", interface='127.0.0.1', port=9999, **users)
예제 #12
0
파일: script.py 프로젝트: huangpanxx/POAS
def execute(config_file):
    global config
    config = _get_config(config_file)
    log.startLogging(sys.stderr)
    application = get_application(config)
    app.startApplication(application, False)
    reactor.run() #@UndefinedVariable
예제 #13
0
    def __init__(self, save_dir=".", 
                       listen_port=6881, 
                       enable_DHT=False,
                       remote_debugging=False):
        """
        @param remote_degugging enables telnet login via port 9999 with a
            username and password of 'admin'
        """
        log.startLogging(sys.stdout) # Start logging to stdout
        self.save_dir = save_dir
        self.listen_port = listen_port
        self.enable_DHT = enable_DHT
        self.tasks = {}
        self.btServer = BTServerFactories(self.listen_port)
        reactor.listenTCP(self.listen_port, self.btServer)
        if enable_DHT:
            log.msg("Turning DHT on.")
            self.dht = DHTProtocol()
            reactor.listenUDP(self.listen_port, self.dht)

        if remote_debugging:
            log.msg("Turning remote debugging on. You may login via telnet " +\
                "on port 9999 username & password are 'admin'")
            import twisted.manhole.telnet
            dbg = twisted.manhole.telnet.ShellFactory()
            dbg.username = "******"
            dbg.password = "******"
            dbg.namespace['app'] = self 
            reactor.listenTCP(9999, dbg)
예제 #14
0
파일: container.py 프로젝트: LCROBOT/rce
def main(reactor, commID, masterIP, masterPort, masterID):
    f = open('/home/rce-user/container.log', 'w')
    log.startLogging(f)
    #log.startLogging(sys.stdout)
    
    manager = ContainerManager(reactor)
    commManager = CommManager(reactor, commID)
    cmdSerializer = CommandSerializer()
    cmdSerializer.registerCommand([ContainerCommand])
    commManager.registerContentSerializers([CommInfoSerializer(),
                                            cmdSerializer,
                                            TagSerializer()])
    
    distributor = ControlDistributor()
    distributor.addHandler(types.CONTAINER, manager.createContainer)
    distributor.addHandler(types.RM_CONTAINER, manager.destroyContainer)
    commManager.registerMessageProcessors([CommInfoProcessor(manager),
                                           CommandProcessor(distributor),
                                           TagProcessor(distributor)])
    
    factory = RCEClientFactory(commManager, masterID)
    factory.addApprovedMessageTypes([msgTypes.COMM_INFO, msgTypes.COMMAND,
                                     msgTypes.TAG])
    reactor.connectTCP(masterIP, masterPort, factory)
    
    reactor.addSystemEventTrigger('before', 'shutdown', manager.shutdown)
    reactor.addSystemEventTrigger('before', 'shutdown', commManager.shutdown)
    
    reactor.run()
    
    f.close()
예제 #15
0
def start_logging(out=_stdout, level='info'):
    """
    Start logging to the file-like object in ``out``. By default, this
    is stdout.
    """
    global _loggers, _observer, _log_level, _started_logging

    if level not in log_levels:
        raise RuntimeError(
            "Invalid log level '{0}'; valid are: {1}".format(
                level, ', '.join(log_levels)
            )
        )

    if _started_logging:
        return

    _started_logging = True

    _log_level = level
    set_global_log_level(_log_level)

    if out:
        _observer = _LogObserver(out)

    if _NEW_LOGGER:
        _observers = []
        if _observer:
            _observers.append(_observer)
        globalLogBeginner.beginLoggingTo(_observers)
    else:
        assert out, "out needs to be given a value if using Twisteds before 15.2"
        from twisted.python import log
        log.startLogging(out)
예제 #16
0
def main(args):
    """ Run forever, grab an image every N seconds. """

    if args["--log"] == True:
        log_filename = "rand_imgur.log"
        log.startLogging(open(log_filename, "a"))
    else:
        log.startLogging(sys.stdout)

    tried_log_path = "tried.log"
    if os.path.exists(tried_log_path):
        tried_log = open(tried_log_path, "r")
        tried = tried_log.readlines()
        tried_log.close()
    else:
        tried = None

    tried_log = open(tried_log_path, "a+")

    while True:
        url, imgur_name = gen_url()
        if not url in tried:
            grab_image(url, imgur_name, args["--directory"])
            tried.append(url)
            tried_log.write(url + "\n")
        else:
            log.msg("Found {url} in list, not trying.".format(url=url))

        sleep(float(args["--interval"]))
예제 #17
0
def main():
	import argparse
	import sys

	def serverEndpoint(x):
		return endpoints.serverFromString(reactor, x)

	def listenFailed(reason):
		log.err(reason)
		reactor.stop()

	def serverListening(_):
		log.msg("NBD Server running")

	log.startLogging(sys.stderr)

	parser = argparse.ArgumentParser(description='NBD Server')
	parser.add_argument('--listen',
		help='Endpoint address to listen on',
		type=serverEndpoint,
		default='tcp:10809:interface=127.0.0.1')
	parser.add_argument('--readonly',
		help='Make the export read-only',
		action='store_true')
	parser.add_argument('filename',
		help='File to serve')
	args = parser.parse_args()

	bdev = FileBlockDevice(args.filename, args.readonly)
	f = NBDServerFactory({os.path.basename(args.filename): bdev})
	d = args.listen.listen(f)
	d.addErrback(listenFailed)
	d.addCallback(serverListening)
	reactor.run()
예제 #18
0
def main(type):
    log.startLogging(sys.stderr, setStdout=False)

    if type == "1":
        client_factory = client_server.Factory()
        reactor.connectTCP('127.0.0.1', 8125, client_factory)
    else :
        client_factory = client_server.FactoryUDP()
        reactor.listenUDP(0, client_factory)


    def wait_for_protocol():
        while len(client_factory.instances) == 0:
            time.sleep(1)

        return True

    d = threads.deferToThread(wait_for_protocol)

    def run_loop(_):
        proc = CommandProcessor(client_factory.instances[0])
        reactor.callInThread(proc.cmdloop)

    d.addCallback(run_loop)

    reactor.run()
예제 #19
0
def main():
    from twisted.internet import reactor
    from twisted.python import log
    import sys
    log.startLogging(sys.stdout)
    reactor.listenTCP(0, RemoteCalculationFactory())
    reactor.run()
예제 #20
0
파일: cli.py 프로젝트: darioodiaz/crossbar
def run_command_start(options):
   """
   Subcommand "crossbar start".
   """
   ## start Twisted logging
   ##
   log.startLogging(sys.stderr)

   log.msg("Crossbar.io {} node starting".format(crossbar.__version__))

   ## we use an Autobahn utility to import the "best" available Twisted reactor
   ##
   reactor = install_reactor(options.reactor, options.debug)

   #if options.debug:
   #   print("Running on reactor {}".format(reactor))

   ## create and start Crossbar.io node
   ##
   node = Node(reactor, options.cbdir, options.debug)
   node.start()

   ## enter event loop
   ##
   reactor.run()
예제 #21
0
    def run(self):
        from twisted.internet import reactor
        from twisted.python import log
        import sys
        # FIXME: fix this namespace
        from Hellanzb.NZBLeecher import NZBLeecherFactory

        #from twisted.internet import cReactor
        #cReactor.install()
        
        # initialize logging
        log.startLogging(sys.stdout)
    
        # create factory protocol and application
        nsf = NZBLeecherFactory()
    
        #from Hellanzb.NZBLeecher.NZBModel import NZBSegmentQueue
        #Hellanzb.queue = NZBSegmentQueue(sys.argv[1])
    
        # connect factory to this host and port
        reactor.connectTCP('unlimited.newshosting.com', 9000, nsf)
        #reactor.connectTCP('unlimited.newshosting.com', 9000, nsf)
        #reactor.connectTCP('unlimited.newshosting.com', 9000, nsf)
        #reactor.connectTCP('unlimited.newshosting.com', 9000, nsf)
    
        # run
        #reactor.run()
        print 'running'
        reactor.run(installSignalHandlers = False)
예제 #22
0
def run_server(fd=None, port=None, procs=None, verbose=False):
    if args.verbose:
        log.startLogging(stdout)
        environ['SOLEDAD_LOG_TO_STDOUT'] = '1'

    config = get_config()
    path = config["blobs_path"]
    if not port:
        port = int(config["blobs_port"])

    root = Resource()
    root.putChild('blobs', BlobsResource("filesystem", path))
    factory = Site(root)

    if fd is None:
        # Create a new listening port and several other
        # processes to help out.
        if procs is None:
            procs = cpu_count()
        log.msg('A total of %d processes will listen on port %d.' % (procs, port))
        port = reactor.listenTCP(port, factory)
        for i in range(procs - 1):
            reactor.spawnProcess(
                None, executable, [executable, __file__, str(port.fileno())],
                childFDs={0: 0, 1: 1, 2: 2, port.fileno(): port.fileno()},
                env=environ)
    else:
        # Another process created the port, just start listening on it.
        log.msg('Adopting file descriptor %d...' % fd)
        port = reactor.adoptStreamPort(fd, AF_INET, factory)

    reactor.run()
    def __init__(self, port, debug):
        if debug:
            log.startLogging(sys.stdout)

        self.server = WampServerFactory("ws://localhost:"+ str(port), debug)
        self.server.protocol = LogeeProtocol
        listenWS(self.server)
예제 #24
0
def startLogging(logfilename):
    if logfilename == '-' or not logfilename:
        logFile = sys.stdout
    else:
        logFile = app.getLogFile(logfilename)
    log.startLogging(logFile)
    sys.stdout.flush()
예제 #25
0
def main():
    log.startLogging(sys.stderr)

    conf_file = os.path.join(
        xdg.BaseDirectory.save_config_path('socialsound'),
        'config.ini')
    config = ConfigObj(conf_file)

    username = config['Pandora']['username']
    password = config['Pandora']['password']

    proxy = config.get('Proxy', {})
    proxy_host = proxy.get('host', None)
    proxy_port = proxy.get('port', None)
    proxy = {}
    if proxy_host: proxy['proxy_host'] = proxy_host
    if proxy_port: proxy['proxy_port'] = proxy_port

    # Start websocket listener
    factory = PandoraFactory("ws://localhost:9000", debug=False,
                             username=username, password=password, **proxy)
    factory.protocol = PandoraProtocol
    listenWS(factory)

    # Start the MPD client factory.
    factory.player = PlayerFactory()
    reactor.connectTCP(MPD_HOST, MPD_PORT, factory.player)

    reactor.run()
예제 #26
0
def run():
    args = PARSER.parse_args()

    # Unpack values. Each should be a list of one item (hence the
    # comma. Yay list unpacking)
    private_key, = args.private_key
    public_key, = args.public_key
    webserver_address, = args.webserver_address
    webserver_user, = args.webserver_user
    webserver_password, = args.webserver_password
    port = int(args.port)

    log.startLogging(sys.stderr)
    log.startLogging(open('gitssh.log', 'w'))

    components.registerAdapter(GitSession, GitConchUser, ISession)

    # Set up authorization
    GitServer.meta = GitMeta(webserver_address,
                             webserver_user, webserver_password)
    GitServer.portal = Portal(GitRealm(GitServer.meta))
    GitServer.portal.registerChecker(TeamPasswordChecker(GitServer.meta))

    # Instantiate a server
    server = GitServer(os.path.abspath(private_key),
                       os.path.abspath(public_key))

    # Start listening
    reactor.listenTCP(port, server)
    reactor.run()
예제 #27
0
파일: app.py 프로젝트: Arttii/deps
    def run(self, host, port, logFile=None):
        """
        Run a minimal twisted.web server on the specified C{port}, bound to the
        interface specified by C{host} and logging to C{logFile}.

        This function will run the default reactor for your platform and so
        will block the main thread of your application.  It should be the last
        thing your klein application does.

        @param host: The hostname or IP address to bind the listening socket
            to.  "0.0.0.0" will allow you to listen on all interfaces, and
            "127.0.0.1" will allow you to listen on just the loopback interface.
        @type host: str

        @param port: The TCP port to accept HTTP requests on.
        @type port: int

        @param logFile: The file object to log to, by default C{sys.stdout}
        @type logFile: file object
        """
        if logFile is None:
            logFile = sys.stdout

        log.startLogging(logFile)
        reactor.listenTCP(port, Site(self.resource()), interface=host)
        reactor.run()
예제 #28
0
파일: util.py 프로젝트: hosle/tapas
def init_logging(logdir, logname):
    if DEBUG_LEVEL > 0:
        log.startLogging(sys.stdout)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    logfile = get_path(os.path.join(logdir, logname))
    log.startLogging(DailyLogFile.fromFullPath(logfile))
예제 #29
0
파일: __init__.py 프로젝트: yaccz/redirbot
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--config", type=str, help="config file")
    parser.add_argument("-V", "--version", action="store_true", default=False)
    args = parser.parse_args()

    if args.version:
        print __version__
        exit(0)

    cp = SafeConfigParser()
    cp.read(args.config)
    # initialize logging
    log.startLogging(sys.stdout)

    # create factory protocol and application
    bot_cnf = {
        "nickname": cp.get("main", "nickname_bot"),
        "nickname_user": cp.get("main", "nickname_user"),
        "channels": cp.get("main", "channels").split(" "),
        "filename": cp.get("main", "logfile"),
        "filename_raw": cp.get("main", "logfile_raw"),
    }

    f = BotFactory(**bot_cnf)
    reactor.connectTCP(cp.get("server", "host"), cp.getint("server", "port"), f)
    reactor.run()
예제 #30
0
파일: master.py 프로젝트: Aerobota/rce
def main(reactor, internalCred, externalCred, internalPort, externalPort,
         commPort, consolePort):
    log.startLogging(sys.stdout)

    # Realms
    rce = RoboEarthCloudEngine(externalCred, commPort)
    user = UserRealm(rce)

    internalCred.add_checker(rce.checkUIDValidity)

    # Portals
    rcePortal = Portal(rce, (internalCred,))
    consolePortal = Portal(user, (externalCred,))

    # Internal Communication
    reactor.listenTCP(internalPort, PBServerFactory(rcePortal))

    # Client Connections
    reactor.listenTCP(consolePort, PBServerFactory(consolePortal))
    reactor.listenTCP(externalPort, Site(RobotResource(rce)))

    reactor.addSystemEventTrigger('before', 'shutdown', rce.preShutdown)
    reactor.addSystemEventTrigger('after', 'shutdown', rce.postShutdown)

    reactor.run()
예제 #31
0
파일: server.py 프로젝트: iSasuke7/piccolo
    def __init__(self, interface: bytes, config_dict: Dict[str, Any]) -> None:
        self.config = config_dict
        if random_rotation:
            self.map_rotator_type = random_choice_cycle
        else:
            self.map_rotator_type = itertools.cycle  # pylint: disable=redefined-variable-type
        self.default_time_limit = default_time_limit.get()
        self.default_cap_limit = cap_limit.get()
        self.advance_on_win = int(advance_on_win.get())
        self.win_count = itertools.count(1)
        self.bans = NetworkDict()

        # attempt to load a saved bans list
        try:
            with open(os.path.join(config.config_dir, bans_file.get()), 'r') as f:
                self.bans.read_list(json.load(f))
        except FileNotFoundError:
            pass
        except IOError as e:
            print('Could not read bans.txt: {}'.format(e))
        except ValueError as e:
            print('Could not parse bans.txt: {}'.format(e))

        self.hard_bans = set()  # possible DDoS'ers are added here
        self.player_memory = deque(maxlen=100)
        if len(self.name) > MAX_SERVER_NAME_SIZE:
            print('(server name too long; it will be truncated to "%s")' % (
                self.name[:MAX_SERVER_NAME_SIZE]))
        self.respawn_time = respawn_time_option.get()
        self.respawn_waves = respawn_waves.get()
        if game_mode.get() == 'ctf':
            self.game_mode = CTF_MODE
        elif game_mode.get() == 'tc':
            self.game_mode = TC_MODE
        elif self.game_mode is None:
            raise NotImplementedError('invalid game mode: %s' % game_mode)
        self.game_mode_name = game_mode.get().split('.')[-1]
        self.team1_name = team1_name.get()
        self.team2_name = team2_name.get()
        self.team1_color = tuple(team1_color.get())
        self.team2_color = tuple(team2_color.get())
        self.friendly_fire = friendly_fire.get()
        self.friendly_fire_on_grief = friendly_fire_on_grief.get()
        self.friendly_fire_time = grief_friendly_fire_time.get()
        self.spade_teamkills_on_grief = spade_teamkills_on_grief.get()
        self.fall_damage = fall_damage.get()
        self.teamswitch_interval = teamswitch_interval.get()
        self.teamswitch_allowed = teamswitch_allowed.get()
        self.max_players = max_players.get()
        self.melee_damage = melee_damage.get()
        self.max_connections_per_ip = max_connections_per_ip.get()
        self.passwords = passwords.get()
        self.server_prefix = server_prefix.get()
        self.time_announcements = time_announcements.get()
        self.balanced_teams = balanced_teams.get()
        self.login_retries = login_retries.get()

        # voting configuration
        self.default_ban_time = default_ban_duration.get()

        self.speedhack_detect = speedhack_detect.get()
        if user_blocks_only.get():
            self.user_blocks = set()
        self.set_god_build = set_god_build.get()
        self.debug_log = debug_log_enabled.get()
        if self.debug_log:
            # TODO: make this configurable
            pyspades.debug.open_debug_log(
                os.path.join(config.config_dir, 'debug.log'))
        if ssh_enabled.get():
            from piccolo.ssh import RemoteConsole
            self.remote_console = RemoteConsole(self)
        irc = irc_options.get()
        if irc.get('enabled', False):
            from piccolo.irc import IRCRelay
            self.irc_relay = IRCRelay(self, irc)
        if status_server_enabled.get():
            from piccolo.statusserver import StatusServerFactory
            self.status_server = StatusServerFactory(self)
        if ban_publish.get():
            from piccolo.banpublish import PublishServer
            self.ban_publish = PublishServer(self, ban_publish_port.get())
        if ban_subscribe_enabled.get():
            from piccolo import bansubscribe
            self.ban_manager = bansubscribe.BanManager(self)
        # logfile path relative to config dir if not abs path
        l = logfile.get()
        if l.strip():  # catches empty filename
            if not os.path.isabs(l):
                l = os.path.join(config.config_dir, l)
            ensure_dir_exists(l)
            if logging_rotate_daily.get():
                logging_file = DailyLogFile(l, '.')
            else:
                logging_file = open(l, 'a')
            log.addObserver(log.FileLogObserver(logging_file).emit)
            log.msg('pyspades server started on %s' % time.strftime('%c'))
        log.startLogging(sys.stdout)  # force twisted logging

        self.start_time = reactor.seconds()
        self.end_calls = []
        # TODO: why is this here?
        create_console(self)

        for user_type, func_names in rights.get().items():
            for func_name in func_names:
                commands.add_rights(user_type, func_name)

        port = self.port = port_option.get()
        ServerProtocol.__init__(self, port, interface)
        self.host.intercept = self.receive_callback
        try:
            self.set_map_rotation(self.config['rotation'])
        except MapNotFound as e:
            print('Invalid map in map rotation (%s), exiting.' % e.map)
            raise SystemExit

        self.update_format()
        self.tip_frequency = tip_frequency.get()
        if self.tips is not None and self.tip_frequency > 0:
            reactor.callLater(self.tip_frequency * 60, self.send_tip)

        self.master = register_master_option.get()
        self.set_master()

        self.http_agent = web_client.Agent(reactor)

        ip_getter = ip_getter_option.get()
        if ip_getter:
            self.get_external_ip(ip_getter)
예제 #32
0
        if client not in self.clients:
            print("registered client {}".format(client.peer))
            self.clients.append(client)

    def unregister(self, client):
        if client in self.clients:
            print("unregistered client {}".format(client.peer))
            self.clients.remove(client)

    def forward(self, payload, sender, isBinary):
        for c in self.clients:
            if c.peer != sender:
                c.sendMessage(payload, isBinary)


if __name__ == '__main__':
    from twisted.python import log
    log.startLogging(sys.stdout)

    wsfactory = PSFactory()
    wsfactory.protocol = PSProto
    wsfactory.startFactory()
    wsres = WebSocketResource(wsfactory)

    root = File(".")
    root.putChild("ws", wsres)

    site = Site(root)
    reactor.listenTCP(8080, site)
    reactor.run()
예제 #33
0
        """
        log.msg("Received response from proxied service: " + repr(response))
        return defer.succeed(response)


if __name__ == '__main__':
    """
    Demonstration LDAP proxy; listens on localhost:10389; passes all requests
    to localhost:8080 and logs responses..
    """
    from ldaptor.protocols.ldap.ldapclient import LDAPClient
    from twisted.internet import protocol, reactor
    from functools import partial
    import sys

    log.startLogging(sys.stderr)
    factory = protocol.ServerFactory()
    proxiedEndpointStr = 'tcp:host=localhost:port=8080'
    use_tls = False
    clientConnector = partial(ldapconnector.connectToLDAPEndpoint, reactor,
                              proxiedEndpointStr, LDAPClient)

    def buildProtocol():
        proto = ExampleProxy()
        proto.clientConnector = clientConnector
        proto.use_tls = use_tls
        return proto

    factory.protocol = buildProtocol
    reactor.listenTCP(10389, factory)
    reactor.run()
예제 #34
0
 def opt_verbose(self):
     from twisted.python import log
     log.startLogging(sys.stderr)
예제 #35
0
def demo():
    log.startLogging(sys.stdout)
    app = MyApp(0)
    reactor.registerWxApp(app)
    reactor.run()
예제 #36
0
 def disable_logger(self):
     temp_name = path.join(gettempdir(), next(_get_candidate_names()))
     tlog.startLogging(open(temp_name, 'w'), setStdout=False)
예제 #37
0
        log.msg("RIGHT")

    def up_right(self):
        log.msg("right")

    def move(self, x, y):
        log.msg("(%d,%d)" % (x, y))


if __name__ == '__main__':
    from twisted.internet import reactor
    from twisted.internet.serialport import SerialPort
    o = Options()
    try:
        o.parseOptions()
    except usage.UsageError as errortext:
        print "%s: %s" % (sys.argv[0], errortext)
        print "%s: Try --help for usage details." % (sys.argv[0])
        raise SystemExit(1)

    logFile = sys.stdout
    if o.opts['outfile']:
        logFile = o.opts['outfile']
    log.startLogging(logFile)

    SerialPort(McFooMouse(),
               o.opts['port'],
               reactor,
               baudrate=int(o.opts['baudrate']))
    reactor.run()
예제 #38
0
def main():
    startLogging(stdout)
    serverFactory = AMPRouteServerFactory()
    serverFactory.routeProtocol = Counter
    reactor.listenTCP(7805, serverFactory)
    reactor.run()
예제 #39
0
    myPort = default_port
    logfile = None

    if myOpts["port"]:
        myPort = int(myOpts["port"])
        if myPort < 1025 or myPort > 65535:
            myPort = default_port

    if myOpts["window"]:
        logfile = "/tmp/Fake_Mercury_%d.log" % (myPort)

    if myOpts["logfile"]:
        logfile = myOpts["logfile"]

    if logfile:
        log.startLogging(open(logfile, "w"))
    else:
        log.startLogging(sys.stdout)
        #log.startLogging(sys.stderr)

    if myOpts["window"]:
        import curses

        stdscr = curses.initscr()
        screen = MyScreen(stdscr)
        # add screen object as a reader to the reactor
        reactor.addReader(screen)

    myFactory = MercuryFactory(MercuryProtocol, myDev, "\r")
    lc = LoopingCall(device_display)
    lc.start(0.250)
예제 #40
0
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import platform
if "Windows" not in platform.system():
    print "Linux System! Use epoll"
    from twisted.internet import epollreactor
    epollreactor.install()
from twisted.internet import reactor ,ssl,threads,defer
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.python import log
import time,os
if not os.path.exists('log'):
    os.makedirs('log')
log.startLogging(open('log/blackfilter_%s'% time.strftime('%Y_%m_%d'),'a'))
from twisted.internet.threads import deferToThread
reactor.suggestThreadPoolSize(200000)
import socket
socket.setdefaulttimeout(80)
import json
from twisted.web.server import NOT_DONE_YET

all_proxy = set()
black_proxy = set()
import threading

def func():
    all_proxy.clear()
    black_proxy.clear()
    threading.Timer(3600*24, func).start()
예제 #41
0
def ygmain(ygclass, txfee=1000, cjfee_a=200, cjfee_r=0.002, ordertype='swreloffer',
           nickserv_password='', minsize=100000, gaplimit=6):
    import sys

    parser = OptionParser(usage='usage: %prog [options] [wallet file]')
    parser.add_option('-o', '--ordertype', action='store', type='string',
                      dest='ordertype', default=ordertype,
                      help='type of order; can be either reloffer or absoffer')
    parser.add_option('-t', '--txfee', action='store', type='int',
                      dest='txfee', default=txfee,
                      help='minimum miner fee in satoshis')
    parser.add_option('-c', '--cjfee', action='store', type='string',
                      dest='cjfee', default='',
                      help='requested coinjoin fee in satoshis or proportion')
    parser.add_option('-p', '--password', action='store', type='string',
                      dest='password', default=nickserv_password,
                      help='irc nickserv password')
    parser.add_option('-s', '--minsize', action='store', type='int',
                      dest='minsize', default=minsize,
                      help='minimum coinjoin size in satoshis')
    parser.add_option('-g', '--gap-limit', action='store', type="int",
                      dest='gaplimit', default=gaplimit,
                      help='gap limit for wallet, default='+str(gaplimit))
    parser.add_option('--fast',
                      action='store_true',
                      dest='fastsync',
                      default=False,
                      help=('choose to do fast wallet sync, only for Core and '
                      'only for previously synced wallet'))
    (options, args) = parser.parse_args()
    if len(args) < 1:
        parser.error('Needs a wallet')
        sys.exit(0)
    wallet_name = args[0]
    ordertype = options.ordertype
    txfee = options.txfee
    if ordertype == 'swreloffer':
        if options.cjfee != '':
            cjfee_r = options.cjfee
        # minimum size is such that you always net profit at least 20%
        #of the miner fee
        minsize = max(int(1.2 * txfee / float(cjfee_r)), options.minsize)
    elif ordertype == 'swabsoffer':
        if options.cjfee != '':
            cjfee_a = int(options.cjfee)
        minsize = options.minsize
    else:
        parser.error('You specified an incorrect offer type which ' +\
                     'can be either swreloffer or swabsoffer')
        sys.exit(0)
    nickserv_password = options.password

    load_program_config()
    if not os.path.exists(os.path.join('wallets', wallet_name)):
        wallet = SegwitWallet(wallet_name, None, max_mix_depth=MAX_MIX_DEPTH,
                              gaplimit=options.gaplimit)
    else:
        while True:
            try:
                pwd = get_password("Enter wallet decryption passphrase: ")
                wallet = SegwitWallet(wallet_name, pwd,
                                      max_mix_depth=MAX_MIX_DEPTH,
                                      gaplimit=options.gaplimit)
            except WalletError:
                print("Wrong password, try again.")
                continue
            except Exception as e:
                print("Failed to load wallet, error message: " + repr(e))
                sys.exit(0)
            break
    if jm_single().config.get("BLOCKCHAIN", "blockchain_source") == "electrum-server":
        jm_single().bc_interface.synctype = "with-script"
    sync_wallet(wallet, fast=options.fastsync)

    maker = ygclass(wallet, [options.txfee, cjfee_a, cjfee_r,
                             options.ordertype, options.minsize])
    jlog.info('starting yield generator')
    clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER")

    nodaemon = jm_single().config.getint("DAEMON", "no_daemon")
    daemon = True if nodaemon == 1 else False
    if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]:
        startLogging(sys.stdout)
    start_reactor(jm_single().config.get("DAEMON", "daemon_host"),
                      jm_single().config.getint("DAEMON", "daemon_port"),
                      clientfactory, daemon=daemon)
예제 #42
0
# License: Copyright(c) 2013 Don.Li
# Summary:

import time
import sys, os
sys.path.insert(0, '../lib')

from twisted.python.log import startLogging, msg
from twisted.internet import reactor, defer
from rpc import ConnectorCreator

# log路径
log_path = r'./logs/pvp.log'
if os.path.exists(log_path):
    os.remove(log_path)
startLogging(open(log_path, 'w'))

# 服务器IP、port, 配置见../etc/env.conf
HOST = '192.168.8.233'
PORT = 28001

# 用于测试的用户数量
TOTAL_USER = 2
# 时间间隔
INTERVAL_ARENA = 5
INTERVAL_TREASURESHARD = 8

global RESULT
global DURATION
# 统计状态值
RESULT = []
예제 #43
0
class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()


class Close(protocol.Protocol):
    def connectionMade(self):
        self.transport.loseConnection()


class CloseFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Close()


log.startLogging(sys.stdout, False)

import pudb
pudb.set_trace()

echo = EchoFactory()
close = CloseFactory()

s = SockJSMultiFactory()
s.addFactory(echo, "echo", {'streaming_limit': 4 * 1024})
s.addFactory(close, "close", {'streaming_limit': 4 * 1024})
s.addFactory(echo, "disabled_websocket_echo", {
    'websocket': False,
    'streaming_limit': 4 * 1024
})
s.addFactory(echo, "cookie_needed_echo", {
예제 #44
0
def main():
    startLogging(file('calamity.log', 'w'))
    runWithProtocol(Cockpit)
예제 #45
0
    def __init__(self, interface, config):
        self.config = config
        if config.get('random_rotation', False):
            self.map_rotator_type = random_choice_cycle
        else:
            self.map_rotator_type = itertools.cycle  # pylint: disable=redefined-variable-type
        self.default_time_limit = config.get('default_time_limit', 20.0)
        self.default_cap_limit = config.get('cap_limit', 10.0)
        self.advance_on_win = int(config.get('advance_on_win', False))
        self.win_count = itertools.count(1)
        self.bans = NetworkDict()
        # TODO: check if this is actually working and not silently failing
        try:
            self.bans.read_list(
                json.load(open(os.path.join(cfg.config_dir, 'bans.txt'), 'rb')))
        except IOError:
            pass
        self.hard_bans = set()  # possible DDoS'ers are added here
        self.player_memory = deque(maxlen=100)
        self.config = config
        if len(self.name) > MAX_SERVER_NAME_SIZE:
            print('(server name too long; it will be truncated to "%s")' % (
                self.name[:MAX_SERVER_NAME_SIZE]))
        self.respawn_time = config.get('respawn_time', 8)
        self.respawn_waves = config.get('respawn_waves', False)
        game_mode = config.get('game_mode', 'ctf')
        if game_mode == 'ctf':
            self.game_mode = CTF_MODE
        elif game_mode == 'tc':
            self.game_mode = TC_MODE
        elif self.game_mode is None:
            raise NotImplementedError('invalid game mode: %s' % game_mode)
        self.game_mode_name = game_mode
        team1 = config.get('team1', {})
        team2 = config.get('team2', {})
        self.team1_name = team1.get('name', 'Blue')
        self.team2_name = team2.get('name', 'Green')
        self.team1_color = tuple(team1.get('color', (0, 0, 196)))
        self.team2_color = tuple(team2.get('color', (0, 196, 0)))
        self.friendly_fire = config.get('friendly_fire', True)
        self.friendly_fire_time = config.get('grief_friendly_fire_time', 2.0)
        self.spade_teamkills_on_grief = config.get('spade_teamkills_on_grief',
                                                   False)
        self.fall_damage = config.get('fall_damage', True)
        self.teamswitch_interval = config.get('teamswitch_interval', 0)
        self.max_players = config.get('max_players', 20)
        self.melee_damage = config.get('melee_damage', 100)
        self.max_connections_per_ip = config.get('max_connections_per_ip', 0)
        self.passwords = config.get('passwords', {})
        self.server_prefix = encode(config.get('server_prefix', '[*]'))
        self.time_announcements = config.get('time_announcements',
                                             [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                                              30, 60, 120, 180, 240, 300, 600,
                                              900, 1200, 1800, 2400, 3000])
        self.balanced_teams = config.get('balanced_teams', None)
        self.login_retries = config.get('login_retries', 1)

        # voting configuration
        self.default_ban_time = config.get('default_ban_duration', 24 * 60)

        self.speedhack_detect = config.get('speedhack_detect', True)
        if config.get('user_blocks_only', False):
            self.user_blocks = set()
        self.set_god_build = config.get('set_god_build', False)
        self.debug_log = config.get('debug_log', False)
        if self.debug_log:
            pyspades.debug.open_debug_log(
                os.path.join(cfg.config_dir, 'debug.log'))
        ssh = config.get('ssh', {})
        if ssh.get('enabled', False):
            from piqueserver.ssh import RemoteConsole
            self.remote_console = RemoteConsole(self, ssh)
        irc = config.get('irc', {})
        if irc.get('enabled', False):
            from piqueserver.irc import IRCRelay
            self.irc_relay = IRCRelay(self, irc)
        status = config.get('status_server', {})
        if status.get('enabled', False):
            from piqueserver.statusserver import StatusServerFactory
            self.status_server = StatusServerFactory(self, status)
        publish = config.get('ban_publish', {})
        if publish.get('enabled', False):
            from piqueserver.banpublish import PublishServer
            self.ban_publish = PublishServer(self, publish)
        ban_subscribe = config.get('ban_subscribe', {})
        if ban_subscribe.get('enabled', True):
            from piqueserver import bansubscribe
            self.ban_manager = bansubscribe.BanManager(self, ban_subscribe)
        # logfile path relative to config dir if not abs path
        logfile = config.get('logfile', '')
        if not os.path.isabs(logfile):
            logfile = os.path.join(cfg.config_dir, logfile)
        if logfile.strip():  # catches empty filename
            if config.get('rotate_daily', False):
                create_filename_path(logfile)
                logging_file = DailyLogFile(logfile, '.')
            else:
                logging_file = open_create(logfile, 'a')
            log.addObserver(log.FileLogObserver(logging_file).emit)
            log.msg('pyspades server started on %s' % time.strftime('%c'))
        log.startLogging(sys.stdout)  # force twisted logging

        self.start_time = reactor.seconds()
        self.end_calls = []
        # TODO: why is this here?
        create_console(self)

        # check for default password usage
        for group, passwords in self.passwords.items():
            if group in DEFAULT_PASSWORDS:
                for password in passwords:
                    if password in DEFAULT_PASSWORDS[group]:
                        print(("WARNING: FOUND DEFAULT PASSWORD '%s'"
                               " IN GROUP '%s'" % (password, group)))

        for password in self.passwords.get('admin', []):
            if not password:
                self.everyone_is_admin = True

        for user_type, func_names in config.get('rights', {}).items():
            for func_name in func_names:
                commands.add_rights(user_type, func_name)

        port = self.port = config.get('port', 32887)
        ServerProtocol.__init__(self, port, interface)
        self.host.intercept = self.receive_callback
        ret = self.set_map_rotation(config['maps'])
        if not ret:
            print('Invalid map in map rotation (%s), exiting.' % ret.map)
            raise SystemExit

        self.update_format()
        self.tip_frequency = config.get('tip_frequency', 0)
        if self.tips is not None and self.tip_frequency > 0:
            reactor.callLater(self.tip_frequency * 60, self.send_tip)

        self.master = config.get('master', True)
        self.set_master()

        get_external_ip(config.get('network_interface', '').encode()).addCallback(
            self.got_external_ip)
예제 #46
0
    def readConnectionLost(self):
        """
        This is the desired event.  Once it has happened, stop the reactor so
        the process will exit.
        """
        self.exitCode = 0
        reactor.stop()


    def connectionLost(self, reason):
        """
        This may only be invoked after C{readConnectionLost}.  If it happens
        otherwise, mark it as an error and shut down.
        """
        if self.exitCode is None:
            self.exitCode = 1
            log.err(reason, "Unexpected call to connectionLost")
        reactor.stop()



if __name__ == '__main__':
    reflect.namedAny(sys.argv[1]).install()
    log.startLogging(file(sys.argv[2], 'w'))
    from twisted.internet import reactor
    protocol = HalfCloseProtocol()
    stdio.StandardIO(protocol)
    reactor.run()
    sys.exit(protocol.exitCode)
예제 #47
0
 try:
     options.parseOptions(args)
 except usage.UsageError, u:
     print 'ERROR: %s' % u
     options.opt_help()
     sys.exit(1)
 if options['log']:
     if options['logfile']:
         if options['logfile'] == '-':
             f = sys.stdout
         else:
             f = file(options['logfile'], 'a+')
     else:
         f = sys.stderr
     realout = sys.stdout
     log.startLogging(f)
     sys.stdout = realout
 else:
     log.discardLogs()
 doConnect()
 fd = sys.stdin.fileno()
 try:
     old = tty.tcgetattr(fd)
 except:
     old = None
 try:
     oldUSR1 = signal.signal(signal.SIGUSR1,
                             lambda *a: reactor.callLater(0, reConnect))
 except:
     oldUSR1 = None
 try:
예제 #48
0
def failed(err):
    log.startLogging(sys.stderr)
    log.err(err)
예제 #49
0
파일: runner.py 프로젝트: pmisik/buildbot
 def opt_verbose(self):
     log.startLogging(sys.stderr)
예제 #50
0
def main():
    log.startLogging(sys.stdout)
    log.msg('Comenzando ejecucion...')
    reactor.listenTCP(16000, EchoServerFactory())
    reactor.run()
예제 #51
0
from twisted.internet import reactor, protocol
from autobahn.websocket.protocol import WebSocketProtocol, ConnectionRequest
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
from twisted.python.log import startLogging, msg
import txaio
txaio.use_twisted()
import sys
startLogging(sys.stdout)

# Examples:
# runner.py /bin/sh -c "tail -f /var/log/nginx/access.log | grep -v secret_admin_page" --line-buffered | awk '{\$1=\"\"; print}'"
# runner.py tail tail -F /var/log/nginx/access.log

COMMAND_NAME = sys.argv[1]
COMMAND_ARGS = sys.argv[1:]
LOCAL_ONLY = False
DEBUG = True


class ProcessProtocol(protocol.ProcessProtocol):
    """ I handle a child process launched via reactor.spawnProcess.
    I just buffer the output into a list and call WebSocketProcessOutputterThingFactory.broadcast when
    any new output is read
    """
    def __init__(self, websocket_factory):
        self.ws = websocket_factory
        self.buffer = []

    def outReceived(self, message):
        self.ws.broadcast(message)
        self.buffer.append(message)
예제 #52
0
                        nargs=2,
                        metavar=('key', 'secret'))
    parser.add_argument('--trades',
                        help='trade channels, eg TRADE-OK--BTC--CNY',
                        nargs='*',
                        default=None)
    parser.add_argument('--orders',
                        help='order channels, eg ORDER-OK--BTC--CNY',
                        nargs='*',
                        default=None)
    parser.add_argument('--config', help='config file', default=None)

    args = parser.parse_args()
    output = args.out
    if output == 'stdout':
        log.startLogging(sys.stdout)
    else:
        log.startLogging(open(output, 'w+'))

    # read the config file if any and apply overrides to it as requested
    config_dict = dict()
    if args.config is not None and os.path.exists(args.config):
        with open(args.config) as config_file:
            config_dict.update(json.load(config_file))

    if args.api:
        config_dict['api'] = dict(apiKey=args.api[0], apiSecret=args.api[1])

    if args.trades is not None:
        config_dict.setdefault('subscriptions', dict())['trade'] = args.trades
예제 #53
0
def main():  # Listen for TCP:1500
    log.startLogging(stdout)

    reactor.listenTCP(1500, Balancer([('127.0.0.1', 1600),
                                      ('127.0.0.1', 1601)]))
    reactor.run()
예제 #54
0
    wsgi_cb(
        str(code) + ' ' + httpStatusCodes.get(code, 'ERROR'), headers.items())
    return result


if __name__ == "__main__":

    params = namedParameters()
    port = params.get('socket', 8080)

    from twisted.web import server
    from twisted.web.wsgi import WSGIResource
    from twisted.python.threadpool import ThreadPool
    from twisted.python import log
    from twisted.internet import reactor
    from twisted.application import service, strports

    # Create and start a thread pool,
    wsgiThreadPool = ThreadPool(1, 1)
    wsgiThreadPool.start()

    # ensuring that it will be stopped when the reactor shuts down
    reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)

    reactor.listenTCP(
        port,
        server.Site(WSGIResource(reactor, wsgiThreadPool, wsgi_application)))
    log.startLogging(log.FileLogObserver(sys.stderr))
    reactor.run()
예제 #55
0
def ygmain(ygclass, nickserv_password='', gaplimit=6):
    import sys

    parser = OptionParser(usage='usage: %prog [options] [wallet file]')
    add_base_options(parser)
    # A note about defaults:
    # We want command line settings to override config settings.
    # This would naturally mean setting `default=` arguments here, to the
    # values in the config.
    # However, we cannot load the config until we know the datadir.
    # The datadir is a setting in the command line options, so we have to
    # call parser.parse_args() before we know the datadir.
    # Hence we do the following: set all modifyable-by-config arguments to
    # default "None" initially; call parse_args(); then call load_program_config
    # and override values of "None" with what is set in the config.
    # (remember, the joinmarket defaultconfig always sets every value, even if
    # the user doesn't).
    parser.add_option('-o',
                      '--ordertype',
                      action='store',
                      type='string',
                      dest='ordertype',
                      default=None,
                      help='type of order; can be either reloffer or absoffer')
    parser.add_option('-t',
                      '--txfee',
                      action='store',
                      type='int',
                      dest='txfee',
                      default=None,
                      help='minimum miner fee in satoshis')
    parser.add_option('-f',
                      '--txfee-factor',
                      action='store',
                      type='float',
                      dest='txfee_factor',
                      default=None,
                      help='variance around the average fee, decimal fraction')
    parser.add_option('-a',
                      '--cjfee-a',
                      action='store',
                      type='string',
                      dest='cjfee_a',
                      default=None,
                      help='requested coinjoin fee (absolute) in satoshis')
    parser.add_option('-r',
                      '--cjfee-r',
                      action='store',
                      type='string',
                      dest='cjfee_r',
                      default=None,
                      help='requested coinjoin fee (relative) as a decimal')
    parser.add_option('-j',
                      '--cjfee-factor',
                      action='store',
                      type='float',
                      dest='cjfee_factor',
                      default=None,
                      help='variance around the average fee, decimal fraction')
    parser.add_option('-p',
                      '--password',
                      action='store',
                      type='string',
                      dest='password',
                      default=nickserv_password,
                      help='irc nickserv password')
    parser.add_option('-s',
                      '--minsize',
                      action='store',
                      type='int',
                      dest='minsize',
                      default=None,
                      help='minimum coinjoin size in satoshis')
    parser.add_option('-z',
                      '--size-factor',
                      action='store',
                      type='float',
                      dest='size_factor',
                      default=None,
                      help='variance around all offer sizes, decimal fraction')
    parser.add_option('-g',
                      '--gap-limit',
                      action='store',
                      type="int",
                      dest='gaplimit',
                      default=gaplimit,
                      help='gap limit for wallet, default=' + str(gaplimit))
    parser.add_option('-m',
                      '--mixdepth',
                      action='store',
                      type='int',
                      dest='mixdepth',
                      default=None,
                      help="highest mixdepth to use")
    (options, args) = parser.parse_args()
    # for string access, convert to dict:
    options = vars(options)
    if len(args) < 1:
        parser.error('Needs a wallet')
        sys.exit(EXIT_ARGERROR)

    load_program_config(config_path=options["datadir"])

    # As per previous note, override non-default command line settings:
    for x in [
            "ordertype", "txfee", "txfee_factor", "cjfee_a", "cjfee_r",
            "cjfee_factor", "minsize", "size_factor"
    ]:
        if options[x] is None:
            options[x] = jm_single().config.get("YIELDGENERATOR", x)
    wallet_name = args[0]
    ordertype = options["ordertype"]
    txfee = int(options["txfee"])
    txfee_factor = float(options["txfee_factor"])
    cjfee_factor = float(options["cjfee_factor"])
    size_factor = float(options["size_factor"])
    if ordertype == 'reloffer':
        cjfee_r = options["cjfee_r"]
        # minimum size is such that you always net profit at least 20%
        #of the miner fee
        minsize = max(int(1.2 * txfee / float(cjfee_r)),
                      int(options["minsize"]))
        cjfee_a = None
    elif ordertype == 'absoffer':
        cjfee_a = int(options["cjfee_a"])
        minsize = int(options["minsize"])
        cjfee_r = None
    else:
        parser.error('You specified an incorrect offer type which ' +\
                     'can be either reloffer or absoffer')
        sys.exit(EXIT_ARGERROR)
    nickserv_password = options["password"]

    if jm_single().bc_interface is None:
        jlog.error("Running yield generator requires configured " +
                   "blockchain source.")
        sys.exit(EXIT_FAILURE)

    wallet_path = get_wallet_path(wallet_name, None)
    wallet = open_test_wallet_maybe(
        wallet_path,
        wallet_name,
        options["mixdepth"],
        wallet_password_stdin=options["wallet_password_stdin"],
        gap_limit=options["gaplimit"])

    wallet_service = WalletService(wallet)
    while not wallet_service.synced:
        wallet_service.sync_wallet(fast=not options["recoversync"])
    wallet_service.startService()

    txtype = wallet_service.get_txtype()
    if txtype == "p2wpkh":
        prefix = "sw0"
    elif txtype == "p2sh-p2wpkh":
        prefix = "sw"
    elif txtype == "p2pkh":
        prefix = ""
    else:
        jlog.error("Unsupported wallet type for yieldgenerator: " + txtype)
        sys.exit(EXIT_ARGERROR)

    ordertype = prefix + ordertype
    jlog.debug("Set the offer type string to: " + ordertype)

    maker = ygclass(wallet_service, [
        txfee, cjfee_a, cjfee_r, ordertype, minsize, txfee_factor,
        cjfee_factor, size_factor
    ])
    jlog.info('starting yield generator')
    clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER")
    if jm_single().config.get("SNICKER", "enabled") == "true":
        if jm_single().config.get("BLOCKCHAIN", "network") == "mainnet":
            jlog.error("You have enabled SNICKER on mainnet, this is not "
                       "yet supported for yieldgenerators; either use "
                       "signet/regtest/testnet, or run SNICKER manually "
                       "with snicker/receive-snicker.py.")
            sys.exit(EXIT_ARGERROR)
        snicker_r = SNICKERReceiver(wallet_service)
        servers = jm_single().config.get("SNICKER", "servers").split(",")
        snicker_factory = SNICKERClientProtocolFactory(snicker_r, servers)
    else:
        snicker_factory = None
    nodaemon = jm_single().config.getint("DAEMON", "no_daemon")
    daemon = True if nodaemon == 1 else False
    if jm_single().config.get("BLOCKCHAIN",
                              "network") in ["regtest", "testnet", "signet"]:
        startLogging(sys.stdout)
    start_reactor(jm_single().config.get("DAEMON", "daemon_host"),
                  jm_single().config.getint("DAEMON", "daemon_port"),
                  clientfactory,
                  snickerfactory=snicker_factory,
                  daemon=daemon)
예제 #56
0
                print "[*] - Stopping the webserver reactor"
                print "[*] - The webserver shutting down"
                print "[*] - The reactor is stopping"
                pass       





        else:
            print('')




#def startListening(8888)


#from twisted.internet import reactor
reactor.callWhenRunning(stack)
reactor.run()

     
log.startLogging(open('data/echo.log', 'w'))    
#endpoint = TCP4ServerEndpoint(reactor, 8081)
#endpoint.listen(CONSOLEFactory())
print 'Starting the teamserver reactor.' 
pollreactor.run(stack)
pollreactor.run(CONSOLEFactory())

예제 #57
0
def main():
    log.startLogging(sys.stdout)


    ct_dp = CT_DP(('localhost', 8080), ('localhost', 5002))
    reactor.run()
예제 #58
0
    def doConnect(self):
        finished = 1
        options['host'] = self.host.get()
        options['port'] = self.port.get()
        options['user'] = self.user.get()
        options['command'] = self.command.get()
        cipher = self.cipher.get()
        mac = self.mac.get()
        escape = self.escape.get()
        if cipher:
            if cipher in SSHClientTransport.supportedCiphers:
                SSHClientTransport.supportedCiphers = [cipher]
            else:
                tkMessageBox.showerror('TkConch', 'Bad cipher.')
                finished = 0

        if mac:
            if mac in SSHClientTransport.supportedMACs:
                SSHClientTransport.supportedMACs = [mac]
            elif finished:
                tkMessageBox.showerror('TkConch', 'Bad MAC.')
                finished = 0

        if escape:
            if escape == 'none':
                options['escape'] = None
            elif escape[0] == '^' and len(escape) == 2:
                options['escape'] = chr(ord(escape[1])-64)
            elif len(escape) == 1:
                options['escape'] = escape
            elif finished:
                tkMessageBox.showerror('TkConch', "Bad escape character '%s'." % escape)
                finished = 0

        if self.identity.get():
            options.identitys.append(self.identity.get())

        for line in self.forwards.get(0,Tkinter.END):
            if line[0]=='L':
                options.opt_localforward(line[2:])
            else:
                options.opt_remoteforward(line[2:])

        if '@' in options['host']:
            options['user'], options['host'] = options['host'].split('@',1)

        if (not options['host'] or not options['user']) and finished:
            tkMessageBox.showerror('TkConch', 'Missing host or username.')
            finished = 0
        if finished:
            self.master.quit()
            self.master.destroy()
            if options['log']:
                realout = sys.stdout
                log.startLogging(sys.stderr)
                sys.stdout = realout
            else:
                log.discardLogs()
            log.deferr = handleError # HACK
            if not options.identitys:
                options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
            host = options['host']
            port = int(options['port'] or 22)
            log.msg((host,port))
            reactor.connectTCP(host, port, SSHClientFactory())
            frame.master.deiconify()
            frame.master.title('%s@%s - TkConch' % (options['user'], options['host']))
        else:
            self.focus()
예제 #59
0
def main():
    parser = get_sendpayment_parser()
    (options, args) = parser.parse_args()
    load_program_config(config_path=options.datadir)
    if options.p2ep and len(args) != 3:
        parser.error("Joinmarket peer-to-peer PayJoin requires exactly three "
                     "arguments: wallet, amount and destination address.")
        sys.exit(EXIT_ARGERROR)
    elif options.schedule == '':
        if ((len(args) < 2) or
            (btc.is_bip21_uri(args[1]) and len(args) != 2) or
            (not btc.is_bip21_uri(args[1]) and len(args) != 3)):
                parser.error("Joinmarket sendpayment (coinjoin) needs arguments:"
                    " wallet, amount, destination address or wallet, bitcoin_uri.")
                sys.exit(EXIT_ARGERROR)

    #without schedule file option, use the arguments to create a schedule
    #of a single transaction
    sweeping = False
    bip78url = None
    if options.schedule == '':
        if btc.is_bip21_uri(args[1]):
            parsed = btc.decode_bip21_uri(args[1])
            try:
                amount = parsed['amount']
            except KeyError:
                parser.error("Given BIP21 URI does not contain amount.")
                sys.exit(EXIT_ARGERROR)
            destaddr = parsed['address']
            if 'jmnick' in parsed:
                if "pj" in parsed:
                    parser.error("Cannot specify both BIP78 and Joinmarket "
                                 "peer-to-peer payjoin at the same time!")
                    sys.exit(EXIT_ARGERROR)
                options.p2ep = parsed['jmnick']
            elif "pj" in parsed:
                # note that this is a URL; its validity
                # checking is deferred to twisted.web.client.Agent
                bip78url = parsed["pj"]
                # setting makercount only for fee sanity check.
                # note we ignore any user setting and enforce N=0,
                # as this is a flag in the code for a non-JM coinjoin;
                # for the fee sanity check, note that BIP78 currently
                # will only allow small fee changes, so N=0 won't
                # be very inaccurate.
                jmprint("Attempting to pay via payjoin.", "info")
                options.makercount = 0
        else:
            amount = btc.amount_to_sat(args[1])
            if amount == 0:
                sweeping = True
            destaddr = args[2]
        mixdepth = options.mixdepth
        addr_valid, errormsg = validate_address(destaddr)
        command_to_burn = (is_burn_destination(destaddr) and sweeping and
            options.makercount == 0 and not options.p2ep)
        if not addr_valid and not command_to_burn:
            jmprint('ERROR: Address invalid. ' + errormsg, "error")
            if is_burn_destination(destaddr):
                jmprint("The required options for burning coins are zero makers"
                    + " (-N 0), sweeping (amount = 0) and not using P2EP", "info")
            sys.exit(EXIT_ARGERROR)
        if sweeping == False and amount < DUST_THRESHOLD:
            jmprint('ERROR: Amount ' + btc.amount_to_str(amount) +
                ' is below dust threshold ' +
                btc.amount_to_str(DUST_THRESHOLD) + '.', "error")
            sys.exit(EXIT_ARGERROR)
        if (options.makercount != 0 and
            options.makercount < jm_single().config.getint(
            "POLICY", "minimum_makers")):
            jmprint('ERROR: Maker count ' + str(options.makercount) +
                ' below minimum_makers (' + str(jm_single().config.getint(
                "POLICY", "minimum_makers")) + ') in joinmarket.cfg.',
                "error")
            sys.exit(EXIT_ARGERROR)
        schedule = [[options.mixdepth, amount, options.makercount,
                     destaddr, 0.0, NO_ROUNDING, 0]]
    else:
        if btc.is_bip21_uri(args[1]):
            parser.error("Schedule files are not compatible with bip21 uris.")
            sys.exit(EXIT_ARGERROR)
        if options.p2ep:
            parser.error("Schedule files are not compatible with PayJoin")
            sys.exit(EXIT_FAILURE)
        result, schedule = get_schedule(options.schedule)
        if not result:
            log.error("Failed to load schedule file, quitting. Check the syntax.")
            log.error("Error was: " + str(schedule))
            sys.exit(EXIT_FAILURE)
        mixdepth = 0
        for s in schedule:
            if s[1] == 0:
                sweeping = True
            #only used for checking the maximum mixdepth required
            mixdepth = max([mixdepth, s[0]])

    wallet_name = args[0]

    check_regtest()

    if options.pickorders:
        chooseOrdersFunc = pick_order
        if sweeping:
            jmprint('WARNING: You may have to pick offers multiple times', "warning")
            jmprint('WARNING: due to manual offer picking while sweeping', "warning")
    else:
        chooseOrdersFunc = options.order_choose_fn

    # If tx_fees are set manually by CLI argument, override joinmarket.cfg:
    if int(options.txfee) > 0:
        jm_single().config.set("POLICY", "tx_fees", str(options.txfee))

    # Dynamically estimate a realistic fee.
    # At this point we do not know even the number of our own inputs, so
    # we guess conservatively with 2 inputs and 2 outputs each.
    fee_per_cp_guess = estimate_tx_fee(2, 2, txtype="p2sh-p2wpkh")
    log.debug("Estimated miner/tx fee for each cj participant: " + str(
        fee_per_cp_guess))

    maxcjfee = (1, float('inf'))
    if not options.p2ep and not options.pickorders and \
       options.makercount != 0:
        maxcjfee = get_max_cj_fee_values(jm_single().config, options)
        log.info("Using maximum coinjoin fee limits per maker of {:.4%}, {} "
                 "".format(maxcjfee[0], btc.amount_to_str(maxcjfee[1])))

    log.info('starting sendpayment')

    max_mix_depth = max([mixdepth, options.amtmixdepths - 1])

    wallet_path = get_wallet_path(wallet_name, None)
    wallet = open_test_wallet_maybe(
        wallet_path, wallet_name, max_mix_depth,
        wallet_password_stdin=options.wallet_password_stdin,
        gap_limit=options.gaplimit)
    wallet_service = WalletService(wallet)
    # in this script, we need the wallet synced before
    # logic processing for some paths, so do it now:
    while not wallet_service.synced:
        wallet_service.sync_wallet(fast=not options.recoversync)
    # the sync call here will now be a no-op:
    wallet_service.startService()


    # From the estimated tx fees, check if the expected amount is a
    # significant value compared the the cj amount; currently enabled
    # only for single join (the predominant, non-advanced case)
    if options.schedule == '':
        total_cj_amount = amount
        if total_cj_amount == 0:
            total_cj_amount = wallet_service.get_balance_by_mixdepth()[options.mixdepth]
            if total_cj_amount == 0:
                raise ValueError("No confirmed coins in the selected mixdepth. Quitting")
        exp_tx_fees_ratio = ((1 + options.makercount) * fee_per_cp_guess) / total_cj_amount
        if exp_tx_fees_ratio > 0.05:
            jmprint('WARNING: Expected bitcoin network miner fees for this coinjoin'
                ' amount are roughly {:.1%}'.format(exp_tx_fees_ratio), "warning")
            if input('You might want to modify your tx_fee'
                ' settings in joinmarket.cfg. Still continue? (y/n):')[0] != 'y':
                sys.exit('Aborted by user.')
        else:
            log.info("Estimated miner/tx fees for this coinjoin amount: {:.1%}"
                .format(exp_tx_fees_ratio))

    if options.makercount == 0 and not options.p2ep and not bip78url:
        tx = direct_send(wallet_service, amount, mixdepth, destaddr,
                         options.answeryes, with_final_psbt=options.with_psbt)
        if options.with_psbt:
            log.info("This PSBT is fully signed and can be sent externally for "
                     "broadcasting:")
            log.info(tx.to_base64())
        return

    if wallet.get_txtype() == 'p2pkh':
        jmprint("Only direct sends (use -N 0) are supported for "
              "legacy (non-segwit) wallets.", "error")
        sys.exit(EXIT_ARGERROR)

    def filter_orders_callback(orders_fees, cjamount):
        orders, total_cj_fee = orders_fees
        log.info("Chose these orders: " +pprint.pformat(orders))
        log.info('total cj fee = ' + str(total_cj_fee))
        total_fee_pc = 1.0 * total_cj_fee / cjamount
        log.info('total coinjoin fee = ' + str(float('%.3g' % (
            100.0 * total_fee_pc))) + '%')
        WARNING_THRESHOLD = 0.02  # 2%
        if total_fee_pc > WARNING_THRESHOLD:
            log.info('\n'.join(['=' * 60] * 3))
            log.info('WARNING   ' * 6)
            log.info('\n'.join(['=' * 60] * 1))
            log.info('OFFERED COINJOIN FEE IS UNUSUALLY HIGH. DOUBLE/TRIPLE CHECK.')
            log.info('\n'.join(['=' * 60] * 1))
            log.info('WARNING   ' * 6)
            log.info('\n'.join(['=' * 60] * 3))
        if not options.answeryes:
            if input('send with these orders? (y/n):')[0] != 'y':
                return False
        return True

    def taker_finished(res, fromtx=False, waittime=0.0, txdetails=None):
        if fromtx == "unconfirmed":
            #If final entry, stop *here*, don't wait for confirmation
            if taker.schedule_index + 1 == len(taker.schedule):
                reactor.stop()
            return
        if fromtx:
            if res:
                txd, txid = txdetails
                reactor.callLater(waittime*60,
                                  clientfactory.getClient().clientStart)
            else:
                #a transaction failed; we'll try to repeat without the
                #troublemakers.
                #If this error condition is reached from Phase 1 processing,
                #and there are less than minimum_makers honest responses, we
                #just give up (note that in tumbler we tweak and retry, but
                #for sendpayment the user is "online" and so can manually
                #try again).
                #However if the error is in Phase 2 and we have minimum_makers
                #or more responses, we do try to restart with the honest set, here.
                if taker.latest_tx is None:
                    #can only happen with < minimum_makers; see above.
                    log.info("A transaction failed but there are insufficient "
                             "honest respondants to continue; giving up.")
                    reactor.stop()
                    return
                #This is Phase 2; do we have enough to try again?
                taker.add_honest_makers(list(set(
                    taker.maker_utxo_data.keys()).symmetric_difference(
                        set(taker.nonrespondants))))
                if len(taker.honest_makers) < jm_single().config.getint(
                    "POLICY", "minimum_makers"):
                    log.info("Too few makers responded honestly; "
                             "giving up this attempt.")
                    reactor.stop()
                    return
                jmprint("We failed to complete the transaction. The following "
                      "makers responded honestly: " + str(taker.honest_makers) +\
                      ", so we will retry with them.", "warning")
                #Now we have to set the specific group we want to use, and hopefully
                #they will respond again as they showed honesty last time.
                #we must reset the number of counterparties, as well as fix who they
                #are; this is because the number is used to e.g. calculate fees.
                #cleanest way is to reset the number in the schedule before restart.
                taker.schedule[taker.schedule_index][2] = len(taker.honest_makers)
                log.info("Retrying with: " + str(taker.schedule[
                    taker.schedule_index][2]) + " counterparties.")
                #rewind to try again (index is incremented in Taker.initialize())
                taker.schedule_index -= 1
                taker.set_honest_only(True)
                reactor.callLater(5.0, clientfactory.getClient().clientStart)
        else:
            if not res:
                log.info("Did not complete successfully, shutting down")
            #Should usually be unreachable, unless conf received out of order;
            #because we should stop on 'unconfirmed' for last (see above)
            else:
                log.info("All transactions completed correctly")
            reactor.stop()

    if options.p2ep:
        # This workflow requires command line reading; we force info level logging
        # to remove noise, and mostly communicate to the user with the fn
        # log.info (directly or via default taker_info_callback).
        set_logging_level("INFO")
        # in the case where the payment just hangs for a long period, allow
        # it to fail gracefully with an information message; this is triggered
        # only by the stallMonitor, which gives up after 20*maker_timeout_sec:
        def p2ep_on_finished_callback(res, fromtx=False, waittime=0.0,
                                      txdetails=None):
            log.error("PayJoin payment was NOT made, timed out.")
            reactor.stop()
        taker = P2EPTaker(options.p2ep, wallet_service, schedule,
                          callbacks=(None, None, p2ep_on_finished_callback))

    elif bip78url:
        # TODO sanity check wallet type is segwit
        manager = parse_payjoin_setup(args[1], wallet_service, options.mixdepth)
        reactor.callWhenRunning(send_payjoin, manager, tls_whitelist=["127.0.0.1"])
        reactor.run()
        return

    else:
        taker = Taker(wallet_service,
                      schedule,
                      order_chooser=chooseOrdersFunc,
                      max_cj_fee=maxcjfee,
                      callbacks=(filter_orders_callback, None, taker_finished))
    clientfactory = JMClientProtocolFactory(taker)
    nodaemon = jm_single().config.getint("DAEMON", "no_daemon")
    daemon = True if nodaemon == 1 else False
    p2ep = True if options.p2ep != "" else False
    if jm_single().config.get("BLOCKCHAIN", "network") in ["regtest", "testnet"]:
        startLogging(sys.stdout)
    start_reactor(jm_single().config.get("DAEMON", "daemon_host"),
                  jm_single().config.getint("DAEMON", "daemon_port"),
                  clientfactory, daemon=daemon, p2ep=p2ep)
def receive_payjoin_main(makerclass):
    parser = OptionParser(
        usage='usage: %prog [options] [wallet file] [amount-to-receive]')
    add_base_options(parser)
    parser.add_option('-g',
                      '--gap-limit',
                      action='store',
                      type="int",
                      dest='gaplimit',
                      default=6,
                      help='gap limit for wallet, default=6')
    parser.add_option('-m',
                      '--mixdepth',
                      action='store',
                      type='int',
                      dest='mixdepth',
                      default=0,
                      help="mixdepth to source coins from")
    parser.add_option('-a',
                      '--amtmixdepths',
                      action='store',
                      type='int',
                      dest='amtmixdepths',
                      help='number of mixdepths in wallet, default 5',
                      default=5)

    (options, args) = parser.parse_args()
    if len(args) < 2:
        parser.error(
            'Needs a wallet, and a receiving amount in bitcoins or satoshis')
        sys.exit(EXIT_ARGERROR)
    wallet_name = args[0]
    try:
        receiving_amount = amount_to_sat(args[1])
    except:
        parser.error("Invalid receiving amount passed: " + receiving_amount)
        sys.exit(EXIT_FAILURE)
    if receiving_amount < 0:
        parser.error("Receiving amount must be a positive number")
        sys.exit(EXIT_FAILURE)
    load_program_config(config_path=options.datadir)

    check_regtest()

    # This workflow requires command line reading; we force info level logging
    # to remove noise, and mostly communicate to the user with the fn
    # log.info (via P2EPMaker.user_info).
    set_logging_level("INFO")

    wallet_path = get_wallet_path(wallet_name, None)
    max_mix_depth = max([options.mixdepth, options.amtmixdepths - 1])
    wallet = open_test_wallet_maybe(
        wallet_path,
        wallet_name,
        max_mix_depth,
        wallet_password_stdin=options.wallet_password_stdin,
        gap_limit=options.gaplimit)
    wallet_service = WalletService(wallet)

    while not wallet_service.synced:
        wallet_service.sync_wallet(fast=not options.recoversync)
    wallet_service.startService()
    # having enforced wallet sync, we can check if we have coins
    # to do payjoin in the mixdepth
    if wallet_service.get_balance_by_mixdepth()[options.mixdepth] == 0:
        jlog.error("Cannot do payjoin from mixdepth " + str(options.mixdepth) +
                   ", no coins. Shutting down.")
        sys.exit(EXIT_ARGERROR)

    maker = makerclass(wallet_service, options.mixdepth, receiving_amount)

    jlog.info('starting receive-payjoin')
    clientfactory = JMClientProtocolFactory(maker, proto_type="MAKER")

    nodaemon = jm_single().config.getint("DAEMON", "no_daemon")
    daemon = True if nodaemon == 1 else False
    if jm_single().config.get("BLOCKCHAIN",
                              "network") in ["regtest", "testnet"]:
        startLogging(sys.stdout)
    start_reactor(jm_single().config.get("DAEMON", "daemon_host"),
                  jm_single().config.getint("DAEMON", "daemon_port"),
                  clientfactory,
                  daemon=daemon,
                  p2ep=True)