diff --git a/silkaj/blockchain_tools.py b/silkaj/blockchain_tools.py index 57d640c8e110b4f0d43d44d3523edb5fe8e65ab2..8c75ea95729b017d19cc6f121805c16c62a0430e 100644 --- a/silkaj/blockchain_tools.py +++ b/silkaj/blockchain_tools.py @@ -31,9 +31,9 @@ class BlockchainParams(object): def __init__(self): self.params = self.get_params() - async def get_params(self): + def get_params(self): client = ClientInstance().client - return await client(blockchain.parameters) + return client(blockchain.parameters) class HeadBlock(object): @@ -47,6 +47,6 @@ class HeadBlock(object): def __init__(self): self.head_block = self.get_head() - async def get_head(self): + def get_head(self): client = ClientInstance().client - return await client(blockchain.current) + return client(blockchain.current) diff --git a/silkaj/blocks.py b/silkaj/blocks.py index b21bc2e3fc61348d2252748e1e63e3afc33856a9..c59107c08999dddc4cad6e633b871e12e6681a38 100644 --- a/silkaj/blocks.py +++ b/silkaj/blocks.py @@ -16,7 +16,6 @@ along with Silkaj. If not, see <https://www.gnu.org/licenses/>. """ import logging -from asyncio import sleep from aiohttp.client_exceptions import ServerDisconnectedError from click import INT, argument, command, progressbar @@ -28,7 +27,7 @@ from duniterpy.key.verifying_key import VerifyingKey from silkaj.constants import BMA_MAX_BLOCKS_CHUNK_SIZE from silkaj.network_tools import EndPoint -from silkaj.tools import coroutine, message_exit +from silkaj.tools import message_exit @command( @@ -39,10 +38,9 @@ If nothing specified, the whole blockchain gets verified.", ) @argument("from_block", default=0, type=INT) @argument("to_block", default=0, type=INT) -@coroutine -async def verify_blocks_signatures(from_block, to_block): +def verify_blocks_signatures(from_block, to_block): client = Client(EndPoint().BMA_ENDPOINT) - to_block = await check_passed_blocks_range(client, from_block, to_block) + to_block = check_passed_blocks_range(client, from_block, to_block) invalid_blocks_signatures = list() chunks_from = range(from_block, to_block + 1, BMA_MAX_BLOCKS_CHUNK_SIZE) with progressbar(chunks_from, label="Processing blocks verification") as bar: @@ -53,28 +51,28 @@ async def verify_blocks_signatures(from_block, to_block): chunk_from, chunk_from + chunk_size ) ) - chunk = await get_chunk(client, chunk_size, chunk_from) + chunk = get_chunk(client, chunk_size, chunk_from) for block in chunk: block = Block.from_signed_raw(block["raw"] + block["signature"] + "\n") verify_block_signature(invalid_blocks_signatures, block) - await client.close() + client.close() display_result(from_block, to_block, invalid_blocks_signatures) -async def check_passed_blocks_range(client, from_block, to_block): - head_number = (await client(bma.blockchain.current))["number"] +def check_passed_blocks_range(client, from_block, to_block): + head_number = (client(bma.blockchain.current))["number"] if to_block == 0: to_block = head_number if to_block > head_number: - await client.close() + client.close() message_exit( "Passed TO_BLOCK argument is bigger than the head block: " + str(head_number) ) if from_block > to_block: - await client.close() + client.close() message_exit("TO_BLOCK should be bigger or equal to FROM_BLOCK") return to_block @@ -88,13 +86,12 @@ def get_chunk_size(from_block, to_block, chunks_from, chunk_from): return (to_block + 1 - from_block) % BMA_MAX_BLOCKS_CHUNK_SIZE -async def get_chunk(client, chunk_size, chunk_from): +def get_chunk(client, chunk_size, chunk_from): try: - return await client(bma.blockchain.blocks, chunk_size, chunk_from) + return client(bma.blockchain.blocks, chunk_size, chunk_from) except ServerDisconnectedError: logging.info("Reach BMA anti-spam protection. Waiting two seconds") - await sleep(2) - return await client(bma.blockchain.blocks, chunk_size, chunk_from) + return client(bma.blockchain.blocks, chunk_size, chunk_from) except DuniterError as error: logging.error(error) diff --git a/silkaj/cert.py b/silkaj/cert.py index 483f089c15b00c60abbea6a77bfa1bc264447aa7..bdcef433ee313ae1746c5bf388f8014a7481aeeb 100644 --- a/silkaj/cert.py +++ b/silkaj/cert.py @@ -26,26 +26,25 @@ from tabulate import tabulate from silkaj import tui, wot from silkaj import wot_tools as wt from silkaj.auth import auth_method +from silkaj.tools import message_exit +from silkaj.network_tools import ClientInstance from silkaj.blockchain_tools import BlockchainParams, HeadBlock from silkaj.constants import ALL, DATE, SUCCESS_EXIT_STATUS from silkaj.crypto_tools import is_pubkey_and_check from silkaj.license import license_approval -from silkaj.network_tools import ClientInstance -from silkaj.tools import coroutine, message_exit @click.command("cert", help="Send certification") @click.argument("uid_pubkey_to_certify") @click.pass_context -@coroutine -async def send_certification(ctx, uid_pubkey_to_certify): +def send_certification(ctx, uid_pubkey_to_certify): client = ClientInstance().client checked_pubkey = is_pubkey_and_check(uid_pubkey_to_certify) if checked_pubkey: uid_pubkey_to_certify = checked_pubkey - idty_to_certify, pubkey_to_certify, send_certs = await wot.choose_identity( + idty_to_certify, pubkey_to_certify, send_certs = wot.choose_identity( uid_pubkey_to_certify ) @@ -53,15 +52,15 @@ async def send_certification(ctx, uid_pubkey_to_certify): key = auth_method() issuer_pubkey = key.pubkey - issuer = await pre_checks(client, issuer_pubkey, pubkey_to_certify) + issuer = pre_checks(client, issuer_pubkey, pubkey_to_certify) # Display license and ask for confirmation - head = await HeadBlock().head_block + head = HeadBlock().head_block currency = head["currency"] license_approval(currency) # Certification confirmation - await certification_confirmation( + certification_confirmation( ctx, issuer, issuer_pubkey, pubkey_to_certify, idty_to_certify ) @@ -75,25 +74,25 @@ async def send_certification(ctx, uid_pubkey_to_certify): if ctx.obj["DISPLAY_DOCUMENT"]: click.echo(certification.signed_raw(), nl=False) - await tui.send_doc_confirmation("certification") + tui.send_doc_confirmation("certification") # Sign document certification.sign([key]) # Send certification document - response = await client(bma.wot.certify, certification.signed_raw()) + response = client(bma.wot.certify, certification.signed_raw()) if response.status == 200: print("Certification successfully sent.") else: - print("Error while publishing certification: {0}".format(await response.text())) + print("Error while publishing certification: {0}".format(response.text())) - await client.close() + client.close() -async def pre_checks(client, issuer_pubkey, pubkey_to_certify): +def pre_checks(client, issuer_pubkey, pubkey_to_certify): # Check whether current user is member - issuer = await wt.is_member(issuer_pubkey) + issuer = wt.is_member(issuer_pubkey) if not issuer: message_exit("Current identity is not member.") @@ -101,11 +100,11 @@ async def pre_checks(client, issuer_pubkey, pubkey_to_certify): message_exit("You can’t certify yourself!") # Check if the certification can be renewed - req = await client(bma.wot.requirements, pubkey_to_certify) + req = client(bma.wot.requirements, pubkey_to_certify) req = req["identities"][0] for cert in req["certifications"]: if cert["from"] == issuer_pubkey: - params = await BlockchainParams().params + params = BlockchainParams().params # Ğ1: 0<–>2y - 2y + 2m # ĞT: 0<–>4.8m - 4.8m + 12.5d renewable = cert["expiresIn"] - params["sigValidity"] + params["sigReplay"] @@ -120,7 +119,7 @@ async def pre_checks(client, issuer_pubkey, pubkey_to_certify): return issuer -async def certification_confirmation( +def certification_confirmation( ctx, issuer, issuer_pubkey, pubkey_to_certify, idty_to_certify ): cert = list() @@ -128,7 +127,7 @@ async def certification_confirmation( client = ClientInstance().client idty_timestamp = idty_to_certify["meta"]["timestamp"] block_uid_idty = block_uid(idty_timestamp) - block = await client(bma.blockchain.block, block_uid_idty.number) + block = client(bma.blockchain.block, block_uid_idty.number) timestamp_date = from_timestamp(block["time"], tz="local").format(ALL) block_uid_date = f": #{idty_timestamp[:15]}… {timestamp_date}" cert.append(["ID", issuer["uid"], "–>", idty_to_certify["uid"] + block_uid_date]) @@ -140,13 +139,13 @@ async def certification_confirmation( tui.display_pubkey_and_checksum(pubkey_to_certify), ] ) - params = await BlockchainParams().params + params = BlockchainParams().params cert_begins = now().format(DATE) cert_ends = now().add(seconds=params["sigValidity"]).format(DATE) cert.append(["Valid", cert_begins, "—>", cert_ends]) click.echo(tabulate(cert, tablefmt="fancy_grid")) if not ctx.obj["DISPLAY_DOCUMENT"]: - await tui.send_doc_confirmation("certification") + tui.send_doc_confirmation("certification") def docs_generation(currency, pubkey_to_certify, idty_to_certify, issuer_pubkey, head): diff --git a/silkaj/commands.py b/silkaj/commands.py index 5ddfda6875827129bb50e3ade2c2016be38b8c98..a6358362c5241adb4f97d59241ddb940334f1486 100644 --- a/silkaj/commands.py +++ b/silkaj/commands.py @@ -29,16 +29,20 @@ from pendulum import from_timestamp from tabulate import tabulate from silkaj.blockchain_tools import HeadBlock -from silkaj.constants import ALL, ASYNC_SLEEP, HOUR +from silkaj.constants import ALL, HOUR from silkaj.network_tools import ClientInstance, EndPoint, best_endpoint_address -from silkaj.tools import CurrencySymbol, coroutine from silkaj.wot_tools import identity_of +from silkaj.network_tools import ( + best_endpoint_address, + EndPoint, + ClientInstance, +) +from silkaj.tools import CurrencySymbol @command("info", help="Display information about currency") -@coroutine -async def currency_info(): - head_block = await HeadBlock().head_block +def currency_info(): + head_block = HeadBlock().head_block ep = EndPoint().ep current_time = from_timestamp(head_block["time"], tz="local") mediantime = from_timestamp(head_block["medianTime"], tz="local") @@ -49,7 +53,7 @@ async def currency_info(): "\nCurrent block number:", head_block["number"], "\nCurrency name:", - await CurrencySymbol().symbol, + CurrencySymbol().symbol, "\nNumber of members:", head_block["membersCount"], "\nMinimal Proof-of-Work:", @@ -62,7 +66,7 @@ async def currency_info(): current_time.diff_for_humans(mediantime, True), ) client = ClientInstance().client - await client.close() + client.close() def match_pattern(pow, match="", p=1): @@ -89,17 +93,16 @@ def power(nbr, pow=0): "diffi", help="Display the current Proof of Work difficulty level to generate the next block", ) -@coroutine -async def difficulties(): +def difficulties(): client = ClientInstance().client try: - ws = await client(bma.ws.block) + ws = client(bma.ws.block) while True: - current = await ws.receive_json() + current = ws.receive_json() jsonschema.validate(current, bma.ws.WS_BLOCK_SCHEMA) - diffi = await client(bma.blockchain.difficulties) + diffi = client(bma.blockchain.difficulties) display_diffi(current, diffi) - await client.close() + client.close() except (aiohttp.WSServerHandshakeError, ValueError) as e: print("Websocket block {0} : {1}".format(type(e).__name__, str(e))) @@ -147,14 +150,13 @@ Common Proof-of-Work difficulty level: {5}, hash starting with `{6}`\n{7}".forma is_flag=True, help="Force detailed view. Compact view happen over 30 blocks", ) -@coroutine -async def list_blocks(number, detailed): - head_block = await HeadBlock().head_block +def list_blocks(number, detailed): + head_block = HeadBlock().head_block current_nbr = head_block["number"] if number == 0: number = head_block["issuersFrame"] client = ClientInstance().client - blocks = await client(bma.blockchain.blocks, number, current_nbr - number + 1) + blocks = client(bma.blockchain.blocks, number, current_nbr - number + 1) issuers = list() issuers_dict = dict() for block in blocks: @@ -172,7 +174,7 @@ async def list_blocks(number, detailed): issuers.append(issuer) for pubkey in issuers_dict.keys(): issuer = issuers_dict[pubkey] - idty = await identity_of(issuer["pubkey"]) + idty = identity_of(issuer["pubkey"]) for issuer2 in issuers: if ( issuer2.get("pubkey") is not None @@ -181,8 +183,7 @@ async def list_blocks(number, detailed): ): issuer2["uid"] = idty["uid"] issuer2.pop("pubkey") - await sleep(ASYNC_SLEEP) - await client.close() + client.close() print( "Last {0} blocks from n°{1} to n°{2}".format( number, current_nbr - number + 1, current_nbr @@ -229,10 +230,9 @@ async def list_blocks(number, detailed): @command("argos", help="Display currency information formatted for Argos or BitBar") -@coroutine -async def argos_info(): - head_block = await HeadBlock().head_block - currency_symbol = await CurrencySymbol().symbol +def argos_info(): + head_block = HeadBlock().head_block + currency_symbol = CurrencySymbol().symbol print(currency_symbol, "|") print("---") ep = EndPoint().ep @@ -265,4 +265,4 @@ async def argos_info(): current_time.diff_for_humans(mediantime, True), ) client = ClientInstance().client - await client.close() + client.close() diff --git a/silkaj/constants.py b/silkaj/constants.py index bd47f463e2bcc46e3bbdf8e66dcf37b33bad1526..15f56295dfd27b0bb2dd24a73bdef8666261c83e 100644 --- a/silkaj/constants.py +++ b/silkaj/constants.py @@ -21,7 +21,6 @@ GTEST_SYMBOL = "ĞTest" G1_DEFAULT_ENDPOINT = "g1.duniter.org", "443" G1_TEST_DEFAULT_ENDPOINT = "g1-test.duniter.org", "443" CONNECTION_TIMEOUT = 10 -ASYNC_SLEEP = 0.15 SUCCESS_EXIT_STATUS = 0 FAILURE_EXIT_STATUS = 1 BMA_MAX_BLOCKS_CHUNK_SIZE = 5000 diff --git a/silkaj/membership.py b/silkaj/membership.py index 9a5a3ca27f1939edb1d617c3defed70b629998df..ad0655c7043aa6c51858d84d002a8fca587bb251 100644 --- a/silkaj/membership.py +++ b/silkaj/membership.py @@ -29,7 +29,6 @@ from silkaj.blockchain_tools import BlockchainParams, HeadBlock from silkaj.constants import DATE, SUCCESS_EXIT_STATUS from silkaj.license import license_approval from silkaj.network_tools import ClientInstance -from silkaj.tools import coroutine @click.command( @@ -38,17 +37,16 @@ from silkaj.tools import coroutine for first emission and for renewal", ) @click.pass_context -@coroutine -async def send_membership(ctx): +def send_membership(ctx): dry_run = ctx.obj["DRY_RUN"] # Authentication key = auth.auth_method() # Get the identity information - head_block = await HeadBlock().head_block + head_block = HeadBlock().head_block membership_timestamp = BlockUID(head_block["number"], head_block["hash"]) - identity = (await wot.choose_identity(key.pubkey))[0] + identity = (wot.choose_identity(key.pubkey))[0] identity_uid = identity["uid"] identity_timestamp = block_uid(identity["meta"]["timestamp"]) @@ -59,9 +57,9 @@ async def send_membership(ctx): # Confirmation client = ClientInstance().client - await display_confirmation_table(identity_uid, key.pubkey, identity_timestamp) + display_confirmation_table(identity_uid, key.pubkey, identity_timestamp) if not dry_run and not ctx.obj["DISPLAY_DOCUMENT"]: - await tui.send_doc_confirmation("membership document for this identity") + tui.send_doc_confirmation("membership document for this identity") membership = generate_membership_document( currency, @@ -78,25 +76,25 @@ async def send_membership(ctx): if dry_run: click.echo(membership.signed_raw()) - await client.close() + client.close() sys.exit(SUCCESS_EXIT_STATUS) if ctx.obj["DISPLAY_DOCUMENT"]: click.echo(membership.signed_raw()) - await tui.send_doc_confirmation("membership document for this identity") + tui.send_doc_confirmation("membership document for this identity") # Send the membership signed raw document to the node - response = await client(bma.blockchain.membership, membership.signed_raw()) + response = client(bma.blockchain.membership, membership.signed_raw()) if response.status == 200: print("Membership successfully sent") else: - print("Error while publishing membership: {0}".format(await response.text())) - logging.debug(await response.text()) - await client.close() + print("Error while publishing membership: {0}".format(response.text())) + logging.debug(response.text()) + client.close() -async def display_confirmation_table(identity_uid, pubkey, identity_timestamp): +def display_confirmation_table(identity_uid, pubkey, identity_timestamp): """ Check whether there is pending memberships already in the mempool Display their expiration date @@ -107,7 +105,7 @@ async def display_confirmation_table(identity_uid, pubkey, identity_timestamp): client = ClientInstance().client - identities_requirements = await client(bma.wot.requirements, pubkey) + identities_requirements = client(bma.wot.requirements, pubkey) for identity_requirements in identities_requirements["identities"]: if identity_requirements["uid"] == identity_uid: membership_expires = identity_requirements["membershipExpiresIn"] @@ -135,11 +133,11 @@ async def display_confirmation_table(identity_uid, pubkey, identity_timestamp): table.append(["Block Identity", str(identity_timestamp)[:45] + "…"]) - block = await client(bma.blockchain.block, identity_timestamp.number) + block = client(bma.blockchain.block, identity_timestamp.number) date_idty_pub = pendulum.from_timestamp(block["time"], tz="local").format(DATE) table.append(["Identity published", date_idty_pub]) - params = await BlockchainParams().params + params = BlockchainParams().params membership_validity = ( pendulum.now().add(seconds=params["msValidity"]).diff_for_humans() ) diff --git a/silkaj/money.py b/silkaj/money.py index 33aed211008e946b54cee02b0b4ccccd5e7bc6e8..771ab40c9be0aebc451084006fa162731ab72147 100644 --- a/silkaj/money.py +++ b/silkaj/money.py @@ -29,15 +29,14 @@ from silkaj.crypto_tools import ( validate_checksum, ) from silkaj.network_tools import ClientInstance -from silkaj.tools import CurrencySymbol, coroutine, message_exit +from silkaj.tools import CurrencySymbol, message_exit from silkaj.tui import display_amount, display_pubkey_and_checksum @command("balance", help="Get wallet balance") @argument("pubkeys", nargs=-1) @pass_context -@coroutine -async def cmd_amount(ctx, pubkeys): +def cmd_amount(ctx, pubkeys): client = ClientInstance().client if not has_auth_method(): @@ -61,34 +60,34 @@ async def cmd_amount(ctx, pubkeys): total = [0, 0] for pubkey in pubkeys_list: - inputs_balance = await get_amount_from_pubkey(pubkey) - await show_amount_from_pubkey(pubkey, inputs_balance) + inputs_balance = get_amount_from_pubkey(pubkey) + show_amount_from_pubkey(pubkey, inputs_balance) total[0] += inputs_balance[0] total[1] += inputs_balance[1] if len(pubkeys_list) > 1: - await show_amount_from_pubkey("Total", total) + show_amount_from_pubkey("Total", total) else: key = auth_method() pubkey = key.pubkey - await show_amount_from_pubkey(pubkey, await get_amount_from_pubkey(pubkey)) - await client.close() + show_amount_from_pubkey(pubkey, get_amount_from_pubkey(pubkey)) + client.close() -async def show_amount_from_pubkey(label, inputs_balance): +def show_amount_from_pubkey(label, inputs_balance): """ Shows the balance of a pubkey. `label` can be either a pubkey or "Total". """ totalAmountInput = inputs_balance[0] balance = inputs_balance[1] - currency_symbol = await CurrencySymbol().symbol - ud_value = await UDValue().ud_value - average, monetary_mass = await get_average() + currency_symbol = CurrencySymbol().symbol + ud_value = UDValue().ud_value + average, monetary_mass = get_average() member = False # if `pubkey` is a pubkey, get pubkey:checksum and uid if label != "Total": - member = await wt.is_member(label) + member = wt.is_member(label) label = display_pubkey_and_checksum(label) # display balance table display = list() @@ -116,16 +115,16 @@ async def show_amount_from_pubkey(label, inputs_balance): echo(tabulate(display, tablefmt="fancy_grid")) -async def get_average(): - head = await HeadBlock().head_block +def get_average(): + head = HeadBlock().head_block monetary_mass = head["monetaryMass"] members_count = head["membersCount"] average = monetary_mass / members_count return average, monetary_mass -async def get_amount_from_pubkey(pubkey): - listinput, amount = await get_sources(pubkey) +def get_amount_from_pubkey(pubkey): + listinput, amount = get_sources(pubkey) totalAmountInput = 0 for input in listinput: @@ -133,10 +132,10 @@ async def get_amount_from_pubkey(pubkey): return totalAmountInput, amount -async def get_sources(pubkey): +def get_sources(pubkey): client = ClientInstance().client # Sources written into the blockchain - sources = await client(tx.sources, pubkey) + sources = client(tx.sources, pubkey) listinput = list() amount = 0 @@ -154,7 +153,7 @@ async def get_sources(pubkey): amount += amount_in_current_base(listinput[-1]) # pending source - history = await client(tx.pending, pubkey) + history = client(tx.pending, pubkey) history = history["history"] pendings = history["sending"] + history["receiving"] + history["pending"] @@ -198,11 +197,11 @@ class UDValue(object): def __init__(self): self.ud_value = self.get_ud_value() - async def get_ud_value(self): + def get_ud_value(self): client = ClientInstance().client - blockswithud = await client(blockchain.ud) + blockswithud = client(blockchain.ud) NBlastUDblock = blockswithud["result"]["blocks"][-1] - lastUDblock = await client(blockchain.block, NBlastUDblock) + lastUDblock = client(blockchain.block, NBlastUDblock) return lastUDblock["dividend"] * 10 ** lastUDblock["unitbase"] diff --git a/silkaj/tools.py b/silkaj/tools.py index b4a10af9dd153bfda37805a381196507a68dc2bc..b8474091ef6dace9b059f8b4a5f6d331773b759c 100644 --- a/silkaj/tools.py +++ b/silkaj/tools.py @@ -15,8 +15,6 @@ You should have received a copy of the GNU Affero General Public License along with Silkaj. If not, see <https://www.gnu.org/licenses/>. """ -from asyncio import get_event_loop -from functools import update_wrapper from sys import exit from silkaj.blockchain_tools import BlockchainParams @@ -34,8 +32,8 @@ class CurrencySymbol(object): def __init__(self): self.symbol = self.get_symbol() - async def get_symbol(self): - params = await BlockchainParams().params + def get_symbol(self): + params = BlockchainParams().params if params["currency"] == "g1": return G1_SYMBOL elif params["currency"] == "g1-test": @@ -45,11 +43,3 @@ class CurrencySymbol(object): def message_exit(message): print(message) exit(FAILURE_EXIT_STATUS) - - -def coroutine(f): - def wrapper(*args, **kwargs): - loop = get_event_loop() - return loop.run_until_complete(f(*args, **kwargs)) - - return update_wrapper(wrapper, f) diff --git a/silkaj/tui.py b/silkaj/tui.py index b61e390f59aebe6c191d1a08e2ee1f9e50921ce4..a32ba044a8aa6e3e1b61f02749f06327be661e23 100644 --- a/silkaj/tui.py +++ b/silkaj/tui.py @@ -42,12 +42,12 @@ def display_amount(tx, message, amount, ud_value, currency_symbol): ) -async def display_pubkey(tx, message, pubkey): +def display_pubkey(tx, message, pubkey): """ Displays a pubkey and the eventually associated id. """ tx.append([message + " (pubkey:checksum)", display_pubkey_and_checksum(pubkey)]) - id = await wot_tools.is_member(pubkey) + id = wot_tools.is_member(pubkey) if id: tx.append([message + " (id)", id["uid"]]) @@ -64,8 +64,8 @@ def display_pubkey_and_checksum( return short_pubkey + ":" + ct.gen_checksum(pubkey) -async def send_doc_confirmation(document_name): +def send_doc_confirmation(document_name): if not click.confirm(f"Do you confirm sending this {document_name}?"): client = network_tools.ClientInstance().client - await client.close() + client.close() sys.exit(constants.SUCCESS_EXIT_STATUS) diff --git a/silkaj/tx.py b/silkaj/tx.py index 2e6fea41a298bbe14b6ace1bfaa186d2996c6f7f..2ebf022f2cff25c0d7981ee4616aeac8b85717d9 100644 --- a/silkaj/tx.py +++ b/silkaj/tx.py @@ -16,7 +16,6 @@ along with Silkaj. If not, see <https://www.gnu.org/licenses/>. """ import math -from asyncio import sleep from re import compile, search import click @@ -33,7 +32,6 @@ from silkaj import money from silkaj import network_tools as nt from silkaj import tools, tui from silkaj.constants import ( - ASYNC_SLEEP, CENT_MULT_TO_UNIT, MINIMAL_ABSOLUTE_TX_AMOUNT, MINIMAL_RELATIVE_TX_AMOUNT, @@ -104,8 +102,7 @@ Sending to many recipients is possible:\n\ @click.option( "--yes", "-y", is_flag=True, help="Assume yes. Do not prompt confirmation" ) -@tools.coroutine -async def send_transaction( +def send_transaction( amounts, amountsud, allsources, @@ -125,12 +122,12 @@ async def send_transaction( ) # compute amounts and amountsud if not allsources: - tx_amounts = await transaction_amount(amounts, amountsud, recipients) + tx_amounts = transaction_amount(amounts, amountsud, recipients) key = auth.auth_method() issuer_pubkey = key.pubkey - pubkey_amount = await money.get_amount_from_pubkey(issuer_pubkey) + pubkey_amount = money.get_amount_from_pubkey(issuer_pubkey) if allsources: if pubkey_amount[0] <= 0: tools.message_exit( @@ -150,7 +147,7 @@ async def send_transaction( if not yes: confirmation_table = tabulate( - await gen_confirmation_table( + gen_confirmation_table( issuer_pubkey, pubkey_amount[0], tx_amounts, @@ -164,7 +161,7 @@ async def send_transaction( if yes or click.confirm( f"{confirmation_table}\nDo you confirm sending this transaction?" ): - await handle_intermediaries_transactions( + handle_intermediaries_transactions( key, issuer_pubkey, tx_amounts, @@ -174,10 +171,10 @@ async def send_transaction( ) else: client = nt.ClientInstance().client - await client.close() + client.close() -async def transaction_amount(amounts, UDs_amounts, outputAddresses): +def transaction_amount(amounts, UDs_amounts, outputAddresses): """ Check that the number of passed amounts(UD) and recipients are the same Returns a list of amounts. @@ -186,7 +183,7 @@ async def transaction_amount(amounts, UDs_amounts, outputAddresses): if amounts: amounts_list = compute_amounts(amounts, CENT_MULT_TO_UNIT) elif UDs_amounts: - UD_value = await money.UDValue().ud_value + UD_value = money.UDValue().ud_value amounts_list = compute_amounts(UDs_amounts, UD_value) if len(amounts_list) != len(outputAddresses) and len(amounts_list) != 1: tools.message_exit( @@ -247,7 +244,7 @@ def check_transaction_values( return outputBackChange -async def gen_confirmation_table( +def gen_confirmation_table( issuer_pubkey, pubkey_amount, tx_amounts, @@ -259,8 +256,8 @@ async def gen_confirmation_table( Generate transaction confirmation """ - currency_symbol = await tools.CurrencySymbol().symbol - ud_value = await money.UDValue().ud_value + currency_symbol = tools.CurrencySymbol().symbol + ud_value = money.UDValue().ud_value total_tx_amount = sum(tx_amounts) tx = list() # display account situation @@ -285,21 +282,20 @@ async def gen_confirmation_table( ud_value, currency_symbol, ) - await tui.display_pubkey(tx, "From", issuer_pubkey) + tui.display_pubkey(tx, "From", issuer_pubkey) # display outputs and amounts for outputAddress, tx_amount in zip(outputAddresses, tx_amounts): - await tui.display_pubkey(tx, "To", outputAddress) - await sleep(ASYNC_SLEEP) + tui.display_pubkey(tx, "To", outputAddress) tui.display_amount(tx, "Amount", tx_amount, ud_value, currency_symbol) # display last informations if outputBackChange: - await tui.display_pubkey(tx, "Backchange", outputBackChange) + tui.display_pubkey(tx, "Backchange", outputBackChange) tx.append(["Comment", comment]) return tx -async def get_list_input_for_transaction(pubkey, TXamount, outputs_number): - listinput, amount = await money.get_sources(pubkey) +def get_list_input_for_transaction(pubkey, TXamount, outputs_number): + listinput, amount = money.get_sources(pubkey) maxInputsNumber = max_inputs_number(outputs_number, NBR_ISSUERS) # generate final list source listinputfinal = [] @@ -330,7 +326,7 @@ async def get_list_input_for_transaction(pubkey, TXamount, outputs_number): return listinputfinal, totalAmountInput, intermediatetransaction -async def handle_intermediaries_transactions( +def handle_intermediaries_transactions( key, issuers, tx_amounts, @@ -342,14 +338,14 @@ async def handle_intermediaries_transactions( while True: # consider there is always one backchange output, hence +1 - listinput_and_amount = await get_list_input_for_transaction( + listinput_and_amount = get_list_input_for_transaction( issuers, sum(tx_amounts), len(outputAddresses) + 1 ) intermediatetransaction = listinput_and_amount[2] if intermediatetransaction: totalAmountInput = listinput_and_amount[1] - await generate_and_send_transaction( + generate_and_send_transaction( key, issuers, [totalAmountInput], @@ -357,10 +353,8 @@ async def handle_intermediaries_transactions( [issuers], "Change operation", ) - await sleep(1) # wait 1 second before sending a new transaction - else: - await generate_and_send_transaction( + generate_and_send_transaction( key, issuers, tx_amounts, @@ -369,7 +363,7 @@ async def handle_intermediaries_transactions( Comment, OutputbackChange, ) - await client.close() + client.close() break @@ -384,7 +378,7 @@ def max_inputs_number(outputs_number, issuers_number): ) -async def generate_and_send_transaction( +def generate_and_send_transaction( key, issuers, tx_amounts, @@ -408,7 +402,7 @@ async def generate_and_send_transaction( print(" - Total: " + str(sum(tx_amounts) / 100)) client = nt.ClientInstance().client - transaction = await generate_transaction_document( + transaction = generate_transaction_document( issuers, tx_amounts, listinput_and_amount, @@ -418,12 +412,12 @@ async def generate_and_send_transaction( ) transaction.sign([key]) - response = await client(process, transaction.signed_raw()) + response = client(process, transaction.signed_raw()) if response.status == 200: print("Transaction successfully sent.") else: tools.message_exit( - "Error while publishing transaction: {0}".format(await response.text()) + "Error while publishing transaction: {0}".format(response.text()) ) @@ -436,7 +430,7 @@ def display_sent_tx(outputAddress, amount): ) -async def generate_transaction_document( +def generate_transaction_document( issuers, tx_amounts, listinput_and_amount, @@ -449,7 +443,7 @@ async def generate_transaction_document( totalAmountInput = listinput_and_amount[1] total_tx_amount = sum(tx_amounts) - head_block = await bt.HeadBlock().head_block + head_block = bt.HeadBlock().head_block currency_name = head_block["currency"] blockstamp_current = BlockUID(head_block["number"], head_block["hash"]) curentUnitBase = head_block["unitbase"] diff --git a/silkaj/tx_history.py b/silkaj/tx_history.py index 466798cfdafe1fe33a8ecc569a9cfe5eda5ad3dd..950d9fcbff054469a535786e22bf354708e9b3f9 100644 --- a/silkaj/tx_history.py +++ b/silkaj/tx_history.py @@ -30,7 +30,7 @@ from silkaj.constants import ALL, ALL_DIGITAL from silkaj.crypto_tools import check_pubkey_format, validate_checksum from silkaj.money import UDValue, amount_in_current_base, get_amount_from_pubkey from silkaj.network_tools import ClientInstance -from silkaj.tools import CurrencySymbol, coroutine +from silkaj.tools import CurrencySymbol from silkaj.tui import display_pubkey_and_checksum @@ -38,34 +38,33 @@ from silkaj.tui import display_pubkey_and_checksum @argument("pubkey") @option("--uids", "-u", is_flag=True, help="Display uids") @option("--full-pubkey", "-f", is_flag=True, help="Display full-length pubkeys") -@coroutine -async def transaction_history(pubkey, uids, full_pubkey): +def transaction_history(pubkey, uids, full_pubkey): if check_pubkey_format(pubkey): pubkey = validate_checksum(pubkey) client = ClientInstance().client - ud_value = await UDValue().ud_value - currency_symbol = await CurrencySymbol().symbol + ud_value = UDValue().ud_value + currency_symbol = CurrencySymbol().symbol - header = await generate_header(pubkey, currency_symbol, ud_value) + header = generate_header(pubkey, currency_symbol, ud_value) received_txs, sent_txs = list(), list() - await get_transactions_history(client, pubkey, received_txs, sent_txs) + get_transactions_history(client, pubkey, received_txs, sent_txs) remove_duplicate_txs(received_txs, sent_txs) - txs_list = await generate_table( + txs_list = generate_table( received_txs, sent_txs, pubkey, ud_value, currency_symbol, uids, full_pubkey ) table = Texttable(max_width=shutil.get_terminal_size().columns) table.add_rows(txs_list) - await client.close() + client.close() echo_via_pager(header + table.draw()) -async def generate_header(pubkey, currency_symbol, ud_value): +def generate_header(pubkey, currency_symbol, ud_value): try: - idty = await wt.identity_of(pubkey) + idty = wt.identity_of(pubkey) except: idty = dict([("uid", "")]) - balance = await get_amount_from_pubkey(pubkey) + balance = get_amount_from_pubkey(pubkey) return "Transactions history from: {uid} {pubkey}\n\ Current balance: {balance} {currency}, {balance_ud} UD {currency} on {date}\n\ ".format( @@ -78,12 +77,12 @@ Current balance: {balance} {currency}, {balance_ud} UD {currency} on {date}\n\ ) -async def get_transactions_history(client, pubkey, received_txs, sent_txs): +def get_transactions_history(client, pubkey, received_txs, sent_txs): """ Get transaction history Store txs in Transaction object """ - tx_history = await client(history, pubkey) + tx_history = client(history, pubkey) currency = tx_history["currency"] for received in tx_history["history"]["received"]: @@ -104,7 +103,7 @@ def remove_duplicate_txs(received_txs, sent_txs): received_txs.remove(received_tx) -async def generate_table( +def generate_table( received_txs, sent_txs, pubkey, ud_value, currency_symbol, uids, full_pubkey ): """ @@ -115,10 +114,10 @@ async def generate_table( """ received_txs_table, sent_txs_table = list(), list() - await parse_received_tx( + parse_received_tx( received_txs_table, received_txs, pubkey, ud_value, uids, full_pubkey ) - await parse_sent_tx(sent_txs_table, sent_txs, pubkey, ud_value, uids, full_pubkey) + parse_sent_tx(sent_txs_table, sent_txs, pubkey, ud_value, uids, full_pubkey) txs_table = received_txs_table + sent_txs_table table_titles = [ @@ -134,7 +133,7 @@ async def generate_table( return txs_table -async def parse_received_tx( +def parse_received_tx( received_txs_table, received_txs, pubkey, ud_value, uids, full_pubkey ): """ @@ -149,7 +148,7 @@ async def parse_received_tx( for received_tx in received_txs: for issuer in received_tx.issuers: issuers.append(issuer) - identities = await wt.identities_from_pubkeys(issuers, uids) + identities = wt.identities_from_pubkeys(issuers, uids) for received_tx in received_txs: tx_list = list() tx_list.append(from_timestamp(received_tx.time, tz="local").format(ALL_DIGITAL)) @@ -165,7 +164,7 @@ async def parse_received_tx( received_txs_table.append(tx_list) -async def parse_sent_tx(sent_txs_table, sent_txs, pubkey, ud_value, uids, full_pubkey): +def parse_sent_tx(sent_txs_table, sent_txs, pubkey, ud_value, uids, full_pubkey): """ Extract recipients’ pubkeys from outputs Get identities from pubkeys @@ -181,7 +180,7 @@ async def parse_sent_tx(sent_txs_table, sent_txs, pubkey, ud_value, uids, full_p if output_available(output.condition, ne, pubkey): pubkeys.append(output.condition.left.pubkey) - identities = await wt.identities_from_pubkeys(pubkeys, uids) + identities = wt.identities_from_pubkeys(pubkeys, uids) for sent_tx in sent_txs: tx_list = list() tx_list.append(from_timestamp(sent_tx.time, tz="local").format(ALL_DIGITAL)) diff --git a/silkaj/wot.py b/silkaj/wot.py index 9d8cf096fa6cfbea0ae6ea523e0c37096ea2b724..b88d825009ef8aec829633de67f6121eb2608220 100644 --- a/silkaj/wot.py +++ b/silkaj/wot.py @@ -28,7 +28,7 @@ from silkaj.blockchain_tools import BlockchainParams from silkaj.constants import DATE from silkaj.crypto_tools import is_pubkey_and_check from silkaj.network_tools import ClientInstance -from silkaj.tools import coroutine +from silkaj.tools import message_exit from silkaj.tui import display_pubkey_and_checksum @@ -51,25 +51,24 @@ def get_sent_certifications(signed, time_first_block, params): help="Check received and sent certifications and consult the membership status of any given identity", ) @click.argument("uid_pubkey") -@coroutine -async def received_sent_certifications(uid_pubkey): +def received_sent_certifications(uid_pubkey): """ get searched id get id of received and sent certifications display in a table the result with the numbers """ client = ClientInstance().client - first_block = await client(blockchain.block, 1) + first_block = client(blockchain.block, 1) time_first_block = first_block["time"] checked_pubkey = is_pubkey_and_check(uid_pubkey) if checked_pubkey: uid_pubkey = checked_pubkey - identity, pubkey, signed = await choose_identity(uid_pubkey) + identity, pubkey, signed = choose_identity(uid_pubkey) certifications = OrderedDict() - params = await BlockchainParams().params - req = await client(wot.requirements, pubkey) + params = BlockchainParams().params + req = client(wot.requirements, pubkey) req = req["identities"][0] certifications["received_expire"] = list() certifications["received"] = list() @@ -104,8 +103,8 @@ async def received_sent_certifications(uid_pubkey): "✔: Certification available to be written or already written into the blockchain", ) ) - await membership_status(certifications, pubkey, req) - await client.close() + membership_status(certifications, pubkey, req) + client.close() def cert_written_in_the_blockchain(written_certs, certifieur): @@ -115,8 +114,8 @@ def cert_written_in_the_blockchain(written_certs, certifieur): return certifieur["uids"][0] -async def membership_status(certifications, pubkey, req): - params = await BlockchainParams().params +def membership_status(certifications, pubkey, req): + params = BlockchainParams().params if len(certifications["received"]) >= params["sigQty"]: print( "Membership expiration due to certification expirations: " @@ -124,7 +123,7 @@ async def membership_status(certifications, pubkey, req): len(certifications["received"]) - params["sigQty"] ] ) - member = await wt.is_member(pubkey) + member = wt.is_member(pubkey) if member: member = True print("member:", member) @@ -154,14 +153,13 @@ def date_approximation(block_id, time_first_block, avgentime): @click.command("lookup", help="User identifier and public key lookup") @click.argument("uid_pubkey") -@coroutine -async def id_pubkey_correspondence(uid_pubkey): +def id_pubkey_correspondence(uid_pubkey): checked_pubkey = is_pubkey_and_check(uid_pubkey) if checked_pubkey: uid_pubkey = checked_pubkey client = ClientInstance().client - lookups = await wt.wot_lookup(uid_pubkey) + lookups = wt.wot_lookup(uid_pubkey) await client.close() content = f"Public keys or user id found matching '{uid_pubkey}':\n" @@ -172,14 +170,14 @@ async def id_pubkey_correspondence(uid_pubkey): click.echo(content) -async def choose_identity(pubkey_uid): +def choose_identity(pubkey_uid): """ Get lookup from a pubkey or an uid Loop over the double lists: pubkeys, then uids If there is one uid, returns it If there is multiple uids, prompt a selector """ - lookups = await wt.wot_lookup(pubkey_uid) + lookups = wt.wot_lookup(pubkey_uid) # Generate table containing the choices identities_choices = {"id": [], "uid": [], "pubkey": [], "timestamp": []} diff --git a/silkaj/wot_tools.py b/silkaj/wot_tools.py index 061765755c230fe1746e9480aa2654b1e36d4693..0514837385c15d7ff4057db9df980cf4ae277195 100644 --- a/silkaj/wot_tools.py +++ b/silkaj/wot_tools.py @@ -15,17 +15,14 @@ You should have received a copy of the GNU Affero General Public License along with Silkaj. If not, see <https://www.gnu.org/licenses/>. """ -from asyncio import sleep - from duniterpy.api.bma import wot from duniterpy.api.errors import DuniterError -from silkaj.constants import ASYNC_SLEEP from silkaj.network_tools import ClientInstance from silkaj.tools import message_exit -async def identity_of(pubkey_uid): +def identity_of(pubkey_uid): """ Only works for members Not able to get corresponding uid from a non-member identity @@ -33,23 +30,23 @@ async def identity_of(pubkey_uid): """ client = ClientInstance().client try: - return await client(wot.identity_of, pubkey_uid) + return client(wot.identity_of, pubkey_uid) except ValueError as e: pass -async def is_member(pubkey_uid): +def is_member(pubkey_uid): """ Check identity is member If member, return corresponding identity, else: False """ try: - return await identity_of(pubkey_uid) + return identity_of(pubkey_uid) except: return False -async def wot_lookup(identifier): +def wot_lookup(identifier): """ :identifier: identity or pubkey in part or whole Return received and sent certifications lists of matching identities @@ -57,7 +54,7 @@ async def wot_lookup(identifier): """ client = ClientInstance().client try: - results = await client(wot.lookup, identifier) + results = client(wot.lookup, identifier) return results["results"] except DuniterError as e: message_exit(e.message) @@ -65,7 +62,7 @@ async def wot_lookup(identifier): pass -async def identities_from_pubkeys(pubkeys, uids): +def identities_from_pubkeys(pubkeys, uids): """ Make list of pubkeys unique, and remove empty strings Request identities @@ -77,8 +74,7 @@ async def identities_from_pubkeys(pubkeys, uids): identities = list() for pubkey in uniq_pubkeys: try: - identities.append(await identity_of(pubkey)) + identities.append(identity_of(pubkey)) except Exception as e: pass - await sleep(ASYNC_SLEEP) return identities