Exemplo n.º 1
0
def __command_vetting__(state, bindings, pargs) :
    """controller command to interact with an vetting contract
    """

    parser = argparse.ArgumentParser(prog='vetting')
    parser.add_argument('-e', '--enclave', help='URL of the enclave service to use', type=str)
    parser.add_argument('-f', '--save_file', help='File where contract data is stored', type=str)
    parser.add_argument('-q', '--quiet', help='Suppress printing the result', action='store_true')
    parser.add_argument('-w', '--wait', help='Wait for the transaction to commit', action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get_verifying_key')
    subparser.add_argument('-s', '--symbol', help='binding symbol for result', type=str)

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument('-t', '--type_id', help='contract identifier for the issuer asset type', type=str, required=True)

    subparser = subparsers.add_parser('approve')
    subparser.add_argument('-i', '--issuer', help='identity of the issuer; ECDSA key', type=str, required=True)

    subparser = subparsers.add_parser('get_authority')
    subparser.add_argument('-i', '--issuer', help='identity of the issuer; ECDSA key', type=str, required=True)
    subparser.add_argument('-s', '--symbol', help='binding symbol for result', type=str)

    options = parser.parse_args(pargs)

    extraparams={'quiet' : options.quiet, 'wait' : options.wait}

    # -------------------------------------------------------
    if options.command == 'get_verifying_key' :
        extraparams['commit'] = False
        message = invocation_request('get-verifying-key')
        result = send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)
        if options.symbol :
            bindings.bind(options.symbol, result)
        return


    # -------------------------------------------------------
    if options.command == 'initialize' :
        message = invocation_request('initialize', options.type_id)
        send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'approve' :
        message = invocation_request('add-approved-key', options.issuer)
        send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)
        return

   # -------------------------------------------------------
    if options.command == 'get_authority' :
        extraparams['commit'] = False
        message = invocation_request('get-authority', options.issuer)
        result = send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)
        if options.symbol :
            bindings.bind(options.symbol, result)
        return
Exemplo n.º 2
0
def command_send(state, bindings, pargs) :
    """controller command to send a message to a contract
    """

    parser = argparse.ArgumentParser(prog='send')
    parser.add_argument('-e', '--enclave', help='URL of the enclave service to use', type=str)
    parser.add_argument('-f', '--save-file', help='File where contract data is stored', type=str)
    parser.add_argument('-p', '--positional', help='JSON encoded list of positional parameters', type=invocation_parameter)
    parser.add_argument('-s', '--symbol', help='Save the result in a symbol for later use', type=str)
    parser.add_argument('-q', '--quiet', help='Do not print the result', action='store_true')
    parser.add_argument('--wait', help='Wait for the transaction to commit', action = 'store_true')

    parser.add_argument('-k', '--kwarg',
                        help='add a keyword argument to the invocation',
                        nargs=2, type=invocation_parameter, action='append')

    parser.add_argument('method',
                        help='message to be sent to the contract',
                        type=str)

    parser.add_argument('positional_params',
                        help='positional parameters sent to the invocation',
                        type=invocation_parameter, nargs='*')

    options = parser.parse_args(pargs)
    waitflag = options.wait

    method = options.method

    pparams = []
    if options.positional :
        assert type(options.positional) is list
        pparams.extend(options.positional)

    if options.positional_params :
        pparams.extend(options.positional_params)

    kparams = dict()
    if options.kwarg :
        for (k, v) in options.kwarg :
            if type(k) is not str :
                raise RuntimeError('expecting string key; {0}'.format(str(k)))
            kparams[k] = v

    message = invocation_request(method, *pparams, **kparams)

    result = send_to_contract(
        state,
        options.save_file,
        message,
        eservice_url=options.enclave,
        quiet=options.quiet,
        wait=options.wait)
    if options.symbol :
        bindings.bind(options.symbol, result)
Exemplo n.º 3
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()
Exemplo n.º 4
0
def __command_auction__(state, bindings, pargs):
    """controller command to interact with an auction contract
    """

    parser = argparse.ArgumentParser(prog='auction')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save-file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get_signing_key')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument('-k',
                           '--key',
                           help='public key of the asset contract',
                           type=str,
                           required=True)

    subparser = subparsers.add_parser('prime')
    subparser.add_argument('-a',
                           '--attestation',
                           help='Escrow attestation from the asset ledger',
                           type=invocation_parameter,
                           required=True)

    subparser = subparsers.add_parser('submit_bid')
    subparser.add_argument('-a',
                           '--attestation',
                           help='Escrow attestation from the asset ledger',
                           type=invocation_parameter,
                           required=True)

    subparser = subparsers.add_parser('get_offered_asset')
    subparser = subparsers.add_parser('cancel_bid')
    subparser = subparsers.add_parser('check_bid')

    subparser = subparsers.add_parser('max_bid')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('close_bidding')

    subparser = subparsers.add_parser('exchange_attestation')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('cancel_attestation')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    if options.command == 'get_signing_key':
        message = invocation_request('get-public-signing-key')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    if options.command == 'initialize':
        message = invocation_request('initialize', options.key)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'prime':
        assert type(options.attestation) is list
        assert len(options.attestation) == 3

        bidinfo = options.attestation[0]
        dependencies = options.attestation[1]
        signature = options.attestation[2]
        message = invocation_request('prime-auction*', bidinfo, dependencies,
                                     signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'submit_bid':
        assert type(options.attestation) is list
        assert len(options.attestation) == 3

        bidinfo = options.attestation[0]
        dependencies = options.attestation[1]
        signature = options.attestation[2]
        message = invocation_request('submit-bid*', bidinfo, dependencies,
                                     signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'get_offered_asset':
        message = invocation_request('get-offered-asset')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'cancel_bid':
        message = invocation_request('cancel-bid')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'check_bid':
        message = invocation_request('check-bid')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'max_bid':
        message = invocation_request('max-bid')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, result)
        return

    if options.command == 'close_bidding':
        message = invocation_request('close-bidding')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'cancel_attestation':
        message = invocation_request('cancel-attestation')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, json.dumps(result))
        return

    if options.command == 'exchange_attestation':
        message = invocation_request('exchange-attestation')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, json.dumps(result))
        return
Exemplo n.º 5
0
def __command_asset_type__(state, bindings, pargs):
    """controller command to interact with an asset_type contract
    """

    parser = argparse.ArgumentParser(prog='asset_type')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save_file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument('-d',
                           '--description',
                           help='human readable description',
                           type=str,
                           default='')
    subparser.add_argument('-n',
                           '--name',
                           help='human readable name',
                           type=str,
                           default='')
    subparser.add_argument('-l',
                           '--link',
                           help='URL where more information is located',
                           type=str,
                           default='')

    subparser = subparsers.add_parser('get_identifier')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('get_description')
    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    # -------------------------------------------------------
    if options.command == 'initialize':
        message = invocation_request('initialize', options.name,
                                     options.description, options.link)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'get_identifier':
        extraparams['commit'] = False
        message = invocation_request('get-identifier')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'get_description':
        extraparams['quiet'] = True
        extraparams['commit'] = False
        message = invocation_request('get-name')
        name = send_to_contract(state,
                                options.save_file,
                                message,
                                eservice_url=options.enclave,
                                **extraparams)
        message = invocation_request('get-description')
        description = send_to_contract(state,
                                       options.save_file,
                                       message,
                                       eservice_url=options.enclave,
                                       **extraparams)
        message = invocation_request('get-link')
        link = send_to_contract(state,
                                options.save_file,
                                message,
                                eservice_url=options.enclave,
                                **extraparams)
        print("NAME: {0}".format(name))
        print("DESC: {0}".format(description))
        print("LINK: {0}".format(link))

        return
Exemplo n.º 6
0
def __command_exchange__(state, bindings, pargs):
    """controller command to interact with an exchange contract
    """

    parser = argparse.ArgumentParser(prog='exchange')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save_file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get_verifying_key')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('get_offered_asset')
    subparser = subparsers.add_parser('get_requested_asset')

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument(
        '-r',
        '--root',
        help='key for the root authority for requested issuer',
        type=str,
        required=True)
    subparser.add_argument(
        '-t',
        '--type_id',
        help='contract identifier for the requested asset type',
        type=str,
        required=True)
    subparser.add_argument('-o',
                           '--owner',
                           help='identity of the asset owner; ECDSA key',
                           type=str,
                           default="")
    subparser.add_argument('-c',
                           '--count',
                           help='amount requested',
                           type=int,
                           required=True)

    subparser = subparsers.add_parser('offer')
    subparser.add_argument('-a',
                           '--asset',
                           help='serialized escrowed asset',
                           type=scheme_parameter,
                           required=True)

    subparser = subparsers.add_parser('claim_offer')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('exchange')
    subparser.add_argument('-a',
                           '--asset',
                           help='serialized escrowed asset',
                           type=scheme_parameter,
                           required=True)

    subparser = subparsers.add_parser('claim_exchange')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('cancel')
    subparser = subparsers.add_parser('cancel_attestation')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    # -------------------------------------------------------
    if options.command == 'get_verifying_key':
        extraparams['commit'] = False
        message = invocation_request('get-verifying-key')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'get_offered_asset':
        extraparams['commit'] = False
        message = invocation_request('examine-offered-asset')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'get_requested_asset':
        extraparams['commit'] = False
        message = invocation_request('examine-requested-asset')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'initialize':
        asset_request = [options.type_id, options.count, options.owner]
        message = invocation_request('initialize', asset_request, options.root)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'offer':
        message = invocation_request('offer-asset', options.asset)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'claim_offer':
        extraparams['commit'] = False
        message = invocation_request('claim-offer')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'exchange':
        message = invocation_request('exchange-asset', options.asset)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'claim_exchange':
        extraparams['commit'] = False
        message = invocation_request('claim-exchange')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'cancel':
        message = invocation_request('cancel')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'cancel_attestation':
        extraparams['commit'] = False
        message = invocation_request('cancel-attestation')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return
def __command_kv__(state, bindings, pargs) :
    """controller command to interact with an asset_type contract
    """

    parser = argparse.ArgumentParser(prog='attestation-test')
    parser.add_argument('-e', '--enclave', help='URL of the enclave service to use', type=str, default='preferred')
    parser.add_argument('-f', '--save_file', help='File where contract data is stored', type=str)
    parser.add_argument('-q', '--quiet', help='Suppress printing the result', action='store_true')
    parser.add_argument('-w', '--wait', help='Wait for the transaction to commit', action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get')
    subparser.add_argument('-k', '--key', help='transfer key', type=str, default='_transfer_')
    subparser.add_argument('-s', '--symbol', help='binding symbol for result', type=str)

    subparser = subparsers.add_parser('set')
    subparser.add_argument('-k', '--key', help='transfer key', type=str, default='_transfer_')
    subparser.add_argument('-v', '--value', help='value to send', type=str, required=True)

    options = parser.parse_args(pargs)

    extraparams={'quiet' : options.quiet, 'wait' : options.wait}

    # -------------------------------------------------------
    if options.command == 'get' :

        kv = KeyValueStore()
        with kv :
            kv.set(options.key, "")

        # push the blocks to the eservice so the server can open the store
        eservice_client = __get_eservice_client__(state, options.save_file, options.enclave)
        kv.sync_to_block_store(eservice_client)

        params = {}
        params['encryption_key'] = kv.encryption_key
        params['state_hash'] = kv.hash_identity
        params['transfer_key'] = options.key
        message = invocation_request('kv_get', **params)
        result = send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)
        result = json.loads(result)

        # sync the server blocks get to the local block manager
        count = kv.sync_from_block_store(result, eservice_client)
        logger.debug("sync complete with %d blocks", count)

        with kv :
            value = kv.get(options.key)
            logger.debug("value: %s", value)

        if options.symbol :
            bindings.bind(options.symbol, value)

        return value

    # -------------------------------------------------------
    if options.command == 'set' :

        kv = KeyValueStore()
        with kv :
            kv.set(options.key, options.value)

        # push the blocks to the eservice so the server can open the store
        # local_block_store = pblocks.local_block_manager()
        eservice_client = __get_eservice_client__(state, options.save_file, options.enclave)
        kv.sync_to_block_store(eservice_client)

        params = {}
        params['encryption_key'] = kv.encryption_key
        params['state_hash'] = kv.hash_identity
        params['transfer_key'] = options.key
        message = invocation_request('kv_set', **params)
        send_to_contract(state, options.save_file, message, eservice_url=options.enclave, **extraparams)

        return
Exemplo n.º 8
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()
def __command_attestation__(state, bindings, pargs):
    """controller command to interact with an asset_type contract
    """

    parser = argparse.ArgumentParser(prog='attestation-test')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save_file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument('-l',
                           '--ledger-key',
                           help='ledger verifying key',
                           type=str)

    subparser = subparsers.add_parser('get_contract_metadata')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('get_contract_code_metadata')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('add_endpoint')
    subparser.add_argument('-c',
                           '--code-metadata',
                           help='contract code metadata',
                           type=invocation_parameter,
                           required=True)
    subparser.add_argument('-i',
                           '--contract-id',
                           help='contract identifier',
                           type=str,
                           required=True)
    subparser.add_argument('-l',
                           '--ledger-attestation',
                           help='attestation from the ledger',
                           type=invocation_parameter,
                           required=True)
    subparser.add_argument('-m',
                           '--contract-metadata',
                           help='contract metadata',
                           type=invocation_parameter,
                           required=True)

    subparser = subparsers.add_parser('generate_secret')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('send_secret')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('recv_secret')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('reveal_secret')
    subparser.add_argument(
        '-a',
        '--state-attestation',
        help='ledger signature for current state attestation',
        type=invocation_parameter,
        required=True)
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    # -------------------------------------------------------
    if options.command == 'initialize':
        message = invocation_request('initialize',
                                     ledger_verifying_key=options.ledger_key)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'get_contract_metadata':
        extraparams['commit'] = False
        message = invocation_request('get_contract_metadata')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'get_contract_code_metadata':
        extraparams['commit'] = False
        message = invocation_request('get_contract_code_metadata')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'add_endpoint':
        message = invocation_request(
            'add_endpoint',
            contract_id=options.contract_id,
            ledger_attestation=options.ledger_attestation,
            contract_metadata=options.contract_metadata,
            contract_code_metadata=options.code_metadata)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'generate_secret':
        message = invocation_request('generate_secret')
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'send_secret':
        return

    # -------------------------------------------------------
    if options.command == 'recv_secret':
        return

    # -------------------------------------------------------
    if options.command == 'reveal_secret':
        extraparams['commit'] = False
        message = invocation_request(
            'reveal_secret', ledger_signature=options.state_attestation)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return
Exemplo n.º 10
0
def __command_issuer__(state, bindings, pargs):
    """controller command to interact with an issuer contract
    """

    parser = argparse.ArgumentParser(prog='issuer')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save_file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get_verifying_key')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('get_balance')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('initialize')
    subparser.add_argument(
        '-t',
        '--type_id',
        help='contract identifier for the issuer asset type',
        type=str,
        required=True)
    subparser.add_argument(
        '-a',
        '--authority',
        help='serialized authority from the vetting organization',
        type=scheme_parameter,
        required=True)

    subparser = subparsers.add_parser('issue')
    subparser.add_argument('-o',
                           '--owner',
                           help='identity of the issuance owner; ECDSA key',
                           type=str,
                           required=True)
    subparser.add_argument('-c',
                           '--count',
                           help='amount of the issuance',
                           type=int,
                           required=True)

    subparser = subparsers.add_parser('transfer')
    subparser.add_argument('-n',
                           '--new_owner',
                           help='identity of the new owner; ECDSA key',
                           type=str,
                           required=True)
    subparser.add_argument('-c',
                           '--count',
                           help='amount to transfer',
                           type=int,
                           required=True)

    subparser = subparsers.add_parser('escrow')  # combine escrow & attestation
    subparser.add_argument('-a',
                           '--agent',
                           help='identity of the escrow agent',
                           type=str,
                           required=True)
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('disburse')
    subparser.add_argument('-a',
                           '--attestation',
                           help='Disburse attestation from the escrow agent',
                           type=scheme_parameter,
                           required=True)

    subparser = subparsers.add_parser('claim')
    subparser.add_argument('-a',
                           '--attestation',
                           help='Disburse attestation from the escrow agent',
                           type=scheme_parameter,
                           required=True)

    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    # -------------------------------------------------------
    if options.command == 'get_verifying_key':
        extraparams['commit'] = False
        message = invocation_request('get-verifying-key')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'get_balance':
        extraparams['commit'] = False
        message = invocation_request('get-balance')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'initialize':
        message = invocation_request('initialize', options.type_id,
                                     options.authority)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'issue':
        message = invocation_request('issue', options.owner, options.count)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'transfer':
        message = invocation_request('transfer', options.new_owner,
                                     options.count)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'escrow':
        extraparams['commit'] = True
        extraparams['wait'] = True
        message = invocation_request('escrow', options.agent)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)

        extraparams['commit'] = False
        extraparams['wait'] = False
        message = invocation_request('escrow-attestation')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, result)
        return

    # -------------------------------------------------------
    if options.command == 'disburse':
        assert type(options.attestation) is list
        dependencies = options.attestation[0]
        signature = options.attestation[1]
        message = invocation_request('disburse', dependencies, signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    # -------------------------------------------------------
    if options.command == 'claim':
        assert type(options.attestation) is list
        old_owner_identity = options.attestation[0]
        dependencies = options.attestation[1]
        signature = options.attestation[2]
        message = invocation_request('claim', old_owner_identity, dependencies,
                                     signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return
Exemplo n.º 11
0
def __command_integer_key__(state, bindings, pargs):
    """controller command to interact with an integer-key contract
    """

    parser = argparse.ArgumentParser(prog='integer_key')
    parser.add_argument('-e',
                        '--enclave',
                        help='URL of the enclave service to use',
                        type=str)
    parser.add_argument('-f',
                        '--save-file',
                        help='File where contract data is stored',
                        type=str)
    parser.add_argument('-q',
                        '--quiet',
                        help='Suppress printing the result',
                        action='store_true')
    parser.add_argument('-w',
                        '--wait',
                        help='Wait for the transaction to commit',
                        action='store_true')

    subparsers = parser.add_subparsers(dest='command')

    subparser = subparsers.add_parser('get_state')

    subparser = subparsers.add_parser('get_signing_key')
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('create')
    subparser.add_argument('-k',
                           '--key',
                           help='key to create',
                           type=str,
                           required=True)
    subparser.add_argument('-v',
                           '--value',
                           help='initial value to give to the key',
                           type=int,
                           default=0)

    subparser = subparsers.add_parser('inc')
    subparser.add_argument('-k',
                           '--key',
                           help='key to increment',
                           type=str,
                           required=True)
    subparser.add_argument('-v',
                           '--value',
                           help='initial value to give to the key',
                           type=int,
                           required=True)

    subparser = subparsers.add_parser('dec')
    subparser.add_argument('-k',
                           '--key',
                           help='key to decrement',
                           type=str,
                           required=True)
    subparser.add_argument('-v',
                           '--value',
                           help='initial value to give to the key',
                           type=int,
                           required=True)

    subparser = subparsers.add_parser('get')
    subparser.add_argument('-k',
                           '--key',
                           help='key to retrieve',
                           type=str,
                           required=True)
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('transfer')
    subparser.add_argument('-k',
                           '--key',
                           help='key to transfer',
                           type=str,
                           required=True)
    subparser.add_argument('-o',
                           '--owner',
                           help='identity to transfer ownership',
                           type=str,
                           required=True)

    subparser = subparsers.add_parser('escrow')
    subparser.add_argument('-k',
                           '--key',
                           help='key to escrow',
                           type=str,
                           required=True)
    subparser.add_argument('-a',
                           '--agent',
                           help='identity of the escrow agent',
                           type=str,
                           required=True)

    subparser = subparsers.add_parser('attestation')
    subparser.add_argument('-k',
                           '--key',
                           help='key to escrow',
                           type=str,
                           required=True)
    subparser.add_argument('-s',
                           '--symbol',
                           help='binding symbol for result',
                           type=str)

    subparser = subparsers.add_parser('disburse')
    subparser.add_argument('-a',
                           '--attestation',
                           help='disburse attestation from escrow agent',
                           type=invocation_parameter,
                           required=True)

    subparser = subparsers.add_parser('exchange')
    subparser.add_argument('-a',
                           '--attestation',
                           help='exchange attestation from escrow agent',
                           type=invocation_parameter,
                           required=True)

    options = parser.parse_args(pargs)

    extraparams = {'quiet': options.quiet, 'wait': options.wait}

    if options.command == 'get_state':
        extraparams['quiet'] = True
        message = invocation_request('get-state')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        __dump_state__(result)
        return

    if options.command == 'get_signing_key':
        message = invocation_request('get-public-signing-key')
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if result and options.symbol:
            bindings.bind(options.symbol, result)
        return

    if options.command == 'create':
        message = invocation_request('create', options.key, options.value)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'inc':
        message = invocation_request('inc', options.key, options.value)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'dec':
        message = invocation_request('dec', options.key, options.value)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'get':
        extraparams['commit'] = False
        message = invocation_request('get-value', options.key)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, result)
        return

    if options.command == 'transfer':
        message = invocation_request('transfer-ownership', options.key,
                                     options.owner)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'escrow':
        message = invocation_request('escrow', options.key, options.agent)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'attestation':
        message = invocation_request('escrow-attestation', options.key)
        result = send_to_contract(state,
                                  options.save_file,
                                  message,
                                  eservice_url=options.enclave,
                                  **extraparams)
        if options.symbol:
            bindings.bind(options.symbol, json.dumps(result))
        return

    if options.command == 'disburse':
        assert type(options.attestation) is list
        assert len(options.attestation) == 3

        bidinfo = dict(options.attestation[0])
        assetkey = bidinfo['key']
        dependencies = options.attestation[1]
        signature = options.attestation[2]
        message = invocation_request('disburse', assetkey, dependencies,
                                     signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return

    if options.command == 'exchange':
        assert type(options.attestation) is list
        assert len(options.attestation) == 4

        offered = dict(options.attestation[0])['key']
        maxbid = dict(options.attestation[1])['key']
        dependencies = options.attestation[2]
        signature = options.attestation[3]
        message = invocation_request('exchange-ownership', offered, maxbid,
                                     dependencies, signature)
        send_to_contract(state,
                         options.save_file,
                         message,
                         eservice_url=options.enclave,
                         **extraparams)
        return