├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── buildproto.sh ├── requirements.txt ├── run_example_service.py ├── service ├── __init__.py ├── common.py ├── example_service.py └── service_spec │ └── example_service.proto ├── snetd_configs └── snetd.ropsten.json └── test_example_service.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # .proto compiled files 107 | service/service_spec/*.py 108 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | 3 | ARG git_owner="singnet" 4 | ARG git_branch="master" 5 | ARG snetd_version 6 | 7 | ENV SINGNET_REPOS=/opt/singnet 8 | 9 | RUN mkdir -p ${SINGNET_REPOS} 10 | 11 | RUN apt-get update && \ 12 | apt-get install -y \ 13 | curl \ 14 | nano \ 15 | git \ 16 | wget 17 | 18 | RUN apt-get install -y python3 python3-pip 19 | 20 | # SNET Daemon 21 | RUN SNETD_GIT_VERSION=`curl -s https://api.github.com/repos/singnet/snet-daemon/releases/latest | grep -oP '"tag_name": "\K(.*)(?=")' || echo "v3.1.6"` && \ 22 | SNETD_VERSION=${snetd_version:-${SNETD_GIT_VERSION}} && \ 23 | cd /tmp && \ 24 | wget https://github.com/singnet/snet-daemon/releases/download/${SNETD_VERSION}/snet-daemon-${SNETD_VERSION}-linux-amd64.tar.gz && \ 25 | tar -xvf snet-daemon-${SNETD_VERSION}-linux-amd64.tar.gz && \ 26 | mv snet-daemon-${SNETD_VERSION}-linux-amd64/snetd /usr/bin/snetd && \ 27 | rm -rf snet-daemon-* 28 | 29 | RUN cd ${SINGNET_REPOS} && \ 30 | git clone -b ${git_branch} https://github.com/${git_owner}/example-service.git && \ 31 | cd example-service && \ 32 | pip3 install -r requirements.txt && \ 33 | sh buildproto.sh 34 | 35 | WORKDIR ${SINGNET_REPOS}/example-service 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 SingularityNET 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # example-service 2 | 3 | Simple arithmetic service compatible with SingularityNET 4 | 5 | ## Getting Started 6 | 7 | ### Prerequisites 8 | 9 | * [Python 3.6.5](https://www.python.org/downloads/release/python-365/) 10 | 11 | ### Installing 12 | 13 | * Clone the git repository: 14 | 15 | ``` 16 | git clone https://github.com/singnet/example-service.git 17 | cd example-service 18 | ``` 19 | 20 | * Install the dependencies and compile the protobuf file: 21 | 22 | ``` 23 | pip3 install -r requirements.txt 24 | sh buildproto.sh 25 | ``` 26 | 27 | ### Running 28 | 29 | #### Standalone 30 | 31 | * Run the example service directly (without `SNET Daemon`): 32 | 33 | ``` 34 | python3 run_example_service.py --no-daemon 35 | ``` 36 | 37 | * To test it run the script: 38 | 39 | ``` 40 | python3 test_example_service.py 41 | ``` 42 | 43 | #### With SingularityNET Daemon 44 | 45 | ##### SingularityNET Daemon Configuration 46 | 47 | To get the `ORGANIZATION_ID` and `SERVICE_ID` you must have already published a service 48 | (check this [link](https://dev.singularitynet.io/tutorials/publish/)). 49 | 50 | Create the `SNET Daemon`'s config JSON file (`snetd.config.json`). 51 | 52 | ``` 53 | { 54 | "DAEMON_END_POINT": "__DAEMON_HOST__:__DAEMON_PORT__", 55 | "BLOCKCHAIN_NETWORK_SELECTED": "__NETWORK__", 56 | "IPFS_END_POINT": "http://ipfs.singularitynet.io:80", 57 | "PASSTHROUGH_ENDPOINT": "http://__SERVICE_GRPC_HOST__:__SERVICE_GRPC_PORT__", 58 | "ORGANIZATION_ID": "__ORGANIZATION_ID__", 59 | "SERVICE_ID": "__SERVICE_ID__", 60 | "PAYMENT_CHANNEL_STORAGE_SERVER": { 61 | "DATA_DIR": "/opt/singnet/etcd/__NETWORK__" 62 | }, 63 | "LOG": { 64 | "LEVEL": "debug", 65 | "OUTPUT": { 66 | "TYPE": "stdout" 67 | } 68 | } 69 | } 70 | ``` 71 | 72 | For example, using the Ropsten testnet, replace tags with: 73 | 74 | - `__DAEMON_HOST__:__DAEMON_PORT__`: localhost:7000 75 | - `__NETWORK__`: ropsten (main for Mainnet) 76 | - `http://__SERVICE_GRPC_HOST__:__SERVICE_GRPC_PORT__`: http://localhost:7003 77 | - `__ORGANIZATION_ID__`: my-organization 78 | - `__SERVICE_ID__`: my-service 79 | 80 | See [SingularityNet daemon configuration](https://github.com/singnet/snet-daemon/blob/master/README.md#configuration) for detailed configuration description. 81 | 82 | ##### Running Service + Daemon on Host 83 | 84 | * Run the script without flag to launch both `SNET Daemon` and the service. But first, 85 | download the latest `SNET Daemon` [release here](https://github.com/singnet/snet-daemon/releases). 86 | 87 | ``` 88 | python3 run_example_service.py 89 | ``` 90 | 91 | ##### Running Service + Daemon in a Docker Container 92 | 93 | * Build the docker image and run a container from it: 94 | 95 | ``` 96 | docker build \ 97 | -t snet_example_service \ 98 | https://github.com/singnet/example-service.git#master 99 | 100 | export ETCD_HOST=$HOME/.snet/etcd/example-service/ 101 | export ETCD_CONTAINER=/opt/singnet/etcd/ 102 | docker run \ 103 | -p 7000:7000 \ 104 | -v $ETCD_HOST:$ETCD_CONTAINER \ 105 | -ti snet_example_service bash 106 | ``` 107 | 108 | Note that the `$ETCD_(HOST|CONTAINER)` are useful to keep your service's etcd folder outside the container. 109 | 110 | From this point we follow the tutorial in the Docker Container's prompt. 111 | 112 | After this, run the service (with `SNET Daemon`), make sure you have the `snetd.config.json` file in the service folder: 113 | 114 | ``` 115 | # cat snetd.config.json 116 | { 117 | "DAEMON_END_POINT": "0.0.0.0:7000", 118 | "BLOCKCHAIN_NETWORK_SELECTED": "ropsten", 119 | "IPFS_END_POINT": "http://ipfs.singularitynet.io:80", 120 | "PASSTHROUGH_ENDPOINT": "http://localhost:7003", 121 | "ORGANIZATION_ID": "my-organization", 122 | "SERVICE_ID": "my-service", 123 | "PAYMENT_CHANNEL_STORAGE_SERVER": { 124 | "DATA_DIR": "/opt/singnet/etcd/ropsten" 125 | }, 126 | "LOG": { 127 | "LEVEL": "debug", 128 | "OUTPUT": { 129 | "TYPE": "stdout" 130 | } 131 | } 132 | } 133 | # python3 run_example_service.py --daemon-config snetd.config.json & 134 | ``` 135 | 136 | ### Testing 137 | 138 | * Invoke the test script (from the same Docker Container): 139 | 140 | ``` 141 | # python3 test_example_service.py 142 | ``` 143 | 144 | ## License 145 | 146 | This project is licensed under the MIT License - see the 147 | [LICENSE](https://github.com/singnet/example-service/blob/master/LICENSE) file for details. 148 | -------------------------------------------------------------------------------- /buildproto.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. service/service_spec/example_service.proto 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | grpcio>=1.14.2 2 | grpcio-tools>=1.14.1 -------------------------------------------------------------------------------- /run_example_service.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import signal 4 | import time 5 | import subprocess 6 | import logging 7 | import pathlib 8 | import glob 9 | import json 10 | import argparse 11 | 12 | from service import registry 13 | 14 | logging.basicConfig(level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s") 15 | log = logging.getLogger("run_example_service") 16 | 17 | 18 | def main(): 19 | parser = argparse.ArgumentParser(description="Run services") 20 | parser.add_argument("--no-daemon", action="store_false", dest="run_daemon", help="do not start the daemon") 21 | parser.add_argument("--daemon-config", 22 | dest="daemon_config", 23 | help="Path of daemon configuration file, without config it won't be started", 24 | required=False) 25 | parser.add_argument("--ssl", action="store_true", dest="run_ssl", help="start the daemon with SSL") 26 | args = parser.parse_args() 27 | root_path = pathlib.Path(__file__).absolute().parent 28 | 29 | # All services modules go here 30 | service_modules = ["service.example_service"] 31 | 32 | # Call for all the services listed in service_modules 33 | all_p = start_all_services(root_path, service_modules, args.run_daemon, args.daemon_config, args.run_ssl) 34 | 35 | # Continuous checking all subprocess 36 | try: 37 | while True: 38 | for p in all_p: 39 | p.poll() 40 | if p.returncode and p.returncode != 0: 41 | kill_and_exit(all_p) 42 | time.sleep(1) 43 | except Exception as e: 44 | log.error(e) 45 | raise 46 | 47 | 48 | def start_all_services(cwd, service_modules, run_daemon, daemon_config, run_ssl): 49 | """ 50 | Loop through all service_modules and start them. 51 | For each one, an instance of Daemon "snetd" is created. 52 | snetd will start with configs from "snetd.config.json" 53 | """ 54 | all_p = [] 55 | for i, service_module in enumerate(service_modules): 56 | service_name = service_module.split(".")[-1] 57 | log.info("Launching {} on port {}".format(service_module, str(registry[service_name]))) 58 | all_p += start_service(cwd, service_module, run_daemon, daemon_config, run_ssl) 59 | return all_p 60 | 61 | 62 | def start_service(cwd, service_module, run_daemon, daemon_config, run_ssl): 63 | """ 64 | Starts SNET Daemon ("snetd") and the python module of the service 65 | at the passed gRPC port. 66 | """ 67 | 68 | def add_ssl_configs(conf): 69 | """Add SSL keys to snetd.config.json""" 70 | with open(conf, "r") as f: 71 | snetd_configs = json.load(f) 72 | snetd_configs["ssl_cert"] = "/opt/singnet/.certs/fullchain.pem" 73 | snetd_configs["ssl_key"] = "/opt/singnet/.certs/privkey.pem" 74 | with open(conf, "w") as f: 75 | json.dump(snetd_configs, f, sort_keys=True, indent=4) 76 | 77 | all_p = [] 78 | if run_daemon: 79 | if daemon_config: 80 | all_p.append(start_snetd(str(cwd), daemon_config)) 81 | else: 82 | for idx, config_file in enumerate(glob.glob("./snetd_configs/*.json")): 83 | if run_ssl: 84 | add_ssl_configs(config_file) 85 | all_p.append(start_snetd(str(cwd), config_file)) 86 | service_name = service_module.split(".")[-1] 87 | grpc_port = registry[service_name]["grpc"] 88 | p = subprocess.Popen([sys.executable, "-m", service_module, "--grpc-port", str(grpc_port)], cwd=str(cwd)) 89 | all_p.append(p) 90 | return all_p 91 | 92 | 93 | def start_snetd(cwd, config_file=None): 94 | """ 95 | Starts the Daemon "snetd": 96 | """ 97 | cmd = ["snetd", "serve"] 98 | if config_file: 99 | cmd = ["snetd", "serve", "--config", config_file] 100 | return subprocess.Popen(cmd, cwd=str(cwd)) 101 | 102 | 103 | def kill_and_exit(all_p): 104 | for p in all_p: 105 | try: 106 | os.kill(p.pid, signal.SIGTERM) 107 | except Exception as e: 108 | log.error(e) 109 | exit(1) 110 | 111 | 112 | if __name__ == "__main__": 113 | main() 114 | -------------------------------------------------------------------------------- /service/__init__.py: -------------------------------------------------------------------------------- 1 | registry = { 2 | "example_service": { 3 | "grpc": 7003, 4 | }, 5 | } 6 | -------------------------------------------------------------------------------- /service/common.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os.path 3 | import time 4 | 5 | from service import registry 6 | 7 | 8 | def common_parser(script_name): 9 | parser = argparse.ArgumentParser(prog=script_name) 10 | service_name = os.path.splitext(os.path.basename(script_name))[0] 11 | parser.add_argument("--grpc-port", 12 | help="port to bind gRPC service to", 13 | default=registry[service_name]['grpc'], 14 | type=int, 15 | required=False) 16 | return parser 17 | 18 | 19 | # From gRPC docs: 20 | # Because start() does not block you may need to sleep-loop if there is nothing 21 | # else for your code to do while serving. 22 | def main_loop(grpc_handler, args): 23 | server = grpc_handler(port=args.grpc_port) 24 | server.start() 25 | try: 26 | while True: 27 | time.sleep(1) 28 | except KeyboardInterrupt: 29 | server.stop(0) 30 | -------------------------------------------------------------------------------- /service/example_service.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | 4 | import grpc 5 | import concurrent.futures as futures 6 | 7 | import service.common 8 | 9 | # Importing the generated codes from buildproto.sh 10 | import service.service_spec.example_service_pb2_grpc as grpc_bt_grpc 11 | from service.service_spec.example_service_pb2 import Result 12 | 13 | logging.basicConfig(level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s") 14 | log = logging.getLogger("example_service") 15 | 16 | 17 | """ 18 | Simple arithmetic service to test the Snet Daemon (gRPC), dApp and/or Snet-CLI. 19 | The user must provide the method (arithmetic operation) and 20 | two numeric inputs: "a" and "b". 21 | 22 | e.g: 23 | With dApp: 'method': mul 24 | 'params': {"a": 12.0, "b": 77.0} 25 | Resulting: response: 26 | value: 924.0 27 | 28 | 29 | Full snet-cli cmd: 30 | $ snet client call mul '{"a":12.0, "b":77.0}' 31 | 32 | Result: 33 | (Transaction info) 34 | Signing job... 35 | 36 | Read call params from cmdline... 37 | 38 | Calling service... 39 | 40 | response: 41 | value: 924.0 42 | """ 43 | 44 | 45 | # Create a class to be added to the gRPC server 46 | # derived from the protobuf codes. 47 | class CalculatorServicer(grpc_bt_grpc.CalculatorServicer): 48 | def __init__(self): 49 | self.a = 0 50 | self.b = 0 51 | self.result = 0 52 | # Just for debugging purpose. 53 | log.debug("CalculatorServicer created") 54 | 55 | # The method that will be exposed to the snet-cli call command. 56 | # request: incoming data 57 | # context: object that provides RPC-specific information (timeout, etc). 58 | def add(self, request, context): 59 | # In our case, request is a Numbers() object (from .proto file) 60 | self.a = request.a 61 | self.b = request.b 62 | 63 | # To respond we need to create a Result() object (from .proto file) 64 | self.result = Result() 65 | 66 | self.result.value = self.a + self.b 67 | log.debug("add({},{})={}".format(self.a, self.b, self.result.value)) 68 | return self.result 69 | 70 | def sub(self, request, context): 71 | self.a = request.a 72 | self.b = request.b 73 | 74 | self.result = Result() 75 | self.result.value = self.a - self.b 76 | log.debug("sub({},{})={}".format(self.a, self.b, self.result.value)) 77 | return self.result 78 | 79 | def mul(self, request, context): 80 | self.a = request.a 81 | self.b = request.b 82 | 83 | self.result = Result() 84 | self.result.value = self.a * self.b 85 | log.debug("mul({},{})={}".format(self.a, self.b, self.result.value)) 86 | return self.result 87 | 88 | def div(self, request, context): 89 | self.a = request.a 90 | self.b = request.b 91 | 92 | self.result = Result() 93 | self.result.value = self.a / self.b 94 | log.debug("div({},{})={}".format(self.a, self.b, self.result.value)) 95 | return self.result 96 | 97 | 98 | # The gRPC serve function. 99 | # 100 | # Params: 101 | # max_workers: pool of threads to execute calls asynchronously 102 | # port: gRPC server port 103 | # 104 | # Add all your classes to the server here. 105 | # (from generated .py files by protobuf compiler) 106 | def serve(max_workers=10, port=7777): 107 | server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers)) 108 | grpc_bt_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server) 109 | server.add_insecure_port("[::]:{}".format(port)) 110 | return server 111 | 112 | 113 | if __name__ == "__main__": 114 | """ 115 | Runs the gRPC server to communicate with the Snet Daemon. 116 | """ 117 | parser = service.common.common_parser(__file__) 118 | args = parser.parse_args(sys.argv[1:]) 119 | service.common.main_loop(serve, args) 120 | -------------------------------------------------------------------------------- /service/service_spec/example_service.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package example_service; 4 | 5 | message Numbers { 6 | float a = 1; 7 | float b = 2; 8 | } 9 | 10 | message Result { 11 | float value = 1; 12 | } 13 | 14 | service Calculator { 15 | rpc add(Numbers) returns (Result) {} 16 | rpc sub(Numbers) returns (Result) {} 17 | rpc mul(Numbers) returns (Result) {} 18 | rpc div(Numbers) returns (Result) {} 19 | } -------------------------------------------------------------------------------- /snetd_configs/snetd.ropsten.json: -------------------------------------------------------------------------------- 1 | { 2 | "daemon_end_point": "0.0.0.0:7000", 3 | "ipfs_end_point": "http://ipfs.singularitynet.io:80", 4 | "blockchain_network_selected": "ropsten", 5 | "passthrough_endpoint": "http://localhost:7003", 6 | "organization_id": "my-organization", 7 | "service_id": "my-service", 8 | "payment_channel_storage_server": { 9 | "data_dir": "/opt/singnet/etcd/ropsten" 10 | }, 11 | "log": { 12 | "level": "debug", 13 | "output": { 14 | "type": "stdout" 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /test_example_service.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import grpc 3 | 4 | # import the generated classes 5 | import service.service_spec.example_service_pb2_grpc as grpc_ex_grpc 6 | import service.service_spec.example_service_pb2 as grpc_ex_pb2 7 | 8 | from service import registry 9 | 10 | if __name__ == "__main__": 11 | 12 | try: 13 | test_flag = False 14 | if len(sys.argv) == 2: 15 | if sys.argv[1] == "auto": 16 | test_flag = True 17 | 18 | # Example Service - Arithmetic 19 | endpoint = input("Endpoint (localhost:{}): ".format(registry["example_service"]["grpc"])) if not test_flag else "" 20 | if endpoint == "": 21 | endpoint = "localhost:{}".format(registry["example_service"]["grpc"]) 22 | 23 | grpc_method = input("Method (add|sub|mul|div): ") if not test_flag else "mul" 24 | a = float(input("Number 1: ") if not test_flag else "12") 25 | b = float(input("Number 2: ") if not test_flag else "7") 26 | 27 | # Open a gRPC channel 28 | channel = grpc.insecure_channel("{}".format(endpoint)) 29 | stub = grpc_ex_grpc.CalculatorStub(channel) 30 | number = grpc_ex_pb2.Numbers(a=a, b=b) 31 | 32 | if grpc_method == "add": 33 | response = stub.add(number) 34 | print(response.value) 35 | elif grpc_method == "sub": 36 | response = stub.sub(number) 37 | print(response.value) 38 | elif grpc_method == "mul": 39 | response = stub.mul(number) 40 | print(response.value) 41 | elif grpc_method == "div": 42 | response = stub.div(number) 43 | print(response.value) 44 | else: 45 | print("Invalid method!") 46 | exit(1) 47 | 48 | except Exception as e: 49 | print(e) 50 | exit(1) 51 | --------------------------------------------------------------------------------