Ejemplo n.º 1
1
    def test_builder_xdr(self):
        cold_account = self.cold.address().decode()
        hot_account = self.hot.address().decode()
        fund(cold_account)
        fund(hot_account)

        cold = Builder(self.cold.seed().decode())
        cold.append_trust_op(cold_account, 'BEER', 1000, hot_account)
        cold.append_payment_op(hot_account, 100, 'BEER', cold_account)
        cold.append_payment_op(cold_account, 2.222, 'BEER', cold_account, hot_account)

        xdr = cold.gen_xdr()
        hot = Builder(self.hot.seed().decode())
        hot.import_from_xdr(xdr)
        # hot.sign()

        try:
            response = hot.submit()
        except:
            assert False
Ejemplo n.º 2
0
 def create_transaction(cls, text):
     builder = Builder(secret=cls.key)
     # use this to use local node e.g with docker instead of public node
     # builder = Builder(secret=cls.key, horizon_uri="http://localhost:8000/")
     builder.append_payment_op(cls.address, '100', 'XLM')
     builder.add_text_memo(text)  # string length <= 28 bytes
     return builder
Ejemplo n.º 3
0
    def test_builder(self):
        cold_account = self.cold.address().decode()
        hot_account = self.hot.address().decode()
        fund(cold_account)

        cold = Builder(self.cold.seed().decode()) \
            .append_create_account_op(hot_account, 200) \
            .append_set_options_op(inflation_dest=cold_account, set_flags=1,
                                   home_domain='256kw.com', master_weight=10,
                                   low_threshold=5, ) \
            .append_trust_op(cold_account, 'BEER', 1000, source=hot_account) \
            .append_allow_trust_op(hot_account, 'BEER', True)
        # append twice for test
        cold.append_payment_op(hot_account, 50.123, 'BEER', cold_account) \
            .append_payment_op(hot_account, 50.123, 'BEER', cold_account)

        cold.sign(self.hot.seed().decode())
        try:  # sign twice
            cold.sign(self.hot.seed().decode())
        except SignatureExistError:
            assert True
        except:
            assert False

        cold.sign()
        assert len(cold.te.signatures) == 2
        assert len(cold.ops) == 5

        try:
            response = cold.submit()
            print(response)
        except:
            assert False
class Build:
    """Creates a transaction between the sender and receiver.

    :param: sender: Account that sends the money (seed).
    :param: receiver: Account that receives the money (Account ID).
    :param: amount: Amount that needs to be sent.
    """
    def __init__(self, sender, receiver, amount=0):
        self.sender, self.receiver, self.amount = sender, receiver, amount
        self.builder = None

    def send(self):
        """Text Memo needs to be added."""
        if self.check_account_validity:
            self.builder = Builder(
                secret=self.sender,
                horizon='https://horizon-testnet.stellar.org')
            self.builder.append_payment_op(self.receiver, self.amount)
            self.builder.sign()
            self.builder.submit()
            return True
        return False

    @property
    def check_account_validity(self):
        return Details(self.receiver).check
Ejemplo n.º 5
0
def create_transaction(sender_seed, recipient_key, hash_value):
    builder = Builder(secret=sender_seed)
    builder.append_payment_op(recipient_key, "1", "XLM")
    builder.add_hash_memo(hash_value.encode())
    builder.sign()
    # TODO: handle possible errors
    return builder.submit()
Ejemplo n.º 6
0
    def __send(self, address, encrypted, sequence_number):
        '''
        Sends the encrypted blocks to the recipient as sequential
        payment transactions.

        Args:
            address: The Stellar address of the recipient.
            encrypted: The encrypted message blocks.
            sequence_number: The current sequence number of the
                             sending account.

        Returns:
            True if successful, False otherwise.
        '''
        try:
            for i in range(0, len(encrypted)):
                sequence = str(sequence_number + i)
                builder = Builder(secret = self.__seed, sequence = sequence)
                builder.append_payment_op(address, '0.0000001', 'XLM')
                builder.add_hash_memo(encrypted[i])
                builder.sign()
                builder.submit()
        except:
            return False

        # todo: check sending status
        return True
Ejemplo n.º 7
0
def test_builder(setup, test_data):
    hot = Keypair.random()
    hot_account = hot.address().decode()
    hot_secret = hot.seed()

    cold = Builder(secret=test_data.cold_secret, horizon=setup.horizon_endpoint_uri, network=setup.network) \
        .append_create_account_op(hot_account, '200') \
        .append_set_options_op(inflation_dest=test_data.cold_account, set_flags=1,
                               home_domain='256kw.com', master_weight=10,
                               low_threshold=5, ) \
        .append_trust_op(test_data.cold_account, 'BEER', '1000', hot_account) \
        .append_allow_trust_op(hot_account, 'BEER', True)
    # append twice for test
    cold.append_payment_op(hot_account, '50.123', 'BEER', test_data.cold_account) \
        .append_payment_op(hot_account, '50.123', 'BEER', test_data.cold_account)
    # TODO: append_bump_sequence_op test
    cold.sign()
    cold.sign(hot_secret)
    # try to sign twice
    with pytest.raises(SignatureExistError):
        cold.sign(hot_secret)

    assert len(cold.te.signatures) == 2
    assert len(cold.ops) == 5

    response = cold.submit()
    assert response.get('hash') == cold.hash_hex()
Ejemplo n.º 8
0
def send_asset(text):
    # send 10 EURT antb123*papayame.com or send 1 XLM PUBKEY memo text
    if CONF['private_key'] == '':
        print(
            'no private key setup  - pls type set to set key or c to create wallet'
        )
        return
    val = text.split()
    memo_type = 'text'
    if len(val) < 3:
        print(
            'invalid syntax please use send amount asset receiver e.g.  s 10 EURT antb123*papayame.com'
        )
        return
    amount, asset, address = val[1], val[2].upper(), val[3]
    if '*' in address:
        res = fed(address.split('*')[1], address)
        sendto = res['account_id']
        memo = res['memo']
        memo_type = res['memo_type']
    else:
        sendto = address
        memo = ''
    # override memo, type if given
    if len(val) == 6:
        memo = val[4]
        memo_type = val[5]
    if len(val) == 5:
        memo = val[4]
        memo_type = 'text'
    print_formatted_text(
        HTML("""Are you sure you want to send
                                <ansiyellow>%s</ansiyellow>
                                <ansired>%s %s</ansired>
                                with memo of <ansiblue>%s</ansiblue> (y/n)
                                """ % (sendto, asset, amount, memo)))
    text = session.prompt(u'> ', default='y')
    if text != 'y': return
    ret, asset_issuer = get_balance_issuer(amount, asset)
    if ret: return
    retsan = send_sanity(sendto, memo_type, asset)
    if not retsan: return
    send = Builder(CONF['private_key'], network=CONF['network'])
    if asset != 'XLM':
        send.append_payment_op(sendto, amount, asset, asset_issuer)
    else:
        send.append_payment_op(sendto, amount)
    if memo != '' and memo_type == 'text':
        send.add_text_memo(memo)
    if memo != '' and memo_type == 'id':
        send.add_id_memo(memo)
    if CONF['multisig'] != '':
        print(
            'You have 2of2 multisig - send this data to the other key to sign when you get it back type signsend data'
        )
        print(send.gen_xdr())
        return
    send.sign()
    send.submit()
Ejemplo n.º 9
0
def create_stellar_deposit(transaction_id):
    transaction = Transaction.objects.get(id=transaction_id)
    # Assume transaction has valid stellar_account, amount_in, asset.name
    stellar_account = transaction.stellar_account
    payment_amount = transaction.amount_in - transaction.amount_fee
    asset = transaction.asset.name

    # If the given Stellar account does not exist, create
    # the account with at least enough XLM for the minimum
    # reserve and a trust line (recommended 2.01 XLM), update
    # the transaction in our internal database, and return.
    address = Address(stellar_account)
    try:
        address.get()
    except HorizonError as e:
        # 404 code corresponds to Resource Missing.
        if e.status_code == 404:
            starting_balance = settings.ACCOUNT_STARTING_BALANCE
            builder = Builder(secret=settings.STELLAR_ACCOUNT_SEED)
            builder.append_create_account_op(
                destination=stellar_account,
                starting_balance=starting_balance,
                source=settings.STELLAR_ACCOUNT_ADDRESS,
            )
            builder.sign()
            try:
                builder.submit()
            except HorizonError as exception:
                raise exception
            transaction.status = Transaction.STATUS.pending_trust
            transaction.save()
            return

    # If the account does exist, deposit the desired amount of the given
    # asset via a Stellar payment. If that payment succeeds, we update the
    # transaction to completed at the current time. If it fails due to a
    # trustline error, we update the database accordingly. Else, we do not update.
    builder = Builder(secret=settings.STELLAR_ACCOUNT_SEED)
    builder.append_payment_op(
        destination=stellar_account,
        asset_code=asset,
        asset_issuer=settings.STELLAR_ACCOUNT_ADDRESS,
        amount=str(payment_amount),
    )
    builder.sign()
    try:
        builder.submit()
    except HorizonError as exception:
        if TRUSTLINE_FAILURE_XDR in exception.message:
            transaction.status = Transaction.STATUS.pending_trust
            transaction.save()
            return

    # If we reach here, the Stellar payment succeeded, so we
    # can mark the transaction as completed.
    transaction.status = Transaction.STATUS.completed
    transaction.completed_at = now()
    transaction.amount_out = payment_amount
    transaction.save()
Ejemplo n.º 10
0
def send_payment(request,amount,currency,sender,account):
    builder = Builder(secret=sender)
    builder.append_payment_op(account,amount,currency)
    builder.add_text_memo("first payment")
    builder.sign()
    s = builder.submit()
    print(s['_links'])
    return HttpResponse("send successfully plz check user transaction here")
Ejemplo n.º 11
0
def build_generate_trust_wallet_transaction(
        transaction_source_address: str,
        source_address: str,
        destination_address: str,
        xlm_amount: Decimal,
        hot_amount: Decimal = Decimal(0),
        sequence=None,
) -> Tuple[bytes, bytes]:
    """"Build transaction return unsigned XDR and transaction hash.

        Args:
            transaction_source_address: Owner of a transaction.
            source_address: Owner of creator address and payment operations.
            destination_address: wallet id of new wallet.
            xlm_amount: starting xlm_balance of new wallet.
            hot_amount: starting hot balance of new wallet.
    """
    builder = Builder(
        address=transaction_source_address,
        horizon=settings['HORIZON_URL'],
        network=settings['PASSPHRASE'],
        sequence=sequence,
    )
    builder.append_create_account_op(source=source_address,
                                     destination=destination_address,
                                     starting_balance=xlm_amount)
    try:
        builder.append_trust_op(
            source=destination_address,
            destination=settings['ISSUER'],
            code=settings['ASSET_CODE'],
            limit=settings['LIMIT_ASSET'],
        )
    except DecodeError:
        raise web.HTTPBadRequest(reason='Parameter values are not valid.')
    except Exception as e:
        msg = str(e)
        raise web.HTTPInternalServerError(reason=msg)

    if hot_amount > 0:
        builder.append_payment_op(
            source=source_address,
            destination=destination_address,
            asset_code=settings['ASSET_CODE'],
            asset_issuer=settings['ISSUER'],
            amount=hot_amount,
        )

    try:
        unsigned_xdr = builder.gen_xdr()
    except Exception as e:
        raise web.HTTPBadRequest(
            reason='Bad request, Please ensure parameters are valid.')

    tx_hash = builder.te.hash_meta()

    return unsigned_xdr, tx_hash
Ejemplo n.º 12
0
 def create_signed_tx(private_key,
                      to_address,
                      amount,
                      network='PUBLIC',
                      memo=None):
     amount = round(amount, 7)
     builder = Builder(secret=private_key, network=network)
     builder.append_payment_op(to_address, amount, 'XLM')
     if memo:
         builder.add_text_memo(memo)
     builder.sign()
     return builder.gen_xdr().decode()
Ejemplo n.º 13
0
 def send_asset(cls, setup, secret_key, address, amount, memo_text=None):
     """A helper to send asset"""
     builder = Builder(secret=secret_key,
                       horizon_uri=setup.horizon_endpoint_uri,
                       network=setup.network)
     builder.append_payment_op(address, amount, setup.test_asset.code,
                               setup.test_asset.issuer)
     if memo_text:
         builder.add_text_memo(memo_text[:28])  # max memo length is 28
     builder.sign()
     reply = builder.submit()
     return reply.get('hash')
Ejemplo n.º 14
0
def transfer_lumen(sender, to_address, amount, memo=None):
    # type: (User, str, float, Optional[str]) -> None

    # ToDo: check remaining lumen of sending account (fee + base reserve)
    # (take base reserve https://www.stellar.org/developers/guides/concepts/fees.html)

    builder = Builder(secret=sender.stellaraccount.seed, network=network)
    builder.append_payment_op(to_address, str(amount), 'XLM')
    if memo:
        builder.add_text_memo(memo)  # string length <= 28 bytes

    builder.sign()
    builder.submit()
Ejemplo n.º 15
0
    def award_degree(self, address, student_name, birthdate, year):
        """Sends a transaction with a hash of the student's informations as text memo.

        :param student_name: in format prenamesurname with only one prename
        :param year: 4-digits number
        :return: Horizon return of the tx
        """
        memo = hash128((student_name+birthdate+year).encode())
        builder = Builder(secret=self.kp.seed().decode())
        builder.add_text_memo(memo)
        builder.append_payment_op(address, 0.0000001)
        builder.sign()
        return builder.submit()
async def build_payment_operation(builder: Builder, source: str, parties_wallet: List):

    for wallet in parties_wallet:
        destination = wallet['address']
        amount = Decimal(wallet['amount'])
        if amount > 0:
            builder.append_payment_op(
                destination=destination,
                amount=amount,
                asset_code=settings['ASSET_CODE'],
                asset_issuer=settings['ISSUER'],
                source=source,
            )
Ejemplo n.º 17
0
 def _add_signer(builder: Builder, deal_address: str, party: str,
                 amount: Decimal):
     """Set permission of parties can signed transaction that generate from joint account"""
     builder.append_set_options_op(source=deal_address,
                                   signer_address=party,
                                   signer_type='ed25519PublicKey',
                                   signer_weight=1)
     builder.append_payment_op(
         source=party,
         destination=deal_address,
         asset_code=settings['ASSET_CODE'],
         asset_issuer=settings['ISSUER'],
         amount=amount,
     )
Ejemplo n.º 18
0
def send_payment(amount, item, asset='XLM'):
    flag = False
    try:
        builder = Builder(secret=MEMBER_SEED)
        builder.append_payment_op(SITE_ADDR, amount, asset)
        builder.add_text_memo(item)
        builder.sign()
        s = builder.submit()
        print(s)
        flag = True
    except Exception as ex:
        print('Error in Payment')
        print(str(ex))
    finally:
        return flag
Ejemplo n.º 19
0
    def transfer(self, amount, to_address, description):
        '''

        '''
        if float(self._get_balance()) < float(amount):
            return 'Insufficient Balance'
        seed = self.get_seed()
        builder = Builder(secret=seed)
        # builder = Builder(secret=seed, network='public') for LIVENET
        builder.append_payment_op(to_address, amount, 'XLM')
        builder.add_text_memo(description)  # string length <= 28 bytes
        builder.sign()

        # Uses an internal horizon instance to submit over the network
        builder.submit()
        return 'SUCCESS'
Ejemplo n.º 20
0
def send_payment(amount, item, asset='XLM'):
    flag = False
    try:
        builder = Builder(
            secret=MEMBER_SEED)  #send payment from member to site
        builder.append_payment_op(SITE_ADDRESS, amount, asset)
        builder.add_text_memo(item)
        builder.sign()
        s = builder.submit()
        global balance
        balance = calculate_balance(s)

        flag = True
    except Exception as e:
        print('Error', e)
    finally:
        return flag
Ejemplo n.º 21
0
def transaction():			# Performs the transaction from one to another thus providing the current balance.
	builder = Builder(secret=send_seed)
	builder.append_payment_op(receive_publickey, '500', 'XLM')		# Assigning of Receiver address, amount & Asset.
	builder.add_text_memo('testing')								# Assigning of a memo or remark.
	builder.sign()
	s = builder.submit()					# Submitting the result of the transaction.
	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,
	}
	return render_template("transaction.html", cbalance=cbalance)
 def create_token_and_lock_account(self, code, owner_address, metadata):
     # Setup the base transaction
     builder = Builder(
         secret=self.issuer_secret,
         network=self.network
     )
     # Append relevant payment ops
     ipfs_hash = self.create_ipfs_hash(metadata)
     builder.append_manage_data_op('token_ipfs_hash', ipfs_hash)
     builder.append_payment_op(
         owner_address,
         '0.0000001',
         code,
         self.issuer_keypair.address().decode()
     )
     builder.append_set_options_op(master_weight=0)
     builder.sign()
     return builder.submit()
def withdraw(key, to_address, amount=None, dst_tag=None):
    keypair = RawKeypair(key)
    builder = Builder(address=public_key_to_address(keypair.raw_public_key()),
                      network='PUBLIC')

    if amount is None:
        builder.append_account_merge_op(to_address)
    else:
        builder.append_payment_op(to_address, str(round(float(amount), 7)),
                                  'XLM')
    if dst_tag is not None:
        builder.add_text_memo(dst_tag)
    builder.keypair = keypair
    builder.sign()
    ret = builder.submit()
    if ret['successful']:
        return ret['hash']
    print(ret)
    return None
Ejemplo n.º 24
0
    def test_builder_xdr(self):
        cold_account = self.cold.address().decode()
        hot_account = self.hot.address().decode()
        fund(cold_account)
        fund(hot_account)

        cold = Builder(self.cold.seed().decode())
        cold.append_trust_op(cold_account, 'BEER', 1000, hot_account)
        cold.append_payment_op(hot_account, 100, 'BEER', cold_account)
        cold.append_payment_op(cold_account, 2.222, 'BEER', cold_account, hot_account)
        xdr = cold.gen_xdr()
        hot = Builder(self.hot.seed().decode())
        hot.import_from_xdr(xdr)
        # hot.sign()

        try:
            response = hot.submit()
        except:
            assert False
    def call(self):
        keypair = self.keypair()

        builder = Builder(address=keypair.address().decode(),
                          sequence=self.random_sequence(),
                          secret=keypair.seed())

        builder.sign()

        builder.add_memo(self.memo())
        builder.add_time_bounds(self.build_time_bounds())

        builder.append_payment_op(source=Keypair.random(),
                                  destination=keypair.address().decode(),
                                  amount='0.000001')
        builder.sign()

        te = builder.gen_te()

        return te.xdr()
Ejemplo n.º 26
0
def issue_asset(issuer_private_key, distributor_private_key, asset_code, limit,
                network):
    issuer_address = Keypair.from_seed(issuer_private_key).address().decode()
    distributor_address = Keypair.from_seed(
        distributor_private_key).address().decode()
    builder = Builder(secret=distributor_private_key, network=network)
    builder.append_trust_op(destination=issuer_address,
                            code=asset_code,
                            limit=limit)
    builder.sign()
    builder.submit()

    builder = Builder(secret=issuer_private_key, network=network)
    builder.append_payment_op(destination=distributor_address,
                              amount=limit,
                              asset_type=asset_code,
                              asset_issuer=issuer_address)
    builder.sign()
    result = builder.submit()

    return result
Ejemplo n.º 27
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     speech_text = ""
     slots = handler_input.request_envelope.request.intent.slots
     stellar = slots["amount"].value
     receiver = slots["contact"].value
     if receiver.lower() in address_book:
         account = ''.join(value for key, value in address_book.items()
                           if receiver.lower() == key.lower())
         builder = Builder(secret=secret)
         builder.append_payment_op(destination=account,
                                   amount=stellar,
                                   asset_code='XLM')
         builder.sign()
         response = builder.submit()
         speech_text = f"{stellar} stellar has been sent to {receiver}."
     else:
         speech_text = "I could not find that contact in your address book."
     handler_input.response_builder.speak(speech_text).set_card(
         SimpleCard("Hello World",
                    speech_text)).set_should_end_session(False)
     return handler_input.response_builder.response
Ejemplo n.º 28
0
def send_asset(
	systemdb,
	source_name, 
	asset_name, 
	asset_source_name, 
	amount, 
	recipient_name):

	q = Query()
	a_sk = systemdb.search(q.name == source_name)[0]['sk']
	r_pk = systemdb.search(q.name == recipient_name)[0]['pk']

	b = Builder(secret = a_sk, network='TESTNET')
	if asset_source_name == None:
		b.append_payment_op(r_pk, amount, asset_name, None)
	else:
		as_pk = systemdb.search(q.name == asset_source_name)[0]['pk']
		b.append_payment_op(r_pk, amount, asset_name, as_pk)
	
	b.sign()
	response = b.submit()

	print response
Ejemplo n.º 29
0
def payment(target_address: str, amount: str, network, source_secret):
    config = configs[network]
    src_address = Keypair.from_seed(source_secret).address().decode()
    builder = Builder(secret=source_secret,
                      horizon_uri=config['HORIZON_URL'],
                      network=network)
    builder.append_payment_op(destination=target_address,
                              asset_code='HOT',
                              asset_issuer=config['ISSUER_HOT'],
                              amount=amount)
    builder.sign()
    print("###############   TX   #################")
    print('Payment {} HOT from {} to {}'.format(amount, src_address,
                                                target_address))
    print('Network: {}'.format(network))
    print('Sequence: {}'.format(builder.sequence))
    print('Hash: {}'.format(builder.hash()))
    print("#########################################")
    click.confirm('Correct?', abort=True)
    print('Submitting...')
    builder.submit()
    print('success')
    return True
Ejemplo n.º 30
0
async def build_unsigned_add_trust_and_hot(
        source_address: str,
        transaction_source_address: str,
        hot_amount: Decimal,
        sequence: str = None) -> Tuple[str, str]:
    """"Build unsigned transfer transaction return unsigned XDR and transaction hash.

        Args:
            source_address: address need to be trust HOT and address for getting HOT
    """
    builder = Builder(
        address=transaction_source_address,
        horizon=settings['HORIZON_URL'],
        network=settings['PASSPHRASE'],
        sequence=sequence,
    )
    builder.append_trust_op(settings['ISSUER'],
                            settings['ASSET_CODE'],
                            source=source_address,
                            limit=settings['LIMIT_ASSET'])

    if hot_amount > 0:
        builder.append_payment_op(
            source=transaction_source_address,
            destination=source_address,
            asset_code=settings['ASSET_CODE'],
            asset_issuer=settings['ISSUER'],
            amount=hot_amount,
        )

    try:
        unsigned_xdr = builder.gen_xdr()
        tx_hash = builder.te.hash_meta()
    except Exception as ex:
        raise web.HTTPNotFound(text=str(ex))
    return unsigned_xdr.decode('utf8'), binascii.hexlify(tx_hash).decode()
Ejemplo n.º 31
0
def send_asset(issuingkeys, receivingkeys, assetcode):
    send_v1 = Builder(secret=issuingkeys.seed().decode())
    send_v1.append_payment_op(receivingkeys.address().decode(
    ), '1', assetcode, issuingkeys.address().decode())
    send_v1.sign()
    return send_v1.submit()