async def set_node_key(request): try: private_key = request.params['private_key'] except KeyError: raise RpcInvalidParamsError(message='Missed private key') PubKeyClient.set_priv_key_to_file(private_key) return True
def execute_delete(pub_key_address): client = PubKeyClient() try: pub_key_data = client.get_status(pub_key_address) if pub_key_data.revoked: return {'error': 'The pub_key was already revoked'}, 409 return client.revoke_pub_key(pub_key_address) except KeyNotFound: return NoContent, 404
def create_certificate(payload, org_name=PUB_KEY_ORGANIZATION, signer=None): parameters = get_params() encryption_algorithm = get_encryption_algorithm(payload) key = generate_key() key_export = generate_key_export(key, encryption_algorithm) if not signer: signer = PubKeyClient().get_signer() cert = build_certificate(parameters, payload, key, signer.get_public_key().as_hex(), org_name) return cert, key, key_export
def test_store_success(self): context = self.get_context() cert, key, _ = PubKeyClient.create_certificate( context.pub_key_payload, signer=context.client.get_signer()) transaction_signature, cert_address, transaction_payload = self._pre_parse_payload_and_exec( context, cert, key) crt_export, crt_bin, crt_sig, rem_sig, pub_key, \ valid_from, valid_to = PubKeyClient.get_crt_export_bin_sig_rem_sig(cert, key, context.client) account = AccountClient.get_account_model(PUB_KEY_STORE_PRICE) storage_account = AccountClient.get_account_model(0) storage_signer = self.get_new_signer() storage_pub_key = storage_signer.get_public_key().as_hex() storage_address = AccountHandler().make_address_from_data( storage_pub_key) data = PubKeyStorage() data.owner = self.account_signer1.get_public_key().as_hex() data.payload.CopyFrom(transaction_payload) data.revoked = False self.expect_get({cert_address: None, self.account_address1: account}) self.expect_get({_make_settings_key('remme.economy_enabled'): None}) self.expect_get({ _make_settings_key(SETTINGS_STORAGE_PUB_KEY): get_setting_from_key_value(SETTINGS_STORAGE_PUB_KEY, storage_pub_key) }) self.expect_get({ self.account_address1: account, storage_address: storage_account }) context.client.store_pub_key(pub_key, rem_sig, crt_sig, valid_from, valid_to) account.balance -= PUB_KEY_STORE_PRICE account.pub_keys.append(cert_address) storage_account.balance += PUB_KEY_STORE_PRICE self.expect_set( transaction_signature, PubKeyMethod.STORE, { self.account_address1: account, cert_address: data, storage_address: storage_account }) self.expect_ok()
def execute_post(pub_key_address): client = PubKeyClient() try: pub_key_data = client.get_status(pub_key_address) now = time.time() valid_from = pub_key_data.payload.valid_from valid_to = pub_key_data.payload.valid_to return {'revoked': pub_key_data.revoked, 'owner_pub_key': pub_key_data.owner, 'entity_hash': pub_key_data.payload.entity_hash, 'valid': not pub_key_data.revoked and valid_from < now and now < valid_to, 'valid_from': valid_from, 'valid_to': valid_to} except KeyNotFound: return NoContent, 404
def execute_store(cert_request, not_valid_before, not_valid_after): pub_key_client = PubKeyClient() key = get_keys_to_sign() cert = pub_key_client.process_csr(cert_request, key, not_valid_before, not_valid_after) crt_export, crt_bin, crt_sig, rem_sig, pub_key, \ valid_from, valid_to = get_crt_export_bin_sig_rem_sig(cert, key, pub_key_client) batch_id, _ = pub_key_client.store_pub_key(pub_key, rem_sig, crt_sig, valid_from, valid_to) response = {'pub_key': pub_key, 'crt_key': crt_export.decode('utf-8'), 'batch_id': batch_id['batch_id']} return response
async def get_public_key_info(request): public_key_address = request.params['public_key_address'] client = PubKeyClient() try: pub_key_data = await client.get_status(public_key_address) if not pub_key_data.payload.ByteSize(): raise KeyNotFound conf_name = pub_key_data.payload.WhichOneof('configuration') conf_payload = getattr(pub_key_data.payload, conf_name) now = time.time() valid_from = pub_key_data.payload.valid_from valid_to = pub_key_data.payload.valid_to return {'is_revoked': pub_key_data.is_revoked, 'owner_public_key': pub_key_data.owner, 'type': conf_name, 'is_valid': (not pub_key_data.is_revoked and valid_from < now and now < valid_to), 'valid_from': valid_from, 'valid_to': valid_to, 'public_key': binascii.hexlify(conf_payload.key).decode('utf-8'), 'entity_hash': pub_key_data.payload.entity_hash.decode('utf-8'), 'entity_hash_signature': binascii.hexlify(pub_key_data.payload.entity_hash_signature).decode('utf-8')} except KeyNotFound: raise KeyNotFound('Public key info not found')
async def test_node_key_retrieve_info_and_it_ok(self, root_mock, fetch_state_mock): resp = await self.create_rpc_request('get_node_config') self.assertEqual(resp.status, 200) data = await resp.json() pub_key = PubKeyClient().get_public_key() self.assertEqual(data['result']['node_public_key'], pub_key)
async def send_raw_transaction(request): try: data = request.params['data'] except KeyError: raise RpcInvalidParamsError(message='Missed data') with suppress(Exception): data = data.encode('utf-8') try: transaction = base64.b64decode(data) except Exception: raise RpcGenericServerDefinedError( error_code=-32050, message='Decode payload of tranasaction failed' ) try: tr_pb = Transaction() tr_pb.ParseFromString(transaction) except DecodeError: raise RpcGenericServerDefinedError( error_code=-32050, message='Failed to parse transaction proto' ) try: tr_head_pb = TransactionHeader() tr_head_pb.ParseFromString(tr_pb.header) except DecodeError: raise RpcGenericServerDefinedError( error_code=-32050, message='Failed to parse transaction head proto' ) prefix, public_key = tr_head_pb.signer_public_key[:2], \ tr_head_pb.signer_public_key[2:] if prefix in ('02', '03') and len(public_key) != 64: raise RpcGenericServerDefinedError( error_code=-32050, message='Signer public key format is not valid' ) client = PubKeyClient() response = client.send_raw_transaction(tr_pb) return response['data']
def validation_logic(payload): try: serialization.load_pem_public_key( payload['pub_key'].encode('utf-8'), default_backend()) address = PubKeyClient().make_address_from_data(payload['pub_key']) LOGGER.debug(f'fetch pub_key_address {address}') except ValueError: return {'error': 'Unable to load pub_key entity'}, 422 return func(address)
def test_store_fail_invalid_validity_date(self): context = self.get_context() cert, key, _ = PubKeyClient.create_certificate( context.pub_key_payload, signer=context.client.get_signer()) crt_export, crt_bin, crt_sig, rem_sig, pub_key, \ valid_from, valid_to = PubKeyClient.get_crt_export_bin_sig_rem_sig(cert, key, context.client) cert_address = PubKeyHandler().make_address_from_data(pub_key) valid_from = int(valid_from - PUB_KEY_MAX_VALIDITY.total_seconds()) valid_to = int(valid_to + PUB_KEY_MAX_VALIDITY.total_seconds()) context.client.store_pub_key(pub_key, rem_sig, crt_sig, valid_from, valid_to) self.expect_get({cert_address: None, self.account_address1: None}) self.expect_invalid_transaction()
def execute_put(cert, key, key_export, name_to_save=None, passphrase=None): client = PubKeyClient() crt_export, crt_bin, crt_sig, rem_sig, pub_key, \ valid_from, valid_to = get_crt_export_bin_sig_rem_sig(cert, key, client) try: saved_to = save_p12(cert, key, name_to_save, passphrase) except ValueError: return {'error': 'The file already exists in specified location'}, 409 batch_id, _ = client.store_pub_key(pub_key, rem_sig, crt_sig, valid_from, valid_to) response = {'priv_key': key_export.decode('utf-8'), 'pub_key': pub_key, 'crt_key': crt_export.decode('utf-8'), 'batch_id': batch_id['batch_id']} if saved_to: response['saved_to'] = saved_to return response
def validation_logic(payload): try: certificate = x509.load_pem_x509_certificate( payload['crt_key'].encode('utf-8'), default_backend()) pub_key = certificate.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) address = PubKeyClient().make_address_from_data(pub_key) LOGGER.debug(f'fetch crt_key_address {address}') except ValueError: return {'error': 'Unable to load crt_key entity'}, 422 return func(address)
def post(payload): tr = payload['transaction'] with suppress(Exception): tr = tr.encode('utf-8') try: transaction = base64.b64decode(tr) except Exception: return {'error': 'Decode payload of tranasaction failed'}, 400 try: tr_pb = Transaction() tr_pb.ParseFromString(transaction) except DecodeError: return {'error': 'Failed to parse transaction proto'}, 400 client = PubKeyClient() try: result = client._send_raw_transaction(tr_pb) return {'batch_id': result['batch_id']}, 200 except Exception as e: return {'error': 'Send batch with transaction failed: %s' % e}, 400
async def get_public_key_info(request): request.params = request.params or {} try: public_key_address = request.params['public_key_address'] except KeyError: raise RpcInvalidParamsError(message='Missed public_key_address') client = PubKeyClient() try: pub_key_data = client.get_status(public_key_address) now = time.time() valid_from = pub_key_data.payload.valid_from valid_to = pub_key_data.payload.valid_to return {'is_revoked': pub_key_data.revoked, 'owner_public_key': pub_key_data.owner, 'is_valid': (not pub_key_data.revoked and valid_from < now and now < valid_to), 'valid_from': valid_from, 'valid_to': valid_to, 'entity_hash': pub_key_data.payload.entity_hash, 'entity_hash_signature': pub_key_data.payload.entity_hash_signature} except KeyNotFound: raise KeyNotFound('Public key info not found')
def validation_logic(pub_key, passphrase=''): try: p12 = crypto.load_pkcs12(pub_key.read(), passphrase) pub_cert = p12.get_certificate().to_cryptography() pub_key = pub_cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) address = PubKeyClient().make_address_from_data(pub_key) except ValueError: return {'error': 'Unable to load pub_key entity'}, 422 except crypto.Error: return {'error': 'Incorrect passphrase'}, 403 return func(address)
def test_revoke_fail_wrong_signer(self): context = self.get_context() cert, key, key_export = PubKeyClient.create_certificate( context.pub_key_payload, org_name='different', signer=self.account_signer2) signature, cert_address, transaction_payload = self._pre_parse_payload_and_exec( context, cert, key, 'revoke') data = PubKeyStorage() data.owner = self.account_signer2.get_public_key().as_hex() data.payload.CopyFrom(transaction_payload) data.revoked = False self.expect_get({cert_address: data}) self.expect_invalid_transaction()
def _pre_parse_payload_and_exec(self, context, cert, key, type='store'): crt_export, crt_bin, crt_sig, rem_sig, pub_key, \ valid_from, valid_to = PubKeyClient.get_crt_export_bin_sig_rem_sig(cert, key, context.client) transaction_payload = context.client.get_new_pub_key_payload( pub_key, rem_sig, crt_sig, valid_from, valid_to) cert_address = PubKeyHandler().make_address_from_data(pub_key) transaction_signature = None if type == 'store': transaction_signature = context.client.store_pub_key( pub_key, rem_sig, crt_sig, valid_from, valid_to) elif type == 'revoke': transaction_signature = context.client.revoke_pub_key(cert_address) else: raise AssertionError('Type for pre parse not found') return transaction_signature, cert_address, transaction_payload
def test_revoke_success(self): context = self.get_context() cert, key, key_export = PubKeyClient.create_certificate( context.pub_key_payload, org_name='different', signer=self.account_signer2) transaction_signature, cert_address, transaction_payload = self._pre_parse_payload_and_exec( context, cert, key, 'revoke') data = PubKeyStorage() data.owner = context.client.get_signer().get_public_key().as_hex() data.payload.CopyFrom(transaction_payload) data.revoked = False self.expect_get({cert_address: data}) data.revoked = True self.expect_set(transaction_signature, PubKeyMethod.REVOKE, {cert_address: data}) self.expect_ok()
def get(): client = PubKeyClient() return {'pubkey': client.get_public_key()}
async def get_node_config(request): client = PubKeyClient() return { 'node_public_key': client.get_public_key(), }
async def get_node_config(request): client = PubKeyClient() return { 'node_public_key': client.get_public_key(), 'storage_public_key': client.get_setting_value(SETTINGS_STORAGE_PUB_KEY), }
async def set_node_key(request): private_key = request.params['private_key'] PubKeyClient.set_priv_key_to_file(private_key) return True
def get(): client = PubKeyClient() data = client.fetch_peers() return {'is_synced': True, 'peer_count': len(data['data'])}
async def send_raw_transaction(request): try: data = request.params['data'] except KeyError: raise RpcInvalidParamsError(message='Missed data') try: transaction = base64.b64decode(data.encode('utf-8')) except Exception: raise RpcGenericServerDefinedError( error_code=-32050, message='Decode payload of tranasaction failed' ) try: tr_pb = Transaction() tr_pb.ParseFromString(transaction) except DecodeError: raise RpcGenericServerDefinedError( error_code=-32050, message='Failed to parse transaction proto' ) try: tr_head_pb = TransactionHeader() tr_head_pb.ParseFromString(tr_pb.header) except DecodeError: raise RpcGenericServerDefinedError( error_code=-32050, message='Failed to parse transaction head proto' ) try: tr_payload_pb = TransactionPayload() tr_payload_pb.ParseFromString(tr_pb.payload) except DecodeError: raise RpcGenericServerDefinedError( error_code=-32050, message='Failed to parse transaction payload proto' ) prefix, public_key = tr_head_pb.signer_public_key[:2], \ tr_head_pb.signer_public_key[2:] if prefix in ('02', '03') and len(public_key) != 64: raise RpcGenericServerDefinedError( error_code=-32050, message='Signer public key format is not valid' ) try: handler = TP_HANDLERS[tr_head_pb.family_name] except KeyError: raise RpcGenericServerDefinedError( error_code=-32050, message='Validation handler not set for this method' ) validator = _get_proto_validator(handler, tr_payload_pb) if validator and not validator.validate(): logger.debug('Form "send_raw_transaction" validator errors: ' f'{validator.errors}') raise RpcGenericServerDefinedError( error_code=-32050, message=f'Invalid "{validator.get_pb_class().__name__}" ' 'structure' ) client = PubKeyClient() response = await client.send_raw_transaction(tr_pb) return response['data']
async def export_node_key(request): client = PubKeyClient() return client.get_private_key()
async def get_node_info(request): client = PubKeyClient() data = client.fetch_peers() return {'is_synced': True, 'peer_count': len(data['data'])}
async def fetch_peers(request): client = PubKeyClient() return client.fetch_peers()