def test_verify_challenge_tx_donot_contain_managedata_operation(self): server_kp = Keypair.random() client_kp = Keypair.random() timeout = 600 network = 'TESTNET' challenge = Builder(server_kp.seed().decode(), network=network, sequence=-1, fee=100) now = int(time.time()) challenge.add_time_bounds({'minTime': now, 'maxTime': now + timeout}) challenge.append_bump_sequence_op(12, source=client_kp.address().decode()) challenge.sign() challenge_tx_server_signed = challenge.gen_xdr() transaction = Builder(client_kp.seed().decode(), network='TESTNET', sequence=0, fee=100) transaction.import_from_xdr(challenge_tx_server_signed) transaction.sign() challenge_tx = transaction.gen_xdr() with pytest.raises(InvalidSep10ChallengeError, match="Operation type should be ManageData."): Builder.verify_challenge_tx(challenge_tx, server_kp.address().decode(), 'TESTNET')
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()
def test_verify_challenge_tx_source_is_different_to_server_account_id( self): server_kp = Keypair.random() client_kp = Keypair.random() network = 'TESTNET' challenge = Builder(server_kp.seed().decode(), network=network, sequence=-1, fee=100) challenge.sign() challenge_tx_server_signed = challenge.gen_xdr() transaction = Builder(client_kp.seed().decode(), network='TESTNET', sequence=0, fee=100) transaction.import_from_xdr(challenge_tx_server_signed) transaction.sign() challenge_tx = transaction.gen_xdr() with pytest.raises( InvalidSep10ChallengeError, match= "Transaction source account is not equal to server's account." ): Builder.verify_challenge_tx(challenge_tx, Keypair.random().address().decode(), 'TESTNET')
def test_verify_challenge_tx(self): server_kp = Keypair.random() client_kp = Keypair.random() timeout = 600 network = 'Public Global Stellar Network ; September 2015' archor_name = "SDF" challenge = Builder.challenge_tx( server_secret=server_kp.seed().decode(), client_account_id=client_kp.address().decode(), archor_name=archor_name, network=network, timeout=timeout) challenge.sign() challenge_tx_server_signed = challenge.gen_xdr() transaction = Builder( client_kp.seed().decode(), network='Public Global Stellar Network ; September 2015', sequence=0, fee=100) transaction.import_from_xdr(challenge_tx_server_signed) transaction.sign() challenge_tx = transaction.gen_xdr() Builder.verify_challenge_tx( challenge_tx, server_kp.address().decode(), 'Public Global Stellar Network ; September 2015')
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()
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
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
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()
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
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
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()
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
def test_verify_challenge_tx_contains_infinite_timebounds(self): server_kp = Keypair.random() client_kp = Keypair.random() timeout = 600 network = 'TESTNET' archor_name = 'sdf' challenge = Builder(server_kp.seed().decode(), network=network, sequence=-1, fee=100) now = int(time.time()) challenge.add_time_bounds({'minTime': now, 'maxTime': 0}) nonce = os.urandom(64) challenge.append_manage_data_op( data_name='{} auth'.format(archor_name), data_value=nonce, source=client_kp.address().decode()) challenge.sign() challenge_tx_server_signed = challenge.gen_xdr() transaction = Builder(client_kp.seed().decode(), network='TESTNET', sequence=0, fee=100) transaction.import_from_xdr(challenge_tx_server_signed) transaction.sign() challenge_tx = transaction.gen_xdr() with pytest.raises( InvalidSep10ChallengeError, match="Transaction requires non-infinite timebounds."): Builder.verify_challenge_tx(challenge_tx, server_kp.address().decode(), 'TESTNET')
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()
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 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()
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()
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()
def test_import_from_xdr(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=1, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) \ .append_manage_data_op("hello", "world") \ .add_time_bounds({'minTime': 1534392138, 'maxTime': 1534392238}) builder.sign() old_xdr = builder.gen_xdr() old_hash = builder.hash() new_hash = Builder( secret=test_data.cold_secret).import_from_xdr(old_xdr).hash() assert new_hash == old_hash
def test_import_from_xdr_custom_network(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=1, horizon_uri=setup.horizon_endpoint_uri, network='CUSTOM_NETWORK') \ .append_manage_data_op("hello", "world") builder.sign() old_xdr = builder.gen_xdr() old_hash = builder.hash() new_hash = Builder( secret=test_data.cold_secret, network='CUSTOM_NETWORK').import_from_xdr(old_xdr).hash() assert new_hash == old_hash
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')
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()
def test_next_builder(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=1, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) \ .append_manage_data_op("hello", "world") builder.sign() next_builder = builder.next_builder() assert next_builder.keypair == builder.keypair assert next_builder.horizon.horizon_uri == builder.horizon.horizon_uri assert next_builder.address == builder.address assert next_builder.network == builder.network assert next_builder.fee == builder.fee assert next_builder.sequence == builder.sequence + 1
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()
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')
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()
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()
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()
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()
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"}
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
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()