コード例 #1
0
    def test_pricefeed(self):
        feed = transactions.PriceFeed(
            **{
                "settlement_price":
                transactions.Price(
                    base=transactions.Asset(amount=214211, asset_id="1.3.0"),
                    quote=transactions.Asset(amount=1241, asset_id="1.3.14"),
                ),
                "core_exchange_rate":
                transactions.Price(
                    base=transactions.Asset(amount=1241, asset_id="1.3.0"),
                    quote=transactions.Asset(amount=6231, asset_id="1.3.14"),
                ),
                "maximum_short_squeeze_ratio":
                1100,
                "maintenance_collateral_ratio":
                1750,
            })

        pFeed = transactions.Asset_publish_feed(fee=transactions.Asset(
            amount=100, asset_id="1.3.0"),
                                                publisher="1.2.0",
                                                asset_id="1.3.3",
                                                feed=feed)

        ops = [transactions.Operation(pFeed)]
        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 = "f68585abf4dce7c8045701136400000000000000000003c34403000000000000d9040000000000000ed6064c04d9040000000000000057180000000000000e0000012009e13f9066fedc3c8c1eb2ac33b15dc67ecebf708890d0f8ab62ec8283d1636002315a189f1f5aa8497b41b8e6bb7c4dc66044510fae25d8f6aebb02c7cdef10"
        self.assertEqual(compare[:-130], txWire[:-130])
コード例 #2
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])
コード例 #3
0
 def test_proposal_update(self):
     s = {
         'fee_paying_account': "1.2.1",
         'proposal': "1.10.90",
         'active_approvals_to_add': ["1.2.5"],
         "fee": transactions.Asset(amount=12512, asset_id="1.3.0"),
     }
     op = transactions.Proposal_update(**s)
     ops = [transactions.Operation(op)]
     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 = "f68585abf4dce7c804570117e03000000000000000015a01050000000000000001203255378db6dc19443e74421c954ad7fdcf23f4ea45fe4fe5a1b078a0f94fb529594819c9799d68efa5cfb5b271a9333a2f516ca4fb5093226275f48a42d9e8cf"
     self.assertEqual(compare[:-130], txWire[:-130])
コード例 #4
0
ファイル: __main__.py プロジェクト: metaperl/airsign
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")
コード例 #5
0
    bitasset_data = client.getObject(asset["bitasset_data_id"])
    base = client.getObject(bitasset_data["options"]["short_backing_asset"])

    # Correct for different precisions of base and quote assets
    price = price * 10 ** asset["precision"] / 10 ** base["precision"]

    # convert into a fraction
    denominator = int(10 ** base["precision"])
    numerator   = int(price * 10 ** base["precision"])

    ops = []
    for producer in producers:
        account = client.ws.get_account(producer)
        feed = transactions.PriceFeed(**{
            "settlement_price" : transactions.Price(
                base=transactions.Asset(amount=numerator, asset_id=asset["id"]),
                quote=transactions.Asset(amount=denominator, asset_id=base["id"]),
            ),
            "core_exchange_rate" : transactions.Price(
                base=transactions.Asset(amount=numerator, asset_id=asset["id"]),
                quote=transactions.Asset(amount=denominator * scale_cer, asset_id="1.3.0"),
            ),
            "maximum_short_squeeze_ratio" : 1200,
            "maintenance_collateral_ratio" : 1100,
        })
        pFeed = transactions.Asset_publish_feed(
            fee=transactions.Asset(amount=0, asset_id="1.3.0"),
            publisher=account["id"],
            asset_id=asset["id"],
            feed=feed
        )