Example #1
0
def sending_asset(Asset_symbol,Asset_Issuer,desAdd,amount):
    '''Similar to sending_lumen except this function sends created assets.
    Asset_symbol: string, symbol of the asset, eg. 'BTC'
    Asset_Issuer: string, Address of the asset Issuer.
    desAdd:string, the address of the lumen receiver.
    amount:float, the amount of lumens you want to send.
    msg:string, optional, the message you want to attach to the transaction.'''
    data = Get_data()
    
    sourceAdd = data['Address']
    asset = asset_Identifier(Asset_symbol,Asset_Issuer)
    
    sequence = horizon.account(sourceAdd).get('sequence')
    op = Payment({'asset':asset,'amount':str(amount),'destination':desAdd})
    tx = Transaction(source=sourceAdd,opts={'sequence':sequence,'operations':[op]})
    envelope_send = Te(tx = tx,opts = {"network_id":"PUBLIC"})
    
    try: envelope_send.sign(Trezor_Access())
    except: raise Exception("Device is currently in use, try reconnect the device")
    
    xdr = envelope_send.xdr()
    xdr = xdr.decode()
    response = horizon.submit(xdr)
    passed_or_not(response)
    return response
Example #2
0
def main(inflation):
    # TODO: Let user select the connection type
    # The stellar/quickstart Docker image uses PostgreSQL
    conn = sqlite3.connect(db_address)

    # Get the next sequence number for the transactions
    sequence = horizon.account(pool_address).get('sequence')
    inflation = XLM_Decimal(inflation)
    transactions = []
    total_payments_cost = 0
    num_payments = 0
    total_fee_cost = 0

    # Create one transaction for each batch
    for batch in accounts_payouts(conn, pool_address, inflation):
        op_count = 0
        ops = {'sequence': sequence, 'operations': []}
        for aid, amount in batch:
            # Check if the payment destination (aid) is valid
            try:
                acc = horizon.get(aid)
            except AccountNotExistError:
                continue
            if not acc:
                continue
            # Include payment operation on ops{}
            ops['operations'].append(aid, amount)
            op_count += 1

        # Build transaction
        tx = Transaction(source=pool_address, opts=ops)
        tx.fee = op_count * BASE_FEE
        envelope = Te(tx=tx, opts={"network_id": network})
        # Append the transaction plain-text (JSON) on the list
        transactions.append(envelope.xdr().decode("utf-8"))

        # Calculate stats
        total_fee_cost += XLM_Decimal(tx.fee) / XLM_STROOP
        total_payments_cost += sum(
            [XLM_Decimal(payment.amount) for payment in tx.operations])
        num_payments += len(tx.operations)

        # Prepare the next sequence number for the transactions
        sequence = int(sequence) + 1

    print(("Stats: \n"
           "Inflation received: %s\n"
           "A total of %s XLM paid over %s inflation payments "
           "using %s XLM in fees. \n"
           "Number of people that donated votes: %s\n") % (
               inflation,
               total_payments_cost,
               num_payments,
               total_fee_cost,
               len(donors),
           ))

    with open("transactions.json", 'w') as outf:
        json.dump(transactions, outf)
    print("Done. Output to transactions.json")
Example #3
0
def send_xlm_vault_transaction(user, destination, amount):
    from stellar_base.transaction import Transaction
    wallet = VaultWallet.objects.get(username=user, name="xlm")
    User = Keypair.from_seed(wallet.private)
    horizon = horizon_testnet()
    asset = Asset.native()

    op = Payment({
        'destination': destination,
        'asset': asset,
        'amount': amount
    })
    msg = TextMemo('From test net !')

    sequence = horizon.account(User.address().decode('utf-8')).get('sequence')

    tx = Transaction(
        source=User.address().decode(),
        opts={
            'sequence': sequence,
            'memo': msg,
            'operations': [
                op,
            ],
        },
    )
    try:
        envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
        envelope.sign(User)
        xdr = envelope.xdr()
        response = horizon.submit(xdr)
        return response['hash']
    except:
        return {"error": ""}
Example #4
0
    def post(self, request):
        source_private_key = request.data.get('sourcePrivateKey')
        dest_address = request.data.get('destAddress')
        amount = request.data.get('amount', '0.0000001')
        source = Keypair.from_seed(source_private_key)
        source_address = source.address().decode('UTF-8')

        requests.get(url=friend_bot_url, params={'addr': source_address})
        requests.get(url=friend_bot_url, params={'addr': dest_address})

        # Create operations for transaction
        payment = Payment(destination=dest_address,
                          asset=Asset('XLM'),
                          amount=amount)
        memo = TextMemo('Transaction Memo')
        sequence = horizon.account(source_address).get('sequence')

        operations = [payment]

        try:
            transaction = Transaction(source=source_address,
                                      sequence=sequence,
                                      memo=memo,
                                      fee=100 * len(operations),
                                      operations=operations)
            envelope = TransactionEnvelope(tx=transaction, network_id="TESTNET")
            # Sign the sender
            envelope.sign(source)
            # Submit it to the network
            xdr = envelope.xdr()
            response = horizon.submit(xdr)

            return Response(response, status=status.HTTP_200_OK)
        except HorizonError as horizonError:
            return Response(horizonError.message, status=horizonError.status_code)
Example #5
0
def opr_change_trust(asset_object, receiver_address, receiver_seed):
    horizon = horizon_testnet()
    sequence = horizon.account(receiver_address).get('sequence')
    print(sequence)
    op = ChangeTrust(
        asset=asset_object,
        limit='5000',
        source=receiver_address
    )
    # print(op.__dict__)
    msg = TextMemo('Change Trust Operation')   
    receiving_account = Keypair.from_seed(receiver_seed)
    tx = Transaction(
        source=receiving_account.address().decode(),
        sequence=sequence,
        time_bounds=None,
        memo=msg,
        fee=None,
        operations=[op],
    )
    envelope = Te(tx=tx, signatures=None, network_id="TESTNET")

    envelope.sign(receiving_account)

    xdr_envelope = envelope.xdr()
    response = horizon.submit(xdr_envelope)
    print(response)
    if 'result_xdr' in response:
        print('Successful')
    else:
        print('Things go Fishy')
def Place_buy_order(buyAsset, buyAssetIssuer, amount, offerID, price,
                    sourceAdd, sourceSeed):
    #the amount here need to be the amount of xlm you want to sell, and the price need to be the price of xlm in terms of the asset you want to buy
    from stellar_base.operation import ManageOffer
    sequence3 = horizon.account(sourceAdd).get('sequence')
    assetBuy = asset_Identifier(buyAsset, buyAssetIssuer)
    assetSell = Asset('XLM')
    op_so = ManageOffer({
        'selling': assetSell,
        'buying': assetBuy,
        'amount': str(amount),
        'price': str(price),
        'offer_id': offerID
    })
    tx_so = Transaction(source=sourceAdd,
                        opts={
                            'sequence': sequence3,
                            'operations': [op_so]
                        })
    envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_so.sign(kp)
    xdr3 = envelope_so.xdr()
    response = horizon.submit(xdr3)
    result = passed_or_not(response)
    return response['result_xdr']
def Cancel_buy_order(buyAsset, buyAssetIssuer, price, xdr_result, sourceAdd,
                     sourceSeed):
    from stellar_base.operation import ManageOffer
    offerID = Get_offer_ID(xdr_result)
    sequence3 = horizon.account(sourceAdd).get('sequence')
    assetBuy = asset_Identifier(buyAsset, buyAssetIssuer)
    assetSell = Asset('XLM')
    op_so = ManageOffer({
        'selling': assetSell,
        'buying': assetBuy,
        'amount': str(0),
        'price': str(price),
        'offer_id': offerID
    })  #How to get the ID of existing order
    tx_so = Transaction(source=sourceAdd,
                        opts={
                            'sequence': sequence3,
                            'operations': [op_so]
                        })
    envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_so.sign(kp)
    xdr3 = envelope_so.xdr()
    response = horizon.submit(xdr3)
    result = passed_or_not(response)
    return response['result_xdr']
def transfer_fund(amount, asset_object, customer_account, issuer_account,
                  issuer_seed):
    horizon = horizon_testnet()
    print('Transferring fund to {}'.format(customer_account))
    op = Payment(destination=customer_account,
                 asset=asset_object,
                 amount=str(amount),
                 source=issuer_account)
    msg = TextMemo('Your first Payment !')
    sequence = horizon.account(issuer_account).get('sequence')
    tx = Transaction(
        source=issuer_account,
        sequence=sequence,
        memo=msg,
        fee=None,
        operations=[op],
    )
    issuer_account1 = Keypair.from_seed(issuer_seed)
    envelope = Te(tx=tx, signatures=None, network_id="TESTNET")

    envelope.sign(issuer_account1)
    xdr_envelope = envelope.xdr()

    response = horizon.submit(xdr_envelope)
    print(response)
    if 'result_xdr' in response:
        print('Successful Transfer')
    else:
        print('Things go Fishy')
Example #9
0
def create_account(user):
    # type: (User) -> None

    # create keypair
    keypair = Keypair.random()
    public_key = keypair.address().decode()
    seed = keypair.seed().decode()

    # store account
    StellarAccount.objects.create(seed=seed,
                                  address=public_key,
                                  user=user,
                                  balance=0.0)

    horizon = horizon_testnet() if settings.DEMO_MODE else horizon_livenet()

    # fund account
    if settings.DEMO_MODE:
        for _ in range(5):
            # noinspection PyBroadException
            try:
                funding_keypair = Keypair.from_seed(
                    settings.FUNDING_ACCOUNT_SEED)

                # create operation
                create_account_operation = CreateAccount({
                    'destination':
                    public_key,
                    'starting_balance':
                    '1'
                })

                # create transaction
                sequence = horizon.account(
                    funding_keypair.address().decode()).get('sequence')
                tx = Transaction(source=funding_keypair.address().decode(),
                                 opts={
                                     'sequence':
                                     sequence,
                                     'memo':
                                     TextMemo('Creating new Zendi account.'),
                                     'operations': [create_account_operation]
                                 })

                # create and sign envelope
                envelope = TransactionEnvelope(tx=tx,
                                               opts={"network_id": "TESTNET"})
                envelope.sign(funding_keypair)

                # Submit the transaction to Horizon
                te_xdr = envelope.xdr()
                horizon.submit(te_xdr)

                break
            except Exception as ex:
                logger.error('Error while funding account', ex)
            time.sleep(1)

    logger.info('Created Stellar Lumen account {} for {}'.format(
        public_key, user))
Example #10
0
 def do(self, network, op):
     tx = Transaction(self.source, sequence=1)
     tx.add_operation(op)
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     return envelope_b64
Example #11
0
 def do(self, network, opts):
     tx = Transaction(self.source, **opts)
     tx.add_operation(Inflation())
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
def send_asset(amt, from_addr, to_addr, asset_nm):
    asset = Asset(asset_nm, issuer_addr)
    tx = Transaction(source=from_addr['address'], opts={'sequence': str(get_sequence(from_addr['address'])), 'fee': 100})
    pay_dic = {'destination': to_addr['address'],'asset': asset, 'amount': str(amt)}
    tx.add_operation(operation=Payment(pay_dic))
    envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
    envelope.sign(Keypair.from_seed(from_addr['seed']))
    req = hz.submit(te=envelope.xdr())
    print(req)
Example #13
0
 def do(self, op):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     tx = Transaction(source=self.source, opts={'sequence': self.seq})
     tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
Example #14
0
def transaction(
):  # Performs the transaction from one to another thus providing the current balance.
    amount = str(request.form['amount'])  # Amount taken from the user.
    memo = TextMemo(request.form['memo'])  # Memo entered by user.

    send = Keypair.from_seed(send_seed)
    horizon = horizon_testnet()
    asset = Asset('XLM')

    op = Payment({
        'destination': receive_publickey,
        'asset': asset,
        'amount': amount,
    })

    sequence = horizon.account(send.address()).get('sequence')

    tx = Transaction(
        source=send.address().decode(),
        opts={
            'sequence': sequence,
            'memo': memo,
            'fee': 100,
            'operations': [
                op,
            ],
        },
    )

    envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
    envelope.sign(send)
    xdr = envelope.xdr()
    response = horizon.submit(xdr)

    trans = response['_links']
    for values in trans.itervalues():
        for confirmation in values.itervalues():
            confirm = confirmation
    address1.get()  # Receiving balance info in JSON format
    address2.get()
    for a1 in address1.balances:
        send_current = a1[
            'balance']  # Retrieving the eaxct balance info fron JSON.
    for a2 in address2.balances:
        receive_current = a2['balance']

    cbalance = {  # Current balance.
        'send_current': send_current,
        'receive_current': receive_current,
        'confirm': confirm,
        # 'amount': amount,
    }
    return render_template("transaction.html", cbalance=cbalance)
Example #15
0
 def do(self, op):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     tx = Transaction(source=self.source, opts={'sequence': self.seq})
     tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
Example #16
0
 def make_envelope(self, network, *args, **kwargs):
     opts = {'sequence': 1, 'fee': 100 * len(args)}
     for opt, value in kwargs.items():
         opts[opt] = value
     tx = Transaction(self.address, **opts)
     for count, op in enumerate(args):
         tx.add_operation(op)
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
Example #17
0
def set_account_signers(horizon, pool_keypair, signers, threshold):
	pool_address = pool_keypair.address().decode()

	operations = [
		SetOptions({
			"signer_address": signer_address,
			"signer_weight": 1,
			"signer_type": "ed25519PublicKey",
			"source_account": pool_address
		})
		for signer_address in signers
	]

	operations.append(
		SetOptions({
			"source_account": pool_address,
			"home_domain": bytes("lumenaut.net", "utf-8"),
			"master_weight": 0,
			"low_threshold": threshold["low"],
			"med_threshold": threshold["medium"],
			"high_threshold": threshold["high"],
			"inflation_dest": pool_address
		})
	)

	sequence = horizon.account(pool_address).get('sequence')
	tx = Transaction(
		source=pool_address,
		opts={
			'sequence': sequence,
			'fee': 100 * len(operations),
			'operations': operations,
		},
	)

	envelope = Te(tx=tx, opts={"network_id": network})
	envelope.sign(pool_keypair)

	xdr = envelope.xdr()
	response = horizon.submit(xdr)

	if "_links" in response:
		logger.debug(
			"Set options transaction href: ",
			response["_links"]["transaction"]["href"])
		logger.debug("Created successfully!")
		return True
	else:
		logger.error("Failed to set account signers, dumping response:")
		logger.error(response)
		return False
Example #18
0
def make_envelope(network, horizon, address, seed, *args, **kwargs):
    opts = {
        'sequence': horizon.account(address)['sequence'],
        'fee': 100 * len(args)
    }
    for opt, value in kwargs.items():
        opts[opt] = value
    tx = Transaction(address, **opts)
    for count, op in enumerate(args):
        tx.add_operation(op)
    envelope = Te(tx, network_id=network)
    signer = Keypair.from_seed(seed)
    envelope.sign(signer)
    envelope_xdr = envelope.xdr()
    return envelope_xdr
Example #19
0
    def perform_transaction(self):
        send_seed = self.seed1
        recieve_address = self.publickey2

        amount = str(input("\nEnter the amount to be transferred(0-9998): "))
        print("0.0000100 will be charged extra for the transaction")

        send = Keypair.from_seed(send_seed)
        horizon = horizon_testnet()
        asset = Asset('XLM')

        op = Payment({
            'destination': recieve_address,
            'asset': asset,
            'amount': amount,
        })

        msg = TextMemo('Transaction Test')
        print("Transferring the ammount to the Receiver......")

        sequence = horizon.account(send.address()).get('sequence')

        tx = Transaction(
            source=send.address().decode(),
            opts={
                'sequence': sequence,
                'memo': msg,
                'fee': 100,
                'operations': [
                    op,
                ],
            },
        )

        envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
        envelope.sign(send)
        xdr = envelope.xdr()
        response = horizon.submit(xdr)
        print("Transaction completed successfully.\n")

        trans = response['_links']
        for values in trans.itervalues():
            for confirmation in values.itervalues():
                print("Confirmation Link: " + confirmation)
        print(
            "\n------------------------------------------------------------------------------"
        )
        print("\nChecking the current balance......")
Example #20
0
def test_deposit_authenticated_success(client, acc1_usd_deposit_transaction_factory):
    """`GET /deposit` succeeds with the SEP 10 authentication flow."""
    client_address = "GDKFNRUATPH4BSZGVFDRBIGZ5QAFILVFRIRYNSQ4UO7V2ZQAPRNL73RI"
    client_seed = "SDKWSBERDHP3SXW5A3LXSI7FWMMO5H7HG33KNYBKWH2HYOXJG2DXQHQY"
    settings.DEPOSIT_AUTH_REQUIRED = True
    deposit = acc1_usd_deposit_transaction_factory()

    # SEP 10.
    response = client.get(f"/auth?account={client_address}", follow=True)
    content = json.loads(response.content)

    envelope_xdr = content["transaction"]
    envelope_object = TransactionEnvelope.from_xdr(envelope_xdr)
    client_signing_key = Keypair.from_seed(client_seed)
    envelope_object.sign(client_signing_key)
    client_signed_envelope_xdr = envelope_object.xdr().decode("ascii")

    response = client.post(
        "/auth",
        data={"transaction": client_signed_envelope_xdr},
        content_type="application/json",
    )
    content = json.loads(response.content)
    encoded_jwt = content["token"]
    assert encoded_jwt

    header = {"HTTP_AUTHORIZATION": f"Bearer {encoded_jwt}"}
    response = client.get(
        f"/deposit?asset_code=USD&account={deposit.stellar_account}",
        follow=True,
        **header,
    )
    content = json.loads(response.content)
    assert response.status_code == 403
    assert content["type"] == "interactive_customer_info_needed"
Example #21
0
def test_auth_get_account(client):
    """`GET <auth>` succeeds with a valid TransactionEnvelope XDR."""
    response = client.get(f"/auth?account={STELLAR_ACCOUNT_1}", follow=True)
    content = json.loads(response.content)
    assert content["network_passphrase"] == "Test SDF Network ; September 2015"
    assert content["transaction"]

    envelope_xdr = content["transaction"]
    envelope_object = TransactionEnvelope.from_xdr(envelope_xdr)
    transaction_object = envelope_object.tx
    assert transaction_object.sequence == 0
    assert len(transaction_object.operations) == 1

    manage_data_op = transaction_object.operations[0]
    assert manage_data_op.type_code() == Xdr.const.MANAGE_DATA
    assert manage_data_op.data_name == "SEP 6 Reference auth"
    assert len(manage_data_op.data_value) == 64

    signatures = envelope_object.signatures
    assert len(signatures) == 1
    server_signature = signatures[0]

    tx_hash = envelope_object.hash_meta()
    server_public_key = Keypair.from_address(settings.STELLAR_ACCOUNT_ADDRESS)
    server_public_key.verify(tx_hash, server_signature.signature)
Example #22
0
def create_envelope(user_kaykair, sequence, memo, opers, FEE=0):
    """事务封包"""
    tx = Transaction(
        source=user_kaykair.address().decode(),  # 事务发起着的公钥
        opts={
            'sequence': sequence,  # 事务发起着的序列号
            'memo': TextMemo(memo),  # 备注
            'fee': len(opers) * FEE,  # 手续费
            'operations': opers,
        },
    )  # 操作
    envelope = Te(tx=tx, opts=dict(network_id='XIANDA_DEV_NET'))  # 操作封包的类Te
    envelope.sign(user_kaykair)  # 事务发起着签名
    # te = envelope.xdr()  # 转换xdr格式数据
    te_hash = hashlib.sha256(envelope.signature_base()).hexdigest()
    return te_hash
Example #23
0
 def make_envelope(self, *args, **kwargs):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     opts = {'sequence': self.seq, 'fee': self.fee * len(args)}
     for opt, value in kwargs.items():
         opts[opt] = value
     tx = Transaction(source=self.address, opts=opts)
     for count, op in enumerate(args):
         tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
Example #24
0
 def create_te(self, user_kaykair, sequence, memo, op, FEE=200):
     """创建te"""
     tx = Transaction(
         source=user_kaykair.address().decode(),
         opts={
             'sequence': sequence,
             'memo': TextMemo(memo),
             'fee': FEE,
             'operations': [op],
         },
     )
     envelope = Te(tx=tx, opts=dict(network_id=self._network_id))
     envelope.sign(user_kaykair)
     te = envelope.xdr()
     tx_hash = hashlib.sha256(envelope.signature_base()).hexdigest()
     return te, tx_hash
Example #25
0
def channel_worker(channel_index, transactions):
    thread_horizon = horizon_instance()
    channel_keypair = channel_keypairs[channel_index]
    channel_address = channel_keypair.address().decode()
    channel_sequence = int(channel_accounts[channel_index].get("sequence")) + 1

    failed = []
    for i in range(len(transactions)):
        env = TransactionEnvelope.from_xdr(transactions[i])

        env.tx.source = channel_address
        env.tx.sequence = channel_sequence

        env.sign(channel_keypair)

        res = requests.post(
            "https://horizon-testnet.stellar.org/transactions",
            data={"tx": env.xdr()},
        )
        res = res.json()

        if res["status"] < 400:
            channel_sequence += 1
        else:
            #print(res)
            failed.append((i, res))

    print("Channel #%d thread finished, %d transaction(s) failed" %
          (channel_index + 1, len(failed)))
 def __init__(self, developer_secret, te_xdr, address):
     self.developer_secret = developer_secret
     self.te = TransactionEnvelope.from_xdr(te_xdr)
     self.tx = self.te.tx
     self.address = address
     self.keypair = self.keypair()
     self.user_keypair = self.user_keypair()
     self.time_bounds()
Example #27
0
def do_single_signer(operation_opts=False, tx_opts=False):
    assert operation_opts and tx_opts
    from stellar_base.operation import Payment
    from stellar_base.transaction import Transaction
    from stellar_base.keypair import Keypair
    from stellar_base.transaction_envelope import TransactionEnvelope as Te

    operation = Payment(opts=operation_opts)
    tx = Transaction(source=SOURCE, opts=tx_opts)
    tx.add_operation(operation=operation)
    envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
    signer = Keypair.from_seed(seed=SEED)
    envelope.sign(keypair=signer)
    envelope_b64 = bip(envelope)

    print(envelope_b64)
    return envelope_b64
Example #28
0
    def make_envelope(self, *args, **kwargs):
        from stellar_base.transaction import Transaction
        from stellar_base.keypair import Keypair
        from stellar_base.transaction_envelope import TransactionEnvelope as Te

        opts = {"sequence": self.seq, "fee": self.fee * len(args)}
        for opt, value in kwargs.items():
            opts[opt] = value
        tx = Transaction(source=self.address, opts=opts)
        for count, op in enumerate(args):
            tx.add_operation(operation=op)
        envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
        signer = Keypair.from_seed(seed=self.seed)
        envelope.sign(keypair=signer)
        envelope_b64 = envelope.xdr()
        print(envelope_b64)
        return envelope_b64
def Trusting_asset(assetName, issuerAdd, truster, trusterSeed, limit):
    asset = Asset(assetName, issuerAdd)
    sequence2 = horizon.account(truster).get('sequence')
    op_ct = ChangeTrust({'asset': asset, 'limit': str(limit)})
    tx_ct = Transaction(source=truster,
                        opts={
                            'sequence': sequence2,
                            'operations': [
                                op_ct,
                            ]
                        })
    envelope_ct = Te(tx=tx_ct, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(trusterSeed)
    envelope_ct.sign(kp)  #sign
    xdr2 = envelope_ct.xdr()
    response = horizon.submit(xdr2)  #submit
    result = passed_or_not(response)
    return response
    def call(self):
        te = TransactionEnvelope.from_xdr(xdr=self.xdr)
        keypair = self.keypair()
        dev_keypair = self.dev_keypair()
        self.validate(dev_keypair, te)

        te.sign(keypair)

        return te.xdr().decode()
Example #31
0
def create_empty_acct(r_kp):
    """
    Creates a tmp account which is empty except for min balance (no fees even)
    """
    r = Address(address=r_kp.address().decode())
    r.get()

    kp = Keypair.random()
    dest = kp.address().decode()
    tx = Transaction(
        source=r.address,
        sequence=r.sequence,
        fee=100,
        operations=[CreateAccount(destination=dest, starting_balance="1")])
    env = Te(tx=tx, network_id="TESTNET")
    env.sign(r_kp)
    horizon.submit(env.xdr())
    return kp
def Fund_new_account(newAdd, IssuerAdd, IssuerSeed, XLMamount):
    from stellar_base.operation import CreateAccount
    sequence = horizon.account(IssuerAdd).get('sequence')
    op = CreateAccount({
        'destination': newAdd,
        'starting_balance': str(XLMamount)
    })
    tx = Transaction(source=IssuerAdd,
                     opts={
                         'sequence': sequence,
                         'operations': [op]
                     })
    envelope = Te(tx=tx, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(IssuerSeed)
    envelope.sign(kp)
    xdr = envelope.xdr()
    response = horizon.submit(xdr)
    result = passed_or_not(response)
    return response
Example #33
0
def main(inflation):
	inflation = XLM_Decimal(inflation)

	conn = sqlite3.connect(db_address)
	transactions = []

	sequence = horizon.account(pool_address).get('sequence')
	total_payments_cost = 0
	num_payments = 0
	total_fee_cost = 0

	for batch in accounts_payout(conn, pool_address, inflation):
		tx = Transaction(
			source = pool_address,
			opts = {
				'sequence': sequence,
				'operations': [make_payment_op(aid, amount) for aid, amount in batch]
			}
		)
		tx.fee = len(tx.operations) * 100
		envelope = Te(tx = tx, opts = {"network_id": network})
		transactions.append(envelope.xdr().decode("utf-8"))

		total_fee_cost += XLM_Decimal(tx.fee) / XLM_STROOP
		total_payments_cost += sum([XLM_Decimal(payment.amount) for payment in tx.operations])
		num_payments += len(tx.operations)

		sequence = int(sequence) + 1

	print(
		"Stats: \n\
		Inflation received: " + str(inflation) + "\n\
		A total of " + str(total_payments_cost) +\
		" XLM paid over " + str(num_payments) +\
		" inflation payments using " + str(total_fee_cost) + " XLM in fees. \n\
		People donated " + str(sum([n for n in donations.values()])) +\
		" XLM to " + str(len(donations.keys())) +\
		" different addresses.\n"
	)

	with open("transactions.json", 'w') as outf:
		json.dump(transactions, outf)
	print("Done. Output to transactions.json")
Example #34
0
 def test_payment_short_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAEAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAc0+E2MAAABAzEdbP2ISsB9pDqmIRPt6WEK0GkVOgAEljnelNQjNpDig6A60+jMtveQjdCocL13GwVbO1B8VBXgQdlAobs0fDg=='
     assert (result == Te.from_xdr(result).xdr())
Example #35
0
 def test_createPassiveOffer_min_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAQAAAABYmVlcgAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAFiZWVyAAAAAK2uFogrxa/78nU4lG0kBdB8JKhKz/MHOgVEGr96kkCOAAAAADuaygAABMsvAAGGoAAAAAAAAAABzT4TYwAAAEAm4lQf6g7mpnw05syhOt3ub+OmSADhSfLwn/xg6bD+6qwqlpF/xflNYWKU1uQOy4P9e1+SWIGJdR+KWryykS0M'  # TODO
     assert (result == Te.from_xdr(result).xdr())
Example #36
0
def te_xdr_build(tx, secret):
    envelope = Envelope(tx)
    signer = Keypair.from_seed(secret)
    envelope.sign(signer)
    re = envelope.xdr()
    return re
Example #37
0
 def test_manageOffer_min_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAMAAAABYmVlcgAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAFiZWVyAAAAAK2uFogrxa/78nU4lG0kBdB8JKhKz/MHOgVEGr96kkCOAAAAADuaygAABMsvAAGGoAAAAAAAAAABAAAAAAAAAAHNPhNjAAAAQBTg1srmkpv/pFqELvCsSurwRPYRUpH05j1sgDzOZdILCdVpxb3sEvMgim1DXE0VhGXqbgZaQV/Sp2VH5C5RKQI='  # TODO
     print(result)
     print(Te.from_xdr(result).xdr())
Example #38
0
 def test_changeTrust_min_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAYAAAABYmVlcgAAAACtrhaIK8Wv+/J1OJRtJAXQfCSoSs/zBzoFRBq/epJAjn//////////AAAAAAAAAAHNPhNjAAAAQL0R9eOS0qesc+HHKQoHMjFUJWvzeQOy+u/7HBHNooo37AOaG85y9jyNoa1D4EduroZmK8vCfCF0V3rn5o9CpgA='
     assert (result == Te.from_xdr(result).xdr())
Example #39
0
 def test_SetOptions_empty_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc0+E2MAAABAymdhj3dFg+3TcCRILXdUu8ZhG3WOuBmX3YXcYJhYemjCDylQEk31vF8wxB/ntRg4/vmCYC2IwhBtw1mJZ8h+Bw=='
     assert (result == Te.from_xdr(result).xdr())
Example #40
0
 def test_allowTrust_shortAsset_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAcAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAACcG9ja2V0a25pdmVzAAAAAQAAAAAAAAABzT4TYwAAAEBK169VZqBQYUrs+ueQzx/UaANo+7HCdUcpflNvT4e5y7o+T7fxzJ845B3hVr8rrJ27Rz/VVslBWkXmxKoaa8sC'
     assert (result == Te.from_xdr(result).xdr())
Example #41
0
 def test_createAccount_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAJiWgAAAAAAAAAABzT4TYwAAAEBBR+eUTPqpyTBLiNMudfSl2AN+oZL9/yp0KE9SyYeIzM2Y7yQH+dGNlwz5PMaaCEGAD+82IZkAPSDyunElc+EP'
     assert (result == Te.from_xdr(result).xdr())
Example #42
0
 def test_accountMerge_min_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAgAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAc0+E2MAAABADFSYbdlswOKfK4Y02Tz/j5j83c7f5YvLe+QxmXcHSd/W8ika63MsM6CDkDZhjRx4+Nt+mfCKpKbP7j0NPzNhCQ=='
     assert (result == Te.from_xdr(result).xdr())
Example #43
0
 def test_pathPayment_min_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAIAAAAAAAAAAACYloAAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAAAAAAHNPhNjAAAAQFwSz9wwBEWCv9cNnuIq+Jjq36mXBI22f6uj/FZ6LbyLljkckSLkF/AqXcaOoOgY9mZ0NrXsHbA5/chSThtgMgQ='  # TODO
     assert (result == Te.from_xdr(result).xdr())
Example #44
0
print('Anna: ', json.dumps(anna, sort_keys=True, indent=4 * ' '))
print('Bob: ', json.dumps(bob, sort_keys=True, indent=4 * ' '))

operation = Payment({
	'source': anna['address'],
	'destination': bob['address'],
	'asset': Asset.native(),
	'amount': '1000', # needs to be a string?
})
tx = Transaction(
	source=anna['address'],
	opts={
		'sequence': json.loads(requests.get(url+'/accounts/'+anna['address']).text)['sequence'],
		'timeBounds': [],
		'memo': NoneMemo(),
		'fee': 100,
		'operations': [
			operation,
		],
	},
)
envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
envelope.sign(Keypair.from_seed(anna['seed']))

print('Tx: ', json.dumps(json.loads(requests.post(
	url=url+'/transactions',
	data={
		'tx': packer(envelope).decode('ascii')
	}
).text), sort_keys=True, indent=4 * ' '))
Example #45
0
 def test_inflation_unXdr(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAAAc0+E2MAAABAL2tfdCYqdtfxvINWVZ0iwcROqxQieoBF9cay5AL2oj2oJDrp3F3sYlHQNJi1orkcMLqsxaGtr6DWdnc0vwIBDg=='
     assert (result == Te.from_xdr(result).xdr())