def __init__(self, path, passwordKey, create): """ Args: path (str): A path indicating where to create or open the wallet. passwordKey (str): A password to use in creating or opening the wallet. create (bool): Whether to create the wallet or simply open. """ self.AddressVersion = settings.ADDRESS_VERSION self._path = path self._lock = RLock() if create: self._iv = bytes(Random.get_random_bytes(16)) self._master_key = bytes(Random.get_random_bytes(32)) self._keys = {} self._contracts = {} self._coins = {} if Blockchain.Default() is None: self._indexedDB = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(self._indexedDB) else: self._indexedDB = Blockchain.Default() self._current_height = 0 self.BuildDatabase() passwordHash = hashlib.sha256(passwordKey).digest() master = AES.new(passwordKey, AES.MODE_CBC, self._iv) mk = master.encrypt(self._master_key) self.SaveStoredData('PasswordHash', passwordHash) self.SaveStoredData('IV', self._iv) self.SaveStoredData('MasterKey', mk) self.SaveStoredData('MigrationState', '1') self.SaveStoredData('Height', self._current_height.to_bytes(4, 'little')) else: self.BuildDatabase() passwordHash = self.LoadStoredData('PasswordHash') if passwordHash is None: raise Exception("Password hash not found in database") hkey = hashlib.sha256(passwordKey).digest() if self.LoadStoredData('MigrationState') != '1': raise Exception("This wallet is currently vulnerable. Please " "execute the \"reencrypt_wallet.py\" script " "on this wallet before continuing") if passwordHash is not None and passwordHash != hkey: raise Exception("Incorrect Password") self._iv = self.LoadStoredData('IV') master_stored = self.LoadStoredData('MasterKey') aes = AES.new(passwordKey, AES.MODE_CBC, self._iv) self._master_key = aes.decrypt(master_stored) self._keys = self.LoadKeyPairs() self._contracts = self.LoadContracts() self._watch_only = self.LoadWatchOnly() self._tokens = self.LoadNEP5Tokens() self._coins = self.LoadCoins() try: h = int(self.LoadStoredData('Height')) self._current_height = h except Exception as e: logger.error("Could not load height data %s " % e) self._current_height = 0 del passwordKey
args = parser.parse_args() try: settings.setup_privnet(args.privnet) except PrivnetConnectionError as e: logger.error(str(e)) if args.datadir: settings.set_data_dir(args.datadir) print("Blockchain DB path:", settings.chain_leveldb_path) if os.path.exists(settings.chain_leveldb_path): print( "Warning: Chain database already exists. If this is from a previous private network, you need to delete %s" % settings.chain_leveldb_path) blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) # Try to set up a notification db #if NotificationDB.instance(): # NotificationDB.instance().start() reactor.suggestThreadPoolSize(15) NodeLeader.Instance().Start() pc = PrivnetClaimall("/tmp/wallet", "coz", args.time, "/tmp/wif") reactor.callInThread(pc.run) reactor.run()
token.array_processed = True import sys import logging #no logging for the node #logname = 'nodes.log' #logging.basicConfig( # level=logging.DEBUG, # filemode='a', # filename=logname, # format="%(levelname)s:%(name)s:%(funcName)s:%(message)s") from neo.Network.NodeLeader import NodeLeader from twisted.internet import reactor, task from neo.Core.Blockchain import Blockchain from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain from neo import Settings blockchain = LevelDBBlockchain(Settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.01) NodeLeader.Instance().Start() reactor.run()
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") # extended json-rpc api parser.add_argument("--extended-rpc", action="store_true", default=False, help="Use extended json-rpc api") # 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() public_key = PUBLIC_KEY_MAINNET is_mainnet = True elif args.testnet: settings.setup_testnet() public_key = PUBLIC_KEY_TESTNET is_mainnet = False 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") 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) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) db_loop_deferred = dbloop.start(.1) db_loop_deferred.addErrback(loopingCallErrorHandler) # 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() wallet = OnlyPublicWallet(public_key, is_mainnet) walletdb_loop = task.LoopingCall(wallet.ProcessBlocks) walletdb_loop.start(.1) if args.port_rpc and args.extended_rpc: logger.info("Starting extended json-rpc api server on http://%s:%s" % (args.host, args.port_rpc)) api_server_rpc = ExtendedJsonRpcApi(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())) # reactor.listenTCP(int(args.port_rpc), server.Site(api_server_rpc)) # api_server_rpc.app.run(args.host, args.port_rpc) elif 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, 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)) 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() if wallet: wallet.Close()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="use MainNet instead of the default TestNet") parser.add_argument("-c", "--config", action="store", help="Use a specific config file") # Where to store stuff parser.add_argument("--datadir", action="store", help="Absolute path to use for database directories") parser.add_argument("-i", "--input", help="Where the input file lives") parser.add_argument("-t", "--totalblocks", help="Total blocks to import", type=int) parser.add_argument("-l", "--logevents", help="Log Smart Contract Events", default=False, action="store_true") parser.add_argument("-n", "--notifications", help="Persist Notifications to database", default=False, action="store_true") parser.add_argument("-a", "--append", action="store_true", default=False, help="Append to current Block database") args = parser.parse_args() if args.mainnet and args.config: print( "Cannot use both --config and --mainnet parameters, please use only one." ) exit(1) # 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) # 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() if args.logevents: settings.log_smart_contract_events = True if not args.input: raise Exception("Please specify an input path") file_path = args.input append = False store_notifications = False start_block = 0 if args.append: append = True if args.notifications: store_notifications = True header_hash_list = [] with open(file_path, 'rb') as file_input: total_blocks_available = int.from_bytes(file_input.read(4), 'little') if total_blocks_available == 0: total_blocks_available = int.from_bytes(file_input.read(4), 'little') total_blocks = total_blocks_available if args.totalblocks and args.totalblocks < total_blocks and args.totalblocks > 0: total_blocks = args.totalblocks target_dir = os.path.join(settings.DATA_DIR_PATH, settings.LEVELDB_PATH) notif_target_dir = os.path.join(settings.DATA_DIR_PATH, settings.NOTIFICATION_DB_PATH) if append: blockchain = LevelDBBlockchain(settings.chain_leveldb_path, skip_header_check=True) Blockchain.RegisterBlockchain(blockchain) start_block = Blockchain.Default().Height print("Starting import at %s " % start_block) else: print("Will import %s of %s blocks to %s" % (total_blocks, total_blocks_available, target_dir)) print( "This will overwrite any data currently in %s and %s.\nType 'confirm' to continue" % (target_dir, notif_target_dir)) try: confirm = prompt("[confirm]> ", is_password=False) except KeyboardInterrupt: confirm = False if not confirm == 'confirm': print("Cancelled operation") return False try: if os.path.exists(target_dir): shutil.rmtree(target_dir) if os.path.exists(notif_target_dir): shutil.rmtree(notif_target_dir) except Exception as e: print("Could not remove existing data %s " % e) return False # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) chain = Blockchain.Default() if store_notifications: NotificationDB.instance().start() stream = MemoryStream() reader = BinaryReader(stream) block = Block() length_ba = bytearray(4) for index in trange(total_blocks, desc='Importing Blocks', unit=' Block'): # set stream data file_input.readinto(length_ba) block_len = int.from_bytes(length_ba, 'little') reader.stream.write(file_input.read(block_len)) reader.stream.seek(0) # get block block.DeserializeForImport(reader) header_hash_list.append(block.Hash.ToBytes()) # add if block.Index > start_block: chain.AddBlockDirectly(block, do_persist_complete=store_notifications) # reset blockheader block._header = None block.__hash = None # reset stream reader.stream.Cleanup() print("Wrote blocks. Now writing headers") chain = Blockchain.Default() # reset header hash list chain._db.delete(DBPrefix.IX_HeaderHashList) total = len(header_hash_list) chain._header_index = header_hash_list print("storing header hash list...") while total - 2000 >= chain._stored_header_count: ms = StreamManager.GetStream() w = BinaryWriter(ms) headers_to_write = chain._header_index[chain._stored_header_count:chain ._stored_header_count + 2000] w.Write2000256List(headers_to_write) out = ms.ToArray() StreamManager.ReleaseStream(ms) with chain._db.write_batch() as wb: wb.put( DBPrefix.IX_HeaderHashList + chain._stored_header_count.to_bytes(4, 'little'), out) chain._stored_header_count += 2000 last_index = len(header_hash_list) chain._db.put(DBPrefix.SYS_CurrentHeader, header_hash_list[-1] + last_index.to_bytes(4, 'little')) print("Imported %s blocks to %s " % (total_blocks, target_dir))
def main(): parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true", default=False, help="Debug") parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="Use MainNet instead of the default TestNet") parser.add_argument("-p", "--privnet", action="store_true", default=False, help="Use PrivNet instead of the default TestNet") parser.add_argument( "--coznet", action="store_true", default=False, help="Use the CoZ network instead of the default TestNet") parser.add_argument("-w", "--wallet", action="store", help="Wallet path") parser.add_argument("-pass", "--password", action="store", help="Wallet path") parser.add_argument("-pro", "--project", action="store", help="Project") parser.add_argument("-fs", "--funding_stage", action="store", help="Funding Stage") parser.add_argument("-ms", "--milestone", action="store", help="Milestone") parser.add_argument("-con", "--fr_config", action="store", help="Funding Roadmap config") parser.add_argument("-sum", "--summary", action="store_true", default=False, help="Get Summary of project") parser.add_argument("-to_addr", "--to_addr", action="store", help="To Addr") parser.add_argument("-from_addr", "--from_addr", action="store", help="From addr") parser.add_argument("-send", "--send_gas", action="store", help="Contribute to project") parser.add_argument("-cr", "--claim_refund", action="store_true", default=False, help="Claim refund") parser.add_argument("-cc", "--claim_contributions", action="store_true", default=False, help="Claim contributions") parser.add_argument("-kyc", "--kyc_status", action="store", help="Get kyc status") parser.add_argument("-kreg", "--kyc_register", action="store", help="Register KYC addr") parser.add_argument("-invoke", "--invoke", action="store", help="Invoke operation") parser.add_argument("-args", "--args", action="store", help="Valuss to input as list []") args = parser.parse_args() if args.mainnet and args.privnet: print("Cannot use both --mainnet and --privnet arguments") exit(1) # Setup depending on command line arguments. By default, the testnet settings are already loaded. if args.mainnet: settings.setup_mainnet() elif args.privnet: settings.setup_privnet() elif args.coznet: settings.setup_coznet() # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) # Try to set up a notification db if NotificationDB.instance(): NotificationDB.instance().start() cli = TheConstructInterface(input_args=args, debug=args.debug) # Run reactor.suggestThreadPoolSize(15) reactor.callInThread(cli.run) NodeLeader.Instance().Start() reactor.run()
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( "-u", "--unittest", 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("-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() # 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) # 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() elif args.unittest: settings.setup_unittest_net() # Logfile settings & setup logfile_fn = os.path.join(settings.DATA_DIR_PATH, 'prompt.log') logfile_max_bytes = 5e7 # 50 MB logfile_backup_count = 3 # 3 logfiles history settings.set_logfile(logfile_fn, logfile_max_bytes, logfile_backup_count) if args.theme: preferences.set_theme(args.theme) if args.verbose: settings.set_log_smart_contract_events(True) 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 fn_prompt_history = os.path.join(settings.DATA_DIR_PATH, '.prompt.py.history') cli = PromptInterface(fn_prompt_history) # Run things 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()
def __init__(self, path, passwordKey, create): """ Args: path: (str) A path indicating where to create or open the wallet passwordKey: (str) A password to use in creating or opening the wallet create: (bool) Whether to create the wallet or simply open """ self.AddressVersion = settings.ADDRESS_VERSION self._path = path if create: self._iv = bytes(Random.get_random_bytes(16)) self._master_key = bytes(Random.get_random_bytes(32)) self._keys = {} self._contracts = {} self._coins = {} if Blockchain.Default() is None: self._indexedDB = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(self._indexedDB) else: self._indexedDB = Blockchain.Default() self._current_height = 0 self.BuildDatabase() passwordHash = hashlib.sha256(passwordKey.encode('utf-8')).digest() master = AES.new(passwordHash, AES.MODE_CBC, self._iv) mk = master.encrypt(self._master_key) self.SaveStoredData('PasswordHash', passwordHash) self.SaveStoredData('IV', self._iv), self.SaveStoredData('MasterKey', mk) self.SaveStoredData('Height', self._current_height.to_bytes(4, 'little')) else: self.BuildDatabase() passwordHash = self.LoadStoredData('PasswordHash') if passwordHash is None: raise Exception("Password hash not found in database") hkey = hashlib.sha256(passwordKey.encode('utf-8')) if passwordHash is not None and passwordHash != hashlib.sha256( passwordKey.encode('utf-8')).digest(): raise Exception("Incorrect Password") self._iv = self.LoadStoredData('IV') master_stored = self.LoadStoredData('MasterKey') aes = AES.new(hkey.digest(), AES.MODE_CBC, self._iv) self._master_key = aes.decrypt(master_stored) self._keys = self.LoadKeyPairs() self._contracts = self.LoadContracts() self._watch_only = self.LoadWatchOnly() self._tokens = self.LoadNEP5Tokens() self._coins = self.LoadCoins() try: h = int(self.LoadStoredData('Height')) self._current_height = h except Exception as e: logger.error("couldnt load height data %s " % e) self._current_height = 0 del passwordKey
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") 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'" ) 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: settings.setup_privnet() elif args.coznet: settings.setup_coznet() if args.theme: preferences.set_theme(args.theme) # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.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()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="Use MainNet instead of the default TestNet") parser.add_argument("-p", "--privnet", action="store_true", default=False, help="Use PrivNet instead of the default TestNet") parser.add_argument("-c", "--config", action="store", help="Use a specific config file") 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'" ) parser.add_argument( "--version", action="version", version="neo-python v{version}".format(version=__version__)) args = parser.parse_args() if args.config and (args.mainnet or args.privnet): print( "Cannot use --config and --mainnet/--privnet together, please use only one" ) exit(1) if args.mainnet and args.privnet: print("Cannot use --mainnet and --privnet together") exit(1) # 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() if args.theme: preferences.set_theme(args.theme) # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) # Try to set up a notification db if NotificationDB.instance(): NotificationDB.instance().start() # Start the prompt interface app = QApplication(sys.argv) # >>> start gui app cli = PromptInterface() # Run #reactor.suggestThreadPoolSize(15) # >>> commented out reactor #reactor.callInThread(cli.run) # >>> commented out reactor cli.run() # >>> running cli without reactor due to threading issue NodeLeader.Instance().Start() #reactor.run() # >>> commented out reactor app.exec_() # >>> catch gui app
def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="use MainNet instead of the default TestNet") parser.add_argument("-c", "--config", action="store", help="Use a specific config file") # Where to store stuff parser.add_argument("--datadir", action="store", help="Absolute path to use for database directories") parser.add_argument("-i", "--input", help="Where the input file lives") parser.add_argument("-t", "--totalblocks", help="Total blocks to import", type=int) parser.add_argument("-l", "--logevents", help="Log Smart Contract Events", default=False, action="store_true") args = parser.parse_args() if args.mainnet and args.config: print( "Cannot use both --config and --mainnet parameters, please use only one." ) exit(1) # 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) # 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() if args.logevents: settings.log_smart_contract_events = True if not args.input: raise Exception("Please specify an input path") file_path = args.input with open(file_path, 'rb') as file_input: total_blocks = int.from_bytes(file_input.read(4), 'little') target_dir = os.path.join(settings.DATA_DIR_PATH, settings.LEVELDB_PATH) notif_target_dir = os.path.join(settings.DATA_DIR_PATH, settings.NOTIFICATION_DB_PATH) print("Will import %s blocks to %s" % (total_blocks, target_dir)) print( "This will overwrite any data currently in %s and %s.\nType 'confirm' to continue" % (target_dir, notif_target_dir)) confirm = prompt("[confirm]> ", is_password=False) if not confirm == 'confirm': print("Cancelled operation") return False try: if os.path.exists(target_dir): shutil.rmtree(target_dir) if os.path.exists(notif_target_dir): shutil.rmtree(notif_target_dir) except Exception as e: print("Could not remove existing data %s " % e) return False # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) chain = Blockchain.Default() stream = MemoryStream() reader = BinaryReader(stream) block = Block() for index in trange(total_blocks, desc='Importing Blocks', unit=' Block'): # set stream data block_len = int.from_bytes(file_input.read(4), 'little') reader.stream.write(file_input.read(block_len)) reader.stream.seek(0) # get block block.Deserialize(reader) # add if block.Index > 0: chain.AddBlockDirectly(block) # reset stream reader.stream.Cleanup() print("Imported %s blocks to %s " % (total_blocks, target_dir))
def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="Use MainNet instead of the default TestNet") parser.add_argument("-p", "--privnet", action="store_true", default=False, help="Use PrivNet instead of the default TestNet") parser.add_argument("-c", "--config", action="store", help="Use a specific config file") parser.add_argument( '--version', action='version', version='neo-python v{version}'.format(version=__version__)) args = parser.parse_args() if args.config and (args.mainnet or args.privnet): print( "Cannot use both --config and --mainnet/--privnet arguments, please use only one." ) exit(1) if args.mainnet and args.privnet: print("Cannot use both --mainnet and --privnet arguments") exit(1) # 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() # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) settings.set_log_smart_contract_events(False) ndb = NotificationDB.instance() ndb.start() # Run reactor.suggestThreadPoolSize(15) NodeLeader.Instance().Start() host = "0.0.0.0" port = settings.RPC_PORT logger.info("Starting json-rpc api server on http://%s:%s" % (host, port)) api_server = JsonRpcApi(port) api_server.app.run(host, port)
def setUpClass(self): self._blockchain = LevelDBBlockchain(path=self.LEVELDB_TESTPATH) Blockchain.RegisterBlockchain(self._blockchain)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", "--mainnet", action="store_true", default=False, help="Use MainNet instead of the default TestNet") parser.add_argument("-p", "--privnet", action="store_true", default=False, help="Use PrivNet instead of the default TestNet") parser.add_argument("-c", "--config", action="store", help="Use a specific config file") 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'" ) parser.add_argument( '--version', action='version', version='neo-python v{version}'.format(version=__version__)) args = parser.parse_args() if args.config and (args.mainnet or args.privnet): print( "Cannot use both --config and --mainnet/--privnet arguments, please use only one." ) exit(1) if args.mainnet and args.privnet: print("Cannot use both --mainnet and --privnet arguments") exit(1) # 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() if args.theme: preferences.set_theme(args.theme) # Instantiate the blockchain and subscribe to notifications blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) # Start the prompt interface cli = PromptInterface() # Run reactor.suggestThreadPoolSize(15) reactor.callInThread(cli.run) NodeLeader.Instance().Start() reactor.run()