def create_from_file(cls,
                         report_name,
                         search_path=['.', '..', './contracts']):
        """Create a code object from a wawaka-aot source file

        :param report_name str: the name of the compilation report file
        :param search_path list of str: directories to search for the source file
        """
        if report_name.endswith('.b64'):
            # we may get the full file path for the contract as the report name
            # so drop the extension, so we actually find and load the report file
            report_name = os.path.basename(report_name)  # only works on Linux
            report_name = report_name[:-4]
        basename = putils.build_simple_file_name(report_name, extension='.cdi')
        filename = putils.find_file_in_path(basename, search_path)
        logger.debug('load wawaka-aot compilation report from %s', filename)
        # file is json-encoded
        with open(filename, "r") as rfile:
            contents = rfile.read()
        contents = contents.rstrip('\0')
        report = json.loads(contents)

        logger.debug('loaded report %s', json.dumps(report))

        return cls.init_from_dict(report)
Exemplo n.º 2
0
    def create_from_file(cls,
                         name,
                         source_name=None,
                         search_path=['.', '..', './contracts'],
                         interpreter='gipsy',
                         compilation_report=None):
        """Create a code object from a Gipsy source file

        :param name str: the name of the scheme contract class
        :param source_name str: the name of the source file
        :param search_path list of str: directories to search for the source file
        """
        if source_name is None:
            source_name = name
        basename = putils.build_simple_file_name(
            source_name, extension=cls.__extension__[interpreter])
        filename = putils.find_file_in_path(basename, search_path)
        logger.debug('load %s contract from %s', interpreter, filename)

        with open(filename, "r") as cfile:
            code = cfile.read()

        report = compilation_report
        if interpreter == 'wawaka-aot' and report is None:
            report = ContractCompilationReport.create_from_file(
                source_name, search_path)

        return cls(code, name, compilation_report=report)
Exemplo n.º 3
0
    def create_from_scheme_file(cls, name, source_name = None, search_path = ['.', '..', './contracts']) :
        """Create a code object from a Gipsy source file

        :param name str: the name of the scheme contract class
        :param source_name str: the name of the source file
        :param search_path list of str: directories to search for the source file
        """
        if source_name is None :
            source_name = name
        basename = putils.build_simple_file_name(source_name, extension=cls.__extension__)
        filename = putils.find_file_in_path(basename, search_path)
        with open(filename, "r") as cfile :
            code = cfile.read()

        return cls(code, name)
Exemplo n.º 4
0
    def create_from_file(cls, name, source_name = None, search_path = ['.', '..', './contracts'], interpreter=None) :
        """Create a code object from a Gipsy source file

        :param name str: the name of the scheme contract class
        :param source_name str: the name of the source file
        :param search_path list of str: directories to search for the source file
        """
        if source_name is None :
            source_name = name
        if interpreter is None :
            interpreter = os.environ.get("PDO_INTERPRETER", "wawaka")

        basename = putils.build_simple_file_name(source_name, extension=cls.__extension__[interpreter])
        filename = putils.find_file_in_path(basename, search_path)
        logger.debug('load %s contract from %s', interpreter, filename)

        with open(filename, "r") as cfile :
            code = cfile.read()

        return cls(code, name)
Exemplo n.º 5
0
def Main():
    global use_ledger
    global use_eservice
    global use_pservice

    # parse out the configuration file first
    conffiles = ['pcontract.toml', 'enclave.toml']
    confpaths = [".", "./etc", ContractEtc]

    parser = argparse.ArgumentParser()

    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument(
        '--config-dir',
        help='directories to search for the configuration file',
        nargs='+')

    parser.add_argument('-i',
                        '--identity',
                        help='Identity to use for the process',
                        default='test-request',
                        type=str)

    parser.add_argument(
        '--logfile',
        help='Name of the log file, __screen__ for standard output',
        type=str)
    parser.add_argument('--loglevel', help='Logging level', type=str)

    parser.add_argument('--ledger',
                        help='URL for the Sawtooth ledger',
                        type=str)
    parser.add_argument('--no-ledger',
                        help='Do not attempt ledger registration',
                        action="store_true")

    parser.add_argument('--data-dir',
                        help='Directory for storing generated files',
                        type=str)
    parser.add_argument('--source-dir',
                        help='Directories to search for contract source',
                        nargs='+',
                        type=str)
    parser.add_argument('--key-dir',
                        help='Directories to search for key files',
                        nargs='+')

    parser.add_argument('--eservice-url',
                        help='List of enclave service URLs to use',
                        nargs='+')
    parser.add_argument('--randomize-eservice',
                        help="Randomize eservice used for each update",
                        action="store_true")

    parser.add_argument('--pservice-url',
                        help='List of provisioning service URLs to use',
                        nargs='+')

    parser.add_argument('--block-store',
                        help='Name of the file where blocks are stored',
                        type=str)

    parser.add_argument('--secret-count',
                        help='Number of secrets to generate',
                        type=int,
                        default=3)
    parser.add_argument('--contract',
                        help='Name of the contract to use',
                        default='mock-contract')
    parser.add_argument('--interpreter',
                        help='Name of the contract to to require',
                        default=ContractInterpreter)
    parser.add_argument('--expressions',
                        help='Name of a file to read for expressions',
                        default=None)

    parser.add_argument(
        '--num-provable-replicas',
        help='Number of sservice signatures needed for proof of replication',
        type=int,
        default=1)
    parser.add_argument(
        '--availability-duration',
        help=
        'duration (in seconds) for which the replicas are stored at storage service',
        type=int,
        default=60)

    options = parser.parse_args()

    # first process the options necessary to load the default configuration
    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    # customize the configuration file for the current request
    global config_map

    config_map['identity'] = options.identity

    if options.data_dir:
        config_map['data'] = options.data_dir

    config_map['contract'] = options.contract

    # parse the configuration file
    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths,
                                                   config_map)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    # set up the logging configuration
    if config.get('Logging') is None:
        config['Logging'] = {'LogFile': '__screen__', 'LogLevel': 'INFO'}
    if options.logfile:
        config['Logging']['LogFile'] = options.logfile
    if options.loglevel:
        config['Logging']['LogLevel'] = options.loglevel.upper()

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    # set up the ledger configuration
    if config.get('Sawtooth') is None:
        config['Sawtooth'] = {
            'LedgerURL': 'http://localhost:8008',
        }
    if options.ledger:
        config['Sawtooth']['LedgerURL'] = options.ledger
    if options.no_ledger or not config['Sawtooth']['LedgerURL']:
        use_ledger = False
        config.pop('Sawtooth', None)

    # set up the key search paths
    if config.get('Key') is None:
        config['Key'] = {
            'SearchPath': ['.', './keys', ContractKeys],
            'FileName': options.identity + ".pem"
        }
    if options.key_dir:
        config['Key']['SearchPath'] = options.key_dir

    # set up the service configuration
    if config.get('Service') is None:
        config['Service'] = {
            'EnclaveServiceURLs': [],
            'ProvisioningServiceURLs': [],
            'EnclaveServiceDatabaseFile': None,
            'Randomize_Eservice': False
        }

    if options.randomize_eservice:
        config['Service']['Randomize_Eservice'] = True
    else:
        config['Service']['Randomize_Eservice'] = False
    if options.eservice_url:
        use_eservice = True
        config['Service']['EnclaveServiceURLs'] = options.eservice_url
    if options.pservice_url:
        use_pservice = True
        config['Service']['ProvisioningServiceURLs'] = options.pservice_url

    # replication parameters
    if options.num_provable_replicas:
        config['Replication'][
            'NumProvableReplicas'] = options.num_provable_replicas
    if options.availability_duration:
        config['Replication']['Duration'] = options.availability_duration

    # set up the data paths
    if config.get('Contract') is None:
        config['Contract'] = {
            'DataDirectory':
            ContractData,
            'SourceSearchPath':
            [".", "./contract",
             os.path.join(ContractHome, 'contracts')]
        }

    if config['Contract'].get('Name') is None:
        config['Contract']['Name'] = options.contract
        config['Contract']['SourceFile'] = '_{0}'.format(options.contract)

    config['Contract']['Interpreter'] = options.interpreter

    if options.data_dir:
        config['Contract']['DataDirectory'] = options.data_dir
    if options.source_dir:
        config['Contract']['SourceSearchPath'] = options.source_dir

    putils.set_default_data_directory(config['Contract']['DataDirectory'])

    # set up the storage service configuration
    if config.get('StorageService') is None:
        config['StorageService'] = {
            'BlockStore':
            os.path.join(config['Contract']['DataDirectory'],
                         options.identity + '.mdb'),
        }
    if options.block_store:
        config['StorageService']['BlockStore'] = options.block_store

    config['secrets'] = options.secret_count

    if options.expressions:
        expression_file = options.expressions
    else:
        expression_file = putils.build_simple_file_name(
            options.contract, '.exp')

    try:
        config['expressions'] = putils.find_file_in_path(
            expression_file, ['.', '..', 'tests'])
    except FileNotFoundError as fe:
        logger.error('unable to locate expression file "%s"', expression_file)
        sys.exit(-1)

    LocalMain(config)
Exemplo n.º 6
0
def Main():
    global use_ledger
    global use_eservice
    global use_pservice

    import pdo.common.config as pconfig
    import pdo.common.logger as plogger

    # parse out the configuration file first
    conffiles = ['pcontract.toml', 'enclave.toml']
    confpaths = [".", "./etc", ContractEtc]

    parser = argparse.ArgumentParser()

    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument(
        '--config-dir',
        help='directories to search for the configuration file',
        nargs='+')

    parser.add_argument('-i',
                        '--identity',
                        help='Identity to use for the process',
                        type=str)

    parser.add_argument(
        '--logfile',
        help='Name of the log file, __screen__ for standard output',
        type=str)
    parser.add_argument('--loglevel', help='Logging level', type=str)

    parser.add_argument('--ledger',
                        help='URL for the Sawtooth ledger',
                        type=str)
    parser.add_argument('--no-ledger',
                        help='Do not attempt ledger registration',
                        action="store_true")

    parser.add_argument('--data-dir',
                        help='Directory for storing generated files',
                        type=str)
    parser.add_argument('--source-dir',
                        help='Directories to search for contract source',
                        nargs='+',
                        type=str)
    parser.add_argument('--key-dir',
                        help='Directories to search for key files',
                        nargs='+')

    parser.add_argument('--eservice-url',
                        help='List of enclave service URLs to use',
                        nargs='+')
    parser.add_argument('--pservice-url',
                        help='List of provisioning service URLs to use',
                        nargs='+')

    parser.add_argument('--secret-count',
                        help='Number of secrets to generate',
                        type=int,
                        default=3)
    parser.add_argument('--contract',
                        help='Name of the contract to use',
                        default='integer-key')
    parser.add_argument('--expressions',
                        help='Name of a file to read for expressions',
                        default=None)

    options = parser.parse_args()

    # first process the options necessary to load the default configuration
    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    # customize the configuration file for the current request
    global config_map

    config_map['identity'] = 'test-request'
    if options.identity:
        config_map['identity'] = options.identity

    if options.data_dir:
        config_map['data'] = options.data_dir

    config_map['contract'] = options.contract

    # parse the configuration file
    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths,
                                                   config_map)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    # set up the logging configuration
    if config.get('Logging') is None:
        config['Logging'] = {'LogFile': '__screen__', 'LogLevel': 'INFO'}
    if options.logfile:
        config['Logging']['LogFile'] = options.logfile
    if options.loglevel:
        config['Logging']['LogLevel'] = options.loglevel.upper()

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    # set up the ledger configuration
    if config.get('Sawtooth') is None:
        config['Sawtooth'] = {
            'LedgerURL': 'http://localhost:8008',
        }
    if options.ledger:
        config['Sawtooth']['LedgerURL'] = options.ledger

    # set up the key search paths
    if config.get('Key') is None:
        config['Key'] = {
            'SearchPath': ['.', './keys', ContractKeys],
            'FileName': options.identity + ".pem"
        }
    if options.key_dir:
        config['Key']['SearchPath'] = options.key_dir

    # set up the service configuration
    if config.get('Service') is None:
        config['Service'] = {
            'EnclaveServiceURLs': [],
            'ProvisioningServiceURLs': []
        }
    if options.eservice_url:
        use_eservice = True
        config['Service']['EnclaveServiceURLs'] = options.eservice_url
    if options.pservice_url:
        use_pservice = True
        config['Service']['ProvisioningServiceURLs'] = options.pservice_url

    # set up the data paths
    if config.get('Contract') is None:
        config['Contract'] = {
            'DataDirectory':
            ContractData,
            'SourceSearchPath':
            [".", "./contract",
             os.path.join(ContractHome, 'contracts')]
        }

    if options.data_dir:
        config['Contract']['DataDirectory'] = options.data_dir
    if options.source_dir:
        config['Contract']['SourceSearchPath'] = options.source_dir

    putils.set_default_data_directory(config['Contract']['DataDirectory'])

    if options.no_ledger or not config['Sawtooth']['LedgerURL']:
        use_ledger = False
        config.pop('Sawtooth', None)

    config['secrets'] = options.secret_count

    if options.expressions:
        expression_file = options.expressions
    else:
        expression_file = putils.build_simple_file_name(
            options.contract, '.exp')

    try:
        config['expressions'] = putils.find_file_in_path(
            expression_file, ['.', '..', 'tests'])
    except FileNotFoundError as fe:
        logger.error('unable to locate expression file "%s"', expression_file)
        sys.exit(-1)

    LocalMain(config)