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 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 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_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 __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 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 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_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 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 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): """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
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 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 test_federation_payment_not_found_raise(self, setup): builder_fed = Builder( address='GBTCBCWLE6YVTR5Y5RRZC36Z37OH22G773HECWEIZTZJSN4WTG3CSOES', sequence=100) with pytest.raises( FederationError, match= 'Cannot determine Stellar Address to Account ID translation via Federation server.' ): builder_fed.federation_payment(fed_address="bad*fed-domain.com", amount="100.5", asset_code="XLM")
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
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, )
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 tx(self, account, cosigner_keypair, weight): builder = Builder(address=account.get_info()['account_id']) builder.append_set_options_op( high_threshold=10, low_threshold=1, master_weight=10, med_threshold=1, signer_weight=weight, signer_address=cosigner_keypair.address().decode(), signer_type='ed25519PublicKey') return builder.gen_te()
def test_add_memo(self, test_data): builder = Builder(test_data.cold_secret, sequence=1, fee=100) builder.add_text_memo("hello") assert builder.memo == memo.TextMemo("hello") builder.add_id_memo(123123) assert builder.memo == memo.IdMemo(123123) hash = b"\x95\xe5\xbb\x95\x15\xd9\x9f\x82\x9d\xf9\x93\xc3'\x8e\xeb\xf1\nj!\xda\xa4\xa1\xe4\xf2<6cG}\x17\x97\xfe" builder.add_hash_memo(hash) assert builder.memo == memo.HashMemo(hash) builder.add_ret_hash_memo(hash) assert builder.memo == memo.RetHashMemo(hash)
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, )
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 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
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 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 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'
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_generate_merge_transaction( transaction_source_address: str, wallet_detail: Dict, parties_wallet: List = None, sequence: str = None ) -> Tuple[Any, str]: """ Builder transaction close escrow wallet by payment remaining HOT from escrow_wallet to provider_wallet and merge account from escrow_wallet to creator_wallet, Finally, return xdr and transaction_hash Args: escrow_wallet: escrow wallet response from get_escrow_wallet_detail parties_walles : list of provider address and amount for payback """ wallet_address = wallet_detail['escrow_address'] wallet_data = wallet_detail['data'] creator_address = ( wallet_data['creator_address'] if wallet_data and 'creator_address' in wallet_data.keys() else await get_creator_address(wallet_address) ) builder = Builder( address=transaction_source_address, horizon=settings['HORIZON_URL'], network=settings['PASSPHRASE'], sequence=sequence, ) if not parties_wallet: parties_wallet = await generate_parties_wallet(wallet_detail) balance = Decimal(wallet_detail['asset'][settings['ASSET_CODE']]) if not await is_match_balance(parties_wallet, balance): raise web.HTTPBadRequest(reason='Total amount not match wallet balance') await build_payment_operation(builder, wallet_address, parties_wallet) await build_remove_trustlines_operation(builder, wallet_address) await build_remove_manage_data_operation(builder, wallet_address, wallet_data.keys()) await build_account_merge_operation(builder, wallet_address, creator_address) try: 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 xdr.decode(), binascii.hexlify(tx_hash).decode()
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 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 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 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()
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()) \ .append_trust_op(cold_account, 'BEER', 1000, hot_account) \ .append_payment_op(hot_account, 100, 'BEER', cold_account) \ .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