def doit(self, printWire=False):
        ops = [Operation(self.op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        if printWire:
            print()
            print(txWire)
            print()
        self.assertEqual(self.cm[:-130], txWire[:-130])

        if TEST_AGAINST_CLI_WALLET:
            from grapheneapi.grapheneapi import GrapheneAPI

            rpc = GrapheneAPI("localhost", 8092)
            self.cm = rpc.serialize_transaction(tx.json())
            # print("soll: %s" % self.cm[:-130])
            # print("ist:  %s" % txWire[:-130])
            # print(txWire[:-130] == self.cm[:-130])
            self.assertEqual(self.cm[:-130], txWire[:-130])

        # Test against Bitshares backened
        live = peerplays.rpc.get_transaction_hex(tx.json())

        # Compare expected result with online result
        self.assertEqual(live[:-130], txWire[:-130])

        # Compare expected result with online backend
        self.assertEqual(live[:-130], self.cm[:-130])
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = transactions.Override_transfer(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "issuer": "1.2.29",
                "from": "1.2.104",
                "to": "1.2.29",
                "amount": {
                    "amount": 100000,
                    "asset_id": "1.3.105"
                },
                "extensions": []
            })

        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")

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(transactions.JsonObj(tx))
        print(compare[:-130])
        print(txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = operations.Comment_options(
            **{
                "author": "xeroc",
                "permlink": "piston",
                "max_accepted_payout": "1000000.000 SBD",
                "percent_steem_dollars": 10000,
                "allow_votes": True,
                "allow_curation_rewards": True,
                "extensions": []
            })
        ops = [operations.Operation(op)]
        tx = Signed_Transaction(ref_block_num=ref_block_num,
                                ref_block_prefix=ref_block_prefix,
                                expiration=expiration,
                                operations=ops)
        tx = tx.sign([wif])
        txWire = hexlify(bytes(tx)).decode("ascii")

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())

        pprint(tx.json())

        print("\n")
        print(compare[:-130])
        print(txWire[:-130])
        print("\n")

        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
    def compareConstructedTX(self):
        # FIXME: Bet cancel does not serialize properly
        op = operations.Bet_cancel(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "bettor_id": "1.2.5555",
                "bet_to_cancel": "1.22.1111",
                "prefix": prefix,
            })
        ops = [Operation(op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())
        print(compare[:-130])
        print(txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = operations.Asset_reserve(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "payer": "1.2.0",
                "amount_to_reserve": {
                    "amount": 1234567890,
                    "asset_id": "1.3.0"
                },
                "extensions": []
            })
        ops = [Operation(op)]
        tx = 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")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())
        print(compare[:-130])
        print(txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
    def compareConstructedTX(self):
        self.op = operations.Balance_claim(
            **{
                "fee": {"amount": 0, "asset_id": "1.3.0"},
                "deposit_to_account": "1.2.0",
                "balance_to_claim": "1.15.0",
                "balance_owner_key": prefix + "1111111111111111111111111111111114T1Anm",
                "total_claimed": {"amount": 0, "asset_id": "1.3.0"},
                "prefix": prefix,
            }
        )

        ops = [Operation(self.op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI

        rpc = GrapheneAPI("localhost", 8092)
        self.cm = rpc.serialize_transaction(tx.json())
        print("soll: %s" % self.cm)
        print("ist:  %s" % txWire)
        print(txWire[:-130] == self.cm[:-130])
        self.assertEqual(self.cm[:-130], txWire[:-130])
def main(rpchost, rpcport, expiration, broadcast, proposer):
    rpc = GrapheneAPI(rpchost, rpcport)
    obj = rpc.get_object("2.0.0")[0]
    current_fees = obj["parameters"]["current_fees"]["parameters"]
    old_fees = obj["parameters"]["current_fees"]
    scale = obj["parameters"]["current_fees"]["scale"] / 1e4

    # General change of parameter
    changes = {}

    # Copy old fees
    for f in current_fees:
        changes[getOperationNameForId(f[0])] = f[1].copy()

    # New fees
    changes["account_update"]["fee"] = int(0.02527 / scale * 1e5)
    changes["proposal_create"]["fee"] = int(5 / scale * 1e5)

    tx = rpc.propose_fee_change(proposer, formatTimeFromNow(expiration),
                                changes, broadcast)
    new_fees = tx["operations"][0][1]["proposed_ops"][0]["op"][1][
        "new_parameters"]["current_fees"]

    click.echo(json.dumps(DeepDiff(old_fees, new_fees), indent=4))

    if not broadcast:
        click.echo(
            "Set broadcast to 'True' if the transaction shall be broadcast!")
Example #8
0
def run():

#    testnet = BitShares("wss://node.testnet.bitshares.eu")
    testnet = BitShares("ws://this.uptick.rocks:18090")
    
    account = Account("committee-account", full=True, bitshares_instance=testnet)
    proposals = account["proposals"]
    client = GrapheneAPI("localhost", 8092, "", "")

    for proposal in proposals:
        pprint(proposal)
        if click.confirm("Approve proposal %s" % proposal["id"]):
            # Get current fees
            core_asset = client.get_asset("1.3.0")
            committee_account = client.get_account("committee-account")
            proposal = client.get_object(proposal["id"])[0]
            prop_op = proposal["proposed_transaction"]["operations"]

            tx = client.approve_proposal(
                "faucet",
                proposal["id"],
                {"active_approvals_to_add": [
                    "committee-member-1",
                    "committee-member-2",
                    "committee-member-3",
                    "committee-member-4",
                    "committee-member-5",
                    "committee-member-6",
                    "committee-member-7",
                    "committee-member-8",
                    "committee-member-9",
                    "committee-member-10"]
                },
                True)
            pprint(tx)
Example #9
0
    def compareConstructedTX(self):
        self.maxDiff = None
        self.op = operations.Committee_member_create(**{
            "fee": {
                "amount": 0,
                "asset_id": "1.3.0"
            },
            "committee_member_account": "1.2.0",
            "url": "foobar"
        })
        ops = [Operation(self.op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        self.cm = rpc.serialize_transaction(tx.json())
        print("soll: %s" % self.cm[:-130])
        print("ist:  %s" % txWire[:-130])
        print(txWire[:-130] == self.cm[:-130])
        self.assertEqual(self.cm[:-130], txWire[:-130])
Example #10
0
    def compareNewWire(self):
        #    def test_online(self):
        #        self.maxDiff = None

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        tx = rpc.create_account("xeroc", "fsafaasf", "", False)
        pprint(tx)
        compare = rpc.serialize_transaction(tx)
        ref_block_num = tx["ref_block_num"]
        ref_block_prefix = tx["ref_block_prefix"]
        expiration = tx["expiration"]

        ops = [
            transactions.Operation(
                transactions.Account_create(**tx["operations"][0][1]))
        ]
        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")
        print("\n")
        print(txWire[:-130])
        print(compare[:-130])
    def compareConstructedTX(self):
        self.maxDiff = None
        self.op = operations.Bid_collateral(**{
            'fee': {'amount': 100,
                    'asset_id': '1.3.0'},
            'additional_collateral': {
                'amount': 10000,
                'asset_id': '1.3.22'},
            'debt_covered': {
                'amount': 100000000,
                'asset_id': '1.3.0'},
            'bidder': '1.2.29',
            'extensions': []
        })
        ops = [Operation(self.op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        self.cm = rpc.serialize_transaction(tx.json())
        print("soll: %s" % self.cm[:-130])
        print("ist:  %s" % txWire[:-130])
        print(txWire[:-130] == self.cm[:-130])
        self.assertEqual(self.cm[:-130], txWire[:-130])
def run(n=0):
    client = GrapheneAPI("localhost", 8092, "", "")
    while True:
        for i in range(0, random.randint(1, 100)):
            print(n, end="", flush=True)
            client.transfer("faucet", "init0", "0.00007", "TEST", "", True)
        time.sleep(random.randint(0, 3))
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = operations.Comment_options(
            **{
                "author": "jared",
                "permlink": "dpaypy",
                "max_accepted_payout": "1000000.000 BBD",
                "percent_dpay_dollars": 10000,
                "allow_votes": True,
                "allow_curation_rewards": True,
                "extensions": [
                    [
                        0,
                        {
                            "beneficiaries": [
                                {
                                    "weight": 2000,
                                    "account": "good-karma"
                                },
                                {
                                    "weight": 5000,
                                    "account": "null"
                                }
                            ]
                        }
                    ]
                ],
            }
        )
        ops = [operations.Operation(op)]
        tx = Signed_Transaction(
            ref_block_num=ref_block_num,
            ref_block_prefix=ref_block_prefix,
            expiration=expiration,
            operations=ops
        )
        tx = tx.sign([wif])
        txWire = hexlify(bytes(tx)).decode("ascii")

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())

        pprint(tx.json())

        print("\n")
        print(compare[:-130])
        print(txWire[:-130])
        print("\n")

        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
def main(rpchost, rpcport, expiration, broadcast, proposer):
    rpc = GrapheneAPI(rpchost, rpcport)
    obj = rpc.get_object("2.0.0")[0]
    new_parameters = deepcopy(obj["parameters"])
    current_fees = obj["parameters"]["current_fees"]["parameters"]
    fees = obj["parameters"]["current_fees"]["parameters"]
    scale = obj["parameters"]["current_fees"]["scale"] / 1e4

    # General change of parameter
    changes = {}

    # Copy old fees
    for f in current_fees:
        changes[getOperationNameForId(f[0])] = f[1].copy()

    # New fees
    new_fee = {"fee": int(0.2 / scale * 1e5), "fee_per_day": int(0.2 / scale * 1e5)}
    changes["htlc_create"] = new_fee
    changes["htlc_redeem"] = new_fee
    changes["htlc_extend"] = new_fee

    tx = rpc.propose_fee_change(
        proposer, formatTimeFromNow(expiration), changes, broadcast
    )
    op = tx["operations"][0][1]["proposed_ops"][0]["op"]

    # New HTLC parameters are in extensions
    op[1]["new_parameters"]["extensions"] = {
        "updatable_htlc_options": {
            "max_preimage_size": 19200,
            "max_timeout_secs": 60 * 60 * 24 * 28,
        }
    }

    ops = [op]
    buildHandle = rpc.begin_builder_transaction()
    for op in ops:
        rpc.add_operation_to_builder_transaction(buildHandle, op)
    rpc.set_fees_on_builder_transaction(buildHandle, "1.3.0")
    params = rpc.get_object("2.0.0")[0]
    preview = params["parameters"]["committee_proposal_review_period"] or 10
    rpc.propose_builder_transaction2(
        buildHandle, proposer, formatTimeFromNow(expiration), preview, False
    )
    rpc.set_fees_on_builder_transaction(buildHandle, "1.3.0")

    # Sign and broadcast
    tx = rpc.sign_builder_transaction(buildHandle, broadcast)

    pprint(tx)
Example #15
0
def main(rpchost, rpcport, expiration, broadcast, proposer):
    rpc = GrapheneAPI(rpchost, rpcport)

    """ Update parameters here
    """
    updated_parameters = dict(maximum_transaction_size=1048576}

    tx = rpc.propose_parameter_change(
        proposer, formatTimeFromNow(expiration), updated_parameters, broadcast
    )

    click.echo(json.dumps(tx, indent=4))

    if not broadcast:
        click.echo("Set broadcast to 'True' if the transaction shall be broadcast!")
def run(port, n=0):
    client = GrapheneAPI("localhost", port)
    client.unlock("password")
    transfer = client.get_prototype_operation("transfer_operation")
    from_account = client.get_account("faucet")
    to_account = client.get_account("xeroc")
    transfer[1]["to"] = to_account["id"]
    transfer[1]["from"] = from_account["id"]
    transfer[1]["amount"]["amount"] = 1 + n

    while True:
        #builder = client.begin_builder_transaction()

        for i in range(0, 200 + random.randint(0, 1000)):
            print(n, end="", flush=True)
            #client.add_operation_to_builder_transaction(builder, transfer)
            client.transfer("faucet", "init0", 100 + n, "TEST", "", True)
Example #17
0
def main(rpchost, rpcport, expiration, broadcast, proposer):
    rpc = GrapheneAPI(rpchost, rpcport)
    expiration = datetime.utcfromtimestamp(time.time() + int(expiration)).strftime(
        "%Y-%m-%dT%H:%M:%S"
    )

    # Get current fees
    obj = rpc.get_object("2.0.0")[0]
    old_fees = obj["parameters"]["current_fees"]
    scale = int(obj["parameters"]["current_fees"]["scale"]) / 1e4
    core_asset = rpc.get_asset("1.3.0")

    # Get ticker/current price
    market = Market(config.market)
    ticker = market.ticker()
    # core_exchange_rate = float(ticker["core_exchange_rate"])
    settlement_price = float(ticker["quoteSettlement_price"])

    # Translate native fee in core_asset fee
    new_fees = config.native_fees.copy()
    for opName in new_fees:
        for f in new_fees[opName]:
            if config.force_integer_core_fee:
                new_fees[opName][f] = int(
                    int(config.native_fees[opName][f] / scale * settlement_price)
                    * 10 ** core_asset["precision"]
                )
            else:
                new_fees[opName][f] = int(
                    config.native_fees[opName][f]
                    * 10 ** core_asset["precision"]
                    / scale
                    * settlement_price
                )

    tx = rpc.propose_fee_change(proposer, expiration, new_fees, broadcast)
    new_fees = tx["operations"][0][1]["proposed_ops"][0]["op"][1]["new_parameters"][
        "current_fees"
    ]

    # Show differences from previous to new fees
    pprint(DeepDiff(old_fees, new_fees))

    if not broadcast:
        print("=" * 80)
        print("Set --broadcast if the transaction shall be broadcast!")
Example #18
0
    def compareConstructedTX(self):
        op = operations.Proposal_update(
            **{
                'fee_paying_account': "1.2.1",
                'proposal': "1.10.90",
                'active_approvals_to_add': ["1.2.5"],
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
            })
        """
        op = operations.Betting_market_resolve(**{
            "fee": {"amount": 0, "asset_id": "1.3.0"},
            "betting_market_id": "1.21.1",
            "resolution": "win",
            "prefix": prefix,
        })
        op = operations.Bet_cancel_operation(**{
            "fee": {"amount": 0, "asset_id": "1.3.0"},
            "bettor_id": "1.2.1241",
            "bet_to_cancel": "1.22.10",
            "prefix": prefix,
        })
        """
        ops = [Operation(op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())
        print(compare[:-130])
        print(txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
Example #19
0
def run(n=0):
    client = GrapheneAPI("localhost", 8092, "", "")
    transfer = client.get_prototype_operation("transfer_operation")
    from_account = client.get_account("faucet")
    to_account = client.get_account("xeroc")
    transfer[1]["to"] = to_account["id"]
    transfer[1]["from"] = from_account["id"]
    transfer[1]["amount"]["amount"] = 3

    while True:
        builder = client.begin_builder_transaction()

        for i in range(0, random.randint(100, 500)):
            print(n, end="", flush=True)
            client.add_operation_to_builder_transaction(builder, transfer)
        client.set_fees_on_builder_transaction(builder, "1.3.0")
        print("\nTransfer!")
        client.sign_builder_transaction(builder, True)
        time.sleep(random.randint(0, 3))
Example #20
0
    def compareConstructedTX(self):
        self.op = operations.Bet_place(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "bettor_id": "1.2.1241",
                "betting_market_id": "1.21.1",
                "amount_to_bet": {
                    "amount": 1000,
                    "asset_id": "1.3.1"
                },
                "backer_multiplier": 2 * GRAPHENE_BETTING_ODDS_PRECISION,
                "back_or_lay": "lay",
                "prefix": prefix,
            })
        ops = [Operation(self.op)]
        """
        from peerplays import PeerPlays
        ppy = PeerPlays()
        ops = transactions.addRequiredFees(ppy.rpc, ops)
        """
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        self.cm = rpc.serialize_transaction(tx.json())
        print("soll: %s" % self.cm[:-130])
        print("ist:  %s" % txWire[:-130])
        print(txWire[:-130] == self.cm[:-130])
        self.assertEqual(self.cm[:-130], txWire[:-130])
Example #21
0
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = transactions.Custom_json(
            **{
                "json": [
                    "reblog", {
                        "account":
                        "xeroc",
                        "author":
                        "chainsquad",
                        "permlink":
                        "streemian-com-to-open-its-doors-and-offer-a-20-discount"
                    }
                ],
                "required_auths": [],
                "required_posting_auths": ["xeroc"],
                "id":
                "follow"
            })
        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])
        txWire = hexlify(bytes(tx)).decode("ascii")

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())

        pprint(tx.json())

        print("\n")
        print(compare[:-130])
        print(txWire[:-130])
        print("\n")

        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = operations.Worker_create(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "owner": "1.2.0",
                "work_begin_date": "1970-01-01T00:00:00",
                "work_end_date": "1970-01-01T00:00:00",
                "daily_pay": 0,
                "name": "Myname",
                "url": "myURL",
                "initializer": [1, {
                    "pay_vesting_period_days": 125
                }]
            })
        ops = [Operation(op)]
        tx = 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")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())
        print("soll: %s" % compare[:-130])
        print("ist:  %s" % txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
Example #23
0
    def doit(self, printWire=False):
        ops = [Operation(self.op)]
        tx = 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], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        if printWire:
            print()
            print(txWire)
            print()
        self.assertEqual(self.cm[:-130], txWire[:-130])

        if TEST_AGAINST_CLI_WALLET:
            from grapheneapi.grapheneapi import GrapheneAPI
            rpc = GrapheneAPI("localhost", 8092)
            self.cm = rpc.serialize_transaction(tx.json())
            # print("soll: %s" % self.cm[:-130])
            # print("ist:  %s" % txWire[:-130])
            # print(txWire[:-130] == self.cm[:-130])
            self.assertEqual(self.cm[:-130], txWire[:-130])
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = transactions.Witness_update(
            **{"owner": "xeroc",
               "url": "foooobar",
               "block_signing_key": "STM6zLNtyFVToBsBZDsgMhgjpwysYVbsQD6YhP3kRkQhANUB4w7Qp",
               "props": {"account_creation_fee": "10.000 STEEM",
                         "maximum_block_size": 1111111,
                         "sbd_interest_rate": 1000},
               "fee": "10.000 STEEM",
               }
        )
        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])
        txWire = hexlify(bytes(tx)).decode("ascii")

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(tx.json())

        pprint(tx.json())

        print("\n")
        print(compare[:-130])
        print(txWire[:-130])
        print("\n")

        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
Example #25
0
    def compareConstructedTX(self):
        #    def test_online(self):
        #        self.maxDiff = None
        op = transactions.Account_create(
            **{
                "fee": {
                    "amount": 1467634,
                    "asset_id": "1.3.0"
                },
                "registrar": "1.2.33",
                "referrer": "1.2.27",
                "referrer_percent": 3,
                "name": "foobar-f124",
                "owner": {
                    "weight_threshold":
                    1,
                    "account_auths": [],
                    "key_auths": [[
                        "BTS5TPTziKkLexhVKsQKtSpo4bAv5RnB8oXcG4sMHEwCcTf3r7dqE",
                        1
                    ]],
                    "address_auths": []
                },
                "active": {
                    "weight_threshold":
                    1,
                    "account_auths": [],
                    "key_auths": [[
                        "BTS5TPTziKkLexhVKsQKtSpo4bAv5RnB8oXcG4sMHEwCcTf3r7dqE",
                        1
                    ]],
                    "address_auths": []
                },
                "options": {
                    "memo_key":
                    "BTS5TPTziKkLexhVKsQKtSpo4bAv5RnB8oXcG4sMHEwCcTf3r7dqE",
                    "voting_account":
                    "1.2.5",
                    "num_witness":
                    26,
                    "num_committee":
                    8,
                    "votes": [
                        "1:22", "1:23", "1:24", "1:25", "1:26", "1:27", "1:28",
                        "1:30", "1:31", "1:32", "1:34", "1:35", "1:36", "1:37",
                        "1:38", "1:40", "1:41", "1:44", "1:45", "1:49", "1:51",
                        "1:56", "1:60", "0:76", "0:84", "0:87", "0:88", "0:91",
                        "0:141", "1:143", "0:147", "2:148", "2:150", "1:165",
                        "1:166", "2:171", "0:173", "2:179"
                    ],
                    "extensions": []
                },
                "extensions": {}
            })

        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)
        tx.verify([PrivateKey(wif).pubkey], "BTS")
        txWire = hexlify(bytes(tx)).decode("ascii")
        pprint(transactions.JsonObj(tx))

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        compare = rpc.serialize_transaction(transactions.JsonObj(tx))
        print(compare[:-130])
        print(txWire[:-130])
        print(txWire[:-130] == compare[:-130])
        self.assertEqual(compare[:-130], txWire[:-130])
from grapheneapi.grapheneapi import GrapheneAPI

import json
import random
import math

if __name__ == '__main__':
    rpc = GrapheneAPI("localhost", 8092)

    asset_symbol = "CNY"
    producers = ["fakeusd-feed-producer"]

    price = random.normalvariate(134, 0.1)
    price = math.fabs(price)

    asset = rpc.get_asset(asset_symbol)
    base = rpc.get_asset("1.3.0")
    price = price * 10**asset["precision"] / 10**base["precision"]
    denominator = 1e5
    numerator = round(price * 1e5)

    for producer in producers:
        account = rpc.get_account(producer)
        price_feed = {
            "settlement_price": {
                "quote": {
                    "asset_id": "1.3.0",
                    "amount": denominator
                },
                "base": {
                    "asset_id": asset["id"],
Example #27
0
def update_price_feed():
    global derived_prices, config
    state = {}

    for asset in _all_assets + [core_symbol]:
        price_median_blockchain[asset] = 0.0
        lastUpdate[asset] = datetime.utcnow()
        myCurrentFeed[asset] = {}

    if configFile.blame != "latest":
        blameFile = config.configPath + "/blame/" + configFile.blame + ".json"
        if os.path.isfile(blameFile):
            # Load data from disk for (faster) debugging and verification
            with open(blameFile, 'r') as fp:
                state = json.load(fp)
                # Load feed sources
                feed = state["feed"]
                # Load configuration from old state
                configStruct = state["config"]
                for key in configStruct:
                    # Skip asset config
                    if key == "asset_config":
                        continue
                    config.__dict__[key] = configStruct[key]

        else:
            sys.exit(
                "Configuration error: Either set 'blame' to an existing " +
                "block number from the blame/ to verify or set it to " +
                "'latest' to run the script online! ")
    else:
        # Load configuration from file
        config = configFile
        # Get prices online from sources
        pool = futures.ThreadPoolExecutor(max_workers=8)
        feed = {}
        mythreads = {}

        for name in config.feedSources:
            print("(%s)" % name, end="", flush=True)
            mythreads[name] = pool.submit(config.feedSources[name].fetch)

        for name in config.feedSources:
            print(".", end="", flush=True)
            feed[name] = mythreads[name].result()

    # rpc variables about bts rpc ##############################################
    rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd)
    fetch_from_wallet(rpc)

    # Determine bts price ######################################################
    derived_prices = derive_prices(feed)

    # Only publish given feeds #################################################
    price_feeds = {}
    update_required = False

    for asset in asset_list_publish:

        # Get Final Price according to price metric
        this_asset_config = config.asset_config[
            asset] if asset in config.asset_config else config.asset_config[
                "default"]
        price_metric = this_asset_config[
            "metric"] if "metric" in this_asset_config else config.asset_config[
                "default"]["metric"]
        if (asset not in derived_prices
                or core_symbol not in derived_prices[asset]
                or price_metric not in derived_prices[asset][core_symbol]):
            print("Warning: Asset %s has no derived price!" % asset)
            continue
        if float(derived_prices[asset][core_symbol][price_metric]) > 0.0:
            quote_precision_core = assets[asset]["precision"]
            symbol = assets[asset]["symbol"]
            assert symbol is not asset
            base_precision_cer = assets[blockchain_feed_quote[asset]][
                "precision"]  # core asset
            core_price_cer = derived_prices[asset][core_symbol][
                price_metric] * 10**(quote_precision_core - base_precision_cer)
            core_price_cer = fractions.Fraction.from_float(
                core_price_cer).limit_denominator(100000)
            denominator_cer = core_price_cer.denominator
            numerator_cer = core_price_cer.numerator

            quote_precision_settle = assets[asset]["precision"]
            symbol = assets[asset]["symbol"]
            assert symbol is not asset
            base_precision_settle = assets[blockchain_feed_quote[asset]][
                "precision"]  # core asset
            core_price_settle = derived_prices[asset]["short_backing_asset"][
                price_metric] * 10**(quote_precision_settle -
                                     base_precision_settle)
            core_price_settle = fractions.Fraction.from_float(
                core_price_settle).limit_denominator(100000)
            denominator_settle = core_price_settle.denominator
            numerator_settle = core_price_settle.numerator

            price_feed = {
                "settlement_price": {
                    "quote": {
                        "asset_id": assets[blockchain_feed_quote[asset]]["id"],
                        "amount": denominator_settle
                    },
                    "base": {
                        "asset_id": assets[asset]["id"],
                        "amount": numerator_settle
                    }
                },
                "maintenance_collateral_ratio":
                config.asset_config[symbol]["maintenance_collateral_ratio"] if
                (symbol in config.asset_config
                 and "maintenance_collateral_ratio"
                 in config.asset_config[symbol]) else
                config.asset_config["default"]["maintenance_collateral_ratio"],
                "maximum_short_squeeze_ratio":
                config.asset_config[symbol]["maximum_short_squeeze_ratio"] if
                (symbol in config.asset_config
                 and "maximum_short_squeeze_ratio"
                 in config.asset_config[symbol]) else
                config.asset_config["default"]["maximum_short_squeeze_ratio"],
                "core_exchange_rate": {
                    "quote": {
                        "asset_id":
                        "1.3.0",
                        "amount":
                        int(denominator_cer *
                            (config.asset_config[symbol]
                             ["core_exchange_factor"] if
                             (symbol in config.asset_config
                              and "core_exchange_factor"
                              in config.asset_config[symbol]) else config.
                             asset_config["default"]["core_exchange_factor"]))
                    },
                    "base": {
                        "asset_id": assets[asset]["id"],
                        "amount": numerator_cer
                    }
                }
            }
            asset_update_required = publish_rule(rpc, asset)
            if asset_update_required:
                update_required = True
            price_feeds[symbol] = {
                "asset_id": assets[asset]["id"],
                "feed": price_feed,
                "publish": asset_update_required
            }
        else:
            print(
                "Warning: Asset %s has a negative derived price of %f (%s metric)!"
                % (asset, float(
                    derived_prices[asset][price_metric]), price_metric))
            continue

    if not debug:
        # Print some stats ##########################################################
        print_stats(price_feeds)

        # Verify results or store them ##############################################
        configStruct = {}
        for key in dir(config):
            if key[0] == "_":
                continue
            if key == "feedSources":
                continue
            if key == "feedsources":
                continue
            if key == "subprocess":
                continue
            if key == "os":
                continue
            configStruct[key] = config.__dict__[key]
        # Store State
        state["feed"] = feed
        state["derived_prices"] = derived_prices
        state["price_feeds"] = price_feeds
        state["lastblock"] = get_last_block(rpc)
        state["config"] = configStruct
        blameFile = config.configPath + "/blame/" + str(
            state["lastblock"]) + ".json"
        with open(blameFile, 'w') as fp:
            json.dump(state, fp)
        print("Blamefile: " + blameFile)

        # Check publish rules and publich feeds #####################################
        if update_required and not debug:
            publish = False
            if config.ask_confirmation:
                if rpc._confirm(
                        "Are you SURE you would like to publish this feed?"):
                    publish = True
            else:
                publish = True

            if publish:
                print("Update required! Forcing now!")
                update_feed(rpc, price_feeds)
        else:
            print("no update required")

    else:
        # Verify results
        print()
        print(
            "[Warning] This script is loading old data for debugging. No price can be published.\n"
            +
            "          Please set 'blame' to 'latest' if you are ready to go online!"
        )
        print()
        compare_feeds(state["derived_prices"], derived_prices)
from grapheneapi.grapheneapi import GrapheneAPI
from bitsharesbase.operations import getOperationNameForId
from bitshares.market import Market
from bitshares import BitShares
import math
import config

if __name__ == "__main__":
    graphene = GrapheneAPI(config.wallet_host, config.wallet_port)
    bts = BitShares(config.witness_url)

    # Get current fees
    core_asset = graphene.get_asset("1.3.0")
    committee_account = graphene.get_account("committee-account")
    proposals = bts.rpc.get_proposed_transactions(committee_account["id"])

    # Get ticker/current price
    market = Market(config.market)
    ticker = market.ticker()
    core_exchange_rate = float(ticker["core_exchange_rate"])
    settlement_price = float(ticker["quoteSettlement_price"])

    for proposal in proposals:
        print("Proposal: %s" % proposal["id"])

        prop_op = proposal["proposed_transaction"]["operations"]

        if len(prop_op) > 1:
            print(" - [Warning] This proposal has more than 1 operation")

        for op in prop_op:
Example #29
0
from grapheneapi.grapheneapi import GrapheneAPI
from graphenebase.transactions import formatTimeFromNow
from pprint import pprint

broadcast = True
proposer = "faucet"

client = GrapheneAPI("localhost", 8092, "", "")
obj = client.get_object("2.0.0")[0]
expiration = formatTimeFromNow(
    obj["parameters"]["committee_proposal_review_period"] + 30)

parameters = {
    "block_interval": 3,
    "maintenance_interval": 60 * 2,
    "maintenance_skip_slots": 3,
    "committee_proposal_review_period": 0,
    "maximum_transaction_size": 2048,
    "maximum_block_size": 2048000000,
    "maximum_time_until_expiration": 86400,
    "maximum_proposal_lifetime": 2419200,
    "maximum_asset_whitelist_authorities": 10,
    "maximum_asset_feed_publishers": 10,
    "maximum_witness_count": 1001,
    "maximum_committee_count": 1001,
    "maximum_authority_membership": 10,
    "reserve_percent_of_fee": 2000,
    "network_percent_of_fee": 2000,
    "lifetime_referrer_percent_of_fee": 3000,
    "cashback_vesting_period_seconds": 31536000,
    "cashback_vesting_threshold": 10000000,