Exemple #1
0
    def run(self):
        """
        Run method of network status command.
        Fetches status of peer using bpl_api.
        If request is unsuccessful then a BPLClientNetworkException is raised.
        Otherwise display the status using an ascii_table.Table object

        :return: (None)
        """

        status = Client(NetworkConfig.get_peer()).api("blocks").status()

        if not status["success"]:
            print(BPLClientNetworkException({
                "message": "cannot get status from network",
                "error": status["error"]
            }),
                  file=sys.stderr)
            sys.exit(1)

        status.pop("success", None)
        status["reward"] = status["reward"]["reward"]
        status = SortedDictionary(status)

        print("\nNetwork Summary")
        print(Table([status.names(), status.values()]))
Exemple #2
0
    def run(self):
        """
        Run method for account transactions command.
        Requests transactions of an address using bpl_api.
        If response from request is successful then displays transactions using a ascii_table.Table object.
        If response from request is unsuccessful then a BPLClientAccountsException is raised.

        :return: (None)
        """

        bpl_transactions = Client(NetworkConfig.get_peer()).api("transactions")
        NetworkInterface.use(NetworkConfig.get_config_identifier())

        response = bpl_transactions.all_transactions({
            "senderId":
            self._address,
            "recipientId":
            self._address,
            "orderBy":
            "timestamp:desc"
        })

        if not response["success"]:
            print(BPLClientAccountsException({
                "message": "Failed to fetch transactions.",
                "error": response["error"]
            }),
                  file=sys.stderr)
            sys.exit(1)

        transactions = self._parse_transactions(response["transactions"])

        print("\nTransactions (Address: {0})".format(self._address))
        print(
            Table([{
                "Header": "Transaction ID",
                "Contents": transactions["id"]
            }, {
                "Header":
                "Timestamp",
                "Contents":
                list(
                    map(lambda x: Time.get_real_time(int(x)),
                        transactions["timestamp"]))
            }, {
                "Header": "Sender",
                "Contents": transactions["senderId"]
            }, {
                "Header": "Recipient",
                "Contents": transactions["recipientId"]
            }, {
                "Header": "Amount",
                "Contents": transactions["amount"]
            }, {
                "Header": "Fee",
                "Contents": transactions["fee"]
            }, {
                "Header": "Confirmations",
                "Contents": transactions["confirmations"]
            }]))
Exemple #3
0
    def run(self):
        """
        Run method for account create command
        Generates a secret passphrase using BIP39 mnemonic generator.
        Private and public keys are then calculated using bpl_lib.crypto.Keys and
        the address is generate from the secret passphrase using bpl_lib.address.Address.
        The secret passphrase, private key, public key and address are then displayed in a
        ascii_table.Table object.

        :return: (None)
        """

        NetworkInterface.use(NetworkConfig.get_config_identifier())

        secret_passphrase = Mnemonic("english").generate(256)

        account = SortedDictionary({
            "secret passphrase":
            secret_passphrase,
            "private key":
            Keys(secret_passphrase).get_private_key(),
            "public key":
            Keys(secret_passphrase).get_public_key(),
            "address":
            Address.from_secret(secret_passphrase)
        })

        print("\nAccount")
        print(Table([account.names(), account.values()]))
Exemple #4
0
    def run(self):
        """
        Run method for config setup

        :return: (None)
        """

        qubits = input("Enter number of qubits in the quantum computer: ")

        if not regular_expression.match(QUBITS_REGEX, qubits):
            print(QASMConfigException({
                "message": "invalid number of qubits",
                "format": "[0-9]{1,2}",
                "qubits": qubits
            }), file=sys.stderr)
            return

        config = {
            "qubits": int(qubits)
        }
        write_file(QC_CONFIG, json.dumps(config))

        config = SortedDictionary(config)
        print("\nQuantum Computer Config")
        print(Table([config.names(), config.values()]))
Exemple #5
0
    def run(self):
        """
        Run method for network peers command.
        Fetches peers from peer using bpl_api.
        If request is unsuccessful then a BPLClientNetworkException is raised.
        Otherwise filter peers based on response status of peers and
        then display the filtered peers using an ascii_table.Table object.

        :return: (None)
        """

        peers = Client(NetworkConfig.get_peer()).api("peers").all_peers(limit=100)

        if not peers["success"]:
            print(BPLClientNetworkException({
                "message": "cannot get peers from network",
                "error": peers["error"]
            }), file=sys.stderr)
            sys.exit(1)

        filtered_peers = sorted(map(lambda x: "{0}:{1}".format(x["ip"], x["port"]), filter(
            lambda x: x["status"] == "OK", peers["peers"]
        )))

        print("\nPeers (Seed Peer: {0})".format(NetworkConfig.get_peer()))
        print(Table([{
            "Header": "Peers",
            "Contents": filtered_peers
        }]))
Exemple #6
0
    def run(self):
        """
        Run method for message sign command
        Prints prompt for the user to enter secret passphrase (input is masked).
        Uses bpl_lib.crypto.Signature to sign message.
        Then displays the result using a ascii_table.Table object.

        :return: (None)
        """

        NetworkInterface.use(NetworkConfig.get_config_identifier())

        secret_passphrase = getpass(prompt="Enter secret passphrase: ")

        signature = Signature(secret_passphrase).sign(self._message)
        signature = SortedDictionary({
            "public key":
            signature["public_key"],
            "address":
            Address.from_public_key(signature["public_key"]),
            "signature":
            signature["signature"]
        })

        print("\nSigned Message (Message: {0})".format(
            self._arguments["<message>"]))
        print(Table([signature.names(), signature.values()]))
Exemple #7
0
    def run(self):
        """
        Return method for config show command

        :return: (None)
        """

        config = SortedDictionary(QuantumComputerConfig.get_config())

        print("\nQuantum Computer Config")
        print(Table([config.names(), config.values()]))
Exemple #8
0
    def run(self):
        """
        Return method for config show command

        :return: (None)
        """

        config = SortedDictionary(VirtualMachineConfig.get_config())

        print("\nVirtual Machine Config")
        print(Table([config.names(), config.values()]))
Exemple #9
0
    def run(self):
        """
        Run method for network config show command.
        Reads the network config and then displays it in a ascii_table.Table object

        :return: (None)
        """

        config = SortedDictionary(NetworkConfig.get_config())

        print("\nNetwork Config ({0})".format(NetworkConfig.get_config_identifier()))
        print(Table([config.names(), config.values()]))
Exemple #10
0
    def __repr__(self):
        """
        Returns string representation of the comparison register using an ascii_table.Table object

        :return: (string)
        """

        return str(
            Table([{
                "Header": condition,
                "Contents": [str(int(self.__getitem__(condition)))]
            } for condition in ["EQ", "NE", "GT", "LT"]]))
Exemple #11
0
    def __repr__(self):
        """
        Returns string representation of the register using an ascii_table.Table object

        :return: (string)
        """

        return str(Table([
            {
                "Header": str(register),
                "Contents": [str(value)]
            } for register, value in self._register.items()
        ]))
Exemple #12
0
    def run(self):
        """
        Run method for network config use command.
        Prints out a table of valid config identifiers.
        User is then prompted to input the name of a valid config identifier. If input is invalid a
        BPLClientNetworkException is raised. Otherwise the identifier is written to config.json and the new selected
        config is displayed using a ascii_table.Table object.

        :return: (None)
        """

        print("\nConfig Identifiers")
        print(
            Table([{
                "Header": "Configs",
                "Contents": NetworkConfig.get_config_identifiers()
            }]))

        config_identifier = input("\nEnter config identifier: ")

        if not NetworkConfig.validate_identifier(config_identifier):
            print(BPLClientNetworkException({
                "message":
                "invalid config identifier",
                "identifiers":
                NetworkConfig.get_config_identifiers(),
                "identifier":
                config_identifier
            }),
                  file=sys.stderr)
            sys.exit(1)

        write_file(NETWORK_CONFIG,
                   json.dumps({"identifier": config_identifier}))

        config = SortedDictionary(NetworkConfig.get_config())
        print("\nNetwork Config ({0})".format(config_identifier))
        print(Table([config.names(), config.values()]))
    def __repr__(self):
        """
        Returns string representation of the memory unit using an ascii_table.Table object

        :return: (string)
        """

        return str(
            Table([{
                "Header": "Addresses",
                "Contents": list(map(str, range(self._capacity)))
            }, {
                "Header": "Values",
                "Contents": list(map(str, self._memory))
            }]))
Exemple #14
0
    def _get_delegate(self):
        """
        Used to fetch the status of any delegates the account voted for and display them individually using a
        ascii_table.Table object

        :return: (None)
        """

        votes = self._bpl_accounts.votes(self._address)

        if not votes["success"]:
            print(BPLClientAccountsException({
                "message": "Delegate unknown on the blockchain.",
                "error": votes["error"]
            }), file=sys.stderr)
            sys.exit(1)

        for vote in votes["delegates"]:
            delegate = SortedDictionary(vote)
            del delegate["address"]
            del delegate["publicKey"]

            print("\nVoted Delegate ({0})".format(delegate["username"]))
            print(Table([delegate.names(), delegate.values()]))
Exemple #15
0
    def _get_account(self):
        """
        Used to fetch the status of the account and then display it using a ascii_table.Table object

        :return: (None)
        """

        account = self._bpl_accounts.account(self._address)

        if not account["success"]:
            print(BPLClientAccountsException({
                "message": "Address unknown on the blockchain.",
                "address": self._address
            }), file=sys.stderr)
            sys.exit(1)

        account = SortedDictionary({
            str(k): str(v) for k, v in account["account"].items()
            if v and len(str(v)) > 0
        })
        del account["address"]

        print("\nAddress Summary")
        print(Table([account.names(), account.values()]))
    def run(self):
        """
        Run method for config setup

        :return: (None)
        """

        registers = input("Enter number of registers in the virtual machine: ")

        if not regular_expression.match(REGISTERS_REGEX, registers):
            print(AssemblySimulatorVMConfigException({
                "message": "invalid number of registers",
                "format": "[0-9]{1,2}",
                "registers": registers
            }), file=sys.stderr)
            return

        memory_capacity = input("Enter number of addressable memory units in the virtual machine: ")

        if not regular_expression.match(MEMORY_CAPACITY_REGEX, memory_capacity):
            print(AssemblySimulatorVMConfigException({
                "message": "invalid number of addressable memory units",
                "format": "[0-9]{1,3}",
                "memory capacity": memory_capacity
            }), file=sys.stderr)
            return

        config = {
            "memory capacity": int(memory_capacity),
            "registers": int(registers)
        }
        write_file(VM_CONFIG, json.dumps(config))

        config = SortedDictionary(config)
        print("\nVirtual Machine Config")
        print(Table([config.names(), config.values()]))
Exemple #17
0
    def run(self):
        """
        Run method for network config new command.
        Prints prompt requesting config identifier.
        Prints prompt requesting peer address and port, peer address user input is validated using a regular expression.
        A similar process is applied to the network version and begin epoch prompts.
        If validation fails at a given state then a BPLClientNetworkException is raised.
        Otherwise the nethash is fetch from the peer address the user entered.
        The currently used config identifier is then stored in config.json and the new config is stored in configs.json
        file. The config is then displayed using a ascii_table.Table object

        :return: (None)
        """

        config_identifier = input("Enter config identifier: ")

        if NetworkConfig.validate_identifier(config_identifier):
            print(BPLClientNetworkException({
                "message": "invalid config identifier. config identifier has already been used.",
                "config identifiers": NetworkConfig.get_config_identifiers(),
                "config identifier": config_identifier
            }), file=sys.stderr)
            sys.exit(1)

        peer_address = input("Enter peer address and port: ")

        if not regular_expression.match(PEER_ADDRESS_REGEX, peer_address):
            print(BPLClientNetworkException({
                "message": "invalid peer address.",
                "format": "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,5}",
                "peer": peer_address
            }), file=sys.stderr)
            sys.exit(1)

        version = input("Enter version: ")

        if not regular_expression.match(VERSION_REGEX, version):
            print(BPLClientNetworkException({
                "message": "invalid network version.",
                "format": "[0-9]{1,3}",
                "version": version
            }), file=sys.stderr)
            sys.exit(1)

        begin_epoch = input("Enter begin epoch: ")

        if not regular_expression.match(EPOCH_REGEX, begin_epoch):
            print(BPLClientNetworkException({
                "message": "invalid begin epoch.",
                "format": "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}",
                "begin epoch": begin_epoch
            }), file=sys.stderr)
            sys.exit(1)

        try:
            nethash = Client(peer_address).api("blocks").nethash()["nethash"]
        except:
            print(BPLClientNetworkException({
                "message": "failed to fetch nethash.",
                "reason": "failed to successfully connect to peer."
            }), file=sys.stderr)
            sys.exit(1)

        configs = NetworkConfig.get_configs()
        configs[config_identifier] = {
            "peer address": peer_address,
            "version": int(version),
            "begin epoch": begin_epoch,
            "nethash": nethash
        }

        write_file(NETWORK_CONFIG, json.dumps({
            "identifier": config_identifier
        }))
        write_file(NETWORK_CONFIGS, json.dumps(configs))

        try:
            Network.use_custom(
                config_identifier, datetime.strptime(begin_epoch, "%Y-%m-%d %H:%M:%S"), int(version)
            )
        except BPLNetworkException:
            pass

        config = SortedDictionary(configs[config_identifier])
        print("\nNetwork Config ({0})".format(config_identifier))
        print(Table([config.names(), config.values()]))