Exemplo n.º 1
0
async def main():
    initialize()

    txs = []
    accounts = []

    minimum_fee = clients[0].get_minimum_fee()

    # Creating new test accounts
    accounts.append(Keypair())
    accounts.append(Keypair())
    accounts.append(Keypair())

    print('Creating new test accounts')
    root_account.create_account(accounts[0].public_address, 100000000,
                                minimum_fee)
    root_account.create_account(accounts[1].public_address, 100000000,
                                minimum_fee)
    assert clients[0].does_account_exists(
        accounts[1].public_address) and clients[0].does_account_exists(
            accounts[0].public_address)
    print('2 Test accounts created - Passed')

    for i in range(tx_count):
        # generating transactions using multiple kin-cores
        builder = Builder('LOCAL',
                          clients[i % len(clients)].horizon,
                          fee=minimum_fee,
                          secret=accounts[i % len(accounts)].secret_seed)
        builder.get_sequence()
        builder.append_manage_data_op('test' + str(i), 'test'.encode())
        builder.sign()
        txs.append(builder)

    # waiting for the txs receipts from different cores
    receipts = await send_txs(txs)

    assert len(receipts) == tx_count
    print('All of the transactions approved by different cores - Passed')

    assert len(set([(rec._result['ledger']) for rec in receipts])) == 1
    print('All of the transactions are in the same ledger - Passed')

    cores_hashes = [(rec._result['hash']) for rec in receipts]
    ledger_no = receipts[0]._result['ledger']

    # waiting for the next ledger
    while ledger_no + 1 > get_latest_ledger(clients[0])['sequence']:
        time.sleep(0.5)

    # getting ledger txs from horizon
    ledger_txs = clients[0].horizon.ledger_transactions(
        ledger_no)['_embedded']['records']

    # comparing ledger hashes with the core hashes
    assert set(cores_hashes) & set([t['hash'] for t in ledger_txs])
    print('Multi cores test - Passed')
Exemplo n.º 2
0
    def onboard_with_phone(self, userid, phone_num):
        resp = self.app.post('/user/register',
                             data=json.dumps({
                                 'user_id': str(userid),
                                 'os': 'android',
                                 'device_model': 'samsung8',
                                 'device_id': '234234',
                                 'time_zone': '05:00',
                                 'token': 'fake_token',
                                 'app_ver': '1.0'
                             }),
                             headers={},
                             content_type='application/json')
        self.assertEqual(resp.status_code, 200)

        # phone authenticate

        resp = self.app.post('/user/firebase/update-id-token',
                             data=json.dumps({
                                 'token': 'fake-token',
                                 'phone_number': phone_num
                             }),
                             headers={USER_ID_HEADER: str(userid)},
                             content_type='application/json')
        self.assertEqual(resp.status_code, 200)

        print('onboarding user --------------')
        from kin import Keypair
        kp = Keypair()
        address = kp.address_from_seed(kp.generate_seed())
        resp = self.app.post('/user/onboard',
                             data=json.dumps({'public_address': address}),
                             headers={USER_ID_HEADER: str(userid)},
                             content_type='application/json')

        print(json.loads(resp.data))
        self.assertEqual(resp.status_code, 200)

        # try onboarding again with the same user - should fail
        print('onboarding same user second time should fail --------------')
        resp = self.app.post('/user/onboard',
                             data=json.dumps({'public_address': address}),
                             headers={USER_ID_HEADER: str(userid)},
                             content_type='application/json')
        print(json.loads(resp.data))
        self.assertEqual(resp.status_code, 400)

        return address
Exemplo n.º 3
0
 def __init__(self, sdk: KinAccount, channel: str):
     self.write_sdk = sdk
     self.write_sdk.raw_seed = BaseKeypair.from_seed(
         sdk.keypair.secret_seed).raw_seed()
     self.root_address = self.write_sdk.keypair.public_address
     self.channel = channel
     self.channel_address = Keypair.address_from_seed(channel)
Exemplo n.º 4
0
def initialize():
    if len(sys.argv) < 4:
        print('invalid number of params :', len(clients))
        sys.exit(1)

    global PASSPHRASE
    global WHITELIST_MANAGER_KEYPAIR
    global root_account
    global tx_count

    PASSPHRASE = sys.argv[1]
    WHITELIST_MANAGER_KEYPAIR = Keypair(sys.argv[2])
    tx_count = int(sys.argv[3])

    for arg in sys.argv[4:]:
        local_env = Environment('LOCAL', arg, PASSPHRASE,
                                'http://localhost:8001')

        # Creates a client
        clients.append(KinClient(local_env))
        print('Client ', len(clients), ' created!')

    # Create the root account object
    root_account = clients[0].kin_account(
        derive_root_account(PASSPHRASE).secret_seed)
    print('Root account object created')
Exemplo n.º 5
0
def generate():
    # generates a file that can be 'sourced' and creates environment vars for
    # payment-service
    keys = Keypair()
    public_address = keys.public_address
    private_seed = keys.secret_seed

    print('# creating %s' % public_address)
    fund_kin(public_address)
    return public_address, private_seed
Exemplo n.º 6
0
def load_accounts(path) -> List[Keypair]:
    """Load seeds from file path and return Keypair list.

    Expected file format is a newline-delimited seed list.
    """
    kps = []
    with open(path) as f:
        for seed in f:
            kps.append(Keypair(seed.strip()))
    return kps
Exemplo n.º 7
0
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 kin import Keypair
    kp = Keypair()
    balance['base_seed']['kin'] = get_kin_balance(
        kp.address_from_seed(base_seed))
    index = 0
    for channel in channel_seeds:
        # seeds only need to carry XLMs
        balance['channel_seeds'][index] = {'kin': 0}
        balance['channel_seeds'][index]['kin'] = get_kin_balance(
            kp.address_from_seed(channel))
        index = index + 1

    return jsonify(status='ok', balance=balance)
Exemplo n.º 8
0
async def main():
    """Create accounts and print their seeds to stdout."""
    args = parse_args()

    # initialize channels
    channel_builders = await init_channel_builders(args.channel_seeds_file, args.passphrase, args.horizon)
    kps = generate_keypairs(args.accounts)
    source_kp = Keypair(args.source_account)

    await create_accounts(source_kp, kps, channel_builders, args.horizon, STARTING_BALANCE)

    if args.json_output:
        keypairs = []
        for kp in kps:
            keypairs.append({"address": kp.public_address, "seed": kp.secret_seed})

        out = {"keypairs": keypairs}
        print(json.dumps(out, indent=True))
    else:
        out = (kp.secret_seed for kp in kps)
        print('\n'.join(list(out)))
Exemplo n.º 9
0
def keypair_list(n):
    return [Keypair() for _ in range(n)]
Exemplo n.º 10
0
async def main():
    # Create the environment
    local_env = Environment('LOCAL', 'http://localhost:8000', PASSPHRASE,
                            'http://localhost:8001')

    # Create a client
    client = KinClient(local_env)
    print('Client created')

    initial_ledger_size = get_latest_ledger(client)['max_tx_set_size']
    try:
        # Set ledger tx size to 1
        requests.get(
            'http://localhost:11626/upgrades?mode=set&maxtxsize=1&upgradetime=2018-10-15T18:34:00Z'
        )

        # Create the root account object
        root_account = client.kin_account(
            derive_root_account(PASSPHRASE).secret_seed)
        print('Root account object created')

        minimum_fee = client.get_minimum_fee()
        # Create an account with 0 base reserve
        test_account = Keypair()
        root_account.create_account(test_account.public_address, 0,
                                    minimum_fee)
        assert client.does_account_exists(test_account.public_address)
        print('Test account created')

        # Add the account to the whitelist
        if not client.does_account_exists(
                WHITELIST_MANAGER_KEYPAIR.public_address):
            root_account.create_account(
                WHITELIST_MANAGER_KEYPAIR.public_address, 10000, 100)
        print('Created whitelisting account')

        builder = Builder('LOCAL',
                          client.horizon,
                          fee=minimum_fee,
                          secret=WHITELIST_MANAGER_KEYPAIR.secret_seed)
        builder.get_sequence()
        builder.append_manage_data_op(test_account.public_address,
                                      test_account._hint)
        builder.sign()
        builder.submit()

        print('Added account to whitelist')

        for _ in range(5):
            txs = []
            first_builder = Builder('LOCAL',
                                    client.horizon,
                                    fee=minimum_fee,
                                    secret=test_account.secret_seed)
            first_builder.append_manage_data_op('test', 'test'.encode())
            first_builder.get_sequence()
            first_builder.sign()
            txs.append(first_builder)

            second_builder = Builder(
                'LOCAL',
                client.horizon,
                fee=minimum_fee,
                secret=WHITELIST_MANAGER_KEYPAIR.secret_seed)
            second_builder.append_payment_op(test_account.public_address, '1')
            second_builder.get_sequence()
            second_builder.sign()
            txs.append(second_builder)

            initial_ledger = get_latest_ledger(client)['sequence']
            print(f'Initial ledger: {initial_ledger}')
            while initial_ledger == get_latest_ledger(client)['sequence']:
                time.sleep(0.5)

            first_populated_ledger = initial_ledger + 2

            print(f'Sending on ledger: {first_populated_ledger}')

            print(f'Sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')
            await send_txs(txs)
            print(f'Done sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')

            first_ledger_txs = client.horizon.ledger_transactions(
                first_populated_ledger)['_embedded']['records']

            # First ledger should have tx from whitelist_manager
            assert WHITELIST_MANAGER_KEYPAIR.public_address == first_ledger_txs[
                0]['source_account']
            print('Verified tx from whitelist manager got priority')
    except:
        raise
    finally:
        # Set tx size to what it was before
        requests.get(
            f'http://localhost:11626/upgrades?mode=set&maxtxsize={initial_ledger_size}&upgradetime=2018-10-15T18:34:00Z'
        )
Exemplo n.º 11
0
"""Test the prioritization of transactions in the ledger for the whitelist_holder"""

import sys
import asyncio
from concurrent.futures import ThreadPoolExecutor

from kin import KinClient, Environment, Keypair
from kin.blockchain.builder import Builder
from helpers import derive_root_account

import requests

import time

PASSPHRASE = sys.argv[1]
WHITELIST_MANAGER_KEYPAIR = Keypair(sys.argv[2])


async def send_txs(txs):
    with ThreadPoolExecutor(max_workers=2) as executor:
        loop = asyncio.get_running_loop()
        promises = [loop.run_in_executor(executor, tx.submit) for tx in txs]

        for _ in await asyncio.gather(*promises):
            pass


def get_latest_ledger(client):
    params = {'order': 'desc', 'limit': 1}
    return client.horizon.ledgers(params=params)['_embedded']['records'][0]
Exemplo n.º 12
0
def main():
    # Create the environment
    local_env = Environment('LOCAL', 'http://localhost:8000', PASSPHRASE,
                            'http://localhost:8001')

    # Create a client
    client = KinClient(local_env)
    print('Client created')

    # Create the root account object
    root_account = client.kin_account(
        derive_root_account(PASSPHRASE).secret_seed)
    print('Root account object created')

    minimum_fee = client.get_minimum_fee()
    # Create an account with 0 base reserve
    test_account = Keypair()
    root_account.create_account(test_account.public_address, 0, minimum_fee)
    assert client.does_account_exists(test_account.public_address)
    print('Test account created')

    # Send a tx that does not require spending kin
    builder = Builder('LOCAL',
                      client.horizon,
                      fee=0,
                      secret=test_account.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op('test', 'test'.encode())
    builder.sign()

    try:
        builder.submit()
    except KinErrors.HorizonError as e:
        # Tx should fail since the fee is under minimum fee
        assert e.extras.result_codes.transaction == KinErrors.TransactionResultCode.INSUFFICIENT_FEE
        print('Sending under minimum fee - Passed')

    builder = Builder('LOCAL',
                      client.horizon,
                      fee=minimum_fee,
                      secret=test_account.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op('test', 'test'.encode())
    builder.sign()

    try:
        builder.submit()
    except KinErrors.HorizonError as e:
        # Tx should fail since the account cant pay the fee
        assert e.extras.result_codes.transaction == KinErrors.TransactionResultCode.INSUFFICIENT_BALANCE
        print('Sending with no fee to pay - Passed')

    # Add the account to the whitelist
    if not client.does_account_exists(
            WHITELIST_MANAGER_KEYPAIR.public_address):
        root_account.create_account(WHITELIST_MANAGER_KEYPAIR.public_address,
                                    10000, 100)
    print('Created whitelisting account')

    builder = Builder('LOCAL',
                      client.horizon,
                      fee=minimum_fee,
                      secret=WHITELIST_MANAGER_KEYPAIR.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op(test_account.public_address,
                                  test_account._hint)
    builder.sign()
    builder.submit()

    print('Added account to whitelist')

    # test_account is now a whitelister, so the fee should be ignored
    builder = Builder('LOCAL',
                      client.horizon,
                      fee=0,
                      secret=test_account.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op('test2', 'test2'.encode())
    builder.sign()
    builder.submit()

    print('Sending prioritized tx under minimum fee - Passed')

    builder = Builder('LOCAL',
                      client.horizon,
                      fee=999999,
                      secret=test_account.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op('test3', 'test3'.encode())
    builder.sign()
    builder.submit()

    print('Sending prioritized tx with fee > balance - Passed')

    # Try the same if the account is not a whitelister, but the tx is whitelisted
    test_account2 = Keypair()
    root_account.create_account(test_account2.public_address, 0, minimum_fee)

    builder = Builder('LOCAL',
                      client.horizon,
                      fee=999999,
                      secret=test_account2.secret_seed)
    builder.get_sequence()
    builder.append_manage_data_op('test', 'test'.encode())
    builder.sign()
    # sign with the whitelister as well to prioritize the tx
    builder.sign(secret=test_account.secret_seed)
    builder.submit()

    print('Sending prioritized tx2 with fee > balance - Passed')
Exemplo n.º 13
0
async def main():
    # Create the environment
    local_env = Environment('LOCAL', 'http://localhost:8000', PASSPHRASE,
                            'http://localhost:8001')

    # Create a client
    client = KinClient(local_env)
    print('Client created')

    initial_ledger_size = get_latest_ledger(client)['max_tx_set_size']
    try:
        # Set ledger tx size to 3
        requests.get(
            'http://localhost:11626/upgrades?mode=set&maxtxsize=3&upgradetime=2018-10-15T18:34:00Z'
        )

        # Create the root account object
        root_account = client.kin_account(
            derive_root_account(PASSPHRASE).secret_seed)
        print('Root account object created')

        minimum_fee = client.get_minimum_fee()
        # Create an account with 0 base reserve
        test_account = Keypair()
        root_account.create_account(test_account.public_address, 0,
                                    minimum_fee)
        assert client.does_account_exists(test_account.public_address)
        print('Test account created')

        accounts = [Keypair() for _ in range(5)]
        builder = Builder('LOCAL',
                          client.horizon,
                          fee=minimum_fee,
                          secret=root_account.keypair.secret_seed)
        for keypair in accounts:
            builder.append_create_account_op(keypair.public_address, '100')

        builder.get_sequence()
        builder.sign()
        builder.submit()

        print('Created 5 accounts')

        txs = []
        for index, account in enumerate(accounts, start=1):
            builder = Builder('LOCAL',
                              client.horizon,
                              fee=minimum_fee * index,
                              secret=account.secret_seed)
            builder.append_manage_data_op('test', 'test'.encode())
            builder.get_sequence()
            builder.sign()
            txs.append(builder)

        initial_ledger = get_latest_ledger(client)['sequence']
        print(f'Initial ledger: {initial_ledger}')
        while initial_ledger == get_latest_ledger(client)['sequence']:
            time.sleep(0.5)

        first_populated_ledger = initial_ledger + 2
        second_populated_ledger = initial_ledger + 3

        print(f'Sending on ledger: {first_populated_ledger}')

        print(f'Sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')
        await send_txs(txs)
        print(f'Done sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')

        first_ledger_txs = client.horizon.ledger_transactions(
            first_populated_ledger)['_embedded']['records']
        second_ledger_txs = client.horizon.ledger_transactions(
            second_populated_ledger)['_embedded']['records']

        # First ledger should have txs where fee>=300
        first_txs = sum(1 for tx in first_ledger_txs if tx['fee_paid'] >= 300)
        assert first_txs == 3

        print('Verified first ledger')

        # Second ledger should have txs where fee<=200
        second_txs = sum(1 for tx in second_ledger_txs
                         if tx['fee_paid'] <= 200)
        assert second_txs == 2

        print('Verified seconds ledger')
    except:
        raise
    finally:
        # Set tx size to what it was before
        requests.get(
            f'http://localhost:11626/upgrades?mode=set&maxtxsize={initial_ledger_size}&upgradetime=2018-10-15T18:34:00Z'
        )
async def main():
    # Create the environment
    local_env = Environment('LOCAL', 'http://localhost:8000', PASSPHRASE,
                            'http://localhost:8001')

    # Create a client
    client = KinClient(local_env)
    print('Client created')

    initial_ledger_size = get_latest_ledger(client)['max_tx_set_size']
    try:
        # Set ledger tx size to 1
        requests.get(
            'http://localhost:11626/upgrades?mode=set&maxtxsize=1&upgradetime=2018-10-15T18:34:00Z'
        )

        # Create the root account object
        root_account = client.kin_account(
            derive_root_account(PASSPHRASE).secret_seed)
        print('Root account object created')

        minimum_fee = client.get_minimum_fee()
        # Create an account with 0 base reserve
        test_account = Keypair()
        root_account.create_account(test_account.public_address, 0,
                                    minimum_fee)
        assert client.does_account_exists(test_account.public_address)
        print('Test account created')

        # Add the account to the whitelist
        if not client.does_account_exists(
                WHITELIST_MANAGER_KEYPAIR.public_address):
            root_account.create_account(
                WHITELIST_MANAGER_KEYPAIR.public_address, 10000, 100)
        print('Created whitelisting account')

        initial_ledger = get_latest_ledger(client)['sequence']

        print(f'Adding account to whitelist on ledger: {initial_ledger + 2}')

        builder = Builder('LOCAL',
                          client.horizon,
                          fee=minimum_fee,
                          secret=WHITELIST_MANAGER_KEYPAIR.secret_seed)
        builder.get_sequence()
        builder.append_manage_data_op(test_account.public_address,
                                      test_account._hint)
        builder.sign()
        builder.submit()

        print('Added account to whitelist')

        while initial_ledger + 1 == get_latest_ledger(client)['sequence']:
            time.sleep(0.5)

        print(
            f'Submitting tx from test account on ledger: {initial_ledger + 3}')

        builder = Builder('LOCAL',
                          client.horizon,
                          fee=0,
                          secret=test_account.secret_seed)
        builder.append_manage_data_op('test', 'test'.encode())
        builder.get_sequence()
        builder.sign()
        builder.submit()

        while initial_ledger + 2 == get_latest_ledger(client)['sequence']:
            time.sleep(0.5)

        populated_ledger_txs = client.horizon.ledger_transactions(
            initial_ledger + 3)['_embedded']['records']
        assert len(populated_ledger_txs) == 1
        assert populated_ledger_txs[0]['fee_paid'] == 0

    except:
        raise
    finally:
        # Set tx size to what it was before
        requests.get(
            f'http://localhost:11626/upgrades?mode=set&maxtxsize={initial_ledger_size}&upgradetime=2018-10-15T18:34:00Z'
        )
Exemplo n.º 15
0
def derive_root_account(passphrase):
    """Return the keypair of the root account, based on the network passphrase."""
    network_hash = sha256(passphrase.encode()).digest()
    seed = BaseKeypair.from_raw_seed(network_hash).seed().decode()
    return Keypair(seed)
Exemplo n.º 16
0
def keypair_list(n) -> List[Keypair]:
    """Return Keypair list according to given amount."""
    return [Keypair() for _ in range(n)]
async def main():
    # Create the environment
    local_env = Environment('LOCAL', 'http://localhost:8000', PASSPHRASE,
                            'http://localhost:8001')

    # Create a client
    client = KinClient(local_env)
    print('Client created')

    initial_ledger_size = get_latest_ledger(client)['max_tx_set_size']
    try:
        # Set ledger tx size to 3
        requests.get(
            'http://localhost:11626/upgrades?mode=set&maxtxsize=3&upgradetime=2018-10-15T18:34:00Z'
        )

        # Create the root account object
        root_account = client.kin_account(
            derive_root_account(PASSPHRASE).secret_seed)
        print('Root account object created')

        minimum_fee = client.get_minimum_fee()
        # Create an account with 0 base reserve
        test_account = Keypair()
        root_account.create_account(test_account.public_address, 0,
                                    minimum_fee)
        assert client.does_account_exists(test_account.public_address)
        print('Test account created')

        # Add the account to the whitelist
        if not client.does_account_exists(
                WHITELIST_MANAGER_KEYPAIR.public_address):
            root_account.create_account(
                WHITELIST_MANAGER_KEYPAIR.public_address, 10000, 100)
        print('Created whitelisting account')

        builder = Builder('LOCAL',
                          client.horizon,
                          fee=minimum_fee,
                          secret=WHITELIST_MANAGER_KEYPAIR.secret_seed)
        builder.get_sequence()
        builder.append_manage_data_op(test_account.public_address,
                                      test_account._hint)
        builder.sign()
        builder.submit()

        print('Added account to whitelist')

        accounts = [Keypair() for _ in range(5)]
        builder = Builder('LOCAL',
                          client.horizon,
                          fee=minimum_fee,
                          secret=root_account.keypair.secret_seed)
        for keypair in accounts:
            builder.append_create_account_op(keypair.public_address, '100')

        builder.get_sequence()
        builder.sign()
        builder.submit()

        print('Created 5 accounts')

        txs = []
        for account in accounts:
            builder = Builder('LOCAL',
                              client.horizon,
                              fee=minimum_fee,
                              secret=account.secret_seed)
            builder.append_manage_data_op('test', 'test'.encode())
            builder.get_sequence()
            builder.sign()
            txs.append(builder)

        for tx in txs[2:]:
            tx.sign(test_account.secret_seed)

        print('Whitelisted 3 transactions')

        initial_ledger = get_latest_ledger(client)['sequence']
        print(f'Initial ledger: {initial_ledger}')
        while initial_ledger == get_latest_ledger(client)['sequence']:
            time.sleep(0.5)

        first_populated_ledger = initial_ledger + 2
        second_populated_ledger = initial_ledger + 3

        print(f'Sending on ledger: {first_populated_ledger}')

        print(f'Sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')
        await send_txs(txs)
        print(f'Done sending txs at {time.strftime("%d/%m/%Y %H:%M:%S")}')

        first_ledger_txs = client.horizon.ledger_transactions(
            first_populated_ledger)['_embedded']['records']
        second_ledger_txs = client.horizon.ledger_transactions(
            second_populated_ledger)['_embedded']['records']

        # First ledger should have 2 whitelisted txs, and 1 non-whitelisted
        whitelisted_amount = sum(1 for tx in first_ledger_txs
                                 if len(tx['signatures']) == 2)
        assert whitelisted_amount == 2

        regular_amount = sum(1 for tx in first_ledger_txs
                             if len(tx['signatures']) == 1)
        assert regular_amount == 1

        # # Second ledger should have 1 whitelisted tx, and 1 non-whitelisted
        whitelisted_amount = sum(1 for tx in second_ledger_txs
                                 if len(tx['signatures']) == 2)
        assert whitelisted_amount == 1

        regular_amount = sum(1 for tx in second_ledger_txs
                             if len(tx['signatures']) == 1)
        assert regular_amount == 1

    except:
        raise
    finally:
        # Set tx size to what it was before
        requests.get(
            f'http://localhost:11626/upgrades?mode=set&maxtxsize={initial_ledger_size}&upgradetime=2018-10-15T18:34:00Z'
        )