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()
def test_network_and_horizon(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=100, network='MOE') assert builder.network == 'MOE' assert builder.horizon.horizon_uri == horizon_testnet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='testnet') assert builder.network == 'TESTNET' assert builder.horizon.horizon_uri == horizon_testnet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='public') assert builder.network == 'PUBLIC' assert builder.horizon.horizon_uri == horizon_livenet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='public', horizon_uri=setup.horizon_endpoint_uri) assert builder.network == 'PUBLIC' assert builder.horizon.horizon_uri == Horizon( horizon_uri=setup.horizon_endpoint_uri).horizon_uri
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_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 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 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 test_gen_compliance_xdr(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=100, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) \ .append_manage_data_op("hello", "world") xdr = builder.gen_compliance_xdr() builder_seq_zero = Builder(secret=test_data.cold_secret, sequence=-1, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) \ .append_manage_data_op("hello", "world") assert xdr == builder_seq_zero.gen_tx().xdr() assert builder.sequence == 100
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 test_federation_payment(self, setup): builder_fed = Builder( address='GBTCBCWLE6YVTR5Y5RRZC36Z37OH22G773HECWEIZTZJSN4WTG3CSOES', sequence=100) builder_fed.federation_payment(fed_address="fed*fed-domain.com", amount="100.5", asset_code="XLM") builder = Builder( address='GBTCBCWLE6YVTR5Y5RRZC36Z37OH22G773HECWEIZTZJSN4WTG3CSOES', sequence=100).add_text_memo("hello memo").append_payment_op( destination= 'GBTCBCWLE6YVTR5Y5RRZC36Z37OH22G773HECWEIZTZJSN4WTG3CSOES', asset_code='XLM', amount="100.5") assert builder_fed.hash() == builder.hash()
def __init__(self, account): self.account = account if account.secret: self.builder = Builder(secret=account.secret, network=account.network) self.address = Address(address=account.account_id, network=account.network)
def build_unsigned_change_trust(source_address: str, transaction_source_address: str, 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 """ 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']) 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()
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()
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 __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 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 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 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 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
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 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 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 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 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 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()
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 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
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 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