Пример #1
0
 def test_encrypt(self):
     for memo in test_cases:
         enc = encode_memo(PrivateKey(memo["wif"]),
                           PublicKey(memo["to"], prefix="GPH"),
                           memo["nonce"],
                           memo["plain"])
         self.assertEqual(memo["message"], enc)
Пример #2
0
 def test_encrypt(self):
     for memo in test_cases:
         enc = encode_memo(
             PrivateKey(memo["wif"]),
             PublicKey(memo["to"], prefix="GPH"),
             memo["nonce"],
             memo["plain"],
         )
         self.assertEqual(memo["message"], enc)
    def test_Transfer(self):
        prefix           = "BTS"
        wif              = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"
        pub              = format(account.PrivateKey(wif).pubkey, prefix)
        from_account_id  = "1.2.0"
        to_account_id    = "1.2.1"
        amount           = 1000000
        asset_id         = "1.3.4"
        message          = "abcdefgABCDEFG0123456789"
        nonce            = "5862723643998573708"
        ref_block_num    = 34294
        ref_block_prefix = 3707022213
        expiration       = "2016-04-06T08:29:27"

        fee          = transactions.Asset(amount=0, asset_id="1.3.0")
        amount       = transactions.Asset(amount=int(amount), asset_id=asset_id)
        encrypted_memo = memo.encode_memo(account.PrivateKey(wif),
                                          account.PublicKey(pub, prefix=prefix),
                                          nonce,
                                          message)
        memoStruct = {"from": pub,
                      "to": pub,
                      "nonce": nonce,
                      "message": encrypted_memo,
                      "chain": prefix}
        memoObj  = transactions.Memo(**memoStruct)
        transferStruct = {"fee": fee,
                          "from": from_account_id,
                          "to": to_account_id,
                          "amount": amount,
                          "memo": memoObj
                          }
        transfer = transactions.Transfer(**transferStruct)
        ops    = [transactions.Operation(transfer)]
        tx     = transactions.Signed_Transaction(ref_block_num=ref_block_num,
                                                 ref_block_prefix=ref_block_prefix,
                                                 expiration=expiration,
                                                 operations=ops)
        tx     = tx.sign([wif], chain=prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")

        compare = "f68585abf4dce7c804570100000000000000000000000140420f0000000000040102c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf02c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf8c94d19817945c5120fa5b6e83079a878e499e2e52a76a7739e9de40986a8e3bd8a68ce316cee50b210000011f39e3fa7071b795491e3b6851d61e7c959be92cc7deb5d8491cf1c3c8c99a1eb44553c348fb8f5001a78b18233ac66727e32fc776d48e92d9639d64f68e641948"
        self.assertEqual(compare[:-130], txWire[:-130])
Пример #4
0
    def test_Transfer(self):
        pub = format(account.PrivateKey(wif).pubkey, prefix)
        from_account_id = "1.2.0"
        to_account_id = "1.2.1"
        amount = 1000000
        asset_id = "1.3.4"
        message = "abcdefgABCDEFG0123456789"
        nonce = "5862723643998573708"

        fee = transactions.Asset(amount=0, asset_id="1.3.0")
        amount = transactions.Asset(amount=int(amount), asset_id=asset_id)
        encrypted_memo = memo.encode_memo(
            account.PrivateKey(wif), account.PublicKey(pub, prefix=prefix),
            nonce, message)
        memoStruct = {
            "from": pub,
            "to": pub,
            "nonce": nonce,
            "message": encrypted_memo,
            "chain": prefix
        }
        memoObj = transactions.Memo(**memoStruct)
        transferStruct = {
            "fee": fee,
            "from": from_account_id,
            "to": to_account_id,
            "amount": amount,
            "memo": memoObj
        }
        transfer = transactions.Transfer(**transferStruct)
        ops = [transactions.Operation(transfer)]
        tx = transactions.Signed_Transaction(ref_block_num=ref_block_num,
                                             ref_block_prefix=ref_block_prefix,
                                             expiration=expiration,
                                             operations=ops)
        tx = tx.sign([wif], chain=prefix)
        tx.verify([PrivateKey(wif).pubkey], "BTS")
        txWire = hexlify(bytes(tx)).decode("ascii")

        compare = "f68585abf4dce7c804570100000000000000000000000140420f0000000000040102c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf02c0ded2bc1f1305fb0faac5e6c03ee3a1924234985427b6167ca569d13df435cf8c94d19817945c5120fa5b6e83079a878e499e2e52a76a7739e9de40986a8e3bd8a68ce316cee50b210000011f39e3fa7071b795491e3b6851d61e7c959be92cc7deb5d8491cf1c3c8c99a1eb44553c348fb8f5001a78b18233ac66727e32fc776d48e92d9639d64f68e641948"
        self.assertEqual(compare[:-130], txWire[:-130])
Пример #5
0
    def encrypt(self, message):
        """ Encrypt a memo

            :param str message: clear text memo message
            :returns: encrypted message
            :rtype: str
        """
        if not message:
            return None

        nonce = str(random.getrandbits(64))
        try:
            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(
                self.from_account["options"]["memo_key"])
        except KeyNotFound:
            # if all fails, raise exception
            raise MissingKeyError(
                "Memo private key {} for {} could not be found".format(
                    self.from_account["options"]["memo_key"],
                    self.from_account["name"]))
        if not memo_wif:
            raise MissingKeyError("Memo key for %s missing!" %
                                  self.from_account["name"])

        if not hasattr(self, "chain_prefix"):
            self.chain_prefix = self.blockchain.prefix

        enc = memo.encode_memo(
            self.privatekey_class(memo_wif),
            self.publickey_class(self.to_account["options"]["memo_key"],
                                 prefix=self.chain_prefix),
            nonce,
            message,
        )

        return {
            "message": enc,
            "nonce": nonce,
            "from": self.from_account["options"]["memo_key"],
            "to": self.to_account["options"]["memo_key"],
        }
Пример #6
0
def main() :
    global args
    global rpc
    config = Configuration()

    if "node" not in config or not config["node"]:
        config["node"] = "wss://bitshares.openledger.info/ws"

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="Command line tool to interact with the BitShares network"
    )

    """
        Default settings for all tools
    """
    parser.add_argument(
        '--node',
        type=str,
        default=config["node"],
        help='Websocket URL for public BitShares API (default: "wss://bitshares.openledger.info/ws")'
    )
    parser.add_argument(
        '--rpcuser',
        type=str,
        default=config["rpcuser"],
        help='Websocket user if authentication is required'
    )
    parser.add_argument(
        '--rpcpassword',
        type=str,
        default=config["rpcpassword"],
        help='Websocket password if authentication is required'
    )
    parser.add_argument(
        '--nobroadcast',
        action='store_true',
        help='Do not broadcast anything'
    )
    subparsers = parser.add_subparsers(help='sub-command help')
    parser.set_defaults(command=None)

    """
        Command "set"
    """
    setconfig = subparsers.add_parser('set', help='Set configuration')
    setconfig.add_argument(
        'key',
        type=str,
        choices=["node",
                 "rpcuser",
                 "rpcpassword",
                 "account"
                 ],
        help='Configuration key'
    )
    setconfig.add_argument(
        'value',
        type=str,
        help='Configuration value'
    )
    setconfig.set_defaults(command="set")

    """
        Command "addkey"
    """
    addkey = subparsers.add_parser('addkey', help='Add a new key to the wallet')
    addkey.add_argument(
        'wifkeys',
        nargs='*',
        type=str,
        help='the private key in wallet import format (wif)'
    )
    addkey.set_defaults(command="addkey")

    """
        Command "listkeys"
    """
    listkeys = subparsers.add_parser('listkeys', help='List available keys in your wallet')
    listkeys.set_defaults(command="listkeys")

    """
        Command "listaccounts"
    """
    listaccounts = subparsers.add_parser('listaccounts', help='List available accounts in your wallet')
    listaccounts.set_defaults(command="listaccounts")

    """
        Command "getbalance"
    """
    getbalance = subparsers.add_parser('getbalance', help='Get balances of available account(s)')
    getbalance.set_defaults(command="getbalance")
    getbalance.add_argument(
        'account',
        type=str,
        nargs="*",
        default=[config["account"]],
        help='Accounts for which to retrieve the balance',
    )

    """
        Command "transfer"
    """
    transfer = subparsers.add_parser('transfer', help='Transfer funds from your wallet to someone else')
    transfer.set_defaults(command="transfer")
    transfer.add_argument(
        '--from',
        type=str,
        help='Transfer from this account',
        default=config["account"],
    )
    transfer.add_argument(
        '--to',
        type=str,
        help='Transfer to this account',
        required=True,
    )
    transfer.add_argument(
        '--amount',
        type=str,
        help='Transfer this amount (format: "amount SYMBOL")',
        action="append",
        required=True,
    )
    transfer.add_argument(
        '--memo',
        default='',
        type=str,
        help='Memo',
    )

    """
        Command "approve"
    """
    approve = subparsers.add_parser('approve', help='approve funds from your wallet to someone else')
    approve.set_defaults(command="approve")
    approve.add_argument(
        '--account',
        type=str,
        help='Approve with this account',
        default=config["account"],
    )
    approve.add_argument(
        'proposal',
        type=str,
        help='Proposal to approve',
    )

    """
        Parse Arguments
    """
    args = parser.parse_args()

    rpc_not_required = ["set", ""]
    if args.command not in rpc_not_required and args.command:
        rpc = GrapheneWebsocketRPC(args.node, args.rpcuser, args.rpcpassword)

    if args.command == "set":
        config[args.key] = args.value

    elif args.command == "addkey":
        wallet = Wallet(rpc)
        if len(args.wifkeys):
            for wifkey in args.wifkeys:
                pub = (wallet.addPrivateKey(wifkey))
                if pub:
                    print(pub)
        else:
            import getpass
            wifkey = ""
            while True:
                wifkey = getpass.getpass('Private Key (wif) [Enter to quit]:')
                if not wifkey:
                    break
                pub = (wallet.addPrivateKey(wifkey))
                if pub:
                    print(pub)

    elif args.command == "listkeys":
        t = PrettyTable(["Available Key"])
        t.align = "l"
        for key in Wallet(rpc).getPublicKeys():
            t.add_row([key])
        print(t)

    elif args.command == "listaccounts":
        t = PrettyTable(["Name", "Available Key"])
        t.align = "l"
        for account in Wallet(rpc).getAccounts():
            t.add_row(account)
        print(t)

    elif args.command == "getbalance":
        if args.account:
            accounts = [a for a in args.account]
        else:
            accounts = [a[0] for a in Wallet(rpc).getAccounts()]

        for account_name in accounts:
            account = rpc.get_account(account_name)
            t = PrettyTable(["Amount", "Asset"])
            t.align = "l"
            balances = rpc.get_account_balances(account["id"], [])
            if not balances:
                continue
            print(account["name"] + ":")
            for balance in balances:
                asset = rpc.get_objects([balance["asset_id"]])[0]
                amount = int(balance["amount"]) / 10 ** asset["precision"]
                if amount:
                    t.add_row([amount, asset["symbol"]])
            print(t)

    elif args.command == "transfer":
        wallet = Wallet(rpc)

        ops = []
        for amountStr in args.amount:
            amount, symbol = amountStr.split(" ")
            amount = float(amount)
            asset = rpc.get_asset(symbol)
            from_account = rpc.get_account(getattr(args, "from"))
            to_account = rpc.get_account(getattr(args, "to"))

            transferObj = {
                "fee": {"amount": 0,
                        "asset_id": "1.3.0"
                        },
                "from": from_account["id"],
                "to": to_account["id"],
                "amount": {"amount": int(amount * 10 ** asset["precision"]),
                           "asset_id": asset["id"]
                           }
            }

            if args.memo:
                memo_key = wallet.getMemoKeyForAccount(getattr(args, "from"))
                if not memo_key:
                    print("Missing memo private key!")
                    return

                import random
                nonce = str(random.getrandbits(64))
                encrypted_memo = memo.encode_memo(PrivateKey(memo_key),
                                                  PublicKey(to_account["options"]["memo_key"]),
                                                  nonce,
                                                  args.memo)
                memoStruct = {"from": from_account["options"]["memo_key"],
                              "to": to_account["options"]["memo_key"],
                              "nonce": nonce,
                              "message": encrypted_memo,
                              "chain": "BTS"}
                transferObj["memo"] = transactions.Memo(**memoStruct)

            transfer = transactions.Transfer(**transferObj)
            ops.append(transactions.Operation(transfer))

        wif = wallet.getActiveKeyForAccount(getattr(args, "from"))
        executeOps(ops, [wif])

    elif args.command == "approve":
        wallet = Wallet(rpc)
        account = rpc.get_account(args.account)
        s = {'fee_paying_account': account["id"],
             'proposal': args.proposal,
             'active_approvals_to_add': [account["id"]],
             "fee": transactions.Asset(amount=0, asset_id="1.3.0"),
             }
        op = transactions.Proposal_update(**s)
        wif = wallet.getActiveKeyForAccount(args.account)
        executeOps([transactions.Operation(op)], [wif])

    else:
        print("No valid command given")