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 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 #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 _get_public_key(self):
        """
        Used to return the public key of the delegate

        :return: (string)
        """

        return Client(NetworkConfig.get_peer()).api("delegates").delegate(
            self._username)["delegate"]["publicKey"]
Exemple #5
0
    def _verify_delegate(self):
        """
        Used to verify whether self._username stores the name of a valid delegate

        :return: (boolean)
        """

        return Client(NetworkConfig.get_peer()).api("delegates").delegate(
            self._username)["success"]
Exemple #6
0
    def run(self):
        """
        Run method for account vote command.
        Verifies that self._username is the name of a valid delegate.
        If self._username is invalid then a BPLClientAccountsException is raised.
        Otherwise the user is prompted for the secret passphrase (input is masked).
        Then the user must confirm the transaction. If the user aborts the transaction then "Aborted." is printed and
        the transaction isn't sent.
        Otherwise the transaction is constructed using bpl_lib.transactions.Vote and sent using bpl_api.
        If the transaction is successful then "Transaction sent successfully with id x" is displayed, otherwise
        "Failed to sent transaction: x" is displayed.

        :return: (None)
        """

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

        if not self._verify_delegate():
            print(BPLClientAccountsException({
                "message": "Invalid delegate.",
                "delegate": self._username
            }),
                  file=sys.stderr)
            sys.exit(1)

        votes = ["+" + self._get_public_key()]
        secret_passphrase = getpass(prompt="Enter secret passphrase: ")

        if input("Confirm (y/n): ").lower() not in ["y", "yes"]:
            print("Aborted.")
            sys.exit(0)

        transaction = VoteTransaction.generate(votes,
                                               secret_passphrase).to_dict()
        response = bpl_transactions.send(transaction)

        if response["success"]:
            print("Transaction sent successfully with id {0}.".format(
                transaction["id"]))
        else:
            print("Failed to send transaction: {0}.".format(response["error"]))
Exemple #7
0
    def __init__(self, arguments):
        """
        Account status command constructor
        Initializes _bpl_accounts and _address

        :param arguments: Contains list of arguments parsed from docopt (list)
        """

        super().__init__(arguments)
        self._bpl_accounts = Client(NetworkConfig.get_peer()).api("accounts")
        self._address = self._arguments["<address>"]
Exemple #8
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()]))
Exemple #9
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()]))