Example #1
0
def history(ctx, account, limit, type, csv, exclude, raw):
    """ Show history of an account
    """
    from gravitybase.operations import getOperationNameForId
    header = ["#", "time (block)", "operation", "details"]
    if csv:
        import csv
        t = csv.writer(sys.stdout, delimiter=";")
        t.writerow(header)
    else:
        t = PrettyTable(header)
        t.align = "r"
        t.align["details"] = "l"

    for a in account:
        account = Account(a, gravity_instance=ctx.gravity)
        for b in account.history(
            limit=limit,
            only_ops=type,
            exclude_ops=exclude
        ):
            row = [
                b["id"].split(".")[2],
                "%s" % (b["block_num"]),
                "{} ({})".format(getOperationNameForId(b["op"][0]), b["op"][0]),
                pprintOperation(b) if not raw else json.dumps(b, indent=4),
            ]
            if csv:
                t.writerow(row)
            else:
                t.add_row(row)
    if not csv:
        click.echo(t)
Example #2
0
 def test_account_upgrade(self):
     account = Account("witness-account")
     tx = account.upgrade()
     ops = tx["operations"]
     op = ops[0][1]
     self.assertEqual(len(ops), 1)
     self.assertEqual(getOperationNameForId(ops[0][0]), "account_upgrade")
     self.assertTrue(op["upgrade_to_lifetime_member"])
     self.assertEqual(
         op["account_to_upgrade"],
         "1.2.1",
     )
Example #3
0
def proposals(ctx, account):
    """ List proposals
    """
    proposals = Proposals(account)
    t = PrettyTable([
        "id",
        "expiration",
        "proposer",
        "required approvals",
        "available approvals",
        "review period time",
        "proposal",
    ])
    t.align = 'l'
    for proposal in proposals:
        if proposal.proposer:
            proposer = Account(proposal.proposer,
                               gravity_instance=ctx.gravity)["name"]
        else:
            proposer = "n/a"

        t.add_row([
            proposal["id"],
            proposal["expiration_time"],
            proposer,
            [
                Account(x)["name"]
                for x in (proposal["required_active_approvals"] +
                          proposal["required_owner_approvals"])
            ],
            json.dumps([
                Account(x)["name"]
                for x in proposal["available_active_approvals"]
            ] + proposal["available_key_approvals"] +
                       proposal["available_owner_approvals"],
                       indent=1),
            proposal.get("review_period_time", None),
            json.dumps(proposal["proposed_transaction"], indent=4),
        ])

    click.echo(str(t))
Example #4
0
    def test_predefined_data(self):
        from gravity.account import Account
        # Inject test data into cache
        _cache = ObjectCache(default_expiration=60 * 60 * 1)
        for i in test_objects:
            _cache[i["id"]] = i
        self.assertEqual(_cache['1.19.5']["test"], "passed")

        BlockchainObject._cache = _cache

        account = Account("1.2.0")
        self.assertEqual(account["name"], "committee-account-passed")
Example #5
0
def balance(ctx, accounts):
    """ Show Account balances
    """
    t = PrettyTable(["Account", "Amount"])
    t.align = "r"
    for a in accounts:
        account = Account(a, gravity_instance=ctx.gravity)
        for b in account.balances:
            t.add_row([
                str(a),
                str(b),
            ])
    click.echo(str(t))
Example #6
0
    def __init__(
        self,
        accounts=[],
        objects=[],
        on_tx=None,
        on_object=None,
        on_block=None,
        on_account=None,
        gravity_instance=None,
    ):
        # Events
        super(Notify, self).__init__()
        self.events = Events()

        # gravity instance
        self.gravity = gravity_instance or shared_gravity_instance()

        # Accounts
        account_ids = []
        for account_name in accounts:
            account = Account(account_name, gravity_instance=self.gravity)
            account_ids.append(account["id"])

        # Callbacks
        if on_tx:
            self.on_tx += on_tx
        if on_object:
            self.on_object += on_object
        if on_block:
            self.on_block += on_block
        if on_account:
            self.on_account += on_account

        # Open the websocket
        self.websocket = GravityWebsocket(
            urls=self.gravity.rpc.urls,
            user=self.gravity.rpc.user,
            password=self.gravity.rpc.password,
            accounts=account_ids,
            objects=objects,
            on_tx=on_tx,
            on_object=on_object,
            on_block=on_block,
            on_account=self.process_account,
        )
Example #7
0
    def sign(self, account=None, **kwargs):
        """ Sign a message with an account's memo key

            :param str account: (optional) the account that owns the bet
                (defaults to ``default_account``)
            :raises ValueError: If not account for signing is provided

            :returns: the signed message encapsulated in a known format
        """
        if not account:
            if "default_account" in config:
                account = config["default_account"]
        if not account:
            raise ValueError("You need to provide an account")

        # Data for message
        account = Account(account, blockchain_instance=self.blockchain)
        info = self.blockchain.info()
        meta = dict(
            timestamp=info["time"],
            block=info["head_block_number"],
            memokey=account["options"]["memo_key"],
            account=account["name"])

        # wif key
        wif = self.blockchain.wallet.getPrivateKeyForPublicKey(
            account["options"]["memo_key"]
        )

        # We strip the message here so we know for sure there are no trailing
        # whitespaces or returns
        message = self.message.strip()

        enc_message = SIGNED_MESSAGE_META.format(**locals())

        # signature
        signature = hexlify(sign_message(
            enc_message,
            wif
        )).decode("ascii")

        return SIGNED_MESSAGE_ENCAPSULATED.format(
            MESSAGE_SPLIT=MESSAGE_SPLIT,
            **locals()
        )
    def test_finalize(self):
        account = Account(account_id)

        op = operations.Transfer(
            **{
                "fee": {
                    "asset_id": "1.3.0",
                    "amount": 1
                },
                "from": account_id,
                "to": '1.2.8',
                "amount": {
                    "asset_id": "1.3.0",
                    "amount": 1
                }
            })

        tx = self.grv.finalizeOp(op, account, "active")
        self.assertEqual(len(tx["signatures"]), 1)
Example #9
0
def print_permissions(account):
    t = PrettyTable(["Permission", "Threshold", "Key/Account"],
                    hrules=allBorders)
    t.align = "r"
    for permission in ["owner", "active"]:
        auths = []
        # account auths:
        for authority in account[permission]["account_auths"]:
            auths.append("%s (%d)" %
                         (Account(authority[0])["name"], authority[1]))
        # key auths:
        for authority in account[permission]["key_auths"]:
            auths.append("%s (%d)" % (authority[0], authority[1]))
        t.add_row([
            permission,
            account[permission]["weight_threshold"],
            "\n".join(auths),
        ])
    print(t)
Example #10
0
def importaccount(ctx, account, role):
    """ Import an account using an account password
    """
    from gravitybase.account import PasswordKey

    password = click.prompt(
        "Account Passphrase",
        hide_input=True,
    )
    account = Account(account, gravity_instance=ctx.gravity)
    imported = False

    if role == "owner":
        owner_key = PasswordKey(account["name"], password, role="owner")
        owner_pubkey = format(owner_key.get_public_key(), ctx.gravity.rpc.chain_params["prefix"])
        if owner_pubkey in [x[0] for x in account["owner"]["key_auths"]]:
            click.echo("Importing owner key!")
            owner_privkey = owner_key.get_private_key()
            ctx.gravity.wallet.addPrivateKey(owner_privkey)
            imported = True

    if role == "active":
        active_key = PasswordKey(account["name"], password, role="active")
        active_pubkey = format(active_key.get_public_key(), ctx.gravity.rpc.chain_params["prefix"])
        if active_pubkey in [x[0] for x in account["active"]["key_auths"]]:
            click.echo("Importing active key!")
            active_privkey = active_key.get_private_key()
            ctx.gravity.wallet.addPrivateKey(active_privkey)
            imported = True

    if role == "memo":
        memo_key = PasswordKey(account["name"], password, role=role)
        memo_pubkey = format(memo_key.get_public_key(), ctx.gravity.rpc.chain_params["prefix"])
        if memo_pubkey == account["memo_key"]:
            click.echo("Importing memo key!")
            memo_privkey = memo_key.get_private_key()
            ctx.gravity.wallet.addPrivateKey(memo_privkey)
            imported = True

    if not imported:
        click.echo("No matching key(s) found. Password correct?")
Example #11
0
def addkey(ctx, key):
    """ Add a private key to the wallet
    """
    if not key:
        while True:
            key = click.prompt(
                "Private Key (wif) [Enter to quit]",
                hide_input=True,
                show_default=False,
                default="exit"
            )
            if not key or key == "exit":
                break
            try:
                ctx.gravity.wallet.addPrivateKey(key)
            except Exception as e:
                click.echo(str(e))
                continue
    else:
        for k in key:
            try:
                ctx.gravity.wallet.addPrivateKey(k)
            except Exception as e:
                click.echo(str(e))

    installedKeys = ctx.gravity.wallet.getPublicKeys()
    if len(installedKeys) == 1:
        name = ctx.gravity.wallet.getAccountFromPublicKey(installedKeys[0])
        if name:  # only if a name to the key was found
            account = Account(name, gravity_instance=ctx.gravity)
            click.echo("=" * 30)
            click.echo("Setting new default user: %s" % account["name"])
            click.echo()
            click.echo("You can change these settings with:")
            click.echo("    uptick set default_account <account>")
            click.echo("=" * 30)
            config["default_account"] = account["name"]
Example #12
0
def permissions(ctx, account):
    """ Show permissions of an account
    """
    print_permissions(Account(account))
Example #13
0
def info(ctx, objects):
    """ Obtain all kinds of information
    """
    if not objects:
        t = PrettyTable(["Key", "Value"])
        t.align = "l"
        info = ctx.gravity.rpc.get_dynamic_global_properties()
        for key in info:
            t.add_row([key, info[key]])
        click.echo(t.get_string(sortby="Key"))

    for obj in objects:
        # Block
        if re.match("^[0-9]*$", obj):
            block = Block(obj, gravity_instance=ctx.gravity)
            if block:
                t = PrettyTable(["Key", "Value"])
                t.align = "l"
                for key in sorted(block):
                    value = block[key]
                    if key == "transactions":
                        value = json.dumps(value, indent=4)
                    t.add_row([key, value])
                click.echo(t)
            else:
                click.echo("Block number %s unknown" % obj)
        # Object Id
        elif len(obj.split(".")) == 3:
            data = ctx.gravity.rpc.get_object(obj)
            if data:
                t = PrettyTable(["Key", "Value"])
                t.align = "l"
                for key in sorted(data):
                    value = data[key]
                    if isinstance(value, dict) or isinstance(value, list):
                        value = json.dumps(value, indent=4)
                    t.add_row([key, value])
                click.echo(t)
            else:
                click.echo("Object %s unknown" % obj)

        # Asset
        elif obj.upper() == obj:
            data = Asset(obj)
            t = PrettyTable(["Key", "Value"])
            t.align = "l"
            for key in sorted(data):
                value = data[key]
                if isinstance(value, dict):
                    value = json.dumps(value, indent=4)
                t.add_row([key, value])
            click.echo(t)

        # Public Key
        elif re.match("^ZGV.{48,55}$", obj):
            account = ctx.gravity.wallet.getAccountFromPublicKey(obj)
            if account:
                t = PrettyTable(["Account"])
                t.align = "l"
                t.add_row([account])
                click.echo(t)
            else:
                click.echo("Public Key not known" % obj)

        # Account name
        elif re.match("^[a-zA-Z0-9\-\._]{2,64}$", obj):
            account = Account(obj, full=True)
            if account:
                t = PrettyTable(["Key", "Value"])
                t.align = "l"
                for key in sorted(account):
                    value = account[key]
                    if isinstance(value, dict) or isinstance(value, list):
                        value = json.dumps(value, indent=4)
                    t.add_row([key, value])
                click.echo(t)
            else:
                click.echo("Account %s unknown" % obj)
        else:
            click.echo("Couldn't identify object to read")
Example #14
0
    def test_account(self):
        Account("witness-account")
        Account("1.2.3")
        asset = Asset("1.3.0")
        symbol = asset["symbol"]
        account = Account("witness-account", full=True)
        self.assertEqual(account.name, "witness-account")
        self.assertEqual(account["name"], account.name)
        self.assertEqual(account["id"], "1.2.1")
        self.assertIsInstance(account.balance("1.3.0"), Amount)
        self.assertIsInstance(account.balance({"symbol": symbol}), Amount)
        self.assertIsInstance(account.balances, list)
        for h in account.history(limit=1):
            pass

        # BlockchainObjects method
        account.cached = False
        self.assertTrue(account.items())
        account.cached = False
        self.assertIn("id", account)
        account.cached = False
        self.assertEqual(account["id"], "1.2.1")
        self.assertEqual(str(account), "<Account 1.2.1>")
        self.assertIsInstance(Account(account), Account)
Example #15
0
    def verify(self, **kwargs):
        """ Verify a message with an account's memo key

            :param str account: (optional) the account that owns the bet
                (defaults to ``default_account``)

            :returns: True if the message is verified successfully
            :raises InvalidMessageSignature if the signature is not ok
        """
        # Split message into its parts
        parts = re.split("|".join(MESSAGE_SPLIT), self.message)
        parts = [x for x in parts if x.strip()]

        assert len(parts) > 2, "Incorrect number of message parts"

        # Strip away all whitespaces before and after the message
        message = parts[0].strip()
        signature = parts[2].strip()
        # Parse the meta data
        meta = dict(re.findall(r'(\S+)=(.*)', parts[1]))

        log.info("Message is: {}".format(message))
        log.info("Meta is: {}".format(json.dumps(meta)))
        log.info("Signature is: {}".format(signature))

        # Ensure we have all the data in meta
        assert "account" in meta, "No 'account' could be found in meta data"
        assert "memokey" in meta, "No 'memokey' could be found in meta data"
        assert "block" in meta, "No 'block' could be found in meta data"
        assert "timestamp" in meta, \
            "No 'timestamp' could be found in meta data"

        account_name = meta.get("account").strip()
        memo_key = meta["memokey"].strip()

        try:
            PublicKey(memo_key)
        except Exception:
            raise InvalidMemoKeyException(
                "The memo key in the message is invalid"
            )

        # Load account from blockchain
        try:
            account = Account(
                account_name,
                blockchain_instance=self.blockchain)
        except AccountDoesNotExistsException:
            raise AccountDoesNotExistsException(
                "Could not find account {}. Are you connected to the right chain?".format(
                    account_name
                ))

        # Test if memo key is the same as on the blockchain
        if not account["options"]["memo_key"] == memo_key:
            raise WrongMemoKey(
                "Memo Key of account {} on the Blockchain".format(
                    account["name"]) +
                "differs from memo key in the message: {} != {}".format(
                    account["options"]["memo_key"], memo_key
                )
            )

        # Reformat message
        enc_message = SIGNED_MESSAGE_META.format(**locals())

        # Verify Signature
        pubkey = verify_message(enc_message, unhexlify(signature))

        # Verify pubky
        pk = PublicKey(hexlify(pubkey).decode("ascii"))
        if format(pk, self.blockchain.prefix) != memo_key:
            raise InvalidMessageSignature

        return True
Example #16
0
from gravity import Gravity
from gravity.account import Account

grv = Gravity("wss://grvapi.graphenelab.org/ws")
acc = Account('g9480a2230f7280f3790')

print('Getting Account: {}'.format(acc))