Exemple #1
0
    def test_orm_foreign_variable_sets_in_contract_doesnt_work(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_variable_contract.s.py'))
        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_foreign_key_contract.s.py'))

        e.execute('stu',
                  'test_orm_variable_contract',
                  'set_v',
                  kwargs={'i': 1000})

        # this should fail
        status = e.execute('stu',
                           'test_orm_foreign_key_contract',
                           'set_fv',
                           kwargs={'i': 999})

        self.assertEqual(status['status_code'], 1)

        i = e.execute('stu', 'test_orm_variable_contract', 'get_v', kwargs={})
        self.assertEqual(i['result'], 1000)
Exemple #2
0
    def test_orm_hash_gets_and_sets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_hash_contract.s.py'))

        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'key1',
                      'v': 1234
                  })
        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'another_key',
                      'v': 9999
                  })

        key1 = e.execute('stu',
                         'test_orm_hash_contract',
                         'get_h',
                         kwargs={'k': 'key1'})
        another_key = e.execute('stu',
                                'test_orm_hash_contract',
                                'get_h',
                                kwargs={'k': 'another_key'})

        self.assertEqual(key1['result'], 1234)
        self.assertEqual(another_key['result'], 9999)
Exemple #3
0
    def test_orm_contract_not_accessible(self):
        e = Executor(metering=False)

        output = e.execute(
            **TEST_SUBMISSION_KWARGS,
            kwargs=submission_kwargs_for_file(
                './test_contracts/test_orm_no_contract_access.s.py'))

        self.assertIsInstance(output['result'], Exception)
Exemple #4
0
    def test_orm_hash_gets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_hash_contract.s.py'))

        res = e.execute('stu',
                        'test_orm_hash_contract',
                        'get_h',
                        kwargs={'k': 'test'})

        self.assertEqual(res['result'], None)
Exemple #5
0
    def test_construct_function_sets_properly(self):
        e = Executor(metering=False)

        r = e.execute(
            **TEST_SUBMISSION_KWARGS,
            kwargs=submission_kwargs_for_file(
                './test_contracts/test_construct_function_works.s.py'))

        output = e.execute('stu',
                           'test_construct_function_works',
                           'get',
                           kwargs={})

        self.assertEqual(output['result'], 42)
Exemple #6
0
    def test_orm_hash_sets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_hash_contract.s.py'),
                  auto_commit=True)

        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'key1',
                      'v': 1234
                  },
                  auto_commit=True)
        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'another_key',
                      'v': 9999
                  },
                  auto_commit=True)

        key1 = self.d.get('test_orm_hash_contract.h:key1')
        another_key = self.d.get('test_orm_hash_contract.h:another_key')

        self.assertEqual(key1, 1234)
        self.assertEqual(another_key, 9999)
Exemple #7
0
    def __init__(self, parallelism=4, *args, **kwargs):

        super().__init__(*args, **kwargs)

        # Number of core / processes we push to
        self.parallelism = parallelism
        self.executor = Executor(driver=self.driver)

        self.work_inbox = WorkInbox(socket_id=self.network_parameters.resolve(
            self.socket_base, ServiceType.INCOMING_WORK, bind=True),
                                    driver=self.driver,
                                    ctx=self.ctx,
                                    client=self.client,
                                    wallet=self.wallet)

        self.pending_sbcs = set()

        self.log = get_logger(f'DEL {self.wallet.vk_pretty[4:12]}')

        self.masternode_socket_book = Peers(
            wallet=self.wallet,
            ctx=self.ctx,
            parameters=self.parameters,
            service_type=ServiceType.BLOCK_AGGREGATOR,
            node_type=MN)

        self.masternode_contract = self.client.get_contract('masternodes')
Exemple #8
0
    def __init__(self,
                 signer='sys',
                 submission_filename=os.path.join(os.path.dirname(__file__),
                                                  'contracts/submission.s.py'),
                 driver=ContractDriver(),
                 metering=False,
                 compiler=ContractingCompiler(),
                 environment={}):

        self.executor = Executor(metering=metering, driver=driver)
        self.raw_driver = driver
        self.signer = signer
        self.compiler = compiler
        self.submission_filename = submission_filename
        self.environment = environment

        # Seed the genesis contracts into the instance
        with open(self.submission_filename) as f:
            contract = f.read()

        self.raw_driver.set_contract(name='submission', code=contract)

        self.raw_driver.commit()

        self.submission_contract = self.get_contract('submission')
Exemple #9
0
    def test_submission(self):
        e = Executor(metering=False)

        code = '''@export
def d():
    a = 1
    return 1            
'''

        kwargs = {'name': 'stubucks', 'code': code}

        e.execute(**TEST_SUBMISSION_KWARGS, kwargs=kwargs, auto_commit=True)

        self.compiler.module_name = 'stubucks'
        new_code = self.compiler.parse_to_code(code)

        self.assertEqual(self.d.get_contract('stubucks'), new_code)
Exemple #10
0
    def test_submission_then_function_call(self):
        e = Executor(metering=False)

        code = '''@export
def d():
    return 1            
'''

        kwargs = {'name': 'stubuckz', 'code': code}

        e.execute(**TEST_SUBMISSION_KWARGS, kwargs=kwargs)
        output = e.execute(sender='stu',
                           contract_name='stubuckz',
                           function_name='d',
                           kwargs={})

        self.assertEqual(output['result'], 1)
        self.assertEqual(output['status_code'], 0)
Exemple #11
0
    def setUp(self):
        self.rpc = rpc.StateInterface(driver=ContractDBDriver(),
                                      engine=Engine(),
                                      compiler=ContractingCompiler(),
                                      blocks=SQLLiteBlockStorageDriver())

        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        self.e = Executor(currency_contract='erc20_clone', metering=False)

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_sys_contracts/currency.s.py'))
Exemple #12
0
    def test_arbitrary_environment_passing_works_via_executor(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/i_use_env.s.py'))

        this_is_a_passed_in_variable = 555

        env = {'this_is_a_passed_in_variable': this_is_a_passed_in_variable}

        output = e.execute('stu',
                           'i_use_env',
                           'env_var',
                           kwargs={},
                           environment=env)

        self.assertEqual(output['result'], this_is_a_passed_in_variable)
    def setUp(self):
        # Hard load the submission contract
        self.d = ContractDriver()
        self.d.flush()

        with open(contracting.__path__[0] + '/contracts/submission.s.py') as f:
            contract = f.read()

        self.d.set_contract(name='submission', code=contract)
        self.d.commit()

        # Execute the currency contract with metering disabled
        self.e = Executor(driver=self.d)
        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_contracts/currency.s.py'),
                       metering=False,
                       auto_commit=True)
Exemple #14
0
    def setUp(self):
        self.d = ContractDriver()
        self.d.flush()

        with open(contracting.__path__[0] + '/contracts/submission.s.py') as f:
            contract = f.read()

        self.d.set_contract(name='submission',
                            code=contract)
        self.d.commit()

        self.e = Executor(currency_contract='erc20_clone', metering=False)

        environment = {'now': Datetime(2019, 1, 1)}

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file('./test_contracts/erc20_clone.s.py'), environment=environment)

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file('./test_contracts/atomic_swaps.s.py'))
Exemple #15
0
    def test_arbitrary_environment_passing_fails_if_not_passed_correctly(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/i_use_env.s.py'))

        this_is_a_passed_in_variable = 555

        env = {
            'this_is_another_passed_in_variable': this_is_a_passed_in_variable
        }

        output = e.execute('stu',
                           'i_use_env',
                           'env_var',
                           kwargs={},
                           environment=env)

        self.assertEqual(output['status_code'], 1)
Exemple #16
0
    def __init__(self, parallelism=4, *args, **kwargs):

        super().__init__(*args, **kwargs)

        # Number of core / processes we push to
        self.parallelism = parallelism
        self.executor = Executor(driver=self.driver)
        self.transaction_executor = execution.SerialExecutor(executor=self.executor)

        self.work_processor = WorkProcessor(client=self.client, nonces=self.nonces)
        self.router.add_service(WORK_SERVICE, self.work_processor)

        self.upgrade_manager.node_type = 'delegate'

        self.log = get_logger(f'Delegate {self.wallet.vk_pretty[4:12]}')
Exemple #17
0
    def test_import_exported_function_works(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/import_this.s.py'))

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/importing_that.s.py'))

        output = e.execute('stu', 'importing_that', 'test', kwargs={})

        self.assertEqual(output['result'], 12345 - 1000)
Exemple #18
0
    def test_orm_foreign_variable_gets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_variable_contract.s.py'))
        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_foreign_key_contract.s.py'))

        e.execute('stu',
                  'test_orm_variable_contract',
                  'set_v',
                  kwargs={'i': 424242})

        # this should fail
        i = e.execute('stu',
                      'test_orm_foreign_key_contract',
                      'get_fv',
                      kwargs={})

        self.assertEqual(i['result'], 424242)
Exemple #19
0
    def test_orm_variable_gets_and_sets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_variable_contract.s.py'))

        e.execute('stu',
                  'test_orm_variable_contract',
                  'set_v',
                  kwargs={'i': 1000})
        res = e.execute('stu',
                        'test_orm_variable_contract',
                        'get_v',
                        kwargs={})

        self.assertEqual(res['result'], 1000)
    def test_transfer_performance(self):
        e = Executor()

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      '../integration/test_contracts/erc20_clone.s.py'))

        for r in self.recipients:
            e.execute(sender='stu',
                      contract_name='erc20_clone',
                      function_name='transfer',
                      kwargs={
                          'amount': 1,
                          'to': r
                      })
Exemple #21
0
    def test_orm_variable_sets_in_contract(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_variable_contract.s.py'),
                  auto_commit=True)

        e.execute('stu',
                  'test_orm_variable_contract',
                  'set_v',
                  kwargs={'i': 1000},
                  auto_commit=True)

        i = self.d.get('test_orm_variable_contract.v')
        self.assertEqual(i, 1000)
def execute_tx(executor: Executor,
               transaction,
               stamp_cost,
               environment: dict = {},
               debug=True):
    # Deserialize Kwargs. Kwargs should be serialized JSON moving into the future for DX.
    kwargs = decode(transaction.payload.kwargs)

    output = executor.execute(sender=transaction.payload.sender.hex(),
                              contract_name=transaction.payload.contractName,
                              function_name=transaction.payload.functionName,
                              stamps=transaction.payload.stampsSupplied,
                              stamp_cost=stamp_cost,
                              kwargs=kwargs,
                              environment=environment,
                              auto_commit=False)

    if debug:
        log.error(output)

    deltas = []
    for k, v in output['writes'].items():
        key, value = encode_kv(k, v)
        d = transaction_capnp.Delta.new_message(key=key, value=value)
        deltas.append(d)

    tx_hash = tx_hash_from_tx(transaction)

    # Encode deltas into a Capnp struct
    tx_output = transaction_capnp.TransactionData.new_message(
        hash=tx_hash,
        transaction=transaction,
        status=output['status_code'],
        state=deltas,
        stampsUsed=output['stamps_used'])

    executor.driver.pending_writes.clear()  # add

    return tx_output
Exemple #23
0
    def test_orm_foreign_hash_sets_in_contract_doesnt_work(self):
        e = Executor(metering=False)

        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_hash_contract.s.py'),
                  auto_commit=True)
        e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file(
                      './test_contracts/test_orm_foreign_hash_contract.s.py'),
                  auto_commit=True)

        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'key1',
                      'v': 1234
                  },
                  auto_commit=True)
        e.execute('stu',
                  'test_orm_hash_contract',
                  'set_h',
                  kwargs={
                      'k': 'another_key',
                      'v': 9999
                  },
                  auto_commit=True)

        status_1 = e.execute('stu',
                             'test_orm_foreign_hash_contract',
                             'set_fh',
                             kwargs={
                                 'k': 'key1',
                                 'v': 5555
                             },
                             auto_commit=True)
        status_2 = e.execute('stu',
                             'test_orm_foreign_hash_contract',
                             'set_fh',
                             kwargs={
                                 'k': 'another_key',
                                 'v': 1000
                             },
                             auto_commit=True)

        key1 = self.d.get('test_orm_hash_contract.h:key1')
        another_key = self.d.get('test_orm_hash_contract.h:another_key')

        self.assertEqual(key1, 1234)
        self.assertEqual(another_key, 9999)
        self.assertEqual(status_1['status_code'], 1)
        self.assertEqual(status_2['status_code'], 1)
class TestMetering(TestCase):
    def setUp(self):
        # Hard load the submission contract
        self.d = ContractDriver()
        self.d.flush()

        with open(contracting.__path__[0] + '/contracts/submission.s.py') as f:
            contract = f.read()

        self.d.set_contract(name='submission', code=contract)
        self.d.commit()

        # Execute the currency contract with metering disabled
        self.e = Executor(driver=self.d)
        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_contracts/currency.s.py'),
                       metering=False,
                       auto_commit=True)

    def tearDown(self):
        self.d.flush()

    def test_simple_execution_deducts_stamps(self):
        prior_balance = self.d.get('currency.balances:stu')

        output = self.e.execute('stu',
                                'currency',
                                'transfer',
                                kwargs={
                                    'amount': 100,
                                    'to': 'colin'
                                },
                                auto_commit=True)

        new_balance = self.d.get('currency.balances:stu')

        self.assertEqual(float(prior_balance - new_balance - 100),
                         output['stamps_used'] / STAMPS_PER_TAU)

    def test_too_few_stamps_fails_and_deducts_properly(self):
        prior_balance = self.d.get('currency.balances:stu')

        print(prior_balance)

        small_amount_of_stamps = 1 * STAMPS_PER_TAU

        output = self.e.execute('stu',
                                'currency',
                                'transfer',
                                kwargs={
                                    'amount': 100,
                                    'to': 'colin'
                                },
                                stamps=small_amount_of_stamps,
                                auto_commit=True)

        print(output)

        new_balance = self.d.get('currency.balances:stu')

        self.assertEqual(float(prior_balance - new_balance),
                         output['stamps_used'] / STAMPS_PER_TAU)

    def test_adding_too_many_stamps_throws_error(self):
        prior_balance = self.d.get('currency.balances:stu')
        too_many_stamps = (prior_balance + 1000) * STAMPS_PER_TAU

        output = self.e.execute('stu',
                                'currency',
                                'transfer',
                                kwargs={
                                    'amount': 100,
                                    'to': 'colin'
                                },
                                stamps=too_many_stamps,
                                auto_commit=True)

        self.assertEqual(output['status_code'], 1)

    def test_adding_all_stamps_with_infinate_loop_eats_all_balance(self):
        self.d.set('currency.balances:stu', 500)
        self.d.commit()

        prior_balance = self.d.get('currency.balances:stu')

        prior_balance *= STAMPS_PER_TAU

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_contracts/inf_loop.s.py'),
                       stamps=prior_balance,
                       metering=True,
                       auto_commit=True)

        new_balance = self.d.get('currency.balances:stu')

        # Not all stamps will be deducted because it will blow up in the middle of execution
        self.assertTrue(new_balance < 0.01)

    def test_submitting_contract_succeeds_with_enough_stamps(self):
        prior_balance = self.d.get('currency.balances:stu')

        print(prior_balance)

        output = self.e.execute(**TEST_SUBMISSION_KWARGS,
                                kwargs=submission_kwargs_for_file(
                                    './test_contracts/erc20_clone.s.py'),
                                auto_commit=True)
        print(output)

        new_balance = self.d.get('currency.balances:stu')

        print(new_balance)

        self.assertEqual(float(prior_balance - new_balance),
                         output['stamps_used'] / STAMPS_PER_TAU)

    def test_pending_writes_has_deducted_stamp_amount_prior_to_auto_commit(
            self):
        prior_balance = self.d.get('currency.balances:stu')

        output = self.e.execute(**TEST_SUBMISSION_KWARGS,
                                kwargs=submission_kwargs_for_file(
                                    './test_contracts/erc20_clone.s.py'),
                                auto_commit=False)
        self.assertNotEquals(
            self.e.driver.pending_writes['currency.balances:stu'],
            prior_balance)
Exemple #25
0
class TestRPC(TestCase):
    def setUp(self):
        self.rpc = rpc.StateInterface(driver=ContractDBDriver(),
                                      engine=Engine(),
                                      compiler=ContractingCompiler())

        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        self.rpc.driver.commit()

        self.e = Executor(currency_contract='erc20_clone', metering=False)

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_sys_contracts/currency.s.py'))

    def tearDown(self):
        self.rpc.driver.flush()

    def test_get_contract(self):
        contract = '''
def stu():
    print('howdy partner')
'''

        name = 'stustu'

        self.rpc.driver.set_contract(name, contract)

        response = self.rpc.get_contract('stustu')

        self.assertEqual(response, contract)

    def test_get_contract_doesnt_exist_returns_status(self):
        response = self.rpc.get_contract('stustu')

        expected = {'status': 1}

        self.assertEqual(response, expected)

    def test_get_methods(self):
        contract = '''
def stu():
    print('howdy partner')
'''

        name = 'stustu'

        self.rpc.driver.set_contract(name, contract)

        response = self.rpc.get_methods('stustu')

        expected = [{'name': 'stu', 'arguments': []}]

        self.assertEqual(response, expected)

    def test_get_methods_doesnt_return_private_methods(self):
        response = self.rpc.get_methods('currency')

        expected = [{
            'name': 'transfer',
            'arguments': ['to', 'amount']
        }, {
            'name': 'approve',
            'arguments': ['spender', 'amount']
        }, {
            'name': 'transfer_from',
            'arguments': ['approver', 'spender', 'amount']
        }]

        self.assertEqual(response, expected)

    def test_get_methods_no_contract_returns_error(self):
        response = self.rpc.get_methods('stustu')

        expected = {'status': 1}

        self.assertEqual(response, expected)

    def test_get_var_that_exists(self):
        response = self.rpc.get_var('currency', 'seed_amount')

        expected = 1000000

        self.assertEqual(response, expected)

    def test_get_var_that_doesnt_exist(self):
        response = self.rpc.get_var('currency', 'bleck')

        expected = {'status': 2}

        self.assertEqual(response, expected)

    def test_get_var_hash_that_exists(self):
        response = self.rpc.get_var(
            'currency', 'balances',
            '324ee2e3544a8853a3c5a0ef0946b929aa488cbe7e7ee31a0fef9585ce398502')

        expected = 1000000

        self.assertEqual(response, expected)

    def test_get_var_hash_that_doesnt_exist(self):
        response = self.rpc.get_var('currency', 'balances', 'xxx')

        expected = {'status': 2}

        self.assertEqual(response, expected)

    def test_get_var_contract_doesnt_exist(self):
        response = self.rpc.get_var('xxx', 'balances', 'xxx')

        expected = {'status': 1}

        self.assertEqual(response, expected)

    def test_get_var_multihash_that_exists(self):
        pass

    def test_get_var_multihash_that_doesnt_exist(self):
        pass

    def test_get_vars_returns_correctly(self):
        expected = ['xrate', 'seed_amount', 'balances', 'allowed']

        response = self.rpc.get_vars('currency')

        self.assertEqual(response, expected)

    def test_get_vars_on_contract_doesnt_exist(self):
        response = self.rpc.get_vars('xxx')

        expected = {'status': 1}

        self.assertEqual(response, expected)

    def test_run_tx(self):
        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        contract = '''
owner = Variable()

@construct
def seed():
    owner.set(ctx.caller)

@export
def get_owner():
    return owner.get()
        '''

        key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        pk = key.get_verifying_key().to_string().hex()

        tx = make_tx(key,
                     contract='submission',
                     func='submit_contract',
                     arguments={
                         'code': contract,
                         'name': 'stu_bucks'
                     })

        result = self.rpc.run(tx)

        self.assertEqual(result['input'], tx)

        owner = result['output']['updates'].get('stu_bucks.owner')

        self.assertEqual(owner, json.dumps(pk))

    def test_run_all_tx(self):
        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(
            name='submission',
            code=contract,
        )

        contract = '''
owner = Variable()

@construct
def seed():
    owner.set(ctx.caller)

@export
def get_owner():
    return owner.get()
                '''

        # nakey = nacl.signing.SigningKey.generate()
        #
        # pk = nakey.verify_key.encode().hex()

        nakey = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        pk = nakey.get_verifying_key().to_string().hex()

        tx = make_tx(nakey,
                     contract='submission',
                     func='submit_contract',
                     arguments={
                         'code': contract,
                         'name': 'stu_bucks'
                     })

        tx_2 = make_tx(nakey,
                       contract='stu_bucks',
                       func='get_owner',
                       arguments={})

        result = self.rpc.run_all([tx, tx_2])

        self.assertEqual(result[0]['input'], tx)
        self.assertEqual(result[1]['input'], tx_2)

        owner = result[0]['output']['updates'].get('stu_bucks.owner')
        accessed_owner = result[1]['output']['result']

        self.assertEqual(owner, json.dumps(pk))
        self.assertEqual(accessed_owner, pk)

    def test_lint_code(self):
        code = '''
@export
def a():
    __ruh_roh__ = 'shaggy'
        '''
        err = "Line 4 : S2- Illicit use of '_' before variable : __ruh_roh__"

        res = self.rpc.lint(code)

        self.assertEqual(res[0], err)

    def test_compile(self):
        code = '''
@export
def public():
    private('hello')

def private(message):
    print(message)
'''

        compiled_code = '''@__export('__main__')
def public():
    __private('hello')


def __private(message):
    print(message)
'''

        compiled_result = self.rpc.compile_code(code)

        self.assertEqual(compiled_result, compiled_code)

    def test_process_json_rpc_command(self):
        contract = '''
def stu():
    print('howdy partner')
'''

        name = 'stustu'

        self.rpc.driver.set_contract(name, contract)

        command = {'command': 'get_contract', 'arguments': {'name': 'stustu'}}

        got_contract = self.rpc.get_contract('stustu')

        rpc_result = self.rpc.process_json_rpc_command(command)

        self.assertEqual(got_contract, rpc_result)

    def test_process_no_command(self):
        command = {'arguments': {'name': 'stustu'}}

        rpc_result = self.rpc.process_json_rpc_command(command)

        self.assertIsNone(rpc_result)

    def test_process_no_args(self):
        command = {'command': 'get_contract'}

        rpc_result = self.rpc.process_json_rpc_command(command)

        self.assertIsNone(rpc_result)

    def test_process_command_that_doesnt_exist(self):
        command = {'command': 'get_stu', 'arguments': {'name': 'stustu'}}

        rpc_result = self.rpc.process_json_rpc_command(command)

        self.assertIsNone(rpc_result)
    'contract_name': 'submission',
    'function_name': 'submit_contract'
}

d = ContractDriver()
d.flush()

with open('../../contracting/contracts/submission.s.py') as f:
    contract = f.read()

d.set_contract(name='submission', code=contract, author='sys')
d.commit()

recipients = [secrets.token_hex(16) for _ in range(1000)]

e = Executor()

e.execute(**TEST_SUBMISSION_KWARGS,
          kwargs=submission_kwargs_for_file(
              '../integration/test_contracts/erc20_clone.s.py'))

import datetime

for i in range(20):
    now = datetime.datetime.now()

    # profiler = Profiler()
    # profiler.start()
    for r in recipients:
        _, res, _ = e.execute(sender='stu',
                              contract_name='erc20_clone',
Exemple #27
0
class TestAtomicSwapContract(TestCase):
    def setUp(self):
        self.d = ContractDriver()
        self.d.flush()

        with open(contracting.__path__[0] + '/contracts/submission.s.py') as f:
            contract = f.read()

        self.d.set_contract(name='submission',
                            code=contract)
        self.d.commit()

        self.e = Executor(currency_contract='erc20_clone', metering=False)

        environment = {'now': Datetime(2019, 1, 1)}

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file('./test_contracts/erc20_clone.s.py'), environment=environment)

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                  kwargs=submission_kwargs_for_file('./test_contracts/atomic_swaps.s.py'))

    def tearDown(self):
        self.e.bypass_privates = False

        self.d.flush()

    def test_initiate_not_enough_approved(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        output = self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5000000
        })

        self.assertEqual(output['status_code'], 1)
        self.assertTrue(isinstance(output['result'], AssertionError))

    def test_initiate_transfers_coins_correctly(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        atomic_swaps = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account':'atomic_swaps'})
        stu = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account': 'stu'})
        stu_as = self.e.execute('stu', 'erc20_clone', 'allowance', kwargs={'owner': 'stu', 'spender': 'atomic_swaps'})

        self.assertEqual(atomic_swaps['result'], 5)
        self.assertEqual(stu['result'], 999995)
        self.assertEqual(stu_as['result'], 999995)

    def test_initiate_writes_to_correct_key_and_properly(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'}, auto_commit=True)
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        }, auto_commit=True)

        key = 'atomic_swaps.swaps:raghu:eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514'

        expiration, amount = self.d.get(key)
        self.assertEqual(expiration, Datetime(2020, 1, 1))
        self.assertEqual(amount, 5)

    def test_redeem_on_wrong_secret_fails(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        output = self.e.execute('raghu', 'atomic_swaps', 'redeem', kwargs={'secret': '00'})

        self.assertEqual(output['status_code'], 1)
        self.assertEqual(str(output['result']), 'Incorrect sender or secret passed.')

    def test_redeem_on_wrong_sender_fails(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        output = self.e.execute('stu', 'atomic_swaps', 'redeem', kwargs={'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'})
        # status_code, result, stamps_used
        self.assertEqual(output['status_code'], 1)
        self.assertEqual(str(output['result']), 'Incorrect sender or secret passed.')

    def test_past_expiration_fails(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2021, 1, 1)}

        output = self.e.execute('raghu', 'atomic_swaps', 'redeem', kwargs={'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                              environment=environment)

        self.assertEqual(output['status_code'], 1)
        self.assertEqual(str(output['result']), 'Swap has expired.')

    def test_successful_redeem_transfers_coins_correctly(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2019, 1, 1)}

        self.e.execute('raghu', 'atomic_swaps', 'redeem', kwargs={'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        atomic_swaps = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account': 'atomic_swaps'})
        raghu = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account': 'raghu'})

        self.assertEqual(raghu['result'], 5)
        self.assertEqual(atomic_swaps['result'], 0)

    def test_successful_redeem_deletes_entry(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2019, 1, 1)}

        self.e.execute('raghu', 'atomic_swaps', 'redeem', kwargs={'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        key = 'atomic_swaps.swaps:raghu:eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514'
        v = self.d.get(key)

        self.assertEqual(v, None)

    def test_refund_works(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2021, 1, 1)}

        self.e.execute('stu', 'atomic_swaps', 'refund', kwargs={'participant': 'raghu', 'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        atomic_swaps = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account': 'atomic_swaps'})
        stu = self.e.execute('stu', 'erc20_clone', 'balance_of', kwargs={'account': 'stu'})

        self.assertEqual(stu['result'], 1000000)
        self.assertEqual(atomic_swaps['result'], 0)

    def test_refund_too_early_fails(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2019, 1, 1)}

        res = self.e.execute('stu', 'atomic_swaps', 'refund',
                       kwargs={'participant': 'raghu', 'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        self.assertEqual(str(res['result']), 'Swap has not expired.')

    def test_refund_participant_is_signer_fails(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2021, 1, 1)}

        res = self.e.execute('raghu', 'atomic_swaps', 'refund',
                       kwargs={'participant': 'raghu', 'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        self.assertEqual(str(res['result']), 'Caller and signer cannot issue a refund.')

    def test_refund_fails_with_wrong_secret(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2019, 1, 1)}

        res = self.e.execute('stu', 'atomic_swaps', 'refund',
                                kwargs={'participant': 'raghu', 'secret': '00'},
                                environment=environment)

        self.assertEqual(str(res['result']), 'No swap to refund found.')

    def test_refund_resets_swaps(self):
        self.e.execute('stu', 'erc20_clone', 'approve', kwargs={'amount': 1000000, 'to': 'atomic_swaps'})
        self.e.execute('stu', 'atomic_swaps', 'initiate', kwargs={
            'participant': 'raghu',
            'expiration': Datetime(2020, 1, 1),
            'hashlock': 'eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514',
            'amount': 5
        })

        environment = {'now': Datetime(2021, 1, 1)}

        self.e.execute('stu', 'atomic_swaps', 'refund',
                       kwargs={'participant': 'raghu', 'secret': '842b65a7d48e3a3c3f0e9d37eaced0b2'},
                       environment=environment)

        key = 'atomic_swaps.swaps:raghu:eaf48a02d3a4bb3aeb0ecb337f6efb026ee0bbc460652510cff929de78935514'
        v = self.d.get(key)

        self.assertEqual(v, None)

    def test_trying_to_call_private_function_fails(self):
        with self.assertRaises(AssertionError):
            self.e.execute('stu', 'atomic_swaps', '__test', kwargs={})

        self.e.bypass_privates = True

        self.e.execute('stu', 'atomic_swaps', '__test', kwargs={})
Exemple #28
0
class TestRPCBlockDriver(TestCase):
    def setUp(self):
        self.rpc = rpc.StateInterface(driver=ContractDBDriver(),
                                      engine=Engine(),
                                      compiler=ContractingCompiler(),
                                      blocks=SQLLiteBlockStorageDriver())

        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        self.e = Executor(currency_contract='erc20_clone', metering=False)

        self.e.execute(**TEST_SUBMISSION_KWARGS,
                       kwargs=submission_kwargs_for_file(
                           './test_sys_contracts/currency.s.py'))

    def tearDown(self):
        self.rpc.driver.flush()
        self.rpc.blocks.flush()

    def test_init(self):
        self.assertTrue(self.rpc.blocks_enabled)

    def test_run_works_same_as_blocks_not_stored(self):
        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        contract = '''
owner = Variable()

@construct
def seed():
    owner.set(ctx.caller)

@export
def get_owner():
    return owner.get()
        '''

        # nakey = nacl.signing.SigningKey.generate()
        #
        # pk = nakey.verify_key.encode().hex()

        nakey = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        pk = nakey.get_verifying_key().to_string().hex()

        tx = make_tx(nakey,
                     contract='submission',
                     func='submit_contract',
                     arguments={
                         'code': contract,
                         'name': 'stu_bucks'
                     })

        result = self.rpc.run(tx)

        self.assertEqual(result['transactions'][0]['input'], tx)

        owner = result['transactions'][0]['output']['updates'].get(
            'stu_bucks.owner')

        self.assertEqual(owner, json.dumps(pk))

    def test_run_blocks_stores_block(self):
        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)

        contract = '''
owner = Variable()

@construct
def seed():
    owner.set(ctx.caller)

@export
def get_owner():
    return owner.get()
        '''

        # nakey = nacl.signing.SigningKey.generate()
        #
        # pk = nakey.verify_key.encode().hex()

        nakey = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        pk = nakey.get_verifying_key().to_string().hex()

        tx = make_tx(nakey,
                     contract='submission',
                     func='submit_contract',
                     arguments={
                         'code': contract,
                         'name': 'stu_bucks'
                     })

        self.assertEqual(self.rpc.blocks.height(), -1)

        result = self.rpc.run(tx)

        self.assertEqual(result['transactions'][0]['input'], tx)

        owner = result['transactions'][0]['output']['updates'].get(
            'stu_bucks.owner')

        self.assertEqual(owner, json.dumps(pk))

        self.assertEqual(self.rpc.blocks.height(), 0)

    def test_run_all_stores_block_and_equals_retrieved_block(self):
        self.rpc.driver.flush()

        with open('../../contractdb/contracts/submission.s.py') as f:
            contract = f.read()

        self.rpc.driver.set_contract(name='submission', code=contract)
        contract = '''
owner = Variable()

@construct
def seed():
    owner.set(ctx.caller)

@export
def get_owner():
    return owner.get()
                '''

        # nakey = nacl.signing.SigningKey.generate()

        nakey = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        pk = nakey.get_verifying_key().to_string().hex()

        tx = make_tx(nakey,
                     contract='submission',
                     func='submit_contract',
                     arguments={
                         'code': contract,
                         'name': 'stu_bucks'
                     })

        from copy import deepcopy

        self.rpc.run(tx)

        tx = make_tx(nakey, contract='stu_bucks', func='get_owner')

        txs = [deepcopy(tx) for _ in range(10)]

        block = self.rpc.run_all(txs)

        got_block = self.rpc.blocks.get_block_by_index(
            self.rpc.blocks.height())

        self.assertDictEqual(block, got_block)