diff --git a/examples/cactus-example-discounted-asset-trade/package.json b/examples/cactus-example-discounted-asset-trade/package.json index bfcdc76187..9c48089582 100644 --- a/examples/cactus-example-discounted-asset-trade/package.json +++ b/examples/cactus-example-discounted-asset-trade/package.json @@ -10,8 +10,7 @@ "build": "npm run build-ts && npm run build:dev:backend:postbuild", "build-ts": "tsc", "build:dev:backend:postbuild": "cp -f ../../yarn.lock ./dist/", - "build_pip_indy_package": "cd ../../packages-python/cactus_validator_socketio_indy && python3 setup.py bdist_wheel", - "start": "npm run build_pip_indy_package && docker-compose build && docker-compose up", + "start": "docker-compose build && docker-compose up", "start-dockerless": "node ./dist/www.js" }, "dependencies": { diff --git a/packages-python/cactus_validator_socketio_indy/.gitignore b/packages-python/cactus_validator_socketio_indy/.gitignore deleted file mode 100644 index 2d711bb5b4..0000000000 --- a/packages-python/cactus_validator_socketio_indy/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -CactusValidatorSocketIOIndy.egg-info/ -testcli/connector.crt \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/Dockerfile b/packages-python/cactus_validator_socketio_indy/Dockerfile deleted file mode 100644 index 8f601ea27a..0000000000 --- a/packages-python/cactus_validator_socketio_indy/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -FROM ghcr.io/hyperledger/indy-node-container/indy_node:1.12.6-ubuntu18-main - -USER root -RUN apt-get update \ - && apt-get install -y supervisor \ - && rm -rf /var/lib/apt/lists/* - -USER indy -WORKDIR /home/indy -COPY --chown=indy:indy './dist/CactusValidatorSocketIOIndy-0.0.1-py3-none-any.whl' '/home/indy' -RUN pip3 install /home/indy/CactusValidatorSocketIOIndy-0.0.1-py3-none-any.whl - -USER root -RUN python3 /home/indy/.local/lib/python3.8/site-packages/other/post_install_script.py - -USER indy -ARG pool_ip=172.16.0.2 -ENV TEST_POOL_IP=$pool_ip - -CMD [ "/usr/bin/supervisord" ] diff --git a/packages-python/cactus_validator_socketio_indy/README.md b/packages-python/cactus_validator_socketio_indy/README.md deleted file mode 100644 index 76d4afbad4..0000000000 --- a/packages-python/cactus_validator_socketio_indy/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# Indy Validator - -- Cactus socketio validator to integrate with Hyperledger Indy - -## Build - -- By default, it assumes that indy pool is available at `172.16.0.2` -- You can modify this behavior by editing `Dockerfile` or by setting arg `pool_ip` - -``` -./setup_indy.sh -``` - -## Updating the dependencies - -- When updating depedency in `requirements.txt` make sure that it's dependencies are updated as well. -- Make sure you update the package version in `setup.py` as well. -- After each update build and run container to ensure it still works. -- Follow this process when updating the package: - -```bash - # Go to package dir - cd packages-python/cactus_validator_socketio_indy/validator-python - - # Setup venv and install core dependencies - python3 -m venv .venv - source .venv/bin/activate - pip install --upgrade setuptools wheel - pip install Flask==2.3.2 Flask-SocketIO==5.1.1 PyJWT==2.4.0 PyYAML==5.4.1 python3-indy==1.16.0 eventlet==0.31.1 cryptography==41.0.3 - - # Freeze current package listing - pip freeze > requirements.txt - - # Copy the contents of requirements.txt to setup.py install_requires list (adjust formatting accordingly). -``` - -## Manual Test - -- Validator used by `cactus-example-discounted-asset-trade` sample app. diff --git a/packages-python/cactus_validator_socketio_indy/config/node-settings.yaml b/packages-python/cactus_validator_socketio_indy/config/node-settings.yaml deleted file mode 100644 index ae36e343f0..0000000000 --- a/packages-python/cactus_validator_socketio_indy/config/node-settings.yaml +++ /dev/null @@ -1,2 +0,0 @@ -port: 8000 -logging_dir: "" \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/config/node-validator-registry.yaml b/packages-python/cactus_validator_socketio_indy/config/node-validator-registry.yaml deleted file mode 100644 index 9e87144846..0000000000 --- a/packages-python/cactus_validator_socketio_indy/config/node-validator-registry.yaml +++ /dev/null @@ -1,3 +0,0 @@ -proto: "" -url: "" -publickey: "" \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/config/validator-001-secrets.yaml b/packages-python/cactus_validator_socketio_indy/config/validator-001-secrets.yaml deleted file mode 100644 index 6ce11b1ec5..0000000000 --- a/packages-python/cactus_validator_socketio_indy/config/validator-001-secrets.yaml +++ /dev/null @@ -1,2 +0,0 @@ -sign_key: "" -auth_credential: "" \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/config/validator-001-settings.yaml b/packages-python/cactus_validator_socketio_indy/config/validator-001-settings.yaml deleted file mode 100644 index dcb824b19a..0000000000 --- a/packages-python/cactus_validator_socketio_indy/config/validator-001-settings.yaml +++ /dev/null @@ -1 +0,0 @@ -port: 8000 \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/post_install_script.py b/packages-python/cactus_validator_socketio_indy/post_install_script.py deleted file mode 100644 index 8e9159a8c2..0000000000 --- a/packages-python/cactus_validator_socketio_indy/post_install_script.py +++ /dev/null @@ -1,104 +0,0 @@ -import os -import shutil - - -def __copy(source: str, destination: str) -> bool: - """Copy given content from source to destination""" - - # Check if source exists - check_source_file = os.path.isfile(source) - check_source_dir = os.path.isdir(source) - - if not check_source_dir and not check_source_file: - print(f'Provided source location: {source} does not exist') - return False - - # Check if destination exists - # If not, create destination - if not os.path.isdir(destination): - print(f'Provided destination: {destination} does not exist. Creating...') - try: - os.makedirs(destination) - except Exception as mkdir_err: - print(mkdir_err) - return False - - # Copy file - if check_source_file: - file_name = os.path.basename(source) - - if os.path.isfile(f'{destination}/{file_name}'): - print(f'File {file_name} already exists in destination {destination}. Removing old one...') - try: - os.remove(f'{destination}/{file_name}') - except Exception as remove_err: - print(remove_err) - return False - try: - shutil.copyfile(src=source, dst=f'{destination}/{file_name}') - except Exception as copyfile_err: - print(copyfile_err) - return False - - # Copy dir - if check_source_dir: - try: - shutil.copytree(src=source, dst=destination, dirs_exist_ok=True) - except Exception as copytree_err: - print(copytree_err) - return False - - return True - - -# Execute script -if __name__ == '__main__': - - # Destination dirs - CONFIG_DST_DIR = '/etc/cactus-indy' - INDY_HOME_DIR = '/home/indy' - VALIDATOR_DST_DIR = f'{INDY_HOME_DIR}/validator-python' - SUPERVISORD_DST_DIR = '/etc' - UTILS_LOCATION = f'{INDY_HOME_DIR}/from-indy-sdk' - SITE_PACKAGES = f'{INDY_HOME_DIR}/.local/lib/python3.8/site-packages' - - # Copy configs - if __copy(source=f'{SITE_PACKAGES}/validator_socketio_indy', destination=CONFIG_DST_DIR): - print('Configs successfully copied') - - # Copy validator - if __copy(source=f'{SITE_PACKAGES}/validator-python', destination=VALIDATOR_DST_DIR): - print('Validator successfully copied') - - # Copy supervisord.conf file - if __copy(source=f'{SITE_PACKAGES}/other/supervisord.conf', destination='/etc'): - print('supervisord file successfully copied') - - # Copy utils.py - if __copy(source=f'{UTILS_LOCATION}/utils.py', - destination=f'{VALIDATOR_DST_DIR}/validator_socketio_module'): - print('utils file successfully copied') - - print('Copying done') - - # Cleanup - files_to_remove = [ - f'{SITE_PACKAGES}/validator_socketio_indy', - f'{SITE_PACKAGES}/validator-python', - f'{SITE_PACKAGES}/other', - f'{INDY_HOME_DIR}/CactusValidatorSocketIOIndy-0.0.1-py3-none-any.whl', - f'{SITE_PACKAGES}/CactusValidatorSocketIOIndy-0.0.1.dist-info' - ] - - for file in files_to_remove: - try: - if os.path.isfile(file): - os.remove(file) - else: - shutil.rmtree(file) - except Exception as err: - print(err) - else: - print(f'Cleaning of {file} successfully ended') - - print('Cleaning done') diff --git a/packages-python/cactus_validator_socketio_indy/setup.py b/packages-python/cactus_validator_socketio_indy/setup.py deleted file mode 100644 index 66b8b51964..0000000000 --- a/packages-python/cactus_validator_socketio_indy/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -import codecs -import os - -from setuptools import setup - -here = os.path.abspath(os.path.dirname(__file__)) - -with codecs.open(os.path.join(here, 'README.md'), encoding="utf-8") as fh: - LONG_DESCRIPTION = f'/n{fh.read()}' - -VERSION = '0.0.1' -DESCRIPTION = 'Python Cactus Validator Indy' - -WHL_VALIDATOR_DIR = '/validator-python' -WHL_VALIDATOR_CONFIG_DIR = '/validator_socketio_indy' -WHL_OTHER_FILES_DIR = '/other' - -WHL_LOCAL_SOCKET_IO_MODULE_DIR = f'{WHL_VALIDATOR_DIR}/validator_socketio_module' - -LOCAL_CONFIG_DIR = './config' - -setup( - name='CactusValidatorSocketIOIndy', - version=VERSION, - description=DESCRIPTION, - long_description_content_type='text/markdown', - long_description=LONG_DESCRIPTION, - data_files=[ - ( - WHL_VALIDATOR_DIR, [ - f'.{WHL_VALIDATOR_DIR}/main.py' - ], - ), - ( - WHL_LOCAL_SOCKET_IO_MODULE_DIR, [ - f'.{WHL_LOCAL_SOCKET_IO_MODULE_DIR}/__init__.py', - f'.{WHL_LOCAL_SOCKET_IO_MODULE_DIR}/AbstractConnector.py', - f'.{WHL_LOCAL_SOCKET_IO_MODULE_DIR}/IndyConnector.py', - f'.{WHL_LOCAL_SOCKET_IO_MODULE_DIR}/Settings.py', - f'.{WHL_LOCAL_SOCKET_IO_MODULE_DIR}/SocketIoValidator.py' - ] - ), - ( - WHL_VALIDATOR_CONFIG_DIR, [ - f'{LOCAL_CONFIG_DIR}/node-settings.yaml', - f'{LOCAL_CONFIG_DIR}/node-validator-registry.yaml', - f'{LOCAL_CONFIG_DIR}/validator-001-secrets.yaml', - f'{LOCAL_CONFIG_DIR}/validator-001-settings.yaml' - ] - ), - ( - WHL_OTHER_FILES_DIR, [ - './supervisord.conf', - './post_install_script.py' - ] - ) - ], - author='Cactus Contributors', - author_email='...', - include_package_data=True, - url='https://github.com/hyperledger/cactus/tree/main/packages-python/cactus_validator_socketio_indy', - install_requires=[ - 'base58==2.1.1', - 'bidict==0.22.1', - 'blinker==1.6.2', - ' cffi==1.15.1', - 'click==8.1.6', - 'cryptography==41.0.6', - 'dnspython==1.16.0', - 'eventlet==0.31.1', - 'Flask==2.3.2', - 'Flask-SocketIO==5.1.1', - 'greenlet==2.0.2', - 'importlib-metadata==6.8.0', - 'itsdangerous==2.1.2', - 'Jinja2==3.1.3', - 'MarkupSafe==2.1.3', - 'pycparser==2.21', - 'PyJWT==2.4.0', - 'python-engineio==4.5.1', - 'python-socketio==5.8.0', - 'python3-indy==1.16.0', - 'PyYAML==5.4.1', - 'six==1.16.0', - 'Werkzeug==3.0.1', - 'zipp==3.16.2' - ], - classifiers=[ - 'Development Status :: Initial version', - 'Programming Language :: Python :: 3', - 'Intended Audience :: Developers' - ] -) \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/setup_indy.sh b/packages-python/cactus_validator_socketio_indy/setup_indy.sh deleted file mode 100755 index 8dbfdb10bd..0000000000 --- a/packages-python/cactus_validator_socketio_indy/setup_indy.sh +++ /dev/null @@ -1,7 +0,0 @@ -set -e - -echo "Building pip package for Indy validator" -python3 setup.py bdist_wheel - -echo "Create image" -docker build . -t indy-validator \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/supervisord.conf b/packages-python/cactus_validator_socketio_indy/supervisord.conf deleted file mode 100644 index 624f920ffe..0000000000 --- a/packages-python/cactus_validator_socketio_indy/supervisord.conf +++ /dev/null @@ -1,20 +0,0 @@ -[supervisord] -logfile = /tmp/supervisord.log -logfile_maxbytes = 50MB -logfile_backups=10 -logLevel = debug -pidfile = /tmp/supervisord.pid -nodaemon = true -minfds = 1024 -minprocs = 200 -umask = 022 -user = indy -identifier = supervisor -directory = /tmp -nocleanup = true -childlogdir = /tmp -strip_ansi = false - -[program:validator] -command=/bin/bash -c 'echo start-server && python3 main.py' -directory=/home/indy/validator-python diff --git a/packages-python/cactus_validator_socketio_indy/testcli/.gitignore b/packages-python/cactus_validator_socketio_indy/testcli/.gitignore deleted file mode 100644 index 483a9c42c3..0000000000 --- a/packages-python/cactus_validator_socketio_indy/testcli/.gitignore +++ /dev/null @@ -1 +0,0 @@ -package-lock.json \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/testcli/package.json b/packages-python/cactus_validator_socketio_indy/testcli/package.json deleted file mode 100644 index cad1141ad5..0000000000 --- a/packages-python/cactus_validator_socketio_indy/testcli/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "testcli", - "license": "Apache-2.0", - "version": "0.0.0", - "private": true, - "dependencies": { - "jsonwebtoken": "8.5.1", - "socket.io-client-fixed-types": "4.5.4" - } -} diff --git a/packages-python/cactus_validator_socketio_indy/testcli/testsock.js b/packages-python/cactus_validator_socketio_indy/testcli/testsock.js deleted file mode 100644 index 1e92264324..0000000000 --- a/packages-python/cactus_validator_socketio_indy/testcli/testsock.js +++ /dev/null @@ -1,149 +0,0 @@ -const fs = require("fs"); -const jwt = require("jsonwebtoken"); -const { exit } = require("process"); -const io = require("socket.io-client-fixed-types"); - -const url = "http://localhost:10080"; -const socket = io(url, { - //transports: [ 'websocket', 'polling'] -}); - -const proofFilePath = "/etc/cactus/validator_socketio_indy/myproof.json"; -const crtPath = "connector.crt"; -const paramAlgorithm = "ES256"; - -socket.on("connect", () => { - console.log("connect"); - console.log(socket.id); - const transport = socket.io.engine.transport.name; - console.log(transport); - //socket.emit('mymessage', 'hoge'); -}); - -socket.on("mymessage", () => { - console.log("received mymessage"); -}); - -socket.on("response", (result) => { - console.log(`#[recv]response, res: ${result}`); - responseFlag = true; - decodeFunc(result.resObj.data) - .then(() => { - console.log("OK - Done."); - exit(0); - }) - .catch(() => { - console.log("Decode ERROR - Abort."); - exit(1); - }); -}); - -const verify = (signature) => - new Promise((resolve, reject) => { - const publicKey = fs.readFileSync(crtPath); - - const option = { - algorithms: paramAlgorithm, - }; - - jwt.verify(signature, publicKey, option, (err, decoded) => { - if (err) { - console.log(`Authentication NG : error = ${err}`); - reject(err); - } else { - console.log("Authentication OK"); - resolve(decoded); - } - }); - }); - -const decodeFunc = async (signsignature) => { - try { - console.log("call verify()"); - console.log(`##signsignature: ${signsignature}`); - const decoded = await verify(signsignature); - console.log("##decoded:", decoded); - } catch (err) { - console.log(`err: ${err}`); - } -}; - -// socket.emit('nop'); -socket.emit("startMonitor"); - -socket.emit("test-event"); - -setTimeout(() => { - console.log("call nop!"); - socket.emit("nop"); -}, 1000); - -setTimeout(() => { - console.log("call request2. get schema request."); - - let proofJson; - try { - let input_obj = JSON.parse(fs.readFileSync(proofFilePath)); - proofJson = JSON.parse(input_obj["proof"]); - } catch (err) { - console.error( - "Error while reading proof and proof request. returning false.", - ); - return false; - } - - did = null; - - let identifiers = proofJson["identifiers"]; - for (let referent of Object.keys(identifiers)) { - let item = identifiers[referent]; - let args_request_getSchema = { did: did, schemaId: item["schema_id"] }; - - // Call Validator - const requestData = { - contract: { channelName: "mychannel", contractName: "indysomething" }, - method: { type: "evaluateTransaction", command: "get_schema" }, - args: { args: args_request_getSchema }, - reqID: "reqID_test", - }; - - socket.emit("request2", requestData); - } -}, 2000); - -/* -setTimeout(() => { - console.log('call request2. args_schema request.'); - - args_schema = "{\"reqId\":1625126127546406478,\"identifier\":\"FVb5jZqvKmr15RgWrNpvjb\",\"operation\":{\"type\":\"107\",\"dest\":\"LXipD5CTqVsZDwm5xieomb\",\"data\":{\"name\":\"Job-Certificate\",\"version\":\"0.2\"}},\"protocolVersion\":2}"; - - // Call Validator - const requestData = { - contract: {"channelName": "mychannel", "contractName": "indysomething"}, - method: {type: "evaluateTransaction", command: "indy_ledger_submit_request"}, - args: {args: args_schema}, - reqID: "reqID_test" - }; - - socket.emit('request2', requestData); - -}, 2000); - - -setTimeout(() => { - console.log('call request2. args_credential_definition request.'); - - args_credential_definition = "{\"reqId\":1625472309372025483,\"identifier\":\"D4NcMEBjGsSEKvoasMBbnj\",\"operation\":{\"type\":\"108\",\"ref\":14,\"signature_type\":\"CL\",\"origin\":\"WV4juMpjLxSroxy2tNuQ5g\",\"tag\":\"TAG1\"},\"protocolVersion\":2}"; - - // Call Validator - const requestData = { - contract: {"channelName": "mychannel", "contractName": "indysomething"}, - method: {type: "evaluateTransaction", command: "indy_ledger_submit_request"}, - args: {args: args_credential_definition}, - reqID: "reqID_test" - }; - - socket.emit('request2', requestData); - -}, 3000); -*/ diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/.gitignore b/packages-python/cactus_validator_socketio_indy/validator-python/.gitignore deleted file mode 100644 index 812051fcf6..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -__pycache__ -*.log -.venv -venv \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/main.py b/packages-python/cactus_validator_socketio_indy/validator-python/main.py deleted file mode 100644 index 331da8f990..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/main.py +++ /dev/null @@ -1,6 +0,0 @@ -from validator_socketio_module.SocketIoValidator import SocketIoValidator - -if __name__ == '__main__': - validator = SocketIoValidator() - validator.init_indy() - validator.run() diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/requirements.txt b/packages-python/cactus_validator_socketio_indy/validator-python/requirements.txt deleted file mode 100644 index 9617f76d5a..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/requirements.txt +++ /dev/null @@ -1,24 +0,0 @@ -base58==2.1.1 -bidict==0.22.1 -blinker==1.6.2 -cffi==1.15.1 -click==8.1.6 -cryptography==41.0.6 -dnspython==1.16.0 -eventlet==0.31.1 -Flask==2.3.2 -Flask-SocketIO==5.1.1 -greenlet==2.0.2 -importlib-metadata==6.8.0 -itsdangerous==2.1.2 -Jinja2==3.1.3 -MarkupSafe==2.1.3 -pycparser==2.21 -PyJWT==2.4.0 -python-engineio==4.5.1 -python-socketio==5.8.0 -python3-indy==1.16.0 -PyYAML==5.4.1 -six==1.16.0 -Werkzeug==3.0.1 -zipp==3.16.2 diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/AbstractConnector.py b/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/AbstractConnector.py deleted file mode 100644 index ef77d5f646..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/AbstractConnector.py +++ /dev/null @@ -1,46 +0,0 @@ -from abc import ABCMeta, abstractmethod - -class AbstractConnector: - @abstractmethod - def __init__(self): - pass - - @abstractmethod - def getValidatorInformation(self, validatorURL): - """Get the validator information including version, name, ID, and other information""" - pass - - @abstractmethod - def sendSignedTransaction(self, signedTransaction): - """Request a verifier to execute a ledger operation""" - pass - - @abstractmethod - def getBalance(self, address): - """Get balance of an account for native token on a leder""" - pass - - @abstractmethod - def execSyncFunction(self, address, funcName, args): - """Execute a synchronous function held by a smart contract""" - pass - - @abstractmethod - def startMonitor(self, clientId, cb): - """Request a validator to start monitoring ledger""" - pass - - @abstractmethod - def stopMonitor(self, clientId): - """Request a validator to stop monitoring ledger""" - pass - - @abstractmethod - def cb(self, callbackData): - """Callback function to call when receiving data from Ledger""" - pass - - @abstractmethod - def nop(self): - """Nop function for testing""" - pass diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/IndyConnector.py b/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/IndyConnector.py deleted file mode 100644 index c55d5db883..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/IndyConnector.py +++ /dev/null @@ -1,130 +0,0 @@ -from abc import ABCMeta, abstractmethod - -import json -import time -from indy import ledger -import asyncio - -from .AbstractConnector import AbstractConnector - -class IndyConnector(AbstractConnector): - def __init__(self, socketio, sessionid, indy_dic): - self.moduleName = "IndyConnector" - self.indy_dic = indy_dic - print(f"##{self.moduleName}.__init__") - - def getValidatorInformation(self, validatorURL): - """Get the validator information including version, name, ID, and other information""" - print(f"##{self.moduleName}.getValidatorInformation()") - - def sendSignedTransaction(self, signedTransaction): - """Request a verifier to execute a ledger operation""" - print(f"##{self.moduleName}.sendSignedTransaction()") - - def getBalance(self, address): - """Get balance of an account for native token on a leder""" - print(f"##{self.moduleName}.getBalance()") - - def execSyncFunction(self, address, funcName, args): - """Execute a synchronous function held by a smart contract""" - print(f"##{self.moduleName}.execSyncFunction()") - - command = args['method']['command'] - if command== 'indy_ledger_submit_request': - print(f"##execSyncFunction : args['args']['args'] : {args['args']['args']}") - # return self.load_schema_or_credential_definition(args['args']['args']) - - if command== 'get_schema' or command== 'get_cred_def': - print(f"##execSyncFunction get_schema_or_cred_def: args['args']['args'] : {args['args']['args']}") - resTuple = self.run_coroutine(self.get_schema_or_cred_def, command, args['args']['args']) - # resList = json.dumps(resTuple) - resJson = {"result": resTuple} - # resJson = {"data":str(resObj)} - print(f"##execSyncFunction resObj : {resJson}") - return resJson - - print(f"##{self.moduleName} unknown command : {command}") - return "unknown command." - - - def load_schema_or_credential_definition(self, args): - """Execute a synchronous function held by a smart contract""" - print(f"##{self.moduleName}.load_schema_or_credential_definition()") - - pool_handle = self.indy_dic['pool_handle'] - responseStr = self.run_coroutine_ensure_previous_request_applied(pool_handle, args, lambda response: response['result']['data'] is not None) - - print(f"##{self.moduleName}.responseStr: {responseStr}") - - response = json.loads(responseStr) - - return response - - def startMonitor(self, clientId, cb): - """Request a validator to start monitoring ledger""" - print(f"##{self.moduleName}.startMonitor()") - - def stopMonitor(self, clientId): - """Request a validator to stop monitoring ledger""" - print(f"##{self.moduleName}.stopMonitor()") - - def cb(self, callbackData): - """Callback function to call when receiving data from Ledger""" - print(f"##{self.moduleName}.cb()") - - def nop(self): - """Nop function for testing""" - print(f"##{self.moduleName}.nop()") - - def run_coroutine_ensure_previous_request_applied(self, pool_handle, checker_request, checker, loop=None): - if loop is None: - loop = asyncio.get_event_loop() - results = loop.run_until_complete(self.ensure_previous_request_applied(pool_handle, checker_request, checker)) - return results - - async def get_schema_or_cred_def(self, command, args): - print(f"##{self.moduleName}.get_schema_or_cred_def()") - - pool_handle = self.indy_dic['pool_handle'] - did = args["did"] - schema_id = args["schemaId"] - if command== 'get_schema': - response = await self.get_schema(pool_handle, did, schema_id) - elif command== 'get_cred_def': - response = await self.get_cred_def(pool_handle, did, schema_id) - - print(f"##get_schema_or_cred_def response : {response}") - - return response - - - async def ensure_previous_request_applied(self, pool_handle, checker_request, checker): - for _ in range(3): - response = json.loads(await ledger.submit_request(pool_handle, checker_request)) - try: - if checker(response): - return json.dumps(response) - except TypeError: - pass - time.sleep(5) - - async def get_schema(self, pool_handle, _did, schema_id): - print(f"##{self.moduleName}.get_schema()") - get_schema_request = await ledger.build_get_schema_request(_did, schema_id) - get_schema_response = await self.ensure_previous_request_applied( - pool_handle, get_schema_request, lambda response: response['result']['data'] is not None) - return await ledger.parse_get_schema_response(get_schema_response) - - async def get_cred_def(self, pool_handle, _did, cred_def_id): - print(f"##{self.moduleName}.get_cred_def()") - get_cred_def_request = await ledger.build_get_cred_def_request(_did, cred_def_id) - get_cred_def_response = \ - await self.ensure_previous_request_applied(pool_handle, get_cred_def_request, - lambda response: response['result']['data'] is not None) - return await ledger.parse_get_cred_def_response(get_cred_def_response) - - def run_coroutine(self, coroutine, command, args, loop=None): - if loop is None: - loop = asyncio.get_event_loop() - result = loop.run_until_complete(coroutine(command, args)) - return result \ No newline at end of file diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/Settings.py b/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/Settings.py deleted file mode 100644 index 030f85c6d3..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/Settings.py +++ /dev/null @@ -1,58 +0,0 @@ -import dataclasses -import yaml - -pathNodeSettings = "/etc/cactus-indy/node-settings.yaml" -pathNodeValidatorRegistry = "/etc/cactus-indy/node-validator-registry.yaml" -pathValidatorSettings = "/etc/cactus-indy/validator-001-settings.yaml" -pathValidatorSecrets = "/etc/cactus-indy/validator-001-secrets.yaml" - -#dataclass for validator--settings.yml -#data members should be equal to yml -@dataclasses.dataclass -class NodeSettings: - port: int - logging_dir: str - -#dataclass for validator--settings.yml -#data members should be equal to yml -@dataclasses.dataclass -class NodeValidatorRegistry: - proto: str - url: str - publickey: str - -#dataclass for validator--settings.yml -#data members should be equal to yml -@dataclasses.dataclass -class ValidatorSettings: - port: int - -#dataclass for validator--settings.yml -#data members should be equal to yml -@dataclasses.dataclass -class ValidatorSecrets: - sign_key: str - auth_credential: str - -@dataclasses.dataclass -class Settings: - nodeSettings: NodeSettings = None - nodeValidatorRegistry: NodeValidatorRegistry = None - validatorSettings: ValidatorSettings = None - validatorSecrets: ValidatorSecrets = None - - # this method is automatically implemented after generate object - def __post_init__(self): - - self.validatorSettings = ValidatorSettings(**(self.loadYaml(pathNodeSettings))) - self.validatorSettings = ValidatorSettings(**(self.loadYaml(pathNodeValidatorRegistry))) - self.validatorSettings = ValidatorSettings(**(self.loadYaml(pathValidatorSettings))) - self.validatorSettings = ValidatorSettings(**(self.loadYaml(pathValidatorSecrets))) - - - def loadYaml(self, yamlFilePath): - # load usersettings file - with open(pathValidatorSettings) as yamlFile: - yamlObj = yaml.safe_load(yamlFile) - - return yamlObj diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/SocketIoValidator.py b/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/SocketIoValidator.py deleted file mode 100644 index e17812e230..0000000000 --- a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/SocketIoValidator.py +++ /dev/null @@ -1,164 +0,0 @@ -from flask import Flask, render_template, request -from flask_socketio import SocketIO -import json -import time -import asyncio -import jwt - -# from indy import ledger, pool -from indy import pool -from indy.error import ErrorCode, IndyError -from .utils import get_pool_genesis_txn_path, PROTOCOL_VERSION - - -from .Settings import Settings -from .IndyConnector import IndyConnector - -class SocketIoValidator: - def __init__(self): - self.moduleName = 'SocketIoValidator' - self.the_cb = None - self.indy_dic = {} - - # load settings - self.settings = Settings() - - self.app = Flask(__name__) - self.app.config['SECRET_KEY'] = 'secret!' - # socketio = SocketIO(app) - - print(f'socket port: {self.settings.validatorSettings.port}') - - self.socketio = SocketIO(self.app, host='0.0.0.0', port=self.settings.validatorSettings.port, logger=True, engineio_logger=True) - - self.privateKeyFile = '/etc/cactus/validator_socketio_indy/CA/connector.priv' - self.algorithm = 'ES256' - - @self.socketio.on('connect') - def handle_connect(): - # print('on connect (sessionid: ' + request.sid + ')') - print(f'on connect (sessionid: {request.sid})') - self.session_dict[request.sid] = self.getValidatorInstance() - - @self.socketio.on('disconnect') - def handle_disconnect(): - print('on disconnect') - del self.session_dict[request.sid] - - @self.socketio.on('startMonitor') - def handle_startMonitor(): - print('on startMonitor') - clientId = None - cb = None - self.session_dict[request.sid].startMonitor(clientId, cb) - def the_cb(resp): return self.cb_helper(request.sid, resp) - - @self.socketio.on('stopMonitor') - def handle_stopMonitor(): - print('on startMonitor') - self.session_dict[request.sid].stopMonitor() - - @self.socketio.on('nop') - def handle_nop(): - print('received nop') - self.session_dict[request.sid].nop() - - @self.socketio.on('test-event') - def handle_event(): - self.session_dict[request.sid].cb('data-from-blockchain') - - @self.socketio.on('request2') - def handle_execSyncFunction(requestData): - print('received request2') - print(f"##requestData: {requestData}") - - result = self.session_dict[request.sid].execSyncFunction(None, None, requestData) - - resp_obj = self.build_res_obj(200, requestData["reqID"], result) - #respJson = json.dumps(resp_obj) - self.socketio.emit("response", resp_obj) - - self.session_dict = {} - - def build_res_obj(self, status_code, req_id, result): - - print(f"##build_res_obj result: {result}") - - signed_results = self.sign(result) - responseData = {} - res_obj = {} - res_obj["status"] = status_code - res_obj["data"] = signed_results - responseData["resObj"] = res_obj - if req_id is not None: - responseData["id"] = req_id - return responseData - - def run(self): - """Run Validator""" - # self.init_indy(); - self.socketio.run(self.app, host='0.0.0.0', port=self.settings.validatorSettings.port) - - def cb_helper(self, sessionid, answer): - print(f'cb helper: {self.session_dict[request.sid]}') - return self.session_dict[sessionid].cb(answer) - - def getValidatorInstance(self): - print(f'##called getValidatorInstance()') - return IndyConnector(self.socketio, request.sid, self.indy_dic) - - def sign(self, data): - """ sign data """ - print(f'##called sign()') - with open(self.privateKeyFile, 'br') as fh: - private_key = fh.read() - - # unique process for reqId in indy data - # data["result"]["reqId"] = str(data["result"]["reqId"]) - - print(f"raw data: {data}") - encoded_jwt = jwt.encode(data, private_key, algorithm="ES256") - print(f"encoded_jwt: {encoded_jwt}") - return encoded_jwt - - # for INDY - def init_indy(self): - """ Initialization process for INDY """ - print(f'##called init_indy()') - - self.run_coroutine(self.init_indy_pool) - self.run_coroutine(self.open_pool) - time.sleep(1) - - # for INDY - async def init_indy_pool(self): - pool_ = { - 'name': 'pool1' - } - print("Open Pool Ledger: {}".format(pool_['name'])) - pool_['genesis_txn_path'] = get_pool_genesis_txn_path(pool_['name']) - pool_['config'] = json.dumps({"genesis_txn": str(pool_['genesis_txn_path'])}) - - # Set protocol version 2 to work with Indy Node 1.4 - await pool.set_protocol_version(PROTOCOL_VERSION) - - try: - await pool.create_pool_ledger_config(pool_['name'], pool_['config']) - print('##init_indy_pool create pool ledger config completed') - except IndyError as ex: - if ex.error_code == ErrorCode.PoolLedgerConfigAlreadyExistsError: - pass - - # for INDY - async def open_pool(self): - # open the pool and get handler - # self.pool_handle = await pool.open_pool_ledger('pool1', None) - self.indy_dic['pool_handle'] = await pool.open_pool_ledger('pool1', None) - print(f"##{self.moduleName} set pool_handle.") - - # for INDY - def run_coroutine(self, coroutine, loop=None): - print(f'##called run_coroutine()') - if loop is None: - loop = asyncio.get_event_loop() - loop.run_until_complete(coroutine()) diff --git a/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/__init__.py b/packages-python/cactus_validator_socketio_indy/validator-python/validator_socketio_module/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tools/create-production-only-archive.ts b/tools/create-production-only-archive.ts index 55280ea5c1..a749d99f8c 100644 --- a/tools/create-production-only-archive.ts +++ b/tools/create-production-only-archive.ts @@ -63,7 +63,6 @@ export const DEFAULT_DELETE_INCLUDE_GLOBS = [ ".yarn/**", "./docs/**", "./images/**", - "./packages-python/**", "./tools/**", "./typings/**", "./whitepaper/**",