Exemplo n.º 1
0
 def send_request(self, method, relative_url, data=None, *, timeout=None):
     network = Network.get_instance()
     if not network:
         raise ErrorConnectingServer('You are offline.')
     url = urljoin(self.base_url, relative_url)
     if self.debug:
         self.logger.debug(f'<-- {method} {url} {data}')
     headers = {}
     if self.user_agent:
         headers['user-agent'] = self.user_agent
     try:
         if method == 'get':
             response = Network.send_http_on_proxy(method, url,
                                                   params=data,
                                                   headers=headers,
                                                   on_finish=self.handle_response,
                                                   timeout=timeout)
         elif method == 'post':
             response = Network.send_http_on_proxy(method, url,
                                                   json=data,
                                                   headers=headers,
                                                   on_finish=self.handle_response,
                                                   timeout=timeout)
         else:
             assert False
     except TrustedCoinException:
         raise
     except Exception as e:
         raise ErrorConnectingServer(e)
     else:
         if self.debug:
             self.logger.debug(f'--> {response}')
         return response
Exemplo n.º 2
0
 async def do_get(self, url="/labels"):
     url = 'https://' + self.target_host + url
     network = Network.get_instance()
     proxy = network.proxy if network else None
     async with make_aiohttp_session(proxy) as session:
         async with session.get(url) as result:
             return await result.json()
Exemplo n.º 3
0
    def __init__(self, config: 'SimpleConfig', exctype, value, tb):
        BaseCrashReporter.__init__(self, exctype, value, tb)
        self.network = Network.get_instance()
        self.config = config

        QWidget.__init__(self)
        self.setWindowTitle('ElectrumSys - ' + _('An Error Occurred'))
        self.setMinimumSize(600, 300)

        Logger.__init__(self)

        main_box = QVBoxLayout()

        heading = QLabel('<h2>' + BaseCrashReporter.CRASH_TITLE + '</h2>')
        main_box.addWidget(heading)
        main_box.addWidget(QLabel(BaseCrashReporter.CRASH_MESSAGE))

        main_box.addWidget(QLabel(BaseCrashReporter.REQUEST_HELP_MESSAGE))

        collapse_info = QPushButton(_("Show report contents"))
        collapse_info.clicked.connect(
            lambda: self.msg_box(QMessageBox.NoIcon,
                                 self,
                                 _("Report contents"),
                                 self.get_report_string(),
                                 rich_text=True))

        main_box.addWidget(collapse_info)

        main_box.addWidget(QLabel(BaseCrashReporter.DESCRIBE_ERROR_MESSAGE))

        self.description_textfield = QTextEdit()
        self.description_textfield.setFixedHeight(50)
        self.description_textfield.setPlaceholderText(
            self.USER_COMMENT_PLACEHOLDER)
        main_box.addWidget(self.description_textfield)

        main_box.addWidget(QLabel(BaseCrashReporter.ASK_CONFIRM_SEND))

        buttons = QHBoxLayout()

        report_button = QPushButton(_('Send Bug Report'))
        report_button.clicked.connect(self.send_report)
        report_button.setIcon(read_QIcon("tab_send.png"))
        buttons.addWidget(report_button)

        never_button = QPushButton(_('Never'))
        never_button.clicked.connect(self.show_never)
        buttons.addWidget(never_button)

        close_button = QPushButton(_('Not Now'))
        close_button.clicked.connect(self.close)
        buttons.addWidget(close_button)

        main_box.addLayout(buttons)

        self.setLayout(main_box)
        self.show()
Exemplo n.º 4
0
 async def do_post(self, url="/labels", data=None):
     url = 'https://' + self.target_host + url
     network = Network.get_instance()
     proxy = network.proxy if network else None
     async with make_aiohttp_session(proxy) as session:
         async with session.post(url, json=data) as result:
             try:
                 return await result.json()
             except Exception as e:
                 raise Exception('Could not decode: ' +
                                 await result.text()) from e
Exemplo n.º 5
0
 def comserver_post_notification(self, payload):
     assert self.is_mobile_paired(), "unexpected mobile pairing error"
     url = 'https://digitalbitbox.com/smartverification/index.php'
     key_s = base64.b64decode(
         self.digitalbitbox_config[ENCRYPTION_PRIVKEY_KEY])
     args = 'c=data&s=0&dt=0&uuid=%s&pl=%s' % (
         self.digitalbitbox_config[CHANNEL_ID_KEY],
         EncodeAES_base64(
             key_s,
             json.dumps(payload).encode('ascii')).decode('ascii'),
     )
     try:
         text = Network.send_http_on_proxy(
             'post',
             url,
             body=args.encode('ascii'),
             headers={'content-type': 'application/x-www-form-urlencoded'})
         _logger.info(f'digitalbitbox reply from server {text}')
     except Exception as e:
         self.handler.show_error(
             repr(e))  # repr because str(Exception()) == ''
Exemplo n.º 6
0
#!/usr/bin/env python3
import asyncio

from electrumsys.network import filter_protocol, Network
from electrumsys.util import create_and_start_event_loop, log_exceptions
from electrumsys.blockchain import hash_raw_header
from electrumsys.simple_config import SimpleConfig

config = SimpleConfig()

loop, stopping_fut, loop_thread = create_and_start_event_loop()
network = Network(config)
network.start()


@log_exceptions
async def f():
    try:
        peers = await network.get_peers()
        peers = filter_protocol(peers)
        results = await network.send_multiple_requests(
            peers, 'blockchain.headers.subscribe', [])
        for server, header in sorted(results.items(),
                                     key=lambda x: x[1].get('height')):
            height = header.get('height')
            blockhash = hash_raw_header(header.get('hex'))
            print(server, height, blockhash)
    finally:
        stopping_fut.set_result(1)

Exemplo n.º 7
0
 def __init__(self):
     QThread.__init__(self)
     Logger.__init__(self)
     self.network = Network.get_instance()
Exemplo n.º 8
0
    def update(self, *, network: Network, servers: dict, use_tor: bool):
        self.clear()

        # connected servers
        connected_servers_item = QTreeWidgetItem([_("Connected nodes"), ''])
        connected_servers_item.setData(0, self.ITEMTYPE_ROLE,
                                       self.ItemType.TOPLEVEL)
        chains = network.get_blockchains()
        n_chains = len(chains)
        for chain_id, interfaces in chains.items():
            b = blockchain.blockchains.get(chain_id)
            if b is None: continue
            name = b.get_name()
            if n_chains > 1:
                x = QTreeWidgetItem(
                    [name + '@%d' % b.get_max_forkpoint(),
                     '%d' % b.height()])
                x.setData(0, self.ITEMTYPE_ROLE, self.ItemType.CHAIN)
                x.setData(0, self.CHAIN_ID_ROLE, b.get_id())
            else:
                x = connected_servers_item
            for i in interfaces:
                star = ' *' if i == network.interface else ''
                item = QTreeWidgetItem(
                    [f"{i.server.to_friendly_name()}" + star,
                     '%d' % i.tip])
                item.setData(0, self.ITEMTYPE_ROLE,
                             self.ItemType.CONNECTED_SERVER)
                item.setData(0, self.SERVER_ADDR_ROLE, i.server)
                item.setToolTip(0, str(i.server))
                x.addChild(item)
            if n_chains > 1:
                connected_servers_item.addChild(x)

        # disconnected servers
        disconnected_servers_item = QTreeWidgetItem(
            [_("Other known servers"), ""])
        disconnected_servers_item.setData(0, self.ITEMTYPE_ROLE,
                                          self.ItemType.TOPLEVEL)
        connected_hosts = set(
            [iface.host for ifaces in chains.values() for iface in ifaces])
        protocol = PREFERRED_NETWORK_PROTOCOL
        for _host, d in sorted(servers.items()):
            if _host in connected_hosts:
                continue
            if _host.endswith('.onion') and not use_tor:
                continue
            port = d.get(protocol)
            if port:
                server = ServerAddr(_host, port, protocol=protocol)
                item = QTreeWidgetItem([server.net_addr_str(), ""])
                item.setData(0, self.ITEMTYPE_ROLE,
                             self.ItemType.DISCONNECTED_SERVER)
                item.setData(0, self.SERVER_ADDR_ROLE, server)
                disconnected_servers_item.addChild(item)

        self.addTopLevelItem(connected_servers_item)
        self.addTopLevelItem(disconnected_servers_item)

        connected_servers_item.setExpanded(True)
        for i in range(connected_servers_item.childCount()):
            connected_servers_item.child(i).setExpanded(True)
        disconnected_servers_item.setExpanded(True)

        # headers
        h = self.header()
        h.setStretchLastSection(False)
        h.setSectionResizeMode(0, QHeaderView.Stretch)
        h.setSectionResizeMode(1, QHeaderView.ResizeToContents)

        super().update()
Exemplo n.º 9
0
 def recovery(self):
     network = Network.get_instance()
     coroutine = account_discovery(network, self.get_account_xpub)
     return network.run_from_another_thread(coroutine)
Exemplo n.º 10
0
#!/usr/bin/env python3

# A simple script that connects to a server and displays block headers

import time
import asyncio

from electrumsys.network import Network
from electrumsys.util import print_msg, json_encode, create_and_start_event_loop, log_exceptions
from electrumsys.simple_config import SimpleConfig

config = SimpleConfig()

# start network
loop, stopping_fut, loop_thread = create_and_start_event_loop()
network = Network(config)
network.start()

# wait until connected
while not network.is_connected():
    time.sleep(1)
    print_msg("waiting for network to get connected...")

header_queue = asyncio.Queue()


@log_exceptions
async def f():
    try:
        await network.interface.session.subscribe(
            'blockchain.headers.subscribe', [], header_queue)