Esempio n. 1
0
def LocalMain(config):
    shell = ContractController(config)

    # if there is a script file, process it; the interactive
    # shell will start unless there is an explicit exit in the script
    script_file = config.get("ScriptFile")
    if script_file:
        logger.info("Processing script file %s", str(script_file))
        if not ContractController.ProcessScript(shell, script_file):
            ContractResponse.exit_commit_workers()
            sys.exit(shell.exit_code)

    shell.cmdloop()
    print("")

    ContractResponse.exit_commit_workers()
    sys.exit(shell.exit_code)
Esempio n. 2
0
def ErrorShutdown():
    """
    Perform a clean shutdown after an error
    """
    try:
        if block_store is not None:
            block_store.close()
    except Exception as e:
        logger.exception('failed to close block_store')

    try:
        enclave_helper.shutdown_enclave()
    except Exception as e:
        logger.exception('shutdown failed')

    # Send termination signal to commit tasks
    ContractResponse.exit_commit_workers()

    sys.exit(-1)
Esempio n. 3
0
def RunService():
    @defer.inlineCallbacks
    def shutdown_twisted():
        logger.info("Stopping Twisted")
        yield reactor.callFromThread(reactor.stop)

    reactor.addSystemEventTrigger('before', 'shutdown', shutdown_twisted)

    atexit.register(lambda: ContractResponse.exit_commit_workers())

    try:
        reactor.run()
    except ReactorNotRunning:
        logger.warn('shutdown')
    except:
        logger.warn('shutdown')

    sys.exit(0)
Esempio n. 4
0
def UpdateTheContract(config, enclaves, contract, contract_invoker_keys):
    commit_dependenices = []
    last_response_committed = None

    ledger_config = config.get('Sawtooth')
    contract_invoker_id = contract_invoker_keys.identity

    # Decide if the contract use a fixed enclave or a randomized one for each update.
    if use_eservice and config['Service']['Randomize_Eservice']:
        enclave_to_use = 'random'
    else:
        enclave_to_use = enclaves[0]

    start_time = time.time()
    total_tests = 0
    total_failed = 0

    test_list = []
    test_file = config['expressions']
    with open(test_file, "r") as efile:
        if test_file.endswith('.exp'):
            fieldnames = ['expression', 'expected', 'invert']
            reader = csv.DictReader(filter(lambda row: row[0] != '#', efile),
                                    fieldnames,
                                    quoting=csv.QUOTE_NONE,
                                    escapechar='\\',
                                    skipinitialspace=True)

            test_list = list(reader)

        elif test_file.endswith('.json'):
            # there is currently no support to set these values outside of the
            # configuration file and that is not going to change soon
            test_max_level = config.get('Test', {}).get('MaxLevel', 0)

            reader = json.load(efile)
            for test in reader:
                if test.get('test-level', 0) > test_max_level:
                    continue

                method = test['MethodName']
                pparms = test.get('PositionalParameters', [])
                kparms = test.get('KeywordParameters', {})
                test['expression'] = contract_helper.invocation_request(
                    method, *pparms, **kparms)
                test_list.append(test)
        else:
            logger.error('unknown test file format; %s', test_file)
            ErrorShutdown()

    for test in test_list:
        expression = test['expression']

        if test.get('description'):
            logger.log(
                plogger.HIGHLIGHT,
                "TEST[{0}] : {1}".format(total_tests,
                                         test['description'].format(**test)))

        try:
            total_tests += 1
            update_request = contract.create_update_request(
                contract_invoker_keys, expression, enclave_to_use)
            update_response = update_request.evaluate()

            raw_result = str(update_response.invocation_response)
            result = raw_result[:15]
            if len(raw_result) >= 15:
                result += "..."

            unpacked_response = contract_helper.invocation_response(raw_result)
            if update_response.status is False:
                logger.info('failed: {0} --> {1}'.format(expression, result))
                if test.get('invert') is None or test.get('invert') != 'fail':
                    total_failed += 1
                    logger.warn('inverted test failed: %s instead of %s',
                                result, test['expected'])

                elif test.get('expected') and not re.match(
                        test.get('expected'), raw_result):
                    total_failed += 1
                    logger.warn('test failed: %s instead of %s', result,
                                test['expected'])

                continue

            logger.info('{0} --> {1}'.format(expression, result))

            if test.get('expected') and not re.match(test.get('expected'),
                                                     raw_result):
                total_failed += 1
                logger.warn('test failed: %s instead of %s', result,
                            test['expected'])

        except Exception as e:
            logger.error('enclave failed to evaluate expression; %s', str(e))
            ErrorShutdown()

        # if this operation did not change state then there is nothing to commit
        if update_response.state_changed:
            # asynchronously submit the commit task: (a commit task replicates
            # change-set and submits the corresponding transaction)
            try:
                logger.info(
                    "asynchronously replicate change set and submit transaction in the background"
                )
                update_response.commit_asynchronously(ledger_config)
                last_response_committed = update_response
            except Exception as e:
                logger.error('failed to submit commit: %s', str(e))
                ErrorShutdown()

            logger.debug('update state')
            contract.set_state(update_response.raw_state)

    if total_failed > 0:
        logger.warn('failed %d of %d tests', total_failed, total_tests)
        ErrorShutdown()

    # wait for the last commit to finish.
    if last_response_committed is not None:
        try:
            txn_id = last_response_committed.wait_for_commit()
            if use_ledger and txn_id is None:
                logger.error("Did not receive txn id for the final commit")
                ErrorShutdown()
        except Exception as e:
            logger.error("Error while waiting for final commit: %s", str(e))
            ErrorShutdown()

    logger.info('completed in %s', time.time() - start_time)
    logger.info('passed %d of %d tests', total_tests - total_failed,
                total_tests)

    #shutdown commit workers
    ContractResponse.exit_commit_workers()
Esempio n. 5
0
def UpdateTheContract(config, contract, enclaves, contract_invoker_keys) :

    ledger_config = config.get('Sawtooth')
    contract_invoker_id = contract_invoker_keys.identity
    last_response_committed = None

    # Decide if the contract use a fixed enclave or a randomized one for each update.
    if use_eservice and config['Service']['Randomize_Eservice']:
        enclave_to_use = 'random'
    else:
        enclave_to_use = enclaves[0]

    start_time = time.time()
    for x in range(config['iterations']) :
        if tamper_block_order :
            # in this evaluation we tamper with the state, so it should fail with a bad authenticator error
            logger.info('the following evaluation should fail with a bad authenticator error')
            temp_saved_state_hash = contract.contract_state.get_state_hash(encoding='b64')
            test_state.TamperWithStateBlockOrder(contract.contract_state)

        try :
            expression = contract_helper.invocation_request('inc_value')
            update_request = contract.create_update_request(contract_invoker_keys, expression, enclave_to_use)
            update_response = update_request.evaluate()

            if update_response.status is False :
                logger.info('failed: {0} --> {1}'.format(expression, update_response.invocation_response))
                continue

            logger.info('{0} --> {1}'.format(expression, update_response.invocation_response))

        except Exception as e:
            logger.error('enclave failed to evaluate expression; %s', str(e))
            ErrorShutdown()

        # if this operation did not change state then there is nothing to commit
        if update_response.state_changed :
            # asynchronously submit the commit task: (a commit task replicates change-set and submits the corresponding transaction)
            try:
                update_response.commit_asynchronously(ledger_config)
                last_response_committed = update_response
            except Exception as e:
                logger.error('failed to submit commit: %s', str(e))
                ErrorShutdown()

            logger.debug('update state')
            contract.set_state(update_response.raw_state)

    # wait for the last commit to finish.
    if last_response_committed is not None:
        try:
            txn_id = last_response_committed.wait_for_commit()
            if use_ledger and txn_id is None:
                logger.error("Did not receive txn id for the last response committed")
                ErrorShutdown()
        except Exception as e:
            logger.error("Error while waiting for the last response committed: %s", str(e))
            ErrorShutdown()

    logger.info("All commits completed")
    logger.info('completed in %s', time.time() - start_time)

    # shutdown commit workers
    ContractResponse.exit_commit_workers()