def main(): host = "localhost" port = 8001 production = False api_key = "9A5Fy8jDxsJQSDdU4thLZs9fwDmtVzBU" did = "iHdasfhasdflkHdasfasdfD" network = "gmunet" private_key = "1F54BCD5592709B695E85F83EBDA515971723AFF56B32E175F14A158D5AC0D99" file_to_upload = "test/sample.txt" try: hive = Hive(host, port, production) # Upload and Sign print("\n--> Upload and Sign") response = hive.upload_and_sign(api_key, did, network, private_key, file_to_upload) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: hive.close()
def main(): host = "localhost" port = 8001 production = False api_key = "9A5Fy8jDxsJQSDdU4thLZs9fwDmtVzBU" did = "iHdasfhasdflkHdasfasdfD" network = "gmunet" message_hash = "516D5A554C6B43454C6D6D6B35584E664367546E437946674156784252425879444847474D566F4C464C6958454E" public_key = "022316EB57646B0444CB97BE166FBE66454EB00631422E03893EE49143B4718AB8" signature = "15FDD2752B686AF7CABE8DF72FCCC91AC25577C6AFB70A81A1D987DAACAE298621E227D585B7020100228AEF96D22AD0403612FFAEDCD7CA3A2070455418181C" file_hash = "QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN" private_key = "1F54BCD5592709B695E85F83EBDA515971723AFF56B32E175F14A158D5AC0D99" try: hive = Hive(host, port, production) # Verify and Show print("\n--> Verify and Show") request_input = { "msg": message_hash, "pub": public_key, "sig": signature, "hash": file_hash, "privateKey": private_key } response = hive.verify_and_show(api_key, did, network, request_input) if response['status']: download_path = 'test/sample_from_hive.txt' print("Status Message :", response['status_message']) print("File Path :", download_path) with open(download_path, 'wb') as file: file.write(response['file_content']) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: hive.close()
def verify_and_show(request): did = request.session['did'] track_page_visit(did, 'Verify And Show', 'service:verify_and_show', True) recent_services = get_recent_services(did) sample_code = {} module_dir = os.path.dirname(__file__) with open(os.path.join(module_dir, 'sample_code/python/verify_and_show.py'), 'r') as myfile: sample_code['python'] = myfile.read() with open(os.path.join(module_dir, 'sample_code/go/verify_and_show.go'), 'r') as myfile: sample_code['go'] = myfile.read() if request.is_ajax(): filename = request.POST.get('file_name') try: userFile = SavedFileInformation.objects.filter(did=did, file_name=filename) data = serializers.serialize('json', userFile) data = data[1:-1] return HttpResponse(data, content_type='application/json') except Exception as e: return redirect(reverse('service:verify_and_show')) elif request.method == 'POST': if not request.session['verify_and_show_submit']: form = VerifyAndShowForm(request.POST, did=did) if form.is_valid(): network = form.cleaned_data.get('network') api_key = form.cleaned_data.get('api_key') request_input = { "msg": form.cleaned_data.get('message_hash'), "pub": form.cleaned_data.get('public_key'), "sig": form.cleaned_data.get('signature'), "hash": form.cleaned_data.get('file_hash'), "privateKey": form.cleaned_data.get('private_key') } try: hive = Hive(GRPC_SERVER_HOST, GRPC_SERVER_PORT, PRODUCTION) response = hive.verify_and_show(api_key, did, network, request_input) if response['status']: request.session['verify_and_show_submit'] = True file_content = response['file_content'] try: content = file_content.decode() except UnicodeDecodeError: response = HttpResponse(file_content, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=file_from_hive' return response track_page_visit(did, 'Verify And Show', 'service:verify_and_show', True, True) return render(request, 'service/verify_and_show.html', {'output': True, 'content': content, 'sample_code': sample_code, 'recent_services': recent_services}) else: messages.success(request, response['status_message']) return redirect(reverse('service:verify_and_show')) except Exception as e: logging.debug(f"did: {did} Method: verify_and_show Error: {e}") messages.success(request, "File could not be verified nor shown. Please try again") return redirect(reverse('service:verify_and_show')) finally: hive.close() else: return redirect(reverse('service:verify_and_show')) else: request.session['verify_and_show_submit'] = False form = VerifyAndShowForm( initial={'api_key': request.session['api_key'], 'private_key': request.session['private_key_mainchain'], 'public_key': request.session['public_key_mainchain']}, did=did) return render(request, 'service/verify_and_show.html', {'output': False, 'form': form, 'sample_code': sample_code, 'recent_services': recent_services})
def main(): parser = argparse.ArgumentParser(description="sample.py", add_help=False) parser.add_argument( '-h', '--help', action='help', default=argparse.SUPPRESS, help= 'Types of services supported: generate_api_key, get_api_key, node_rpc_methods, ' 'upload_and_sign, verify_and_show, create_wallet, view_wallet, request_ela, ' 'deploy_eth_contract, watch_eth_contract') parser.add_argument('-s', action="store", dest="service") results = parser.parse_args() service = results.service host = config('GRPC_SERVER_HOST') port = config('GRPC_SERVER_PORT') production = config('PRODUCTION', default=False, cast=bool) network = "gmunet" ela_to_use = 'EQeMkfRk3JzePY7zpUSg5ZSvNsWedzqWXN' ela_eth_to_use = '0x48F01b2f2b1a546927ee99dD03dCa37ff19cB84e' did_to_use = 'n84dqvIK9O0LIPXi27uL0aRnoR45Exdxl218eQyPDD4lW8RPov' api_key_to_use = '1htfwNmjePvE6blvXPc3YjD8Iqkst53ZF8EwnCZxbvyIcOoHt8wQHxPq4y501awz' private_key_to_use = '1F54BCD5592709B695E85F83EBDA515971723AFF56B32E175F14A158D5AC0D99' # Check whether grpc server is healthy first try: health_check = HealthCheck(host, port, production) print("--> Checking the health status of grpc server") response = health_check.check() if response.status != health_check_pb2.HealthCheckResponse.SERVING: print("grpc server is not running properly") else: print("grpc server is running") except Exception as e: print(e) print("grpc server is not running properly") sys.exit(1) if service == "node_rpc_methods": try: node_rpc = NodeRpc(host, port, production) print("--> Get current height") current_height = node_rpc.get_current_height( api_key_to_use, did_to_use, network, "mainchain") print("Current Height - mainchain: ", current_height) current_height = node_rpc.get_current_height( api_key_to_use, did_to_use, network, "did") print("Current Height - did sidechain: ", current_height) current_height = node_rpc.get_current_height( api_key_to_use, did_to_use, network, "token") print("Current Height - token sidechain: ", current_height) current_height = node_rpc.get_current_height( api_key_to_use, did_to_use, network, "eth") print("Current Height - eth sidechain: ", current_height) print("--> Get current block info") current_block_info = node_rpc.get_current_block_info( api_key_to_use, did_to_use, network, "mainchain") print("Current block info - mainchain: ", current_block_info) current_block_info = node_rpc.get_current_block_info( api_key_to_use, did_to_use, network, "did") print("Current block info - did sidechain: ", current_block_info) current_block_info = node_rpc.get_current_block_info( api_key_to_use, did_to_use, network, "token") print("Current block info - token sidechain: ", current_block_info) current_block_info = node_rpc.get_current_block_info( api_key_to_use, did_to_use, network, "eth") print("Current block info - eth sidechain: ", current_block_info) print("--> Get current mining info - mainchain") current_mining_info = node_rpc.get_current_mining_info( api_key_to_use, did_to_use, network) print("Current mining info: ", current_mining_info) except Exception as e: print(e) finally: node_rpc.close() elif service == "generate_api_key": try: common = Common(host, port, production) # Generate API Key print("--> Generate API Key - SHARED_SECRET_ADENINE") response = common.generate_api_request( config('SHARED_SECRET_ADENINE'), did_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: common.close() elif service == "get_api_key": try: common = Common(host, port, production) # Get API Key print("--> Get API Key - SHARED_SECRET_ADENINE") response = common.get_api_key_request( config('SHARED_SECRET_ADENINE'), did_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: common.close() elif service == "upload_and_sign": try: hive = Hive(host, port, production) # Upload and Sign print("\n--> Upload and Sign") response = hive.upload_and_sign(api_key_to_use, did_to_use, network, private_key_to_use, 'test/sample.txt') if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: hive.close() elif service == "verify_and_show": try: hive = Hive(host, port, production) # Verify and Show print("\n--> Verify and Show") request_input = { "msg": "516D5A445272666E76485648354E363277674C505171316D3575586D7459684A5A4475666D4679594B476F745535", "pub": "022316EB57646B0444CB97BE166FBE66454EB00631422E03893EE49143B4718AB8", "sig": "327C64F47047B71F1AA235CE465D5A80EB823648C7355E8A3EFBF3DE9AA25D443588E101EE0E693BE80A4C7D200CBB65ED838296EE3A8088401C342C0FBCD4E7", "hash": "QmZDRrfnvHVH5N62wgLPQq1m5uXmtYhJZDufmFyYKGotU5", "privateKey": private_key_to_use } response = hive.verify_and_show(api_key_to_use, did_to_use, network, request_input) if response['status']: download_path = 'test/sample_from_hive.txt' print("Status Message :", response['status_message']) print("File Path :", download_path) with open(download_path, 'wb') as file: file.write(response['file_content']) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: hive.close() elif service == "create_wallet": try: wallet = Wallet(host, port, production) print("\n--> Create Wallet") response = wallet.create_wallet(api_key_to_use, did_to_use, network) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: wallet.close() elif service == "view_wallet": try: node_rpc = NodeRpc(host, port, production) print("\n--> View Wallet") print("--> Get current balance") current_balance = node_rpc.get_current_balance( api_key_to_use, did_to_use, network, "mainchain", ela_to_use) print("Current balance - mainchain:", current_balance) current_balance = node_rpc.get_current_balance( api_key_to_use, did_to_use, network, "did", ela_to_use) print("Current balance - did sidechain:", current_balance) current_balance = node_rpc.get_current_balance( api_key_to_use, did_to_use, network, "token", ela_to_use) print("Current balance - token sidechain:", current_balance) current_balance = node_rpc.get_current_balance( api_key_to_use, did_to_use, network, "eth", ela_eth_to_use) print("Current balance - eth sidechain:", current_balance) except Exception as e: print(e) finally: node_rpc.close() elif service == "request_ela": try: wallet = Wallet(host, port, production) print("\n--> Request ELA") # Mainchain response = wallet.request_ela(api_key_to_use, did_to_use, 'mainchain', ela_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) # DID sidechain response = wallet.request_ela(api_key_to_use, did_to_use, 'did', ela_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) # Token sidechain response = wallet.request_ela(api_key_to_use, did_to_use, 'token', ela_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) # Eth sidechain response = wallet.request_ela(api_key_to_use, did_to_use, 'eth', ela_eth_to_use) if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: wallet.close() elif service == "deploy_eth_contract": try: sidechain_eth = SidechainEth(host, port, production) # Deploy ETH Contract # The eth account addresses below is used from that of privatenet. In order to test this, # you must first run https://github.com/cyber-republic/elastos-privnet locally # For production GMUnet, this won't work print("\n--> Deploy ETH Contract") response = sidechain_eth.deploy_eth_contract( api_key_to_use, did_to_use, network, ela_eth_to_use, '0x35a12175385b24b2f906d6027d440aac7bd31e1097311fa8e3cf21ceac7c4809', 2000000, 'test/HelloWorld.sol') if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: sidechain_eth.close() elif service == "watch_eth_contract": try: sidechain_eth = SidechainEth(host, port, production) print("\n--> Watch ETH Contract") response = sidechain_eth.watch_eth_contract( api_key_to_use, did_to_use, network, '0xc0ba7D9CF73c0410FfC9FB5b768F5257906B13c1', 'HelloWorld', 'QmXYqHg8gRnDkDreZtXJgqkzmjujvrAr5n6KXexmfTGqHd') if response['status']: json_output = json.loads(response['output']) print("Status Message :", response['status_message']) for i in json_output['result']: print(i, ':', json_output['result'][i]) else: print("Error Message: " + response['status_message']) except Exception as e: print(e) finally: sidechain_eth.close()
def upload_and_sign(request): did = request.session['did'] track_page_visit(did, 'Upload And Sign', 'service:upload_and_sign', True) recent_services = get_recent_services(did) sample_code = {} module_dir = os.path.dirname(__file__) with open(os.path.join(module_dir, 'sample_code/python/upload_and_sign.py'), 'r') as myfile: sample_code['python'] = myfile.read() with open(os.path.join(module_dir, 'sample_code/go/upload_and_sign.go'), 'r') as myfile: sample_code['go'] = myfile.read() if request.is_ajax(): boolean = request.POST.get('delete') if boolean: SavedFileInformation.objects.filter(did=did).delete() return HttpResponse("Files have been deleted") return HttpResponse("files have not been deleted") elif request.method == 'POST': userFileCount = len(SavedFileInformation.objects.filter(did=did)) if userFileCount >= 50: request.session['upload_and_sign_submit'] = True messages.warning(request, "you have reached the total number of files") form = UploadAndSignForm(initial={'did': did, 'api_key': request.session['api_key'], 'private_key': request.session['private_key_mainchain']}) return render(request, "service/upload_and_sign.html", {'form': form, 'output': False, 'sample_code': sample_code, 'recent_services': recent_services, 'total_reached': True}) if not request.session['upload_and_sign_submit']: # Purge old requests for housekeeping. UploadFile.objects.filter(did=did).delete() form = UploadAndSignForm(request.POST, request.FILES, initial={'did': did}) if form.is_valid(): network = form.cleaned_data.get('network') file_name = form.cleaned_data.get('file_name') " ".join(file_name.split()) # standardizing whitespaces api_key = form.cleaned_data.get('api_key') private_key = form.cleaned_data.get('private_key') file_content = form.cleaned_data.get('file_content').encode() userFile = SavedFileInformation.objects.filter(did=did, file_name=file_name) if len(userFile) != 0: request.session['upload_and_sign_submit'] = True messages.warning(request, "You have already upload a file with that name, please change the name " "of the file") return redirect(reverse('service:upload_and_sign')) form.save() obj, created = UploadFile.objects.update_or_create(defaults={'did': did}) true_file_name = obj.filename() if file_content: remove_uploaded_file = False user_uploaded_file = ContentFile(file_content) else: remove_uploaded_file = True user_uploaded_file = File(request.FILES['uploaded_file']) obj.uploaded_file.save(get_random_string(32), user_uploaded_file) try: temp_file = UploadFile.objects.get(did=did) file_path = temp_file.uploaded_file.path except Exception as e: messages.success(request, "Please upload a file or fill out the 'File content' field") return redirect(reverse('service:upload_and_sign')) try: hive = Hive(GRPC_SERVER_HOST, GRPC_SERVER_PORT, PRODUCTION) response = hive.upload_and_sign(api_key, did, network, private_key, file_path) if response['status']: request.session['upload_and_sign_submit'] = True data = json.loads(response['output']) message_hash = data['result']['msg'] public_key = data['result']['pub'] signature = data['result']['sig'] file_hash = data['result']['hash'] if network == 'gmunet': SavedFileInformation.objects.update_or_create(did=did, file_name=file_name, message_hash=message_hash, signature=signature, file_hash=file_hash) track_page_visit(did, 'Upload And Sign', "service:upload_and_sign", True, True) return render(request, "service/upload_and_sign.html", {"message_hash": message_hash, "public_key": public_key, "signature": signature, "file_hash": file_hash, 'output': True, 'sample_code': sample_code, 'recent_services': recent_services, 'total_reached': False}) else: messages.success(request, response['status_message']) return redirect(reverse('service:upload_and_sign')) except Exception as e: logging.debug(f"did: {did} Method: upload_and_sign Error: {e}") messages.success(request, "File could not be uploaded. Please try again") return redirect(reverse('service:upload_and_sign')) finally: temp_file.delete() if (remove_uploaded_file): os.remove(os.path.join(MEDIA_ROOT, 'user_files', true_file_name)) hive.close() else: return redirect(reverse('service:upload_and_sign')) else: request.session['upload_and_sign_submit'] = False form = UploadAndSignForm(initial={'did': did, 'api_key': request.session['api_key'], 'private_key': request.session['private_key_mainchain']}) return render(request, "service/upload_and_sign.html", {'form': form, 'output': False, 'sample_code': sample_code, 'recent_services': recent_services, 'total_reached': False})