From f119922c247e151b31e457be1f2a87c4f3fac181 Mon Sep 17 00:00:00 2001
From: Moul <moul@moul.re>
Date: Tue, 10 Jul 2018 11:41:45 +0200
Subject: [PATCH] [enh] #42: head_block and params: retrieve once and use in
 the program.

---
 silkaj/cert.py     | 15 ++++++-------
 silkaj/commands.py | 53 ++++++++++++++++++++++------------------------
 silkaj/money.py    | 15 ++++++-------
 silkaj/silkaj.py   | 16 +++++++-------
 silkaj/tx.py       | 32 +++++++++++++---------------
 silkaj/wot.py      |  3 +--
 6 files changed, 63 insertions(+), 71 deletions(-)

diff --git a/silkaj/cert.py b/silkaj/cert.py
index bcd6a34f..e27ccc70 100644
--- a/silkaj/cert.py
+++ b/silkaj/cert.py
@@ -3,15 +3,14 @@ from tabulate import tabulate
 
 from silkaj.auth import auth_method
 from silkaj.tools import get_publickey_from_seed, message_exit, sign_document_from_seed
-from silkaj.network_tools import get_current_block, post_request
+from silkaj.network_tools import post_request
 from silkaj.license import license_approval
 from silkaj.constants import NO_MATCHING_ID
 from silkaj.wot import is_member, get_pubkey_from_id, get_pubkeys_from_id,\
         get_uid_from_pubkey
 
 
-def send_certification(ep, cli_args):
-    current_blk = get_current_block(ep)
+def send_certification(ep, head_block, cli_args):
     certified_uid = cli_args.subsubcmd
     certified_pubkey = get_pubkey_from_id(ep, certified_uid)
 
@@ -20,7 +19,7 @@ def send_certification(ep, cli_args):
         message_exit(NO_MATCHING_ID)
 
     # Display license and ask for confirmation
-    license_approval(current_blk["currency"])
+    license_approval(head_block["currency"])
 
     # Authentication
     seed = auth_method(cli_args)
@@ -44,7 +43,7 @@ def send_certification(ep, cli_args):
     # Certification confirmation
     if not certification_confirmation(issuer_id, issuer_pubkey, certified_uid, certified_pubkey):
         return
-    cert_doc = generate_certification_document(id_lookup, current_blk, issuer_pubkey, certified_uid)
+    cert_doc = generate_certification_document(id_lookup, head_block, issuer_pubkey, certified_uid)
     cert_doc += sign_document_from_seed(cert_doc, seed) + "\n"
 
     # Send certification document
@@ -62,13 +61,13 @@ def certification_confirmation(issuer_id, issuer_pubkey, certified_uid, certifie
         return True
 
 
-def generate_certification_document(id_lookup, current_blk, issuer_pubkey, certified_uid):
+def generate_certification_document(id_lookup, head_block, issuer_pubkey, certified_uid):
     return "Version: 10\n\
 Type: Certification\n\
-Currency: " + current_blk["currency"] + "\n\
+Currency: " + head_block["currency"] + "\n\
 Issuer: " + issuer_pubkey + "\n\
 IdtyIssuer: " + id_lookup["pubkey"] + "\n\
 IdtyUniqueID: " + certified_uid + "\n\
 IdtyTimestamp: " + id_lookup["uids"][0]["meta"]["timestamp"] + "\n\
 IdtySignature: " + id_lookup["uids"][0]["self"] + "\n\
-CertTimestamp: " + str(current_blk["number"]) + "-" + current_blk["hash"] + "\n"
+CertTimestamp: " + str(head_block["number"]) + "-" + head_block["hash"] + "\n"
diff --git a/silkaj/commands.py b/silkaj/commands.py
index 60a05edd..2daa81ac 100644
--- a/silkaj/commands.py
+++ b/silkaj/commands.py
@@ -11,22 +11,21 @@ from silkaj.tools import convert_time, get_currency_symbol, message_exit
 from silkaj.constants import NO_MATCHING_ID
 
 
-def currency_info(ep):
+def currency_info(ep, head_block):
     info_type = ["newcomers", "certs", "actives", "leavers", "excluded", "ud", "tx"]
     i, info_data = 0, dict()
     while (i < len(info_type)):
             info_data[info_type[i]] = get_request(ep, "blockchain/with/" + info_type[i])["result"]["blocks"]
             i += 1
-    current = get_current_block(ep)
     system("clear")
-    print("Connected to node:", ep[best_node(ep, 1)], ep["port"],
-    "\nCurrent block number:", current["number"],
-    "\nCurrency name:", get_currency_symbol(current["currency"]),
-    "\nNumber of members:", current["membersCount"],
-    "\nMinimal Proof-of-Work:", current["powMin"],
-    "\nCurrent time:", convert_time(current["time"], "all"),
-    "\nMedian time:", convert_time(current["medianTime"], "all"),
-    "\nDifference time:", convert_time(current["time"] - current["medianTime"], "hour"),
+    print("Connected to node:", ep[best_node(ep, False)], ep["port"],
+    "\nCurrent block number:", head_block["number"],
+    "\nCurrency name:", get_currency_symbol(head_block["currency"]),
+    "\nNumber of members:", head_block["membersCount"],
+    "\nMinimal Proof-of-Work:", head_block["powMin"],
+    "\nCurrent time:", convert_time(head_block["time"], "all"),
+    "\nMedian time:", convert_time(head_block["medianTime"], "all"),
+    "\nDifference time:", convert_time(head_block["time"] - head_block["medianTime"], "hour"),
     "\nNumber of blocks containing: \
      \n- new comers:", len(info_data["newcomers"]),
     "\n- Certifications:", len(info_data["certs"]),
@@ -159,11 +158,10 @@ def network_info(ep, discover):
     print(tabulate(endpoints, headers="keys", tablefmt="orgtbl", stralign="center"))
 
 
-def list_issuers(ep, nbr, last):
-    current_blk = get_current_block(ep)
-    current_nbr = current_blk["number"]
+def list_issuers(ep, head_block, nbr, last):
+    current_nbr = head_block["number"]
     if nbr == 0:
-        nbr = current_blk["issuersFrame"]
+        nbr = head_block["issuersFrame"]
     url = "blockchain/blocks/" + str(nbr) + "/" + str(current_nbr - nbr + 1)
     blocks, list_issuers, j = get_request(ep, url), list(), 0
     issuers_dict = dict()
@@ -217,28 +215,27 @@ def list_issuers(ep, nbr, last):
         tabulate(sorted_list, headers="keys", tablefmt="orgtbl", floatfmt=".1f", stralign="center")))
 
 
-def argos_info(ep):
+def argos_info(ep, head_block):
     info_type = ["newcomers", "certs", "actives", "leavers", "excluded", "ud", "tx"]
     pretty_names = {'g1': 'Äž1', 'gtest': 'Äžtest'}
     i, info_data = 0, dict()
     while (i < len(info_type)):
             info_data[info_type[i]] = get_request(ep, "blockchain/with/" + info_type[i])["result"]["blocks"]
             i += 1
-    current = get_current_block(ep)
-    pretty = current["currency"]
-    if current["currency"] in pretty_names:
-        pretty = pretty_names[current["currency"]]
+    pretty = head_block["currency"]
+    if head_block["currency"] in pretty_names:
+        pretty = pretty_names[head_block["currency"]]
     print(pretty, "|")
     print("---")
-    href = 'href=http://%s:%s/' % (ep[best_node(ep, 1)], ep["port"])
-    print("Connected to node:", ep[best_node(ep, 1)], ep["port"], "|", href,
-    "\nCurrent block number:", current["number"],
-    "\nCurrency name:", get_currency_symbol(current["currency"]),
-    "\nNumber of members:", current["membersCount"],
-    "\nMinimal Proof-of-Work:", current["powMin"],
-    "\nCurrent time:", convert_time(current["time"], "all"),
-    "\nMedian time:", convert_time(current["medianTime"], "all"),
-    "\nDifference time:", convert_time(current["time"] - current["medianTime"], "hour"),
+    href = 'href=http://%s:%s/' % (ep[best_node(ep, False)], ep["port"])
+    print("Connected to node:", ep[best_node(ep, False)], ep["port"], "|", href,
+    "\nCurrent block number:", head_block["number"],
+    "\nCurrency name:", get_currency_symbol(head_block["currency"]),
+    "\nNumber of members:", head_block["membersCount"],
+    "\nMinimal Proof-of-Work:", head_block["powMin"],
+    "\nCurrent time:", convert_time(head_block["time"], "all"),
+    "\nMedian time:", convert_time(head_block["medianTime"], "all"),
+    "\nDifference time:", convert_time(head_block["time"] - head_block["medianTime"], "hour"),
     "\nNumber of blocks containing… \
      \n-- new comers:", len(info_data["newcomers"]),
     "\n-- Certifications:", len(info_data["certs"]),
diff --git a/silkaj/money.py b/silkaj/money.py
index fb7e5f58..21c67e82 100644
--- a/silkaj/money.py
+++ b/silkaj/money.py
@@ -1,10 +1,10 @@
-from silkaj.network_tools import get_request, get_current_block
+from silkaj.network_tools import get_request
 from silkaj.tools import get_currency_symbol, get_publickey_from_seed
 from silkaj.auth import auth_method
 from silkaj.wot import check_public_key
 
 
-def cmd_amount(ep, cli_args):
+def cmd_amount(ep, cli_args, config, head_block, ud_value, currency_symbol):
     if not cli_args.subsubcmd.startswith("--"):
         pubkeys = cli_args.subsubcmd.split(":")
         for pubkey in pubkeys:
@@ -13,8 +13,8 @@ def cmd_amount(ep, cli_args):
                 return
         total = [0, 0]
         for pubkey in pubkeys:
-            value = get_amount_from_pubkey(ep, pubkey)
-            show_amount_from_pubkey(ep, pubkey, value)
+            value = get_amount_from_pubkey(ep, head_block, pubkey)
+            show_amount_from_pubkey(pubkey, value, ud_value, currency_symbol)
             total[0] += value[0]
             total[1] += value[1]
         if (len(pubkeys) > 1):
@@ -22,7 +22,7 @@ def cmd_amount(ep, cli_args):
     else:
         seed = auth_method(cli_args)
         pubkey = get_publickey_from_seed(seed)
-        show_amount_from_pubkey(ep, pubkey, get_amount_from_pubkey(ep, pubkey))
+        show_amount_from_pubkey(pubkey, get_amount_from_pubkey(ep, head_block, pubkey), ud_value, currency_symbol)
 
 
 def show_amount_from_pubkey(ep, pubkey, value):
@@ -50,7 +50,7 @@ def show_amount_from_pubkey(ep, pubkey, value):
     print("Total Quantitative =",  round(totalAmountInput / 100, 2), currency_symbol + "\n")
 
 
-def get_amount_from_pubkey(ep, pubkey):
+def get_amount_from_pubkey(ep, head_block, pubkey):
     sources = get_request(ep, "tx/sources/" + pubkey)["sources"]
 
     listinput = []
@@ -69,8 +69,7 @@ def get_amount_from_pubkey(ep, pubkey):
     pendings = history["sending"] + history["receiving"] + history["pending"]
     # print(pendings)
 
-    current_blk = get_current_block(ep)
-    last_block_number = int(current_blk["number"])
+    last_block_number = int(head_block["number"])
 
     # add pending output
     for pending in pendings:
diff --git a/silkaj/silkaj.py b/silkaj/silkaj.py
index f978837a..d514df44 100644
--- a/silkaj/silkaj.py
+++ b/silkaj/silkaj.py
@@ -107,7 +107,7 @@ def manage_cmd(ep, cli_args):
     if cli_args.subcmd == "about":
         about()
     elif cli_args.subcmd == "info":
-        currency_info(ep)
+        currency_info(ep, head_block)
 
     elif cli_args.subcmd == "diffi":
         difficulties(ep)
@@ -120,19 +120,19 @@ def manage_cmd(ep, cli_args):
         network_info(ep, cli_args.contains_switches("discover"))
 
     elif cli_args.subcmd == "issuers" and cli_args.subsubcmd and int(cli_args.subsubcmd) >= 0:
-        list_issuers(ep, int(cli_args.subsubcmd), cli_args.contains_switches('last'))
+        list_issuers(ep, head_block, int(cli_args.subsubcmd), cli_args.contains_switches('last'))
 
     elif cli_args.subcmd == "argos":
-        argos_info(ep)
+        argos_info(ep, head_block)
 
-    elif cli_args.subcmd == "amount" and cli_args.subsubcmd:
-        cmd_amount(ep, cli_args)
+    elif cli_args.subcmd == "amount":
+        cmd_amount(ep, cli_args, currency_config, head_block, ud_value, currency_symbol)
 
     elif cli_args.subcmd == "tx" or cli_args.subcmd == "transaction":
-        send_transaction(ep, cli_args)
+        send_transaction(ep, cli_args, head_block, ud_value, currency_symbol)
 
     elif cli_args.subcmd == "cert":
-        send_certification(ep, cli_args)
+        send_certification(ep, head_block, cli_args)
 
     elif cli_args.subcmd == "generate_auth_file":
         generate_auth_file(cli_args)
@@ -141,7 +141,7 @@ def manage_cmd(ep, cli_args):
         id_pubkey_correspondence(ep, cli_args.subsubcmd)
 
     elif cli_args.subcmd == "wot":
-        received_sent_certifications(ep, cli_args.subsubcmd)
+        received_sent_certifications(ep, params, cli_args.subsubcmd)
 
     elif cli_args.subcmd == "license":
         display_license()
diff --git a/silkaj/tx.py b/silkaj/tx.py
index 96aa30a4..befcb2bf 100644
--- a/silkaj/tx.py
+++ b/silkaj/tx.py
@@ -4,8 +4,8 @@ from time import sleep
 import urllib
 
 from tabulate import tabulate
-from silkaj.network_tools import get_request, post_request, get_current_block
-from silkaj.tools import get_currency_symbol, get_publickey_from_seed, sign_document_from_seed,\
+from silkaj.network_tools import get_request, post_request
+from silkaj.tools import get_publickey_from_seed, sign_document_from_seed,\
         check_public_key, message_exit
 from silkaj.auth import auth_method
 from silkaj.wot import get_uid_from_pubkey
@@ -13,7 +13,7 @@ from silkaj.money import get_last_ud_value, get_amount_from_pubkey
 from silkaj.constants import NO_MATCHING_ID
 
 
-def send_transaction(ep, cli_args):
+def send_transaction(ep, cli_args, head_block, ud_value, currency_symbol):
     """
     Main function
     """
@@ -22,14 +22,14 @@ def send_transaction(ep, cli_args):
     seed = auth_method(cli_args)
     issuer_pubkey = get_publickey_from_seed(seed)
 
-    pubkey_amount = get_amount_from_pubkey(ep, issuer_pubkey)[0]
+    pubkey_amount = get_amount_from_pubkey(ep, head_block, issuer_pubkey)[0]
     outputAddresses = output.split(':')
     check_transaction_values(comment, outputAddresses, outputBackChange, pubkey_amount < amount * len(outputAddresses), issuer_pubkey)
 
     if cli_args.contains_switches('yes') or cli_args.contains_switches('y') or \
         input(tabulate(transaction_confirmation(ep, issuer_pubkey, amount, ud, outputAddresses, comment),
         tablefmt="fancy_grid") + "\nDo you confirm sending this transaction? [yes/no]: ") == "yes":
-        generate_and_send_transaction(ep, seed, issuer_pubkey, amount, outputAddresses, comment, allSources, outputBackChange)
+        generate_and_send_transaction(ep, head_block, seed, issuer_pubkey, amount, outputAddresses, comment, allSources, outputBackChange)
 
 
 def cmd_transaction(cli_args, ud):
@@ -92,10 +92,10 @@ def transaction_confirmation(ep, issuer_pubkey, amount, ud, outputAddresses, com
     return tx
 
 
-def generate_and_send_transaction(ep, seed, issuers, AmountTransfered, outputAddresses, Comment="", all_input=False, OutputbackChange=None):
+def generate_and_send_transaction(ep, head_block, seed, issuers, AmountTransfered, outputAddresses, Comment="", all_input=False, OutputbackChange=None):
 
     while True:
-        listinput_and_amount = get_list_input_for_transaction(ep, issuers, AmountTransfered * len(outputAddresses), all_input)
+        listinput_and_amount = get_list_input_for_transaction(ep, head_block, issuers, AmountTransfered * len(outputAddresses), all_input)
         intermediatetransaction = listinput_and_amount[2]
 
         if intermediatetransaction:
@@ -104,7 +104,7 @@ def generate_and_send_transaction(ep, seed, issuers, AmountTransfered, outputAdd
             print("   - From:    " + issuers)
             print("   - To:      " + issuers)
             print("   - Amount:  " + str(totalAmountInput / 100))
-            transaction = generate_transaction_document(ep, issuers, totalAmountInput, listinput_and_amount, outputAddresses, "Change operation")
+            transaction = generate_transaction_document(ep, head_block, issuers, totalAmountInput, listinput_and_amount, outputAddresses, "Change operation")
             transaction += sign_document_from_seed(transaction, seed) + "\n"
             post_request(ep, "tx/process", "transaction=" + urllib.parse.quote_plus(transaction))
             print("Change Transaction successfully sent.")
@@ -119,7 +119,7 @@ def generate_and_send_transaction(ep, seed, issuers, AmountTransfered, outputAdd
                 print("   - Amount:  " + str(listinput_and_amount[1] / 100))
             else:
                 print("   - Amount:  " + str(AmountTransfered / 100 * len(outputAddresses)))
-            transaction = generate_transaction_document(ep, issuers, AmountTransfered, listinput_and_amount, outputAddresses, Comment, OutputbackChange)
+            transaction = generate_transaction_document(ep, head_block, issuers, AmountTransfered, listinput_and_amount, outputAddresses, Comment, OutputbackChange)
             transaction += sign_document_from_seed(transaction, seed) + "\n"
 
             post_request(ep, "tx/process", "transaction=" + urllib.parse.quote_plus(transaction))
@@ -127,17 +127,16 @@ def generate_and_send_transaction(ep, seed, issuers, AmountTransfered, outputAdd
             break
 
 
-def generate_transaction_document(ep, issuers, AmountTransfered, listinput_and_amount, outputAddresses, Comment="", OutputbackChange=None):
+def generate_transaction_document(ep, head_block, issuers, AmountTransfered, listinput_and_amount, outputAddresses, Comment="", OutputbackChange=None):
 
     totalAmountTransfered = AmountTransfered * len(outputAddresses)
 
     listinput = listinput_and_amount[0]
     totalAmountInput = listinput_and_amount[1]
 
-    current_blk = get_current_block(ep)
-    currency_name = current_blk["currency"]
-    blockstamp_current = str(current_blk["number"]) + "-" + str(current_blk["hash"])
-    curentUnitBase = current_blk["unitbase"]
+    currency_name = head_block["currency"]
+    blockstamp_current = str(head_block["number"]) + "-" + str(head_block["hash"])
+    curentUnitBase = head_block["unitbase"]
 
     if not OutputbackChange:
         OutputbackChange = issuers
@@ -196,7 +195,7 @@ def generate_transaction_document(ep, issuers, AmountTransfered, listinput_and_a
     return transaction_document
 
 
-def get_list_input_for_transaction(ep, pubkey, TXamount, allinput=False):
+def get_list_input_for_transaction(ep, head_block, pubkey, TXamount, allinput=False):
     # real source in blockchain
     sources = get_request(ep, "tx/sources/" + pubkey)["sources"]
     if sources is None:
@@ -211,8 +210,7 @@ def get_list_input_for_transaction(ep, pubkey, TXamount, allinput=False):
     history = get_request(ep, "tx/history/" + pubkey + "/pending")["history"]
     pendings = history["sending"] + history["receiving"] + history["pending"]
 
-    current_blk = get_current_block(ep)
-    last_block_number = int(current_blk["number"])
+    last_block_number = int(head_block["number"])
 
     # add pending output
     for pending in pendings:
diff --git a/silkaj/wot.py b/silkaj/wot.py
index 40712cf7..64c029d9 100644
--- a/silkaj/wot.py
+++ b/silkaj/wot.py
@@ -18,7 +18,7 @@ def get_sent_certifications(certs, time_first_block, params):
     return sent, expire
 
 
-def received_sent_certifications(ep, id):
+def received_sent_certifications(ep, params, id):
     """
     check id exist
     many identities could exist
@@ -26,7 +26,6 @@ def received_sent_certifications(ep, id):
     get id of received and sent certifications
     display on a chart the result with the numbers
     """
-    params = get_request(ep, "blockchain/parameters")
     time_first_block = get_request(ep, "blockchain/block/1")["time"]
     if get_pubkeys_from_id(ep, id) == NO_MATCHING_ID:
         message_exit(NO_MATCHING_ID)
-- 
GitLab