async def certification_confirmation(issuer, issuer_pubkey, pubkey_to_certify, idty_to_certify): cert = list() cert.append( ["Cert", "Issuer", "–>", "Recipient: Published: #block-hash date"]) 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_uid_date = (": #" + idty_timestamp[:15] + "… " + convert_time(block["time"], "all")) cert.append( ["ID", issuer["uid"], "–>", idty_to_certify["uid"] + block_uid_date]) cert.append([ "Pubkey", display_pubkey_and_checksum(issuer_pubkey), "–>", display_pubkey_and_checksum(pubkey_to_certify), ]) params = await BlockchainParams().params cert_begins = convert_time(time(), "date") cert_ends = convert_time(time() + params["sigValidity"], "date") cert.append(["Valid", cert_begins, "—>", cert_ends]) echo(tabulate(cert, tablefmt="fancy_grid")) if not confirm("Do you confirm sending this certification?"): await client.close() sys.exit(SUCCESS_EXIT_STATUS)
async def id_pubkey_correspondence(id_pubkey): client = ClientInstance().client # determine if id_pubkey is a pubkey checked_pubkey = is_pubkey_and_check(id_pubkey) if checked_pubkey: id_pubkey = checked_pubkey try: idty = await identity_of(id_pubkey) print( "{} public key corresponds to identity: {}".format( display_pubkey_and_checksum(id_pubkey), idty["uid"] ) ) except: message_exit("No matching identity") # if not ; then it is a uid else: pubkeys = await wot_lookup(id_pubkey) print("Public keys found matching '{}':\n".format(id_pubkey)) for pubkey in pubkeys: print("→", display_pubkey_and_checksum(pubkey["pubkey"]), end=" ") try: corresponding_id = await client(wot.identity_of, pubkey["pubkey"]) print("↔ " + corresponding_id["uid"]) except: print("") await client.close()
def test_display_pubkey_and_checksum(pubkey, checksum): assert pubkey + ":" + checksum == display_pubkey_and_checksum(pubkey) assert pubkey[: SHORT_PUBKEY_SIZE] + "…:" + checksum == display_pubkey_and_checksum( pubkey, short=True) assert pubkey[:14] + "…:" + checksum == display_pubkey_and_checksum( pubkey, short=True, length=14)
def assign_idty_from_pubkey(pubkey, identities): idty = display_pubkey_and_checksum(pubkey, True) for identity in identities: if pubkey == identity["pubkey"]: idty = "{0} - {1}".format( identity["uid"], display_pubkey_and_checksum(pubkey, True) ) return idty
def display_sent_tx(outputAddress, amount): print( " - To: ", display_pubkey_and_checksum(outputAddress), "\n - Amount: ", amount / 100, )
async def show_amount_from_pubkey(pubkey, inputs_balance): 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() # if `pubkey` is a pubkey, get pubkey:checksum if pubkey != "Total": pubkey = display_pubkey_and_checksum(pubkey) # display balance table display = list() display.append(["Balance of pubkey", pubkey]) if totalAmountInput - balance != 0: display_amount(display, "Blockchain", balance, ud_value, currency_symbol) display_amount( display, "Pending transaction", (totalAmountInput - balance), ud_value, currency_symbol, ) display_amount(display, "Total amount", totalAmountInput, ud_value, currency_symbol) display.append([ "Total relative to M/N", "{0} x M/N".format(round(totalAmountInput / average, 2)), ]) echo(tabulate(display, tablefmt="fancy_grid"))
async def test_display_confirmation_table( patched_wot_requirements, monkeypatch, capsys ): monkeypatch.setattr(bma.wot, "requirements", patched_wot_requirements) monkeypatch.setattr(bma.blockchain, "parameters", patched_params) monkeypatch.setattr(bma.blockchain, "block", patched_block) client = ClientInstance().client identities_requirements = await client(bma.wot.requirements, pubkey) for identity_requirements in identities_requirements["identities"]: if identity_requirements["uid"] == identity_uid: membership_expires = identity_requirements["membershipExpiresIn"] pending_expires = identity_requirements["membershipPendingExpiresIn"] pending_memberships = identity_requirements["pendingMemberships"] break table = list() if membership_expires: expires = pendulum.now().add(seconds=membership_expires).diff_for_humans() table.append(["Expiration date of current membership", expires]) if pending_memberships: line = [ "Number of pending membership(s) in the mempool", len(pending_memberships), ] table.append(line) expiration = pendulum.now().add(seconds=pending_expires).diff_for_humans() table.append(["Pending membership documents will expire", expiration]) table.append(["User Identifier (UID)", identity_uid]) table.append(["Public Key", display_pubkey_and_checksum(pubkey)]) table.append(["Block Identity", str(identity_timestamp)[:45] + "…"]) block = await client(bma.blockchain.block, identity_timestamp.number) table.append( ["Identity published", pendulum.from_timestamp(block["time"]).format("LL")], ) params = await BlockchainParams().params membership_validity = ( pendulum.now().add(seconds=params["msValidity"]).diff_for_humans() ) table.append(["Expiration date of new membership", membership_validity]) membership_mempool = ( pendulum.now().add(seconds=params["msPeriod"]).diff_for_humans() ) table.append( ["Expiration date of new membership from the mempool", membership_mempool] ) expected = tabulate(table, tablefmt="fancy_grid") + "\n" await membership.display_confirmation_table( identity_uid, pubkey, identity_timestamp ) captured = capsys.readouterr() assert expected == captured.out
async def display_confirmation_table(identity_uid, pubkey, identity_timestamp): """ Check whether there is pending memberships already in the mempool Display their expiration date Actually, it works sending a membership document even if the time between two renewals is not awaited as for the certification """ client = ClientInstance().client identities_requirements = await client(bma.wot.requirements, pubkey) for identity_requirements in identities_requirements["identities"]: if identity_requirements["uid"] == identity_uid: membership_expires = identity_requirements["membershipExpiresIn"] pending_expires = identity_requirements["membershipPendingExpiresIn"] pending_memberships = identity_requirements["pendingMemberships"] break table = list() if membership_expires: expires = pendulum.now().add(seconds=membership_expires).diff_for_humans() table.append(["Expiration date of current membership", expires]) if pending_memberships: line = [ "Number of pending membership(s) in the mempool", len(pending_memberships), ] table.append(line) expiration = pendulum.now().add(seconds=pending_expires).diff_for_humans() table.append(["Pending membership documents will expire", expiration]) table.append(["User Identifier (UID)", identity_uid]) table.append(["Public Key", display_pubkey_and_checksum(pubkey)]) table.append(["Block Identity", str(identity_timestamp)[:45] + "…"]) block = await client(bma.blockchain.block, identity_timestamp.number) table.append( ["Identity published", pendulum.from_timestamp(block["time"]).format("LL")] ) params = await BlockchainParams().params membership_validity = ( pendulum.now().add(seconds=params["msValidity"]).diff_for_humans() ) table.append(["Expiration date of new membership", membership_validity]) membership_mempool = ( pendulum.now().add(seconds=params["msPeriod"]).diff_for_humans() ) table.append( ["Expiration date of new membership from the mempool", membership_mempool] ) click.echo(tabulate(table, tablefmt="fancy_grid"))
async 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) 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) certifications = OrderedDict() params = await BlockchainParams().params req = await client(wot.requirements, pubkey) req = req["identities"][0] certifications["received_expire"] = list() certifications["received"] = list() for cert in identity["others"]: certifications["received_expire"].append( expiration_date_from_block_id( cert["meta"]["block_number"], time_first_block, params ) ) certifications["received"].append( cert_written_in_the_blockchain(req["certifications"], cert) ) ( certifications["sent"], certifications["sent_expire"], ) = get_sent_certifications(signed, time_first_block, params) nbr_sent_certs = len(certifications["sent"]) if "sent" in certifications else 0 print( "{0} ({1}) from block #{2}\nreceived {3} and sent {4}/{5} certifications:\n{6}\n{7}\n".format( identity["uid"], display_pubkey_and_checksum(pubkey, True), identity["meta"]["timestamp"][:15] + "…", len(certifications["received"]), nbr_sent_certs, params["sigStock"], tabulate( certifications, headers="keys", tablefmt="orgtbl", stralign="center", ), "✔: Certifications written into the blockchain", ) ) await membership_status(certifications, pubkey, req) await client.close()
async def test_display_pubkey(message, pubkey, id, monkeypatch): monkeypatch.setattr("silkaj.wot.is_member", patched.is_member) expected = [[ message + " (pubkey:checksum)", display_pubkey_and_checksum(pubkey) ]] if id: expected.append([message + " (id)", id]) tx = list() await display_pubkey(tx, message, pubkey) assert tx == expected
async def generate_header(pubkey, currency_symbol, ud_value): try: idty = await identity_of(pubkey) except: idty = dict([("uid", "")]) balance = await get_amount_from_pubkey(pubkey) return "Transactions history from: {uid} {pubkey}\n\ Current balance: {balance} {currency}, {balance_ud} UD {currency} on the {date}\n\ ".format( uid=idty["uid"], pubkey=display_pubkey_and_checksum(pubkey), currency=currency_symbol, balance=balance[1] / 100, balance_ud=round(balance[1] / ud_value, 2), date=convert_time(time(), "all"), )
async 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 wot_lookup(pubkey_uid) # Generate table containing the choices identities_choices = {"id": [], "uid": [], "pubkey": [], "timestamp": []} for pubkey_index, lookup in enumerate(lookups): for uid_index, identity in enumerate(lookup["uids"]): identities_choices["id"].append(str(pubkey_index) + str(uid_index)) identities_choices["pubkey"].append( display_pubkey_and_checksum(lookup["pubkey"]) ) identities_choices["uid"].append(identity["uid"]) identities_choices["timestamp"].append( identity["meta"]["timestamp"][:20] + "…" ) identities = len(identities_choices["uid"]) if identities == 1: pubkey_index = 0 uid_index = 0 elif identities > 1: table = tabulate(identities_choices, headers="keys", tablefmt="orgtbl") click.echo(table) # Loop till the passed value is in identities_choices message = "Which identity would you like to select (id)?" selected_id = None while selected_id not in identities_choices["id"]: selected_id = click.prompt(message) pubkey_index = int(selected_id[:-1]) uid_index = int(selected_id[-1:]) return ( lookups[pubkey_index]["uids"][uid_index], lookups[pubkey_index]["pubkey"], lookups[pubkey_index]["signed"], )
def check_transaction_values(comment, outputAddresses, outputBackChange, enough_source, issuer_pubkey): """ Check the comment format Check the pubkeys and the checksums of the recipients and the outputbackchange In case of a valid checksum, assign and return the pubkey without the checksum Check the balance is big enough for the transaction """ checkComment(comment) for i, outputAddress in enumerate(outputAddresses): if check_pubkey_format(outputAddress): outputAddresses[i] = validate_checksum(outputAddress) if outputBackChange: if check_pubkey_format(outputBackChange): outputBackChange = validate_checksum(outputBackChange) if enough_source: message_exit( display_pubkey_and_checksum(issuer_pubkey) + " pubkey doesn’t have enough money for this transaction.") return outputBackChange
async def generate_and_send_transaction( key, issuers, tx_amounts, listinput_and_amount, outputAddresses, Comment, OutputbackChange=None, ): """ Display sent transaction Generate, sign, and send transaction document """ intermediate_tx = listinput_and_amount[2] if intermediate_tx: print("Generate Change Transaction") else: print("Generate Transaction:") print(" - From: " + display_pubkey_and_checksum(issuers)) for tx_amount, outputAddress in zip(tx_amounts, outputAddresses): display_sent_tx(outputAddress, tx_amount) print(" - Total: " + str(sum(tx_amounts) / 100)) client = ClientInstance().client transaction = await generate_transaction_document( issuers, tx_amounts, listinput_and_amount, outputAddresses, Comment, OutputbackChange, ) transaction.sign([key]) response = await client(process, transaction.signed_raw()) if response.status == 200: print("Transaction successfully sent.") else: message_exit("Error while publishing transaction: {0}".format( await response.text()))