Ejemplo n.º 1
0
    def QUpdateAccount(self,
                       account_name,
                       owner_key,
                       active_key,
                       memo_key,
                       voting_account,
                       num_witness,
                       num_committee,
                       votes,
                       fee_asset=None,
                       isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(account_name)
        dst_account = iso.getAccount(voting_account)
        params = {
            "account": src_account['id'],
        }
        from bitshares.blind import key_permission
        role = "active"
        if owner_key:
            owner_auth = key_permission(owner_key)
            params["owner"] = owner_auth
            role = "owner"
        if active_key:
            active_auth = key_permission(active_key)
            params["active"] = active_auth
            role = "owner"
        if not (votes is None):
            params["new_options"] = {
                "voting_account":
                dst_account["id"],
                "memo_key":
                memo_key if memo_key else src_account["options"]["memo_key"],
                "votes":
                votes,
                "num_witness":
                num_witness,
                "num_committee":
                num_committee,
            }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Account_update(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, role, lazy=True)
        else:
            tx.appendSigner(src_account, role, lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 2
0
    def QFundFeePool(self,
                     asset_id,
                     amount_num,
                     source_account,
                     fee_asset=None,
                     isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(source_account)
        amount = iso.getAmount(amount_num, asset_id).json()
        params = {
            "from_account": iso.getAccount(source_account)['id'],
            "asset_id": amount["asset_id"],
            "amount": int(amount["amount"]),
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Asset_fund_fee_pool(**params))
        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 3
0
    def QUpgradeAccount(self, account_name, fee_asset=None, isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(account_name)
        params = {
            "account_to_upgrade": src_account['id'],
            "upgrade_to_lifetime_member": True,
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Account_upgrade(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 4
0
    def VTransfer(self,
                  asset_id,
                  amount_num,
                  source_account,
                  target_account,
                  memo=None,
                  fee_asset=None,
                  isolator=None):
        iso = isolator
        tx = TransactionBuilder(blockchain_instance=iso.bts)
        src_account = iso.getAccount(source_account)
        params = {
            "amount": iso.getAmount(amount_num, asset_id).json(),
            "from": iso.getAccount(source_account)['id'],
            "to": iso.getAccount(target_account)['id'],
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}
        if memo:
            with iso.unlockedWallet() as w:
                params['memo'] = iso.getMemo(source_account, target_account,
                                             memo)

        return (Transfer(**params), [(src_account, "active")])
Ejemplo n.º 5
0
    def QViewTransaction(self, trx, highlight=-1, isolator=None):
        iso = isolator
        blockchain_instance = iso.bts

        trx["operations"] = [
            getOperationClassForId(op_id)(**op)
            for (op_id, op) in trx["operations"]
        ]
        tx = TransactionBuilder(trx, blockchain_instance=blockchain_instance)

        #for (op_id, op) in trx["operations"]:
        #	op_klass = getOperationClassForId(op_id)
        #	log.debug("getOpertationClassForId %d yields %s" % (op_id, op_klass.__name__))
        #	tx.appendOps(op_klass(**op))

        #if "signatures" in trx:
        #	tx["signatures"] = trx["signatures"]
        #
        #if "missing_signatures" in trx:
        #    tx["missing_signatures"] = trx["missing_signatures"]

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        win.setPreviewMode(True)
        win.highlightOp(highlight)
        return win.exec_()
Ejemplo n.º 6
0
    def QReserveAsset(self,
                      asset_id,
                      amount_num,
                      source_account,
                      fee_asset=None,
                      isolator=None):
        iso = isolator
        bitshares_instance = iso.bts
        tx = TransactionBuilder(bitshares_instance=bitshares_instance)
        src_account = iso.getAccount(source_account)
        params = {
            "amount_to_reserve": iso.getAmount(amount_num, asset_id).json(),
            "payer": iso.getAccount(source_account)['id'],
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Asset_reserve(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 7
0
def flood(ctx, account, ops, txs, to):
    from bitsharesbase.operations import Transfer
    from bitshares.transactionbuilder import TransactionBuilder
    assert ctx.bitshares.rpc.chain_params[
        "prefix"] == "TEST", "Flooding only on the testnet. Please switch the API to node testnet.bitshares.eu"
    account = Account(account, bitshares_instance=ctx.bitshares)
    to_account = Account(to, bitshares_instance=ctx.bitshares)
    tx = TransactionBuilder(bitshares_instance=ctx.bitshares)

    txcnt = 0
    while txcnt < txs or txs < 0:
        txcnt += 1
        for j in range(0, ops):
            tx.appendOps(
                Transfer(
                    **{
                        "fee": {
                            "amount": 0,
                            "asset_id": "1.3.0"
                        },
                        "from": account["id"],
                        "to": to_account["id"],
                        "amount": {
                            "amount": 1,
                            "asset_id": "1.3.0"
                        },
                        "memo": None
                    }))
        tx.appendSigner(account, "active")
        tx.broadcast()
        click.echo(tx["signatures"])
Ejemplo n.º 8
0
    def obtain_raw_tx():
#         if old_operation is None:
        _memo = memo.encrypt(memo_plain)
        _expiration = Config.get("bitshares", "transaction_expiration_in_sec", 60 * 60 * 24)  # 24 hours
#         else:
#             memo_encrypted = memo.encrypt(memo_plain)

        op = operations.Transfer(**{
            "fee": {
                "amount": 0,
                "asset_id": "1.3.0"
            },  # will be replaced
            "from": from_account["id"],
            "to": to_account["id"],
            "amount": amount.json(),
            "memo": _memo,
            "prefix": bitshares_instance.prefix
        })

        tx = TransactionBuilder(
            bitshares_instance=bitshares_instance
        )
        tx.appendOps(op)
        tx.set_expiration(_expiration)

        # Build the transaction, obtain fee to be paid
        tx.constructTx()
        return tx.json()
Ejemplo n.º 9
0
	def open_transactionbuffer(self):
		if not(self.ui.txFrame.isVisible()):
			showmessage("Collect several transactions into one. Press Apply when ready.")
			self.trxbuffer = TransactionBuilder(bitshares_instance=self.iso.bts)
		
		self._txRedraw()
		self.ui.txFrame.setVisible(True)
Ejemplo n.º 10
0
def broadcast(ctx, filename):
    if filename:
        tx = filename.read()
    else:
        tx = sys.stdin.read()
    tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
    tx.broadcast()
    pprint(tx.json())
Ejemplo n.º 11
0
def sign(ctx, filename):
    if filename:
        tx = filename.read()
    else:
        tx = sys.stdin.read()
    tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
    tx.appendMissingSignatures()
    tx.sign()
    pprint(tx.json())
Ejemplo n.º 12
0
def send_claim(ctx, claim_expiration):

    proposalBuilder = ProposalBuilder("vel-ma", claim_expiration
                                      or 2 * 24 * 60 * 60)

    tx = TransactionBuilder(eval(proposalBuilder.json()),
                            bitshares_instance=ctx.bitshares)
    tx.broadcast()
    print_tx(tx.json())
Ejemplo n.º 13
0
def broadcast(ctx, filename):
    """ Broadcast a json-formatted transaction
    """
    if filename:
        tx = filename.read()
    else:
        tx = sys.stdin.read()
    tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
    tx.broadcast()
    print_tx(tx.json())
Ejemplo n.º 14
0
def sign(ctx, filename):
    """ Sign a json-formatted transaction
    """
    if filename:
        tx = filename.read()
    else:
        tx = sys.stdin.read()
    tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
    tx.appendMissingSignatures()
    tx.sign()
    print_tx(tx.json())
Ejemplo n.º 15
0
    def _QExecS(self, iso, vs):
        tx = TransactionBuilder(blockchain_instance=iso.bts)
        for (op, sigs) in vs:
            tx.appendOps(op)
            for (account, role) in sigs:
                if iso.bts.wallet.locked():
                    tx.addSigningInformation(account, role, lazy=True)
                else:
                    tx.appendSigner(account, role, lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=iso)
        return win.exec_()
Ejemplo n.º 16
0
    def QCreateWorker(self,
                      worker_account,
                      name,
                      url,
                      begin_date,
                      end_date,
                      daily_pay,
                      worker_type,
                      vesting_days=365,
                      fee_asset=None,
                      isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(worker_account)
        if isinstance(daily_pay, float):
            daily_pay = int(daily_pay * 100000)
        if worker_type == "vesting" or worker_type == 1:
            work_init = (1, {"pay_vesting_period_days": vesting_days})
        elif worker_type == "burn" or worker_type == 2:
            work_init = (2, None)
        elif worker_type == "refund" or worker_type == 0:
            work_init = (0, None)
        else:
            raise ValueError("Unknown worker_type")
        params = {
            "owner": src_account['id'],
            "name": name,
            "url": url,
            "work_begin_date": begin_date.strftime("%Y-%m-%dT%H:%M:%S"),
            "work_end_date": end_date.strftime("%Y-%m-%dT%H:%M:%S"),
            "daily_pay": daily_pay,
            "initializer": work_init
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Worker_create(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 17
0
    def QTransferToBlind(self,
                         asset_id,
                         amount_num,
                         source_account,
                         target_pubkey,
                         fee_asset=None,
                         isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(source_account)
        asset = iso.getAsset(asset_id)
        amount = iso.getAmount(amount_num, asset_id).json()

        from bitshares.blind import gen_blind_outputs
        confirm, balances = gen_blind_outputs(
            [[target_pubkey, amount["amount"]]], asset["id"]
            #,debug_priv="5JG5w3hXMq1fb32hzzd3CSWj4EMXeX6tiN2yxJf6SYZ8eZJ4EBB"
        )

        params = {
            "amount": confirm["amount"],
            "from": src_account['id'],
            "blinding_factor": confirm["blinding_factor"],
            "outputs": confirm["outputs"],
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Transfer_to_blind(**params))
        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        r = win.exec_()
        if not r:
            return False
        for b in balances:
            b["description"] = "from @" + src_account["name"]
        win._receiveBlindTransfers(iso,
                                   balances, [],
                                   comment1="@" + src_account["name"])
        return True
Ejemplo n.º 18
0
    def VUpdateAsset(self,
                     symbol,
                     issuer,
                     new_issuer=None,
                     flags={},
                     description="",
                     is_prediction_market=False,
                     market_fee_percent=0,
                     core_exchange_rate=None,
                     fee_asset=None,
                     isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(issuer)
        new_account = iso.getAccount(new_issuer) if new_issuer else None
        if new_account and new_account["id"] == src_account["id"]:
            new_account = None
        flags_int = toint(flags)
        asset = iso.getAsset(symbol)
        options = asset['options']
        options['description'] = description
        options['flags'] = flags_int
        options['market_fee_percent'] = market_fee_percent
        if core_exchange_rate:
            core_exchange_rate["quote"]["asset_id"] = asset["id"]
            options["core_exchange_rate"] = core_exchange_rate
        #options = {
        #	"market_fee_percent": 0, #1 - 1 percent?
        #	"flags": flags_int,
        #	"whitelist_authorities" : [],
        #	"blacklist_authorities" : [],
        #	"whitelist_markets" : [],
        #	"blacklist_markets" : [],
        #	"description": description,
        #}
        params = {
            "issuer": src_account['id'],
            "asset_to_update": asset['id'],
            "new_options": options,
        }
        if "is_prediction_market" in asset:
            params["is_prediction_market"] = is_prediction_market
        if new_account:
            params["new_issuer"] = new_account["id"]
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        return (Asset_update(**params), [(src_account, "active")])
Ejemplo n.º 19
0
    def QTransferFromBlind(self,
                           asset_id,
                           amount_num,
                           source_pubkey,
                           target_account,
                           fee_asset=None,
                           isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        dst_account = iso.getAccount(target_account)
        asset = iso.getAsset(asset_id)
        amount = iso.getAmount(amount_num, asset_id).json()

        from bitshares.blind import transfer_from_blind
        confirm = transfer_from_blind(
            blockchain_instance,
            source_pubkey,
            dst_account["id"],
            amount["amount"],
            asset["symbol"],
            broadcast=False
            #,debug_priv="5JG5w3hXMq1fb32hzzd3CSWj4EMXeX6tiN2yxJf6SYZ8eZJ4EBB"
        )
        tx = confirm["trx"]
        #		if fee_asset:
        #			params['fee'] = iso.getAmount(0, fee_asset).json()
        #		else:
        #			params['fee'] = {"amount": 0, "asset_id": "1.3.0"}
        #
        #		from pprint import pprint
        #		print("USE:")
        #		pprint(params)
        #
        #		tx.appendOps(Transfer_from_blind(**params))
        #		if iso.bts.wallet.locked():
        #			tx.addSigningInformation(dst_account, "active", lazy=True)
        #		else:
        #			tx.appendSigner(dst_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        r = win.exec_()
        if not r:
            return False
        win._receiveBlindTransfers(iso,
                                   confirm["balances"],
                                   confirm["inputs"],
                                   to_temp=True)
        return True
Ejemplo n.º 20
0
    def import_transaction(self):
        path, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Import transaction file', '',
            "bitshares transaction (*.json)")
        if not path:
            return False

        with open(path, "r") as f:
            data = f.read()

        trx = json.loads(data)
        trx["operations"] = [
            getOperationClassForId(op_id)(**op)
            for (op_id, op) in trx["operations"]
        ]

        tx = TransactionBuilder(trx, blockchain_instance=self.iso.bts)
        self.tx = tx
        self.applyTransaction(tx, self.iso)

        return True
Ejemplo n.º 21
0
    def VCancelOrder(self,
                     source_account,
                     order_id,
                     fee_asset=None,
                     isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(source_account)
        params = {
            "fee_paying_account": iso.getAccount(source_account)['id'],
            "order": order_id,
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        return (Limit_order_cancel(**params), [(src_account, "active")])
Ejemplo n.º 22
0
    def QIssueAsset(self,
                    asset_id,
                    amount_num,
                    source_account,
                    target_account,
                    memo=None,
                    fee_asset=None,
                    isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(source_account)
        params = {
            "asset_to_issue": iso.getAmount(amount_num, asset_id).json(),
            "issuer": iso.getAccount(source_account)['id'],
            "issue_to_account": iso.getAccount(target_account)['id'],
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}
        if memo:
            params['memo'] = iso.getMemo(source_account, target_account, memo)

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Asset_issue(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 23
0
    def VSellAsset(self,
                   source_account,
                   sell_asset_id,
                   sell_amount,
                   buy_asset_id,
                   buy_amount,
                   expiration=3600 * 24,
                   fill_or_kill=False,
                   fee_asset=None,
                   isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(source_account)
        params = {
            "seller": iso.getAccount(source_account)['id'],
            "amount_to_sell": iso.getAmount(sell_amount, sell_asset_id).json(),
            "min_to_receive": iso.getAmount(buy_amount, buy_asset_id).json(),
            "expiration": expiration,
            "fill_or_kill": fill_or_kill,
        }
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        import datetime
        now = datetime.datetime.utcnow()
        add = datetime.timedelta(seconds=expiration)
        params["expiration"] = (now + add).strftime("%Y-%m-%dT%H:%M:%S")

        from pprint import pprint
        print("USE:")
        pprint(params)

        return (Limit_order_create(**params), [(src_account, "active")])
Ejemplo n.º 24
0
    def QCreateAsset(self,
                     issuer,
                     symbol,
                     precision,
                     max_supply,
                     permissions={},
                     flags={},
                     description="",
                     market_fee_percent=0,
                     core_exchange_rate=None,
                     is_prediction_market=False,
                     bitasset_options=None,
                     fee_asset=None,
                     isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        src_account = iso.getAccount(issuer)
        permissions_int = toint(permissions)
        flags_int = toint(flags)
        #max_supply = total * pow(10, precision)
        #print("TOTAL:", total, "=> MAX SUPPLY:", max_supply)
        options = {
            "max_supply": max_supply,  #satoshi
            "market_fee_percent": market_fee_percent,  #0-100
            "max_market_fee": max_supply,  # satoshi
            "issuer_permissions": permissions_int,
            "flags": flags_int,
            "core_exchange_rate": {
                "base": {
                    "amount": 1 * 100000,
                    "asset_id": "1.3.0"
                },
                "quote": {
                    "amount": 1 * pow(10, precision),
                    "asset_id": "1.3.1"
                }
            },
            "whitelist_authorities": [],
            "blacklist_authorities": [],
            "whitelist_markets": [],
            "blacklist_markets": [],
            "description": description,
            "extensions": [],
        }
        if core_exchange_rate:
            core_exchange_rate["quote"]["asset_id"] = "1.3.1"
            options["core_exchange_rate"] = core_exchange_rate
        #bitasset_options = {
        #	"feed_lifetime_sec": 86400,
        #	"minimum_feeds": 1,
        #	"force_settlement_delay_sec": 86400,
        #	"force_settlement_offset_percent": 0,
        #	"maximum_force_settlement_volume": 2000,
        #	"short_backing_asset": "1.3.0"
        #	"extensions": []
        #}
        bitasset_options = {
            "feed_lifetime_sec":
            bitasset_options["feed_lifetime_sec"],
            "minimum_feeds":
            bitasset_options["minimum_feeds"],
            "force_settlement_delay_sec":
            bitasset_options["force_settlement_delay_sec"],
            "force_settlement_offset_percent":
            bitasset_options["force_settlement_offset_percent"],
            "maximum_force_settlement_volume":
            bitasset_options["maximum_force_settlement_volume"],
            "short_backing_asset":
            bitasset_options["short_backing_asset"],
            "extensions": []
        } if bitasset_options else None
        params = {
            "issuer": src_account['id'],
            "symbol": symbol,
            "precision": precision,
            "common_options": options,
            "bitasset_opts": bitasset_options,
            "is_prediction_market": False,
        }
        if bitasset_options:
            params["is_prediction_market"] = False
        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        from pprint import pprint
        print("USE:")
        pprint(params)

        tx.appendOps(Asset_create(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(src_account, "active", lazy=True)
        else:
            tx.appendSigner(src_account, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()
Ejemplo n.º 25
0
def broadcast_transaction(signed_transaction, bitshares_instance=None):
    if type(signed_transaction) == str:
        signed_transaction = json.loads(signed_transaction)

    tx = TransactionBuilder(
        signed_transaction,
        bitshares_instance=bitshares_instance
    )

    # Only broadcast if case 2 || 3
    assert len(tx.json()["operations"]) == 1, "Only one op per transaction allowed"
    from_account = tx.json()["operations"][0][1]["from"]
    to_account = tx.json()["operations"][0][1]["to"]

    # insert all transactions into storage
    storage = _get_os()

    def map_operation(tx, op_in_tx, operation):
        assert operation[0] == 0, "We only deal with transfers!"
        j = dict(
            op=operation,
            decoded_memo=tx["decoded_memo"],
            expiration=tx["expiration"],
            op_in_tx=op_in_tx,
            transaction_id=tx["transaction_id"]
        )
        if tx.get("incident_id", None) is not None:
            j["incident_id"] = tx["incident_id"]
        return operation_formatter.decode_operation(j)

    for op_in_tx, operation in enumerate(tx.get("operations", [])):
        storage.insert_operation(map_operation(tx, op_in_tx, operation))

    exception_occured = None
    try:
        # check validity
        tx.verify_authority()
    except Exception as e:
        exception_occured = e

    if exception_occured is None and from_account != to_account:
        try:
            tx = tx.broadcast()
            if tx.get("id", None):
                return {"hash": tx["id"] + ":" + str(tx["trx_num"]), "block": tx["block_num"]}
            else:
                return {"hash": "no_id_given", "block": -1}
        except UnhandledRPCError as e:
            if "insufficient_balance" in str(e):
                raise NotEnoughBalanceException()
            elif "amount.amount > 0" in str(e):
                raise AmountTooSmallException()
            elif "now <= trx.expiration" in str(e):
                raise TransactionExpiredException()
            else:
                raise e
        except Exception as e:
            exception_occured = e

    if exception_occured:
        # this operation might not exist
        for op_in_tx, operation in enumerate(tx.get("operations", [])):
            storage.flag_operation_failed(map_operation(tx, op_in_tx, operation),
                                          str(exception_occured))
        raise exception_occured

    if from_account == to_account:
        block_num = bitshares_instance.rpc.get_dynamic_global_properties()['last_irreversible_block_num']
        # This happens in case of virtual consolidation transactions/transfers
        for op_in_tx, operation in enumerate(tx.get("operations", [])):
            op = map_operation(tx, op_in_tx, operation)
            op["block_num"] = block_num + (op_in_tx + 1) * 0.1
            op["tx_in_block"] = 0
            op["fee_value"] = 0
            storage.flag_operation_completed(op)
        return {"hash": "virtual_transfer", "block": op["block_num"]}
    else:
        raise Exception("This should be unreachable")
Ejemplo n.º 26
0
    def QRegisterAccount(self,
                         registrar_name,
                         referrer_name,
                         data,
                         fee_asset=None,
                         isolator=None):
        iso = isolator
        blockchain_instance = iso.bts
        tx = TransactionBuilder(blockchain_instance=blockchain_instance)
        registrarAccount = iso.getAccount(registrar_name)
        referrerAccount = iso.getAccount(referrer_name)

        if not (registrarAccount.is_ltm):
            showerror("%s is not a lifetime member" % registrar_name)
            return None

        params = {
            "registrar": registrarAccount['id'],
            "referrer": referrerAccount['id'],
            "referrer_percent": 100,
            "name": data['name'],
            "owner": {
                'account_auths': [],
                'address_auths': [],
                'weight_threshold': 1,
                'key_auths': [[data['owner_key'], 1]]
            },
            "active": {
                'account_auths': [],
                'address_auths': [],
                'weight_threshold': 1,
                'key_auths': [[data['active_key'], 1]]
            },
            "options": {
                "memo_key": data['memo_key'],
                "votes": [],
                "voting_account": registrarAccount['id'],
                "num_witness": 0,
                "num_committee": 0,
            },
            "extensions": []
        }

        if fee_asset:
            params['fee'] = iso.getAmount(0, fee_asset).json()
        else:
            params['fee'] = {"amount": 0, "asset_id": "1.3.0"}

        #from pprint import pprint
        #print("USE:")
        #pprint(params)

        tx.appendOps(Account_create(**params))

        if iso.bts.wallet.locked():
            tx.addSigningInformation(registrarAccount, "active", lazy=True)
        else:
            tx.appendSigner(registrarAccount, "active", lazy=True)

        win = QTransactionBuilder(trxbuffer=tx, iso=isolator)
        return win.exec_()