Esempio n. 1
0
def create_escrow_account(activationaccountsecret, owneraddress, cosignersfile,
                          fullassetcode):
    splitassetcode = fullassetcode.split(":")
    asset_code = splitassetcode[0]
    asset_issuer = splitassetcode[1]
    activation_kp = Keypair.from_secret(activationaccountsecret)

    horizon_server = stellar_sdk.Server()
    activation_account = horizon_server.load_account(activation_kp.public_key)

    new_escrow_account = create_account()
    escrow_address = new_escrow_account["address"]
    vesting_kp = Keypair.from_secret(new_escrow_account["secret"])
    txb = (TransactionBuilder(
        activation_account,
        network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE
    ).append_create_account_op(escrow_address,
                               starting_balance="7.6").append_change_trust_op(
                                   asset_code,
                                   asset_issuer,
                                   source=escrow_address))
    tx = txb.build()
    tx.sign(activation_kp)
    tx.sign(vesting_kp)
    horizon_server.submit_transaction(tx)
    vesting_account = horizon_server.load_account(escrow_address)
    txb = (TransactionBuilder(
        vesting_account,
        network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE).
           append_ed25519_public_key_signer(owneraddress,
                                            weight=5,
                                            source=escrow_address))
    cosigners = json.load(cosignersfile)
    for cosigner in cosigners:
        txb.append_ed25519_public_key_signer(cosigner["address"],
                                             weight=1,
                                             source=escrow_address)
    txb.append_manage_data_op(DATA_ENTRY_KEY,
                              "here comes the formula or reference",
                              source=escrow_address)

    recovery_transaction = create_recovery_transaction(
        escrow_address, asset_code, asset_issuer, activation_kp.public_key)
    txb.append_pre_auth_tx_signer(recovery_transaction.hash(),
                                  weight=10,
                                  source=escrow_address)

    txb.append_set_options_op(master_weight=0,
                              low_threshold=10,
                              med_threshold=10,
                              high_threshold=10,
                              source=escrow_address)

    tx = txb.build()
    tx.sign(vesting_kp)
    horizon_server.submit_transaction(tx)
    print(f"Created escrow account {escrow_address}")
    print(f"Recovery transaction:\n{recovery_transaction.to_xdr()}")
Esempio n. 2
0
 def test_to_txrep_return_memo(self):
     keypair = Keypair.from_secret(
         "SAHGKA7QJB6SRFDZSPZDEEIOEHUHTQS4XVN4IMR5YCKBPEN5A6YNKKUO")
     account = Account(keypair.public_key, 46489056724385792)
     transaction_builder = TransactionBuilder(
         source_account=account,
         network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
         base_fee=100,
     )
     transaction_builder.add_return_hash_memo(
         "ef14f82df770697f56789b4db4e59d1ece902484739ba167cf99fae319ebcc34")
     transaction_builder.add_time_bounds(1535756672, 1567292672)
     transaction_builder.append_payment_op(
         destination=
         "GBAF6NXN3DHSF357QBZLTBNWUTABKUODJXJYYE32ZDKA2QBM2H33IK6O",
         asset_code="USD",
         asset_issuer=
         "GAZFEVBSEGJJ63WPVVIWXLZLWN2JYZECECGT6GUNP4FJDVZVNXWQWMYI",
         amount="40.0004",
         source=keypair.public_key,
     )
     te = transaction_builder.build()
     te.sign(keypair)
     txrep = to_txrep(te)
     assert txrep == get_txrep_file("test_to_txrep_return_memo.txt")
     assert (from_txrep(
         txrep, Network.TESTNET_NETWORK_PASSPHRASE).to_xdr() == te.to_xdr())
    def test_verify_challenge_tx_contain_subsequent_manage_data_ops_without_the_server_account_as_the_source_account(
        self, ):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        home_domain = "example.com"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(
            server_account, network_passphrase, 100).append_manage_data_op(
                data_name="{} auth".format(home_domain),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            ).append_manage_data_op(
                data_name="data key",
                data_value="data value",
                source=client_kp.public_key,
            ).add_time_bounds(now, now + 900).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match="The transaction has operations that are unrecognized.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                home_domain,
                network_passphrase,
            )
    def test_verify_challenge_tx_operation_value_is_none(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        home_domain = "example.com"
        now = int(time.time())
        nonce_encoded = None
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(
            server_account, network_passphrase, 100).append_manage_data_op(
                data_name="{} auth".format(home_domain),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            ).add_time_bounds(now, now + 900).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match="Operation value should not be null.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                home_domain,
                network_passphrase,
            )
Esempio n. 5
0
 def test_to_txrep_fullline_comment(self):
     keypair = Keypair.from_secret(
         "SAHGKA7QJB6SRFDZSPZDEEIOEHUHTQS4XVN4IMR5YCKBPEN5A6YNKKUO")
     account = Account(keypair.public_key, 46489056724385792)
     transaction_builder = TransactionBuilder(
         source_account=account,
         network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
         base_fee=100,
     )
     transaction_builder.add_text_memo("Enjoy this transaction")
     transaction_builder.add_time_bounds(1535756672, 1567292672)
     transaction_builder.append_payment_op(
         destination=
         "GBAF6NXN3DHSF357QBZLTBNWUTABKUODJXJYYE32ZDKA2QBM2H33IK6O",
         asset_code="USD",
         asset_issuer=
         "GAZFEVBSEGJJ63WPVVIWXLZLWN2JYZECECGT6GUNP4FJDVZVNXWQWMYI",
         amount="40.0004",
         source=keypair.public_key,
     )
     te = transaction_builder.build()
     te.sign(keypair)
     txrep = to_txrep(te)
     file_txrep = get_txrep_file("test_to_txrep_fullline_comment.txt")
     assert txrep == to_txrep(
         from_txrep(file_txrep, Network.TESTNET_NETWORK_PASSPHRASE))
Esempio n. 6
0
    def test_verify_challenge_tx_contains_infinite_timebounds(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        domain_name = "example.com"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_manage_data_op(
                data_name="{} auth".format(domain_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            )
            .add_time_bounds(now, 0)
            .build()
        )

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
            InvalidSep10ChallengeError,
            match="Transaction requires non-infinite timebounds.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                domain_name,
                network_passphrase,
            )
def send_asset_to_account(destination, asset, amount, from_secret,
                          funder_secret):
    split_asset = asset.split(':', 1)
    asset_code = split_asset[0]
    asset_issuer = split_asset[1]
    #Create keypairs from the secrets
    from_kp = stellar_sdk.Keypair.from_secret(from_secret)
    funder_kp = stellar_sdk.Keypair.from_secret(funder_secret)

    #load the funder account
    horizon_server = stellar_sdk.Server()
    funder_account = horizon_server.load_account(funder_kp.public_key)

    # Create the transaction
    transaction = TransactionBuilder(funder_account).append_payment_op(
        destination,
        amount,
        asset_code,
        asset_issuer,
        source=from_kp.public_key).build()
    transaction.sign(from_kp)
    transaction.sign(funder_kp)
    response = horizon_server.submit_transaction(transaction)
    print(response)
    print(
        'Sent {amount} {asset} from {from_address} to {destination} funded by {funder_address}'
        .format(amount=amount,
                asset=asset,
                from_address=from_kp.public_key,
                destination=destination,
                funder_address=funder_kp.public_key))
    def test_verify_challenge_tx_not_within_range_of_the_specified_timebounds(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_manage_data_op(
                data_name="{} auth".format(anchor_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            )
            .add_time_bounds(now - 100, now - 50)
            .build()
        )

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
            InvalidSep10ChallengeError,
            match="Transaction is not within range of the specified timebounds.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed, server_kp.public_key, network_passphrase
            )
    def test_verify_challenge_tx_transaction_is_not_signed_by_the_server(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        timeout = 900

        now = int(time.time())
        server_keypair = Keypair.from_secret(server_kp.secret)
        server_account = Account(account_id=server_keypair.public_key, sequence=-1)
        transaction_builder = TransactionBuilder(
            server_account, network_passphrase, 100
        )
        transaction_builder.add_time_bounds(min_time=now, max_time=now + timeout)
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        transaction_builder.append_manage_data_op(
            data_name="{} auth".format(anchor_name),
            data_value=nonce_encoded,
            source=client_kp.public_key,
        )
        challenge = transaction_builder.build().to_xdr()

        transaction = TransactionEnvelope.from_xdr(challenge, network_passphrase)
        transaction.sign(client_kp)
        challenge_tx = transaction.to_xdr()
        with pytest.raises(
            InvalidSep10ChallengeError,
            match="Transaction not signed by server: {}".format(server_kp.public_key),
        ):
            verify_challenge_transaction(
                challenge_tx, server_kp.public_key, network_passphrase
            )
    def test_verify_challenge_tx_dont_contains_timebound(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_manage_data_op(
                data_name="{} auth".format(anchor_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            )
            .build()
        )

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
            InvalidSep10ChallengeError, match="Transaction requires timebounds."
        ):
            verify_challenge_transaction(
                challenge_tx_signed, server_kp.public_key, network_passphrase
            )
    def test_verify_transaction_signatures_raise_no_signature(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_manage_data_op(
                data_name="{} auth".format(anchor_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            )
            .add_time_bounds(now, now + 900)
            .build()
        )

        signers = []
        with pytest.raises(
            InvalidSep10ChallengeError, match="Transaction has no signatures."
        ):
            _verify_transaction_signatures(challenge_te, signers)
    def get_or_create_destination_account(
        transaction: Transaction, ) -> Tuple[Account, bool]:
        """
        Returns:
            Account: The account found or created for the Transaction
            bool: True if trustline doesn't exist, False otherwise.

        If the account doesn't exist, Polaris must create the account using an account provided by the
        anchor. Polaris can use the distribution account of the anchored asset or a channel account if
        the asset's distribution account requires non-master signatures.

        If the transacted asset's distribution account does require non-master signatures,
        DepositIntegration.create_channel_account() will be called. See the function docstring for more
        info.

        On failure to create the destination account, a RuntimeError exception is raised.
        """
        try:
            account, json_resp = get_account_obj(
                Keypair.from_public_key(transaction.stellar_account))
            return account, is_pending_trust(transaction, json_resp)
        except RuntimeError:
            if MultiSigTransactions().requires_multisig(transaction):
                source_account_kp = MultiSigTransactions.get_channel_keypair(
                    transaction)
                source_account, _ = get_account_obj(source_account_kp)
            else:
                source_account_kp = Keypair.from_secret(
                    transaction.asset.distribution_seed)
                source_account, _ = get_account_obj(source_account_kp)

            builder = TransactionBuilder(
                source_account=source_account,
                network_passphrase=settings.STELLAR_NETWORK_PASSPHRASE,
                # this transaction contains one operation so base_fee will be multiplied by 1
                base_fee=settings.MAX_TRANSACTION_FEE_STROOPS
                or settings.HORIZON_SERVER.fetch_base_fee(),
            )
            transaction_envelope = builder.append_create_account_op(
                destination=transaction.stellar_account,
                starting_balance=settings.ACCOUNT_STARTING_BALANCE,
            ).build()
            transaction_envelope.sign(source_account_kp)

            try:
                settings.HORIZON_SERVER.submit_transaction(
                    transaction_envelope)
            except BaseHorizonError as e:  # pragma: no cover
                raise RuntimeError(
                    "Horizon error when submitting create account "
                    f"to horizon: {e.message}")

            account, _ = get_account_obj(
                Keypair.from_public_key(transaction.stellar_account))
            return account, True
        except BaseHorizonError as e:
            raise RuntimeError(
                f"Horizon error when loading stellar account: {e.message}")
        except ConnectionError:
            raise RuntimeError("Failed to connect to Horizon")
Esempio n. 13
0
    def test_verify_challenge_tx_donot_contain_managedata_operation(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        domain_name = "example.com"
        now = int(time.time())
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_set_options_op()
            .add_time_bounds(now, now + 900)
            .build()
        )

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
            InvalidSep10ChallengeError, match="Operation type should be ManageData."
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                domain_name,
                network_passphrase,
            )
 def test_read_challenge_transaction_fee_bump_transaction_raise(self):
     inner_keypair = Keypair.from_secret(
         "SBKTIFHJSS3JJWEZO2W74DZSA45WZU56LOL3AY7GAW63BXPEJQFYV53E"
     )
     inner_source = Account(inner_keypair.public_key, 7)
     destination = "GDQERENWDDSQZS7R7WKHZI3BSOYMV3FSWR7TFUYFTKQ447PIX6NREOJM"
     amount = "2000.0000000"
     inner_tx = (
         TransactionBuilder(
             inner_source, Network.TESTNET_NETWORK_PASSPHRASE, 200, v1=True
         )
         .append_payment_op(destination=destination, amount=amount, asset_code="XLM")
         .add_time_bounds(0, 0)
         .build()
     )
     inner_tx.sign(inner_keypair)
     fee_source = Keypair.from_secret(
         "SB7ZMPZB3YMMK5CUWENXVLZWBK4KYX4YU5JBXQNZSK2DP2Q7V3LVTO5V"
     )
     base_fee = 200
     fee_bump_tx = TransactionBuilder.build_fee_bump_transaction(
         fee_source.public_key,
         base_fee,
         inner_tx,
         Network.TESTNET_NETWORK_PASSPHRASE,
     )
     fee_bump_tx.sign(fee_source)
     challenge = fee_bump_tx.to_xdr()
     with pytest.raises(
         ValueError,
         match="Invalid challenge, expected a TransactionEnvelope but received a FeeBumpTransactionEnvelope.",
     ):
         read_challenge_transaction(
             challenge, inner_keypair.public_key, Network.TESTNET_NETWORK_PASSPHRASE
         )
Esempio n. 15
0
def create_assets_for_distributing(amount):

    # Keys for accounts to issue and receive the new asset
    issuing_keypair = Keypair.from_secret(os.getenv("ISSUING_PRIVATE"))
    issuing_public = issuing_keypair.public_key
    issuing_account = server.load_account(issuing_public)

    distributor_keypair = Keypair.from_secret(os.getenv("DISTRIBUTOR_INRX_PRIVATE_KEY"))
    distributor_public = distributor_keypair.public_key
    distributor_account = server.load_account(distributor_public)

    inr_asset = Asset("INRx", issuing_public)

    payment_transaction = (
        TransactionBuilder(
            source_account=issuing_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=server.fetch_base_fee(),
        )
        .append_change_trust_op(inr_asset.code, inr_asset.issuer, None, distributor_public)
        .append_payment_op(
            destination=distributor_public,
            amount=amount,
            asset_code=inr_asset.code,
            asset_issuer=inr_asset.issuer,
        )
        .build()
    )
    payment_transaction.sign(issuing_keypair)
    payment_transaction.sign(distributor_keypair)
    resp = server.submit_transaction(payment_transaction)
    pprint(resp)

    account_details = server.accounts().account_id(distributor_public).call()
    print("\n\ndistributor new balance: ", account_details["balances"][0]["balance"], inr_asset.code)
    def test_verify_challenge_tx_sequence_not_zero(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, 10086)
        challenge_te = (
            TransactionBuilder(server_account, network_passphrase, 100)
            .append_manage_data_op(
                data_name="{} auth".format(anchor_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            )
            .add_time_bounds(now, now + 900)
            .build()
        )

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
            InvalidSep10ChallengeError,
            match="The transaction sequence number should be zero.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed, server_kp.public_key, network_passphrase
            )
    def test_verify_challenge_tx_contain_zero_op(self, ):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        domain_name = "example.com"
        now = int(time.time())
        nonce = os.urandom(48)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(server_account, network_passphrase,
                                           100).add_time_bounds(
                                               now, now + 900).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match="Transaction should contain at least one operation.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                domain_name,
                network_passphrase,
            )
    def test_verify_challenge_tx_contain_subsequent_ops_that_secend_op_no_source_account(
        self, ):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        domain_name = "example.com"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(
            server_account, network_passphrase, 100).append_manage_data_op(
                data_name="{} auth".format(domain_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            ).append_manage_data_op(data_name="Hello",
                                    data_value="world").add_time_bounds(
                                        now, now + 900).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match="Operation should have a source account.",
        ):
            verify_challenge_transaction(
                challenge_tx_signed,
                server_kp.public_key,
                domain_name,
                network_passphrase,
            )
    def test_verify_challenge_tx_contain_subsequent_manage_data_ops_with_server_account_as_source_account(
        self, ):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        domain_name = "example.com"
        now = int(time.time())
        nonce = os.urandom(48)
        nonce_encoded = base64.b64encode(nonce)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(
            server_account, network_passphrase, 100).append_manage_data_op(
                data_name="{} auth".format(domain_name),
                data_value=nonce_encoded,
                source=client_kp.public_key,
            ).append_manage_data_op(
                data_name="data key",
                data_value="data value",
                source=server_kp.public_key,
            ).add_time_bounds(now, now + 900).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        verify_challenge_transaction(
            challenge_tx_signed,
            server_kp.public_key,
            domain_name,
            network_passphrase,
        )
    def test_verify_challenge_tx_operation_value_is_not_a_64_bytes_base64_string(
            self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        anchor_name = "SDF"
        now = int(time.time())
        nonce = os.urandom(32)
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(
            server_account, network_passphrase, 100).append_manage_data_op(
                data_name="{} auth".format(anchor_name),
                data_value=nonce,
                source=client_kp.public_key,
            ).add_time_bounds(now, now + 300).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match=
                "Operation value should be a 64 bytes base64 random string.",
        ):
            verify_challenge_transaction(challenge_tx_signed,
                                         server_kp.public_key,
                                         network_passphrase)
Esempio n. 21
0
def create_preauth_transaction(escrow_kp):
    unlock_time = int(time.time()) + 60 * 10  # 10 minutes from now
    horizon_server = stellar_sdk.Server()
    escrow_account = horizon_server.load_account(escrow_kp.public_key)
    escrow_account.increment_sequence_number()
    tx = (TransactionBuilder(escrow_account).append_set_options_op(
        master_weight=0, low_threshold=1, med_threshold=1,
        high_threshold=1).add_time_bounds(unlock_time, 0).build())
    tx.sign(escrow_kp)
    return tx
def rewardUser(uid, amount):
    """
    Reward the user by increasing his karma points via blockchain
    """
    server = Server("https://horizon-testnet.stellar.org")
    source_key = Keypair.from_secret(
        "SA6HHDJ5KZKYFZVOOGHENIPVKV2HGKICN4RYQ2UZNZHZP7ZIYSQIQDCI")
    destination_id = "GA4QPSGBHK7RAJZBBEDCIKFPSYLG3O2UTBT2I56RN4B5KIQF2GFZKSMF"

    # First, check to make sure that the destination account exists.
    # You could skip this, but if the account does not exist, you will be charged
    # the transaction fee when the transaction fails.
    try:
        server.load_account(destination_id)
    except NotFoundError:
        # If the account is not found, surface an error message for logging.
        raise Exception("The destination account does not exist!")

    # If there was no error, load up-to-date information on your account.
    source_account = server.load_account(source_key.public_key)

    # Let's fetch base_fee from network
    base_fee = server.fetch_base_fee()

    # Start building the transaction.
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=base_fee,
        )
        # Because Stellar allows transaction in many currencies, you must specify the asset type.
        # Here we are sending Lumens.
        .append_payment_op(destination=destination_id,
                           amount="10",
                           asset_code="XLM")
        # A memo allows you to add your own metadata to a transaction. It's
        # optional and does not affect how Stellar treats the transaction.
        .add_text_memo("Test Transaction")
        # Wait a maximum of three minutes for the transaction
        .set_timeout(10).build())

    # Sign the transaction to prove you are actually the person sending it.
    transaction.sign(source_key)

    try:
        # And finally, send it off to Stellar!
        response = server.submit_transaction(transaction)
        print(f"Response: {response}")
    except (BadRequestError, BadResponseError) as err:
        print(f"Something went wrong!\n{err}")

    return None
Esempio n. 23
0
def add_trustline(secret_key, asset_code, asset_issuer):
    kp = stellar_sdk.Keypair.from_secret(secret_key)
    horizon_server = stellar_sdk.Server()
    account = horizon_server.load_account(kp.public_key)
    transaction = TransactionBuilder(account).append_change_trust_op(asset_code, asset_issuer).build()
    transaction.sign(kp)
    response = horizon_server.submit_transaction(transaction)
    print(response)
    print(
        "Added trustline to {asset_code}:{asset_issuer} for account {address}".format(
            asset_code=asset_code, asset_issuer=asset_issuer, address=kp.public_key
        )
    )
Esempio n. 24
0
def transfer(accountsecret, fullassetcode, destination, amount):

    split_asset = fullassetcode.split(":", 1)
    asset_code = split_asset[0]
    asset_issuer = split_asset[1]
    # Create keypair from the secret
    kp = stellar_sdk.Keypair.from_secret(accountsecret)

    horizon_server = stellar_sdk.Server()
    account = horizon_server.load_account(kp.public_key)
    txbuilder = TransactionBuilder(account)
    txbuilder.append_payment_op(destination, amount, asset_code, asset_issuer)
    txe = txbuilder.build()
    txe.sign(kp)
    horizon_server.submit_transaction(txe)
Esempio n. 25
0
def send_asset_to_account(destination, asset, amount, source, signer):
    split_asset = asset.split(':', 1)
    asset_code = split_asset[0]
    asset_issuer = split_asset[1]
    horizon_server = stellar_sdk.Server()
    source_account = horizon_server.load_account(source)
    transaction = TransactionBuilder(source_account).append_payment_op(
        destination, amount, asset_code, asset_issuer).build()
    for sk in signer:
        kp = stellar_sdk.Keypair.from_secret(sk)
        transaction.sign(kp)
    response = horizon_server.submit_transaction(transaction)
    print(response)
    print('Sent {amount} {asset} to {destination}'.format(
        amount=amount, asset=asset, destination=destination))
def add_trustline(
    accountsecret: str,
    fullassetcode:
    str = "TFT:GA47YZA3PKFUZMPLQ3B5F2E3CJIB57TGGU7SPCQT2WAEYKN766PWIMB3"):
    splitassetcode = fullassetcode.split(":")
    # Create keypair from the secret
    kp = stellar_sdk.Keypair.from_secret(accountsecret)

    horizon_server = stellar_sdk.Server()
    account = horizon_server.load_account(kp.public_key)
    txbuilder = TransactionBuilder(account)
    txbuilder.append_change_trust_op(splitassetcode[0], splitassetcode[1])
    txe = txbuilder.build()
    txe.sign(kp)
    horizon_server.submit_transaction(txe)
Esempio n. 27
0
def create_recovery_transaction(
        vesting_address, asset_code: str, asset_issuer: str,
        activation_account: str) -> stellar_sdk.TransactionEnvelope:

    horizon_server = stellar_sdk.Server()
    source_account = horizon_server.load_account(vesting_address)
    source_account.sequence += 1
    txe = (TransactionBuilder(
        source_account,
        network_passphrase=stellar_sdk.Network.TESTNET_NETWORK_PASSPHRASE).
           append_change_trust_op(
               asset_code=asset_code,
               asset_issuer=asset_issuer, limit="0").append_manage_data_op(
                   DATA_ENTRY_KEY,
                   None).append_account_merge_op(activation_account).build())
    return txe
Esempio n. 28
0
def set_account_signers(address, public_key_signer, preauth_tx_hash,
                        signer_kp):
    horizon_server = stellar_sdk.Server()
    account = horizon_server.load_account(address)
    tx = (TransactionBuilder(account).append_pre_auth_tx_signer(
        preauth_tx_hash, 1).append_ed25519_public_key_signer(
            public_key_signer,
            1).append_set_options_op(master_weight=1,
                                     low_threshold=2,
                                     med_threshold=2,
                                     high_threshold=2).build())

    tx.sign(signer_kp)
    response = horizon_server.submit_transaction(tx)
    print(response)
    print(
        "Set the signers of {address} to {pk_signer} and {preauth_hash_signer}"
        .format(address=address,
                pk_signer=public_key_signer,
                preauth_hash_signer=preauth_tx_hash))
 def create_deposit_envelope(transaction,
                             source_account) -> TransactionEnvelope:
     payment_amount = round(
         Decimal(transaction.amount_in) - Decimal(transaction.amount_fee),
         transaction.asset.significant_decimals,
     )
     builder = TransactionBuilder(
         source_account=source_account,
         network_passphrase=settings.STELLAR_NETWORK_PASSPHRASE,
         # only one operation, so base_fee will be multipled by 1
         base_fee=settings.MAX_TRANSACTION_FEE_STROOPS
         or settings.HORIZON_SERVER.fetch_base_fee(),
     )
     _, json_resp = get_account_obj(
         Keypair.from_public_key(transaction.stellar_account))
     if transaction.claimable_balance_supported and is_pending_trust(
             transaction, json_resp):
         logger.debug(
             f"Crafting claimable balance operation for Transaction {transaction.id}"
         )
         claimant = Claimant(destination=transaction.stellar_account)
         asset = Asset(code=transaction.asset.code,
                       issuer=transaction.asset.issuer)
         builder.append_create_claimable_balance_op(
             claimants=[claimant],
             asset=asset,
             amount=str(payment_amount),
             source=transaction.asset.distribution_account,
         )
     else:
         builder.append_payment_op(
             destination=transaction.stellar_account,
             asset_code=transaction.asset.code,
             asset_issuer=transaction.asset.issuer,
             amount=str(payment_amount),
             source=transaction.asset.distribution_account,
         )
     if transaction.memo:
         builder.add_memo(make_memo(transaction.memo,
                                    transaction.memo_type))
     return builder.build()
    def test_verify_challenge_tx_donot_contain_any_operation(self):
        server_kp = Keypair.random()
        client_kp = Keypair.random()
        network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        now = int(time.time())
        server_account = Account(server_kp.public_key, -1)
        challenge_te = (TransactionBuilder(server_account, network_passphrase,
                                           100).add_time_bounds(
                                               now, now + 300).build())

        challenge_te.sign(server_kp)
        challenge_te.sign(client_kp)
        challenge_tx_signed = challenge_te.to_xdr()

        with pytest.raises(
                InvalidSep10ChallengeError,
                match="Transaction requires a single ManageData operation.",
        ):
            verify_challenge_transaction(challenge_tx_signed,
                                         server_kp.public_key,
                                         network_passphrase)