Пример #1
0
def main():
    conn = client.Connection(('localhost', 50001))
    xpub, = sys.argv[1:]
    total = 0
    k = pycoin.ui.key_from_text.key_from_text(xpub)
    for change in (0, 1):
        empty = 0
        for n in range(100):
            address = k.subkey(change).subkey(n).address()
            script = script_for_address(address)
            script_hash = hashlib.sha256(script).digest()[::-1].hex()
            log.debug(
                '{}',
                conn.call('blockchain.scripthash.get_history', script_hash))
            reply = conn.call('blockchain.scripthash.get_balance', script_hash)
            result = reply['result']
            confirmed = result['confirmed'] / 1e8
            total += confirmed
            if confirmed:
                log.info('{}/{} => {} has {:11.8f} BTC', change, n, address,
                         confirmed)
                empty = 0
            else:
                empty += 1
                if empty >= 10:
                    break
    log.info('total balance: {} BTC', total)
Пример #2
0
def connection(hostspec, password=None, namespace=None):
    if not "://" in hostspec:
        hostspec = "socket://" + hostspec
    scheme, netloc, _, _, _ = _urlparse.urlsplit(hostspec)

    kwargs = {}
    if namespace != None:
        kwargs["namespace"] = namespace

    if scheme == "socket":
        # Parse URL
        if "@" in netloc:
            userinfo, hostport = netloc.split("@", 1)
        else:
            userinfo, hostport = "", netloc
        if ":" in userinfo:
            userinfo_user, userinfo_password = userinfo.split(":", 1)
        else:
            userinfo_user, userinfo_password = userinfo, None
        if ":" in hostport:
            host, port = hostport.split(":")
        else:
            host, port = hostport, default_port

        # If userinfo has been given, authenticate using it.
        # Allow forms
        # socket://password@host:port
        # socket://dontcare:password@host:port
        if password == None and userinfo:
            if userinfo_password:
                password = userinfo_password
            else:
                password = userinfo

        rv = client.Connection(host, int(port), password=password, **kwargs)
    elif scheme == "shell":
        p = subprocess.Popen(hostspec[len("shell://"):],
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        rv = client.Connection(p.stdout, p.stdin, **kwargs)
    else:
        raise ValueError('invalid URI "%s"' % (hostspec, ))
    rv.hostspec = hostspec
    return rv
Пример #3
0
    def test_ping_is_sent_in_the_background(self, ping):
        c = client.Connection()
        c._heartbeat_sec = 0.1
        try:
            c.connect(*self.server_addr)

            # Several calls expected when heartbeat is so fast.
            for _ in range(10):
                if ping.call_count >= 5:
                    return
                time.sleep(0.1)

            raise Exception(f"ping called only {ping.call_count} time(s)")

        finally:
            c.disconnect()
	def save(self, event = None) -> None:
		if self.pass_entry.get() != self.inven.password:
			messagebox.showinfo('Error', 'Password is incorrect.')
			return

		connection = None
		try:
			connection = client.Connection()
			connection.save_file(self.inven.to_dict())
			messagebox.showinfo('Alert', f'{self.inven.name} was saved sucessfully.')
		except:
			messagebox.showinfo('Connection Error', 'Unable to connect to server.\nEnsure that you are connected to a network.')
		finally:
			if connection is not None:
				connection.terminate()

		self.cancel()
Пример #5
0
    def test_ping_can_close_connection(self):
        c = client.Connection()
        c._heartbeat_sec = 0.1
        try:
            c.connect(*self.server_addr)

            self._server_process.kill()
            self._server_process.wait()

            time.sleep(0.3)

            self.assertIs(c.is_connected(), False)

            with self.assertRaises(Exception):
                c.ping()

        finally:
            c.disconnect()
Пример #6
0
    def load(self, event=None) -> None:
        """Tries to get the specified file from the server."""

        # ensure both fields are given
        if self.name_entry.get() == '':
            messagebox.showinfo('Error', 'Name cannot be left blank.')
        elif self.pass_entry.get() == '':
            messagebox.showinfo('Error', 'Password cannot be left blank.')
        else:

            # try to connect to server if not already
            try:

                if self.connection is None:
                    self.connection = client.Connection()

                # send a request for the file
                inven_dict = self.connection.request_file(
                    self.name_entry.get(), self.pass_entry.get())

                if inven_dict == utils.INVALID_FILE_REQUEST:
                    messagebox.showinfo(
                        'Error',
                        f'{self.name_entry.get()} is not available for download.'
                    )
                elif inven_dict == utils.INVALID_PASSWORD:
                    messagebox.showinfo('Error', 'Password is incorrect.')
                else:
                    # download sucessful, open up inventory
                    self.cancel()
                    invenscreen.InvenScreen(
                        self.window, inven_loader.dict_to_inven(inven_dict))

            except Exception as e:

                if self.connection is not None:
                    self.connection.terminate()
                messagebox.showinfo(
                    'Connection Error',
                    'Unable to connect to server.\nEnsure that you are connected to a network.'
                )

                raise e
Пример #7
0
    def __init__(self, self_addr, others_addrs):
        self.addrs = [self_addr] + others_addrs
        self.n_hosts = len(self.addrs)

        # host_id (fd) -> one-sided write connection to host
        self._hosts = defaultdict(client.Connection)
        self._server = server.Listener(*self_addr)

        # incoming fd -> host_id (fd)
        self._clients = defaultdict(int)
        self._poll = Poll()
        self._handlers = dict()

        for (ip, port) in self.addrs:
            host = client.Connection(ip, port)
            self._hosts[host.connect()] = host

        self.hosts_ids = self._hosts.keys()

        for cl in self._server.accept_clients(self.n_hosts):
            self.reg_for_poll(cl, self._rpc_handler, ev_id=EV_REMOTE)

        for host in self.hosts_ids:
            self.send_to(host, commands.ID, *self_addr)

        self.host_by_addr = {
            (conn.ip, conn.port): host_id for (host_id, conn) in self._hosts.items()
        }
        

        while len(self._clients) != self.n_hosts:
            fd = self._poll.wait_one()

            msg = RPC.read_one_msg(fd)
            cmd, addr = serialize.unserialize(msg)
            cmd = int(cmd)

            if cmd != commands.ID:
                raise RuntimeError("Initial message from host missed.")
                
            addr = tuple([addr[0], int(addr[1])])

            self._clients[fd] = self.host_by_addr[addr]
Пример #8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--testnet', action='store_true')
    parser.add_argument('address', nargs='+')
    args = parser.parse_args()

    if args.testnet:
        Network = FujicoinTestnet
        port = 60001
    else:
        Network = FujicoinMainnet
        port = 50001

    conn = client.Connection(('localhost', port))
    for addr in args.address:
        script = Network.ui.script_for_address(addr)
        script_hash = hashlib.sha256(script).digest()[::-1].hex()
        reply = conn.call('blockchain.scripthash.get_balance', script_hash)
        result = reply['result']
        print('{} has {} satoshis'.format(addr, result))
Пример #9
0
    settings = termios.tcgetattr(sys.stdin)

    # publish to simulator
    if (use_simulator == 1):
        pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=1)
    # publish to robot
    else:
        pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)

    rospy.init_node('turtlebot_teleop')

    receiver = receiver.Status(robot_ip, robot_port)

    # create movement register
    move = Movement(client.Connection(sumo_ip, sumo_port, receiver), speed,
                    turn, step_dur)

    # start thread to listen to incoming messages
    start_new_thread(receiver.start, (move, ))

    # establish connection with sumo
    msg = messages.getIntegrationRequestMsg(move.speed, move.turn, receiver.ip,
                                            receiver.port)

    # waits for a positive reply to the integration request
    while 1:
        try:
            reply = move.conn.sendRequest(msg)
            print("RECEIVED: %s" % (msg))
            info = json.loads(reply)
Пример #10
0
def connect(hostspec, password=None, namespace=None):
    """Returns Connection to pythonshare server at hostspec.

    Parameters:

      hostspec (string):
              Syntax:
              [socket://][PASSWORD@]HOST[:PORT][/NAMESPACE]
              shell://[SHELLCOMMAND]
              The default scheme is socket. Examples:
              hostname equals socket://hostname:8089
              host:port equals socket://host:port
              host/namespace equals socket://host:8089/namespace

      password (string, optional):
              use password to log in to the server. Overrides
              hostspec password.

      namespace (string, optional):
              send code to the namespace on server by default.
              Overrides hostspec namespace.
    """
    if not "://" in hostspec:
        hostspec = "socket://" + hostspec
    scheme, netloc, path, _, _ = _urlparse.urlsplit(hostspec)

    kwargs = {}
    if namespace != None:
        kwargs["namespace"] = namespace

    if scheme == "socket":
        # Parse URL
        if "@" in netloc:
            userinfo, hostport = netloc.split("@", 1)
        else:
            userinfo, hostport = "", netloc
        if ":" in userinfo:
            userinfo_user, userinfo_password = userinfo.split(":", 1)
        else:
            userinfo_user, userinfo_password = userinfo, None
        if ":" in hostport:
            host, port = hostport.split(":")
        else:
            host, port = hostport, default_port

        # If userinfo has been given, authenticate using it.
        # Allow forms
        # socket://password@host:port
        # socket://dontcare:password@host:port
        if password == None and userinfo:
            if userinfo_password:
                password = userinfo_password
            else:
                password = userinfo

        if not "namespace" in kwargs and path.replace("/", "", 1):
            kwargs["namespace"] = path.replace("/", "", 1)

        rv = client.Connection(host, int(port), password=password, **kwargs)
    elif scheme == "shell":
        p = subprocess.Popen(hostspec[len("shell://"):],
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        rv = client.Connection(p.stdout, p.stdin, **kwargs)
    else:
        raise ValueError('invalid URI "%s"' % (hostspec, ))
    rv.hostspec = hostspec
    return rv
Пример #11
0
def connection(server):
    conn = client.Connection('localhost:8080')
    yield conn
    conn.close()