Ejemplo n.º 1
0
    def setUpClass(cls):
        super(TestNotifyDebugEvents, cls).setUpClass()
        output = Compiler.instance().load('%s/sc_debug_events.py' %
                                          os.path.dirname(__file__)).default
        cls.script = output.write()

        settings.set_log_smart_contract_events(False)
Ejemplo n.º 2
0
    def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(ImuSmartContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = wallet_pass

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        # Setup redis cache
        self.redis_cache = redis.StrictRedis(host='localhost', port=6379, db=0)

        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        # Setup handler for smart contract Runtime.Notify event
        #
        # Here only listen to 'imuBalance' and save it to redis
        @self.smart_contract.on_notify
        def sc_notify(event):
            """ This method catches Runtime.Notify calls, and updates the balances cache """
            logger.info("sc_notify event: %s", str(event))

            if event.event_payload[0].decode("utf-8") == "imuBalance":
                address = event.event_payload[1].decode("utf-8")
                amount = int(event.event_payload[2])

                logger.info("- setting balance of %s to %s", address, amount)
                self.redis_cache.set("balance:%s" % address, amount)
                self.redis_cache.set("balanceUpdatedAt:%s" % address,
                                     int(time.time()))
Ejemplo n.º 3
0
def main():
    args = sys.argv[1:]
    args += os.getenv('CONTRACT_FILE', '').split(' ')
    args += os.getenv('CONTRACT_ARGS', '').split(' ')
    args = list(filter(None, args))

    if len(args) < 2:  # must provide file name and arguments
        print("WARN! No smart contracts args... skip")
        return

    settings.setup_privnet(True)
    settings.set_log_smart_contract_events(True)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    app = ImportSC(args, blockchain, reactor)

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    reactor.callInThread(app.worker)

    NodeLeader.Instance().Start()

    reactor.run()

    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 4
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("cannot configure log.  Please specify on or off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("cannot configure log.  Please specify on or off")

        else:
            print("cannot configure %s " % what)
            print("Try 'config log on/off'")
Ejemplo n.º 5
0
def main():

    settings.setup('protocol.coz.json')
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    global Wallet
    Wallet = UserWallet.Open(path="infinitewallet", password="******")
    logger.info("Created the Wallet")
    logger.info(Wallet.AddressVersion)
    walletdb_loop = task.LoopingCall(Wallet.ProcessBlocks)
    walletdb_loop.start(1)
    #Wallet.CreateKey(KeyPair.PrivateKeyFromWIF(wif))

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 6
0
def main():
    # Use TestNet
    settings.setup_testnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 7
0
    def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(MilestoneSmartContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = wallet_pass

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        # Setup redis
        self.rds = Redis(host='redis', port=6379, db=0)

        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        # Setup handler for smart contract Runtime.Notify event
        #
        @self.smart_contract.on_notify
        def sc_notify(event):
            """ This method catches Runtime.Notify calls, and add them to Redis """
            logger.info("sc_notify event: %s", str(event))

            # Make sure that the event payload list has at least one element.
            if not len(event.event_payload):
                return

            # The event payload list has at least one element. As developer of the smart contract
            # you should know what data-type is in the bytes, and how to decode it. In this example,
            # it's just a string, so we decode it with utf-8:
            msg = event.event_payload[0].decode("utf-8")
            self.rds.publish('neo-event', msg)
Ejemplo n.º 8
0
def main():
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Hook up Klein API to Twisted reactor.
    endpoint_description = "tcp:port=%s:interface=localhost" % API_PORT

    # If you want to make this service externally available (not only at localhost),
    # then remove the `interface=localhost` part:
    # endpoint_description = "tcp:port=%s" % API_PORT

    endpoint = endpoints.serverFromString(reactor, endpoint_description)
    endpoint.listen(Site(app.resource()))

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 9
0
def main():
    # Use TestNet
    settings.setup_testnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Hook up Klein API to Twisted reactor.
    endpoint_description = "tcp:port=%s:interface=localhost" % API_PORT

    # If you want to make this service externally available (not only at localhost),
    # then remove the `interface=localhost` part:
    # endpoint_description = "tcp:port=%s" % API_PORT

    endpoint = endpoints.serverFromString(reactor, endpoint_description)
    endpoint.listen(Site(app.resource()))

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 10
0
    def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(SurTokenContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = to_aes_key(wallet_pass)

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        @self.smart_contract.on_notify
        def sc_notify(event):
            logger.info("SmartContract Runtime.Notify event: %s", event)

            # Make sure that the event payload list has at least one element.
            if not len(event.event_payload):
                return

            # The event payload list has at least one element. As developer of the smart contract
            # you should know what data-type is in the bytes, and how to decode it. In this example,
            # it's just a string, so we decode it with utf-8:
            logger.info("- payload part 1: %s",
                        event.event_payload[0].decode("utf-8"))
Ejemplo n.º 11
0
def main():
    """ """
    # check to see if the chains already exist
    if not os.path.isdir(f'{Path.home()}/.neopython/Chains/SC234'):
        subprocess.call(['expect', './config/np-setup.exp'])

    # Setup the blockchain with logging smart contract events turned on
    settings.set_log_smart_contract_events(
        True)  # uncomment if you want to be spammed with notifications

    # initialize environment, nep5-token, and testnet protocol
    init_environ('./config/environment.json', './config/nep5-token.json',
                 './src/neo-python/neo/data/protocol.testnet.json')
    settings.setup('./src/neo-python/neo/data/protocol.testnet.json'
                   )  # use testnet protocol file

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)

    # add blocks to the blockchain every 0.1 seconds
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # configure and run faucet web app on the specified host and port
    host = os.environ.get('FAUCET_HOST', 'localhost')
    port = os.environ.get('FAUCET_PORT', 80)
    store = ItemStore()
    store.app.run(host=host, port=port)

    logger.info('Shutting down.')
Ejemplo n.º 12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--config", action="store", help="Config file (default. %s)" % PROTOCOL_CONFIG,
                        default=PROTOCOL_CONFIG)
    args = parser.parse_args()
    settings.setup(args.config)

    logger.info("Starting api.py")
    logger.info("Config: %s", args.config)
    logger.info("Network: %s", settings.net_name)

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()



    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 13
0
async def setup_and_start(loop):
    # Use TestNet
    settings.setup_privnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    p2p = NetworkService()
    loop.create_task(p2p.start())
    bg_task = loop.create_task(custom_background_code())

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    app = web.Application()
    app.add_routes([
        web.route('*', '/', home_route),
        web.get("/echo-get/{msg}", echo_msg),
        web.post("/echo-post/", echo_post),
    ])

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "0.0.0.0", API_PORT)
    await site.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    return site
Ejemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser()

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-m", "--mainnet", action="store_true", default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument("-p", "--privnet", action="store_true", default=False,
                       help="Use PrivNet instead of the default TestNet")
    group.add_argument("--coznet", action="store_true", default=False,
                       help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c", "--config", action="store", help="Use a specific config file")

    args = parser.parse_args()

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    # logger.info(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(True)
    logger.info("Using network: %s" % settings.net_name)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Start SurTokenContract thread
    surTokenContract.start()

    # Hook up Klein API to Twisted reactor
    endpoint_description = "tcp:port=%s" % API_PORT
    endpoint = endpoints.serverFromString(reactor, endpoint_description)
    endpoint.listen(Site(app.resource()))

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 15
0
    def execute(self, arguments):
        if len(arguments) == 0:
            print("Please specify the required parameter")
            return False

        try:
            flag = bool(util.strtobool(arguments[0]))
            settings.set_log_smart_contract_events(flag)
        except ValueError:
            print("Invalid option")
            return False

        if flag:
            print("Smart contract event logging is now enabled")
            return True
        else:
            print("Smart contract event logging is now disabled")
            return True
Ejemplo n.º 16
0
async def setup_and_start(loop):
    # Use TestNet
    settings.setup_testnet()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    p2p = NetworkService()
    loop.create_task(p2p.start())
    bg_task = loop.create_task(custom_background_code())

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    return bg_task
Ejemplo n.º 17
0
def main():
    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 18
0
    def run(self):

        # bl: changing to 8 as recommended in the 8-10 range by localhuman (previously had this at 150)
        settings.set_max_peers(8)

        # Setup the blockchain
        self.blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
        Blockchain.RegisterBlockchain(self.blockchain)
        NodeLeader.Instance().Start()
        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)
        Blockchain.Default().PersistBlocks()

        # Disable smart contract events for external smart contracts
        settings.set_log_smart_contract_events(False)

        # if the wallet was set up (by setting a path and loading the password), then open it!
        if self.wallet_path:
            self.wallet_open()

        # Start a thread with custom code
        d = threading.Thread(target=self.whitelist_addresses)
        d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
        d.start()

        # invoke any pre-start action that needs to occur before we start the reactor.
        # optional for subclasses to implement.
        self.pre_start()

        # Run all the things (blocking call)
        self.logger.info("Everything setup and running. Waiting for events...")
        reactor.run()
        self.logger.info("Shutting down")
        if self.wallet_path:
            self.wallet_close()
        Blockchain.Default().Dispose()
        NodeLeader.Instance().Shutdown()
        self.logger.info("Shut down.")
Ejemplo n.º 19
0
def main():
    # Setup the blockchain
    # settings.setup('./neo-python/protocol.coz.json')
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)
    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Start a thread with custom code
    d = threading.Thread(target=log_block)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run all the things (blocking call)
    logger.info("Everything setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 20
0
def main():
    settings.setup_privnet(True)
    settings.set_log_smart_contract_events(True)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    args = sys.argv[1:]
    args += os.getenv('CONTRACT_FILE', '').split(' ')
    args += os.getenv('CONTRACT_ARGS', '').split(' ')
    args = list(filter(None, args))

    if len(args) < 2:  # must provide file name and arguments
        print("WARN! No smart contracts args... skip")
        return

    app = ImportSC(args, blockchain, reactor)

    loop = task.LoopingCall(blockchain.PersistBlocks)
    deferred = loop.start(.1)
    deferred.addErrback(app.on_loopError)

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    NodeLeader.Instance().Start()
    NodeLeader.Instance().PeerCheckLoop()

    # PyAssumeType(twisted.internet.reactor, twisted.internet.selectreactor.SelectReactor)
    reactor.callInThread(app.worker)
    reactor.run()

    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 21
0
def main():
    parser = argparse.ArgumentParser()

    # Network options
    group_network_container = parser.add_argument_group(title="Network options")
    group_network = group_network_container.add_mutually_exclusive_group(required=True)
    group_network.add_argument("--mainnet", action="store_true", default=False, help="Use MainNet")
    group_network.add_argument("--testnet", action="store_true", default=False, help="Use TestNet")
    group_network.add_argument("--privnet", action="store_true", default=False, help="Use PrivNet")
    group_network.add_argument("--coznet", action="store_true", default=False, help="Use CozNet")
    group_network.add_argument("--config", action="store", help="Use a specific config file")

    # Ports for RPC and REST api
    group_modes = parser.add_argument_group(title="Mode(s)")
    group_modes.add_argument("--port-rpc", type=int, help="port to use for the json-rpc api (eg. 10332)")
    group_modes.add_argument("--port-rest", type=int, help="port to use for the rest api (eg. 80)")

    # Advanced logging setup
    group_logging = parser.add_argument_group(title="Logging options")
    group_logging.add_argument("--logfile", action="store", type=str, help="Logfile")
    group_logging.add_argument("--syslog", action="store_true", help="Log to syslog instead of to log file ('user' is the default facility)")
    group_logging.add_argument("--syslog-local", action="store", type=int, choices=range(0, 7), metavar="[0-7]", help="Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0').")
    group_logging.add_argument("--disable-stderr", action="store_true", help="Disable stderr logger")

    # Where to store stuff
    parser.add_argument("--datadir", action="store",
                        help="Absolute path to use for database directories")
    # peers
    parser.add_argument("--maxpeers", action="store", default=5,
                        help="Max peers to use for P2P Joining")

    # host
    parser.add_argument("--host", action="store", type=str, help="Hostname ( for example 127.0.0.1)", default="0.0.0.0")

    # Now parse
    args = parser.parse_args()
    # print(args)

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    if args.logfile and (args.syslog or args.syslog_local):
        print("Error: Cannot only use logfile or syslog at once")
        parser.print_help()
        return

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    if args.datadir:
        settings.set_data_dir(args.datadir)
    if args.maxpeers:
        settings.set_max_peers(args.maxpeers)

    if args.syslog or args.syslog_local is not None:
        # Setup the syslog facility
        if args.syslog_local is not None:
            print("Logging to syslog local%s facility" % args.syslog_local)
            syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local
        else:
            print("Logging to syslog user facility")
            syslog_facility = SysLogHandler.LOG_USER

        # Setup logzero to only use the syslog handler
        logzero.syslog(facility=syslog_facility)
    else:
        # Setup file logging
        if args.logfile:
            logfile = os.path.abspath(args.logfile)
            if args.disable_stderr:
                print("Logging to logfile: %s" % logfile)
            else:
                print("Logging to stderr and logfile: %s" % logfile)
            logzero.logfile(logfile, maxBytes=LOGFILE_MAX_BYTES, backupCount=LOGFILE_BACKUP_COUNT, disableStderrLogger=args.disable_stderr)

        else:
            print("Logging to stdout and stderr")

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Write a PID file to easily quit the service
    write_pid_file()

    # Setup Twisted and Klein logging to use the logzero setup
    observer = STDLibLogObserver(name=logzero.LOGZERO_DEFAULT_LOGGER)
    globalLogPublisher.addObserver(observer)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    # Setup twisted reactor, NodeLeader and start the NotificationDB
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()
    NotificationDB.instance().start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" % (args.host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
#        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, args.host)
#        endpoints.serverFromString(reactor, endpoint_rpc).listen(Site(api_server_rpc.app.resource()))
#        reactor.listenTCP(int(args.port_rpc), server.Site(api_server_rpc))
        api_server_rpc.app.run(args.host, args.port_rpc)

    if args.port_rest:
        logger.info("Starting REST api server on http://%s:%s" % (args.host, args.port_rest))
        api_server_rest = RestApi()
#        endpoint_rest = "tcp:port={0}:interface={1}".format(args.port_rest, args.host)
#        endpoints.serverFromString(reactor, endpoint_rest).listen(Site(api_server_rest.app.resource()))
        api_server_rest.app.run(args.host, args.port_rest)

    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    logger.info("Closing databases...")
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 22
0
def main():
    parser = argparse.ArgumentParser()

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-m", "--mainnet", action="store_true", default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument("-t", "--testnet", action="store_true", default=False,
                       help="Use TestNett instead of the default TestNet")
    group.add_argument("-p", "--privnet", action="store_true", default=False,
                       help="Use PrivNet instead of the default TestNet")
    group.add_argument("--coznet", action="store_true", default=False,
                       help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c", "--config", action="store", help="Use a specific config file")

    parser.add_argument("--port-rpc", type=int, help="port to use for the json-rpc api (eg. 10332)")
    parser.add_argument("--port-rest", type=int, help="port to use for the rest api (eg. 80)")

    args = parser.parse_args()

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    # Write a PID file to easily quit the service
    write_pid_file()

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Start the notification db instance
    ndb = NotificationDB.instance()
    ndb.start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()

    host = "0.0.0.0"

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" % (host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(Site(api_server_rpc.app.resource()))

    if args.port_rest:
        logger.info("Starting notification api server on http://%s:%s" % (host, args.port_rest))
        api_server_rest = NotificationRestApi()
        endpoint_rest = "tcp:port={0}:interface={1}".format(args.port_rest, host)
        endpoints.serverFromString(reactor, endpoint_rest).listen(Site(api_server_rest.app.resource()))

    app = Klein()
    app.run(host, 9999)
Ejemplo n.º 23
0
def main():
    parser = argparse.ArgumentParser()

    # Network options
    group_network_container = parser.add_argument_group(
        title="Network options")
    group_network = group_network_container.add_mutually_exclusive_group(
        required=True)
    group_network.add_argument("--mainnet",
                               action="store_true",
                               default=False,
                               help="Use MainNet")
    group_network.add_argument("--testnet",
                               action="store_true",
                               default=False,
                               help="Use TestNet")
    group_network.add_argument("--privnet",
                               action="store_true",
                               default=False,
                               help="Use PrivNet")
    group_network.add_argument("--coznet",
                               action="store_true",
                               default=False,
                               help="Use CozNet")
    group_network.add_argument("--config",
                               action="store",
                               help="Use a specific config file")

    # Ports for RPC and REST api
    group_modes = parser.add_argument_group(title="Mode(s)")
    group_modes.add_argument(
        "--port-rpc",
        type=int,
        help="port to use for the json-rpc api (eg. 10332)")
    group_modes.add_argument("--port-rest",
                             type=int,
                             help="port to use for the rest api (eg. 80)")

    # Advanced logging setup
    group_logging = parser.add_argument_group(title="Logging options")
    group_logging.add_argument("--logfile",
                               action="store",
                               type=str,
                               help="Logfile")
    group_logging.add_argument(
        "--syslog",
        action="store_true",
        help=
        "Log to syslog instead of to log file ('user' is the default facility)"
    )
    group_logging.add_argument(
        "--syslog-local",
        action="store",
        type=int,
        choices=range(0, 7),
        metavar="[0-7]",
        help=
        "Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0')."
    )
    group_logging.add_argument("--disable-stderr",
                               action="store_true",
                               help="Disable stderr logger")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")
    # peers
    parser.add_argument("--maxpeers",
                        action="store",
                        default=5,
                        help="Max peers to use for P2P Joining")

    # host
    parser.add_argument("--host",
                        action="store",
                        type=str,
                        help="Hostname ( for example 127.0.0.1)",
                        default="0.0.0.0")

    # Now parse
    args = parser.parse_args()
    # print(args)

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    if args.logfile and (args.syslog or args.syslog_local):
        print("Error: Cannot only use logfile or syslog at once")
        parser.print_help()
        return

    # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.
    if args.datadir:
        settings.set_data_dir(args.datadir)

    # Network configuration depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    if args.maxpeers:
        settings.set_max_peers(args.maxpeers)

    if args.syslog or args.syslog_local is not None:
        # Setup the syslog facility
        if args.syslog_local is not None:
            print("Logging to syslog local%s facility" % args.syslog_local)
            syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local
        else:
            print("Logging to syslog user facility")
            syslog_facility = SysLogHandler.LOG_USER

        # Setup logzero to only use the syslog handler
        logzero.syslog(facility=syslog_facility)
    else:
        # Setup file logging
        if args.logfile:
            logfile = os.path.abspath(args.logfile)
            if args.disable_stderr:
                print("Logging to logfile: %s" % logfile)
            else:
                print("Logging to stderr and logfile: %s" % logfile)
            logzero.logfile(logfile,
                            maxBytes=LOGFILE_MAX_BYTES,
                            backupCount=LOGFILE_BACKUP_COUNT,
                            disableStderrLogger=args.disable_stderr)

        else:
            print("Logging to stdout and stderr")

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Write a PID file to easily quit the service
    write_pid_file()

    # Setup Twisted and Klein logging to use the logzero setup
    observer = STDLibLogObserver(name=logzero.LOGZERO_DEFAULT_LOGGER)
    globalLogPublisher.addObserver(observer)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    # Setup twisted reactor, NodeLeader and start the NotificationDB
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()
    NotificationDB.instance().start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" %
                    (args.host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
        endpoint_rpc = "tcp:port={0}:interface={1}".format(
            args.port_rpc, args.host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(
            Site(api_server_rpc.app.resource()))
#        reactor.listenTCP(int(args.port_rpc), server.Site(api_server_rpc))
#        api_server_rpc.app.run(args.host, args.port_rpc)

    if args.port_rest:
        logger.info("Starting REST api server on http://%s:%s" %
                    (args.host, args.port_rest))
        api_server_rest = RestApi()
        endpoint_rest = "tcp:port={0}:interface={1}".format(
            args.port_rest, args.host)
        endpoints.serverFromString(reactor, endpoint_rest).listen(
            Site(api_server_rest.app.resource()))


#        api_server_rest.app.run(args.host, args.port_rest)

    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    logger.info("Closing databases...")
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 24
0
    def setUpClass(cls):
        super(TestNotifyDebugEvents, cls).setUpClass()
        output = Compiler.instance().load('%s/sc_debug_events.py' % os.path.dirname(__file__)).default
        cls.script = output.write()

        settings.set_log_smart_contract_events(False)
Ejemplo n.º 25
0
    def __init__(self, input_args=None, debug=False):
        self.input_parser = InputParser()
        self.input_args = input_args
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()
        settings.set_log_smart_contract_events(False)

        self.notify = NotificationDB.instance()

        # if debug:
        #     settings.set_log_smart_contract_events(True)

        # EVENTS
        @events.on(SmartContractEvent.RUNTIME_NOTIFY)
        @events.on(SmartContractEvent.RUNTIME_LOG)
        @events.on(SmartContractEvent.EXECUTION_SUCCESS)
        @events.on(SmartContractEvent.EXECUTION_FAIL)
        @events.on(SmartContractEvent.STORAGE)
        def on_sc_event(sc_event):
            if sc_event.test_mode:
                self.active_color = colors.WARNING
            else:
                self.active_color = colors.GREEN

            if str(sc_event.contract_hash) == str(self.SC_hash):
                et = sc_event.event_type
                results = sc_event.event_payload

                if not debug and sc_event.test_mode:
                    return

                # Inding the invoked op
                if et == SmartContractEvent.RUNTIME_LOG and sc_event.test_mode:
                    try:
                        decoded_result = results[0].decode("utf-8")
                        if ':' in decoded_result:
                            self.invoked_operation = decoded_result.split(
                                ':')[-1]
                    except:
                        pass

                if et == SmartContractEvent.EXECUTION_SUCCESS or et == SmartContractEvent.RUNTIME_NOTIFY:
                    print(
                        self.active_color +
                        '\n|--------   T H E    C O N S T R U C T  --------|' +
                        colors.ENDC)

                    for result in results:
                        if self.invoked_operation in [
                                'fs_attribute', 'get_active_index',
                                'update_active_ms_progress', 'get_ms_progess'
                        ]:
                            result = int.from_bytes(result,
                                                    byteorder='little',
                                                    signed=False)
                        print('\033[1m Output:\033[0m \t\t\t', result)

                    if sc_event.test_mode:
                        print('\n \033[1mSuccessfully Sent Request:\033[0m\t',
                              self.invoked_operation)
                        print('\n Please wait for block to process.. ')
                    else:
                        print(
                            '\n \033[1mSuccessfully Executed Request:\033[0m\t',
                            self.invoked_operation)
                        self.invoking = False
                        self.invoked_operation = ''

                    self.op_output = results

                    print(self.active_color +
                          '|-----------------------------------------------|' +
                          colors.ENDC)
                    print('\n')

                elif debug:
                    print(
                        self.active_color +
                        '\n|--------   T H E    C O N S T R U C T  --------|' +
                        colors.ENDC)
                    print(' Event Type: ', et)
                    for result in results:
                        print(' \033[1mOutput:\033[0m \t\t\t', result)
                    print('\n')
Ejemplo n.º 26
0
def main():
    parser = argparse.ArgumentParser()

    # Network group
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-m", "--mainnet", action="store_true", default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument("-p", "--privnet", nargs="?", metavar="host", const=True, default=False,
                       help="Use a private net instead of the default TestNet, optionally using a custom host (default: 127.0.0.1)")
    group.add_argument("--coznet", action="store_true", default=False,
                       help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c", "--config", action="store", help="Use a specific config file")

    # Theme
    parser.add_argument("-t", "--set-default-theme", dest="theme",
                        choices=["dark", "light"],
                        help="Set the default theme to be loaded from the config file. Default: 'dark'")

    # Verbose
    parser.add_argument("-v", "--verbose", action="store_true", default=False,
                        help="Show smart-contract events by default")

    # Where to store stuff
    parser.add_argument("--datadir", action="store",
                        help="Absolute path to use for database directories")

    # peers
    parser.add_argument("--maxpeers", action="store", default=5,
                        help="Max peers to use for P2P Joining")

    # Show the neo-python version
    parser.add_argument("--version", action="version",
                        version="neo-python v{version}".format(version=__version__))

    args = parser.parse_args()

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.privnet:
        try:
            settings.setup_privnet(args.privnet)
        except PrivnetConnectionError as e:
            logger.error(str(e))
            return
    elif args.coznet:
        settings.setup_coznet()

    if args.theme:
        preferences.set_theme(args.theme)

    if args.verbose:
        settings.set_log_smart_contract_events(True)

    if args.datadir:
        settings.set_data_dir(args.datadir)

    if args.maxpeers:
        settings.set_max_peers(args.maxpeers)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    # Start the prompt interface
    cli = PromptInterface()

    # Run things
#    reactor.suggestThreadPoolSize(15)
    reactor.callInThread(cli.run)
    NodeLeader.Instance().Start()

    # reactor.run() is blocking, until `quit()` is called which stops the reactor.
    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 27
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract emit Notify events on execution failure is now enabled")
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract emit Notify events on execution failure is now disabled")
                    settings.set_emit_notify_events_on_sc_execution_error(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print("Cannot configure VM instruction logging. Please specify on|off")

        elif what == 'maxpeers':
            try:
                c1 = int(get_arg(args, 1).lower())
                num_peers = int(c1)
                if num_peers > 0:
                    old_max_peers = settings.CONNECTED_PEER_MAX
                    settings.set_max_peers(num_peers)
                    NodeLeader.Instance().OnUpdatedMaxPeers(old_max_peers, num_peers)
                    print("set max peers to %s " % num_peers)
                else:
                    print("Please specify integer greater than zero")
            except Exception as e:
                print("Cannot configure max peers. Please specify an integer greater than 0")

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'" % what)
Ejemplo n.º 28
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'"
                % what)
Ejemplo n.º 29
0
def main():
    parser = argparse.ArgumentParser()

    # Network group
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-m",
                       "--mainnet",
                       action="store_true",
                       default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument(
        "-p",
        "--privnet",
        nargs="?",
        metavar="host",
        const=True,
        default=False,
        help=
        "Use a private net instead of the default TestNet, optionally using a custom host (default: 127.0.0.1)"
    )
    group.add_argument(
        "--coznet",
        action="store_true",
        default=False,
        help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c",
                       "--config",
                       action="store",
                       help="Use a specific config file")

    # Theme
    parser.add_argument(
        "-t",
        "--set-default-theme",
        dest="theme",
        choices=["dark", "light"],
        help=
        "Set the default theme to be loaded from the config file. Default: 'dark'"
    )

    # Verbose
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        default=False,
                        help="Show smart-contract events by default")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")

    # Show the neo-python version
    parser.add_argument(
        "--version",
        action="version",
        version="neo-python v{version}".format(version=__version__))

    args = parser.parse_args()

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.privnet:
        try:
            settings.setup_privnet(args.privnet)
        except PrivnetConnectionError as e:
            logger.error(str(e))
            return
    elif args.coznet:
        settings.setup_coznet()

    if args.theme:
        preferences.set_theme(args.theme)

    if args.verbose:
        settings.set_log_smart_contract_events(True)

    if args.datadir:
        settings.set_data_dir(args.datadir)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    # Try to set up a notification db
    if NotificationDB.instance():
        NotificationDB.instance().start()

    # Start the prompt interface
    cli = PromptInterface()

    # Run things
    reactor.suggestThreadPoolSize(15)
    reactor.callInThread(cli.run)
    NodeLeader.Instance().Start()

    # reactor.run() is blocking, until `quit()` is called which stops the reactor.
    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
Ejemplo n.º 30
0
    def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(LootMarketsSmartContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = wallet_pass

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        # Setup redis cache.
        self.redis_cache = redis.StrictRedis(host='localhost', port=6379, db=0)

        self.calling_transaction = None
        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        # Setup handler for smart contract Runtime.Notify event.
        # Here we listen to all notify events.
        @self.smart_contract.on_notify
        def sc_notify(event):
            """ This method catches Runtime.Notify calls, and updates the relevant cache. """

            # Log the received smart contract event.
            logger.info("- SmartContract Event: %s", str(event))
            event_name = event.event_payload[0].decode("utf-8")

            # ==== General Events ====
            # Smart contract events that are not specific to a marketplace.

            # Event: balance_of
            if event_name == "balance_of":
                # Convert the given script hash to an address.
                script_hash = event.event_payload[1]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                balance = int.from_bytes(event.event_payload[2], 'little')
                # Save the balance to the cache.
                logger.info("- Balance of %s updated to %s LOOT", address,
                            balance)
                self.redis_cache.set("balance:%s" % address, int(balance))
                return

            # Event: get_marketplace_owner
            if event_name == "get_marketplace_owner":
                marketplace = event.event_payload[1].decode("utf-8")
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                logger.info("- Owner of %s: %s", marketplace, address)
                self.redis_cache.set("owner:%s" % marketplace, address)
                return

            # ==== Marketplace Events ====
            # Events that are specific to a marketplace.

            # Get the name of the marketplace, if it is none this is not a marketplace operation, return.
            marketplace = event.event_payload[1]
            if marketplace is not None:
                marketplace = marketplace.decode("utf-8")
            else:
                return

            # Ignore smart contract events that are not on our marketplace being used.
            if marketplace != self.marketplace:
                return

            # Event: get_inventory
            if event_name == "get_inventory":
                # Convert the script hash to an address.
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)

                # After being converted from a byte to an int, append each element to the list.
                inventory = []
                for i in event.event_payload[3]:
                    item_id = int.from_bytes(i, 'little')
                    inventory.append(item_id)

                # Update the inventory in the redis cache.
                logger.info("- Setting inventory of %s to %s", address,
                            inventory)
                self.redis_cache.set("inventory:%s" % address, inventory)
                self.redis_cache.set("inventoryUpdatedAt:%s" % address,
                                     int(time.time()))

            # Event: get_all_offers
            if event_name == "get_all_offers":
                retrieved_offers = event.event_payload[2]
                # Decode all the offers given in the payload.
                offers = []
                for i in retrieved_offers:
                    # Offer is received like 'offer\x03' so we convert to 'offer3'.
                    # We don't want to show the cached offers to the players.
                    i = i.decode("utf-8")
                    index = ord(i.split('offer')[1])
                    offer_id = 'offer' + str(index)
                    if offer_id not in self.cached_offers:
                        offers.append(offer_id)

                # Log the information and save to the cache.
                logger.info("-Setting offers in marketplace: %s", offers)
                self.redis_cache.set("offers", offers)
                self.redis_cache.set("timeOffersUpdated", str(datetime.now()))

            # Event: get_offer
            if event_name == "get_offer":
                print("Event: get_offer")
                # Get all the relevant information about the offer.
                offer = event.event_payload[2]
                address = offer[0]
                offer_id_encoded = offer[1]

                # If the offer is empty, return.
                if not offer:
                    return

                # We receive the offer index sent from contract in format e.g. "offer\x03", convert to "offer3".
                index = ord(offer_id_encoded.decode().split('offer')[1])
                offer_id = 'offer' + str(index)

                # Decode the bytes into integers.
                item_id = int.from_bytes(offer[2], 'little')
                price = int.from_bytes(offer[3], 'little')

                # Convert the script hash to an address.
                script_hash = address
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)

                # Put the offer information in a list and save it to the redis cache with the offer id as the key.
                offer_information = [address, offer_id, item_id, price]
                logger.info("-Setting offer:%s to %s", offer_id,
                            offer_information)
                self.redis_cache.set(offer_id, offer_information)

            # Event: Market/Item operation
            # The game/operator must know if these operations were successfully completed within the smart contract.
            # All of these notify events are sent in the same format.
            if event_name in ("cancel_offer", "buy_offer", "put_offer",
                              "give_items", "remove_item"):
                # Convert the script hash to address.
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                # Check if the operation was successfully completed within the smart contract.
                operation_successful = event.event_payload[3]
                # Save the address, and result to the cache with the event_name used as a key.
                self.redis_cache.set(event_name + "%s" % address,
                                     operation_successful)
                logger.info(
                    "-" + event_name + " of address %s was completed: %s",
                    address, operation_successful)
Ejemplo n.º 31
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                elif c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                elif c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                elif c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)
                else:
                    print("Cannot configure log. Please specify on|off")

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                elif c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)
                else:
                    print(
                        "Cannot configure VM instruction logging. Please specify on|off"
                    )

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        elif what == 'node-requests':
            if len(args) in [2, 3]:
                if len(args) == 3:
                    NodeLeader.Instance().setBlockReqSizeAndMax(
                        int(args[1]), int(args[2]))
                elif len(args) == 2:
                    NodeLeader.Instance().setBlockReqSizeByName(args[1])
            else:
                print("Invalid number of arguments")

        elif what == 'maxpeers':
            c1 = get_arg(args, 1)
            if c1 is not None:
                print("Maxpeers set to ", c1)
                settings.set_max_peers(c1)

            else:
                print("Maintaining current number of maxpeers")
        elif what == 'compiler-nep8':
            c1 = get_arg(args, 1)
            if c1 is not None:
                c1 = c1.lower()
                if c1 == 'on' or c1 == '1':
                    print("Compiler NEP8 instructions on")
                    settings.COMPILER_NEP_8 = True
                elif c1 == 'off' or c1 == '0':
                    print("Compiler NEP8 instructions off")
                    settings.COMPILER_NEP_8 = False
                else:
                    print(
                        "Cannot configure compiler NEP8 instructions. Please specify on|off"
                    )
            else:
                print(
                    "Cannot configure compiler NEP8 instructions. Please specify on|off"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off', 'config vm-log on|off', config compiler-nep8 on|off, or 'config maxpeers {num_peers}'"
                % what)
Ejemplo n.º 32
0
    def configure(self, args):
        what = get_arg(args)

        if what == 'debug':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Debug logging is now enabled")
                    settings.set_loglevel(logging.DEBUG)
                if c1 == 'off' or c1 == '0':
                    print("Debug logging is now disabled")
                    settings.set_loglevel(logging.INFO)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-events':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("Smart contract event logging is now enabled")
                    settings.set_log_smart_contract_events(True)
                if c1 == 'off' or c1 == '0':
                    print("Smart contract event logging is now disabled")
                    settings.set_log_smart_contract_events(False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'sc-debug-notify':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print(
                        "Smart contract emit Notify events on execution failure is now enabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(True)
                if c1 == 'off' or c1 == '0':
                    print(
                        "Smart contract emit Notify events on execution failure is now disabled"
                    )
                    settings.set_emit_notify_events_on_sc_execution_error(
                        False)

            else:
                print("Cannot configure log. Please specify on|off")

        elif what == 'vm-log':
            c1 = get_arg(args, 1).lower()
            if c1 is not None:
                if c1 == 'on' or c1 == '1':
                    print("VM instruction execution logging is now enabled")
                    settings.set_log_vm_instruction(True)
                if c1 == 'off' or c1 == '0':
                    print("VM instruction execution logging is now disabled")
                    settings.set_log_vm_instruction(False)

            else:
                print(
                    "Cannot configure VM instruction logging. Please specify on|off"
                )

        elif what == 'maxpeers':
            try:
                c1 = int(get_arg(args, 1).lower())
                num_peers = int(c1)
                if num_peers > 0:
                    old_max_peers = settings.CONNECTED_PEER_MAX
                    settings.set_max_peers(num_peers)
                    NodeLeader.Instance().OnUpdatedMaxPeers(
                        old_max_peers, num_peers)
                    print("set max peers to %s " % num_peers)
                else:
                    print("Please specify integer greater than zero")
            except Exception as e:
                print(
                    "Cannot configure max peers. Please specify an integer greater than 0"
                )

        else:
            print(
                "Cannot configure %s try 'config sc-events on|off', 'config debug on|off', 'config sc-debug-notify on|off' or 'config vm-log on|off'"
                % what)
Ejemplo n.º 33
0
def main():
    parser = argparse.ArgumentParser()

    # Network options
    group_network_container = parser.add_argument_group(title="Network options")
    group_network = group_network_container.add_mutually_exclusive_group(required=True)
    group_network.add_argument("--mainnet", action="store_true", default=False, help="Use MainNet")
    group_network.add_argument("--testnet", action="store_true", default=False, help="Use TestNet")
    group_network.add_argument("--privnet", action="store_true", default=False, help="Use PrivNet")
    group_network.add_argument("--coznet", action="store_true", default=False, help="Use CozNet")
    group_network.add_argument("--config", action="store", help="Use a specific config file")

    # Ports for RPC and REST api
    group_modes = parser.add_argument_group(title="Mode(s)")
    group_modes.add_argument("--port-rpc", type=int, help="port to use for the json-rpc api (eg. 10332)")
    group_modes.add_argument("--port-rest", type=int, help="port to use for the rest api (eg. 80)")

    # Advanced logging setup
    group_logging = parser.add_argument_group(title="Logging options")
    group_logging.add_argument("--logfile", action="store", type=str, help="Logfile")
    group_logging.add_argument("--syslog", action="store_true", help="Log to syslog instead of to log file ('user' is the default facility)")
    group_logging.add_argument("--syslog-local", action="store", type=int, choices=range(0, 7), metavar="[0-7]",
                               help="Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0').")
    group_logging.add_argument("--disable-stderr", action="store_true", help="Disable stderr logger")

    # Where to store stuff
    parser.add_argument("--datadir", action="store",
                        help="Absolute path to use for database directories")
    # peers
    parser.add_argument("--maxpeers", action="store", default=5,
                        help="Max peers to use for P2P Joining")

    # If a wallet should be opened
    parser.add_argument("--wallet",
                        action="store",
                        help="Open wallet. Will allow you to use methods that require an open wallet")

    # host
    parser.add_argument("--host", action="store", type=str, help="Hostname ( for example 127.0.0.1)", default="0.0.0.0")

    # Now parse
    args = parser.parse_args()
    # print(args)

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    if args.logfile and (args.syslog or args.syslog_local):
        print("Error: Cannot only use logfile or syslog at once")
        parser.print_help()
        return

    # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.
    if args.datadir:
        settings.set_data_dir(args.datadir)

    # Network configuration depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    if args.maxpeers:
        try:
            settings.set_max_peers(args.maxpeers)
            print("Maxpeers set to ", args.maxpeers)
        except ValueError:
            print("Please supply a positive integer for maxpeers")
            return  

    if args.syslog or args.syslog_local is not None:
        # Setup the syslog facility
        if args.syslog_local is not None:
            print("Logging to syslog local%s facility" % args.syslog_local)
            syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local
        else:
            print("Logging to syslog user facility")
            syslog_facility = SysLogHandler.LOG_USER

        # Setup logzero to only use the syslog handler
        logzero.syslog(facility=syslog_facility)
    else:
        # Setup file logging
        if args.logfile:
            logfile = os.path.abspath(args.logfile)
            if args.disable_stderr:
                print("Logging to logfile: %s" % logfile)
            else:
                print("Logging to stderr and logfile: %s" % logfile)
            logzero.logfile(logfile, maxBytes=LOGFILE_MAX_BYTES, backupCount=LOGFILE_BACKUP_COUNT, disableStderrLogger=args.disable_stderr)

        else:
            print("Logging to stdout and stderr")

    if args.wallet:
        if not os.path.exists(args.wallet):
            print("Wallet file not found")
            return

        passwd = os.environ.get('NEO_PYTHON_JSONRPC_WALLET_PASSWORD', None)
        if not passwd:
            passwd = prompt("[password]> ", is_password=True)

        password_key = to_aes_key(passwd)
        try:
            wallet = UserWallet.Open(args.wallet, password_key)

        except Exception as e:
            print(f"Could not open wallet {e}")
            return
    else:
        wallet = None

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Write a PID file to easily quit the service
    write_pid_file()

    # Setup Twisted and Klein logging to use the logzero setup
    observer = STDLibLogObserver(name=logzero.LOGZERO_DEFAULT_LOGGER)
    globalLogPublisher.addObserver(observer)

    def loopingCallErrorHandler(error):
        logger.info("Error in loop: %s " % error)

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.chain_leveldb_path)
    Blockchain.RegisterBlockchain(blockchain)

    start_block_persisting()

    # If a wallet is open, make sure it processes blocks
    if wallet:
        walletdb_loop = task.LoopingCall(wallet.ProcessBlocks)
        wallet_loop_deferred = walletdb_loop.start(1)
        wallet_loop_deferred.addErrback(loopingCallErrorHandler)

    # Setup twisted reactor, NodeLeader and start the NotificationDB
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()
    NotificationDB.instance().start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" % (args.host, args.port_rpc))
        try:
            rpc_class = load_class_from_path(settings.RPC_SERVER)
        except ValueError as err:
            logger.error(err)
            sys.exit()
        api_server_rpc = rpc_class(args.port_rpc, wallet=wallet)

        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, args.host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(Site(api_server_rpc.app.resource()))

    if args.port_rest:
        logger.info("Starting REST api server on http://%s:%s" % (args.host, args.port_rest))
        try:
            rest_api = load_class_from_path(settings.REST_SERVER)
        except ValueError as err:
            logger.error(err)
            sys.exit()
        api_server_rest = rest_api()
        endpoint_rest = "tcp:port={0}:interface={1}".format(args.port_rest, args.host)
        endpoints.serverFromString(reactor, endpoint_rest).listen(Site(api_server_rest.app.resource()))

    reactor.addSystemEventTrigger('before', 'shutdown', stop_block_persisting)
    reactor.run()

    # After the reactor is stopped, gracefully shutdown the database.
    logger.info("Closing databases...")
    NotificationDB.close()
    Blockchain.Default().Dispose()
    NodeLeader.Instance().Shutdown()
    if wallet:
        wallet.Close()
Ejemplo n.º 34
0
def main():
    parser = argparse.ArgumentParser()

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-m",
                       "--mainnet",
                       action="store_true",
                       default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument("-t",
                       "--testnet",
                       action="store_true",
                       default=False,
                       help="Use TestNet instead of the default TestNet")
    group.add_argument("-p",
                       "--privnet",
                       action="store_true",
                       default=False,
                       help="Use PrivNet instead of the default TestNet")
    group.add_argument(
        "--coznet",
        action="store_true",
        default=False,
        help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c",
                       "--config",
                       action="store",
                       help="Use a specific config file")

    parser.add_argument("--port-rpc",
                        type=int,
                        help="port to use for the json-rpc api (eg. 10332)")
    parser.add_argument("--port-rest",
                        type=int,
                        help="port to use for the rest api (eg. 80)")

    args = parser.parse_args()

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    # Write a PID file to easily quit the service
    write_pid_file()

    # Setup the blockchain
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    NodeLeader.Instance().Start()

    # Disable smart contract events for external smart contracts
    settings.set_log_smart_contract_events(False)

    # Open a wallet otherwise exit.
    try:
        bcontract.start_db_loop()
    except Exception as e:
        logger.error(
            "Error starting the custom neo node. wallet file and correct password are necessary %s"
            % e)
        exit(1)

    #
    # Start a thread with custom code
    #
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    host = "0.0.0.0"

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" %
                    (host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(
            Site(api_server_rpc.app.resource()))

    if args.port_rest:
        logger.info("Starting smartcontract api server on http://%s:%s" %
                    (host, args.port_rest))
        endpoint_description = "tcp:port={0}:interface={1}".format(
            args.port_rest, host)
        endpoint = endpoints.serverFromString(reactor, endpoint_description)
        endpoint.listen(Site(app.resource()))

    # app.run(host, 9999)
    # Run all the things (blocking call)
    logger.info("Everything is setup and running. Waiting for events...")
    reactor.run()
    logger.info("Shutting down.")
Ejemplo n.º 35
0
async def setup_and_start(loop):
    parser = argparse.ArgumentParser()

    # Network options
    group_network_container = parser.add_argument_group(
        title="Network options")
    group_network = group_network_container.add_mutually_exclusive_group(
        required=True)
    group_network.add_argument("--mainnet",
                               action="store_true",
                               default=False,
                               help="Use MainNet")
    group_network.add_argument("--testnet",
                               action="store_true",
                               default=False,
                               help="Use TestNet")
    group_network.add_argument("--privnet",
                               action="store_true",
                               default=False,
                               help="Use PrivNet")
    group_network.add_argument("--coznet",
                               action="store_true",
                               default=False,
                               help="Use CozNet")
    group_network.add_argument("--config",
                               action="store",
                               help="Use a specific config file")

    # Ports for RPC and REST api
    group_modes = parser.add_argument_group(title="Mode(s)")
    group_modes.add_argument(
        "--port-rpc",
        type=int,
        help="port to use for the json-rpc api (eg. 10332)")
    group_modes.add_argument("--port-rest",
                             type=int,
                             help="port to use for the rest api (eg. 80)")

    # Advanced logging setup
    group_logging = parser.add_argument_group(title="Logging options")
    group_logging.add_argument("--logfile",
                               action="store",
                               type=str,
                               help="Logfile")
    group_logging.add_argument(
        "--syslog",
        action="store_true",
        help=
        "Log to syslog instead of to log file ('user' is the default facility)"
    )
    group_logging.add_argument(
        "--syslog-local",
        action="store",
        type=int,
        choices=range(0, 7 + 1),
        metavar="[0-7]",
        help=
        "Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0')."
    )
    group_logging.add_argument("--disable-stderr",
                               action="store_true",
                               help="Disable stderr logger")

    # Where to store stuff
    parser.add_argument("--datadir",
                        action="store",
                        help="Absolute path to use for database directories")
    # peers
    parser.add_argument("--minpeers",
                        action="store",
                        type=int,
                        choices=range(1, 10 + 1),
                        metavar="[1-10]",
                        help="Min peers to use for P2P Joining")

    parser.add_argument("--maxpeers",
                        action="store",
                        type=int,
                        choices=range(1, 10 + 1),
                        metavar="[1-10]",
                        help="Max peers to use for P2P Joining")

    # If a wallet should be opened
    parser.add_argument(
        "--wallet",
        action="store",
        help=
        "Open wallet. Will allow you to use methods that require an open wallet"
    )

    # host
    parser.add_argument("--host",
                        action="store",
                        type=str,
                        help="Hostname ( for example 127.0.0.1)",
                        default="0.0.0.0")

    # Now parse
    args = parser.parse_args()
    # print(args)

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        raise SystemExit

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        raise SystemExit

    if args.logfile and (args.syslog or args.syslog_local):
        print("Error: Cannot only use logfile or syslog at once")
        parser.print_help()
        raise SystemExit

    # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.
    if args.datadir:
        settings.set_data_dir(args.datadir)

    # Network configuration depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    def set_min_peers(num_peers) -> bool:
        try:
            settings.set_min_peers(num_peers)
            print("Minpeers set to ", num_peers)
            return True
        except ValueError:
            print("Please supply a positive integer for minpeers")
            return False

    def set_max_peers(num_peers) -> bool:
        try:
            settings.set_max_peers(num_peers)
            print("Maxpeers set to ", num_peers)
            return True
        except ValueError:
            print("Please supply a positive integer for maxpeers")
            return False

    minpeers = args.minpeers
    maxpeers = args.maxpeers

    if minpeers and maxpeers:
        if minpeers > maxpeers:
            print("minpeers setting cannot be bigger than maxpeers setting")
            return
        if not set_min_peers(minpeers) or not set_max_peers(maxpeers):
            return
    elif minpeers:
        if not set_min_peers(minpeers):
            return
        if minpeers > settings.CONNECTED_PEER_MAX:
            if not set_max_peers(minpeers):
                return
    elif maxpeers:
        if not set_max_peers(maxpeers):
            return
        if maxpeers < settings.CONNECTED_PEER_MIN:
            if not set_min_peers(maxpeers):
                return

    if args.syslog or args.syslog_local is not None:
        # Setup the syslog facility
        if args.syslog_local is not None:
            print("Logging to syslog local%s facility" % args.syslog_local)
            syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local
        else:
            print("Logging to syslog user facility")
            syslog_facility = SysLogHandler.LOG_USER

        # Setup logzero to only use the syslog handler
        logzero.syslog(facility=syslog_facility)
    else:
        # Setup file logging
        if args.logfile:
            logfile = os.path.abspath(args.logfile)
            if args.disable_stderr:
                print("Logging to logfile: %s" % logfile)
            else:
                print("Logging to stderr and logfile: %s" % logfile)
            logzero.logfile(logfile,
                            maxBytes=LOGFILE_MAX_BYTES,
                            backupCount=LOGFILE_BACKUP_COUNT,
                            disableStderrLogger=args.disable_stderr)

        else:
            print("Logging to stdout and stderr")

    if args.wallet:
        if not os.path.exists(args.wallet):
            print("Wallet file not found")
            return

        passwd = os.environ.get('NEO_PYTHON_JSONRPC_WALLET_PASSWORD', None)
        if not passwd:
            try:
                passwd = prompt("[password]> ", is_password=True)
            except KeyboardInterrupt:
                print("Wallet opening cancelled")
                return

        password_key = to_aes_key(passwd)
        try:
            wallet = UserWallet.Open(args.wallet, password_key)
            asyncio.create_task(
                wallet.sync_wallet(start_block=wallet._current_height))

        except Exception as e:
            print(f"Could not open wallet {e}")
            return
    else:
        wallet = None

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Write a PID file to easily quit the service
    write_pid_file()

    # Instantiate the blockchain and subscribe to notifications
    blockchain = Blockchain(getBlockchainDB())
    Blockchain.RegisterBlockchain(blockchain)

    p2p = NetworkService()
    p2p_task = loop.create_task(p2p.start())
    loop.create_task(custom_background_code())

    NotificationDB.instance().start()

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" %
                    (args.host, args.port_rpc))
        try:
            rpc_class = load_class_from_path(settings.RPC_SERVER)
        except ValueError as err:
            logger.error(err)
            sys.exit()
        api_server_rpc = rpc_class(wallet=wallet)

        runner = web.AppRunner(api_server_rpc.app)
        await runner.setup()
        site = web.TCPSite(runner, args.host, args.port_rpc)
        await site.start()

    if args.port_rest:
        logger.info("Starting REST api server on http://%s:%s" %
                    (args.host, args.port_rest))
        try:
            rest_api = load_class_from_path(settings.REST_SERVER)
        except ValueError as err:
            logger.error(err)
            sys.exit()
        api_server_rest = rest_api()
        runner = web.AppRunner(api_server_rest.app)
        await runner.setup()
        site = web.TCPSite(runner, args.host, args.port_rpc)
        await site.start()

    return wallet
    def run(self):
        # bl: changing to 15 so that we can get connections with a high number to improve transaction relayability
        settings.set_max_peers(15)

        loop = asyncio.get_event_loop()

        # because a KeyboardInterrupt is so violent it can shutdown the DB in an unpredictable state.
        loop.add_signal_handler(SIGINT, quit)
        loop.add_signal_handler(SIGHUP, quit)
        loop.add_signal_handler(SIGTERM, quit)

        # Disable smart contract events for external smart contracts
        settings.set_log_smart_contract_events(False)

        # Instantiate the blockchain and subscribe to notifications
        blockchain = Blockchain(
            DBFactory.getBlockchainDB(settings.chain_leveldb_path))
        Blockchain.RegisterBlockchain(blockchain)

        # Try to set up a notification db
        if NotificationDB.instance():
            NotificationDB.instance().start()

        # if the wallet was set up (by setting a path and loading the password), then open it!
        if self.wallet_path:
            self.wallet_open()

        # invoke any pre-start action that needs to occur before we start the loop.
        # optional for subclasses to implement.
        self.pre_start()

        blockchain_main_task = loop.create_task(self.run_loop())
        p2p = NetworkService()
        loop.create_task(p2p.start())

        async def shutdown():
            all_tasks = asyncio.all_tasks()
            for task in all_tasks:
                task.cancel()
                with suppress(asyncio.CancelledError):
                    await task

        try:
            loop.run_forever()
        except (SystemExit, KeyboardInterrupt):
            with suppress((SystemExit, Exception)):
                blockchain_main_task.exception()
            loop.run_until_complete(p2p.shutdown())
            loop.run_until_complete(shutdown())
            loop.run_until_complete(loop.shutdown_asyncgens())
            loop.stop()
        finally:
            loop.close()

        # Run things

        if self.wallet_path:
            logger.info("Closing wallet file %s" % self.wallet_path)
            asyncio.run(self.wallet_close())

        # After the reactor is stopped, gracefully shutdown the database.
        logger.info("Closing databases...")
        NotificationDB.close()
        Blockchain.Default().Dispose()