Exemplo n.º 1
0
    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')
Exemplo n.º 2
0
def test_sdk_create_fail(setup, helpers, test_sdk):
    with pytest.raises(ValueError, match='invalid secret key: bad'):
        kin.SDK(secret_key='bad',
                horizon_endpoint_uri=setup.horizon_endpoint_uri,
                network=setup.network,
                kin_asset=setup.test_asset)

    keypair = Keypair.random()
    secret_key = keypair.seed()
    address = keypair.address().decode()

    with pytest.raises(ValueError, match='invalid channel key: bad'):
        kin.SDK(secret_key=secret_key,
                channel_secret_keys=['bad'],
                horizon_endpoint_uri=setup.horizon_endpoint_uri,
                network=setup.network,
                kin_asset=setup.test_asset)

    # wallet account does not exist
    with pytest.raises(kin.AccountNotFoundError):
        kin.SDK(secret_key=secret_key,
                horizon_endpoint_uri=setup.horizon_endpoint_uri,
                network=setup.network,
                kin_asset=setup.test_asset)

    helpers.fund_account(setup, address)

    # wallet account exists but not yet activated
    with pytest.raises(kin.AccountNotActivatedError):
        kin.SDK(secret_key=secret_key,
                horizon_endpoint_uri=setup.horizon_endpoint_uri,
                network=setup.network,
                kin_asset=setup.test_asset)

    helpers.trust_asset(setup, secret_key)

    channel_keypair = Keypair.random()
    channel_secret_key = channel_keypair.seed()

    # channel account does not exist
    with pytest.raises(kin.AccountNotFoundError):
        kin.SDK(secret_key=secret_key,
                channel_secret_keys=[channel_secret_key],
                horizon_endpoint_uri=setup.horizon_endpoint_uri,
                network=setup.network,
                kin_asset=setup.test_asset)

    # bad Horizon endpoint
    with pytest.raises(kin.NetworkError):
        kin.SDK(secret_key=secret_key,
                horizon_endpoint_uri='bad',
                network=setup.network,
                kin_asset=setup.test_asset)

    # no Horizon on endpoint
    with pytest.raises(kin.NetworkError):
        kin.SDK(secret_key=secret_key,
                horizon_endpoint_uri='http://localhost:666',
                network=setup.network,
                kin_asset=setup.test_asset)
Exemplo n.º 3
0
    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')
Exemplo n.º 4
0
    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')
Exemplo n.º 5
0
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))
Exemplo n.º 6
0
                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
Exemplo n.º 7
0
    def test_set_account_signers(self):
        pool_kp = Keypair.random()
        signer1 = Keypair.random()
        signer2 = Keypair.random()

        # fixture for getting the account
        responses.add(responses.GET,
                      'https://horizon-testnet.stellar.org/accounts/%s' %
                      (pool_kp.address().decode()),
                      body=json.dumps({'sequence': '1234'}),
                      content_type='application/json')

        # fixture for creating a transaction
        responses.add(responses.POST,
                      'https://horizon-testnet.stellar.org/transactions/',
                      body=json.dumps({
                          '_links': {
                              'transaction': {
                                  'href': 'http://transaction-url/'
                              }
                          }
                      }),
                      content_type='application/json')

        signers_file = self.mock_signers_file([
            signer1,
            signer2,
        ])

        signers = get_signers(signers_file.name)
        self.assertTrue(
            set_account_signers(horizon_testnet(), pool_kp, signers,
                                SIGNING_THRESHOLD))
Exemplo n.º 8
0
    def test_create_pool_account(self):
        account_kp = Keypair.random()
        pool_kp = Keypair.random()

        # fixture for getting the account
        responses.add(responses.GET,
                      'https://horizon-testnet.stellar.org/accounts/%s' %
                      (account_kp.address().decode()),
                      body=json.dumps({'sequence': '1234'}),
                      content_type='application/json')

        # fixture for creating a transaction
        responses.add(responses.POST,
                      'https://horizon-testnet.stellar.org/transactions/',
                      body=json.dumps({
                          '_links': {
                              'transaction': {
                                  'href': 'http://transaction-url/'
                              }
                          }
                      }),
                      content_type='application/json')

        self.assertTrue(
            create_pool_account(horizon_testnet(), 'TESTNET',
                                account_kp.seed(), pool_kp))
Exemplo n.º 9
0
def setup(testnet):
    class Struct:
        """Handy variable holder"""
        def __init__(self, **entries):
            self.__dict__.update(entries)

    sdk_keypair = Keypair.random()
    issuer_keypair = Keypair.random()
    test_asset = Asset('KIN', issuer_keypair.address().decode())

    # global testnet
    if testnet:
        from stellar_base.horizon import HORIZON_TEST
        return Struct(type='testnet',
                      network='TESTNET',
                      sdk_keypair=sdk_keypair,
                      issuer_keypair=issuer_keypair,
                      test_asset=test_asset,
                      horizon_endpoint_uri=HORIZON_TEST)

    # local testnet (zulucrypto docker)
    # https://github.com/zulucrypto/docker-stellar-integration-test-network
    from stellar_base.network import NETWORKS
    NETWORKS['CUSTOM'] = 'Integration Test Network ; zulucrypto'
    return Struct(type='local',
                  network='CUSTOM',
                  sdk_keypair=sdk_keypair,
                  issuer_keypair=issuer_keypair,
                  test_asset=test_asset,
                  horizon_endpoint_uri='http://localhost:8000')
Exemplo n.º 10
0
    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')
Exemplo n.º 11
0
def test_monitor_accounts_kin_payments_multiple(setup, test_sdk, helpers):
    keypair1 = Keypair.random()
    address1 = keypair1.address().decode()
    keypair2 = Keypair.random()
    address2 = keypair2.address().decode()

    assert test_sdk.create_account(address1, starting_balance=100)
    assert test_sdk.create_account(address2, starting_balance=100)
    assert helpers.trust_asset(setup, keypair1.seed())
    assert helpers.trust_asset(setup, keypair2.seed())

    ev1 = threading.Event()
    ev2 = threading.Event()
    tx_datas1 = []
    tx_datas2 = []

    def account_tx_callback(addr, tx_data):
        assert addr == address1 or addr == address2
        op_data = tx_data.operations[0]
        if op_data.to_address == address1:
            tx_datas1.append(tx_data)
            ev1.set()
        elif op_data.to_address == address2:
            tx_datas2.append(tx_data)
            ev2.set()

    # start monitoring
    sleep(1)
    test_sdk.monitor_accounts_kin_payments([address1, address2],
                                           account_tx_callback)

    # send payments
    tx_hash12 = test_sdk.send_kin(address1, 10)
    assert tx_hash12
    tx_hash22 = test_sdk.send_kin(address2, 10)
    assert tx_hash22

    # wait until callback gets them all
    assert ev1.wait(3)
    assert ev2.wait(3)

    # check collected operations
    assert tx_datas1[0].hash == tx_hash12
    op_data = tx_datas1[0].operations[0]
    assert op_data.type == 'payment'
    assert op_data.asset_code == setup.test_asset.code
    assert op_data.asset_issuer == setup.test_asset.issuer
    assert op_data.from_address == test_sdk.get_address()
    assert op_data.to_address == address1
    assert op_data.amount == Decimal('10')

    assert tx_datas2[0].hash == tx_hash22
    op_data = tx_datas2[0].operations[0]
    assert op_data.type == 'payment'
    assert op_data.asset_code == setup.test_asset.code
    assert op_data.asset_issuer == setup.test_asset.issuer
    assert op_data.from_address == test_sdk.get_address()
    assert op_data.to_address == address2
    assert op_data.amount == Decimal('10')
    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)
Exemplo n.º 13
0
 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
Exemplo n.º 14
0
def create_multiple_keypair():
    print("Create multiple keypair")
    sm = StellarMnemonic()
    secret_phrase = sm.generate()
    kp0 = Keypair.deterministic(secret_phrase, index=0)
    kp1 = Keypair.deterministic(secret_phrase, index=1)
    kp2 = Keypair.deterministic(secret_phrase, index=2)
    for keypair in (kp0, kp1, kp2):
        print("Public key / Account address:\n", keypair.address().decode())
        print("Seed / Your secret to keep it on local:\n",
              keypair.seed().decode())
Exemplo n.º 15
0
def test_channels(setup):
    # prepare channel accounts
    channel_keypairs = [
        Keypair.random(),
        Keypair.random(),
        Keypair.random(),
        Keypair.random()
    ]
    channel_seeds = [
        channel_keypair.seed() for channel_keypair in channel_keypairs
    ]
    channel_addresses = [
        channel_keypair.address().decode()
        for channel_keypair in channel_keypairs
    ]
    for channel_address in channel_addresses:
        fund(setup, channel_address)

    # init sdk with these channels
    sdk = kin.SDK(base_seed=setup.sdk_keypair.seed(),
                  horizon_endpoint_uri=setup.horizon_endpoint_uri,
                  network=setup.network,
                  channel_seeds=channel_seeds)
    assert sdk
    assert sdk.channel_manager
    assert sdk.channel_manager.channel_builders.qsize() == len(
        channel_keypairs)

    def channel_worker():
        # create an account using a channel
        address = Keypair.random().address().decode()
        tx_hash = sdk.create_account(address, starting_balance=100)
        assert tx_hash
        sleep(1)
        tx_data = sdk.get_transaction_data(tx_hash)
        assert tx_data
        # transaction envelope source is some channel account
        assert tx_data.source_account in channel_addresses
        # operation source is the base account
        assert tx_data.operations[0].source_account == sdk.get_address()

    # now issue parallel transactions
    threads = []
    for channel_keypair in channel_keypairs:
        t = threading.Thread(target=channel_worker)
        threads.append(t)
    for t in threads:
        t.start()

    # wait for all to finish
    for t in threads:
        t.join()
Exemplo n.º 16
0
def generate_pool_keypair(desired_tail=None):
	kp = None

	if desired_tail:

		logger.debug("Looking for address ending in '%s'..." % (desired_tail,))
		while True:
			kp = Keypair.random()
			if kp.address().decode()[-len(desired_tail):] == desired_tail:
				break
	else:
		kp = Keypair.random()

	return kp
Exemplo n.º 17
0
def generate_pool_keypair():
	kp = None

	if len(sys.argv) > 1:
		desired_tail = sys.argv[1]

		print("Looking for address ending in '" + desired_tail + "'...")
		while True:
			kp = Keypair.random()
			if kp.address().decode()[-len(desired_tail):] == desired_tail:
				break
	else:
		kp = Keypair.random()

	return kp
Exemplo n.º 18
0
def _init_session_from_new_account():
    """
    Initializes a session from a newly created account. A Stellar keypair is randomly generated.
    :return: Returns the initialized CLI session.
    :rtype: CliSession
    """
    account_name = None
    if yes_or_no_input(
            "Do you want to give a name to the new account to be created?"
    ) == USER_INPUT_YES:
        account_name = safe_input("Please insert the account name")

    keypair = Keypair.random()
    address = keypair.address().decode()
    seed = keypair.seed().decode()

    cli_session = CliSession(account_name, address, seed)
    if _config_file_is_to_update():
        if yes_or_no_input("Do you want to save the seed of the new account in the encrypted configuration file") == \
                USER_INPUT_YES:
            cli_session.store_account_in_config_file()
        else:
            seed_file = safe_input(
                "Specify a file to which the seed of the new created account should be saved. "
                "Notice that the seed will be saved in plain text on the specified file. "
                "Please store it in a safe place. If anyone can reach the seed it can fully "
                "control your account")
            write_file(seed_file, seed)
            cli_session.store_account_in_config_file()
    return cli_session
Exemplo n.º 19
0
def create_vault_wallet(user, username, currency):
    if currency not in ('xmr','eth','xlm'):
        access = globals()['create_'+currency+'_connection']()
        addr = access.getnewaddress(username)
    elif currency == 'xmr':
        paymentid = (binascii.b2a_hex(os.urandom(8))).decode()
        moneropaymentid = MoneroPaymentid.objects.create(
            user=user, paymentid=paymentid)
        param = {
            "payment_id": paymentid
        }
        addr = create_xmr_connection("make_integrated_address", param)[
            "result"]['integrated_address']
    elif currency == 'xlm':
        kp = Keypair.random()
        addr = kp.address().decode()
        requests.get('https://friendbot.stellar.org/?addr=' + addr)    
        vault, created = VaultWallet.objects.get_or_create(
        user=user, username=username, name=currency)
        vault.addresses.add(WalletAddress.objects.create(address=addr))
        vault.private = kp.seed().decode()
        vault.save()
        return addr
        
    wallet, created = VaultWallet.objects.get_or_create(
        user=user, username=username, name=currency)
    wallet.addresses.add(WalletAddress.objects.create(address=addr))
    return addr
Exemplo n.º 20
0
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": ""}
Exemplo n.º 21
0
def Create_wallet_file():
    # create the clinet object
    devices = Wait_for_devices()
    transport = Choose_device(devices)
    client = TrezorClient(transport)
    
    
    # Label your wallet, something like 'lumen'.
    print('Please provide label for new drive: ')
    label = input()
    
    print('Computer asked TREZOR for new strong password.\n')
    print('Please confirm action on your device.\n')
    trezor_entropy = client.get_entropy(32)
    urandom_entropy = os.urandom(32)
    passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest()
    
    if len(passw) != 32:
        raise Exception("32 bytes password expected")
        
    bip32_path = [10, 0]
    passw_encrypted = client.encrypt_keyvalue(bip32_path, label, passw, False, True)

    wallet_info = {'label': label,
            'bip32_path': bip32_path,
            'password_encrypted_hex': binascii.hexlify(passw_encrypted).decode(),
            'Address':Keypair.from_raw_seed(passw).address().decode()}
    
    #Store the wallet Information
    with open('Stellar_wallet.json', 'w') as fp:
        json.dump(wallet_info, fp)
        
    print('Please disconnect your Trezor hardware wallet.')
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')
Exemplo n.º 23
0
def test_sign(test_builder):
    test_builder.append_create_account_op(Keypair.random().address().decode(),
                                          100)
    assert len(test_builder.ops) == 1
    test_builder.sign()
    assert test_builder.te
    assert test_builder.tx
Exemplo n.º 24
0
def initialize_keypair(add_funds=True):
    kp = Keypair.random()
    if add_funds:
        publickey = kp.address().decode()
        url = 'https://friendbot.stellar.org/?addr=' + publickey
        requests.get(url)
    return kp
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 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']
Exemplo n.º 27
0
    def __init__(self):
        kp = Keypair.random()
        self.fee = 100
        self.address = kp.address().decode('ascii')
        self.seed = kp.seed().decode('ascii') or None

        fund(self.address)
Exemplo n.º 28
0
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')
Exemplo n.º 29
0
def create_and_fund_account():
    keypair = Keypair.random()
    logging.info('Created account: secret=%s, address=%s',
                 keypair.seed().decode(),
                 keypair.address().decode())
    fund_account(keypair)
    return keypair
Exemplo n.º 30
0
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"
Exemplo n.º 31
0
def newAccount(creator=False):
	kp = Keypair.random()
	r = requests.get(url + '/friendbot?addr=' + kp.address().decode('ascii')) # Get 1000 lumens
	assert 'hash' in json.loads(r.text)
	return {
		'address': kp.address().decode('ascii'),
		'seed': kp.seed().decode('ascii')
	}
Exemplo n.º 32
0
    def __init__(self):
        kp = Keypair.random()
        self.fee = 100
        self.address = kp.address().decode('ascii')
        self.seed = kp.seed().decode('ascii') or None

        r = requests.get('https://horizon-testnet.stellar.org/friendbot?addr=' + self.address)
        assert 'hash' in json.loads(r.text), "\n" + urlParam + "\n" + r.text
Exemplo n.º 33
0
 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
Exemplo n.º 34
0
 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'
Exemplo n.º 35
0
    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
Exemplo n.º 36
0
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
Exemplo n.º 37
0
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 * ' '))
Exemplo n.º 38
0
def te_xdr_build(tx, secret):
    envelope = Envelope(tx)
    signer = Keypair.from_seed(secret)
    envelope.sign(signer)
    re = envelope.xdr()
    return re
Exemplo n.º 39
0
    def __init__(self):

        self.cold = Keypair.random()
        self.hot = Keypair.random()