def check_func_secret_seed(k, v, *a, **kw): try: Keypair.from_seed(v).address().decode() except DecodeError as e: raise ValidationError('bad `secret_seed`, "%s": %s' % (v, e)) return
def transfer_fund(amount, asset_object, customer_account, issuer_account, issuer_seed): horizon = horizon_testnet() print('Transferring fund to {}'.format(customer_account)) op = Payment(destination=customer_account, asset=asset_object, amount=str(amount), source=issuer_account) msg = TextMemo('Your first Payment !') sequence = horizon.account(issuer_account).get('sequence') tx = Transaction( source=issuer_account, sequence=sequence, memo=msg, fee=None, operations=[op], ) issuer_account1 = Keypair.from_seed(issuer_seed) envelope = Te(tx=tx, signatures=None, network_id="TESTNET") envelope.sign(issuer_account1) xdr_envelope = envelope.xdr() response = horizon.submit(xdr_envelope) print(response) if 'result_xdr' in response: print('Successful Transfer') else: print('Things go Fishy')
def test_deposit_authenticated_success(client, acc1_usd_deposit_transaction_factory): """`GET /deposit` succeeds with the SEP 10 authentication flow.""" client_address = "GDKFNRUATPH4BSZGVFDRBIGZ5QAFILVFRIRYNSQ4UO7V2ZQAPRNL73RI" client_seed = "SDKWSBERDHP3SXW5A3LXSI7FWMMO5H7HG33KNYBKWH2HYOXJG2DXQHQY" settings.DEPOSIT_AUTH_REQUIRED = True deposit = acc1_usd_deposit_transaction_factory() # SEP 10. response = client.get(f"/auth?account={client_address}", follow=True) content = json.loads(response.content) envelope_xdr = content["transaction"] envelope_object = TransactionEnvelope.from_xdr(envelope_xdr) client_signing_key = Keypair.from_seed(client_seed) envelope_object.sign(client_signing_key) client_signed_envelope_xdr = envelope_object.xdr().decode("ascii") response = client.post( "/auth", data={"transaction": client_signed_envelope_xdr}, content_type="application/json", ) content = json.loads(response.content) encoded_jwt = content["token"] assert encoded_jwt header = {"HTTP_AUTHORIZATION": f"Bearer {encoded_jwt}"} response = client.get( f"/deposit?asset_code=USD&account={deposit.stellar_account}", follow=True, **header, ) content = json.loads(response.content) assert response.status_code == 403 assert content["type"] == "interactive_customer_info_needed"
def Place_buy_order(buyAsset, buyAssetIssuer, amount, offerID, price, sourceAdd, sourceSeed): #the amount here need to be the amount of xlm you want to sell, and the price need to be the price of xlm in terms of the asset you want to buy from stellar_base.operation import ManageOffer sequence3 = horizon.account(sourceAdd).get('sequence') assetBuy = asset_Identifier(buyAsset, buyAssetIssuer) assetSell = Asset('XLM') op_so = ManageOffer({ 'selling': assetSell, 'buying': assetBuy, 'amount': str(amount), 'price': str(price), 'offer_id': offerID }) tx_so = Transaction(source=sourceAdd, opts={ 'sequence': sequence3, 'operations': [op_so] }) envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"}) kp = Keypair.from_seed(sourceSeed) envelope_so.sign(kp) xdr3 = envelope_so.xdr() response = horizon.submit(xdr3) result = passed_or_not(response) return response['result_xdr']
def send_xlm_vault_transaction(user, destination, amount): from stellar_base.transaction import Transaction wallet = VaultWallet.objects.get(username=user, name="xlm") User = Keypair.from_seed(wallet.private) horizon = horizon_testnet() asset = Asset.native() op = Payment({ 'destination': destination, 'asset': asset, 'amount': amount }) msg = TextMemo('From test net !') sequence = horizon.account(User.address().decode('utf-8')).get('sequence') tx = Transaction( source=User.address().decode(), opts={ 'sequence': sequence, 'memo': msg, 'operations': [ op, ], }, ) try: envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(User) xdr = envelope.xdr() response = horizon.submit(xdr) return response['hash'] except: return {"error": ""}
def opr_change_trust(asset_object, receiver_address, receiver_seed): horizon = horizon_testnet() sequence = horizon.account(receiver_address).get('sequence') print(sequence) op = ChangeTrust( asset=asset_object, limit='5000', source=receiver_address ) # print(op.__dict__) msg = TextMemo('Change Trust Operation') receiving_account = Keypair.from_seed(receiver_seed) tx = Transaction( source=receiving_account.address().decode(), sequence=sequence, time_bounds=None, memo=msg, fee=None, operations=[op], ) envelope = Te(tx=tx, signatures=None, network_id="TESTNET") envelope.sign(receiving_account) xdr_envelope = envelope.xdr() response = horizon.submit(xdr_envelope) print(response) if 'result_xdr' in response: print('Successful') else: print('Things go Fishy')
def __init__(self, secret=None, address=None, horizon=None, horizon_uri=None, network=None): if secret: if not is_valid_secret_key(secret): raise ValueError('invalid secret key') address = Keypair.from_seed(secret).address().decode() elif address: if not is_valid_address(address): raise ValueError('invalid address') else: raise Exception('either secret or address must be provided') # call baseclass constructor to init base class variables super(Builder, self).__init__(secret=secret, address=address, sequence=1) # custom overrides self.network = network.upper() if network else 'PUBLIC' if horizon: self.horizon = horizon elif horizon_uri: self.horizon = Horizon(horizon_uri) else: self.horizon = Horizon( HORIZON_LIVE) if self.network == 'PUBLIC' else Horizon( HORIZON_TEST)
def Cancel_buy_order(buyAsset, buyAssetIssuer, price, xdr_result, sourceAdd, sourceSeed): from stellar_base.operation import ManageOffer offerID = Get_offer_ID(xdr_result) sequence3 = horizon.account(sourceAdd).get('sequence') assetBuy = asset_Identifier(buyAsset, buyAssetIssuer) assetSell = Asset('XLM') op_so = ManageOffer({ 'selling': assetSell, 'buying': assetBuy, 'amount': str(0), 'price': str(price), 'offer_id': offerID }) #How to get the ID of existing order tx_so = Transaction(source=sourceAdd, opts={ 'sequence': sequence3, 'operations': [op_so] }) envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"}) kp = Keypair.from_seed(sourceSeed) envelope_so.sign(kp) xdr3 = envelope_so.xdr() response = horizon.submit(xdr3) result = passed_or_not(response) return response['result_xdr']
def create_account(user): # type: (User) -> None # create keypair keypair = Keypair.random() public_key = keypair.address().decode() seed = keypair.seed().decode() # store account StellarAccount.objects.create(seed=seed, address=public_key, user=user, balance=0.0) horizon = horizon_testnet() if settings.DEMO_MODE else horizon_livenet() # fund account if settings.DEMO_MODE: for _ in range(5): # noinspection PyBroadException try: funding_keypair = Keypair.from_seed( settings.FUNDING_ACCOUNT_SEED) # create operation create_account_operation = CreateAccount({ 'destination': public_key, 'starting_balance': '1' }) # create transaction sequence = horizon.account( funding_keypair.address().decode()).get('sequence') tx = Transaction(source=funding_keypair.address().decode(), opts={ 'sequence': sequence, 'memo': TextMemo('Creating new Zendi account.'), 'operations': [create_account_operation] }) # create and sign envelope envelope = TransactionEnvelope(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(funding_keypair) # Submit the transaction to Horizon te_xdr = envelope.xdr() horizon.submit(te_xdr) break except Exception as ex: logger.error('Error while funding account', ex) time.sleep(1) logger.info('Created Stellar Lumen account {} for {}'.format( public_key, user))
def do(self, network, op): tx = Transaction(self.source, sequence=1) tx.add_operation(op) envelope = Te(tx, network_id=network) signer = Keypair.from_seed(self.seed) envelope.sign(signer) envelope_b64 = envelope.xdr() return envelope_b64
def build(self, developer_secret, address, network=None): dev_keypair = Keypair.from_seed(developer_secret) dev_account = AccountBuilder().build(dev_keypair) user_keypair = Keypair.from_address(address) user_account = AccountBuilder().build(user_keypair) return App(dev_account,user_account,network)
def __init__(self, key=None): if key is None: self.kp = Keypair.random() else: try: self.kp = Keypair.from_seed(key) except: print("You passed a wrong private key as third argument") raise
def do(self, network, opts): tx = Transaction(self.source, **opts) tx.add_operation(Inflation()) envelope = Te(tx, network_id=network) signer = Keypair.from_seed(self.seed) envelope.sign(signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def send_asset(amt, from_addr, to_addr, asset_nm): asset = Asset(asset_nm, issuer_addr) tx = Transaction(source=from_addr['address'], opts={'sequence': str(get_sequence(from_addr['address'])), 'fee': 100}) pay_dic = {'destination': to_addr['address'],'asset': asset, 'amount': str(amt)} tx.add_operation(operation=Payment(pay_dic)) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(Keypair.from_seed(from_addr['seed'])) req = hz.submit(te=envelope.xdr()) print(req)
def generate_non_fungible_token(self, initial_owner_secret, code, metadata=None): owner_keypair = Keypair.from_seed(initial_owner_secret) # First we generate the token trustline on the network self.create_trustline(initial_owner_secret, code) # Next we send exactly 0.0000001 to the initial owner return self.create_token_and_lock_account( code, owner_keypair.address().decode(), metadata )
def school_login(): # To be able to reload if request.method == 'GET': return render_template('index.html', js_folder=url_for('static', filename='js'), img_folder=url_for('static', filename='img'), css_folder=url_for('static', filename='css'), school=1) try: Keypair.from_seed(request.form['secret']) # To check if the key is valid session['school_seed'] = request.form['secret'] return render_template('index.html', js_folder=url_for('static', filename='js'), img_folder=url_for('static', filename='img'), css_folder=url_for('static', filename='css'), school=1) except: return render_template('index.html', js_folder=url_for('static', filename='js'), img_folder=url_for('static', filename='img'), css_folder=url_for('static', filename='css'), school=1, formschoolerror=1)
def do(self, op): from stellar_base.transaction import Transaction from stellar_base.keypair import Keypair from stellar_base.transaction_envelope import TransactionEnvelope as Te tx = Transaction(source=self.source, opts={'sequence': self.seq}) tx.add_operation(operation=op) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) signer = Keypair.from_seed(seed=self.seed) envelope.sign(keypair=signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def do(self, op): from stellar_base.transaction import Transaction from stellar_base.keypair import Keypair from stellar_base.transaction_envelope import TransactionEnvelope as Te tx = Transaction(source=self.source, opts={'sequence': self.seq}) tx.add_operation(operation=op) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) signer = Keypair.from_seed(seed=self.seed) envelope.sign(keypair=signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def unlock(self): seed = self.keyInput.get() try: self.kp = Keypair.from_seed(seed) self.connected = True self.key = self.kp.seed().decode() self.address = self.kp.address().decode() except: messagebox.showerror( "Wrong key", "Cannot unlock the account, please check the key you entered") self.run()
def __init__(self, secret_key, channel_keys, network, horizon): self.base_key = secret_key self.base_address = Keypair.from_seed(secret_key).address().decode() self.num_channels = len(channel_keys) self.channel_builders = queue.Queue(len(channel_keys)) self.horizon = horizon for channel_key in channel_keys: # create a channel transaction builder. builder = Builder(secret=channel_key, network=network, horizon=horizon) self.channel_builders.put(builder)
def transaction( ): # Performs the transaction from one to another thus providing the current balance. amount = str(request.form['amount']) # Amount taken from the user. memo = TextMemo(request.form['memo']) # Memo entered by user. send = Keypair.from_seed(send_seed) horizon = horizon_testnet() asset = Asset('XLM') op = Payment({ 'destination': receive_publickey, 'asset': asset, 'amount': amount, }) sequence = horizon.account(send.address()).get('sequence') tx = Transaction( source=send.address().decode(), opts={ 'sequence': sequence, 'memo': memo, 'fee': 100, 'operations': [ op, ], }, ) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(send) xdr = envelope.xdr() response = horizon.submit(xdr) trans = response['_links'] for values in trans.itervalues(): for confirmation in values.itervalues(): confirm = confirmation 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, 'confirm': confirm, # 'amount': amount, } return render_template("transaction.html", cbalance=cbalance)
def test_transaction_authenticated_success( mock_render, client, acc1_usd_deposit_transaction_factory, acc2_eth_withdrawal_transaction_factory, ): """ Succeeds with expected response if authentication required. Though it filters using the stellar transaction ID, the logic should apply in any case. """ del mock_render client_address = "GDKFNRUATPH4BSZGVFDRBIGZ5QAFILVFRIRYNSQ4UO7V2ZQAPRNL73RI" client_seed = "SDKWSBERDHP3SXW5A3LXSI7FWMMO5H7HG33KNYBKWH2HYOXJG2DXQHQY" acc1_usd_deposit_transaction_factory() withdrawal = acc2_eth_withdrawal_transaction_factory() withdrawal.stellar_address = client_address withdrawal.save() # SEP 10. response = client.get(f"/auth?account={client_address}", follow=True) content = json.loads(response.content) envelope_xdr = content["transaction"] envelope_object = TransactionEnvelope.from_xdr(envelope_xdr) client_signing_key = Keypair.from_seed(client_seed) envelope_object.sign(client_signing_key) client_signed_envelope_xdr = envelope_object.xdr().decode("ascii") response = client.post( "/auth", data={"transaction": client_signed_envelope_xdr}, content_type="application/json", ) content = json.loads(response.content) encoded_jwt = content["token"] assert encoded_jwt # For testing, we make the key `HTTP_AUTHORIZATION`. This is the value that # we expect due to the middleware. header = {"HTTP_AUTHORIZATION": f"Bearer {encoded_jwt}"} response = client.get( f"/transaction?stellar_transaction_id={withdrawal.stellar_transaction_id}", follow=True, **header, ) content = json.loads(response.content) assert response.status_code == 200 withdrawal_transaction = content.get("transaction") assert withdrawal_transaction["kind"] == "withdrawal" assert withdrawal_transaction["status"] == Transaction.STATUS.completed
def balance_api(): """endpoint used to get the current balance of the seed and channels""" if not config.DEBUG: limit_to_localhost() base_seed, channel_seeds = ssm.get_stellar_credentials() balance = {'base_seed': {}, 'channel_seeds': {}} from stellar_base.keypair import Keypair balance['base_seed']['kin'] = stellar.get_kin_balance( Keypair.from_seed(base_seed).address().decode()) balance['base_seed']['xlm'] = stellar.get_xlm_balance( Keypair.from_seed(base_seed).address().decode()) index = 0 for channel in channel_seeds: # seeds only need to carry XLMs balance['channel_seeds'][index] = {'xlm': 0} balance['channel_seeds'][index]['xlm'] = stellar.get_xlm_balance( Keypair.from_seed(channel).address().decode()) index = index + 1 return jsonify(status='ok', balance=balance)
def make_envelope(self, network, *args, **kwargs): opts = {'sequence': 1, 'fee': 100 * len(args)} for opt, value in kwargs.items(): opts[opt] = value tx = Transaction(self.address, **opts) for count, op in enumerate(args): tx.add_operation(op) envelope = Te(tx, network_id=network) signer = Keypair.from_seed(self.seed) envelope.sign(signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def __init__(self, config): self.seed = os.environ.get('STELLAR_SEED') or config.get('stellar_seed') self.keypair = Keypair.from_seed(self.seed) self.address = self.keypair.address().decode() self.selling_asset = Asset(config['base_asset']['code'], config['base_asset']['issuer']) self.buying_asset = Asset(config['counter_asset']['code'], config['counter_asset']['issuer']) self.buying_amount = config['buying_amount'] self.buying_rate = config['buying_rate'] self.selling_amount = config['selling_amount'] self.selling_rate = config['selling_rate'] self.horizon_url = config['horizon'] self.horizon = Horizon(config['horizon']) self.network = 'public'
def test_transactions_authenticated_success( mock_render, client, acc2_eth_withdrawal_transaction_factory, acc2_eth_deposit_transaction_factory, ): """ Response has correct length and status code, if the SEP 10 authentication token is required. """ del mock_render client_address = "GDKFNRUATPH4BSZGVFDRBIGZ5QAFILVFRIRYNSQ4UO7V2ZQAPRNL73RI" client_seed = "SDKWSBERDHP3SXW5A3LXSI7FWMMO5H7HG33KNYBKWH2HYOXJG2DXQHQY" withdrawal = acc2_eth_withdrawal_transaction_factory() withdrawal.stellar_address = client_address withdrawal.save() acc2_eth_deposit_transaction_factory() # SEP 10. response = client.get(f"/auth?account={client_address}", follow=True) content = json.loads(response.content) envelope_xdr = content["transaction"] envelope_object = TransactionEnvelope.from_xdr(envelope_xdr) client_signing_key = Keypair.from_seed(client_seed) envelope_object.sign(client_signing_key) client_signed_envelope_xdr = envelope_object.xdr().decode("ascii") response = client.post( "/auth", data={"transaction": client_signed_envelope_xdr}, content_type="application/json", ) content = json.loads(response.content) encoded_jwt = content["token"] assert encoded_jwt # For testing, we make the key `HTTP_AUTHORIZATION`. This is the value that # we expect due to the middleware. header = {"HTTP_AUTHORIZATION": f"Bearer {encoded_jwt}"} response = client.get( f"/transactions?asset_code={withdrawal.asset.name}&account={withdrawal.stellar_account}", follow=True, **header, ) content = json.loads(response.content) assert len(content.get("transactions")) == 2 assert response.status_code == 200
def make_envelope(network, horizon, address, seed, *args, **kwargs): opts = { 'sequence': horizon.account(address)['sequence'], 'fee': 100 * len(args) } for opt, value in kwargs.items(): opts[opt] = value tx = Transaction(address, **opts) for count, op in enumerate(args): tx.add_operation(op) envelope = Te(tx, network_id=network) signer = Keypair.from_seed(seed) envelope.sign(signer) envelope_xdr = envelope.xdr() return envelope_xdr
def __init__(self, base_seed, channel_seeds, network, horizon): if not base_seed: raise ValueError('base seed not provided') if not network: raise ValueError('network not provided') if not horizon: raise ValueError('horizon not provided') self.base_seed = base_seed self.base_address = Keypair.from_seed(base_seed).address().decode() self.channel_builders = queue.Queue(len(channel_seeds)) for channel_seed in channel_seeds: # create a channel transaction builder and load channel account sequence number. builder = Builder(secret=channel_seed, network=network, horizon=horizon) self.channel_builders.put(builder)
def perform_transaction(self): send_seed = self.seed1 recieve_address = self.publickey2 amount = str(input("\nEnter the amount to be transferred(0-9998): ")) print("0.0000100 will be charged extra for the transaction") send = Keypair.from_seed(send_seed) horizon = horizon_testnet() asset = Asset('XLM') op = Payment({ 'destination': recieve_address, 'asset': asset, 'amount': amount, }) msg = TextMemo('Transaction Test') print("Transferring the ammount to the Receiver......") sequence = horizon.account(send.address()).get('sequence') tx = Transaction( source=send.address().decode(), opts={ 'sequence': sequence, 'memo': msg, 'fee': 100, 'operations': [ op, ], }, ) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(send) xdr = envelope.xdr() response = horizon.submit(xdr) print("Transaction completed successfully.\n") trans = response['_links'] for values in trans.itervalues(): for confirmation in values.itervalues(): print("Confirmation Link: " + confirmation) print( "\n------------------------------------------------------------------------------" ) print("\nChecking the current balance......")
def make_envelope(self, *args, **kwargs): from stellar_base.transaction import Transaction from stellar_base.keypair import Keypair from stellar_base.transaction_envelope import TransactionEnvelope as Te opts = {'sequence': self.seq, 'fee': self.fee * len(args)} for opt, value in kwargs.items(): opts[opt] = value tx = Transaction(source=self.address, opts=opts) for count, op in enumerate(args): tx.add_operation(operation=op) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) signer = Keypair.from_seed(seed=self.seed) envelope.sign(keypair=signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def is_seed_matching_address(seed, address): """ Checks if the specified seed address matches the specified address. :param str seed: Seed to be evaluated. :param str address: Address to be evaluated. :return: Returns true if seed address matches the specified address, and false otherwise. :rtype: bool """ if not is_seed_valid(seed) \ or not is_address_valid(address): return False keypair = Keypair.from_seed(seed=seed) if keypair.address().decode() == address: return True return False
def make_envelope(self, *args, **kwargs): from stellar_base.transaction import Transaction from stellar_base.keypair import Keypair from stellar_base.transaction_envelope import TransactionEnvelope as Te opts = {"sequence": self.seq, "fee": self.fee * len(args)} for opt, value in kwargs.items(): opts[opt] = value tx = Transaction(source=self.address, opts=opts) for count, op in enumerate(args): tx.add_operation(operation=op) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) signer = Keypair.from_seed(seed=self.seed) envelope.sign(keypair=signer) envelope_b64 = envelope.xdr() print(envelope_b64) return envelope_b64
def do_single_signer(operation_opts=False, tx_opts=False): assert operation_opts and tx_opts from stellar_base.operation import Payment from stellar_base.transaction import Transaction from stellar_base.keypair import Keypair from stellar_base.transaction_envelope import TransactionEnvelope as Te operation = Payment(opts=operation_opts) tx = Transaction(source=SOURCE, opts=tx_opts) tx.add_operation(operation=operation) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) signer = Keypair.from_seed(seed=SEED) envelope.sign(keypair=signer) envelope_b64 = bip(envelope) print(envelope_b64) return envelope_b64
print('Anna: ', json.dumps(anna, sort_keys=True, indent=4 * ' ')) print('Bob: ', json.dumps(bob, sort_keys=True, indent=4 * ' ')) operation = Payment({ 'source': anna['address'], 'destination': bob['address'], 'asset': Asset.native(), 'amount': '1000', # needs to be a string? }) tx = Transaction( source=anna['address'], opts={ 'sequence': json.loads(requests.get(url+'/accounts/'+anna['address']).text)['sequence'], 'timeBounds': [], 'memo': NoneMemo(), 'fee': 100, 'operations': [ operation, ], }, ) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(Keypair.from_seed(anna['seed'])) print('Tx: ', json.dumps(json.loads(requests.post( url=url+'/transactions', data={ 'tx': packer(envelope).decode('ascii') } ).text), sort_keys=True, indent=4 * ' '))
def te_xdr_build(tx, secret): envelope = Envelope(tx) signer = Keypair.from_seed(secret) envelope.sign(signer) re = envelope.xdr() return re