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()
def custom_background_code(connection_str, ip_dict): """ Custom code run in a background thread. This function is run in a daemonized thread, which means it can be instantly killed at any moment, whenever the main thread quits. If you need more safety, don't use a daemonized thread and handle exiting this thread in another way (eg. with signals and events). """ while True: conn = psycopg2.connect(connection_str) cursor = conn.cursor() logger.info("Block %s / %s", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight)) print(len(NodeLeader.Instance().Peers)) insert_time = time.time() if len(NodeLeader.Instance().Peers) > 0: for peer in NodeLeader.Instance().Peers: print(peer.host) if peer.host in ip_dict: address_list = ip_dict[peer.host] for address_id in address_list: cursor.execute( "INSERT INTO p2p_tcp_status_history (ts, connection_id, p2p_tcp_status) VALUES (%s, %s, %s)", [getSqlDateTime(insert_time), address_id, True]) else: print("ip not in database") conn.commit() cursor.close() conn.close() sleep(15)
def execute(self, arguments): c1 = get_arg(arguments) if c1 is not None: try: current_max = settings.CONNECTED_PEER_MAX settings.set_max_peers(c1) c1 = int(c1) p_len = len(NodeLeader.Instance().Peers) if c1 < current_max and c1 < p_len: to_remove = p_len - c1 peers = NodeLeader.Instance().Peers for i in range(to_remove): peer = peers[-1] # disconnect last peer added first peer.Disconnect("Max connected peers reached", isDead=False) peers.pop() print(f"Maxpeers set to {c1}") return c1 except ValueError: print("Please supply a positive integer for maxpeers") return else: print(f"Maintaining maxpeers at {settings.CONNECTED_PEER_MAX}") return
def main(): # Use TestNet settings.setup_testnet() # 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 = MakeMultisig() # 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(**options): settings.setup_privnet() # Setup the blockchain blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Setup Notifications Database NotificationDB.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.") logger.info("Closing databases...") NotificationDB.close() Blockchain.Default().Dispose() NodeLeader.Instance().Shutdown()
def _clear_mempool(self): txs = [] values = NodeLeader.Instance().MemPool.values() for tx in values: txs.append(tx) for tx in txs: del NodeLeader.Instance().MemPool[tx.Hash.ToBytes()]
def show_nodes(self): if len(NodeLeader.Instance().Peers) > 0: out = '' for peer in NodeLeader.Instance().Peers: out += 'Peer %s - IO: %s\n' % (peer.Name(), peer.IOStats()) print_tokens([(Token.Number, out)], self.token_style) else: print('Not connected yet\n')
def show_nodes(self): if len(NodeLeader.Instance().Peers) > 0: out = "Total Connected: %s\n" % len(NodeLeader.Instance().Peers) for peer in NodeLeader.Instance().Peers: out += "Peer %s - IO: %s\n" % (peer.Name(), peer.IOStats()) print_formatted_text(FormattedText([("class:number", out)]), style=self.token_style) else: print("Not connected yet\n")
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 execute(self, arguments=None): if len(NodeLeader.Instance().Peers) > 0: out = "Total Connected: %s\n" % len(NodeLeader.Instance().Peers) for i, peer in enumerate(NodeLeader.Instance().Peers): out += f"Peer {i} {peer.Name():>12} - {peer.address:>21} - IO {peer.IOStats()}\n" print(out) return out else: print("Not connected yet\n") return
def test_config_node_requests(self): # test no input args = ['node-requests'] res = CommandConfig().execute(args) self.assertFalse(res) # test updating block request size # first make sure we have a predictable state NodeLeader.Instance().Reset() leader = NodeLeader.Instance() leader.ADDRS = ["127.0.0.1:20333", "127.0.0.2:20334"] leader.DEAD_ADDRS = ["127.0.0.1:20335"] # test slow setting args = ['node-requests', 'slow'] res = CommandConfig().execute(args) self.assertTrue(res) # test normal setting args = ['node-requests', 'normal'] res = CommandConfig().execute(args) self.assertTrue(res) # test fast setting args = ['node-requests', 'fast'] res = CommandConfig().execute(args) self.assertTrue(res) # test bad setting args = ['node-requests', 'blah'] res = CommandConfig().execute(args) self.assertFalse(res) # test custom setting args = ['node-requests', '20', '6000'] res = CommandConfig().execute(args) self.assertTrue(res) # test bad custom input args = ['node-requests', '20', 'blah'] res = CommandConfig().execute(args) self.assertFalse(res) # test bad custom setting: breqmax should be greater than breqpart args = ['node-requests', '20', '10'] res = CommandConfig().execute(args) self.assertFalse(res) # test another bad custom setting: breqpart should not exceed 500 args = ['node-requests', '600', '5000'] res = CommandConfig().execute(args) self.assertFalse(res)
def execute(self, arguments): if len(arguments) in [1, 2]: if len(arguments) == 2: try: return NodeLeader.Instance().setBlockReqSizeAndMax(int(arguments[0]), int(arguments[1])) except ValueError: print("Invalid values. Please specify a block request part and max size for each node, like 30 and 1000") return False elif len(arguments) == 1: return NodeLeader.Instance().setBlockReqSizeByName(arguments[0]) else: print("Please specify the required parameter") return False
def test_relay(self): leader = NodeLeader.Instance() def mock_call_later(delay, method, *args): method(*args) def mock_connect_tcp(host, port, factory, timeout=120): node = NeoNode() node.endpoint = Endpoint(host, port) leader.AddConnectedPeer(node) return node def mock_send_msg(node, message): return True with patch('twisted.internet.reactor.connectTCP', mock_connect_tcp): with patch('twisted.internet.reactor.callLater', mock_call_later): with patch('neo.Network.NeoNode.NeoNode.SendSerializedMessage', mock_send_msg): leader.Start() miner = MinerTransaction() res = leader.Relay(miner) self.assertFalse(res) tx = self._generate_tx() res = leader.Relay(tx) self.assertEqual(res, True) self.assertTrue(tx.Hash.ToBytes() in leader.MemPool.keys()) res2 = leader.Relay(tx) self.assertFalse(res2)
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.')
def get_peers(self): """Get all known nodes and their 'state' """ node = NodeLeader.Instance() result = {"connected": [], "unconnected": [], "bad": []} connected_peers = [] for peer in node.Peers: result['connected'].append({ "address": peer.host, "port": peer.port }) connected_peers.append("{}:{}".format(peer.host, peer.port)) for addr in node.DEAD_ADDRS: host, port = addr.rsplit(':', 1) result['bad'].append({"address": host, "port": port}) # "UnconnectedPeers" is never used. So a check is needed to # verify that a given address:port does not belong to a connected peer for addr in node.KNOWN_ADDRS: host, port = addr.rsplit(':', 1) if addr not in connected_peers: result['unconnected'].append({ "address": host, "port": int(port) }) return result
def sign_and_finish(self, wallet, jsn): context = ContractParametersContext.FromJson(jsn) if context is None: print("Failed to parse JSON") return None wallet.Sign(context) if context.Completed: print("Signature complete, relaying...") tx = context.Verifiable tx.scripts = context.GetScripts() wallet.SaveTransaction(tx) print("will send tx: %s " % json.dumps(tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(tx) if relayed: print("Relayed Tx: %s " % tx.Hash.ToString()) self.wait_for_tx(tx) return ('success') else: print("Could not relay tx %s " % tx.Hash.ToString()) return ('fail') else: print("Transaction signed, but the signature is still incomplete") return (json.dumps(context.ToJson(), separators=(',', ':')))
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.")
def send_to_address(self, params): asset, address, amount, fee = self.parse_send_params(params) standard_contract = self.wallet.GetStandardAddress() signer_contract = self.wallet.GetContract(standard_contract) output = TransactionOutput(AssetId=asset, Value=amount, script_hash=address) contract_tx = ContractTransaction(outputs=[output]) tx = self.wallet.MakeTransaction(tx=contract_tx, change_address=None, fee=fee) if tx is None: raise JsonRpcError(-300, "Insufficient funds") data = standard_contract.Data tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=data) ] context = ContractParametersContext( tx, isMultiSig=signer_contract.IsMultiSigContract) self.wallet.Sign(context) if context.Completed: tx.scripts = context.GetScripts() NodeLeader.Instance().Relay(tx) return tx.ToJson() else: return context.ToJson()
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() # 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 a thread with custom code t = threading.Thread(target=custom_background_stateinfo) t.setDaemon( True ) # daemonizing the thread will kill it when the main thread is quit t.start() # Run all the things (blocking call) reactor.run() logger.info("Shutting down.")
def quit(self): print('Shutting down. This may take a bit...') self.go_on = False NotificationDB.close() Blockchain.Default().Dispose() reactor.stop() NodeLeader.Instance().Shutdown()
def get_status(self, request): request.setHeader('Content-Type', 'application/json') return json.dumps({ 'current_height': Blockchain.Default().Height, 'version': settings.VERSION_NAME, 'num_peers': len(NodeLeader.Instance().Peers) }, indent=4, sort_keys=True)
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.")
def start_node(): # Setup blockchain settings.setup("data/protocol.json") blockchain = LevelDBBlockchain(settings.chain_leveldb_path) print(settings.SEED_LIST) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Start a thread with custom code d = threading.Thread(target=node_custom_background_code) d.setDaemon(True) d.start() logger.info("Ready") reactor.run() logger.info("Shutting down.")
def process_transaction(self, contract_tx, fee=None, address_from=None, change_addr=None): standard_contract = self.wallet.GetStandardAddress() signer_contract = self.wallet.GetContract(standard_contract) tx = self.wallet.MakeTransaction(tx=contract_tx, change_address=change_addr, fee=fee, from_addr=address_from) if tx is None: raise JsonRpcError(-300, "Insufficient funds") data = standard_contract.Data tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=data) ] context = ContractParametersContext( tx, isMultiSig=signer_contract.IsMultiSigContract) self.wallet.Sign(context) if context.Completed: tx.scripts = context.GetScripts() NodeLeader.Instance().Relay(tx) return tx.ToJson() else: return context.ToJson()
def InvokeContract(wallet, tx): wallet_tx = wallet.MakeTransaction(tx=tx) if wallet_tx: context = ContractParametersContext(wallet_tx) wallet.Sign(context) if context.Completed: tx.scripts = context.GetScripts() wallet.SaveTransaction(wallet_tx) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % tx.Hash.ToString()) return True else: print("Could not relay tx %s " % tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def __init__(self, incoming_client=False): """ Create an instance. The NeoNode class is the equivalent of the C# RemoteNode.cs class. It represents a single Node connected to the client. Args: incoming_client (bool): True if node is an incoming client and the handshake should be initiated. """ from neo.Network.NodeLeader import NodeLeader self.leader = NodeLeader.Instance() self.nodeid = self.leader.NodeId self.remote_nodeid = random.randint(1294967200, 4294967200) self.endpoint = '' self.buffer_in = bytearray() self.myblockrequests = set() self.bytes_in = 0 self.bytes_out = 0 self.host = None self.port = None self.identifier = self.leader.NodeCount self.leader.NodeCount += 1 self.incoming_client = incoming_client self.expect_verack_next = False self.Log("New Node created %s " % self.identifier)
def main(): conn = psycopg2.connect(connection_str) cursor = conn.cursor() ip_dict = getIpAddressMap(cursor) cursor.close() conn.close() # Use Custom config settings.setup("./config.json") settings.set_max_peers(500) # Setup the blockchain blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Start a thread with custom code d = threading.Thread(target=custom_background_code, args=( connection_str, ip_dict, )) d.setDaemon( True ) # daemonizing the thread will kill it when the main thread is quit d.start() # Run all the things (blocking call) reactor.run() logger.info("Shutting down.")
def InvokeWithTokenVerificationScript(wallet, tx, token, fee=Fixed8.Zero()): wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True) if wallet_tx: token_contract_state = Blockchain.Default().GetContract( token.ScriptHash.ToString()) print("token contract %s " % token_contract_state) tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=token.ScriptHash.Data) ] reedeem_script = token_contract_state.Code.Script.hex() # there has to be at least 1 param, and the first # one needs to be a signature param param_list = bytearray(b'\x00\x00') verification_contract = Contract.Create( reedeem_script, param_list, wallet.GetDefaultContract().PublicKeyHash) context = ContractParametersContext(wallet_tx) wallet.Sign(context) context.Add(verification_contract, 0, 0) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("full wallet tx: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) # toarray = Helper.ToArray(wallet_tx) # print("to arary %s " % toarray) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) # if it was relayed, we save tx wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def get_peers(self): """Get all known nodes and their "state" In the current implementation of NodeLeader there is no way to know which nodes are bad. """ node = NodeLeader.Instance() result = {"connected": [], "unconnected": [], "bad": []} connected_peers = [] for peer in node.Peers: result['connected'].append({ "address": peer.host, "port": peer.port }) connected_peers.append("{}:{}".format(peer.host, peer.port)) # "UnconnectedPeers" is never used. So a check is needed to # verify that a given address:port does not belong to a connected peer for peer in node.ADDRS: addr, port = peer.split(':') if peer not in connected_peers: result['unconnected'].append({ "address": addr, "port": int(port) }) return result
def do_send_created_tx(self): passwd = self._gathered_passwords[0] tx = self._wallet_send_tx self._wallet_send_tx = None self._gathered_passwords = None self._gather_password_action = None if not self.Wallet.ValidatePassword(passwd): print("incorrect password") return try: context = ContractParametersContext(tx) self.Wallet.Sign(context) if context.Completed: tx.scripts = context.GetScripts() self.Wallet.SaveTransaction(tx) relayed = NodeLeader.Instance().Relay(tx) if relayed: print("Relayed Tx: %s " % tx.Hash.ToString()) else: print("Could not relay tx %s " % tx.Hash.ToString()) except Exception as e: print("could not sign %s " % e) traceback.print_stack() traceback.print_exc()