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
Example #2
0
def trust_asset(text):
    if CONF['private_key'] == '':
        print(
            'no private key setup  - use set to set key or c to create wallet')
        return
    val = text.split(' ')
    if len(val) != 3:
        print('invalid syntax please use trust anchor asset')
        return
    url = 'https://raw.githubusercontent.com/stellarterm/stellarterm/master/directory/directory.json'
    r = requests.get(url)
    b = json.loads(r.text)
    asset_name = val[-1].upper()
    asset_anchor = val[1]
    try:
        asset_key = b['anchors'][asset_anchor]['assets'][asset_name].split(
            '-')[1]
    except:
        print('unabled to find anchor or asset so quiting trust')
        return
    trst = Builder(CONF['private_key'], network=CONF['network'])
    if val[0] == 'trust':
        print('trusting.. ' + asset_name + ' ' + asset_key)
        trst.append_trust_op(asset_key, asset_name)
    else:
        print('untrust ' + asset_name + ' ' + asset_key +
              ' please ensure your balance is 0 before this operation')
        trst.append_trust_op(asset_key, asset_name, limit=0)
    trst.sign()
    trst.submit()
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
Example #4
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
Example #5
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()
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()
Example #7
0
def submit(systemdb, Account, ptxnum):
	key = 'ptx'+str(ptxnum)
	q = Query()
	xdr = systemdb.search(q.name==key)[0]['xdr']
	a_sk = systemdb.search(q.name == Account)[0]['sk']

	b = Builder(secret = a_sk, network='TESTNET')
	b.import_from_xdr(xdr)
	print b.submit()
Example #8
0
def set_account(settype, var1):
    print('set account')
    sa = Builder(CONF['private_key'], network=CONF['network'])
    if settype == 'inflation':
        sa.append_set_options_op(inflation=var1)
    else:
        sa.append_set_options_op(home_domain=var1)
    sa.sign()
    sa.submit()
Example #9
0
def lock(systemdb, Account):
	q = Query()
	a_sk = systemdb.search(q.name == Account)[0]['sk']
	b = Builder(secret = a_sk, network='TESTNET')

	b.append_set_options_op(master_weight=0, low_threshold=1, med_threshold=1, high_threshold=1)

	b.sign()

	print b.submit()
Example #10
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()
Example #11
0
def data(
	systemdb,
	Account, 
	name, 
	message):

	q = Query()
	a_sk = systemdb.search(q.name == Account)[0]['sk']
	b = Builder(secret = a_sk, network='TESTNET')

	b.append_manage_data_op(name, message)
	b.sign()
	print b.submit()
Example #12
0
 def cancel_all_offers(self):
     # 取消当前交易对的所有委单
     offers = self.handle_offers_data()
     builder = Builder(secret=self.seed, network=self.network, horizon=self.horizon_url)
     for offer in offers:
         builder.append_manage_offer_op(selling_code=self.selling_asset.code,
                                        selling_issuer=self.selling_asset.issuer,
                                        buying_code=self.buying_asset.code,
                                        buying_issuer=self.buying_asset.issuer,
                                        amount='0',
                                        price='1',
                                        offer_id=offer['id'])
     builder.sign()
     builder.submit()
Example #13
0
def submit_operations(account_seed, operations, transaction_memo):
    """
    This method signs the given operations and submits them to the Stellar network
    :param str account_seed: Seed of the account submitting the operations. It is required to sign the transactions.
    :param Operation operations: Operations to be submitted.
    :param str transaction_memo: Text memo to be included in Stellar transaction. Maximum size of 28 bytes.
    :return: Returns a string containing the server response or None if the transaction could not be submitted.
    :rtype: str or None
    """
    try:
        builder = Builder(secret=account_seed)
    except Exception:
        # Too broad exception because no specific exception is being thrown by the stellar_base package.
        # TODO: This should be fixed in future versions
        print("An error occurred (Please check your Internet connection)")
        return None

    builder.add_text_memo(transaction_memo)
    for operation in operations:
        builder.append_op(operation)
    builder.sign()
    try:
        return builder.submit()
    except Exception:
        # Too broad exception because no specific exception is being thrown by the stellar_base package.
        # TODO: This should be fixed in future versions
        print("An error occurred (Please check your Internet connection)")
        return None
Example #14
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'
Example #15
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()
Example #16
0
def bounty_dispatcher(document, amount):
    """
    Dispatch amount specified to the destination address
    :param document: Desetination address
    :param amount: Amount of nwc to dispatch
    :return: response object
    """
    for line in document:
        builder = Builder(secret=REAL_SEED, network='public')
        builder.add_text_memo(
            "NWC bounty reward amount: {}".format(amount)).append_payment_op(
                destination=line,
                amount=amount,
                asset_code='NWC',
                asset_issuer=ISSUER)
        builder.sign()
        response = builder.submit()
        print(response)
        with open("bounty.log", "a+") as log:
            log.write("\n")
            log.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            log.write("\n")
            log.write("=============================================")
            log.write("\n")
            log.write(json.dumps(response))
            log.write("\n")
    return response
Example #17
0
def burn_tokens(address):
    """
    Burn the recent payments to the address for the percent specified in the BURN_RATE constant
    :param address: address to burn the tokens on
    :return: response object
    """
    # get recent payments
    address_obj = Address(address=address)
    payments = address_obj.payments()
    asset_sum = 0
    for payment in payments:
        asset_sum += payment

    burn_sum = asset_sum * BURN_RATE

    # send the BURN % of tokens to the issuer ultimately taking them out of circulation
    builder = Builder(secret=REAL_SEED, network='public')
    builder.add_text_memo(
        "NWC daily burn: {}".format(burn_sum)).append_payment_op(
            destination=ISSUER,
            amount=burn_sum,
            asset_code='NWC',
            asset_issuer=ISSUER)
    builder.sign()
    response = builder.submit()
    return response
Example #18
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()
Example #19
0
def test_builder_xdr(setup, helpers, test_data):
    hot = Keypair.random()
    hot_account = hot.address().decode()
    hot_secret = hot.seed()

    helpers.fund_account(setup, hot_account)

    cold = Builder(secret=test_data.cold_secret, horizon=setup.horizon_endpoint_uri, network=setup.network) \
        .append_trust_op(test_data.cold_account, 'BEER', '1000', hot_account) \
        .append_allow_trust_op(hot_account, 'BEER', True, test_data.cold_account) \
        .append_payment_op(hot_account, '100', 'BEER', test_data.cold_account, test_data.cold_account) \
        .append_payment_op(test_data.cold_account, '2.222', 'BEER', test_data.cold_account, hot_account)
    cold.sign()

    xdr = cold.gen_xdr()

    hot = Builder(secret=hot_secret,
                  horizon=setup.horizon_endpoint_uri,
                  network=setup.network)
    hot.import_from_xdr(xdr)
    hot.sign()

    assert len(hot.te.signatures) == 2
    assert len(hot.ops) == 4

    response = hot.submit()
    assert response.get('hash') == hot.hash_hex()
Example #20
0
def trust_asset(issuingkeys, receivingkeys, assetcode):
    builder = Builder(secret=issuingkeys.seed().decode(), network='TESTNET')
    builder.append_trust_op(destination=issuingkeys.address(
    ).decode(), code=assetcode, source=receivingkeys.address().decode())
    builder.sign(secret=issuingkeys.seed().decode())
    builder.sign(secret=receivingkeys.seed().decode())
    return builder.submit()
Example #21
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
Example #22
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")
 def create_trustline(self, secret, code):
     builder = Builder(secret=secret, network=self.network)
     builder.append_trust_op(
         self.issuer_keypair.address().decode(),
         code,
         limit='0.0000001'
     )
     builder.sign()
     return builder.submit()
Example #24
0
 def trust_asset(setup, secret_key, memo_text=None):
     """A helper to establish a trustline"""
     builder = Builder(secret=secret_key,
                       horizon_uri=setup.horizon_endpoint_uri,
                       network=setup.network)
     builder.append_trust_op(setup.test_asset.issuer, setup.test_asset.code)
     if memo_text:
         builder.add_text_memo(memo_text[:28])  # max memo length is 28
     builder.sign()
     reply = builder.submit()
     return reply.get('hash')
Example #25
0
def payment():
    min_time = int(time.time()) - 10
    max_time = min_time + 100
    time_bounds = {'minTime': min_time, 'maxTime': max_time}
    builder = Builder(dav_seed).add_time_bounds(time_bounds=time_bounds) \
        .append_payment_op(destination=eve_address, amount='100', asset_code='XLM', asset_issuer=None)
    builder.sign()  # signed by dav with default seed
    builder.sign(alice_seed)  # signed by alice
    builder.sign(bob_seed)  # signed by bob
    resp = builder.submit()
    return resp
Example #26
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')
Example #27
0
def pay(message, amount, secret, address):

    sender_secret = secret
    receiver_address = address

    builder = Builder(secret=sender_secret,
                      horizon_uri=None,
                      network='TESTNET')
    builder.add_text_memo(message).append_payment_op(
        destination=receiver_address, amount=amount, asset_code='XLM')
    builder.sign()
    response = builder.submit()
Example #28
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
Example #29
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()
Example #30
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
Example #31
0
 def send(self, destination, amount):
     destination = check_pay_by_name(destination, "XLM")
     wallet = Wallet.objects.get(user=self.user, name=self.coin)
     try:
         builder = Builder(secret=wallet.private)
         builder.add_text_memo("EXMR, Stellar!").append_payment_op(
             destination=destination.strip(),
             amount=str(amount),
             asset_code='XLM')
         builder.sign()
         response = builder.submit()
         return response["hash"]
     except:
         return {"error": "insufficient funds"}
Example #32
0
 def create_offers(self):
     # 创建挂单。这里是两个订单
     # 买入价格 = 买一价 * (1 - buying_rate)
     # 卖出价格 = 卖一价 * (1 + selling_rate)
     market_price = self.get_price()
     builder = Builder(secret=self.seed, network=self.network, horizon=self.horizon_url)
     # 卖出 base_asset
     selling_price = round(float(market_price['ask']) * (1 + self.selling_rate), 7)
     builder.append_manage_offer_op(selling_code=self.selling_asset.code, selling_issuer=self.selling_asset.issuer,
                                    buying_code=self.buying_asset.code,
                                    buying_issuer=self.buying_asset.issuer,
                                    amount=self.selling_amount, price=selling_price)
     # 买入 base_asset
     buying_tmp_price = float(market_price['bid']) * (1 - self.buying_rate)
     buying_price = round(1 / buying_tmp_price, 7)
     buying_amount = round(self.buying_amount * buying_tmp_price, 7)
     builder.append_manage_offer_op(selling_code=self.buying_asset.code,
                                    selling_issuer=self.buying_asset.issuer,
                                    buying_code=self.selling_asset.code,
                                    buying_issuer=self.selling_asset.issuer,
                                    amount=buying_amount,
                                    price=buying_price)
     builder.sign()
     builder.submit()