diff --git a/.travis.yml b/.travis.yml index b4202e6dba9f1ef4eac64f06868f5143a5c842f3..4eaf165cafe3ad570db9716e9e3c38b07235e7b9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ sudo: false language: python python: # We don't actually use the Travis Python, but this keeps it organized. - - "3.4" + - "3.5" addons: apt: packages: diff --git a/appveyor.yml b/appveyor.yml index cc5b18d86b6bf8def98178e94919097d3f8ab82e..7f38948077e1342046d7f96a832d6d5665df6476 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -7,14 +7,14 @@ environment: matrix: - PYTHON: "C:\\Python34_64" - PYTHON_VERSION: "3.4" + PYTHON_VERSION: "3.5" PYTHON_ARCH: "64" CONDA_PY: "34" CONDA_NPY: "18" platform: x64 - PYTHON: "C:\\Python34_32" - PYTHON_VERSION: "3.4" + PYTHON_VERSION: "3.5" PYTHON_ARCH: "32" CONDA_PY: "34" CONDA_NPY: "18" diff --git a/requirements.txt b/requirements.txt index cd01f840b879c9e116ca7a2031242fb452397a10..cb79cb87732bddcba1798d8eb1096777a17b6cad 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ pretenders -ucoinpy +ucoinpy>=0.13 git+https://github.com/Insoleet/quamash.git@sockets_only \ No newline at end of file diff --git a/src/sakia/core/account.py b/src/sakia/core/account.py index f0b8f0bd224dd6b82b5a5b7b22d6a0a96301a217..c901dce087ab50fe910ffeebbc82bd8af78c0543 100644 --- a/src/sakia/core/account.py +++ b/src/sakia/core/account.py @@ -240,15 +240,14 @@ class Account(QObject): "Wallet", self._identities_registry) self.wallets.append(wallet) - @asyncio.coroutine - def identity(self, community): + async def identity(self, community): """ Get the account identity in the specified community :param sakia.core.community.Community community: The community where to look after the identity :return: The account identity in the community :rtype: sakia.core.registry.Identity """ - identity = yield from self._identities_registry.future_find(self.pubkey, community) + identity = await self._identities_registry.future_find(self.pubkey, community) if identity.local_state == LocalState.NOT_FOUND: identity.uid = self.name return identity @@ -280,8 +279,7 @@ class Account(QObject): """ return self.wallets[0].dividends(community) - @asyncio.coroutine - def future_amount(self, community): + async def future_amount(self, community): """ Get amount of money owned in a community by all the wallets owned by this account @@ -291,12 +289,11 @@ class Account(QObject): """ value = 0 for w in self.wallets: - val = yield from w.future_value(community) + val = await w.future_value(community) value += val return value - @asyncio.coroutine - def amount(self, community): + async def amount(self, community): """ Get amount of money owned in a community by all the wallets owned by this account @@ -306,12 +303,11 @@ class Account(QObject): """ value = 0 for w in self.wallets: - val = yield from w.value(community) + val = await w.value(community) value += val return value - @asyncio.coroutine - def check_registered(self, community): + async def check_registered(self, community): """ Checks for the pubkey and the uid of an account in a community :param sakia.core.Community community: The community we check for registration @@ -352,8 +348,7 @@ class Account(QObject): else: return False, self.pubkey, None - @asyncio.coroutine - def execute_requests(parsers, search): + async def execute_requests(parsers, search): tries = 0 request = bma.wot.CertifiersOf nonlocal registered @@ -361,7 +356,7 @@ class Account(QObject): #Multiplying the tries without any reason... while tries < 3 and not registered[0] and not registered[2]: try: - data = yield from community.bma_access.simple_request(request, + data = await community.bma_access.simple_request(request, req_args={'search': search}) if data: registered = parsers[request](data) @@ -387,7 +382,7 @@ class Account(QObject): bma.wot.CertifiersOf: _parse_uid_certifiers, bma.wot.Lookup: _parse_uid_lookup } - yield from execute_requests(uid_parsers, self.pubkey) + await execute_requests(uid_parsers, self.pubkey) # If the uid wasn't found when looking for the pubkey # We look for the uid and check for the pubkey @@ -396,12 +391,11 @@ class Account(QObject): bma.wot.CertifiersOf: _parse_pubkey_certifiers, bma.wot.Lookup: _parse_pubkey_lookup } - yield from execute_requests(pubkey_parsers, self.name) + await execute_requests(pubkey_parsers, self.name) return registered - @asyncio.coroutine - def send_selfcert(self, password, community): + async def send_selfcert(self, password, community): """ Send our self certification to a target community @@ -418,21 +412,20 @@ class Account(QObject): selfcert.sign([key]) logging.debug("Key publish : {0}".format(selfcert.signed_raw())) - responses = yield from community.bma_access.broadcast(bma.wot.Add, {}, {'pubkey': self.pubkey, + responses = await community.bma_access.broadcast(bma.wot.Add, {}, {'pubkey': self.pubkey, 'self_': selfcert.signed_raw(), 'other': {}}) result = (False, "") for r in responses: if r.status == 200: - result = (True, (yield from r.json())) + result = (True, (await r.json())) elif not result[0]: - result = (False, (yield from r.text())) + result = (False, (await r.text())) else: - yield from r.release() + await r.release() return result - @asyncio.coroutine - def send_membership(self, password, community, mstype): + async def send_membership(self, password, community, mstype): """ Send a membership document to a target community. Signal "document_broadcasted" is emitted at the end. @@ -443,9 +436,9 @@ class Account(QObject): """ logging.debug("Send membership") - blockid = yield from community.blockid() - self_identity = yield from self._identities_registry.future_find(self.pubkey, community) - selfcert = yield from self_identity.selfcert(community) + blockid = await community.blockid() + self_identity = await self._identities_registry.future_find(self.pubkey, community) + selfcert = await self_identity.selfcert(community) membership = Membership(PROTOCOL_VERSION, community.currency, selfcert.pubkey, blockid.number, @@ -454,20 +447,19 @@ class Account(QObject): key = SigningKey(self.salt, password) membership.sign([key]) logging.debug("Membership : {0}".format(membership.signed_raw())) - responses = yield from community.bma_access.broadcast(bma.blockchain.Membership, {}, + responses = await community.bma_access.broadcast(bma.blockchain.Membership, {}, {'membership': membership.signed_raw()}) result = (False, "") for r in responses: if r.status == 200: - result = (True, (yield from r.json())) + result = (True, (await r.json())) elif not result[0]: - result = (False, (yield from r.text())) + result = (False, (await r.text())) else: - yield from r.release() + await r.release() return result - @asyncio.coroutine - def certify(self, password, community, pubkey): + async def certify(self, password, community, pubkey): """ Certify an other identity @@ -476,9 +468,9 @@ class Account(QObject): :param str pubkey: The certified identity pubkey """ logging.debug("Certdata") - blockid = yield from community.blockid() - identity = yield from self._identities_registry.future_find(pubkey, community) - selfcert = yield from identity.selfcert(community) + blockid = await community.blockid() + identity = await self._identities_registry.future_find(pubkey, community) + selfcert = await identity.selfcert(community) if selfcert: certification = Certification(PROTOCOL_VERSION, community.currency, self.pubkey, pubkey, @@ -493,31 +485,30 @@ class Account(QObject): 'self_': selfcert.signed_raw(), 'other': "{0}\n".format(certification.inline())} logging.debug("Posted data : {0}".format(data)) - responses = yield from community.bma_access.broadcast(bma.wot.Add, {}, data) + responses = await community.bma_access.broadcast(bma.wot.Add, {}, data) result = (False, "") for r in responses: if r.status == 200: - result = (True, (yield from r.json())) + result = (True, (await r.json())) elif not result[0]: - result = (False, (yield from r.text())) + result = (False, (await r.text())) else: - yield from r.release() + await r.release() return result else: return (False, self.tr("Could not find user self certification.")) - @asyncio.coroutine - def revoke(self, password, community): + async def revoke(self, password, community): """ Revoke self-identity on server, not in blockchain :param str password: The account SigningKey password :param sakia.core.community.Community community: The community target of the revocation """ - revoked = yield from self._identities_registry.future_find(self.pubkey, community) + revoked = await self._identities_registry.future_find(self.pubkey, community) revocation = Revocation(PROTOCOL_VERSION, community.currency, None) - selfcert = yield from revoked.selfcert(community) + selfcert = await revoked.selfcert(community) key = SigningKey(self.salt, password) revocation.sign(selfcert, [key]) @@ -531,15 +522,15 @@ class Account(QObject): 'sig': revocation.signatures[0] } logging.debug("Posted data : {0}".format(data)) - responses = yield from community.bma_access.broadcast(bma.wot.Revoke, {}, data) + responses = await community.bma_access.broadcast(bma.wot.Revoke, {}, data) result = (False, "") for r in responses: if r.status == 200: - result = (True, (yield from r.json())) + result = (True, (await r.json())) elif not result[0]: - result = (False, (yield from r.text())) + result = (False, (await r.text())) else: - yield from r.release() + await r.release() return result def start_coroutines(self): diff --git a/src/sakia/core/app.py b/src/sakia/core/app.py index 00bd48f0f89fb538dfba537d45e5c38ee5704bc8..22722c1f65dccec79a84ecf306a01cff7b5aa05a 100644 --- a/src/sakia/core/app.py +++ b/src/sakia/core/app.py @@ -501,8 +501,7 @@ class Application(QObject): self.save_registries() @asyncify - @asyncio.coroutine - def get_last_version(self): + async def get_last_version(self): if self.preferences['enable_proxy'] is True: connector = ProxyConnector("http://{0}:{1}".format( self.preferences['proxy_address'], @@ -510,10 +509,10 @@ class Application(QObject): else: connector = None try: - response = yield from asyncio.wait_for(aiohttp.get("https://api.github.com/repos/ucoin-io/sakia/releases", + response = await asyncio.wait_for(aiohttp.get("https://api.github.com/repos/ucoin-io/sakia/releases", connector=connector), timeout=15) if response.status == 200: - releases = yield from response.json() + releases = await response.json() for r in releases: if not latest: latest = r diff --git a/src/sakia/core/community.py b/src/sakia/core/community.py index 791c80d7f108522267338b74f8da5e571460c874..c0832ca379c4a0651922df2efba3120280c96501 100644 --- a/src/sakia/core/community.py +++ b/src/sakia/core/community.py @@ -116,21 +116,19 @@ class Community(QObject): u = ord('\u24B6') + ord(letter) - ord('A') return chr(u) - @asyncio.coroutine - def dividend(self): + async def dividend(self): """ Get the last generated community universal dividend. :return: The last UD or 1 if no UD was generated. """ - block = yield from self.get_ud_block() + block = await self.get_ud_block() if block: return block['dividend'] else: return 1 - @asyncio.coroutine - def computed_dividend(self): + async def computed_dividend(self): """ Get the computed community universal dividend. @@ -140,12 +138,12 @@ class Community(QObject): :return: The computed UD or 1 if no UD was generated. """ - block = yield from self.get_ud_block() + block = await self.get_ud_block() if block: - parameters = yield from self.parameters() + parameters = await self.parameters() return math.ceil( max( - (yield from self.dividend()), + (await self.dividend()), float(0) if block['membersCount'] == 0 else parameters['c'] * block['monetaryMass'] / block['membersCount'] ) @@ -154,8 +152,7 @@ class Community(QObject): else: return 1 - @asyncio.coroutine - def get_ud_block(self, x=0): + async def get_ud_block(self, x=0): """ Get a block with universal dividend @@ -163,14 +160,14 @@ class Community(QObject): :return: The last block with universal dividend. """ try: - udblocks = yield from self.bma_access.future_request(bma.blockchain.UD) + udblocks = await self.bma_access.future_request(bma.blockchain.UD) blocks = udblocks['result']['blocks'] if len(blocks) > 0: index = len(blocks)-(1+x) if index < 0: index = 0 block_number = blocks[index] - block = yield from self.bma_access.future_request(bma.blockchain.Block, + block = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) return block else: @@ -183,8 +180,7 @@ class Community(QObject): logging.debug(str(e)) return None - @asyncio.coroutine - def monetary_mass(self): + async def monetary_mass(self): """ Get the community monetary mass @@ -193,14 +189,13 @@ class Community(QObject): # Get cached block by block number block_number = self.network.current_blockid.number if block_number: - block = yield from self.bma_access.future_request(bma.blockchain.Block, + block = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) return block['monetaryMass'] else: return 0 - @asyncio.coroutine - def nb_members(self): + async def nb_members(self): """ Get the community members number @@ -209,7 +204,7 @@ class Community(QObject): try: # Get cached block by block number block_number = self.network.current_blockid.number - block = yield from self.bma_access.future_request(bma.blockchain.Block, + block = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) return block['membersCount'] except ValueError as e: @@ -219,8 +214,7 @@ class Community(QObject): logging.debug(str(e)) return 0 - @asyncio.coroutine - def time(self): + async def time(self): """ Get the blockchain time :return: The community blockchain time @@ -229,7 +223,7 @@ class Community(QObject): try: # Get cached block by block number block_number = self.network.current_blockid.number - block = yield from self.bma_access.future_request(bma.blockchain.Block, + block = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) return block['medianTime'] except ValueError as e: @@ -259,20 +253,18 @@ class Community(QObject): """ return self._bma_access - @asyncio.coroutine - def parameters(self): + async def parameters(self): """ Return community parameters in bma format """ - return self.bma_access.future_request(bma.blockchain.Parameters) + return await self.bma_access.future_request(bma.blockchain.Parameters) - @asyncio.coroutine - def certification_expired(self, certtime): + async def certification_expired(self, certtime): """ Return True if the certificaton time is too old """ - parameters = yield from self.parameters() - blockchain_time = yield from self.time() + parameters = await self.parameters() + blockchain_time = await self.time() return blockchain_time - certtime > parameters['sigValidity'] def add_node(self, node): @@ -291,8 +283,7 @@ class Community(QObject): """ self._network.remove_root_node(index) - @asyncio.coroutine - def get_block(self, number=None): + async def get_block(self, number=None): """ Get a block @@ -300,16 +291,15 @@ class Community(QObject): """ if number is None: block_number = self.network.current_blockid.number - data = yield from self.bma_access.future_request(bma.blockchain.Block, + data = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) else: logging.debug("Requesting block {0}".format(number)) - data = yield from self.bma_access.future_request(bma.blockchain.Block, + data = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': number}) return data - @asyncio.coroutine - def blockid(self): + async def blockid(self): """ Get the block id. @@ -317,7 +307,7 @@ class Community(QObject): """ try: block_number = self.network.current_blockid.number - block = yield from self.bma_access.future_request(bma.blockchain.Block, + block = await self.bma_access.future_request(bma.blockchain.Block, req_args={'number': block_number}) signed_raw = "{0}{1}\n".format(block['raw'], block['signature']) except ValueError as e: @@ -326,14 +316,13 @@ class Community(QObject): return Block.from_signed_raw(signed_raw).blockid - @asyncio.coroutine - def members_pubkeys(self): + async def members_pubkeys(self): """ Listing members pubkeys of a community :return: All members pubkeys. """ - memberships = yield from self.bma_access.future_request(bma.wot.Members) + memberships = await self.bma_access.future_request(bma.wot.Members) return [m['pubkey'] for m in memberships["results"]] def start_coroutines(self): diff --git a/src/sakia/core/graph.py b/src/sakia/core/graph.py index a2314c4c6d081ae3c6aa574350757928c28c280e..04ce7ebffddd6a852f2f632b0878d98c46ca6b9b 100644 --- a/src/sakia/core/graph.py +++ b/src/sakia/core/graph.py @@ -24,9 +24,8 @@ class Graph(object): # graph empty if None parameter self._graph = graph or (dict() and (graph is None)) - @asyncio.coroutine - def refresh_signature_validity(self): - parameters = yield from self.community.parameters() + async def refresh_signature_validity(self): + parameters = await self.community.parameters() self.signature_validity = parameters['sigValidity'] # arc considered strong during 75% of signature validity time self.ARC_STATUS_STRONG_time = int(self.signature_validity * 0.75) @@ -46,8 +45,7 @@ class Graph(object): """ return self._graph - @asyncio.coroutine - def get_shortest_path_between_members(self, from_identity, to_identity): + async def get_shortest_path_between_members(self, from_identity, to_identity): """ Return path list of nodes from from_identity to to_identity :param identity from_identity: @@ -57,16 +55,16 @@ class Graph(object): path = list() # if from_identity has no certifications, we can not make a path - certifier_list = yield from from_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) - certified_list = yield from from_identity.unique_valid_certified_by(self.app.identities_registry, self.community) + certifier_list = await from_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) + certified_list = await from_identity.unique_valid_certified_by(self.app.identities_registry, self.community) print (certifier_list, certified_list) if not certifier_list and not certified_list: logging.debug('from_identity has no certifications : can not calculate wot path') return path # if to_identity has no certifications, we can not make a path - certifier_list = yield from to_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) - certified_list = yield from to_identity.unique_valid_certified_by(self.app.identities_registry, self.community) + certifier_list = await to_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) + certified_list = await to_identity.unique_valid_certified_by(self.app.identities_registry, self.community) if not certifier_list and not certified_list: logging.debug('to_identity has no certifications : can not calculate wot path') return path @@ -74,20 +72,20 @@ class Graph(object): logging.debug("path between %s to %s..." % (from_identity.uid, to_identity.uid)) if from_identity.pubkey not in self._graph.keys(): self.add_identity(from_identity) - certifier_list = yield from from_identity.unique_valid_certifiers_of(self.app.identities_registry, + certifier_list = await from_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) - yield from self.add_certifier_list(certifier_list, from_identity, to_identity) - certified_list = yield from from_identity.unique_valid_certified_by(self.app.identities_registry, + await self.add_certifier_list(certifier_list, from_identity, to_identity) + certified_list = await from_identity.unique_valid_certified_by(self.app.identities_registry, self.community) - yield from self.add_certified_list(certified_list, from_identity, to_identity) + await self.add_certified_list(certified_list, from_identity, to_identity) if to_identity.pubkey not in self._graph.keys(): # recursively feed graph searching for account node... - yield from self.explore_to_find_member(to_identity, + await self.explore_to_find_member(to_identity, self._graph[from_identity.pubkey]['connected'], list()) if len(self._graph[from_identity.pubkey]['connected']) > 0 and to_identity.pubkey in self._graph: # calculate path of nodes between identity and to_identity - path = yield from self.find_shortest_path(self._graph[from_identity.pubkey], + path = await self.find_shortest_path(self._graph[from_identity.pubkey], self._graph[to_identity.pubkey]) if path: @@ -97,8 +95,7 @@ class Graph(object): return path - @asyncio.coroutine - def explore_to_find_member(self, identity, connected=None, done=None): + async def explore_to_find_member(self, identity, connected=None, done=None): """ Scan graph recursively to find identity :param identity identity: identity instance to find @@ -119,21 +116,21 @@ class Graph(object): if node['id'] in tuple(done): continue identity_selected = identity.from_handled_data(node['text'], node['id'], None, BlockchainState.VALIDATED) - certifier_list = yield from identity_selected.unique_valid_certifiers_of(self.app.identities_registry, + certifier_list = await identity_selected.unique_valid_certifiers_of(self.app.identities_registry, self.community) - yield from self.add_certifier_list(certifier_list, identity_selected, identity) + await self.add_certifier_list(certifier_list, identity_selected, identity) if identity.pubkey in tuple(self._graph.keys()): return True - certified_list = yield from identity_selected.unique_valid_certified_by(self.app.identities_registry, + certified_list = await identity_selected.unique_valid_certified_by(self.app.identities_registry, self.community) - yield from self.add_certified_list(certified_list, identity_selected, identity) + await self.add_certified_list(certified_list, identity_selected, identity) if identity.pubkey in tuple(self._graph.keys()): return True if node['id'] not in tuple(done): done.append(node['id']) if len(done) >= len(self._graph): return False - found = yield from self.explore_to_find_member(identity, + found = await self.explore_to_find_member(identity, self._graph[identity_selected.pubkey]['connected'], done) if found: @@ -141,8 +138,7 @@ class Graph(object): return False - @asyncio.coroutine - def find_shortest_path(self, start, end, path=None): + async def find_shortest_path(self, start, end, path=None): """ Find recursively the shortest path between two nodes :param dict start: Start node @@ -160,14 +156,13 @@ class Graph(object): for pubkey in tuple(self._graph[start['id']]['connected']): node = self._graph[pubkey] if node not in path: - newpath = yield from self.find_shortest_path(node, end, path) + newpath = await self.find_shortest_path(node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest - @asyncio.coroutine - def add_certifier_list(self, certifier_list, identity, identity_account): + async def add_certifier_list(self, certifier_list, identity, identity_account): """ Add list of certifiers to graph :param list certifier_list: List of certifiers from api @@ -177,7 +172,7 @@ class Graph(object): """ if self.community: try: - yield from self.refresh_signature_validity() + await self.refresh_signature_validity() # add certifiers of uid for certifier in tuple(certifier_list): # add only valid certification... @@ -186,7 +181,7 @@ class Graph(object): # new node if certifier['identity'].pubkey not in self._graph.keys(): node_status = 0 - is_member = yield from certifier['identity'].is_member(self.community) + is_member = await certifier['identity'].is_member(self.community) if certifier['identity'].pubkey == identity_account.pubkey: node_status += NODE_STATUS_HIGHLIGHTED if is_member is False: @@ -226,7 +221,7 @@ class Graph(object): current_confirmations = current_block_number - certifier['block_number'] + 1 else: current_confirmations = 0 - members_pubkeys = yield from self.community.members_pubkeys() + members_pubkeys = await self.community.members_pubkeys() max_confirmation = self.community.network.fork_window(members_pubkeys) + 1 # Current confirmation can be negative if self.community.network.current_blockid.number @@ -250,8 +245,7 @@ class Graph(object): except NoPeerAvailable as e: logging.debug(str(e)) - @asyncio.coroutine - def add_certified_list(self, certified_list, identity, identity_account): + async def add_certified_list(self, certified_list, identity, identity_account): """ Add list of certified from api to graph :param list certified_list: List of certified from api @@ -262,7 +256,7 @@ class Graph(object): if self.community: try: - yield from self.refresh_signature_validity() + await self.refresh_signature_validity() # add certified by uid for certified in tuple(certified_list): # add only valid certification... @@ -270,7 +264,7 @@ class Graph(object): continue if certified['identity'].pubkey not in self._graph.keys(): node_status = 0 - is_member = yield from certified['identity'].is_member(self.community) + is_member = await certified['identity'].is_member(self.community) if certified['identity'].pubkey == identity_account.pubkey: node_status += NODE_STATUS_HIGHLIGHTED if is_member is False: @@ -304,7 +298,7 @@ class Graph(object): current_confirmations = current_block_number - certified['block_number'] + 1 else: current_confirmations = 0 - members_pubkeys = yield from self.community.members_pubkeys() + members_pubkeys = await self.community.members_pubkeys() max_confirmations = self.community.network.fork_window(members_pubkeys) + 1 if max_confirmations > current_confirmations >= 0: diff --git a/src/sakia/core/money/quant_zerosum.py b/src/sakia/core/money/quant_zerosum.py index 9bb7e21124a238988bfdbdf17189baf51462231b..47daa48b154662170fb5ab86434b64a4479b6cf0 100644 --- a/src/sakia/core/money/quant_zerosum.py +++ b/src/sakia/core/money/quant_zerosum.py @@ -24,8 +24,7 @@ class QuantitativeZSum: def diff_units(cls, currency): return QuantitativeZSum.units(currency) - @asyncio.coroutine - def value(self): + async def value(self): """ Return quantitative value of amount minus the average value @@ -33,22 +32,20 @@ class QuantitativeZSum: :param sakia.core.community.Community community: Community instance :return: int """ - ud_block = yield from self.community.get_ud_block() + ud_block = await self.community.get_ud_block() if ud_block and ud_block['membersCount'] > 0: - monetary_mass = yield from self.community.monetary_mass() + monetary_mass = await self.community.monetary_mass() average = monetary_mass / ud_block['membersCount'] else: average = 0 return self.amount - average - @asyncio.coroutine - def differential(self): - value = yield from Quantitative(self.amount, self.community, self.app).value() + async def differential(self): + value = await Quantitative(self.amount, self.community, self.app).value() return value - @asyncio.coroutine - def localized(self, units=False, international_system=False): - value = yield from self.value() + async def localized(self, units=False, international_system=False): + value = await self.value() localized_value = QLocale().toString(float(value), 'f', 0) @@ -60,7 +57,6 @@ class QuantitativeZSum: else: return localized_value - @asyncio.coroutine - def diff_localized(self, units=False, international_system=False): - localized = yield from Quantitative(self.amount, self.community, self.app).localized(units, international_system) + async def diff_localized(self, units=False, international_system=False): + localized = await Quantitative(self.amount, self.community, self.app).localized(units, international_system) return localized \ No newline at end of file diff --git a/src/sakia/core/money/quantitative.py b/src/sakia/core/money/quantitative.py index e0072fbfb512c4efa42462a455a06157fd4d9018..14d0cc9b7e5e0c910ce06d3fb97e688c24c53bf2 100644 --- a/src/sakia/core/money/quantitative.py +++ b/src/sakia/core/money/quantitative.py @@ -23,8 +23,7 @@ class Quantitative(): def diff_units(cls, currency): return Quantitative.units(currency) - @asyncio.coroutine - def value(self): + async def value(self): """ Return quantitative value of amount @@ -34,9 +33,8 @@ class Quantitative(): """ return int(self.amount) - @asyncio.coroutine - def differential(self): - value = yield from self.value() + async def differential(self): + value = await self.value() return value def _to_si(self, value): @@ -58,9 +56,8 @@ class Quantitative(): return localized_value, prefix - @asyncio.coroutine - def localized(self, units=False, international_system=False): - value = yield from self.value() + async def localized(self, units=False, international_system=False): + value = await self.value() prefix = "" if international_system: localized_value, prefix = self._to_si(value) @@ -76,9 +73,8 @@ class Quantitative(): else: return localized_value - @asyncio.coroutine - def diff_localized(self, units=False, international_system=False): - value = yield from self.differential() + async def diff_localized(self, units=False, international_system=False): + value = await self.differential() prefix = "" if international_system: localized_value, prefix = self._to_si(value) diff --git a/src/sakia/core/money/relative.py b/src/sakia/core/money/relative.py index 30d83ff4de45c20aa3a0bba11bbdefdd13127bb7..c72588c9d3db999b10b530114b22e43ef7209cbc 100644 --- a/src/sakia/core/money/relative.py +++ b/src/sakia/core/money/relative.py @@ -23,23 +23,21 @@ class Relative(): def diff_units(self, currency): return self.units(currency) - @asyncio.coroutine - def value(self): + async def value(self): """ Return relative value of amount :param int amount: Value :param sakia.core.community.Community community: Community instance :return: float """ - dividend = yield from self.community.dividend() + dividend = await self.community.dividend() if dividend > 0: return self.amount / float(dividend) else: return self.amount - @asyncio.coroutine - def differential(self): - value = yield from self.value() + async def differential(self): + value = await self.value() return value def _to_si(self, value): @@ -65,9 +63,8 @@ class Relative(): return localized_value, prefix - @asyncio.coroutine - def localized(self, units=False, international_system=False): - value = yield from self.value() + async def localized(self, units=False, international_system=False): + value = await self.value() prefix = "" if international_system: localized_value, prefix = self._to_si(value) @@ -82,9 +79,8 @@ class Relative(): else: return localized_value - @asyncio.coroutine - def diff_localized(self, units=False, international_system=False): - value = yield from self.differential() + async def diff_localized(self, units=False, international_system=False): + value = await self.differential() prefix = "" if international_system and value != 0: localized_value, prefix = self._to_si(value) diff --git a/src/sakia/core/money/relative_zerosum.py b/src/sakia/core/money/relative_zerosum.py index f32b5274eb0b1c25c36cb46a15166615da4b9b4d..df26685bc3e7834ff9e6504cb1ca1bf95b744d6e 100644 --- a/src/sakia/core/money/relative_zerosum.py +++ b/src/sakia/core/money/relative_zerosum.py @@ -24,8 +24,7 @@ class RelativeZSum: def diff_units(cls, currency): return RelativeZSum.units(currency) - @asyncio.coroutine - def value(self): + async def value(self): """ Return relative value of amount minus the average value @@ -33,10 +32,10 @@ class RelativeZSum: :param sakia.core.community.Community community: Community instance :return: float """ - ud_block = yield from self.community.get_ud_block() + ud_block = await self.community.get_ud_block() if ud_block and ud_block['membersCount'] > 0: - monetary_mass = yield from self.community.monetary_mass() - dividend = yield from self.community.dividend() + monetary_mass = await self.community.monetary_mass() + dividend = await self.community.dividend() median = monetary_mass / ud_block['membersCount'] relative_value = self.amount / float(dividend) relative_median = median / dividend @@ -45,13 +44,11 @@ class RelativeZSum: relative_median = 0 return relative_value - relative_median - @asyncio.coroutine - def differential(self): + async def differential(self): return Relative(self.amount, self.community, self.app).value() - @asyncio.coroutine - def localized(self, units=False, international_system=False): - value = yield from self.value() + async def localized(self, units=False, international_system=False): + value = await self.value() localized_value = QLocale().toString(float(value), 'f', self.app.preferences['digits_after_comma']) @@ -62,8 +59,8 @@ class RelativeZSum: else: return localized_value - def diff_localized(self, units=False, international_system=False): - value = yield from self.differential() + async def diff_localized(self, units=False, international_system=False): + value = await self.differential() localized_value = QLocale().toString(float(value), 'f', self.app.preferences['digits_after_comma']) diff --git a/src/sakia/core/net/api/bma/access.py b/src/sakia/core/net/api/bma/access.py index e0d4440b44b38b0a72c9e2a7ae595eb2b35ee2b8..a0445b1a92ab3f45eb4bf8c96a5f4408ba2813d3 100644 --- a/src/sakia/core/net/api/bma/access.py +++ b/src/sakia/core/net/api/bma/access.py @@ -214,8 +214,7 @@ class BmaAccess(QObject): else: return nodes - @asyncio.coroutine - def future_request(self, request, req_args={}, get_args={}): + async def future_request(self, request, req_args={}, get_args={}): """ Start a request to the network and returns a future. @@ -237,7 +236,7 @@ class BmaAccess(QObject): conn_handler = node.endpoint.conn_handler() req = request(conn_handler, **req_args) try: - json_data = yield from req.get(**get_args) + json_data = await req.get(**get_args) self._update_cache(request, req_args, get_args, json_data) return json_data except ValueError as e: @@ -253,8 +252,7 @@ class BmaAccess(QObject): raise NoPeerAvailable("", len(nodes)) return json_data - @asyncio.coroutine - def simple_request(self, request, req_args={}, get_args={}): + async def simple_request(self, request, req_args={}, get_args={}): """ Start a request to the network but don't cache its result. @@ -270,7 +268,7 @@ class BmaAccess(QObject): tries = 0 while tries < 3: try: - json_data = yield from req.get(**get_args) + json_data = await req.get(**get_args) return json_data except ValueError as e: if '404' in str(e) or '400' in str(e): @@ -284,8 +282,7 @@ class BmaAccess(QObject): else: raise NoPeerAvailable("", len(nodes)) - @asyncio.coroutine - def broadcast(self, request, req_args={}, post_args={}): + async def broadcast(self, request, req_args={}, post_args={}): """ Broadcast data to a network. Sends the data to all knew nodes. @@ -307,7 +304,7 @@ class BmaAccess(QObject): conn_handler = node.endpoint.conn_handler() req = request(conn_handler, **req_args) try: - reply = yield from req.post(**post_args) + reply = await req.post(**post_args) replies.append(reply) except ValueError as e: if '404' in str(e) or '400' in str(e): diff --git a/src/sakia/core/net/network.py b/src/sakia/core/net/network.py index f91f21ae5bddb7945df97485ee41333dff152d69..7f7f8ebaa4d83fef1e95cbe9ce4da44aaf9e757a 100644 --- a/src/sakia/core/net/network.py +++ b/src/sakia/core/net/network.py @@ -124,7 +124,7 @@ class Network(QObject): Start network nodes crawling :return: """ - asyncio.async(self.discover_network()) + asyncio.ensure_future(self.discover_network()) def stop_coroutines(self): """ @@ -303,8 +303,7 @@ class Network(QObject): for node in self._nodes: node.refresh(manual=True) - @asyncio.coroutine - def discover_network(self): + async def discover_network(self): """ Start crawling which never stops. To stop this crawling, call "stop_crawling" method. @@ -314,7 +313,7 @@ class Network(QObject): for node in self.nodes: if self.continue_crawling(): node.refresh() - yield from asyncio.sleep(15) + await asyncio.sleep(15) logging.debug("End of network discovery") @pyqtSlot(Peer, str) diff --git a/src/sakia/core/net/node.py b/src/sakia/core/net/node.py index 64c4aade5ac9bb86e3448a726ac5fd9751086f17..cb312212541a1e6fe44214c55572be5f28c66d2d 100644 --- a/src/sakia/core/net/node.py +++ b/src/sakia/core/net/node.py @@ -62,8 +62,7 @@ class Node(QObject): self._refresh_counter = 0 @classmethod - @asyncio.coroutine - def from_address(cls, currency, address, port): + async def from_address(cls, currency, address, port): """ Factory method to get a node from a given address @@ -74,7 +73,7 @@ class Node(QObject): :return: A new node :rtype: sakia.core.net.Node """ - peer_data = yield from bma.network.Peering(ConnectionHandler(address, port)).get() + peer_data = await bma.network.Peering(ConnectionHandler(address, port)).get() peer = Peer.from_signed_raw("{0}{1}\n".format(peer_data['raw'], peer_data['signature'])) @@ -294,8 +293,7 @@ class Node(QObject): self._refresh_counter += 1 @asyncify - @asyncio.coroutine - def refresh_block(self): + async def refresh_block(self): """ Refresh the blocks of this node """ @@ -303,14 +301,14 @@ class Node(QObject): logging.debug("Requesting {0}".format(conn_handler)) try: - block_data = yield from bma.blockchain.Current(conn_handler).get() + block_data = await bma.blockchain.Current(conn_handler).get() block_hash = block_data['hash'] self.state = Node.ONLINE if not self.block or block_hash != self.block['hash']: try: if self.block: - self.main_chain_previous_block = yield from bma.blockchain.Block(conn_handler, + self.main_chain_previous_block = await bma.blockchain.Block(conn_handler, self.block['number']).get() except ValueError as e: if '404' in str(e): @@ -348,15 +346,14 @@ class Node(QObject): self.state = Node.CORRUPTED @asyncify - @asyncio.coroutine - def refresh_informations(self): + async def refresh_informations(self): """ Refresh basic information (pubkey and currency) """ conn_handler = self.endpoint.conn_handler() try: - peering_data = yield from bma.network.Peering(conn_handler).get() + peering_data = await bma.network.Peering(conn_handler).get() node_pubkey = peering_data["pubkey"] node_currency = peering_data["currency"] self.state = Node.ONLINE @@ -382,15 +379,14 @@ class Node(QObject): self.state = Node.CORRUPTED @asyncify - @asyncio.coroutine - def refresh_summary(self): + async def refresh_summary(self): """ Refresh the summary of this node """ conn_handler = self.endpoint.conn_handler() try: - summary_data = yield from bma.node.Summary(conn_handler).get() + summary_data = await bma.node.Summary(conn_handler).get() self.software = summary_data["ucoin"]["software"] self.version = summary_data["ucoin"]["version"] self.state = Node.ONLINE @@ -410,14 +406,13 @@ class Node(QObject): self.state = Node.CORRUPTED @asyncify - @asyncio.coroutine - def refresh_uid(self): + async def refresh_uid(self): """ Refresh the node UID """ conn_handler = self.endpoint.conn_handler() try: - data = yield from bma.wot.Lookup(conn_handler, self.pubkey).get() + data = await bma.wot.Lookup(conn_handler, self.pubkey).get() self.state = Node.ONLINE timestamp = 0 uid = "" @@ -446,22 +441,21 @@ class Node(QObject): self.state = Node.CORRUPTED @asyncify - @asyncio.coroutine - def refresh_peers(self): + async def refresh_peers(self): """ Refresh the list of peers knew by this node """ conn_handler = self.endpoint.conn_handler() try: - peers_data = yield from bma.network.peering.Peers(conn_handler).get(leaves='true') + peers_data = await bma.network.peering.Peers(conn_handler).get(leaves='true') self.state = Node.ONLINE if peers_data['root'] != self._last_merkle['root']: leaves = [leaf for leaf in peers_data['leaves'] if leaf not in self._last_merkle['leaves']] for leaf_hash in leaves: try: - leaf_data = yield from bma.network.peering.Peers(conn_handler).get(leaf=leaf_hash) + leaf_data = await bma.network.peering.Peers(conn_handler).get(leaf=leaf_hash) if "raw" in leaf_data['leaf']['value']: peer_doc = Peer.from_signed_raw("{0}{1}\n".format(leaf_data['leaf']['value']['raw'], leaf_data['leaf']['value']['signature'])) diff --git a/src/sakia/core/registry/identities.py b/src/sakia/core/registry/identities.py index ec8ccfa875885b9f4d7c9d55e054fdb6951aff71..bb2608e906e0e2277c22e80da3320d5d031e1d13 100644 --- a/src/sakia/core/registry/identities.py +++ b/src/sakia/core/registry/identities.py @@ -62,13 +62,12 @@ class IdentitiesRegistry: self._instances[community.currency] = {} return self._identities(community) - @asyncio.coroutine - def _find_by_lookup(self, pubkey, community): + async def _find_by_lookup(self, pubkey, community): identity = self._identities(community)[pubkey] lookup_tries = 0 while lookup_tries < 3: try: - data = yield from community.bma_access.simple_request(bma.wot.Lookup, + data = await community.bma_access.simple_request(bma.wot.Lookup, req_args={'search': pubkey}) timestamp = 0 for result in data['results']: @@ -92,8 +91,7 @@ class IdentitiesRegistry: return identity return identity - @asyncio.coroutine - def future_find(self, pubkey, community): + async def future_find(self, pubkey, community): """ :param pubkey: The pubkey we look for @@ -109,7 +107,7 @@ class IdentitiesRegistry: tries = 0 while tries < 3 and identity.local_state == LocalState.NOT_FOUND: try: - data = yield from community.bma_access.simple_request(bma.blockchain.Membership, + data = await community.bma_access.simple_request(bma.blockchain.Membership, req_args={'search': pubkey}) identity.uid = data['uid'] identity.sigdate = data['sigDate'] @@ -117,7 +115,7 @@ class IdentitiesRegistry: identity.blockchain_state = BlockchainState.VALIDATED except ValueError as e: if '404' in str(e) or '400' in str(e): - identity = yield from self._find_by_lookup(pubkey, community) + identity = await self._find_by_lookup(pubkey, community) return identity else: tries += 1 diff --git a/src/sakia/core/registry/identity.py b/src/sakia/core/registry/identity.py index b3028c71c98184b80830c3cdaa4c0d012bed4d25..e36f11e105d509a1344a3127bce6f180421821d8 100644 --- a/src/sakia/core/registry/identity.py +++ b/src/sakia/core/registry/identity.py @@ -90,8 +90,7 @@ class Identity(QObject): return cls(uid, pubkey, sigdate, local_state, blockchain_state) - @asyncio.coroutine - def selfcert(self, community): + async def selfcert(self, community): """ Get the identity self certification. This request is not cached in the person object. @@ -102,7 +101,7 @@ class Identity(QObject): """ try: timestamp = 0 - lookup_data = yield from community.bma_access.future_request(bma.wot.Lookup, + lookup_data = await community.bma_access.future_request(bma.wot.Lookup, req_args={'search': self.pubkey}) for result in lookup_data['results']: @@ -135,8 +134,7 @@ class Identity(QObject): except NoPeerAvailable: logging.debug("No peer available") - @asyncio.coroutine - def get_join_date(self, community): + async def get_join_date(self, community): """ Get the person join date. This request is not cached in the person object. @@ -145,11 +143,11 @@ class Identity(QObject): :return: A datetime object """ try: - search = yield from community.bma_access.future_request(bma.blockchain.Membership, + search = await community.bma_access.future_request(bma.blockchain.Membership, {'search': self.pubkey}) if len(search['memberships']) > 0: membership_data = search['memberships'][0] - block = yield from community.bma_access.future_request(bma.blockchain.Block, + block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': membership_data['blockNumber']}) return block['medianTime'] except ValueError as e: @@ -159,16 +157,15 @@ class Identity(QObject): logging.debug(str(e)) raise MembershipNotFoundError(self.pubkey, community.name) - @asyncio.coroutine - def get_expiration_date(self, community): + async def get_expiration_date(self, community): try: - membership = yield from self.membership(community) + membership = await self.membership(community) join_block_number = membership['blockNumber'] try: - join_block = yield from community.bma_access.future_request(bma.blockchain.Block, + join_block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': join_block_number}) - parameters = yield from community.bma_access.future_request(bma.blockchain.Parameters) + parameters = await community.bma_access.future_request(bma.blockchain.Parameters) join_date = join_block['medianTime'] expiration_date = join_date + parameters['sigValidity'] except NoPeerAvailable: @@ -182,8 +179,7 @@ class Identity(QObject): #TODO: Manage 'OUT' memberships ? Maybe ? - @asyncio.coroutine - def membership(self, community): + async def membership(self, community): """ Get the person last membership document. @@ -192,7 +188,7 @@ class Identity(QObject): :rtype: dict """ try: - search = yield from community.bma_access.future_request(bma.blockchain.Membership, + search = await community.bma_access.future_request(bma.blockchain.Membership, {'search': self.pubkey}) block_number = -1 membership_data = None @@ -219,10 +215,9 @@ class Identity(QObject): logging.debug(str(e)) raise MembershipNotFoundError(self.pubkey, community.name) - @asyncio.coroutine - def published_uid(self, community): + async def published_uid(self, community): try: - data = yield from community.bma_access.future_request(bma.wot.Lookup, + data = await community.bma_access.future_request(bma.wot.Lookup, req_args={'search': self.pubkey}) timestamp = 0 @@ -243,20 +238,18 @@ class Identity(QObject): logging.debug(str(e)) return False - @asyncio.coroutine - def uid_is_revokable(self, community): - published = yield from self.published_uid(community) + async def uid_is_revokable(self, community): + published = await self.published_uid(community) if published: try: - yield from community.bma_access.future_request(bma.wot.CertifiersOf, + await community.bma_access.future_request(bma.wot.CertifiersOf, {'search': self.pubkey}) except ValueError as e: if '404' in str(e) or '400' in str(e): return True return False - @asyncio.coroutine - def is_member(self, community): + async def is_member(self, community): """ Check if the person is a member of a community @@ -264,7 +257,7 @@ class Identity(QObject): :return: True if the person is a member of a community """ try: - certifiers = yield from community.bma_access.future_request(bma.wot.CertifiersOf, + certifiers = await community.bma_access.future_request(bma.wot.CertifiersOf, {'search': self.pubkey}) return certifiers['isMember'] except ValueError as e: @@ -276,8 +269,7 @@ class Identity(QObject): logging.debug(str(e)) return False - @asyncio.coroutine - def certifiers_of(self, identities_registry, community): + async def certifiers_of(self, identities_registry, community): """ Get the list of this person certifiers @@ -288,7 +280,7 @@ class Identity(QObject): """ certifiers = list() try: - data = yield from community.bma_access.future_request(bma.wot.CertifiersOf, + data = await community.bma_access.future_request(bma.wot.CertifiersOf, {'search': self.pubkey}) for certifier_data in data['certifications']: @@ -314,7 +306,7 @@ class Identity(QObject): logging.debug(str(e)) try: - data = yield from community.bma_access.future_request(bma.wot.Lookup, {'search': self.pubkey}) + data = await community.bma_access.future_request(bma.wot.Lookup, {'search': self.pubkey}) for result in data['results']: if result["pubkey"] == self.pubkey: self._refresh_uid(result['uids']) @@ -329,7 +321,7 @@ class Identity(QObject): None, BlockchainState.BUFFERED, community) - block = yield from community.bma_access.future_request(bma.blockchain.Block, + block = await community.bma_access.future_request(bma.blockchain.Block, {'number': certifier_data['meta']['block_number']}) certifier['cert_time'] = block['medianTime'] certifier['block_number'] = None @@ -341,8 +333,7 @@ class Identity(QObject): logging.debug(str(e)) return certifiers - @asyncio.coroutine - def unique_valid_certifiers_of(self, identities_registry, community): + async def unique_valid_certifiers_of(self, identities_registry, community): """ Get the certifications in the blockchain and in the pools Get only unique and last certification for each pubkey @@ -351,13 +342,13 @@ class Identity(QObject): :return: The list of the certifiers of this community :rtype: list """ - certifier_list = yield from self.certifiers_of(identities_registry, community) + certifier_list = await self.certifiers_of(identities_registry, community) unique_valid = [] # add certifiers of uid for certifier in tuple(certifier_list): # add only valid certification... try: - cert_expired = yield from community.certification_expired(certifier['cert_time']) + cert_expired = await community.certification_expired(certifier['cert_time']) except NoPeerAvailable: logging.debug("No peer available") cert_expired = True @@ -373,8 +364,7 @@ class Identity(QObject): unique_valid.append(certifier) return unique_valid - @asyncio.coroutine - def certified_by(self, identities_registry, community): + async def certified_by(self, identities_registry, community): """ Get the list of persons certified by this person :param sakia.core.registry.IdentitiesRegistry identities_registry: The registry @@ -386,7 +376,7 @@ class Identity(QObject): """ certified_list = list() try: - data = yield from community.bma_access.future_request(bma.wot.CertifiedBy, {'search': self.pubkey}) + data = await community.bma_access.future_request(bma.wot.CertifiedBy, {'search': self.pubkey}) for certified_data in data['certifications']: certified = {} certified['identity'] = identities_registry.from_handled_data(certified_data['uid'], @@ -407,7 +397,7 @@ class Identity(QObject): logging.debug(str(e)) try: - data = yield from community.bma_access.future_request(bma.wot.Lookup, {'search': self.pubkey}) + data = await community.bma_access.future_request(bma.wot.Lookup, {'search': self.pubkey}) for result in data['results']: if result["pubkey"] == self.pubkey: self._refresh_uid(result['uids']) @@ -428,15 +418,14 @@ class Identity(QObject): logging.debug(str(e)) return certified_list - @asyncio.coroutine - def unique_valid_certified_by(self, identities_registry, community): - certified_list = yield from self.certified_by(identities_registry, community) + async def unique_valid_certified_by(self, identities_registry, community): + certified_list = await self.certified_by(identities_registry, community) unique_valid = [] # add certifiers of uid for certified in tuple(certified_list): # add only valid certification... try: - cert_expired = yield from community.certification_expired(certified['cert_time']) + cert_expired = await community.certification_expired(certified['cert_time']) except NoPeerAvailable: logging.debug("No peer available") cert_expired = True @@ -452,13 +441,12 @@ class Identity(QObject): unique_valid.append(certified) return unique_valid - @asyncio.coroutine - def membership_expiration_time(self, community): - membership = yield from self.membership(community) + async def membership_expiration_time(self, community): + membership = await self.membership(community) join_block = membership['blockNumber'] - block = yield from community.get_block(join_block) + block = await community.get_block(join_block) join_date = block['medianTime'] - parameters = yield from community.parameters() + parameters = await community.parameters() expiration_date = join_date + parameters['sigValidity'] current_time = time.time() return expiration_date - current_time diff --git a/src/sakia/core/transfer.py b/src/sakia/core/transfer.py index 6f83ff1cd0adba5611e35b71141a7ea9f7fab287..53d130111371bfb547180b3d6cf434365f569d5f 100644 --- a/src/sakia/core/transfer.py +++ b/src/sakia/core/transfer.py @@ -326,8 +326,7 @@ class Transfer(QObject): """ self.run_state_transitions(()) - @asyncio.coroutine - def send(self, txdoc, community): + async def send(self, txdoc, community): """ Send a transaction and update the transfer state to AWAITING if accepted. If the transaction was refused (return code != 200), state becomes REFUSED @@ -337,21 +336,21 @@ class Transfer(QObject): :param community: The community target of the transaction """ self.sha_hash = txdoc.sha_hash - responses = yield from community.bma_access.broadcast(bma.tx.Process, + responses = await community.bma_access.broadcast(bma.tx.Process, post_args={'transaction': txdoc.signed_raw()}) - blockid = yield from community.blockid() - block = yield from community.bma_access.future_request(bma.blockchain.Block, + blockid = await community.blockid() + block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': blockid.number}) signed_raw = "{0}{1}\n".format(block['raw'], block['signature']) block_doc = Block.from_signed_raw(signed_raw) result = (False, "") for r in responses: if r.status == 200: - result = (True, (yield from r.json())) + result = (True, (await r.json())) elif not result[0]: - result = (False, (yield from r.text())) + result = (False, (await r.text())) else: - yield from r.text() + await r.text() self.run_state_transitions(([r.status for r in responses], block_doc)) self.run_state_transitions(([r.status for r in responses])) return result diff --git a/src/sakia/core/txhistory.py b/src/sakia/core/txhistory.py index b6d7e442e24f84b865d7063b227cc428b77b545d..0b412accc0f6f1c73ea4d52a9e2029230e9a43f8 100644 --- a/src/sakia/core/txhistory.py +++ b/src/sakia/core/txhistory.py @@ -74,7 +74,7 @@ class TxHistory(): def stop_coroutines(self): self._stop_coroutines = True - def _get_block_doc(self, community, number): + async def _get_block_doc(self, community, number): """ Retrieve the current block document :param sakia.core.Community community: The community we look for a block @@ -86,7 +86,7 @@ class TxHistory(): block = None while block is None and tries < 3: try: - block = yield from community.bma_access.future_request(bma.blockchain.Block, + block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': number}) signed_raw = "{0}{1}\n".format(block['raw'], block['signature']) @@ -102,8 +102,7 @@ class TxHistory(): tries += 1 return block_doc - @asyncio.coroutine - def _parse_transaction(self, community, tx, blockid, + async def _parse_transaction(self, community, tx, blockid, mediantime, received_list, txid): """ Parse a transaction @@ -122,13 +121,13 @@ class TxHistory(): receivers = [tx.issuers[0]] try: - issuer = yield from self.wallet._identities_registry.future_find(tx.issuers[0], community) + issuer = await self.wallet._identities_registry.future_find(tx.issuers[0], community) issuer_uid = issuer.uid except LookupFailureError: issuer_uid = "" try: - receiver = yield from self.wallet._identities_registry.future_find(receivers[0], community) + receiver = await self.wallet._identities_registry.future_find(receivers[0], community) receiver_uid = receiver.uid except LookupFailureError: receiver_uid = "" @@ -180,8 +179,7 @@ class TxHistory(): return transfer return None - @asyncio.coroutine - def _parse_block(self, community, block_number, received_list, txmax): + async def _parse_block(self, community, block_number, received_list, txmax): """ Parse a block :param sakia.core.Community community: The community @@ -190,7 +188,7 @@ class TxHistory(): :param int txmax: Latest tx id :return: The list of transfers sent """ - block_doc = yield from self._get_block_doc(community, block_number) + block_doc = await self._get_block_doc(community, block_number) transfers = [] if block_doc: for transfer in [t for t in self._transfers if t.state == TransferState.AWAITING]: @@ -201,7 +199,7 @@ class TxHistory(): ] for (txid, tx) in enumerate(new_tx): - transfer = yield from self._parse_transaction(community, tx, block_doc.blockid, + transfer = await self._parse_transaction(community, tx, block_doc.blockid, block_doc.mediantime, received_list, txid+txmax) if transfer != None: #logging.debug("Transfer amount : {0}".format(transfer.metadata['amount'])) @@ -213,11 +211,10 @@ class TxHistory(): logging.debug("Could not find or parse block {0}".format(block_number)) return transfers - @asyncio.coroutine - def request_dividends(self, community, parsed_block): + async def request_dividends(self, community, parsed_block): for i in range(0, 6): try: - dividends_data = yield from community.bma_access.future_request(bma.ud.History, + dividends_data = await community.bma_access.future_request(bma.ud.History, req_args={'pubkey': self.wallet.pubkey}) dividends = dividends_data['history']['history'].copy() @@ -231,8 +228,7 @@ class TxHistory(): pass return {} - @asyncio.coroutine - def _refresh(self, community, block_number_from, block_to, received_list): + async def _refresh(self, community, block_number_from, block_to, received_list): """ Refresh last transactions @@ -243,9 +239,9 @@ class TxHistory(): new_dividends = [] try: logging.debug("Refresh from : {0} to {1}".format(block_number_from, block_to['number'])) - dividends = yield from self.request_dividends(community, block_number_from) - with_tx_data = yield from community.bma_access.future_request(bma.blockchain.TX) - members_pubkeys = yield from community.members_pubkeys() + dividends = await self.request_dividends(community, block_number_from) + with_tx_data = await community.bma_access.future_request(bma.blockchain.TX) + members_pubkeys = await community.members_pubkeys() fork_window = community.network.fork_window(members_pubkeys) blocks_with_tx = with_tx_data['result']['blocks'] while block_number_from <= block_to['number']: @@ -267,7 +263,7 @@ class TxHistory(): # We parse only blocks with transactions if block_number_from in blocks_with_tx: - transfers = yield from self._parse_block(community, block_number_from, + transfers = await self._parse_block(community, block_number_from, received_list, udid + len(new_transfers)) new_transfers += transfers @@ -283,12 +279,12 @@ class TxHistory(): # We check if latest parsed block_number is a new high number if block_number_from > self.latest_block: - self.available_sources = yield from self.wallet.sources(community) + self.available_sources = await self.wallet.sources(community) if self._stop_coroutines: return self.latest_block = block_number_from - parameters = yield from community.parameters() + parameters = await community.parameters() for transfer in [t for t in self._transfers if t.state == TransferState.AWAITING]: transfer.run_state_transitions((False, block_to, parameters['avgGenTime'], parameters['medianTimeBlocks'])) @@ -302,14 +298,13 @@ class TxHistory(): self.wallet.refresh_finished.emit(received_list) - @asyncio.coroutine - def _check_block(self, community, block_number): + async def _check_block(self, community, block_number): """ Parse a block :param sakia.core.Community community: The community :param int block_number: The block to check for transfers """ - block_doc = yield from self._get_block_doc(community, block_number) + block_doc = await self._get_block_doc(community, block_number) # We check if transactions are still present for transfer in [t for t in self._transfers @@ -320,8 +315,7 @@ class TxHistory(): transfer.run_state_transitions((True, block_doc)) return False - @asyncio.coroutine - def _rollback(self, community): + async def _rollback(self, community): """ Rollback last transactions until we find one still present in the main blockchain @@ -338,11 +332,11 @@ class TxHistory(): tx_blocks.reverse() for i, block_number in enumerate(tx_blocks): self.wallet.refresh_progressed.emit(i, len(tx_blocks), self.wallet.pubkey) - if (yield from self._check_block(community, block_number)): + if (await self._check_block(community, block_number)): break - current_block = yield from self._get_block_doc(community, community.network.current_blockid.number) - members_pubkeys = yield from community.members_pubkeys() + current_block = await self._get_block_doc(community, community.network.current_blockid.number) + members_pubkeys = await community.members_pubkeys() fork_window = community.network.fork_window(members_pubkeys) # We check if transactions VALIDATED are in the fork window now for transfer in [t for t in self._transfers @@ -351,15 +345,14 @@ class TxHistory(): except NoPeerAvailable: logging.debug("No peer available") - @asyncio.coroutine - def refresh(self, community, received_list): + async def refresh(self, community, received_list): # We update the block goal try: current_block_number = community.network.current_blockid.number if current_block_number: - current_block = yield from community.bma_access.future_request(bma.blockchain.Block, + current_block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': current_block_number}) - members_pubkeys = yield from community.members_pubkeys() + members_pubkeys = await community.members_pubkeys() # We look for the first block to parse, depending on awaiting and validating transfers and ud... tx_blocks = [tx.blockid.number for tx in self._transfers if tx.state in (TransferState.AWAITING, TransferState.VALIDATING) \ @@ -370,34 +363,32 @@ class TxHistory(): [max(0, self.latest_block - community.network.fork_window(members_pubkeys))] block_from = min(set(blocks)) - yield from self._wait_for_previous_refresh() + await self._wait_for_previous_refresh() if block_from < current_block["number"]: # Then we start a new one logging.debug("Starts a new refresh") - task = asyncio.async(self._refresh(community, block_from, current_block, received_list)) + task = asyncio.ensure_future(self._refresh(community, block_from, current_block, received_list)) self._running_refresh.append(task) except ValueError as e: logging.debug("Block not found") except NoPeerAvailable: logging.debug("No peer available") - @asyncio.coroutine - def rollback(self, community, received_list): - yield from self._wait_for_previous_refresh() + async def rollback(self, community, received_list): + await self._wait_for_previous_refresh() # Then we start a new one logging.debug("Starts a new rollback") - task = asyncio.async(self._rollback(community)) + task = asyncio.ensure_future(self._rollback(community)) self._running_refresh.append(task) # Then we start a refresh to check for new transactions - yield from self.refresh(community, received_list) + await self.refresh(community, received_list) - @asyncio.coroutine - def _wait_for_previous_refresh(self): + async def _wait_for_previous_refresh(self): # We wait for current refresh coroutines if len(self._running_refresh) > 0: logging.debug("Wait for the end of previous refresh") - done, pending = yield from asyncio.wait(self._running_refresh) + done, pending = await asyncio.wait(self._running_refresh) for cor in done: try: self._running_refresh.remove(cor) diff --git a/src/sakia/core/txhistory_indexation.py b/src/sakia/core/txhistory_indexation.py index c8c95c9c7ae682a56eb76df6b6e08795896eb953..aa3cd4a61ccff8cef3b7db524fda3d21bf93732b 100644 --- a/src/sakia/core/txhistory_indexation.py +++ b/src/sakia/core/txhistory_indexation.py @@ -71,17 +71,15 @@ class TxHistory(): self._stop_coroutines = True @staticmethod - @asyncio.coroutine - def _validation_state(community, block_number, current_block): - members_pubkeys = yield from community.members_pubkeys() + async def _validation_state(community, block_number, current_block): + members_pubkeys = await community.members_pubkeys() if block_number + community.network.fork_window(members_pubkeys) + 1 < current_block["number"]: state = Transfer.VALIDATED else: state = Transfer.VALIDATING return state - @asyncio.coroutine - def _parse_transaction(self, community, txdata, received_list, txid, current_block): + async def _parse_transaction(self, community, txdata, received_list, txid, current_block): tx_outputs = [OutputSource.from_inline(o) for o in txdata['outputs']] receivers = [o.pubkey for o in tx_outputs if o.pubkey != txdata['issuers'][0]] @@ -89,19 +87,19 @@ class TxHistory(): block_number = txdata['block_number'] mediantime = txdata['time'] - state = yield from TxHistory._validation_state(community, block_number, current_block) + state = await TxHistory._validation_state(community, block_number, current_block) if len(receivers) == 0: receivers = [txdata['issuers'][0]] try: - issuer = yield from self.wallet._identities_registry.future_find(txdata['issuers'][0], community) + issuer = await self.wallet._identities_registry.future_find(txdata['issuers'][0], community) issuer_uid = issuer.uid except LookupFailureError: issuer_uid = "" try: - receiver = yield from self.wallet._identities_registry.future_find(receivers[0], community) + receiver = await self.wallet._identities_registry.future_find(receivers[0], community) receiver_uid = receiver.uid except LookupFailureError: receiver_uid = "" @@ -158,17 +156,16 @@ class TxHistory(): transfer.check_registered(txdata['hash'], current_block['number'], mediantime, community.network.fork_window(community.members_pubkeys()) + 1) - @asyncio.coroutine - def refresh(self, community, received_list): + async def refresh(self, community, received_list): """ Refresh last transactions :param sakia.core.Community community: The community :param list received_list: List of transactions received """ - current_block = yield from community.bma_access.future_request(bma.blockchain.Block, + current_block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': community.network.current_blockid.number}) - members_pubkeys = yield from community.members_pubkeys() + members_pubkeys = await community.members_pubkeys() # We look for the first block to parse, depending on awaiting and validating transfers and ud... blocks = [tx.metadata['block'] for tx in self._transfers if tx.state in (Transfer.AWAITING, Transfer.VALIDATING)] +\ @@ -180,7 +177,7 @@ class TxHistory(): dividends_data = bma.ud.History.null_value for i in range(0, 6): if dividends_data == bma.ud.History.null_value: - dividends_data = yield from community.bma_access.future_request(bma.ud.History, + dividends_data = await community.bma_access.future_request(bma.ud.History, req_args={'pubkey': self.wallet.pubkey}) dividends = dividends_data['history']['history'] @@ -196,7 +193,7 @@ class TxHistory(): while parsed_block < current_block['number']: udid = 0 for d in [ud for ud in dividends if ud['block_number'] in range(parsed_block, parsed_block+100)]: - state = yield from TxHistory._validation_state(community, d['block_number'], current_block) + state = await TxHistory._validation_state(community, d['block_number'], current_block) if d['block_number'] not in [ud['block_number'] for ud in self._dividends]: d['id'] = udid @@ -211,7 +208,7 @@ class TxHistory(): tx_history = bma.tx.history.Blocks.null_value for i in range(0, 6): if tx_history == bma.tx.history.Blocks.null_value: - tx_history = yield from community.bma_access.future_request(bma.tx.history.Blocks, + tx_history = await community.bma_access.future_request(bma.tx.history.Blocks, req_args={'pubkey': self.wallet.pubkey, 'from_':str(parsed_block), 'to_': str(parsed_block + 99)}) @@ -230,7 +227,7 @@ class TxHistory(): parsed_block, current_block['number'])) else: - transfer = yield from self._parse_transaction(community, txdata, received_list, + transfer = await self._parse_transaction(community, txdata, received_list, udid + txid, current_block) if transfer: new_transfers.append(transfer) @@ -239,7 +236,7 @@ class TxHistory(): parsed_block += 100 if current_block['number'] > self.latest_block: - self.available_sources = yield from self.wallet.sources(community) + self.available_sources = await self.wallet.sources(community) if self._stop_coroutines: return self.latest_block = current_block['number'] diff --git a/src/sakia/core/wallet.py b/src/sakia/core/wallet.py index 3a1ce1bc2c54e94e88ee5d6bf202e13ffe6c1e03..de7ac9f3235724a03ab1021df91cd0b29b2416e1 100644 --- a/src/sakia/core/wallet.py +++ b/src/sakia/core/wallet.py @@ -110,7 +110,7 @@ class Wallet(QObject): :param community: The community to refresh its cache """ logging.debug("Refresh transactions for {0}".format(self.pubkey)) - asyncio.async(self.caches[community.currency].refresh(community, received_list)) + asyncio.ensure_future(self.caches[community.currency].refresh(community, received_list)) def rollback_transactions(self, community, received_list): """ @@ -119,7 +119,7 @@ class Wallet(QObject): :param community: The community to refresh its cache """ logging.debug("Refresh transactions for {0}".format(self.pubkey)) - asyncio.async(self.caches[community.currency].rollback(community, received_list)) + asyncio.ensure_future(self.caches[community.currency].rollback(community, received_list)) def check_password(self, salt, password): """ @@ -137,21 +137,19 @@ class Wallet(QObject): key = SigningKey("{0}{1}".format(salt, self.walletid), password) return (key.pubkey == self.pubkey) - @asyncio.coroutine - def relative_value(self, community): + async def relative_value(self, community): """ Get wallet value relative to last generated UD :param community: The community to get value :return: The wallet relative value """ - value = yield from self.value(community) + value = await self.value(community) ud = community.dividend relative_value = value / float(ud) return relative_value - @asyncio.coroutine - def value(self, community): + async def value(self, community): """ Get wallet absolute value @@ -159,7 +157,7 @@ class Wallet(QObject): :return: The wallet absolute value """ value = 0 - sources = yield from self.sources(community) + sources = await self.sources(community) for s in sources: value += s.amount return value @@ -212,8 +210,7 @@ class Wallet(QObject): outputs.append(OutputSource(self.pubkey, overhead)) return outputs - @asyncio.coroutine - def send_money(self, salt, password, community, + async def send_money(self, salt, password, community, recipient, amount, message): """ Send money to a given recipient in a specified community @@ -226,8 +223,8 @@ class Wallet(QObject): :param str message: The message to send with the transfer """ try: - blockid = yield from community.blockid() - block = yield from community.bma_access.future_request(bma.blockchain.Block, + blockid = await community.blockid() + block = await community.bma_access.future_request(bma.blockchain.Block, req_args={'number': blockid.number}) except ValueError as e: if '404' in str(e): @@ -244,13 +241,13 @@ class Wallet(QObject): logging.debug("Sender pubkey:{0}".format(key.pubkey)) try: - issuer = yield from self._identities_registry.future_find(key.pubkey, community) + issuer = await self._identities_registry.future_find(key.pubkey, community) issuer_uid = issuer.uid except LookupFailureError as e: issuer_uid = "" try: - receiver = yield from self._identities_registry.future_find(recipient, community) + receiver = await self._identities_registry.future_find(recipient, community) receiver_uid = receiver.uid except LookupFailureError as e: receiver_uid = "" @@ -283,10 +280,9 @@ class Wallet(QObject): tx.sign([key]) logging.debug("Transaction : {0}".format(tx.signed_raw())) - return (yield from transfer.send(tx, community)) + return (await transfer.send(tx, community)) - @asyncio.coroutine - def sources(self, community): + async def sources(self, community): """ Get available sources in a given community @@ -295,7 +291,7 @@ class Wallet(QObject): """ tx = [] try: - data = yield from community.bma_access.future_request(bma.tx.Sources, + data = await community.bma_access.future_request(bma.tx.Sources, req_args={'pubkey': self.pubkey}) for s in data['sources']: tx.append(InputSource.from_bma(s)) diff --git a/src/sakia/gui/certification.py b/src/sakia/gui/certification.py index a46712688d28f62d1451b57036280ebac9b0f7d4..118fd80bc29fd510c23b0dc177719f1f49f92a3d 100644 --- a/src/sakia/gui/certification.py +++ b/src/sakia/gui/certification.py @@ -43,34 +43,32 @@ class CertificationDialog(QDialog, Ui_CertificationDialog): self.radio_contact.setEnabled(False) @classmethod - @asyncio.coroutine - def certify_identity(cls, app, account, password_asker, community, identity): + async def certify_identity(cls, app, account, password_asker, community, identity): dialog = cls(app, account, password_asker) dialog.combo_community.setCurrentText(community.name) dialog.edit_pubkey.setText(identity.pubkey) dialog.radio_pubkey.setChecked(True) - return (yield from dialog.async_exec()) + return (await dialog.async_exec()) @asyncify - @asyncio.coroutine - def accept(self): + async def accept(self): if self.radio_contact.isChecked(): index = self.combo_contact.currentIndex() pubkey = self.account.contacts[index]['pubkey'] else: pubkey = self.edit_pubkey.text() - password = yield from self.password_asker.async_exec() + password = await self.password_asker.async_exec() if password == "": return QApplication.setOverrideCursor(Qt.WaitCursor) - result = yield from self.account.certify(password, self.community, pubkey) + result = await self.account.certify(password, self.community, pubkey) if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("Certification"), self.tr("Success sending certification")) else: - yield from QAsyncMessageBox.information(self, self.tr("Certification"), + await QAsyncMessageBox.information(self, self.tr("Certification"), self.tr("Success sending certification")) QApplication.restoreOverrideCursor() super().accept() @@ -79,7 +77,7 @@ class CertificationDialog(QDialog, Ui_CertificationDialog): toast.display(self.tr("Certification"), self.tr("Could not broadcast certification : {0}" .format(result[1]))) else: - yield from QAsyncMessageBox.critical(self, self.tr("Certification"), + await QAsyncMessageBox.critical(self, self.tr("Certification"), self.tr("Could not broadcast certification : {0}" .format(result[1]))) QApplication.restoreOverrideCursor() @@ -89,12 +87,11 @@ class CertificationDialog(QDialog, Ui_CertificationDialog): self.refresh() @asyncify - @asyncio.coroutine - def refresh(self): - account_identity = yield from self.account.identity(self.community) - is_member = yield from account_identity.is_member(self.community) + async def refresh(self): + account_identity = await self.account.identity(self.community) + is_member = await account_identity.is_member(self.community) try: - block_0 = yield from self.community.get_block(0) + block_0 = await self.community.get_block(0) except ValueError as e: if '404' in str(e) or '000' in str(e): block_0 = None diff --git a/src/sakia/gui/community_tile.py b/src/sakia/gui/community_tile.py index 419a5a156378a8621b1ebafa5aa66682ccda1eec..7b347c3245cb1668289096db99b2f288a1c13b9b 100644 --- a/src/sakia/gui/community_tile.py +++ b/src/sakia/gui/community_tile.py @@ -56,19 +56,18 @@ class CommunityTile(QFrame): self.refresh() @asyncify - @asyncio.coroutine - def refresh(self): + async def refresh(self): self.busy.show() self.setFixedSize(QSize(150, 150)) try: - current_block = yield from self.community.get_block() - members_pubkeys = yield from self.community.members_pubkeys() - amount = yield from self.app.current_account.amount(self.community) - localized_amount = yield from self.app.current_account.current_ref(amount, + current_block = await self.community.get_block() + members_pubkeys = await self.community.members_pubkeys() + amount = await self.app.current_account.amount(self.community) + localized_amount = await self.app.current_account.current_ref(amount, self.community, self.app).localized(units=True, international_system=self.app.preferences['international_system_of_units']) if current_block['monetaryMass']: - localized_monetary_mass = yield from self.app.current_account.current_ref(current_block['monetaryMass'], + localized_monetary_mass = await self.app.current_account.current_ref(current_block['monetaryMass'], self.community, self.app).localized(units=True, international_system=self.app.preferences['international_system_of_units']) else: diff --git a/src/sakia/gui/community_view.py b/src/sakia/gui/community_view.py index 6d6ad9166acac18d27ae293ccec4751720180b97..13fcaec4b37a8948788dd99419083ac40a598818 100644 --- a/src/sakia/gui/community_view.py +++ b/src/sakia/gui/community_view.py @@ -149,8 +149,7 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_block(self, block_number): + async def refresh_block(self, block_number): """ When a new block is found, start handling data. @param: block_number: The number of the block mined @@ -158,9 +157,9 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): logging.debug("Refresh block") self.status_info.clear() try: - person = yield from self.app.identities_registry.future_find(self.app.current_account.pubkey, self.community) - expiration_time = yield from person.membership_expiration_time(self.community) - parameters = yield from self.community.parameters() + person = await self.app.identities_registry.future_find(self.app.current_account.pubkey, self.community) + expiration_time = await person.membership_expiration_time(self.community) + parameters = await self.community.parameters() sig_validity = parameters['sigValidity'] warning_expiration_time = int(sig_validity / 3) will_expire_soon = (expiration_time < warning_expiration_time) @@ -178,7 +177,7 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): self.tr("<b>Warning : Membership expiration in {0} days</b>").format(days)) self.app.notifications['membership_expire_soon'][1] = time.time() - certifiers_of = yield from person.unique_valid_certifiers_of(self.app.identities_registry, + certifiers_of = await person.unique_valid_certifiers_of(self.app.identities_registry, self.community) if len(certifiers_of) < parameters['sigQty']: if 'warning_certifications' not in self.status_info: @@ -206,8 +205,7 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_status(self): + async def refresh_status(self): """ Refresh status bar """ @@ -219,7 +217,7 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): if current_block_number: text += self.tr(" Block {0}").format(current_block_number) try: - block = yield from self.community.get_block(current_block_number) + block = await self.community.get_block(current_block_number) text += " ({0})".format(QLocale.toString( QLocale(), QDateTime.fromTime_t(block['medianTime']), @@ -254,7 +252,7 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): if self.app.preferences['expert_mode']: try: - members_pubkeys = yield from self.community.members_pubkeys() + members_pubkeys = await self.community.members_pubkeys() label_text += self.tr(" - Median fork window : {0}")\ .format(self.community.network.fork_window(members_pubkeys)) except NoPeerAvailable as e: @@ -266,13 +264,12 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_quality_buttons(self): + async def refresh_quality_buttons(self): if self.account and self.community: try: - account_identity = yield from self.account.identity(self.community) - published_uid = yield from account_identity.published_uid(self.community) - uid_is_revokable = yield from account_identity.uid_is_revokable(self.community) + account_identity = await self.account.identity(self.community) + published_uid = await account_identity.published_uid(self.community) + uid_is_revokable = await account_identity.uid_is_revokable(self.community) if published_uid: logging.debug("UID Published") self.action_revoke_uid.setEnabled(uid_is_revokable) @@ -308,29 +305,27 @@ class CommunityWidget(QWidget, Ui_CommunityWidget): self.tab_informations.refresh() @asyncify - @asyncio.coroutine - def send_membership_demand(self, checked=False): - password = yield from self.password_asker.async_exec() + async def send_membership_demand(self, checked=False): + password = await self.password_asker.async_exec() if self.password_asker.result() == QDialog.Rejected: return - result = yield from self.account.send_membership(password, self.community, 'IN') + result = await self.account.send_membership(password, self.community, 'IN') if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("Membership"), self.tr("Success sending Membership demand")) else: - yield from QAsyncMessageBox.information(self, self.tr("Membership"), + await QAsyncMessageBox.information(self, self.tr("Membership"), self.tr("Success sending Membership demand")) else: if self.app.preferences['notifications']: toast.display(self.tr("Membership"), result[1]) else: - yield from QAsyncMessageBox.critical(self, self.tr("Membership"), + await QAsyncMessageBox.critical(self, self.tr("Membership"), result[1]) @asyncify - @asyncio.coroutine - def send_membership_leaving(self): - reply = yield from QAsyncMessageBox.warning(self, self.tr("Warning"), + async def send_membership_leaving(self): + reply = await QAsyncMessageBox.warning(self, self.tr("Warning"), self.tr("""Are you sure ? Sending a leaving demand cannot be canceled. The process to join back the community later will have to be done again.""") @@ -339,58 +334,56 @@ The process to join back the community later will have to be done again.""") password = self.password_asker.exec_() if self.password_asker.result() == QDialog.Rejected: return - result = yield from self.account.send_membership(password, self.community, 'OUT') + result = await self.account.send_membership(password, self.community, 'OUT') if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("Revoke"), self.tr("Success sending Revoke demand")) else: - yield from QAsyncMessageBox.information(self, self.tr("Revoke"), + await QAsyncMessageBox.information(self, self.tr("Revoke"), self.tr("Success sending Revoke demand")) else: if self.app.preferences['notifications']: toast.display(self.tr("Revoke"), result[1]) else: - yield from QAsyncMessageBox.critical(self, self.tr("Revoke"), + await QAsyncMessageBox.critical(self, self.tr("Revoke"), result[1]) @asyncify - @asyncio.coroutine - def publish_uid(self, checked=False): - password = yield from self.password_asker.async_exec() + async def publish_uid(self, checked=False): + password = await self.password_asker.async_exec() if self.password_asker.result() == QDialog.Rejected: return - result = yield from self.account.send_selfcert(password, self.community) + result = await self.account.send_selfcert(password, self.community) if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("UID"), self.tr("Success publishing your UID")) else: - yield from QAsyncMessageBox.information(self, self.tr("Membership"), + await QAsyncMessageBox.information(self, self.tr("Membership"), self.tr("Success publishing your UID")) else: if self.app.preferences['notifications']: toast.display(self.tr("UID"), result[1]) else: - yield from QAsyncMessageBox.critical(self, self.tr("UID"), + await QAsyncMessageBox.critical(self, self.tr("UID"), result[1]) @asyncify - @asyncio.coroutine - def revoke_uid(self, checked=False): - password = yield from self.password_asker.async_exec() + async def revoke_uid(self, checked=False): + password = await self.password_asker.async_exec() if self.password_asker.result() == QDialog.Rejected: return - result = yield from self.account.revoke(password, self.community) + result = await self.account.revoke(password, self.community) if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("Revoke UID"), self.tr("Your UID was revoked successfully.")) else: - yield from QAsyncMessageBox.information(self, self.tr("Membership"), + await QAsyncMessageBox.information(self, self.tr("Membership"), self.tr("Your UID was revoked successfully.")) else: if self.app.preferences['notifications']: toast.display(self.tr("Revoke UID"), result[1]) else: - yield from QAsyncMessageBox.critical(self, self.tr("UID"), + await QAsyncMessageBox.critical(self, self.tr("UID"), result[1]) def showEvent(self, QShowEvent): diff --git a/src/sakia/gui/identities_tab.py b/src/sakia/gui/identities_tab.py index 11a2b2967cc01a2eaae0de69c5f0ce720f82d2b0..8e47493afcb06b1e6ae063229bde0f486c462887 100644 --- a/src/sakia/gui/identities_tab.py +++ b/src/sakia/gui/identities_tab.py @@ -93,8 +93,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): @once_at_a_time @asyncify - @asyncio.coroutine - def identity_context_menu(self, point): + async def identity_context_menu(self, point): index = self.table_identities.indexAt(point) model = self.table_identities.model() if index.row() < model.rowCount(): @@ -103,7 +102,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): pubkey_index = model.sourceModel().index(source_index.row(), pubkey_col) pubkey = model.sourceModel().data(pubkey_index, Qt.DisplayRole) - identity = yield from self.app.identities_registry.future_find(pubkey, self.community) + identity = await self.app.identities_registry.future_find(pubkey, self.community) menu = QMenu(self) informations = QAction(self.tr("Informations"), self) @@ -167,17 +166,15 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): self.window().refresh_contacts() @asyncify - @asyncio.coroutine - def send_money_to_identity(self, identity): - result = yield from TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, + async def send_money_to_identity(self, identity): + result = await TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, self.community, identity) if result == QDialog.Accepted: self.money_sent.emit() @asyncify - @asyncio.coroutine - def certify_identity(self, identity): - yield from CertificationDialog.certify_identity(self.app, self.account, self.password_asker, + async def certify_identity(self, identity): + await CertificationDialog.certify_identity(self.app, self.account, self.password_asker, self.community, identity) def copy_identity_pubkey(self): @@ -197,8 +194,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): @once_at_a_time @asyncify - @asyncio.coroutine - def _async_execute_search_text(self, checked): + async def _async_execute_search_text(self, checked): cancel_once_task(self, self._async_search_members) cancel_once_task(self, self._async_search_direct_connections) @@ -207,7 +203,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): if len(text) < 2: return try: - response = yield from self.community.bma_access.future_request(bma.wot.Lookup, {'search': text}) + response = await self.community.bma_access.future_request(bma.wot.Lookup, {'search': text}) identities = [] for identity_data in response['results']: for uid_data in identity_data['uids']: @@ -218,7 +214,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): identities.append(identity) self.edit_textsearch.clear() - yield from self.refresh_identities(identities) + await self.refresh_identities(identities) except ValueError as e: logging.debug(str(e)) finally: @@ -226,8 +222,7 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): @once_at_a_time @asyncify - @asyncio.coroutine - def _async_search_members(self, checked=False): + async def _async_search_members(self, checked=False): """ Search members of community and display found members """ @@ -236,20 +231,19 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): if self.community: self.busy.show() - pubkeys = yield from self.community.members_pubkeys() + pubkeys = await self.community.members_pubkeys() identities = [] for p in pubkeys: - identity = yield from self.app.identities_registry.future_find(p, self.community) + identity = await self.app.identities_registry.future_find(p, self.community) identities.append(identity) self.edit_textsearch.clear() - yield from self.refresh_identities(identities) + await self.refresh_identities(identities) self.busy.hide() @once_at_a_time @asyncify - @asyncio.coroutine - def _async_search_direct_connections(self, checked=False): + async def _async_search_direct_connections(self, checked=False): """ Search members of community and display found members """ @@ -258,32 +252,31 @@ class IdentitiesTabWidget(QWidget, Ui_IdentitiesTab): if self.account and self.community: try: - yield from self.refresh_identities([]) + await self.refresh_identities([]) self.busy.show() - self_identity = yield from self.account.identity(self.community) + self_identity = await self.account.identity(self.community) account_connections = [] - certs_of = yield from self_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) + certs_of = await self_identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) for p in certs_of: account_connections.append(p['identity']) certifiers_of = [p for p in account_connections] - certs_by = yield from self_identity.unique_valid_certified_by(self.app.identities_registry, self.community) + certs_by = await self_identity.unique_valid_certified_by(self.app.identities_registry, self.community) for p in certs_by: account_connections.append(p['identity']) certified_by = [p for p in account_connections if p.pubkey not in [i.pubkey for i in certifiers_of]] identities = certifiers_of + certified_by self.busy.hide() - yield from self.refresh_identities(identities) + await self.refresh_identities(identities) except NoPeerAvailable: self.busy.hide() - @asyncio.coroutine - def refresh_identities(self, identities): + async def refresh_identities(self, identities): """ Refresh the table with specified identities. If no identities is passed, use the account connections. """ - yield from self.table_identities.model().sourceModel().refresh_identities(identities) + await self.table_identities.model().sourceModel().refresh_identities(identities) self.table_identities.resizeColumnsToContents() def resizeEvent(self, event): diff --git a/src/sakia/gui/informations_tab.py b/src/sakia/gui/informations_tab.py index a2184503ea6ca3346a7b4589dab7402db40cf213..24dac8c7817969d41f19e31816b6dc38884e8395 100644 --- a/src/sakia/gui/informations_tab.py +++ b/src/sakia/gui/informations_tab.py @@ -50,45 +50,44 @@ class InformationsTabWidget(QWidget, Ui_InformationsTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_labels(self): + async def refresh_labels(self): self.busy.show() # try to request money parameters try: - params = yield from self.community.parameters() + params = await self.community.parameters() except NoPeerAvailable as e: logging.debug('community parameters error : ' + str(e)) return False # try to request money variables from last ud block try: - block_ud = yield from self.community.get_ud_block() + block_ud = await self.community.get_ud_block() except NoPeerAvailable as e: logging.debug('community get_ud_block error : ' + str(e)) return False try: - block_ud_minus_1 = yield from self.community.get_ud_block(1) + block_ud_minus_1 = await self.community.get_ud_block(1) except NoPeerAvailable as e: logging.debug('community get_ud_block error : ' + str(e)) return False if block_ud: # display float values - localized_ud = yield from self.account.current_ref(block_ud['dividend'], self.community, self.app).diff_localized() + localized_ud = await self.account.current_ref(block_ud['dividend'], self.community, self.app).diff_localized() - computed_dividend = yield from self.community.computed_dividend() + computed_dividend = await self.community.computed_dividend() # display float values - localized_ud_plus_1 = yield from self.account.current_ref(computed_dividend, + localized_ud_plus_1 = await self.account.current_ref(computed_dividend, self.community, self.app).diff_localized() - localized_mass = yield from self.account.current_ref(block_ud['monetaryMass'], + localized_mass = await self.account.current_ref(block_ud['monetaryMass'], self.community, self.app).diff_localized() if block_ud_minus_1: mass_minus_1 = (float(0) if block_ud['membersCount'] == 0 else block_ud_minus_1['monetaryMass'] / block_ud['membersCount']) - localized_mass_minus_1_per_member = yield from self.account.current_ref(mass_minus_1, + localized_mass_minus_1_per_member = await self.account.current_ref(mass_minus_1, self.community, self.app).diff_localized() - localized_mass_minus_1 = yield from self.account.current_ref(block_ud_minus_1['monetaryMass'], + localized_mass_minus_1 = await self.account.current_ref(block_ud_minus_1['monetaryMass'], self.community, self.app).diff_localized() else: diff --git a/src/sakia/gui/mainwindow.py b/src/sakia/gui/mainwindow.py index de02aa7cfd047335191d2f76a60082e03a57b8bf..a7f6e69ef671ec613ee7fd21e60a4f57e6b7ae49 100644 --- a/src/sakia/gui/mainwindow.py +++ b/src/sakia/gui/mainwindow.py @@ -95,18 +95,16 @@ class MainWindow(QMainWindow, Ui_MainWindow): self.refresh() @asyncify - @asyncio.coroutine - def open_add_account_dialog(self, checked=False): + async def open_add_account_dialog(self, checked=False): dialog = ProcessConfigureAccount(self.app, None) - result = yield from dialog.async_exec() + result = await dialog.async_exec() if result == QDialog.Accepted: self.action_change_account(self.app.current_account.name) @asyncify - @asyncio.coroutine - def open_configure_account_dialog(self, checked=False): + async def open_configure_account_dialog(self, checked=False): dialog = ProcessConfigureAccount(self.app, self.app.current_account) - result = yield from dialog.async_exec() + result = await dialog.async_exec() if result == QDialog.Accepted: if self.app.current_account: self.action_change_account(self.app.current_account.name) diff --git a/src/sakia/gui/member.py b/src/sakia/gui/member.py index bbaa68aa30ae7d38a0138bf7b0e0dcc1ee22c7a8..7a5f25713c72ccfeb348f1228b417cb44141bf1b 100644 --- a/src/sakia/gui/member.py +++ b/src/sakia/gui/member.py @@ -34,11 +34,10 @@ class MemberDialog(QDialog, Ui_DialogMember): self.refresh() @asyncify - @asyncio.coroutine - def refresh(self): + async def refresh(self): try: - join_date = yield from self.identity.get_join_date(self.community) + join_date = await self.identity.get_join_date(self.community) except MembershipNotFoundError: join_date = None @@ -53,8 +52,8 @@ class MemberDialog(QDialog, Ui_DialogMember): # if selected member is not the account member... if self.identity.pubkey != self.account.pubkey: # add path from selected member to account member - account_identity = yield from self.account.identity(self.community) - path = yield from graph.get_shortest_path_between_members(self.identity, + account_identity = await self.account.identity(self.community) + path = await graph.get_shortest_path_between_members(self.identity, account_identity) text = self.tr(""" diff --git a/src/sakia/gui/process_cfg_community.py b/src/sakia/gui/process_cfg_community.py index c49463db540d103d0b1d45d1794727e1698e672b..dca582223fe7f1b5e4cf00abb5db0ebb9783fa5a 100644 --- a/src/sakia/gui/process_cfg_community.py +++ b/src/sakia/gui/process_cfg_community.py @@ -58,13 +58,12 @@ class StepPageInit(Step): return self.config_dialog.password_asker @asyncify - @asyncio.coroutine - def check_guest(self, checked=False): + async def check_guest(self, checked=False): server = self.config_dialog.lineedit_server.text() port = self.config_dialog.spinbox_port.value() logging.debug("Is valid ? ") try: - self.node = yield from Node.from_address(None, server, port) + self.node = await Node.from_address(None, server, port) community = Community.create(self.node) self.config_dialog.button_connect.setEnabled(False) self.config_dialog.button_register.setEnabled(False) @@ -76,17 +75,16 @@ class StepPageInit(Step): self.config_dialog.label_error.setText(str(e)) @asyncify - @asyncio.coroutine - def check_connect(self, checked=False): + async def check_connect(self, checked=False): server = self.config_dialog.lineedit_server.text() port = self.config_dialog.spinbox_port.value() logging.debug("Is valid ? ") try: - self.node = yield from Node.from_address(None, server, port) + self.node = await Node.from_address(None, server, port) community = Community.create(self.node) self.config_dialog.button_connect.setEnabled(False) self.config_dialog.button_register.setEnabled(False) - registered = yield from self.account.check_registered(community) + registered = await self.account.check_registered(community) self.config_dialog.button_connect.setEnabled(True) self.config_dialog.button_register.setEnabled(True) if registered[0] is False and registered[2] is None: @@ -103,25 +101,24 @@ Yours : {0}, the network : {1}""".format(registered[1], registered[2]))) self.config_dialog.label_error.setText(str(e)) @asyncify - @asyncio.coroutine - def check_register(self, checked=False): + async def check_register(self, checked=False): server = self.config_dialog.lineedit_server.text() port = self.config_dialog.spinbox_port.value() logging.debug("Is valid ? ") try: - self.node = yield from Node.from_address(None, server, port) + self.node = await Node.from_address(None, server, port) community = Community.create(self.node) self.config_dialog.button_connect.setEnabled(False) self.config_dialog.button_register.setEnabled(False) - registered = yield from self.account.check_registered(community) + registered = await self.account.check_registered(community) self.config_dialog.button_connect.setEnabled(True) self.config_dialog.button_register.setEnabled(True) if registered[0] is False and registered[2] is None: - password = yield from self.password_asker.async_exec() + password = await self.password_asker.async_exec() if self.password_asker.result() == QDialog.Rejected: return self.config_dialog.label_error.setText(self.tr("Broadcasting identity...")) - result = yield from self.account.send_selfcert(password, community) + result = await self.account.send_selfcert(password, community) if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("UID broadcast"), self.tr("Identity broadcasted to the network")) @@ -243,8 +240,7 @@ class ProcessConfigureCommunity(QDialog, Ui_CommunityConfigurationDialog): self.stacked_pages.setCurrentIndex(previous_index) self.step.display_page() - @asyncio.coroutine - def start_add_node(self): + async def start_add_node(self): """ Add node slot """ @@ -252,15 +248,15 @@ class ProcessConfigureCommunity(QDialog, Ui_CommunityConfigurationDialog): port = self.spinbox_add_port.value() try: - node = yield from Node.from_address(self.community.currency, server, port) + node = await Node.from_address(self.community.currency, server, port) self.community.add_node(node) except Exception as e: - yield from QAsyncMessageBox.critical(self, self.tr("Error"), + await QAsyncMessageBox.critical(self, self.tr("Error"), str(e)) self.tree_peers.setModel(PeeringTreeModel(self.community)) def add_node(self): - asyncio.async(self.start_add_node()) + asyncio.ensure_future(self.start_add_node()) def remove_node(self): """ diff --git a/src/sakia/gui/transactions_tab.py b/src/sakia/gui/transactions_tab.py index 802ad7782922b5679f6d1fa3571bdd1ad72695ec..384b5bccd439a1d40dea820d410ca5cc11989f5b 100644 --- a/src/sakia/gui/transactions_tab.py +++ b/src/sakia/gui/transactions_tab.py @@ -87,10 +87,9 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_minimum_maximum(self): + async def refresh_minimum_maximum(self): try: - block = yield from self.community.get_block(1) + block = await self.community.get_block(1) minimum_datetime = QDateTime() minimum_datetime.setTime_t(block['medianTime']) minimum_datetime.setTime(QTime(0, 0)) @@ -143,11 +142,10 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_balance(self): + async def refresh_balance(self): self.busy_balance.show() - amount = yield from self.app.current_account.amount(self.community) - localized_amount = yield from self.app.current_account.current_ref(amount, self.community, + amount = await self.app.current_account.amount(self.community) + localized_amount = await self.app.current_account.current_ref(amount, self.community, self.app).localized(units=True, international_system=self.app.preferences['international_system_of_units']) @@ -162,8 +160,7 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def history_context_menu(self, point): + async def history_context_menu(self, point): index = self.table_history.indexAt(point) model = self.table_history.model() if index.row() < model.rowCount(QModelIndex()): @@ -178,7 +175,7 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): pubkey_index = model.sourceModel().index(source_index.row(), pubkey_col) pubkey = model.sourceModel().data(pubkey_index, Qt.DisplayRole) - identity = yield from self.app.identities_registry.future_find(pubkey, self.community) + identity = await self.app.identities_registry.future_find(pubkey, self.community) transfer = model.sourceModel().transfers()[source_index.row()] if state_data == TransferState.REFUSED or state_data == TransferState.TO_SEND: @@ -256,16 +253,14 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): self.window().refresh_contacts() @asyncify - @asyncio.coroutine - def send_money_to_identity(self, identity): - yield from TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, + async def send_money_to_identity(self, identity): + await TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, self.community, identity) self.table_history.model().sourceModel().refresh_transfers() @asyncify - @asyncio.coroutine - def certify_identity(self, identity): - yield from CertificationDialog.certify_identity(self.app, self.account, self.password_asker, + async def certify_identity(self, identity): + await CertificationDialog.certify_identity(self.app, self.account, self.password_asker, self.community, identity) def view_wot(self): @@ -273,9 +268,8 @@ class TransactionsTabWidget(QWidget, Ui_transactionsTabWidget): self.view_in_wot.emit(identity) @asyncify - @asyncio.coroutine - def send_again(self, checked=False, transfer=None): - result = yield from TransferMoneyDialog.send_transfer_again(self.app, self.app.current_account, + async def send_again(self, checked=False, transfer=None): + result = await TransferMoneyDialog.send_transfer_again(self.app, self.app.current_account, self.password_asker, self.community, transfer) self.table_history.model().sourceModel().refresh_transfers() diff --git a/src/sakia/gui/transfer.py b/src/sakia/gui/transfer.py index 3929b13a0a0159bbb932ef272e5dbf32e3173fce..0e44a25ad15f9608b9fdce4f17c003ce9db5ad19 100644 --- a/src/sakia/gui/transfer.py +++ b/src/sakia/gui/transfer.py @@ -71,28 +71,25 @@ class TransferMoneyDialog(QDialog, Ui_TransferMoneyDialog): @classmethod - @asyncio.coroutine - def send_money_to_identity(cls, app, account, password_asker, community, identity): + async def send_money_to_identity(cls, app, account, password_asker, community, identity): dialog = cls(app, account, password_asker, community, None) dialog.edit_pubkey.setText(identity.pubkey) dialog.radio_pubkey.setChecked(True) - return (yield from dialog.async_exec()) + return (await dialog.async_exec()) @classmethod - @asyncio.coroutine - def send_transfer_again(cls, app, account, password_asker, community, transfer): + async def send_transfer_again(cls, app, account, password_asker, community, transfer): dialog = cls(app, account, password_asker, community, transfer) - dividend = yield from community.dividend() + dividend = await community.dividend() relative = transfer.metadata['amount'] / dividend dialog.spinbox_amount.setMaximum(transfer.metadata['amount']) dialog.spinbox_relative.setMaximum(relative) dialog.spinbox_amount.setValue(transfer.metadata['amount']) - return (yield from dialog.async_exec()) + return (await dialog.async_exec()) @asyncify - @asyncio.coroutine - def accept(self): + async def accept(self): comment = self.edit_message.text() if self.radio_contact.isChecked(): @@ -103,25 +100,25 @@ class TransferMoneyDialog(QDialog, Ui_TransferMoneyDialog): amount = self.spinbox_amount.value() if not amount: - yield from QAsyncMessageBox.critical(self, self.tr("Money transfer"), + await QAsyncMessageBox.critical(self, self.tr("Money transfer"), self.tr("No amount. Please give the transfert amount"), QMessageBox.Ok) return - password = yield from self.password_asker.async_exec() + password = await self.password_asker.async_exec() if self.password_asker.result() == QDialog.Rejected: return QApplication.setOverrideCursor(Qt.WaitCursor) QApplication.processEvents() - result = yield from self.wallet.send_money(self.account.salt, password, self.community, + result = await self.wallet.send_money(self.account.salt, password, self.community, recipient, amount, comment) if result[0]: if self.app.preferences['notifications']: toast.display(self.tr("Transfer"), self.tr("Success sending money to {0}").format(recipient)) else: - yield from QAsyncMessageBox.information(self, self.tr("Transfer"), + await QAsyncMessageBox.information(self, self.tr("Transfer"), self.tr("Success sending money to {0}").format(recipient)) QApplication.restoreOverrideCursor() @@ -134,56 +131,52 @@ class TransferMoneyDialog(QDialog, Ui_TransferMoneyDialog): if self.app.preferences['notifications']: toast.display(self.tr("Transfer"), "Error : {0}".format(result[1])) else: - yield from QAsyncMessageBox.critical(self, self.tr("Transfer"), result[1]) + await QAsyncMessageBox.critical(self, self.tr("Transfer"), result[1]) QApplication.restoreOverrideCursor() @asyncify - @asyncio.coroutine - def amount_changed(self, value): - dividend = yield from self.community.dividend() + async def amount_changed(self, value): + dividend = await self.community.dividend() relative = value / dividend self.spinbox_relative.blockSignals(True) self.spinbox_relative.setValue(relative) self.spinbox_relative.blockSignals(False) @asyncify - @asyncio.coroutine - def relative_amount_changed(self, value): - dividend = yield from self.community.dividend() + async def relative_amount_changed(self, value): + dividend = await self.community.dividend() amount = value * dividend self.spinbox_amount.blockSignals(True) self.spinbox_amount.setValue(amount) self.spinbox_amount.blockSignals(False) @asyncify - @asyncio.coroutine - def change_current_community(self, index): + async def change_current_community(self, index): self.community = self.account.communities[index] - amount = yield from self.wallet.value(self.community) + amount = await self.wallet.value(self.community) - ref_text = yield from self.account.current_ref(amount, self.community, self.app)\ + ref_text = await self.account.current_ref(amount, self.community, self.app)\ .diff_localized(units=True, international_system=self.app.preferences['international_system_of_units']) self.label_total.setText("{0}".format(ref_text)) self.spinbox_amount.setSuffix(" " + self.community.currency) - amount = yield from self.wallet.value(self.community) - dividend = yield from self.community.dividend() + amount = await self.wallet.value(self.community) + dividend = await self.community.dividend() relative = amount / dividend self.spinbox_amount.setMaximum(amount) self.spinbox_relative.setMaximum(relative) @asyncify - @asyncio.coroutine - def change_displayed_wallet(self, index): + async def change_displayed_wallet(self, index): self.wallet = self.account.wallets[index] - amount = yield from self.wallet.value(self.community) - ref_text = yield from self.account.current_ref(amount, self.community, self.app)\ + amount = await self.wallet.value(self.community) + ref_text = await self.account.current_ref(amount, self.community, self.app)\ .diff_localized(units=True, international_system=self.app.preferences['international_system_of_units']) self.label_total.setText("{0}".format(ref_text)) - amount = yield from self.wallet.value(self.community) - dividend = yield from self.community.dividend() + amount = await self.wallet.value(self.community) + dividend = await self.community.dividend() relative = amount / dividend self.spinbox_amount.setMaximum(amount) self.spinbox_relative.setMaximum(relative) diff --git a/src/sakia/gui/wot_tab.py b/src/sakia/gui/wot_tab.py index 7f30f8cc424ddd2e3686c1983dbe84dc3e7811f5..bc97af0cffe09cd7bb0a816c7b0882476d24de1a 100644 --- a/src/sakia/gui/wot_tab.py +++ b/src/sakia/gui/wot_tab.py @@ -92,11 +92,10 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_informations_frame(self): + async def refresh_informations_frame(self): parameters = self.community.parameters try: - identity = yield from self.account.identity(self.community) + identity = await self.account.identity(self.community) membership = identity.membership(self.community) renew_block = membership['blockNumber'] last_renewal = self.community.get_block(renew_block)['medianTime'] @@ -105,8 +104,8 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): last_renewal = None expiration = None - certified = yield from identity.unique_valid_certified_by(self.app.identities_registry, self.community) - certifiers = yield from identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) + certified = await identity.unique_valid_certified_by(self.app.identities_registry, self.community) + certifiers = await identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) if last_renewal and expiration: date_renewal = QLocale.toString( QLocale(), @@ -185,8 +184,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): @once_at_a_time @asyncify - @asyncio.coroutine - def draw_graph(self, identity): + async def draw_graph(self, identity): """ Draw community graph centered on the identity @@ -196,16 +194,16 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): self.busy.show() if self.community: - identity_account = yield from self.account.identity(self.community) + identity_account = await self.account.identity(self.community) #Connect new identity if self._current_identity != identity: self._current_identity = identity # create Identity from node metadata - certifier_list = yield from identity.unique_valid_certifiers_of(self.app.identities_registry, + certifier_list = await identity.unique_valid_certifiers_of(self.app.identities_registry, self.community) - certified_list = yield from identity.unique_valid_certified_by(self.app.identities_registry, + certified_list = await identity.unique_valid_certified_by(self.app.identities_registry, self.community) # create empty graph instance @@ -215,16 +213,16 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): node_status = 0 if identity == identity_account: node_status += NODE_STATUS_HIGHLIGHTED - is_member = yield from identity.is_member(self.community) + is_member = await identity.is_member(self.community) if is_member is False: node_status += NODE_STATUS_OUT node_status += NODE_STATUS_SELECTED graph.add_identity(identity, node_status) # populate graph with certifiers-of - yield from graph.add_certifier_list(certifier_list, identity, identity_account) + await graph.add_certifier_list(certifier_list, identity, identity_account) # populate graph with certified-by - yield from graph.add_certified_list(certified_list, identity, identity_account) + await graph.add_certified_list(certified_list, identity, identity_account) # draw graph in qt scene self.graphicsView.scene().update_wot(graph.get()) @@ -232,20 +230,19 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): # if selected member is not the account member... if identity.pubkey != identity_account.pubkey: # add path from selected member to account member - path = yield from graph.get_shortest_path_between_members(identity, identity_account) + path = await graph.get_shortest_path_between_members(identity, identity_account) if path: self.graphicsView.scene().update_path(path) self.busy.hide() @once_at_a_time @asyncify - @asyncio.coroutine - def reset(self, checked=False): + async def reset(self, checked=False): """ Reset graph scene to wallet identity """ if self.account and self.community: - identity = yield from self.account.identity(self.community) + identity = await self.account.identity(self.community) self.draw_graph(identity) def refresh(self): @@ -258,8 +255,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): self.reset() @asyncify - @asyncio.coroutine - def search(self): + async def search(self): """ Search nodes when return is pressed in combobox lineEdit """ @@ -267,7 +263,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): if len(text) < 2: return False - response = yield from self.community.bma_access.future_request(bma.wot.Lookup, {'search': text}) + response = await self.community.bma_access.future_request(bma.wot.Lookup, {'search': text}) nodes = {} for identity in response['results']: @@ -312,8 +308,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): dialog.exec_() @asyncify - @asyncio.coroutine - def sign_node(self, metadata): + async def sign_node(self, metadata): identity = self.app.identities_registry.from_handled_data( metadata['text'], metadata['id'], @@ -321,12 +316,11 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): BlockchainState.VALIDATED, self.community ) - yield from CertificationDialog.certify_identity(self.app, self.account, self.password_asker, + await CertificationDialog.certify_identity(self.app, self.account, self.password_asker, self.community, identity) @asyncify - @asyncio.coroutine - def send_money_to_node(self, metadata): + async def send_money_to_node(self, metadata): identity = self.app.identities_registry.from_handled_data( metadata['text'], metadata['id'], @@ -334,7 +328,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget): BlockchainState.VALIDATED, self.community ) - result = yield from TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, + result = await TransferMoneyDialog.send_money_to_identity(self.app, self.account, self.password_asker, self.community, identity) if result == QDialog.Accepted: self.money_sent.emit() diff --git a/src/sakia/models/identities.py b/src/sakia/models/identities.py index cfabfbb4b734667d9b00dbb8c10f040f3929bcdd..19ab2fc9ad33310e2a1649846d6483520cec7501 100644 --- a/src/sakia/models/identities.py +++ b/src/sakia/models/identities.py @@ -113,8 +113,7 @@ class IdentitiesTableModel(QAbstractTableModel): """ return [i[1] for i in self.identities_data] - @asyncio.coroutine - def identity_data(self, identity): + async def identity_data(self, identity): """ Return the identity in the form a tuple to display :param sakia.core.registry.Identity identity: The identity to get data from @@ -122,16 +121,15 @@ class IdentitiesTableModel(QAbstractTableModel): :rtype: tuple """ try: - join_date = yield from identity.get_join_date(self.community) - expiration_date = yield from identity.get_expiration_date(self.community) + join_date = await identity.get_join_date(self.community) + expiration_date = await identity.get_expiration_date(self.community) except MembershipNotFoundError: join_date = None expiration_date = None return identity.uid, identity.pubkey, join_date, expiration_date, identity.sigdate - @asyncio.coroutine - def refresh_identities(self, identities): + async def refresh_identities(self, identities): """ Change the identities to display @@ -144,11 +142,11 @@ class IdentitiesTableModel(QAbstractTableModel): self.beginResetModel() identities_data = [] for identity in identities: - data = yield from self.identity_data(identity) + data = await self.identity_data(identity) identities_data.append(data) if len(identities) > 0: try: - parameters = yield from self.community.parameters() + parameters = await self.community.parameters() self._sig_validity = parameters['sigValidity'] except NoPeerAvailable as e: logging.debug(str(e)) diff --git a/src/sakia/models/network.py b/src/sakia/models/network.py index 20a6e7872ee1e67dfec620063209c88333569b84..f591cda03c43bd037b919c0de6dd1c585ac1c519 100644 --- a/src/sakia/models/network.py +++ b/src/sakia/models/network.py @@ -144,15 +144,14 @@ class NetworkTableModel(QAbstractTableModel): self.community = community self.refresh_nodes() - @asyncio.coroutine - def data_node(self, node: Node) -> tuple: + async def data_node(self, node: Node) -> tuple: """ Return node data tuple :param ..core.net.node.Node node: Network node :return: """ try: - members_pubkey = yield from self.community.members_pubkeys() + members_pubkey = await self.community.members_pubkeys() is_member = node.pubkey in members_pubkey except NoPeerAvailable as e: logging.error(e) @@ -177,14 +176,13 @@ class NetworkTableModel(QAbstractTableModel): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_nodes(self): + async def refresh_nodes(self): self.beginResetModel() self.nodes_data = [] nodes_data = [] if self.community: for node in self.community.network.nodes: - data = yield from self.data_node(node) + data = await self.data_node(node) nodes_data.append(data) self.nodes_data = nodes_data self.endResetModel() diff --git a/src/sakia/models/txhistory.py b/src/sakia/models/txhistory.py index de5d3adc44113296f1768ab9bfbfe45eb8da3b6e..d629a5a650390760cd14586220740537c0aa0fec 100644 --- a/src/sakia/models/txhistory.py +++ b/src/sakia/models/txhistory.py @@ -229,10 +229,9 @@ class HistoryTableModel(QAbstractTableModel): else: return [] - @asyncio.coroutine - def data_received(self, transfer): + async def data_received(self, transfer): amount = transfer.metadata['amount'] - deposit = yield from self.account.current_ref(transfer.metadata['amount'], self.community, self.app)\ + deposit = await self.account.current_ref(transfer.metadata['amount'], self.community, self.app)\ .diff_localized(international_system=self.app.preferences['international_system_of_units']) comment = "" if transfer.metadata['comment'] != "": @@ -253,10 +252,9 @@ class HistoryTableModel(QAbstractTableModel): comment, transfer.state, txid, transfer.metadata['issuer'], block_number, amount) - @asyncio.coroutine - def data_sent(self, transfer): + async def data_sent(self, transfer): amount = transfer.metadata['amount'] - paiment = yield from self.account.current_ref(transfer.metadata['amount'], self.community, self.app)\ + paiment = await self.account.current_ref(transfer.metadata['amount'], self.community, self.app)\ .diff_localized(international_system=self.app.preferences['international_system_of_units']) comment = "" if transfer.metadata['comment'] != "": @@ -277,10 +275,9 @@ class HistoryTableModel(QAbstractTableModel): "", comment, transfer.state, txid, transfer.metadata['receiver'], block_number, amount) - @asyncio.coroutine - def data_dividend(self, dividend): + async def data_dividend(self, dividend): amount = dividend['amount'] - deposit = yield from self.account.current_ref(dividend['amount'], self.community, self.app)\ + deposit = await self.account.current_ref(dividend['amount'], self.community, self.app)\ .diff_localized(international_system=self.app.preferences['international_system_of_units']) comment = "" receiver = self.account.name @@ -295,8 +292,7 @@ class HistoryTableModel(QAbstractTableModel): @once_at_a_time @asyncify - @asyncio.coroutine - def refresh_transfers(self): + async def refresh_transfers(self): self.beginResetModel() self.transfers_data = [] self.endResetModel() @@ -307,15 +303,15 @@ class HistoryTableModel(QAbstractTableModel): data = None if type(transfer) is Transfer: if transfer.metadata['issuer'] == self.account.pubkey: - data = yield from self.data_sent(transfer) + data = await self.data_sent(transfer) else: - data = yield from self.data_received(transfer) + data = await self.data_received(transfer) elif type(transfer) is dict: - data = yield from self.data_dividend(transfer) + data = await self.data_dividend(transfer) if data: transfers_data.append(data) try: - members_pubkeys = yield from self.community.members_pubkeys() + members_pubkeys = await self.community.members_pubkeys() self._max_confirmations = self.community.network.fork_window(members_pubkeys) + 1 except NoPeerAvailable as e: logging.debug(str(e)) diff --git a/src/sakia/tests/core/test_identity.py b/src/sakia/tests/core/test_identity.py index a4047b1ba03b7869bb43f311008e71f907e45553..dac636724a58654f678fbf40c57fadbb5157a6d1 100644 --- a/src/sakia/tests/core/test_identity.py +++ b/src/sakia/tests/core/test_identity.py @@ -46,9 +46,8 @@ class TestIdentity(unittest.TestCase, QuamashTest): identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - @asyncio.coroutine - def exec_test(): - certified = yield from identity.certifiers_of(self.identities_registry, self.community) + async def exec_test(): + certified = await identity.certifiers_of(self.identities_registry, self.community) self.assertEqual(len(certified), 1) self.assertEqual(certified[0]['identity'].uid, "doe") @@ -63,9 +62,8 @@ class TestIdentity(unittest.TestCase, QuamashTest): identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - @asyncio.coroutine - def exec_test(): - ms = yield from identity.membership(self.community) + async def exec_test(): + ms = await identity.membership(self.community) self.assertEqual(ms["blockNumber"], 0) self.assertEqual(ms["blockHash"], "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709") self.assertEqual(ms["membership"], "IN") @@ -82,10 +80,9 @@ class TestIdentity(unittest.TestCase, QuamashTest): identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - @asyncio.coroutine - def exec_test(): + async def exec_test(): with self.assertRaises(MembershipNotFoundError): - yield from identity.membership(self.community) + await identity.membership(self.community) self.lp.run_until_complete(exec_test()) mock.delete_mock() diff --git a/src/sakia/tests/gui/certification/test_certification.py b/src/sakia/tests/gui/certification/test_certification.py index 88a5cb7744924461808ab9008820cfb4a49d0abb..885019c06bf30dcfdf534dc5d888221f4f5b5e36 100644 --- a/src/sakia/tests/gui/certification/test_certification.py +++ b/src/sakia/tests/gui/certification/test_certification.py @@ -65,29 +65,27 @@ class TestCertificationDialog(unittest.TestCase, QuamashTest): self.account, self.password_asker) - @asyncio.coroutine - def open_dialog(certification_dialog): - result = yield from certification_dialog.async_exec() + async def open_dialog(certification_dialog): + result = await certification_dialog.async_exec() self.assertEqual(result, QDialog.Accepted) def close_dialog(): if certification_dialog.isVisible(): certification_dialog.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(certification_dialog.radio_pubkey, Qt.LeftButton) QTest.keyClicks(certification_dialog.edit_pubkey, "FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn") QTest.mouseClick(certification_dialog.button_box.button(QDialogButtonBox.Ok), Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) topWidgets = QApplication.topLevelWidgets() for w in topWidgets: if type(w) is QMessageBox: QTest.keyClick(w, Qt.Key_Enter) self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(open_dialog(certification_dialog)) mock.delete_mock() diff --git a/src/sakia/tests/gui/identities_tab/test_identities_table.py b/src/sakia/tests/gui/identities_tab/test_identities_table.py index 89427da18742ded9aeac94a4913734fb73d66011..1ad2e3ac65c91a5a630c83683f535b139f7c3211 100644 --- a/src/sakia/tests/gui/identities_tab/test_identities_table.py +++ b/src/sakia/tests/gui/identities_tab/test_identities_table.py @@ -74,9 +74,8 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): identities_tab.close() future.set_result(True) - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(2) + async def exec_test(): + await asyncio.sleep(2) urls = [mock.get_request(i).url for i in range(0, 7)] self.assertTrue('/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ' in urls, msg="Not found in {0}".format(urls)) @@ -91,7 +90,7 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): QTest.keyClicks(identities_tab.edit_textsearch, "doe") QTest.mouseClick(identities_tab.button_search, Qt.LeftButton) - yield from asyncio.sleep(2) + await asyncio.sleep(2) req = 7 self.assertEqual(mock.get_request(req).method, 'GET') @@ -100,10 +99,10 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): req += 1 self.assertEqual(identities_tab.table_identities.model().rowCount(), 1) - yield from asyncio.sleep(2) + await asyncio.sleep(2) self.lp.call_soon(close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.call_later(15, close_dialog) self.lp.run_until_complete(open_widget()) mock.delete_mock() diff --git a/src/sakia/tests/gui/process_cfg_account/test_add_account.py b/src/sakia/tests/gui/process_cfg_account/test_add_account.py index 45aca84e1eac59be6daac25a489d25c0b9ca9f78..604967d42715edc2aa4209f7b733528f6626ef67 100644 --- a/src/sakia/tests/gui/process_cfg_account/test_add_account.py +++ b/src/sakia/tests/gui/process_cfg_account/test_add_account.py @@ -38,17 +38,15 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): process_account = ProcessConfigureAccount(self.application, None) - @asyncio.coroutine - def open_dialog(process_account): - result = yield from process_account.async_exec() + async def open_dialog(process_account): + result = await process_account.async_exec() self.assertEqual(result, QDialog.Accepted) def close_dialog(): if process_account.isVisible(): process_account.close() - @asyncio.coroutine - def exec_test(): + async def exec_test(): QTest.keyClicks(process_account.edit_account_name, "test") self.assertEqual(process_account.stacked_pages.currentWidget(), process_account.page_init, @@ -82,7 +80,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): msg="Current widget : {0}".format(process_account.stacked_pages.currentWidget().objectName())) process_account.password_asker.password = "testsakia" process_account.password_asker.remember = True - yield from asyncio.sleep(1) + await asyncio.sleep(1) QTest.mouseClick(process_account.button_next, Qt.LeftButton) self.assertEqual(len(self.application.accounts), 1) self.assertEqual(self.application.current_account.name, "test") @@ -90,7 +88,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(len(self.application.current_account.wallets), 1) self.lp.call_later(10, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(open_dialog(process_account)) if __name__ == '__main__': diff --git a/src/sakia/tests/gui/process_cfg_community/test_add_community.py b/src/sakia/tests/gui/process_cfg_community/test_add_community.py index e669ba2d691c896afdeaa42e3d2f46df19058c5f..010d042438e8dff85d183e38d15b02931d29ba87 100644 --- a/src/sakia/tests/gui/process_cfg_community/test_add_community.py +++ b/src/sakia/tests/gui/process_cfg_community/test_add_community.py @@ -50,9 +50,8 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) @@ -63,7 +62,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") self.assertEqual(process_community.spinbox_port.value(), 50000) QTest.mouseClick(process_community.button_register, Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') self.assertEqual(mock.get_request(1).method, 'GET') @@ -73,7 +72,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(mock.get_request(i).method, 'GET') self.assertEqual(mock.get_request(i).url, '/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') - yield from asyncio.sleep(5) + await asyncio.sleep(5) self.assertEqual(mock.get_request(5).method, 'GET') self.assertEqual(mock.get_request(5).url, '/wot/certifiers-of/john') @@ -85,7 +84,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(mock.get_request(9).url[:8], '/wot/add') self.assertEqual(mock.get_request(9).method, 'POST') self.assertEqual(process_community.label_error.text(), "Broadcasting identity...") - yield from asyncio.sleep(1) + await asyncio.sleep(1) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_add_nodes, @@ -93,7 +92,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): QTest.mouseClick(process_community.button_next, Qt.LeftButton) self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Accepted) mock.delete_mock() @@ -111,9 +110,8 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) @@ -124,7 +122,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") self.assertEqual(process_community.spinbox_port.value(), 50000) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) - yield from asyncio.sleep(3) + await asyncio.sleep(3) self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') @@ -143,7 +141,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): process_community.close() self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) mock.delete_mock() @@ -161,9 +159,8 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) @@ -174,7 +171,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") self.assertEqual(process_community.spinbox_port.value(), 50000) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') @@ -187,7 +184,7 @@ Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ process_community.close() self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Rejected) mock.delete_mock() @@ -206,9 +203,8 @@ Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ if process_community.isVisible(): process_community.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) @@ -219,7 +215,7 @@ Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") self.assertEqual(process_community.spinbox_port.value(), 50000) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') @@ -232,7 +228,7 @@ Yours : wrong_uid, the network : john""") process_community.close() self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Rejected) mock.delete_mock() @@ -250,9 +246,8 @@ Yours : wrong_uid, the network : john""") if process_community.isVisible(): process_community.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) @@ -263,7 +258,7 @@ Yours : wrong_uid, the network : john""") self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") self.assertEqual(process_community.spinbox_port.value(), 50000) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') @@ -277,7 +272,7 @@ Yours : wrong_uid, the network : john""") QTest.mouseClick(process_community.button_next, Qt.LeftButton) self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) mock.delete_mock() diff --git a/src/sakia/tests/gui/transfer/test_transfer.py b/src/sakia/tests/gui/transfer/test_transfer.py index 6d75a2bca21604e250af483d3af8de08ff313bcf..3414fc4f23c24e67d1180e413a71229830c40866 100644 --- a/src/sakia/tests/gui/transfer/test_transfer.py +++ b/src/sakia/tests/gui/transfer/test_transfer.py @@ -68,31 +68,29 @@ class TestTransferDialog(unittest.TestCase, QuamashTest): None) self.account.wallets[0].init_cache(self.application, self.community) - @asyncio.coroutine - def open_dialog(certification_dialog): - result = yield from certification_dialog.async_exec() + async def open_dialog(certification_dialog): + result = await certification_dialog.async_exec() self.assertEqual(result, QDialog.Accepted) def close_dialog(): if transfer_dialog.isVisible(): transfer_dialog.close() - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) - self.account.wallets[0].caches[self.community.currency].available_sources = yield from self.wallet.sources(self.community) + async def exec_test(): + await asyncio.sleep(1) + self.account.wallets[0].caches[self.community.currency].available_sources = await self.wallet.sources(self.community) QTest.mouseClick(transfer_dialog.radio_pubkey, Qt.LeftButton) QTest.keyClicks(transfer_dialog.edit_pubkey, "FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn") transfer_dialog.spinbox_amount.setValue(10) QTest.mouseClick(transfer_dialog.button_box.button(QDialogButtonBox.Ok), Qt.LeftButton) - yield from asyncio.sleep(1) + await asyncio.sleep(1) topWidgets = QApplication.topLevelWidgets() for w in topWidgets: if type(w) is QMessageBox: QTest.keyClick(w, Qt.Key_Enter) self.lp.call_later(15, close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.run_until_complete(open_dialog(transfer_dialog)) mock.delete_mock() diff --git a/src/sakia/tests/gui/wot_tab/test_wot_tab.py b/src/sakia/tests/gui/wot_tab/test_wot_tab.py index 6b1977d372692c39a24b32a97f287b8e1e608922..08e97cbf9d68126140b80baf80226b7e3c128d68 100644 --- a/src/sakia/tests/gui/wot_tab/test_wot_tab.py +++ b/src/sakia/tests/gui/wot_tab/test_wot_tab.py @@ -67,22 +67,20 @@ class TestWotTab(unittest.TestCase, QuamashTest): wot_tab.show() return future - @asyncio.coroutine - def async_open_widget(): - yield from open_widget() + async def async_open_widget(): + await open_widget() def close_dialog(): if wot_tab.isVisible(): wot_tab.close() future.set_result(True) - @asyncio.coroutine - def exec_test(): - yield from asyncio.sleep(1) + async def exec_test(): + await asyncio.sleep(1) self.assertTrue(wot_tab.isVisible()) self.lp.call_soon(close_dialog) - asyncio.async(exec_test()) + asyncio.ensure_future(exec_test()) self.lp.call_later(15, close_dialog) self.lp.run_until_complete(async_open_widget()) mock.delete_mock() diff --git a/src/sakia/tools/decorators.py b/src/sakia/tools/decorators.py index 169bdae169dc49e22b1a64a39dcd0cbcb7a10cf6..99080ce8d51041adf9c39fc2049ce1c8a951afdd 100644 --- a/src/sakia/tools/decorators.py +++ b/src/sakia/tools/decorators.py @@ -38,6 +38,6 @@ def once_at_a_time(fn): def asyncify(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): - return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs)) + return asyncio.ensure_future(asyncio.coroutine(fn)(*args, **kwargs)) return wrapper