diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 020a219d..05382cd8 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -71,3 +71,4 @@ jobs: export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python # sh -ex ./snet/cli/test/utils/run_all_functional.sh python3 ./snet/cli/test/functional_tests/test_entry_point.py + python3 ./snet/cli/test/functional_tests/func_tests.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..d2052183 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,66 @@ +name: tests_functional_tests_update +on: + push: + branches: [ "functional-tests-update" ] +# pull_request: +# branches: [ "development" ] + workflow_dispatch: + +jobs: + run_tests_functional_tests_update: + runs-on: ubuntu-latest + container: node:20-bookworm + steps: + + - name: install packs + run: | + apt update + apt install -y libudev-dev libusb-1.0-0-dev curl jq + apt install -y python3-pip python3.11-venv + + - name: clone repo + uses: actions/checkout@v3 + + - name: install pip packages + run: | + pip3 install -r requirements.txt --break-system-packages + # pip3 install nose --break-system-packages + # pip3 uninstall pyreadline --break-system-packages + # pip3 install pyreadline3 --break-system-packages + + - name: install snet-cli + run: | + # ./scripts/blockchain install + pip3 install -e . --break-system-packages + + # - name: install platform-contracts + # run: | + # cd .. + # git clone https://github.com/singnet/platform-contracts.git + # cd platform-contracts + # npm install + # npm install ganache-cli + # npm run-script compile + + # - name: build example service + # run: | + # git clone https://github.com/singnet/example-service.git + # cd example-service + # pip3 install -r requirements.txt --break-system-packages + # sh buildproto.sh + + # - name: unit tests + # run: | + # cd ./snet/cli/test + # nosetests -v --with-doctest + + - name: functional tests for cli + run: | + export SNET_TEST_WALLET_PRIVATE_KEY=${{ secrets.PRIV_KEY }} + export SNET_TEST_INFURA_KEY=${{ secrets.INF_KEY }} + export SNET_TEST_WALLET_ADDRESS=${{ secrets.ADDR }} + export FORMER_SNET_TEST_INFURA_KEY=${{ secrets.FORM_INF_KEY }} + export PIP_BREAK_SYSTEM_PACKAGES=1 + export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python + # sh -ex ./snet/cli/test/utils/run_all_functional.sh + python3 ./snet/cli/test/functional_tests/test_entry_point.py diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..736b7ef8 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,50 @@ +[build-system] +requires = [ + "setuptools>=61.0", + "wheel", + "protobuf~=6.30", + "grpcio-tools~=1.59" +] +build-backend = "setuptools.build_meta" + +[project] +name = "snet-cli" +version = "3.1.0" +description = "SingularityNET CLI" +readme = "README.md" +requires-python = ">=3.10" +license = {text = "MIT"} +authors = [ + {name = "SingularityNET Foundation", email = "info@singularitynet.io"} +] +urls = {Homepage = "https://github.com/singnet/snet-cli"} + +# Cleaned dependencies list +dependencies = [ + "protobuf~=6.30", + "grpcio~=1.59", + "grpcio-tools~=1.59", + "wheel~=0.45", + "rlp~=4.0", + "web3~=7.0", + "mnemonic==0.21", + "pyyaml~=6.0.1", + "ipfshttpclient==0.4.13.2", + "pymultihash==0.8.2", + "base58==2.1.1", + "argcomplete~=3.1", + "grpcio-health-checking~=1.59", + "jsonschema~=4.1", + "eth-account~=0.9", + "trezor~=0.13.8", + "ledgerblue~=0.1.48", + "snet-contracts==1.0.1", + "lighthouseweb3~=0.1.4", + "cryptography~=46.0" +] + +[project.scripts] +snet = "snet.cli:main" + +[tool.setuptools.packages.find] +include = ["snet*"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 36cb230a..d48692a1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,23 +1,24 @@ -protobuf==4.21.6 -grpcio-tools==1.59.0 -wheel==0.41.2 -jsonrpcclient==4.0.3 -eth-hash==0.5.2 -rlp==3.0.0 -eth-rlp==0.3.0 -web3==6.11.1 -mnemonic==0.20 -pycoin==0.92.20230326 -pyyaml==6.0.1 +protobuf~=6.30 +grpcio~=1.59 +grpcio-tools~=1.59 +wheel~=0.45 +# jsonrpcclient~=4.0 +# eth-hash~=0.5 +rlp~=4.0 +# eth-rlp~=2.0 +web3~=7.0 +mnemonic==0.21 +# pycoin==0.92.20241201 +pyyaml~=6.0.1 ipfshttpclient==0.4.13.2 pymultihash==0.8.2 base58==2.1.1 -argcomplete==3.1.2 -grpcio-health-checking==1.59.0 -jsonschema==4.0.0 -eth-account==0.9.0 -trezor==0.13.8 -ledgerblue==0.1.48 -snet-contracts==1.0.0 -lighthouseweb3==0.1.4 -cryptography==44.0.1 +argcomplete~=3.1 +grpcio-health-checking~=1.59 +jsonschema~=4.1 +eth-account~=0.9 +trezor~=0.13.8 +ledgerblue~=0.1.48 +snet-contracts==1.0.1 +lighthouseweb3~=0.1.4 +cryptography~=46.0 diff --git a/setup.py b/setup.py index 14d766d3..da43752a 100644 --- a/setup.py +++ b/setup.py @@ -1,73 +1,71 @@ import os from pathlib import Path -from setuptools import find_namespace_packages, setup +from setuptools import setup from setuptools.command.develop import develop as _develop from setuptools.command.install import install as _install +from setuptools.command.build_py import build_py as _build_py +from grpc_tools import protoc +from pkg_resources import resource_filename -from snet.cli.utils.utils import compile_proto -from version import __version__ - -PACKAGE_NAME = 'snet-cli' - - -this_directory = os.path.abspath(os.path.dirname(__file__)) -with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f: - long_description = f.read() +def install_and_compile_proto(): + """ + Compiles protobuf files directly. + """ + proto_dir = Path(__file__).absolute().parent.joinpath( + "snet", "cli", "resources", "proto") + # Locate the standard grpc_tools internal protos (google/protobuf/...) + grpc_protos_include = resource_filename('grpc_tools', '_proto') -with open("./requirements.txt") as f: - requirements_str = f.read() -requirements = requirements_str.split("\n") + print(f"Proto directory: {proto_dir}") + print(f"Grpc include directory: {grpc_protos_include}") + if not proto_dir.exists(): + print(f"Warning: Proto directory not found at {proto_dir}") + return -def install_and_compile_proto(): - proto_dir = Path(__file__).absolute().parent.joinpath( - "snet", "cli", "resources", "proto") - print(proto_dir, "->", proto_dir) + # glob('*.proto') is non-recursive. It will NOT look inside subfolders. for fn in proto_dir.glob('*.proto'): - print("Compiling protobuf", fn) - compile_proto(proto_dir, proto_dir, proto_file=fn) - + print(f"Compiling protobuf: {fn}") + + command = [ + 'grpc_tools.protoc', + f'-I{proto_dir}', + f'-I{grpc_protos_include}', # <--- CRITICAL FIX: Add standard protos to include path + f'--python_out={proto_dir}', + f'--grpc_python_out={proto_dir}', + str(fn) + ] + + if protoc.main(command) != 0: + print(f"Error: Failed to compile {fn}") + raise RuntimeError(f"Protocol buffer compilation failed for {fn}") + +class build_py(_build_py): + """ + Override build_py to compile protos before building the wheel. + This is the hook used by 'python -m build'. + """ + def run(self): + self.execute(install_and_compile_proto, (), msg="Compile protocol buffers") + _build_py.run(self) class develop(_develop): - """Post-installation for development mode.""" - + """Post-installation for development mode (pip install -e .).""" def run(self): + self.execute(install_and_compile_proto, (), msg="Compile protocol buffers") _develop.run(self) - self.execute(install_and_compile_proto, (), - msg="Compile protocol buffers") - class install(_install): - """Post-installation for installation mode.""" - + """Post-installation for legacy installation mode.""" def run(self): + self.execute(install_and_compile_proto, (), msg="Compile protocol buffers") _install.run(self) - self.execute(install_and_compile_proto, (), - msg="Compile protocol buffers") - setup( - name=PACKAGE_NAME, - version=__version__, - packages=find_namespace_packages(include=['snet*']), - url='https://github.com/singnet/snet-cli', - author="SingularityNET Foundation", - author_email="info@singularitynet.io", - description="SingularityNET CLI", - long_description=long_description, - long_description_content_type='text/markdown', - license="MIT", - python_requires='>=3.10', - install_requires=requirements, - include_package_data=True, cmdclass={ 'develop': develop, 'install': install, + 'build_py': build_py, }, - entry_points={ - 'console_scripts': [ - 'snet = snet.cli:main' - ], - } -) +) \ No newline at end of file diff --git a/snet/cli/arguments.py b/snet/cli/arguments.py index 380b0c7e..7ad76e2f 100644 --- a/snet/cli/arguments.py +++ b/snet/cli/arguments.py @@ -24,18 +24,24 @@ def __init__(self, default_choice=None, *args, **kwargs): super().__init__(*args, **kwargs) def error(self, message): - sys.stderr.write("error: {}\n\n".format(message)) + sys.stderr.write(f"error: {message}\n\n") self.print_help(sys.stderr) sys.exit(2) def _parse_known_args(self, arg_strings, *args, **kwargs): - if self.default_choice and not len(list(filter(lambda option: option in arg_strings, {'-h', '--help'}))): - for action in list(filter( - lambda subparser_action: isinstance( - subparser_action, argparse._SubParsersAction), - self._subparsers._actions - )): - if not len(list(filter(lambda arg: arg in action._name_parser_map.keys(), arg_strings))): + if self.default_choice and not any(arg in arg_strings for arg in {'-h', '--help'}): + + subparser_action = next( + (a for a in self._actions if isinstance(a, argparse._SubParsersAction)), + None + ) + + if subparser_action: + is_subcommand_present = any( + arg in subparser_action.choices for arg in arg_strings + ) + + if not is_subcommand_present: arg_strings = [self.default_choice] + arg_strings return super()._parse_known_args( @@ -575,8 +581,8 @@ def add_mpe_account_options(parser): subparsers = parser.add_subparsers(title="Commands", metavar="COMMAND") subparsers.required = True - def add_p_snt_address_opt(p): - p.add_argument( + def add_p_snt_address_opt(_p): + _p.add_argument( "--singularitynettoken-at", "--snt", default=None, help="Address of SingularityNetToken contract, if not specified we read address from \"networks\"") @@ -1153,7 +1159,7 @@ def add_mpe_service_options(parser): p.add_argument("name", help="Name of the contributor") p.add_argument("email_id", help="Email of the contributor") - p = subparsers.add_parser("metadata-remove-contributor", help="Add contributor") + p = subparsers.add_parser("metadata-remove-contributor", help="Remove contributor") p.set_defaults(fn="metadata_remove_contributor") add_p_metadata_file_opt(p) p.add_argument("email_id", help="Email of the contributor") diff --git a/snet/cli/commands/commands.py b/snet/cli/commands/commands.py index 64b80b91..d7ec7ddb 100644 --- a/snet/cli/commands/commands.py +++ b/snet/cli/commands/commands.py @@ -144,9 +144,9 @@ def get_gas_price_verbose(self): gas_price = self.w3.eth.gas_price if gas_price <= 15000000000: gas_price += gas_price * 1 / 3 - elif gas_price > 15000000000 and gas_price <= 50000000000: + elif 15000000000 < gas_price <= 50000000000: gas_price += gas_price * 1 / 5 - elif gas_price > 50000000000 and gas_price <= 150000000000: + elif 50000000000 < gas_price <= 150000000000: gas_price += 7000000000 elif gas_price > 150000000000: gas_price += gas_price * 1 / 10 @@ -166,8 +166,8 @@ def get_identity(self): return RpcIdentityProvider(self.w3, self.get_wallet_index()) if identity_type == "mnemonic": return MnemonicIdentityProvider(self.w3, self.config.get_session_field("mnemonic"), self.get_wallet_index()) - # if identity_type == "trezor": - # return TrezorIdentityProvider(self.w3, self.get_wallet_index()) + if identity_type == "trezor": + return TrezorIdentityProvider(self.w3, self.get_wallet_index()) if identity_type == "ledger": return LedgerIdentityProvider(self.w3, self.get_wallet_index()) if identity_type == "key": @@ -177,7 +177,8 @@ def get_identity(self): def check_ident(self): identity_type = self.config.get_session_field("identity_type") - if get_kws_for_identity_type(identity_type)[0][1] and not self.ident.private_key: + kws = get_kws_for_identity_type(identity_type) + if kws and all(kws.values()) and not self.ident.private_key: if identity_type == "key": secret = self.config.get_session_field("private_key") else: @@ -258,7 +259,9 @@ def create(self): identity_type = self.args.identity_type identity["identity_type"] = identity_type - for kw, is_secret in get_kws_for_identity_type(identity_type): + kws = get_kws_for_identity_type(identity_type) + + for kw, is_secret in kws.items(): value = getattr(self.args, kw) if value is None and is_secret: kw_prompt = "{}: ".format(" ".join(kw.capitalize().split("_"))) @@ -272,7 +275,8 @@ def create(self): identity["default_wallet_index"] = self.args.wallet_index password = None - if not self.args.do_not_encrypt and get_kws_for_identity_type(identity_type)[0][1]: + + if not self.args.do_not_encrypt and any(kws.values()): self._printout("For 'mnemonic' and 'key' identity_type, secret encryption is enabled by default, " "so you need to come up with a password that you then need to enter on every transaction. " "To disable encryption, use the '-de' or '--do-not-encrypt' argument.") @@ -287,15 +291,13 @@ def create(self): def list(self): for identity_section in filter(lambda x: x.startswith("identity."), self.config.sections()): identity = self.config[identity_section] - key_is_secret_lookup = {} identity_type = self.config.get(identity_section, 'identity_type') - for kw, is_secret in get_kws_for_identity_type(identity_type): - key_is_secret_lookup[kw] = is_secret + kws = get_kws_for_identity_type(identity_type) self._pprint({ identity_section[len("identity."):]: { - k: (v if not key_is_secret_lookup.get(k, False) else "xxxxxx") for k, v in identity.items() + k: (v if not kws.get(k, False) else "xxxxxx") for k, v in identity.items() } }) @@ -360,7 +362,7 @@ def populate_contract_address(self, rez, key): w3=self.w3, contract_name="MultiPartyEscrow") rez[key]['default_fetchtoken_at'] = read_default_contract_address( w3=self.w3, contract_name="FetchToken") - except Exception as e: + except Exception: pass return @@ -587,7 +589,7 @@ def error_organization_not_found(self, org_id, found): def info(self): org_id = self.args.org_id - (found, org_id, org_name, owner, members, serviceNames) = self._get_organization_by_id(org_id) + (found, org_id, org_name, owner, members, service_names) = self._get_organization_by_id(org_id) self.error_organization_not_found(self.args.org_id, found) org_m = self._get_organization_metadata_from_registry(web3.Web3.to_text(org_id)) @@ -604,9 +606,9 @@ def info(self): self._printout("\nMembers:") for idx, member in enumerate(members): self._printout(" - {}".format(member)) - if serviceNames: + if service_names: self._printout("\nServices:") - for idx, service in enumerate(serviceNames): + for idx, service in enumerate(service_names): self._printout(" - {}".format(bytes32_to_str(service))) def metadata_validate(self): @@ -670,7 +672,7 @@ def _metadata_validate_with_schema(self): try: with open(metadata_file, 'r') as f: metadata_dict = json.load(f) - except Exception as e: + except Exception: return {"status": 2, "msg": "Organization metadata json file not found, please check --metadata-file path"} validator = jsonschema.Draft7Validator(schema) @@ -747,7 +749,7 @@ def delete(self): try: self.transact_contract_command("Registry", "deleteOrganization", [ type_converter("bytes32")(org_id)]) - except Exception as e: + except Exception: self._printerr( "\nTransaction error!\nHINT: Check if you are the owner of organization with id={}\n".format(org_id)) raise @@ -818,7 +820,7 @@ def change_owner(self): try: self.transact_contract_command("Registry", "changeOrganizationOwner", [type_converter("bytes32")(org_id), self.args.owner]) - except Exception as e: + except Exception: self._printerr( "\nTransaction error!\nHINT: Check if you are the owner of {}\n".format(org_id)) raise @@ -848,7 +850,7 @@ def add_members(self): try: self.transact_contract_command( "Registry", "addOrganizationMembers", params) - except Exception as e: + except Exception: self._printerr( "\nTransaction error!\nHINT: Check if you are the owner of {}\n".format(org_id)) raise @@ -879,7 +881,7 @@ def rem_members(self): try: self.transact_contract_command( "Registry", "removeOrganizationMembers", params) - except Exception as e: + except Exception: self._printerr( "\nTransaction error!\nHINT: Check if you are the owner of {}\n".format(org_id)) raise @@ -892,7 +894,7 @@ def list_my(self): rez_owner = [] rez_member = [] for idx, org_id in enumerate(org_list): - (found, org_id, org_name, owner, members, serviceNames) = self.call_contract_command( + (found, org_id, org_name, owner, members, service_names) = self.call_contract_command( "Registry", "getOrganizationById", [org_id]) if not found: raise Exception( diff --git a/snet/cli/commands/mpe_channel.py b/snet/cli/commands/mpe_channel.py index e2d5be02..c1f70577 100644 --- a/snet/cli/commands/mpe_channel.py +++ b/snet/cli/commands/mpe_channel.py @@ -2,13 +2,8 @@ import os import pickle import shutil -import tempfile -from collections import defaultdict -from importlib.metadata import metadata from pathlib import Path -from eth_abi.codec import ABICodec -from web3._utils.events import get_event_data from snet.contracts import get_contract_def, get_contract_deployment_block from snet.cli.commands.commands import OrganizationCommand @@ -85,27 +80,34 @@ def _event_data_args_to_dict(self, event_data): "group_id": event_data["groupId"], } - def _get_all_opened_channels_from_blockchain(self, starting_block_number, to_block_number): - mpe_address = self.get_mpe_address() - event_topics = [self.ident.w3.keccak( - text="ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)").hex()] + def _get_all_opened_channels_from_blockchain(self, start_block, end_block): + start_block = int(start_block) + end_block = int(end_block) + mpe_address = self.ident.w3.to_checksum_address(self.get_mpe_address()) + + abi = get_contract_def("MultiPartyEscrow")["abi"] + contract = self.ident.w3.eth.contract(address = mpe_address, abi = abi) + + raw_topic = self.ident.w3.keccak( + text = "ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)") + event_topics = [self.ident.w3.to_hex(raw_topic)] + blocks_per_batch = 5000 - codec: ABICodec = self.ident.w3.codec logs = [] - from_block = starting_block_number - while from_block <= to_block_number: - to_block = min(from_block + blocks_per_batch, to_block_number) + + from_block = start_block + while from_block <= end_block: + to_block = min(from_block + blocks_per_batch, end_block) logs += self.ident.w3.eth.get_logs({"fromBlock": from_block, - "toBlock": to_block, - "address": mpe_address, - "topics": event_topics}) + "toBlock": to_block, + "address": mpe_address, + "topics": event_topics}) from_block = to_block + 1 - abi = get_contract_def("MultiPartyEscrow") - event_abi = abi_get_element_by_name(abi, "ChannelOpen") + channel_open_event = contract.events.ChannelOpen() + event_data_list = [channel_open_event.process_log(l)["args"] for l in logs] - event_data_list = [get_event_data(codec, event_abi, l)["args"] for l in logs] channels_opened = list(map(self._event_data_args_to_dict, event_data_list)) return channels_opened @@ -186,15 +188,15 @@ def _check_mpe_address_metadata(self, metadata): def _init_or_update_org_if_needed(self, metadata, org_registration): # if service was already initialized and metadataURI hasn't changed we do nothing if self.is_org_initialized(): - if self.is_metadataURI_has_changed(org_registration): + if self.is_metadata_uri_has_changed(org_registration): self._printerr("# Organization with org_id=%s " % - (self.args.org_id)) + self.args.org_id) self._printerr( "# ATTENTION!!! price or other paramaters might have been changed!\n") else: return # we do nothing self._printerr("# Initilize service with org_id=%s" % - (self.args.org_id)) + self.args.org_id) # self._check_mpe_address_metadata(metadata) org_dir = self.get_org_spec_dir(self.args.org_id) @@ -226,7 +228,7 @@ def _init_or_update_registered_org_if_needed(self): org_registration = self._get_organization_registration( self.args.org_id) # if metadataURI hasn't been changed we do nothing - if not self.is_metadataURI_has_changed(org_registration): + if not self.is_metadata_uri_has_changed(org_registration): return else: org_registration = self._get_organization_registration( @@ -236,11 +238,11 @@ def _init_or_update_registered_org_if_needed(self): self.args.org_id) self._init_or_update_org_if_needed(org_metadata, org_registration) - def is_metadataURI_has_changed(self, new_reg): + def is_metadata_uri_has_changed(self, new_reg): old_reg = self._read_org_info(self.args.org_id) return new_reg.get("orgMetadataURI") != old_reg.get("orgMetadataURI") - def is_service_metadataURI_has_changed(self, new_reg): + def is_service_metadata_uri_has_changed(self, new_reg): old_reg = self._read_service_info( self.args.org_id, self.args.service_id) return new_reg.get("metadataURI") != old_reg.get("metadataURI") @@ -432,7 +434,7 @@ def _smart_get_channel_for_org(self, metadata, filter_by): def channel_extend_and_add_funds_for_org(self): self._init_or_update_registered_org_if_needed() metadata = self._read_metadata_for_org(self.args.org_id) - channel_id = self._smart_get_channel_for_org(metadata, "sender")["channelId"] + channel_id = self._smart_get_channel_for_org(metadata, "sender")["channel_id"] self._channel_extend_add_funds_with_channel_id(channel_id) def _get_channel_state_from_blockchain(self, channel_id): @@ -448,7 +450,7 @@ def _read_metadata_for_org(self, org_id): sdir = self.get_org_spec_dir(org_id) if not os.path.exists(sdir): raise Exception( - "Service with org_id=%s is not initialized" % (org_id)) + "Service with org_id=%s is not initialized" % org_id) return OrganizationMetadata.from_file(sdir.joinpath("organization_metadata.json")) def _convert_channel_dict_to_str(self, channel, filters=None): @@ -560,7 +562,7 @@ def _get_service_registration(self): "bytes32")(self.args.service_id)] response = self.call_contract_command( "Registry", "getServiceRegistrationById", params) - if response[0] == False: + if not response[0]: raise Exception("Cannot find Service with id=%s in Organization with id=%s" % ( self.args.service_id, self.args.org_id)) return {"metadataURI": response[2]} @@ -579,7 +581,7 @@ def _get_service_metadata_from_registry(self): def _init_or_update_service_if_needed(self, metadata, service_registration): # if service was already initialized and metadataURI hasn't changed we do nothing if self.is_service_initialized(): - if self.is_service_metadataURI_has_changed(service_registration): + if self.is_service_metadata_uri_has_changed(service_registration): self._printerr("# Service with org_id=%s and service_id=%s was updated" % ( self.args.org_id, self.args.service_id)) self._printerr( @@ -636,7 +638,7 @@ def _init_or_update_registered_service_if_needed(self): service_registration = self._get_service_registration() # if metadataURI hasn't been changed we do nothing - if not self.is_service_metadataURI_has_changed(service_registration): + if not self.is_service_metadata_uri_has_changed(service_registration): return else: service_registration = self._get_service_registration() diff --git a/snet/cli/commands/mpe_client.py b/snet/cli/commands/mpe_client.py index 760cfff4..836966b3 100644 --- a/snet/cli/commands/mpe_client.py +++ b/snet/cli/commands/mpe_client.py @@ -68,7 +68,7 @@ def _get_call_params(self): try: params = self._transform_call_params(params) - except Exception as e: + except Exception: self._printerr('Fail to "transform" call params') raise diff --git a/snet/cli/commands/mpe_service.py b/snet/cli/commands/mpe_service.py index 442b6a45..b4d9606c 100644 --- a/snet/cli/commands/mpe_service.py +++ b/snet/cli/commands/mpe_service.py @@ -3,7 +3,6 @@ from pathlib import Path from re import search from sys import exit -import tempfile from grpc_health.v1 import health_pb2 as heartb_pb2 from grpc_health.v1 import health_pb2_grpc as heartb_pb2_grpc @@ -384,10 +383,6 @@ def metadata_validate(self): Validates whether service metadata (`service_metadata.json` if not provided as argument) is consistent with the schema provided in `service_schema` present in `snet_cli/snet/snet_cli/resources.` - Args: - metadata_file: Option provided through the command line. (default: service_metadata.json) - service_schema: Schema of a consistent service metadata file. - Raises: ValidationError: Inconsistent service metadata structure or missing values. docs -> Handling ValidationErrors (https://python-jsonschema.readthedocs.io/en/stable/errors/) @@ -483,7 +478,7 @@ def _get_organization_registration(self, org_id): params = [type_converter("bytes32")(org_id)] result = self.call_contract_command( "Registry", "getOrganizationById", params) - if result[0] == False: + if not result[0]: raise Exception("Cannot find Organization with id=%s" % ( self.args.org_id)) return {"orgMetadataURI": result[2]} @@ -570,7 +565,7 @@ def _get_service_registration(self): "bytes32")(self.args.service_id)] rez = self.call_contract_command( "Registry", "getServiceRegistrationById", params) - if rez[0] == False: + if not rez[0]: raise Exception("Cannot find Service with id=%s in Organization with id=%s" % ( self.args.service_id, self.args.org_id)) return {"metadataURI": rez[2]} @@ -591,21 +586,21 @@ def print_service_metadata_from_registry(self): metadata = self._get_service_metadata_from_registry() self._printout(metadata.get_json_pretty()) - def _service_status(self, url, secure=True): + def _service_status(self, url): try: channel = open_grpc_channel(endpoint=url) stub = heartb_pb2_grpc.HealthStub(channel) response = stub.Check( heartb_pb2.HealthCheckRequest(service=""), timeout=10) - if response != None and response.status == 1: + if response is not None and response.status == 1: return True return False - except Exception as e: + except Exception: return False def print_service_status(self): metadata = self._get_service_metadata_from_registry() - if self.args.group_name != None: + if self.args.group_name is not None: groups = {self.args.group_name: metadata.get_all_endpoints_for_group( self.args.group_name)} else: diff --git a/snet/cli/commands/mpe_treasurer.py b/snet/cli/commands/mpe_treasurer.py index 4043c269..7b3b040f 100644 --- a/snet/cli/commands/mpe_treasurer.py +++ b/snet/cli/commands/mpe_treasurer.py @@ -41,10 +41,10 @@ def _get_stub_and_request_classes(self, service_name): codegen_dir, service_name) return stub_class, request_class - def _decode_PaymentReply(self, p): + def _decode__payment_reply(self, p): return {"channel_id": int4bytes_big(p.channel_id), "nonce": int4bytes_big(p.channel_nonce), "amount": int4bytes_big(p.signed_amount), "signature": p.signature} - def _call_GetListUnclaimed(self, grpc_channel): + def _call_get_list_unclaimed(self, grpc_channel): stub_class, request_class = self._get_stub_and_request_classes( "GetListUnclaimed") stub = stub_class(grpc_channel) @@ -62,9 +62,9 @@ def _call_GetListUnclaimed(self, grpc_channel): raise Exception( "Signature was set in GetListUnclaimed. Response is invalid") - return [self._decode_PaymentReply(p) for p in response.payments] + return [self._decode__payment_reply(p) for p in response.payments] - def _call_GetListInProgress(self, grpc_channel): + def _call_get_list_in_progress(self, grpc_channel): stub_class, request_class = self._get_stub_and_request_classes( "GetListInProgress") stub = stub_class(grpc_channel) @@ -76,9 +76,9 @@ def _call_GetListInProgress(self, grpc_channel): request = request_class( mpe_address=mpe_address, current_block=current_block, signature=bytes(signature)) response = getattr(stub, "GetListInProgress")(request) - return [self._decode_PaymentReply(p) for p in response.payments] + return [self._decode__payment_reply(p) for p in response.payments] - def _call_StartClaim(self, grpc_channel, channel_id, channel_nonce): + def _call_start_claim(self, grpc_channel, channel_id, channel_nonce): stub_class, request_class = self._get_stub_and_request_classes( "StartClaim") stub = stub_class(grpc_channel) @@ -88,11 +88,11 @@ def _call_StartClaim(self, grpc_channel, channel_id, channel_nonce): request = request_class(mpe_address=mpe_address, channel_id=web3.Web3.to_bytes( channel_id), signature=bytes(signature)) response = getattr(stub, "StartClaim")(request) - return self._decode_PaymentReply(response) + return self._decode__payment_reply(response) def print_unclaimed(self): grpc_channel = open_grpc_channel(self.args.endpoint) - payments = self._call_GetListUnclaimed(grpc_channel) + payments = self._call_get_list_unclaimed(grpc_channel) self._printout("# channel_id channel_nonce signed_amount (ASI(FET))") total = 0 for p in payments: @@ -117,7 +117,7 @@ def _blockchain_claim(self, payments): def _start_claim_channels(self, grpc_channel, channels_ids): """ Safely run StartClaim for given channels """ - unclaimed_payments = self._call_GetListUnclaimed(grpc_channel) + unclaimed_payments = self._call_get_list_unclaimed(grpc_channel) unclaimed_payments_dict = { p["channel_id"]: p for p in unclaimed_payments} @@ -134,14 +134,14 @@ def _start_claim_channels(self, grpc_channel, channels_ids): continue to_claim.append((channel_id, blockchain["nonce"])) - payments = [self._call_StartClaim( + payments = [self._call_start_claim( grpc_channel, channel_id, nonce) for channel_id, nonce in to_claim] return payments def _claim_in_progress_and_claim_channels(self, grpc_channel, channels): """ Claim all 'pending' payments in progress and after we claim given channels """ # first we get the list of all 'payments in progress' in case we 'lost' some payments. - payments = self._call_GetListInProgress(grpc_channel) + payments = self._call_get_list_in_progress(grpc_channel) if len(payments) > 0: self._printout( "There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them." % len(payments)) @@ -158,7 +158,7 @@ def claim_all_channels(self): self.check_ident() grpc_channel = open_grpc_channel(self.args.endpoint) # we take list of all channels - unclaimed_payments = self._call_GetListUnclaimed(grpc_channel) + unclaimed_payments = self._call_get_list_unclaimed(grpc_channel) channels = [p["channel_id"] for p in unclaimed_payments] self._claim_in_progress_and_claim_channels(grpc_channel, channels) @@ -166,7 +166,7 @@ def claim_almost_expired_channels(self): self.check_ident() grpc_channel = open_grpc_channel(self.args.endpoint) # we take list of all channels - unclaimed_payments = self._call_GetListUnclaimed(grpc_channel) + unclaimed_payments = self._call_get_list_unclaimed(grpc_channel) channels = [] for p in unclaimed_payments: diff --git a/snet/cli/config.py b/snet/cli/config.py index 7747fc36..f9a36dd3 100644 --- a/snet/cli/config.py +++ b/snet/cli/config.py @@ -69,7 +69,7 @@ def set_session_identity(self, identity, out_f): print( 'Identity "%s" is not bind to any network. You should switch network manually if you need.' % identity, file=out_f) - print("Switch to identity: %s" % (identity), file=out_f) + print("Switch to identity: %s" % identity, file=out_f) self["session"]["identity"] = identity self._persist() @@ -106,7 +106,7 @@ def set_session_field(self, key, value, out_f): self.set_identity_field(session_identity, key, value) print("set {}={} for identity={}".format(key, value, session_identity), file=out_f) else: - all_keys = get_session_network_keys() + get_session_identity_keys() + ["default_ipfs_endpoint"] + all_keys = get_session_keys() raise Exception("key {} not in {}".format(key, all_keys)) def unset_session_field(self, key, out_f): diff --git a/snet/cli/identity.py b/snet/cli/identity.py index 67ba62f8..ef792ee9 100644 --- a/snet/cli/identity.py +++ b/snet/cli/identity.py @@ -6,14 +6,13 @@ import rlp from eth_account import Account -from eth_account.messages import defunct_hash_message -from eth_account._utils.legacy_transactions import encode_transaction, \ - UnsignedTransaction, serializable_unsigned_transaction_from_dict +from eth_account.messages import encode_defunct from ledgerblue.comm import getDongle from ledgerblue.commException import CommException +from rlp.sedes import big_endian_int, binary from trezorlib.client import TrezorClient -from trezorlib import messages as proto -from trezorlib.transport.hid import HidTransport +from trezorlib.transport import get_transport +from trezorlib import ethereum, tools, ui from snet.cli.utils.utils import get_address_from_private, normalize_private_key @@ -35,6 +34,20 @@ def sign_message_after_solidity_keccak(self, message): raise NotImplementedError() +class Transaction(rlp.Serializable): + fields = [ + ('nonce', big_endian_int), + ('gasPrice', big_endian_int), + ('gas', big_endian_int), + ('to', binary), + ('value', big_endian_int), + ('data', binary), + ('v', big_endian_int), + ('r', big_endian_int), + ('s', big_endian_int), + ] + + class KeyIdentityProvider(IdentityProvider): def __init__(self, w3, private_key): self.w3 = w3 @@ -106,7 +119,7 @@ def get_address(self): def transact(self, transaction, out_f): print("Submitting transaction...\n", file=out_f) - txn_hash = self.w3.eth.sendTransaction(transaction) + txn_hash = self.w3.eth.send_transaction(transaction) return send_and_wait_for_transaction_receipt(txn_hash, self.w3) def sign_message_after_solidity_keccak(self, message): @@ -144,45 +157,69 @@ def sign_message_after_solidity_keccak(self, message): class TrezorIdentityProvider(IdentityProvider): def __init__(self, w3, index): self.w3 = w3 - self.client = TrezorClient(HidTransport.enumerate()[0]) self.index = index + + try: + transport = get_transport() + except Exception as e: + raise RuntimeError("No Trezor device found. Ensure it is connected and unlocked.") from e + + self.client = TrezorClient(transport, ui = ui.ClickUI()) + self.path = tools.parse_path(f"m/44'/60'/0'/0/{index}") + self.address = self.w3.to_checksum_address( - "0x" + bytes(self.client.ethereum_get_address([44 + BIP32_HARDEN, - 60 + BIP32_HARDEN, - BIP32_HARDEN, 0, - index])).hex()) + ethereum.get_address(self.client, self.path) + ) def get_address(self): return self.address def transact(self, transaction, out_f): - print("Sending transaction to trezor for signature...\n", file=out_f) - signature = self.client.ethereum_sign_tx(n=[44 + BIP32_HARDEN, 60 + BIP32_HARDEN, - BIP32_HARDEN, 0, self.index], - nonce=transaction["nonce"], - gas_price=transaction["gasPrice"], - gas_limit=transaction["gas"], - to=bytearray.fromhex( - transaction["to"][2:]), - value=transaction["value"], - data=bytearray.fromhex(transaction["data"][2:])) - - transaction.pop("from") - unsigned_transaction = serializable_unsigned_transaction_from_dict( - transaction) - raw_transaction = encode_transaction(unsigned_transaction, - vrs=(signature[0], - int(signature[1].hex(), 16), - int(signature[2].hex(), 16))) + print("Sending transaction to trezor for signature...\n", file = out_f) + + tx_data = transaction.get("data", b"") + if isinstance(tx_data, str) and tx_data.startswith("0x"): + tx_data = bytes.fromhex(tx_data[2:]) + + tx_to = transaction["to"] + if isinstance(tx_to, str) and tx_to.startswith("0x"): + tx_to = bytes.fromhex(tx_to[2:]) + + chain_id = int(transaction.get("chainId", self.w3.eth.chain_id)) + + v, r, s = ethereum.sign_tx( + self.client, + n = self.path, + nonce = int(transaction["nonce"]), + gas_price = int(transaction["gasPrice"]), + gas_limit = int(transaction["gas"]), + to = transaction["to"], # Trezorlib handles "0x" strings fine here + value = int(transaction["value"]), + data = tx_data, + chain_id = chain_id + ) + r = int.from_bytes(r, byteorder = "big") + s = int.from_bytes(s, byteorder = "big") + + signed_tx = Transaction( + nonce = int(transaction["nonce"]), + gasPrice = int(transaction["gasPrice"]), + gas = int(transaction["gas"]), + to = tx_to, + value = int(transaction["value"]), + data = tx_data, + v = v, + r = r, + s = s + ) + + raw_transaction = rlp.encode(signed_tx) + return send_and_wait_for_transaction(raw_transaction, self.w3, out_f) def sign_message_after_solidity_keccak(self, message): - n = self.client._convert_prime([44 + BIP32_HARDEN, - 60 + BIP32_HARDEN, - BIP32_HARDEN, - 0, - self.index]) - return self.client.call(proto.EthereumSignMessage(address_n=n, message=message)).signature + result = ethereum.sign_message(self.client, self.path, message) + return result.signature class LedgerIdentityProvider(IdentityProvider): @@ -198,7 +235,9 @@ def __init__(self, w3, index): except CommException: raise RuntimeError( "Received commException from Ledger. Are you sure your device is plugged in?") + self.dongle_path = parse_bip32_path("44'/60'/0'/0/{}".format(index)) + apdu = LedgerIdentityProvider.GET_ADDRESS_OP apdu += bytearray([len(self.dongle_path) + 1, int(len(self.dongle_path) / 4)]) + self.dongle_path @@ -216,55 +255,81 @@ def get_address(self): return self.address def transact(self, transaction, out_f): - tx = UnsignedTransaction( - nonce=transaction["nonce"], - gasPrice=transaction["gasPrice"], - gas=transaction["gas"], - to=bytes(bytearray.fromhex(transaction["to"][2:])), - value=transaction["value"], - data=bytes(bytearray.fromhex(transaction["data"][2:])) + chain_id = int(transaction.get("chainId", self.w3.eth.chain_id)) + + tx_obj = Transaction( + nonce = int(transaction["nonce"]), + gasPrice = int(transaction["gasPrice"]), + gas = int(transaction["gas"]), + to = bytes.fromhex(transaction["to"][2:]), + value = int(transaction["value"]), + data = bytes.fromhex(transaction["data"][2:]), + v = chain_id, + r = 0, + s = 0 ) - encoded_tx = rlp.encode(tx, UnsignedTransaction) + encoded_tx = rlp.encode(tx_obj) overflow = len(self.dongle_path) + 1 + len(encoded_tx) - 255 if overflow > 0: - encoded_tx, remaining_tx = encoded_tx[:- - overflow], encoded_tx[-overflow:] + encoded_tx_part, remaining_tx = encoded_tx[:-overflow], encoded_tx[-overflow:] + else: + encoded_tx_part = encoded_tx + remaining_tx = b"" apdu = LedgerIdentityProvider.SIGN_TX_OP - apdu += bytearray([len(self.dongle_path) + 1 + - len(encoded_tx), int(len(self.dongle_path) / 4)]) - apdu += self.dongle_path + encoded_tx + apdu += bytearray([len(self.dongle_path) + 1 + len(encoded_tx_part), int(len(self.dongle_path) / 4)]) + apdu += self.dongle_path + encoded_tx_part + try: - print("Sending transaction to Ledger for signature...\n", file=out_f) + print("Sending transaction to Ledger for signature...\n", file = out_f) result = self.dongle.exchange(apdu) - while overflow > 0: - encoded_tx = remaining_tx - overflow = len(encoded_tx) - 255 + while remaining_tx: + overflow = len(remaining_tx) - 255 if overflow > 0: - encoded_tx, remaining_tx = encoded_tx[:- - overflow], encoded_tx[-overflow:] + encoded_tx_part, remaining_tx = remaining_tx[:-overflow], remaining_tx[-overflow:] + else: + encoded_tx_part = remaining_tx + remaining_tx = b"" apdu = LedgerIdentityProvider.SIGN_TX_OP_CONT - apdu += bytearray([len(encoded_tx)]) - apdu += encoded_tx + apdu += bytearray([len(encoded_tx_part)]) + apdu += encoded_tx_part result = self.dongle.exchange(apdu) + except CommException as e: - if e.sw == 27013: + if e.sw == 0x6985: # Common status word for user denial raise RuntimeError("Transaction denied from Ledger by user") - raise RuntimeError(e.message, e.sw) - - transaction.pop("from") - unsigned_transaction = serializable_unsigned_transaction_from_dict( - transaction) - raw_transaction = encode_transaction(unsigned_transaction, - vrs=(result[0], - int.from_bytes( - result[1:33], byteorder="big"), - int.from_bytes(result[33:65], byteorder="big"))) + raise RuntimeError(f"Ledger error: {e.sw:x}") + + v_raw = result[0] + + if v_raw <= 1: + v_parity = v_raw + else: + v_parity = 1 - (v_raw % 2) + + v = (chain_id * 2 + 35) + v_parity + + r = int.from_bytes(result[1:33], byteorder = "big") + s = int.from_bytes(result[33:65], byteorder = "big") + + signed_tx = Transaction( + nonce = tx_obj.nonce, + gasPrice = tx_obj.gasPrice, + gas = tx_obj.gas, + to = tx_obj.to, + value = tx_obj.value, + data = tx_obj.data, + v = v, + r = r, + s = s + ) + + raw_transaction = rlp.encode(signed_tx) return send_and_wait_for_transaction(raw_transaction, self.w3, out_f) def sign_message_after_solidity_keccak(self, message): @@ -315,39 +380,43 @@ def parse_bip32_path(path): return result -def get_kws_for_identity_type(identity_type): - SECRET = True - PLAINTEXT = False +def get_kws_for_identity_type(identity_type: str) -> dict: + secret = True + plaintext = False + + result = {} if identity_type == "rpc": - return [("network", PLAINTEXT)] + result["network"] = plaintext elif identity_type == "mnemonic": - return [("mnemonic", SECRET)] + result["mnemonic"] = secret elif identity_type == "key": - return [("private_key", SECRET)] - # elif identity_type == "trezor": - # return [] - elif identity_type == "ledger": - return [] + result["private_key"] = secret elif identity_type == "keystore": - return [("keystore_path", PLAINTEXT)] + result["keystore_path"] = plaintext + elif identity_type in ["trezor", "ledger"]: + # empty dict + pass else: raise RuntimeError( "unrecognized identity_type {}".format(identity_type)) + return result def get_identity_types(): # temporary fully removed: trezor - return ["rpc", "mnemonic", "key", "ledger", "keystore"] + return ["rpc", "mnemonic", "key", "trezor", "ledger", "keystore"] def sign_transaction_with_private_key(w3, private_key, transaction): - return w3.eth.account.sign_transaction(transaction, private_key).rawTransaction + return w3.eth.account.sign_transaction(transaction, private_key).raw_transaction def sign_message_with_private_key(w3, private_key, message): - h = defunct_hash_message(message) - return w3.eth.account.signHash(h, private_key).signature + message_encoded = encode_defunct(primitive = message) + signed_message = w3.eth.account.sign_message(message_encoded, private_key) + + return signed_message.signature def unlock_keystore_with_password(w3, path_to_keystore): diff --git a/snet/cli/metadata/organization.py b/snet/cli/metadata/organization.py index 28a5c1af..311e02f0 100644 --- a/snet/cli/metadata/organization.py +++ b/snet/cli/metadata/organization.py @@ -88,7 +88,7 @@ def update_payment_expiration_threshold(self, payment_expiration_threshold): self.payment.payment_expiration_threshold = payment_expiration_threshold def update_payment_channel_storage_type(self, payment_channel_storage_type): - self.update_payment_channel_storage_type = payment_channel_storage_type + self.payment.payment_channel_storage_type = payment_channel_storage_type def update_payment_address(self, payment_address): self.payment.payment_address = payment_address @@ -102,9 +102,6 @@ def update_request_timeout(self, request_timeout): def update_endpoints(self, endpoints): self.payment.update_endpoints(endpoints) - def get_group_id(self, group_name=None): - return base64.b64decode(self.get_group_id_base64(group_name)) - def get_payment_address(self): return self.payment.payment_address diff --git a/snet/cli/test/functional_tests/func_tests.py b/snet/cli/test/functional_tests/func_tests.py index 30a35761..c10205e7 100644 --- a/snet/cli/test/functional_tests/func_tests.py +++ b/snet/cli/test/functional_tests/func_tests.py @@ -1,12 +1,8 @@ import warnings import argcomplete import unittest -import unittest.mock as mock -import shutil import os -from snet.cli.commands.commands import BlockchainCommand - with warnings.catch_warnings(): # Suppress the eth-typing package`s warnings related to some new networks warnings.filterwarnings("ignore", "Network .* does not have a valid ChainId. eth-typing should be " @@ -15,6 +11,12 @@ from snet.cli.config import Config +INFURA_KEY = os.environ.get("SNET_TEST_INFURA_KEY") +PRIVATE_KEY = os.environ.get("SNET_TEST_WALLET_PRIVATE_KEY") +ADDR = os.environ.get("SNET_TEST_WALLET_ADDRESS") +INFURA = f"https://sepolia.infura.io/v3/{INFURA_KEY}" +IDENTITY = "sepolia" + class StringOutput: def __init__(self): @@ -32,11 +34,12 @@ def execute(args_list, parser, conf): except TypeError: args = parser.parse_args(argv + ["-h"]) f = StringOutput() - getattr(args.cmd(conf, args, out_f = f), args.fn)() + getattr(args.cmd(conf, args, out_f=f), args.fn)() return f.text except Exception as e: raise + class BaseTest(unittest.TestCase): def setUp(self): self.conf = Config() @@ -44,90 +47,5 @@ def setUp(self): argcomplete.autocomplete(self.parser) -class TestCommands(BaseTest): - def test_balance_output(self): - result = execute(["account", "balance"], self.parser, self.conf) - assert len(result.split("\n")) >= 4 - - def test_balance_address(self): - result = execute(["account", "balance"], self.parser, self.conf) - assert result.split("\n")[0].split()[1] == "0xe5D1fA424DE4689F9d2687353b75D7a8987900fD" - -class TestDepositWithdraw(BaseTest): - def setUp(self): - super().setUp() - self.balance_1: int - self.balance_2: int - self.amount = 0.1 - - def test_deposit(self): - result = execute(["account", "balance"], self.parser, self.conf) - self.balance_1 = float(result.split("\n")[3].split()[1]) - execute(["account", "deposit", f"{self.amount}", "-y", "-q"], self.parser, self.conf) - result = execute(["account", "balance"], self.parser, self.conf) - self.balance_2 = float(result.split("\n")[3].split()[1]) - assert self.balance_2 == self.balance_1 + self.amount - - def test_withdraw(self): - result = execute(["account", "balance"], self.parser, self.conf) - self.balance_1 = float(result.split("\n")[3].split()[1]) - execute(["account", "withdraw", f"{self.amount}", "-y", "-q"], self.parser, self.conf) - result = execute(["account", "balance"], self.parser, self.conf) - self.balance_2 = float(result.split("\n")[3].split()[1]) - assert self.balance_2 == self.balance_1 - self.amount - - -class TestGenerateLibrary(BaseTest): - def setUp(self): - super().setUp() - self.path = './temp_files' - self.org_id = '26072b8b6a0e448180f8c0e702ab6d2f' - self.service_id = 'Exampleservice' - - def test_generate(self): - execute(["sdk", "generate-client-library", self.org_id, self.service_id, self.path], self.parser, self.conf) - assert os.path.exists(f'{self.path}/{self.org_id}/{self.service_id}/python/') - - def tearDown(self): - shutil.rmtree(self.path) - - -class TestEncryptionKey(BaseTest): - def setUp(self): - super().setUp() - self.key = "1234567890123456789012345678901234567890123456789012345678901234" - self.password = "some_pass" - self.name = "some_name" - self.default_name = "default_name" - result = execute(["identity", "list"], self.parser, self.conf) - if self.default_name not in result: - execute(["identity", "create", self.default_name, "key", "--private-key", self.key, "-de"], - self.parser, - self.conf) - - def test_1_create_identity_with_encryption_key(self): - with mock.patch('getpass.getpass', return_value=self.password): - execute(["identity", "create", self.name, "key", "--private-key", self.key], - self.parser, - self.conf) - result = execute(["identity", "list"], self.parser, self.conf) - assert self.name in result - - def test_2_get_encryption_key(self): - with mock.patch('getpass.getpass', return_value=self.password): - execute(["identity", self.name], self.parser, self.conf) - cmd = BlockchainCommand(self.conf, self.parser.parse_args(['session'])) - enc_key = cmd.config.get_session_field("private_key") - res_key = cmd._get_decrypted_secret(enc_key) - assert res_key == self.key - - def test_3_delete_identity(self): - with mock.patch('getpass.getpass', return_value=self.password): - execute(["identity", self.default_name], self.parser, self.conf) - execute(["identity", "delete", self.name], self.parser, self.conf) - result = execute(["identity", "list"], self.parser, self.conf) - assert self.name not in result - - if __name__ == "__main__": unittest.main() diff --git a/snet/cli/test/functional_tests/mint/mint.py b/snet/cli/test/functional_tests/mint/mint.py deleted file mode 100644 index bf37a47b..00000000 --- a/snet/cli/test/functional_tests/mint/mint.py +++ /dev/null @@ -1,62 +0,0 @@ -from snet.contracts import get_contract_object - -from packages.snet_cli.snet.snet_cli.utils.utils import get_web3 -from web3.gas_strategies.time_based import medium_gas_price_strategy - -TRANSACTION_TIMEOUT = 500 -DEFAULT_GAS = 300000 -HTTP_PROVIDER = "http://localhost:8545" - -wallet_address_1 = "0x592E3C0f3B038A0D673F19a18a773F993d4b2610" -contract_address = "0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14" -signer_private_key = ( - "0xc71478a6d0fe44e763649de0a0deb5a080b788eefbbcf9c6f7aef0dd5dbd67e0" -) - -initialNonce = 0 -mint_amount = 10000000000000000 - - -def _get_nonce(web3, address): - nonce = web3.eth.get_transaction_count(address) - if initialNonce >= nonce: - nonce = initialNonce + 1 - nonce = nonce - return nonce - - -def send_transaction(web3, contract_fn, *args): - txn_hash = _send_signed_transaction(web3, contract_fn, *args) - return web3.eth.wait_for_transaction_receipt(txn_hash, TRANSACTION_TIMEOUT) - - -def _send_signed_transaction(web3, wallet_address, contract_fn, *args): - transaction = contract_fn(*args).buildTransaction( - { - "chainId": int(web3.version.network), - "gas": DEFAULT_GAS, - "gasPrice": web3.eth.gas_price * 4 / 3, - "nonce": _get_nonce(web3, wallet_address), - } - ) - - signed_txn = web3.eth.account.sign_transaction( - transaction, private_key=signer_private_key - ) - return web3.to_hex(web3.eth.send_raw_transaction(signed_txn.rawTransaction)) - - -def mint_token(): - w3 = get_web3(HTTP_PROVIDER) - address_1 = w3.to_checksum_address(wallet_address_1) - contract = get_contract_object( - w3, contract_file="SingularityNetToken.json", address=contract_address - ) - - send_transaction( - w3, wallet_address_1, contract.functions.mint, address_1, int(mint_amount) - ) - - -if __name__ == "__main__": - mint_token() diff --git a/snet/cli/test/functional_tests/script10_claim_timeout_all.sh b/snet/cli/test/functional_tests/script10_claim_timeout_all.sh deleted file mode 100755 index dd713ed9..00000000 --- a/snet/cli/test/functional_tests/script10_claim_timeout_all.sh +++ /dev/null @@ -1,39 +0,0 @@ -snet service metadata-init ./service_spec1/ ExampleService --group-name group0 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 9.8.9.8:8080 -snet service metadata-init ./service_spec1/ ExampleService -snet service metadata-add-group group1 -snet service metadata-add-endpoints group1 8.8.8.8:22 1.2.3.4:8080 - -snet service metadata-add-group group2 -snet service metadata-add-endpoints group2 8.8.8.8:2 1.2.3.4:800 - -snet organization metadata-init org1 testo individual -snet organization add-group group0 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet organization add-group group1 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 1.2.1.1:8089 -snet organization add-group group2 0x32267d505B1901236508DcDa64C1D0d5B9DF639a 1.2.1.1:8089 -snet organization create testo -y -q -snet service metadata-remove-group group0 -snet service publish testo tests -y -q - -EXPIRATION0=$(($(snet channel block-number) - 1)) -EXPIRATION1=$(($(snet channel block-number) - 1)) -EXPIRATION2=$(($(snet channel block-number) + 100000)) - -snet account deposit 100 -y -q - -assert_balance() { - MPE_BALANCE=$(snet account balance | grep MPE) - test ${MPE_BALANCE##*:} = $1 -} - -# should file because group_name has not been specified -snet channel open-init testo tests 1 $EXPIRATION0 -yq && exit 1 || echo "fail as expected" - -snet channel open-init testo group0 0.1 $EXPIRATION0 -yq -snet channel open-init testo group1 1 $EXPIRATION1 -yq -snet channel open-init testo group2 10 $EXPIRATION2 -yq - -assert_balance 88.9 - -# should claim channels 0 and 1, but not 2 -snet channel claim-timeout-all -y -assert_balance 90 diff --git a/snet/cli/test/functional_tests/script11_update_metadata.sh b/snet/cli/test/functional_tests/script11_update_metadata.sh deleted file mode 100755 index 7fb5f82d..00000000 --- a/snet/cli/test/functional_tests/script11_update_metadata.sh +++ /dev/null @@ -1,69 +0,0 @@ -# simple case of one group -snet service metadata-init ./service_spec1/ ExampleService --fixed-price 0.0001 --endpoints 8.8.8.8:2020 --group-name group1 - -snet --print-traceback organization metadata-init org1 testo individual -snet --print-traceback organization add-group group1 0x52653A9091b5d5021bed06c5118D24b23620c529 5.5.6.7:8089 -snet --print-traceback organization add-group group2 0x52653A9091b5d5021bed06c5118D24b23620c529 1.2.1.1:8089 -snet --print-traceback organization create testo -y -q -snet --print-traceback service publish testo tests -y -q - -# change group_id - -# case with several groups -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --group-name group0 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 9.8.9.8:8080 - -snet --print-traceback service metadata-add-daemon-addresses group0 0x123 -test "$(< service_metadata.json jq '.groups[0].daemon_addresses | length')" = 1 && echo "succes" || exit 1 -snet --print-traceback service metadata-add-daemon-addresses group0 0x234 - -snet --print-traceback service metadata-update-daemon-addresses group0 0x123 -test "$(< service_metadata.json jq '.groups[0].daemon_addresses | length')" = 1 && echo "succes" || exit 1 - -snet --print-traceback service metadata-add-daemon-addresses group10 0x123 || echo "fail as expected" - -snet --print-traceback service metadata-add-group group1 -snet --print-traceback service metadata-add-endpoints group1 8.8.8.8:22 1.2.3.4:8080 - - -snet --print-traceback service metadata-add-group group2 -snet --print-traceback service metadata-add-endpoints group2 8.8.8.8:2 1.2.3.4:800 - -# this should fail as group0 is not in organization -snet --print-traceback service update-metadata testo tests -yq && exit 1 || echo "fail as expected" -snet --print-traceback service metadata-remove-group group0 -snet --print-traceback service update-metadata testo tests -yq - - - -#add assets with single value - -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --metadata-file=service_asset_metadata.json -#cp service_metadata.json service_asset_metadata.json -snet --print-traceback service metadata-add-assets ./service_spec1/test hero_image --metadata-file=service_asset_metadata.json -snet --print-traceback service metadata-add-assets ./service_spec1/test terms_of_use --metadata-file=service_asset_metadata.json -result=$(cat service_asset_metadata.json | jq '.assets.hero_image') -test $result = '"QmWQhwwnvK4YHvEarEguTDhz8o2kwvyfPhv5favs1VS4xm/test"' && echo "add asset with single value test case passed " || exit 1 - -#add assets with multiple values -snet --print-traceback service metadata-add-assets ./service_spec1/test images --metadata-file=service_asset_metadata.json -snet --print-traceback service metadata-add-assets ./service_spec1/test images --metadata-file=service_asset_metadata.json -result=$(cat service_asset_metadata.json | jq '.assets.images[1]') -test $result = '"QmWQhwwnvK4YHvEarEguTDhz8o2kwvyfPhv5favs1VS4xm/test"' && echo "add asset with multiple value test case passed " || exit 1 - -#remove assets -snet --print-traceback service metadata-remove-assets hero_image --metadata-file=service_asset_metadata.json -result=$(cat service_asset_metadata.json | jq '.assets.hero_image') -test $result = '""' && echo "metadata-remove-assets test case passed " || exit 1 - -#remove all assets -snet --print-traceback service metadata-remove-all-assets --metadata-file=service_asset_metadata.json -result=$(cat service_asset_metadata.json | jq '.assets') -test $result = '{}' && echo "metadata-remove-all-assets test case passed " || exit 1 -rm service_asset_metadata.json - -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --group-name group1 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 9.8.9.8:8080 -snet --print-traceback service metadata-set-free-calls group1 12 -snet --print-traceback service metadata-set-freecall-signer-address group1 0x123 -test "$(< service_metadata.json jq '.groups[0].free_calls')" = 12 \ -&& test "$(< service_metadata.json jq '.groups[0].free_call_signer_address')" = '"0x123"' \ -&& echo "free call test passed" || exit 1 diff --git a/snet/cli/test/functional_tests/script12_extend_add_for_service.sh b/snet/cli/test/functional_tests/script12_extend_add_for_service.sh deleted file mode 100755 index 56919344..00000000 --- a/snet/cli/test/functional_tests/script12_extend_add_for_service.sh +++ /dev/null @@ -1,80 +0,0 @@ -snet organization metadata-init org1 testo individual -snet organization add-group group1 0x52653A9091b5d5021bed06c5118D24b23620c529 5.5.6.7:8089 -snet organization add-group group2 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 1.2.1.1:8089 -snet organization create test0 -y -q - -snet service metadata-init ./service_spec1/ ExampleService --fixed-price 0.0001 --endpoints 8.8.8.8:2020 --group-name group1 - -snet organization create testo -y -q -snet service publish testo tests -y -q - -snet account deposit 100000000 -yq - -snet channel open-init testo group1 123.123 1 -yq - -snet channel print-initialized | grep 123.223 && exit 1 || echo "fail as expected" - -snet --print-traceback channel extend-add-for-org testo group1 --amount 0.1 --expiration 314 -yq -snet channel extend-add-for-org testo group1 --amount 0.2 -yq -snet --print-traceback channel extend-add-for-org testo group1 --expiration 315 -yq -snet channel print-initialized | grep 123.423 -snet channel print-initialized | grep 315 - -rm -rf ~/.snet/mpe_client -snet --print-traceback channel extend-add-for-org testo group1 --amount 0.1 --expiration 315 -yq -snet channel extend-add-for-org testo group1 --amount 0.1 -yq -snet channel extend-add-for-org testo group1 --expiration 31415 -yq -snet channel print-initialized | grep 123.623 -snet channel print-initialized | grep 31415 - -snet --print-traceback channel open-init testo group1 7777.8888 1 -yq --open-new-anyway -snet channel extend-add-for-org testo group1 --amount 0.01 --expiration 314 -yq && exit 1 || echo "fail as expected" -snet channel extend-add-for-org testo group1 --amount 0.01 -yq && exit 1 || echo "fail as expected" -snet channel extend-add-for-org testo group1 --expiration 31477 -yq && exit 1 || echo "fail as expected" - -snet channel extend-add-for-org testo group1 --amount 0.01 --expiration 314 -yq --channel-id 1 -snet channel extend-add-for-org testo group1 --amount 0.01 --channel-id 1 -yq -snet channel extend-add-for-org testo group1 --expiration 31477 -yq --channel-id 1 -snet channel print-initialized | grep 7777.9088 -snet channel print-initialized | grep 31477 - -# multiply payment groups case -#snet service metadata-init ./service_spec1/ ExampleService 0x52653A9091b5d5021bed06c5118D24b23620c529 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 --group-name group2 -snet service metadata-add-group group2 -snet service metadata-add-endpoints group2 8.8.8.8:20202 9.10.9.8:8080 - -snet service update-metadata testo tests -yq - -snet channel open-init testo group2 2222.33333 1 -yq - -snet --print-traceback channel extend-add-for-org testo group1 --amount 0.001 --expiration 314 -yq && exit 1 || echo "fail as expected" -snet channel extend-add-for-org testo group1 --amount 0.001 -yq && exit 1 || echo "fail as expected" -snet channel extend-add-for-org testo group1 --expiration 4321 -yq && exit 1 || echo "fail as expected" - -snet channel extend-add-for-org testo group2 --amount 0.001 --expiration 4321 -yq -snet channel extend-add-for-org testo group2 --amount 0.001 -yq -snet channel extend-add-for-org testo group2 --expiration 4321 -yq - -snet channel print-initialized -snet channel print-initialized | grep 2222.33533 -snet channel print-initialized | grep 4321 - -#reinitializing the channel use the existing chnanels. -snet channel open-init testo group2 2222.33333 1 -yq - -snet channel print-initialized -snet channel extend-add-for-org testo group2 --amount 0.0001 --expiration 4444 -yq -snet channel extend-add-for-org testo group2 --amount 0.0001 -yq -snet channel extend-add-for-org testo group2 --expiration 5643 -yq -snet channel print-initialized -snet channel print-initialized | grep 2222.33553 -snet channel print-initialized | grep 5643 - -rm -rf ~/.snet/mpe_client - -snet channel extend-add-for-org testo group2 --amount 0.00001 --expiration 7654 -yq -snet channel extend-add-for-org testo group2 --amount 0.00001 -yq -snet channel extend-add-for-org testo group2 --expiration 7655 -yq -snet channel print-initialized -snet channel print-initialized | grep 2222.33555 -snet channel print-initialized | grep 7655 diff --git a/snet/cli/test/functional_tests/script13_call_reinitialize.sh b/snet/cli/test/functional_tests/script13_call_reinitialize.sh deleted file mode 100644 index 3b7ea88b..00000000 --- a/snet/cli/test/functional_tests/script13_call_reinitialize.sh +++ /dev/null @@ -1,64 +0,0 @@ -# script13 - -# run daemon -cd simple_daemon -python test_simple_daemon.py & -DAEMON=$! -cd .. - -snet service metadata-init ./service_spec1/ ExampleService --fixed-price 0.0001 --endpoints 127.0.0.1:50051 --group-name group1 -snet account deposit 12345 -y -q -snet organization metadata-init org1 testo individual -snet organization add-group group1 0x52653A9091b5d5021bed06c5118D24b23620c529 127.0.0.1:50051 - -snet organization create testo -y -q - -snet service publish testo tests -y -q -snet --print-traceback service print-service-status testo tests -snet --print-traceback channel open-init testo group1 1 +10days -yq - -snet --print-traceback client call testo tests group1 classify {} -y - -rm -rf ~/.snet/mpe_client - -snet client call testo tests group1 classify {} -y -snet --print-traceback client call testo tests group1 classify {} -y --skip-update-check - -# we will corrupt initialized channel -rm -rf ~/.snet/mpe_client/*/testo/tests/service/*py -rm -rf ~/.snet/mpe_client/*/testo/channel* -# in the current version snet-cli cannot detect this problem, so it should fail -# and it is ok, because it shoudn't update service at each call -snet client call testo tests classify group1 {} -y && exit 1 || echo "fail as expected" - -snet service metadata-add-endpoints group1 localhost:50051 - -# this should still fail because we skip registry check -snet client call testo tests group1 classify {} -y --skip-update-check && exit 1 || echo "fail as expected" - -snet service update-metadata testo tests -yq - -# no snet-cli should automatically update service, because metadataURI has changed -snet --print-traceback client call testo tests group1 classify {} -y - -# multiply payment groups case -# multiply payment groups case -snet service metadata-init ./service_spec1/ ExampleService --fixed-price 0.0001 --endpoints 127.0.0.1:50051 --group-name group1 - -snet organization add-group group2 0x52653A9091b5d5021bed06c5118D24b23620c529 127.0.0.1:50051 -snet organization update-metadata testo -yq -snet --print-traceback service publish testo tests2 -y -q -snet service print-service-status testo tests2 -snet --print-traceback client call testo tests2 group2 classify {} -y && exit 1 || echo "fail as expected" - -snet service metadata-add-group group2 -snet service metadata-set-fixed-price group2 0.0001 -snet service metadata-add-endpoints group2 127.0.0.1:50051 -snet service update-metadata testo tests2 -y - -snet --print-traceback channel open-init testo group2 1 +10days -yq -snet --print-traceback client call testo tests2 group2 classify {} -y - -rm -rf ~/.snet/mpe_client - -kill $DAEMON diff --git a/snet/cli/test/functional_tests/script14_full_stateless_logic.sh b/snet/cli/test/functional_tests/script14_full_stateless_logic.sh deleted file mode 100644 index 00825283..00000000 --- a/snet/cli/test/functional_tests/script14_full_stateless_logic.sh +++ /dev/null @@ -1,53 +0,0 @@ -# Test get-channel-state -# run daemon -cd simple_daemon -python test_simple_daemon.py & -DAEMON=$! -cd .. - -snet service metadata-init ./service_spec1/ ExampleService --fixed-price 0.0001 --endpoints 127.0.0.1:50051 --group-name group1 -snet account deposit 12345 -y -q -snet organization metadata-init org1 testo individual -snet organization add-group group1 0x52653A9091b5d5021bed06c5118D24b23620c529 127.0.0.1:50051 - -snet organization create testo -y -q - -snet service publish testo tests -y -q -snet channel open-init testo group1 1 +10days -yq -snet channel print-initialized - -test_get_channel_state() { - MPE_BALANCE=$(snet client get-channel-state 0 localhost:50051 | grep current_unspent_amount_in_cogs) - test ${MPE_BALANCE##*=} = $1 -} - -test_get_channel_state 100000000 - -snet client call testo tests group1 classify {} -y - -test_get_channel_state 99990000 - -snet channel print-initialized -snet --print-traceback treasurer claim-all --endpoint localhost:50051 --wallet-index 9 -yq - -test_get_channel_state 99990000 - -snet client call testo tests group1 classify {} -y -snet client call testo tests group1 classify {} -y - -test_get_channel_state 99970000 - -# we will start claim of all channels but will not write them to blockchain -echo n | snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 && exit 1 || echo "fail as expected" - -test_get_channel_state 99970000 -snet client call testo tests group1 classify {} -y -test_get_channel_state 99960000 - -snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -test_get_channel_state 99960000 -snet client call testo tests group1 classify {} -y - -test_get_channel_state 99950000 - -kill $DAEMON diff --git a/snet/cli/test/functional_tests/script15_sdk_generate_client_library.sh b/snet/cli/test/functional_tests/script15_sdk_generate_client_library.sh deleted file mode 100755 index 4b0006c2..00000000 --- a/snet/cli/test/functional_tests/script15_sdk_generate_client_library.sh +++ /dev/null @@ -1,21 +0,0 @@ -# simple case of one group -snet service metadata-init ./service_spec1/ ExampleService --group-name group1 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 -snet organization metadata-init org1 testo individual -snet organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 127.0.0.1:50051 -snet organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 127.0.0.1:50051 -snet organization create testo -y -q -snet service publish testo tests -y -q - -snet sdk generate-client-library python testo tests -test -f client_libraries/testo/tests/python/ExampleService_pb2_grpc.py - -snet sdk generate-client-library nodejs testo tests -test -f client_libraries/testo/tests/nodejs/ExampleService_grpc_pb.js - -# test relative path (and using already installed compiler) -snet sdk generate-client-library nodejs testo tests snet_output -test -f snet_output/testo/tests/nodejs/ExampleService_grpc_pb.js - -# test absolute path -snet sdk generate-client-library nodejs testo tests /tmp/snet_output -test -f /tmp/snet_output/testo/tests/nodejs/ExampleService_grpc_pb.js diff --git a/snet/cli/test/functional_tests/script1_twogroups.sh b/snet/cli/test/functional_tests/script1_twogroups.sh deleted file mode 100755 index 3b95f983..00000000 --- a/snet/cli/test/functional_tests/script1_twogroups.sh +++ /dev/null @@ -1,259 +0,0 @@ -snet session - -# service side - -#should fail (not existed directory) -snet service metadata-init ./bad_dir/ ExampleService --encoding json --service-type jsonrpc --group-name group1 && exit 1 || echo "fail as expected" - -#should fail (directory doesn't contain any *.proto files) -snet service metadata-init ./ ExampleService --encoding json --service-type jsonrpc --group-name group1 && exit 1 || echo "fail as expected" - -# happy flow -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 -jq .model_ipfs_hash=1 service_metadata.json >tmp.txt -mv -f tmp.txt service_metadata.json -snet service metadata-set-model ./service_spec1/ -snet service metadata-add-description --json '{"description_string":"string1","description_int":1,"description_dict":{"a":1,"b":"s"}}' -snet service metadata-add-description --json '{"description_string":"string1","description_int":1,"description_dict":{"a":1,"b":"s"}}' --description "description" --url "http://127.0.0.1" -cat service_metadata.json | jq '.service_description.url' | grep "http://127.0.0.1" -snet service metadata-add-description --url "http://127.0.0.2" -cat service_metadata.json | jq '.service_description.url' | grep "http://127.0.0.2" -snet service metadata-add-description --json '{"description":"s"}' --description "description" && exit 1 || echo "fail as expected" -snet service metadata-add-description --json '{"url":"http://127.0.0.1"}' --url "http://127.0.0.2" && exit 1 || echo "fail as expected" - -#seconf argument is group_id should be removed -snet service metadata-add-group group2 -snet service metadata-add-endpoints group1 8.8.8.8:2020 9.8.9.8:8080 -snet service metadata-add-endpoints group2 8.8.8.8:22 1.2.3.4:8080 -grep "8.8.8.8:2020" service_metadata.json -snet service metadata-remove-all-endpoints group2 -grep "8.8.8.8:22" service_metadata.json && exit 1 || echo "fail as expected" -snet service metadata-remove-all-endpoints group1 -snet service metadata-add-endpoints group1 8.8.8.8:2020 9.8.9.8:8080 -snet service metadata-add-endpoints group2 8.8.8.8:22 1.2.3.4:8080 -snet --print-traceback service metadata-update-endpoints group2 8.8.8.8:23456 1.2.3.4:22 -grep "8.8.8.8:23456" service_metadata.json -grep "8.8.8.8:2020" service_metadata.json -grep "9.8.9.8:8080" service_metadata.json -grep "8.8.8.8:22" service_metadata.json && exit 1 || echo "fail as expected" -grep "1.2.3.4:8080" service_metadata.json && exit 1 || echo "fail as expected" - -snet service metadata-set-fixed-price group1 0.0001 - -# test --endpoints and --fixed-price options in 'snet service metadata-init' -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 --fixed-price 0 --endpoints 8.8.8.8:2020 9.8.9.8:8080 --metadata-file service_metadata2.json -grep fixed_price service_metadata2.json -snet service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 9.8.9.8:8080 --metadata-file service_metadata2.json -grep fixed_price service_metadata2.json -grep 9.8.9.8:8080 service_metadata2.json - -IPFS_HASH=$(snet service publish-in-ipfs) -echo $IPFS_HASH -ipfs cat $IPFS_HASH >service_metadata2.json - -# compare service_metadata.json and service_metadata2.json -cmp <(jq -S . service_metadata.json) <(jq -S . service_metadata2.json) -snet organization metadata-init org1 testo individual -grep org1 organization_metadata.json -snet organization create testo && exit 1 || echo "fail as expected" -# -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 -grep 5.5.6.7 organization_metadata.json -grep 0x42A605c07EdE0E1f648aB054775D6D4E38496144 organization_metadata.json -grep 5.5.6.7:8089 organization_metadata.json -snet --print-traceback organization create testo -y -snet organization print-metadata org1 testo >organization_metadata_print.json - -snet service metadata-add-tags tag1 tag2 tag3 -grep "tag1" service_metadata.json -grep "tag2" service_metadata.json -grep "tag3" service_metadata.json -grep "tag4" service_metadata.json && exit 1 || echo "fail as expected" - -snet service metadata-remove-tags tag2 tag1 -grep "tag2" service_metadata.json && exit 1 || echo "fail as expected" -grep "tag1" service_metadata.json && exit 1 || echo "fail as expected" -grep "tag3" service_metadata.json - -snet service publish testo tests -y -q -snet service update-add-tags testo tests tag1 tag2 tag3 -y -q -snet service update-remove-tags testo tests tag2 tag1 -y -q -snet service print-tags testo tests - -# it should have only tag3 now -cmp <(echo "tag3") <(snet service print-tags testo tests) - -snet service print-metadata testo tests >service_metadata3.json - -# compare service_metadata.json and service_metadata3.json -cmp <(jq -S . service_metadata.json) <(jq -S . service_metadata3.json) - -# test get_api_registry and -snet service get-api-registry testo tests _d1 -snet service get-api-metadata --metadata-file service_metadata3.json _d2 - -# as usual, by default it is metatada_file=service_metadata.json -snet service get-api-metadata _d3 - -cmp ./service_spec1/ExampleService.proto _d1/ExampleService.proto -cmp ./service_spec1/ExampleService.proto _d2/ExampleService.proto -cmp ./service_spec1/ExampleService.proto _d3/ExampleService.proto - -rm -r _d1 _d2 _d3 - -# client side -snet account balance -snet account deposit 123456 -y -q -snet account transfer 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 42 -y -q -snet account withdraw 1 -y -q - -#open channel usig org and group -snet --print-traceback channel open-init-metadata testo group1 42 1 -y -q -snet channel print-initialized -snet channel claim-timeout 0 -y -q -snet channel print-initialized -# we do not send transaction second time -snet channel claim-timeout 0 -y -q && exit 1 || echo "fail as expected" - -snet channel extend-add 0 --expiration 10000 --amount 42 -y -q -snet channel print-initialized -snet channel extend-add 0 --amount 42 -y -q -snet channel print-initialized -snet channel extend-add 0 --expiration +10000blocks -y -q -snet channel extend-add 0 --expiration +10000days -y -q && exit 1 || echo "fail as expected" -snet channel extend-add 0 --expiration +10000days --force -y -q -snet channel extend-add 0 --expiration 57600000 --force -y -q && exit 1 || echo "fail as expected" - -EXPIRATION1=$(($(snet channel block-number) + 57600000)) -snet channel extend-add 0 --expiration $EXPIRATION1 --force --amount 0 -y -q - -snet channel open-init testo group1 9712.1234 +14days -y -q - -# test print_initialized_channels and print_all_channels. We should have channels openned for specific identity -snet channel print-initialized -snet --print-traceback channel print-initialized | grep 84 -snet channel print-all-filter-sender | grep 0x42A605c07EdE0E1f648aB054775D6D4E38496144 - -# we have two initilized channels one for group1 and anther for group1 (recipient=0x42A605c07EdE0E1f648aB054775D6D4E38496144) - -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --group-name group2 --fixed-price 0.0001 --endpoints 8.8.8.8:2020 --metadata-file service_metadata2.json -grep "8.8.8.8:2020" service_metadata2.json -snet service metadata-update-endpoints group2 8.8.8.8:2025 --metadata-file service_metadata2.json -grep "8.8.8.8:2025" service_metadata2.json -grep "8.8.8.8:2020" service_metadata2.json && exit 1 || echo "fail as expected" - -snet service publish testo tests2 -y -q --metadata-file service_metadata2.json - -snet channel open-init testo group2 7234.345 1 -y -q --signer 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB - -snet --print-traceback channel print-initialized-filter-org testo group2 -snet channel print-initialized-filter-org testo group2 | grep 7234.345 -snet channel print-initialized-filter-org testo group2 | grep 9712.1234 && exit 1 || echo "fail as expected" - -snet channel print-initialized -snet channel print-initialized | grep 84 -snet channel print-initialized | grep 7234.345 - -snet channel print-initialized --only-id -snet channel print-initialized --only-id | grep 7234.345 && exit 1 || echo "fail as expected" - -snet channel print-initialized --filter-signer | grep 7234.345 && exit 1 || echo "fail as expected" -snet channel print-initialized --filter-signer --wallet-index 1 | grep 7234.345 - -snet channel print-initialized-filter-org testo group2 -snet channel print-initialized-filter-org testo group2 | grep 7234.345 - -rm -rf ~/.snet/mpe_client/ - -# snet shoundn't try to open new channels. He simply should reinitilize old ones -snet channel open-init testo group1 0 0 -y -q -snet channel open-init testo group2 0 0 -y -q -snet channel open-init testo group2 0 0 --signer 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB -y -q -snet channel print-initialized | grep 7234.345 -snet channel print-initialized | grep 84 -snet channel open-init-metadata testo group2 0 0 - -rm -rf ~/.snet/mpe_client/ -# this should open new channel instead of using old one -snet channel open-init testo group2 111222 1 --open-new-anyway -yq -snet channel print-initialized | grep 9712.1234 && exit 1 || echo "fail as expected" -snet channel print-initialized-filter-org testo group2 | grep 111222 - -rm -rf ~/.snet/mpe_client/ - -snet --print-traceback channel print-all-filter-group testo group2 -snet channel print-all-filter-sender -snet channel print-all-filter-recipient - -#Uncomment this when all testing is done -#snet channel print-all-filter-sender | grep 0x42A605c07EdE0E1f648aB054775D6D4E38496144 -# -#snet channel print-all-filter-recipient | grep 0x52653A9091b5d5021bed06c5118D24b23620c529 && exit 1 || echo "fail as expected" -#snet channel print-all-filter-recipient --wallet-index 9 |grep 0x52653A9091b5d5021bed06c5118D24b23620c529 -#snet channel print-all-filter-recipient --recipient 0x52653A9091b5d5021bed06c5118D24b23620c529 |grep 0x52653A9091b5d5021bed06c5118D24b23620c529 -# -#snet channel print-all-filter-group testo group2 | grep 0x52653A9091b5d5021bed06c5118D24b23620c529 -#snet channel print-all-filter-group testo group2 | grep 0x42A605c07EdE0E1f648aB054775D6D4E38496144 && exit 1 || echo "fail as expected" -# -#snet channel print-all-filter-group testo group2 |grep 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 -# -#snet channel print-all-filter-group-sender testo group2 | grep 0x52653A9091b5d5021bed06c5118D24b23620c529 -#snet channel print-all-filter-group-sender testo group2 | grep 0x42A605c07EdE0E1f648aB054775D6D4E38496144 && exit 1 || echo "fail as expected" - -# should fail because of wrong groupId -snet channel init-metadata testo metadata-tests 0 --metadata-file service_metadata2.json && exit 1 || echo "fail as expected" -snet channel init testo wrong_group_name 1 && exit 1 || echo "fail as expected" - -snet --print-traceback channel init-metadata testo group1 1 -snet --print-traceback channel init testo group2 1 -snet channel print-initialized -snet channel print-all-filter-sender -snet service delete testo tests -y -q -snet organization list-services testo - -# open channel with sender=signer=0x32267d505B1901236508DcDa64C1D0d5B9DF639a - -snet account transfer 0x32267d505B1901236508DcDa64C1D0d5B9DF639a 1 -y -q -snet channel open-init testo group2 1 314156700003452 --force -y -q --wallet-index 3 -snet channel print-all-filter-sender --sender 0x32267d505B1901236508DcDa64C1D0d5B9DF639a | grep 314156700003452 -snet channel print-all-filter-sender | grep 314156700003452 && exit 1 || echo "fail as expected" - -snet channel print-all-filter-group-sender testo group2 --sender 0x32267d505B1901236508DcDa64C1D0d5B9DF639a | grep 314156700003452 -snet organization list-services testo -# test migration to different network - -# get service metadata from registry and set mpe_address to wrong value -snet service print-metadata testo tests2 | jq '.mpe_address = "0x52653A9091b5d5021bed06c5118D24b23620c529"' >service_metadata.json - -# this should fail because of wrong mpe_address -snet service publish-in-ipfs && exit 1 || echo "fail as expected" - -snet service publish-in-ipfs --multipartyescrow-at 0x52653A9091b5d5021bed06c5118D24b23620c529 -snet service publish-in-ipfs && exit 1 || echo "fail as expected" -snet service publish-in-ipfs --update-mpe-address -snet --print-traceback service publish-in-ipfs - -snet --print-traceback service print-metadata testo tests2 | jq '.mpe_address = "0x52653A9091b5d5021bed06c5118D24b23620c529"' >service_metadata.json - -# this should fail because of wrong mpe_address -snet service publish testo tests4 && exit 1 || echo "fail as expected" - -snet --print-traceback service publish testo tests4 --multipartyescrow-at 0x52653A9091b5d5021bed06c5118D24b23620c529 -yq -snet service publish testo tests5 -yq && exit 1 || echo "fail as expected" -snet service publish testo tests6 --update-mpe-address -yq -snet service publish testo tests7 -yq - -# test snet service update-metadata -snet service metadata-add-group group1 -#group already added -snet service metadata-add-group group2 && exit 1 || echo "fail as expected" -snet service metadata-add-endpoints group1 8.8.8.8:22 1.2.3.4:8080 -snet service update-metadata testo tests7 -y - - -#testcase for updating fixed price -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 --fixed-price 0.01212 --endpoints 8.8.8.8:2020 9.8.9.8:8080 --metadata-file service_metadata_fixed_price.json -grep "1212000" service_metadata_fixed_price.json -snet service metadata-set-fixed-price group1 0.2323 --metadata-file service_metadata_fixed_price.json -grep "23230000" service_metadata_fixed_price.json diff --git a/snet/cli/test/functional_tests/script2_deposit_transfer.sh b/snet/cli/test/functional_tests/script2_deposit_transfer.sh deleted file mode 100755 index 806ea007..00000000 --- a/snet/cli/test/functional_tests/script2_deposit_transfer.sh +++ /dev/null @@ -1,24 +0,0 @@ -# test deposit and transfer functions in snet client - -# initial balance should be 0 -MPE_BALANCE=$(snet account balance|grep MPE) -test ${MPE_BALANCE##*:} = "0" - -snet account deposit 12345.678 -y -q - -MPE_BALANCE=$(snet account balance|grep MPE) -test ${MPE_BALANCE##*:} = "12345.678" - -snet account transfer 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 42.314 -y -q - -MPE_BALANCE=$(snet account balance --account 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18|grep MPE) -test ${MPE_BALANCE##*:} = "42.314" - - -MPE_BALANCE=$(snet account balance|grep MPE) -test ${MPE_BALANCE##*:} = "12303.364" - - -snet account withdraw 1.42 -y -q -MPE_BALANCE=$(snet account balance|grep MPE) -test ${MPE_BALANCE##*:} = "12301.944" diff --git a/snet/cli/test/functional_tests/script3_without_addresses.sh b/snet/cli/test/functional_tests/script3_without_addresses.sh deleted file mode 100755 index 6ed4c927..00000000 --- a/snet/cli/test/functional_tests/script3_without_addresses.sh +++ /dev/null @@ -1,77 +0,0 @@ -# service side -# check how snet-cli works if we pass contract address via command line interface - -# remove networks -rm -rf ../../snet/snet_cli/resources/contracts/networks/*.json - -#unset addresses -snet unset current_singularitynettoken_at || echo "could fail if hasn't been set (it is ok)" -snet unset current_registry_at || echo "could fail if hasn't been set (it is ok)" -snet unset current_multipartyescrow_at || echo "could fail if hasn't been set (it is ok)" - -# now snet-cli will work only if we pass contract addresses as commandline arguments - -# this should fail without addresses -snet account balance && exit 1 || echo "fail as expected" -snet organization create testo --org-id testo -y -q && exit 1 || echo "fail as expected" - -snet --print-traceback organization metadata-init org1 testo individual --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 -snet --print-traceback organization create testo -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 - -snet service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet service metadata-add-group group2 -snet service metadata-add-endpoints group1 8.8.8.8:2020 9.8.9.8:8080 -snet service metadata-add-endpoints group2 8.8.8.8:22 1.2.3.4:8080 -snet service metadata-set-fixed-price group1 0.0001 -snet service metadata-set-fixed-price group2 0.0001 - -snet service metadata-add-tags tag1 tag2 tag3 -grep "tag1" service_metadata.json -grep "tag2" service_metadata.json -grep "tag3" service_metadata.json -grep "tag4" service_metadata.json && exit 1 || echo "fail as expected" - -snet service metadata-remove-tags tag2 tag1 -grep "tag2" service_metadata.json && exit 1 || echo "fail as expected" -grep "tag1" service_metadata.json && exit 1 || echo "fail as expected" -grep "tag3" service_metadata.json - -IPFS_HASH=$(snet service publish-in-ipfs --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e) -ipfs cat $IPFS_HASH >service_metadata2.json - -# compare service_metadata.json and service_metadata2.json -cmp <(jq -S . service_metadata.json) <(jq -S . service_metadata2.json) - -snet service publish testo tests -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet service update-add-tags testo tests tag1 tag2 tag3 -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet service update-remove-tags testo tests tag2 tag1 -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet service print-tags testo tests --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet organization list --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -# it should have only tag3 now -cmp <(echo "tag3") <(snet service print-tags testo tests --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2) - -snet service print-metadata testo tests --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 | grep -v "We must check that hash in IPFS is correct" >service_metadata3.json - -# compare service_metadata.json and service_metadata3.json -cmp <(jq -S . service_metadata.json) <(jq -S . service_metadata3.json) - -# client side -snet account balance --snt 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet account deposit 12345 -y -q --snt 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet account transfer 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 42 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet account withdraw 1 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet channel open-init-metadata testo group1 42 1 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel claim-timeout 0 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet channel extend-add 0 --expiration 10000 --amount 42 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet channel open-init testo group2 1 1000000 -y -q --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel print-initialized --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel print-all-filter-sender --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -rm -rf ~/.snet/mpe_client/ -snet channel init-metadata testo group1 0 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel init testo group1 1 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel print-initialized --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e --registry 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet channel print-all-filter-sender --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet service delete testo tests -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet organization list-services testo --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 diff --git a/snet/cli/test/functional_tests/script4_only_with_networks.sh b/snet/cli/test/functional_tests/script4_only_with_networks.sh deleted file mode 100755 index 753131a1..00000000 --- a/snet/cli/test/functional_tests/script4_only_with_networks.sh +++ /dev/null @@ -1,96 +0,0 @@ -# We try to get config address from the differnt sources. -# The order of priorioty is following: -# - command line argument (at or _at) -# - current session configuration (current__at) -# - networks/*json - -# In this test we check this priority - -rm -rf ../../snet/snet_cli/resources/contracts/networks/*.json - -#unset addresses -snet unset current_singularitynettoken_at || echo "could fail if hasn't been set (it is ok)" -snet unset current_registry_at || echo "could fail if hasn't been set (it is ok)" -snet unset current_multipartyescrow_at || echo "could fail if hasn't been set (it is ok)" -snet session -# this should fail without addresses -snet account balance && exit 1 || echo "fail as expected" -snet --print-traceback organization metadata-init org1 testo individual && exit 1 || echo "fail as expected" -snet organization create testo testo -y -q && exit 1 || echo "fail as expected" - -# set networks -echo '{"829257324":{"events":{},"links":{},"address":"0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/MultiPartyEscrow.json -echo '{"829257324":{"events":{},"links":{},"address":"0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/Registry.json -echo '{"829257324":{"events":{},"links":{},"address":"0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/SingularityNetToken.json - -# this should work -snet account balance -snet --print-traceback organization metadata-init org1 testo individual -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 -snet organization create testo -y -q -snet organization delete testo -y -q - -# this should fail (addresses are INVALID) -snet organization create testo -y -q --registry-at 0x1e74fefa82e83e0964f0d9f53c68e03f7298a8b2 && exit 1 || echo "fail as expected" -snet account balance --snt 0x1e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e && exit 1 || echo "fail as expected" - -# set INVALID addresses -snet set current_singularitynettoken_at 0x1e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 -snet set current_registry_at 0x1e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet set current_multipartyescrow_at 0x1c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e - -# this should fail because INVALID address -snet account balance && exit 1 || echo "fail as expected" -snet --print-traceback organization metadata-init org1 testo individual && exit 1 || echo "fail as expected" -snet organization create testo -y -q && exit 1 || echo "fail as expected" - -# this should work because command line has more priority -snet account balance --snt 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet --print-traceback organization metadata-init org1 testo individual --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 - -snet organization create testo -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet organization delete testo -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 - -# set INVALID networks -echo '{"829257324":{"events":{},"links":{},"address":"0x1c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/MultiPartyEscrow.json -echo '{"829257324":{"events":{},"links":{},"address":"0x1e74fefa82e83e0964f0d9f53c68e03f7298a8b2","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/Registry.json -echo '{"829257324":{"events":{},"links":{},"address":"0x1e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14","transactionHash":""}}' >../../snet/snet_cli/resources/contracts/networks/SingularityNetToken.json - -# this should fail (because addresses in networks are invalid ) -snet account balance && exit 1 || echo "fail as expected" -snet --print-traceback organization metadata-init org1 testo individual && exit 1 || echo "fail as expected" -snet organization create testo -y -q && exit 1 || echo "fail as expected" - -# set VALID session -snet set current_singularitynettoken_at 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 -snet set current_registry_at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet set current_multipartyescrow_at 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e - -# this should work -snet account balance -snet --print-traceback organization metadata-init org1 testo individual -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 -snet organization create testo -y -q -snet organization delete testo -y -q - -# set INVALID addresses -snet set current_singularitynettoken_at 0x1e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 -snet set current_registry_at 0x1e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet set current_multipartyescrow_at 0x1c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e - -# this should fail (because addresses in networks are invalid ) -snet account balance && exit 1 || echo "fail as expected" -snet --print-traceback organization metadata-init org1 testo individual && exit 1 || echo "fail as expected" -snet organization create testo -y -q && exit 1 || echo "fail as expected" - -# this should work because command line has more priority -snet account balance --snt 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 --mpe 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e -snet --print-traceback organization metadata-init org1 testo individual --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet --print-traceback organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet --print-traceback organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet organization create testo -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -snet organization delete testo -y -q --registry-at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 diff --git a/snet/cli/test/functional_tests/script5_identity1_rpc_mnemonic.sh b/snet/cli/test/functional_tests/script5_identity1_rpc_mnemonic.sh deleted file mode 100755 index e6126425..00000000 --- a/snet/cli/test/functional_tests/script5_identity1_rpc_mnemonic.sh +++ /dev/null @@ -1,73 +0,0 @@ -# test itentities managment. - -# This is first and second ganache identity -A0=0x592E3C0f3B038A0D673F19a18a773F993d4b2610 -A1=0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB - -assert_mpe_balance () { - MPE_BALANCE=$(snet account balance --account $1 |grep MPE) - test ${MPE_BALANCE##*:} = $2 -} - - -# this should fail because snet-user should be in use now -snet identity delete snet-user && exit 1 || echo "fail as expected" - -snet identity create key0 key --private-key 0xc71478a6d0fe44e763649de0a0deb5a080b788eefbbcf9c6f7aef0dd5dbd67e0 --network local - -snet identity create rpc0 rpc --network local -snet identity rpc0 - -# switch to main net (rpc0 is bind to the local network!) -snet network mainnet -snet account balance && exit 1 || echo "fail as expected" -snet network local - - -snet account deposit 100 -y -assert_mpe_balance $A0 100 - -# A0 -> A1 42 -snet account transfer $A1 42 -y -assert_mpe_balance $A1 42 - -snet identity create rpc1 rpc --network local --wallet-index 1 -snet identity rpc1 - -# A1 -> A0 1 -snet account transfer $A0 1 -y -assert_mpe_balance $A1 41 - -# A0 -> A1 2 -snet account transfer $A1 2 --wallet-index 0 -y -assert_mpe_balance $A1 43 - -snet identity create mne0 mnemonic --network local --mnemonic "a b c d" -snet identity mne0 -M0=`snet account print` -M1=`snet account print --wallet-index 1` - -snet identity create mne1 mnemonic --wallet-index 1 --network local --mnemonic "a b c d" -snet identity mne1 -M11=`snet account print` - -test $M1 = $M11 - -snet identity rpc0 - -# A0 -> M1 0.1 -snet account transfer $M1 0.1 -y -assert_mpe_balance $M1 0.1 - -# A0 -> M1 0.2 -snet identity key0 -snet account transfer $M1 0.1 -y -assert_mpe_balance $M1 0.2 - -snet identity snet-user -snet identity delete rpc0 -snet identity rpc0 && exit 1 || echo "fail as expected" - -snet identity delete rpc1 -snet identity delete mne0 -snet identity delete mne1 diff --git a/snet/cli/test/functional_tests/script6_organization.sh b/snet/cli/test/functional_tests/script6_organization.sh deleted file mode 100755 index 6bc1e2d2..00000000 --- a/snet/cli/test/functional_tests/script6_organization.sh +++ /dev/null @@ -1,104 +0,0 @@ -# Test "snet organization" - -snet organization metadata-init org1 testo individual -snet organization add-group group1 0x42A605c07EdE0E1f648aB054775D6D4E38496144 5.5.6.7:8089 -snet organization add-group group2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 1.2.1.1:8089 -snet organization create test0 -y -q - -# fail to create organization with the same id -snet organization create test0 -y -q && exit 1 || echo "fail as expected" - -## check if this feature is required --org-id and --auto are mutually exclusive -snet organization create test1 --org-id test1 --auto -y -q && exit 1 || echo "fail as expected" - -## create organization with random id -snet organization create test0 --auto -y -q && exit 1 || echo "fail as expected" - -snet organization create test1 --members 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB -y -q -snet organization create test2 --members 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB,0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 -y -q -snet organization add-members test2 0x32267d505B1901236508DcDa64C1D0d5B9DF639a -y -snet organization add-members test2 0x5c1011aB3C7f46EC5E78073D61DF6d002983F04a,0x42A605c07EdE0E1f648aB054775D6D4E38496144 -y -snet organization add-members test2 0x5c1011aB3C7f46EC5E78073D61DF6d002983F04a,0x42A605c07EdE0E1f648aB054775D6D4E38496144 -y | grep "No member was added" -snet organization add-members test2 0x5c1011aB3C7f46EC5E78073D61DF6d002983F04a,0x42A605c07EdE0E1f648aB054775D6D4E38496144,0xc990EEAad8c943E3C6bA4cbcd8a54a949Fb83f78 -y - -snet --print-traceback service metadata-init ./service_spec1/ ExampleService --encoding json --service-type jsonrpc --group-name group1 -snet service metadata-add-endpoints group1 8.8.8.8:22 1.2.3.4:8080 -snet service metadata-set-fixed-price group1 0.0001 -snet service publish test2 tests -y -q -snet service publish test2 tests2 -y -q -snet organization info test2 - -snet organization rem-members test2 0x32267d505B1901236508DcDa64C1D0d5B9DF639a,0x5c1011aB3C7f46EC5E78073D61DF6d002983F04a -y -snet organization rem-members test2 0x42A605c07EdE0E1f648aB054775D6D4E38496144 -y -snet organization rem-members test2 0x42A605c07EdE0E1f648aB054775D6D4E38496144,0xc990EEAad8c943E3C6bA4cbcd8a54a949Fb83f78 -y - -# second time shoudn't remove -snet organization rem-members test2 0x42A605c07EdE0E1f648aB054775D6D4E38496144,0xc990EEAad8c943E3C6bA4cbcd8a54a949Fb83f78 -y 2>&1 | grep "No member was removed" - -snet organization list -snet organization list-org-names -# test2 should be found here -snet organization list-my | grep test2 -snet organization info test2 - -snet --print-traceback organization metadata-add-assets ./service_spec1/test hero_image -result=$(< organization_metadata.json jq '.assets.hero_image') -test $result = '"QmWQhwwnvK4YHvEarEguTDhz8o2kwvyfPhv5favs1VS4xm/test"' && echo "add asset with single value test case passed " || exit 1 - -#remove assets -snet --print-traceback organization metadata-remove-assets hero_image -test "$(< organization_metadata.json jq '.assets.hero_image')" = '""' && echo "metadata-remove-assets test case passed " || exit 1 - -snet --print-traceback organization metadata-remove-all-assets -test "$(< organization_metadata.json jq '.assets')" = '{}' && echo "metadata-remove-all-assets test case passed " || exit 1 - -# description test -snet --print-traceback organization metadata-add-description --description "this is the dummy description of my org" \ ---short-description "this is short description" --url "dummy.com" - -(test "$(< organization_metadata.json jq '.description.description')" = '"this is the dummy description of my org"' \ -&& test "$(< organization_metadata.json jq '.description.short_description')" = '"this is short description"' \ -&& test "$(< organization_metadata.json jq '.description.url')" = '"dummy.com"' \ -&& echo "passed") || exit 1 - -# contacts test -# add contact -snet --print-traceback organization metadata-add-contact support --email dummy@dummy.io --phone 1234567890 -(test "$(< organization_metadata.json jq '.contacts | length')" = 1 \ -&& test "$(< organization_metadata.json jq '.contacts[0].contact_type')" = '"support"' \ -&& test "$(< organization_metadata.json jq '.contacts[0].phone')" = '"1234567890"' \ -&& test "$(< organization_metadata.json jq '.contacts[0].email_id')" = '"dummy@dummy.io"' \ -&& echo "passed") || exit 1 - -# add contact without email and phone -test "$(snet --print-traceback organization metadata-add-contact support)" = "email and phone both can not be empty" \ -|| exit 1 - -# remove contact by type -snet --print-traceback organization metadata-add-contact support --email support@dummy.io --phone 0987654321 -snet --print-traceback organization metadata-add-contact dummy --email dummy@dummy.io --phone 6789012345 -snet --print-traceback organization metadata-remove-contacts dummy -test "$(< organization_metadata.json jq '.contacts | length')" = 2 && echo "passed" || exit 1 - -# remove all contacts -snet --print-traceback organization metadata-remove-all-contacts -test "$(< organization_metadata.json jq '.contacts | length')" = 0 && echo "passed" || exit 1 - -## change test2 organization name to NEW_TEST2_NAME -#snet organization change-name test2 NEW_TEST2_NAME -y -#snet organization change-name test2 NEW_TEST2_NAME -y && exit 1 || echo "fail as expected" -## change test2 organization name back to test2 -#snet organization change-name test2 test2 -y - -snet organization change-owner test2 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB -y -snet organization change-owner test2 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB -y && exit 1 || echo "fail as expected" -snet organization add-members test2 0x32267d505B1901236508DcDa64C1D0d5B9DF639a -y && exit 1 || echo "fail as expected" - -# this should work because owner is the second account -snet organization add-members test2 0x32267d505B1901236508DcDa64C1D0d5B9DF639a --wallet-index 1 -y - -snet organization delete test2 -y && exit 1 || echo "fail as expected" - -snet organization delete test2 --wallet-index 1 -y - -snet organization info test2 || echo "fail as expected" diff --git a/snet/cli/test/functional_tests/script7_contracts.sh b/snet/cli/test/functional_tests/script7_contracts.sh deleted file mode 100644 index 28fd3f15..00000000 --- a/snet/cli/test/functional_tests/script7_contracts.sh +++ /dev/null @@ -1,31 +0,0 @@ -# Test "snet contracts" - -snet contract Registry --at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 createOrganization ExampleOrganization1 ExampleOrganization1 '["0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB"]' --transact -y -snet contract Registry createOrganization ExampleOrganization2 ExampleOrganization2 '["0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB","0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18"]' --transact -y -snet organization list 2>&1 | grep ExampleOrganization1 -snet organization list 2>&1 | grep ExampleOrganization2 - -# organization ExampleOrganization2 should alread have two given members -snet organization add-members ExampleOrganization2 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB,0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 -y 2>&1 | grep "No member was added" - -# deposit 1000000 cogs to MPE from the first address (0x592E3C0f3B038A0D673F19a18a773F993d4b2610) -snet contract SingularityNetToken --at 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 approve 0x5C7a4290F6F8FF64c69eEffDFAFc8644A4Ec3a4E 1000000 --transact -y -snet contract MultiPartyEscrow --at 0x5C7a4290F6F8FF64c69eEffDFAFc8644A4Ec3a4E deposit 1000000 --transact -y - -# deposit 1000000 cogs to MPE from the first address (0x592E3C0f3B038A0D673F19a18a773F993d4b2610) -snet contract SingularityNetToken approve 0x5C7a4290F6F8FF64c69eEffDFAFc8644A4Ec3a4E 1000000 --transact -y -snet contract MultiPartyEscrow deposit 1000000 --transact -y - -# check balance of the First account in MPE (it should be 2000000 cogs) -REZ=`snet contract MultiPartyEscrow --at 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e balances 0x592E3C0f3B038A0D673F19a18a773F993d4b2610` -test $REZ = 2000000 - -# We set expiration as current_block - 1 -EXPIRATION=$((`snet channel block-number` - 1)) -snet contract MultiPartyEscrow --at 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e openChannel 0x3b2b3C2e2E7C93db335E69D827F3CC4bC2A2A2cB 0x0067b427E299Eb2A4CBafc0B04C723F77c6d8a18 0 420000 $EXPIRATION --transact -y - -REZ=`snet contract MultiPartyEscrow nextChannelId` -test $REZ = 1 - -#We can immediately claim timeout because expiration was set in the past -snet contract MultiPartyEscrow --at 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e channelClaimTimeout 0 --transact -y \ No newline at end of file diff --git a/snet/cli/test/functional_tests/script8_networks.sh b/snet/cli/test/functional_tests/script8_networks.sh deleted file mode 100644 index 520d29e3..00000000 --- a/snet/cli/test/functional_tests/script8_networks.sh +++ /dev/null @@ -1,16 +0,0 @@ -# Test "snet network" - -snet network create local_bad http://localhost:8080 && exit 1 || echo "fail as expected" - -# create network without check -snet network create local_bad http://localhost:8080 --skip-check - -#switch to this network -snet network local_bad - -#switch to mainnet -snet network mainnet - -#switch to goerli -snet network goerli - diff --git a/snet/cli/test/functional_tests/script9_treasurer.sh b/snet/cli/test/functional_tests/script9_treasurer.sh deleted file mode 100644 index 638cca34..00000000 --- a/snet/cli/test/functional_tests/script9_treasurer.sh +++ /dev/null @@ -1,90 +0,0 @@ -# Test 'snet treasurer' - -# run daemon -cd simple_daemon -python test_simple_daemon.py & -DAEMON=$! -cd .. - - -snet account deposit 12345 -y -q - -# service provider has --wallet-index==9 (0x52653A9091b5d5021bed06c5118D24b23620c529) -# make two endpoints (both are actually valid) - -snet organization metadata-init org1 testo individual -snet organization add-group group0 0x52653A9091b5d5021bed06c5118D24b23620c529 5.5.6.7:8089 -snet organization create testo -y -q - - - - -snet service metadata-init ./service_spec1/ ExampleService --group-name group0 --fixed-price 0.0001 --endpoints 127.0.0.1:50051 -snet service publish testo tests -y -q - - - -assert_balance () { -MPE_BALANCE=$(snet account balance --account 0x52653A9091b5d5021bed06c5118D24b23620c529 |grep MPE) -test ${MPE_BALANCE##*:} = $1 -} - -EXPIRATION0=$((`snet channel block-number` + 100)) -EXPIRATION1=$((`snet channel block-number` + 100000)) -EXPIRATION2=$((`snet channel block-number` + 100000)) - -snet channel open-init-metadata testo group0 1 $EXPIRATION0 -yq #channe id =0 - -# add second endpoint to metadata (in order to test case with two endpoints in metadata) -snet service metadata-add-endpoints group0 localhost:50051 - -# formally we will have two open chanels (channnel_id = 1,2) for the same group (testo/group0) -snet channel open-init-metadata testo group0 1 $EXPIRATION1 -yq --open-new-anyway #channel id =1 -snet channel open-init-metadata testo group0 1 $EXPIRATION2 -yq --open-new-anyway #channel id =2 - -#low level equivalent to "snet client call testo tests0 classify {}" -snet --print-traceback client call-lowlevel testo tests group0 0 0 10000 classify {} -# should fail because nonce is incorect -snet client call-lowlevel testo tests group0 0 1 20000 classify {} && exit 1 || echo "fail as expected" -# should fail because amount is incorect -snet client call-lowlevel testo tests group0 0 0 10000 classify {} && exit 1 || echo "fail as expected" -snet client call testo tests group0 classify {} --save-response response.pb --channel-id 1 --endpoint http://127.0.0.1:50051 -y -snet client call testo tests group0 classify {} --save-field binary_field out.bin --channel-id 2 --endpoint http://localhost:50051 -y -snet client call testo tests group0 classify {} --save-field predictions out.txt --channel-id 2 -y -rm -f response.pb out.bin out.txt -snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -assert_balance 0.0004 -snet client call testo tests group0 classify {} -y --channel-id 0 -snet client call testo tests group0 classify {} -y --channel-id 1 -snet client get-channel-state 0 http://localhost:50051 -snet client get-channel-state 1 http://127.0.0.1:50051 - -# low level equivalent to "snet client call testo tests1 classify {} --channel-id 1" -snet client call-lowlevel testo tests group0 1 1 20000 classify {} - -snet client call testo tests group0 classify {} --channel-id 2 -y - -#only channel 0 should be claimed -snet treasurer claim-expired --expiration-threshold 1000 --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -assert_balance 0.0005 -snet treasurer claim 1 2 --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -assert_balance 0.0008 - -echo y | snet client call testo tests group0 classify {} --channel-id 0 -snet client call testo tests group0 classify {} --channel-id 0 -y -snet client call testo tests group0 classify {} --channel-id 1 -y -snet client call testo tests group0 classify {} --channel-id 2 -y - -# we will start claim of all channels but will not write then to blockchain -echo n | snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 && exit 1 || echo "fail as expected" -assert_balance 0.0008 - -snet client call testo tests group0 classify {} --channel-id 1 -y -snet client call testo tests group0 classify {} --channel-id 2 -y - -# and now we should claim everything (including pending payments) -snet treasurer claim-all --endpoint 127.0.0.1:50051 --wallet-index 9 -yq -assert_balance 0.0014 - -kill $DAEMON diff --git a/snet/cli/test/functional_tests/service_spec1/ExampleService.proto b/snet/cli/test/functional_tests/service_spec1/ExampleService.proto deleted file mode 100644 index 2b3cca6b..00000000 --- a/snet/cli/test/functional_tests/service_spec1/ExampleService.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -service ExampleService { - rpc classify(ClassifyRequest) returns (ClassifyResponse); -} - -message ClassifyRequest { - string image_type = 1; - string image = 2; -} - -message ClassifyResponse { - repeated string predictions = 1; - repeated float confidences = 2; - bytes binary_field = 3; -} - diff --git a/snet/cli/test/functional_tests/service_spec1/test b/snet/cli/test/functional_tests/service_spec1/test deleted file mode 100644 index 9daeafb9..00000000 --- a/snet/cli/test/functional_tests/service_spec1/test +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/snet/cli/test/functional_tests/test_aapreparation.py b/snet/cli/test/functional_tests/test_aapreparation.py new file mode 100644 index 00000000..37952d3b --- /dev/null +++ b/snet/cli/test/functional_tests/test_aapreparation.py @@ -0,0 +1,46 @@ +import unittest +from func_tests import BaseTest, execute, ADDR, IDENTITY, PRIVATE_KEY, INFURA, INFURA_KEY + + +class TestAAMainPreparations(BaseTest): + def setUp(self): + super().setUp() + self.new_network = "auto_test" + + def test_1_identity_create(self): + execute(["identity", "create", IDENTITY, "key", "--private-key", PRIVATE_KEY, "-de"], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + assert f"identity: {IDENTITY}" in result + + def test_2_set_network_mainnet(self): + execute(["network", "mainnet"], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + assert "network: mainnet" in result + + def test_3_set_network_sepolia(self): + execute(["network", "sepolia"], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + assert "network: sepolia" in result + + def test_41_network_create(self): + result = execute(["network", "create", self.new_network, INFURA], self.parser, self.conf) + assert f"add network with name='{self.new_network}'" in result + + def test_42_network_create_confirmation(self): + execute(["network", self.new_network], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + execute(["network", "sepolia"], self.parser, self.conf) + assert "network: ", self.new_network in result + + def test_5_set_infura(self): + execute(["set", "default_eth_rpc_endpoint", INFURA], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + assert INFURA_KEY in result + + def test_6_print_account(self): + result = execute(["account", "print"], self.parser, self.conf) + print(result) + assert ADDR in result + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_channels.py b/snet/cli/test/functional_tests/test_channels.py new file mode 100644 index 00000000..14ce54ef --- /dev/null +++ b/snet/cli/test/functional_tests/test_channels.py @@ -0,0 +1,79 @@ +from func_tests import BaseTest, execute, ADDR +import unittest +import re + + +class TestChannels(BaseTest): + def setUp(self): + super().setUp() + self.org_id = "SNet" + self.org_2_id = "singularitynet" + self.amount = "0.001" + self.password = "12345" + self.group = "default_group" + data = execute(["channel", "print-filter-sender"], self.parser, self.conf) + lines = data.split("\n") + self.max_id = "" + for line in lines: + parts = line.split() + if len(parts) >= 6 and parts[0].isdigit() and parts[-1].isdigit(): + self.max_id = parts[0] + + def test_channel_1_extend(self): + execute(["account", "deposit", self.amount, "-y", "-q"], self.parser, self.conf) + if self.max_id: + result1 = execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + else: + block_number = int(execute(["channel", "block-number"], self.parser, self.conf)) + channel_open_output = execute(["channel", "open", self.org_id, self.group, self.amount, f"{block_number+10000}", "-y", "--open-new-anyway"], self.parser, self.conf) + match = re.search(r"#channel_id\s+(\d+)", channel_open_output) + self.max_id = match.group(1) + execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + result1 = execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, + self.conf) + # result2 = execute(["channel", "extend-add-for-org", self.org_id, "default_group", "--channel-id", f"{self.max_id}", "-y"], self.parser, self.conf) + print(result1) + assert "event: ChannelAddFunds" in result1 + + def test_channel_2_print_filter_sender(self): + result = execute(["channel", "print-filter-sender"], self.parser, self.conf) + print(result) + assert "Channels for sender: ", ADDR in result + + def test_channel_3_print_filter_group_sender(self): + result = execute(["channel", "print-filter-group-sender", self.org_id, self.group], self.parser, self.conf) + assert "Channels for sender: ", ADDR in result + + def test_channel_4_print_filter_group(self): + result = execute(["channel", "print-filter-group", self.org_id, self.group], self.parser, self.conf) + assert self.max_id in result + + def test_channel_5_print_filter_recipient(self): + result = execute(["channel", "print-filter-recipient"], self.parser, self.conf) + assert "Channels for recipient:", ADDR in result + + def test_channel_5_claim(self): + execute(["account", "deposit", self.amount, "-y", "-q"], self.parser, self.conf) + if self.max_id: + execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + result1 = execute(["channel", "claim-timeout", f"{self.max_id}", "-y"], self.parser, self.conf) + execute(["account", "deposit", self.amount, "-y", "-q"], self.parser, self.conf) + execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + result2 = execute(["channel", "claim-timeout-all", "-y"], self.parser, self.conf) + else: + block_number = int(execute(["channel", "block-number"], self.parser, self.conf)) + execute(["channel", "open", self.org_id, self.group, self.amount, f"{block_number-1}", "-y"], self.parser, self.conf) + execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + result1 = execute(["channel", "claim-timeout", f"{self.max_id}", "-y"], self.parser, self.conf) + execute(["account", "deposit", self.amount, "-y", "-q"], self.parser, self.conf) + execute(["channel", "extend-add", self.max_id, "--amount", self.amount, "-y"], self.parser, self.conf) + result2 = execute(["channel", "claim-timeout-all", "-y"], self.parser, self.conf) + print(result1) + assert ("event: ChannelSenderClaim" in result1) and ("event: ChannelSenderClaim" in result2) + + def test_channel_6_print_all(self): + result = execute(["channel", "print-all", "-ds"], self.parser, self.conf) + assert self.max_id in result + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_client.py b/snet/cli/test/functional_tests/test_client.py new file mode 100644 index 00000000..e2af43c5 --- /dev/null +++ b/snet/cli/test/functional_tests/test_client.py @@ -0,0 +1,67 @@ +from func_tests import BaseTest, execute, ADDR, PRIVATE_KEY, INFURA +import os +import unittest + + +class TestClient(BaseTest): + def setUp(self): + super().setUp() + self.org_id = "egor-sing-test" + self.service_id = "hate-detection" + self.group = "default_group" + self.identity_name = "some__name" + self.method = "runsync" + self.params = "./detection.json" + self.endpoint = "https://ai-ui-service.singularitynet.io:8001" + self.max_id = "357" + self.nonce = "1" + self.amount_in_cogs = "1" + + def test_0_preparations(self): + identity_list=execute(["identity", "list"], self.parser, self.conf) + if self.identity_name not in identity_list: + execute(["identity", "create", self.identity_name, "key", "--private-key", PRIVATE_KEY, "-de"], self.parser, self.conf) + execute(["network", "sepolia"], self.parser, self.conf) + result = execute(["session"], self.parser, self.conf) + assert "network: sepolia" in result + + def test_1_channel_open(self): + execute(["set", "default_eth_rpc_endpoint", INFURA], self.parser, self.conf) + execute(["account", "deposit", "0.1", "-y"], self.parser, self.conf) + self.block=int(execute(["channel", "block-number"], self.parser, self.conf)) + print(self.block) + result = execute(["channel", "print-filter-group-sender", self.org_id, self.group], self.parser, self.conf) + if ADDR not in result[13:]: + result=execute(["channel", "open", self.org_id, "default_group", "0.0001", f"{self.block+100}", "-y"], self.parser, self.conf) + else: + pass + print(result) + assert "#channel_id" in result + + def test_2_service_call(self): + params_file = open("detection.json", "w+") + params_file.write("""{ + "input": { + "text": "Hello man answer me soon" + } +} + """) + params_file.close() + result=execute(["client", "call", self.org_id, self.service_id, self.group, self.method, self.params, "-y"], self.parser, self.conf) + assert "spam" in result + + def test_3_service_get_channel_state(self): + result=execute(["client", "get-channel-state", self.max_id, self.endpoint], self.parser, self.conf) + assert "current_unspent_amount_in_cogs = " in result + + def test_4_call_low_level(self): + result = execute(["client", "call-lowlevel", self.org_id, self.service_id, self.group, self.max_id, self.nonce, self.amount_in_cogs, self.method, self.params], self.parser, self.conf) + assert "spam" in result + + def test_5_get_api_registry(self): + execute(["service", "get-api-registry", self.org_id, self.service_id, "./"], self.parser, self.conf) + assert os.path.exists("./hate.proto") + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_commands.py b/snet/cli/test/functional_tests/test_commands.py new file mode 100644 index 00000000..d9fc692f --- /dev/null +++ b/snet/cli/test/functional_tests/test_commands.py @@ -0,0 +1,29 @@ +import unittest +from func_tests import BaseTest, execute, ADDR +import importlib + + +class TestCommands(BaseTest): + def setUp(self): + super().setUp() + + def test_balance_output(self): + result = execute(["account", "balance"], self.parser, self.conf) + assert len(result.split("\n")) >= 4 + + def test_balance_address(self): + result = execute(["account", "balance"], self.parser, self.conf) + assert result.split("\n")[0].split()[1] == ADDR + + def test_version(self): + file_path = "./version.py" + spec = importlib.util.spec_from_file_location("version", file_path) + version_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(version_module) + self.version = version_module.__version__ + result = execute(["version"], self.parser, self.conf) + assert f"version: {self.version}" in result + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_contract.py b/snet/cli/test/functional_tests/test_contract.py new file mode 100644 index 00000000..572e43e6 --- /dev/null +++ b/snet/cli/test/functional_tests/test_contract.py @@ -0,0 +1,71 @@ +from func_tests import BaseTest, execute, ADDR +import unittest + +class TestContract(BaseTest): + def setUp(self): + super().setUp() + self.last_channel_id = int(execute(["contract", "MultiPartyEscrow", "nextChannelId"], self.parser, self.conf)) - 1 + self.amount = "1" + self.block_number = int(execute(["channel", "block-number"], self.parser, self.conf)) + self.channel = execute(["channel", "print-filter-sender"], self.parser, self.conf).split()[11] + + def test_SingularityNetToken_name(self): + result = execute(["contract", "SingularityNetToken", "name"], self.parser, self.conf) + assert "SingularityNet Token" in result + + def test_SingularityNetToken_decimals(self): + result = execute(["contract", "SingularityNetToken", "decimals"], self.parser, self.conf) + assert "8" in result + + def test_SingularityNetToken_symbol(self): + result = execute(["contract", "SingularityNetToken", "symbol"], self.parser, self.conf) + assert "AGIX" in result + + def test_SingularityNetToken_totalSupply(self): + result = int(execute(["contract", "SingularityNetToken", "totalSupply"], self.parser, self.conf)) + assert 1772090920768158 <= result + + def test_SingularityNetToken_paused(self): + result=execute(["contract", "SingularityNetToken", "paused"], self.parser, self.conf) + assert "False" in result + + def test_MultiPartyEscrow_1_balances(self): + result = int(execute(["contract", "MultiPartyEscrow", "balances", ADDR], self.parser, self.conf)) + assert result > 0 + + def test_MultiPartyEscrow_token(self): + result = execute(["contract", "MultiPartyEscrow", "token"], self.parser, self.conf) + assert "0xf703b9aB8931B6590CFc95183be4fEf278732016" in result + + def test_MultiPartyEscrow_channels(self): + result = execute(["contract", "MultiPartyEscrow", "channels", f"{self.last_channel_id}"], self.parser, self.conf) + assert len(result) > 150 + + def test_MultiPartyEscrow_addFunds(self): + print(self.channel) + result = execute(["contract", "MultiPartyEscrow", "channelAddFunds", self.channel, self.amount, "-y"], self.parser, self.conf) + assert "event: ChannelAddFunds" in result + + def test_MultiPartyEscrow_channelExtend(self): + result = execute(["contract", "MultiPartyEscrow", "channelExtend", self.channel, f"{self.block_number+100}", "-y"], self.parser, self.conf).split()[11] + assert "event: ChannelExtend" in result + + def test_Registry_getOrganizationById(self): + result = execute(["contract", "Registry", "getOrganizationById", "SNet"], self.parser, self.conf) + assert len(result) > 400 + + def test_Registry_listOrganizations(self): + result = execute(["contract", "Registry", "listOrganizations"], self.parser, self.conf) + assert len(result) > 12000 + + def test_Registry_getServiceRegistrationById(self): + result = execute(["contract", "Registry", "getServiceRegistrationById", "SNet", "example-service-constructor"], self.parser, self.conf) + assert "True" in result + + def test_Registry_listServicesForOrganization(self): + result = execute(["contract", "Registry", "listServicesForOrganization", "SNet"], self.parser, self.conf) + assert "True" in result + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_deposit_withdraw_transfer.py b/snet/cli/test/functional_tests/test_deposit_withdraw_transfer.py new file mode 100644 index 00000000..e9d388ec --- /dev/null +++ b/snet/cli/test/functional_tests/test_deposit_withdraw_transfer.py @@ -0,0 +1,35 @@ +import unittest +from func_tests import BaseTest, execute, ADDR +import math + + +class TestDepositWithdrawTransfer(BaseTest): + def setUp(self): + super().setUp() + self.balance_1: int + self.balance_2: int + self.amount = 0.1 + + def test_deposit(self): + result = execute(["account", "balance"], self.parser, self.conf) + self.balance_1 = float(result.split("\n")[3].split()[1]) + execute(["account", "deposit", f"{self.amount}", "-y", "-q"], self.parser, self.conf) + result = execute(["account", "balance"], self.parser, self.conf) + self.balance_2 = float(result.split("\n")[3].split()[1]) + assert math.isclose(self.balance_2, self.balance_1 + self.amount, rel_tol=1e-3) + + def test_withdraw(self): + result = execute(["account", "balance"], self.parser, self.conf) + self.balance_1 = float(result.split("\n")[3].split()[1]) + execute(["account", "withdraw", f"{self.amount}", "-y", "-q"], self.parser, self.conf) + result = execute(["account", "balance"], self.parser, self.conf) + self.balance_2 = float(result.split("\n")[3].split()[1]) + assert math.isclose(self.balance_2, self.balance_1 - self.amount, rel_tol=1e-3) + + def test_transfer(self): + result = execute(["account", "transfer", ADDR, f"{self.amount}", "-y"], self.parser, self.conf) + assert "TransferFunds" in result + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_encryption_key.py b/snet/cli/test/functional_tests/test_encryption_key.py new file mode 100644 index 00000000..28bfa012 --- /dev/null +++ b/snet/cli/test/functional_tests/test_encryption_key.py @@ -0,0 +1,45 @@ +import unittest +from func_tests import BaseTest, execute, PRIVATE_KEY +import unittest.mock as mock +from snet.cli.commands.commands import BlockchainCommand + + +class TestEncryptionKey(BaseTest): + def setUp(self): + super().setUp() + self.key = PRIVATE_KEY + self.password = "some_pass" + self.name = "some_name" + self.default_name = "default_name" + result = execute(["identity", "list"], self.parser, self.conf) + if self.default_name not in result: + execute(["identity", "create", self.default_name, "key", "--private-key", self.key, "-de"], + self.parser, + self.conf) + + def test_1_create_identity_with_encryption_key(self): + with mock.patch('getpass.getpass', return_value=self.password): + execute(["identity", "create", self.name, "key", "--private-key", self.key], + self.parser, + self.conf) + result = execute(["identity", "list"], self.parser, self.conf) + assert self.name in result + + def test_2_get_encryption_key(self): + with mock.patch('getpass.getpass', return_value=self.password): + execute(["identity", self.name], self.parser, self.conf) + cmd = BlockchainCommand(self.conf, self.parser.parse_args(['session'])) + enc_key = cmd.config.get_session_field("private_key") + res_key = cmd._get_decrypted_secret(enc_key) + assert res_key == self.password + + def test_3_delete_identity(self): + with mock.patch('getpass.getpass', return_value=self.password): + execute(["identity", self.default_name], self.parser, self.conf) + execute(["identity", "delete", self.name], self.parser, self.conf) + result = execute(["identity", "list"], self.parser, self.conf) + assert self.name not in result + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_entry_point.py b/snet/cli/test/functional_tests/test_entry_point.py index 26ad257d..8e5b7a5e 100644 --- a/snet/cli/test/functional_tests/test_entry_point.py +++ b/snet/cli/test/functional_tests/test_entry_point.py @@ -65,4 +65,7 @@ def test_version(self): if __name__ == '__main__': - unittest.main() + cli_tests = unittest.TestLoader().loadTestsFromTestCase(TestEntryPoint) + functional_tests = unittest.TestLoader().discover("./snet/cli/test/functional_tests", pattern="test_*.py") + all_tests = unittest.TestSuite([cli_tests, functional_tests]) + unittest.TextTestRunner().run(all_tests) diff --git a/snet/cli/test/functional_tests/test_generate_library.py b/snet/cli/test/functional_tests/test_generate_library.py new file mode 100644 index 00000000..f06a12ed --- /dev/null +++ b/snet/cli/test/functional_tests/test_generate_library.py @@ -0,0 +1,23 @@ +import unittest +import os +from func_tests import BaseTest, execute +import shutil + + +class TestGenerateLibrary(BaseTest): + def setUp(self): + super().setUp() + self.path = './temp_files' + self.org_id = '26072b8b6a0e448180f8c0e702ab6d2f' + self.service_id = 'Exampleservice' + + def test_generate(self): + execute(["sdk", "generate-client-library", self.org_id, self.service_id, self.path], self.parser, self.conf) + assert os.path.exists(f'{self.path}/{self.org_id}/{self.service_id}/python/') + + def tearDown(self): + shutil.rmtree(self.path) + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_onboarding.py b/snet/cli/test/functional_tests/test_onboarding.py new file mode 100644 index 00000000..48a9f98a --- /dev/null +++ b/snet/cli/test/functional_tests/test_onboarding.py @@ -0,0 +1,221 @@ +import os +from func_tests import BaseTest, execute +import json +import unittest + + +class TestOrganization(BaseTest): + def setUp(self): + super().setUp() + self.org_id = "singularitynet" + self.correct_msg = f"List of {self.org_id}'s Services:" + + def test_list_of_services(self): + result = execute(["organization", "list-services", self.org_id], self.parser, self.conf) + assert self.correct_msg in result + + def test_org_info(self): + result = execute(["organization", "info", self.org_id], self.parser, self.conf) + assert "Organization Name" in result + + +""" temporarily closed so as not to clog up the logs +class TestOnboardingOrgAndServ(BaseTest): + def setUp(self): + super().setUp() + self.identity_name = "identity_name" + self.proto = "./" + self.org_name = "auto_test" + self.org_id = "auto_test" + self.org_type = "individual" + self.description = "DESCRIPTION" + self.short_description = "SHORT DESCRIPTION" + self.url = "https://URL.com" + self.group_name = "default_group" + self.endpoint = "https://node1.naint.tech:62400" + self.password = "12345" + self.service_id = "auto_test_service" + self.new_description = "NEW DESCRIPTION" + self.free_calls = "100" + self.contributor = "Stasy" + self.contributor_mail = "stasy@hotmail.com" + self.tags = "new", "text2text", "t2t", "punctuality" + self.tags2 = "update-add-tag" + self.hero_image = "./img.jpg" + self.contact = "author" + self.email = "author@hotmail.com" + self.phone = "+1234567890" + + def test_0_preparation(self): + identity_list = execute(["identity", "list"], self.parser, self.conf) + if self.identity_name not in identity_list: + execute(["identity", "create", self.identity_name, "key", "--private-key", PRIVATE_KEY, "-de"], self.parser, self.conf) + execute(["network", "sepolia"], self.parser, self.conf) + proto_file = open("ExampleService.proto", "w+") + proto_file.write("syntax = "proto3"; + +package example_service; + +message Numbers { + float a = 1; + float b = 2; +} + +message Result { + float value = 1; +} + +service Calculator { + rpc add(Numbers) returns (Result) {} + rpc sub(Numbers) returns (Result) {} + rpc mul(Numbers) returns (Result) {} + rpc div(Numbers) returns (Result) {} +}") + proto_file.close() + result = execute(["session"], self.parser, self.conf) + hero_image = open("img.jpg", "w+") + hero_image.close() + assert "network: sepolia" in result + + def test_1_metadata_init(self): + execute(["organization", "metadata-init", self.org_id, self.org_name, self.org_type], self.parser, self.conf) + execute(["organization", "metadata-add-description", "--description", self.description, "--short-description", self.short_description, "--url", self.url], + self.parser, + self.conf) + execute(["organization", "add-group", self.group_name, ADDR, self.endpoint], self.parser, self.conf) + execute(["service", "metadata-init", self.proto, self.service_id], self.parser, self.conf) + assert os.path.exists("./organization_metadata.json"), "File organization_metadata.json was not created!" + + def test_2_create_organization(self): + result = execute(["organization", "create", self.org_id, "-y"], self.parser, self.conf) + assert "event: OrganizationCreated" in result + + def test_31_create_service(self): + result = execute(["service", "publish", self.org_id, self.service_id, "-y"], self.parser, self.conf) + assert "event: ServiceCreated" in result + + def test_32_publish_in_ipfs(self): + result = execute(["service", "publish-in-ipfs", "-y"], self.parser, self.conf) + assert len(result) > 45 + + def test_33_publish_in_filecoin(self): + execute(["set", "filecoin_api_key", "8dcbe8a5.0e1595c6c556430dad42ef13abc00e2f"], self.parser, self.conf) + result = execute(["service", "publish-in-filecoin", "-y"], self.parser, self.conf) + print(result) + assert "Ok" in result + + def test_41_list(self): + result = execute(["organization", "list"], self.parser, self.conf) + assert self.org_id in result + + def test_42_list_org_names(self): + result = execute(["organization", "list-org-names"], self.parser, self.conf) + assert self.org_name in result + + def test_43_list_my(self): + result = execute(["organization", "list-my"], self.parser, self.conf) + assert self.org_id in result + + def test_44_list_services(self): + result = execute(["organization", "list-services", self.org_id], self.parser, self.conf) + assert self.service_id in result + + + def test_5_change_members(self): + result_add = execute(["organization", "add-members", self.org_id, ADDR, "-y"], self.parser, self.conf) + result_rem = execute(["organization", "rem-members", self.org_id, ADDR, "-y"], self.parser, self.conf) + # result_change_owner = execute(["organization", "change-owner", self.org_id, ADDR], self.parser, self.conf) + assert "event: OrganizationModified" in result_rem + + def test_61_change_org_metadata(self): + execute(["organization", "metadata-add-assets", self.hero_image, "hero_image"], self.parser, self.conf) + execute(["organization", "metadata-remove-assets", "hero_image"], self.parser, self.conf) + execute(["organization", "metadata-remove-all-assets"], self.parser, self.conf) + execute(["organization", "metadata-add-contact", self.contact, "--email", self.email, "--phone", self.phone], self.parser, self.conf) + execute(["organization", "metadata-remove-contacts", self.contact], self.parser, self.conf) + execute(["organization", "metadata-remove-all-contacts"], self.parser, self.conf) + execute(["organization", "metadata-add-description", "--description", self.new_description], self.parser, self.conf) + execute(["organization", "update-metadata", self.org_id, "-y"], self.parser, self.conf) + result = execute(["organization", "print-metadata", self.org_id], self.parser, self.conf) + assert self.new_description in result + + @patch("builtins.input", side_effect=["1", "2"]) + def test_62_change_service_metadata(self, mock_input): + execute(["service", "metadata-remove-group", self.group_name], self.parser, self.conf) + execute(["service", "metadata-add-group", self.group_name], self.parser, self.conf) + execute(["organization", "update-group", self.group_name], self.parser, self.conf) + execute(["service", "metadata-add-daemon-addresses", self.group_name, ADDR], self.parser, self.conf) + execute(["service", "metadata-remove-all-daemon-addresses", self.group_name], self.parser, self.conf) + execute(["service", "metadata-update-daemon-addresses", self.group_name, ADDR], self.parser, self.conf) + execute(["service", "metadata-add-endpoints", self.group_name, self.endpoint], self.parser, self.conf) + execute(["service", "metadata-remove-all-endpoints", self.group_name], self.parser, self.conf) + execute(["service", "metadata-add-endpoints", self.group_name, self.endpoint], self.parser, self.conf) + execute(["service", "metadata-set-free-calls", self.group_name, self.free_calls], self.parser, self.conf) + execute(["service", "metadata-set-freecall-signer-address", self.group_name, ADDR], self.parser, self.conf) + execute(["service", "metadata-add-description", "--description", self.new_description, "--short-description", self.short_description, "--url", self.url], + self.parser, + self.conf) + execute(["service", "metadata-add-contributor", self.contributor, self.contributor_mail], self.parser, self.conf) + execute(["service", "metadata-remove-contributor", self.contributor_mail], self.parser, self.conf) + execute(["service", "metadata-add-contributor", self.contributor, self.contributor_mail], self.parser, self.conf) + execute(["service", "metadata-add-assets", self.hero_image, "hero_image"], self.parser, self.conf) + execute(["service", "metadata-remove-assets", "hero_image"], self.parser, self.conf) + execute(["service", "metadata-remove-all-assets"], self.parser, self.conf) + execute(["service", "metadata-add-media", self.hero_image], self.parser, self.conf) + execute(["service", "metadata-remove-media", "1"], self.parser, self.conf) + execute(["service", "metadata-remove-all-media"], self.parser, self.conf) + execute(["service", "metadata-add-media", self.hero_image], self.parser, self.conf) + execute(["service", "metadata-add-media", self.hero_image], self.parser, self.conf) + execute(["service", "metadata-swap-media-order", "1", "2"], self.parser, self.conf) + execute(["service", "metadata-change-media-order"], self.parser, self.conf) + execute(["service", "update-metadata", self.org_id, self.service_id, "-y"], self.parser, self.conf) + result = execute(["service", "print-metadata", self.org_id, self.service_id], self.parser, self.conf) + print(execute(["service", "print-metadata", self.org_id, self.service_id], self.parser, self.conf)) + print(execute(["service", "print-service-status", self.org_id, self.service_id], self.parser, self.conf)) + assert self.contributor in result + + TODO: New logic for adding tags + def test_63_tags(self): + execute(["service", "metadata-add-tags", self.tags], self.parser, self.conf) + execute(["service", "update-metadata", self.org_id, self.service_id, "-y"], self.parser, self.conf) + execute(["service", "metadata-remove-tags", self.tags], self.parser, self.conf) + execute(["service", "update-add-tags", self.org_id, self.service_id, self.tags2, "-y"], self.parser, self.conf) + execute(["service", "update-remove-tags", self.org_id, self.service_id, self.tags2, "-y"], self.parser, self.conf) + print(execute(["service", "print-tags", self.org_id, self.service_id], self.parser, self.conf)) + result = execute(["service", "print-tags", self.org_id, self.service_id], self.parser, self.conf) + assert self.tags in result + + + def test_64_get_api_metadata(self): + os.remove(f"./ExampleService.proto") + execute(["service", "get-api-metadata", "./"], self.parser, self.conf) + assert os.path.exists(f"./ExampleService.proto") + + def test_65_metadata_set_api(self): + res = execute(["service", "metadata-set-api", "./", "--storage", "ipfs"], self.parser, self.conf) + print(res) + with open("service_metadata.json", "r", encoding="utf-8") as f: + metadata = json.load(f) + assert metadata["service_api_source"].startswith("ipfs://") + + @patch("builtins.input", side_effect=["auto_test", "1", "ipfs", "./", "y", "default_group", "1", ADDR, ADDR, "y", "150", ADDR, "n", "google.com", "long description", "short", "Stasy", "stasy@hotmail.com", "n", "y", "service_metadata"]) + def test_66_metadata_init_utility(self, mock_input): + os.remove(f"./service_metadata.json") + execute(["service", "metadata-init-utility"], self.parser, self.conf) + assert os.path.exists(f"./service_metadata.json") + + def test_7_delete_service(self): + result = execute(["service", "delete", self.org_id, self.service_id, "-y"], self.parser, self.conf) + os.remove(f"./service_metadata.json") + assert "event: ServiceDeleted" in result + + def test_8_delete_organization(self): + result = execute(["organization", "delete", self.org_id, "-y"], self.parser, self.conf) + os.remove(f"./organization_metadata.json") + os.remove(f"img.jpg") + assert "event: OrganizationDeleted" in result +""" + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/snet/cli/test/functional_tests/test_org_metadata.py b/snet/cli/test/functional_tests/test_org_metadata.py new file mode 100644 index 00000000..0716eddc --- /dev/null +++ b/snet/cli/test/functional_tests/test_org_metadata.py @@ -0,0 +1,33 @@ +import os +from func_tests import BaseTest, execute, ADDR +import unittest + + +class TestOrgMetadata(BaseTest): + def setUp(self): + super().setUp() + self.success_msg = "Organization metadata is valid and ready to publish." + self.name = "test_org" + self.org_id = "test_org_id" + self.org_type = "individual" + self.org_description = "--description" + self.org_short_description = "--short-description" + self.org_url = "--url" + self.group_name = "default_group" + self.endpoint = "https://node1.naint.tech:62400" + + def test_metadata_init(self): + execute(["organization", "metadata-init", self.name, self.org_id, self.org_type], self.parser, self.conf) + execute(["organization", "metadata-add-description", self.org_description, "DESCRIPTION", self.org_short_description, "SHORT_DESCRIPTION", self.org_url, "https://URL"], + self.parser, + self.conf) + execute(["organization", "add-group", self.group_name, ADDR, self.endpoint], self.parser, self.conf) + result = execute(["organization", "validate-metadata"], self.parser, self.conf) + assert self.success_msg in result + + def tearDown(self): + os.remove(f"./organization_metadata.json") + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/functional_tests/test_unset.py b/snet/cli/test/functional_tests/test_unset.py new file mode 100644 index 00000000..f5a51412 --- /dev/null +++ b/snet/cli/test/functional_tests/test_unset.py @@ -0,0 +1,28 @@ +from func_tests import BaseTest, execute +import unittest + + +class Unset(BaseTest): + def test_unset_filecoin(self): + execute(["set", "filecoin_api_key", "1"], self.parser, self.conf) + result = execute(["unset", "filecoin_api_key"], self.parser, self.conf) + assert "unset" in result + + def test_unset_current_registry_at(self): + execute(["set", "current_registry_at", "1"], self.parser, self.conf) + result = execute(["unset", "current_registry_at"], self.parser, self.conf) + assert "unset" in result + + def test_unset_current_multipartyescrow_at(self): + execute(["set", "current_multipartyescrow_at", "1"], self.parser, self.conf) + result = execute(["unset", "current_multipartyescrow_at"], self.parser, self.conf) + assert "unset" in result + + def test_unset_current_singularitynettoken_at(self): + execute(["set", "current_singularitynettoken_at", "1"], self.parser, self.conf) + result = execute(["unset", "current_singularitynettoken_at"], self.parser, self.conf) + assert "unset" in result + + +if __name__ == "__main__": + unittest.main() diff --git a/snet/cli/test/utils/reset_environment.sh b/snet/cli/test/utils/reset_environment.sh deleted file mode 100755 index bbecd7e8..00000000 --- a/snet/cli/test/utils/reset_environment.sh +++ /dev/null @@ -1,61 +0,0 @@ -# This is a part of circleci functional tests -# This script does following: -# - restart ipfs -# - restart ganache and remigrate platform-contracts -# - set correct networks/*json for Registry and MultiPartyEscrow (but not for SingularityNetToken !) -# - reset .snet configuration -# - add snet-user to snet-cli with first ganache idenity - -if [ ! $1 = "--i-no-what-i-am-doing" ]; then - echo "This script is intended to be run from circleci" - exit 1 -fi - -cwd=$(pwd) - -# I. restart ipfs -ipfs shutdown || echo "supress an error" - -rm -rf ~/.ipfs -ipfs init -ipfs bootstrap rm --all -ipfs config Addresses.API /ip4/127.0.0.1/tcp/5002 -ipfs config Addresses.Gateway /ip4/0.0.0.0/tcp/8081 -nohup ipfs daemon >ipfs.log 2>&1 & - -# II. restart ganache and remigrate platform-contracts -killall node || echo "supress an error" - -# cd ../platform-contracts -# nohup ./node_modules/.bin/ganache-cli --mnemonic 'gauge enact biology destroy normal tunnel slight slide wide sauce ladder produce' --networkId 829257324 >/dev/null & -# ./node_modules/.bin/truffle migrate --network local - -# III. remove old snet-cli configuration -rm -rf ~/.snet - -# IV. Configure SNET-CLI. - -# set correct ipfs endpoint -# (the new new configuration file with default values will be created automatically) -# snet set default_ipfs_endpoint http://localhost:5002 - -# Add local network and switch to it -# snet network create local http://localhost:8545 - -# swith to local network -# snet network local - -# Configure contract addresses for local network (it will not be necessary for goerli or mainnet! ) -# snet set current_singularitynettoken_at 0x6e5f20669177f5bdf3703ec5ea9c4d4fe3aabd14 -# snet set current_registry_at 0x4e74fefa82e83e0964f0d9f53c68e03f7298a8b2 -# snet set current_multipartyescrow_at 0x5c7a4290f6f8ff64c69eeffdfafc8644a4ec3a4e - -# Create First identity (snet-user = first ganache). -# (snet will automatically swith to this new identity) -# snet identity create snet-user rpc --network local -snet identity create --private-key "$SNET_TEST_WALLET_PRIVATE_KEY" test key --network sepolia -sed -i "s/$FORMER_SNET_TEST_INFURA_KEY/$SNET_TEST_INFURA_KEY/g" ~/.snet/config -snet session -export PYTHONPATH=$cwd -python $cwd"./snet/cli/test/functional_tests/mint/mint.py" -snet account balance diff --git a/snet/cli/test/utils/run_all_functional.sh b/snet/cli/test/utils/run_all_functional.sh deleted file mode 100755 index 2815a9cb..00000000 --- a/snet/cli/test/utils/run_all_functional.sh +++ /dev/null @@ -1,11 +0,0 @@ -for f in snet/cli/test/functional_tests/script?_* -do - bash -ex ./snet/cli/test/utils/reset_environment.sh --i-no-what-i-am-doing - bash -ex -c "cd snet/cli/test/functional_tests; bash -ex `basename $f`" -done - -for f in snet/cli/test/functional_tests/script??_* -do - bash -ex ./snet/cli/test/utils/reset_environment.sh --i-no-what-i-am-doing - bash -ex -c "cd snet/cli/test/functional_tests; bash -ex `basename $f`" -done diff --git a/snet/cli/utils/ipfs_utils.py b/snet/cli/utils/ipfs_utils.py index 49fccfe5..8279c88b 100644 --- a/snet/cli/utils/ipfs_utils.py +++ b/snet/cli/utils/ipfs_utils.py @@ -109,7 +109,8 @@ def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True): # Decode Base58 bash to multihash try: - mh = multihash.decode(ipfs_hash_base58.encode('ascii'), "base58") + decoded_hash_bytes = base58.b58decode(ipfs_hash_base58) + mh = multihash.decode(decoded_hash_bytes) except Exception as e: raise ValueError(f"Invalid multihash for IPFS hash: {ipfs_hash_base58}. Error: {str(e)}") from e diff --git a/snet/cli/utils/proto_utils.py b/snet/cli/utils/proto_utils.py index d150f569..5f115dc4 100644 --- a/snet/cli/utils/proto_utils.py +++ b/snet/cli/utils/proto_utils.py @@ -79,11 +79,11 @@ def switch_to_json_payload_encoding(call_fn, response_class): """ Switch payload encoding to JSON for GRPC call """ def json_serializer(*args, **kwargs): - return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), "utf-8") + return bytes(json_format.MessageToJson(args[0], preserving_proto_field_name=True), "utf-8") def json_deserializer(*args, **kwargs): resp = response_class() - json_format.Parse(args[0], resp, True) + json_format.Parse(args[0], resp, ignore_unknown_fields=True) return resp call_fn._request_serializer = json_serializer diff --git a/snet/cli/utils/utils.py b/snet/cli/utils/utils.py index 0efc8d20..0512b3fa 100644 --- a/snet/cli/utils/utils.py +++ b/snet/cli/utils/utils.py @@ -1,6 +1,5 @@ import json import os -import subprocess import functools import re import sys @@ -15,7 +14,6 @@ import web3 import grpc from grpc_tools.protoc import main as protoc -from trezorlib.cli.firmware import download from snet import cli from snet.cli.resources.root_certificate import certificate @@ -63,7 +61,7 @@ def __str__(self): def get_web3(rpc_endpoint): if rpc_endpoint.startswith("ws:"): - provider = web3.WebsocketProvider(rpc_endpoint) + provider = web3.LegacyWebSocketProvider(rpc_endpoint) else: provider = web3.HTTPProvider(rpc_endpoint) @@ -274,7 +272,7 @@ def get_address_from_private(private_key): return web3.Account.from_key(private_key).address -class add_to_path(): +class add_to_path: def __init__(self, path): self.path = path @@ -361,7 +359,7 @@ def check_training_in_proto(protodir) -> bool: for file in files: if ".proto" not in file: continue - with open(protodir.joinpath(file), "r") as f: + with open(os.path.join(protodir, file), "r") as f: proto_text = f.read() if 'import "training.proto";' in proto_text: return True diff --git a/version.py b/version.py deleted file mode 100644 index 528787cf..00000000 --- a/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "3.0.0"