def read_c_result(ID, server: cServer): global result_ID_list p = pcap.PCAP(server.s_c_feed) p.open('r') for w in p: # here we apply our knowledge about the event/pkt's internal struct try: e = cbor2.loads(w) except: logging.critical('cbor2 loader failed - skipping logentry') continue href = hashlib.sha256(e[0]).digest() e[0] = cbor2.loads(e[0]) # rewrite the packet's byte arrays for pretty printing: e[0] = pcap.base64ify(e[0]) fid = e[0][0] seq = e[0][1] if e[2] != None: e[2] = cbor2.loads(e[2]) e[1] = pcap.base64ify(e[1]) if isinstance(e[2], dict) and e[2]['type'] == 'result': if e[2]['ID'] == ID: logging.debug(f'from read_result ID={e[2]["ID"]}') logging.debug(f"** fid={fid}, seq={seq}, ${len(w)} bytes") logging.debug(f" hashref={href.hex()}") logging.debug(f" content={e[2]}") if result_ID_list.__contains__(ID): clear_await(ID) handle_result(e) return True p.close() return False
def on_message(client, userdata, msg): # print("Message: "+msg.topic+" "+str(cbor.loads(msg.payload))) if userdata.anonymous and msg.topic == topic_register_res % userdata.conn_id: client.unsubscribe(topic_register_res % userdata.conn_id) client.disconnect() client.loop_stop() payload = cbor.loads(msg.payload) if "error" in payload: print("Server error: " + payload["error"]) return my_log("Registered") userdata.sys_id = payload["id"] client = mqtt.Client(userdata.conn_id) userdata.client = client client.user_data_set(userdata) client.on_log = on_log client.on_connect = on_connect client.on_message = on_message client.on_disconnect = on_disconnect client.username_pw_set(userdata.username, userdata.password) userdata.anonymous = False client.connect("aerostun.dev") client.loop_start() elif (not userdata.anonymous) and (msg.topic == topic_myid_res % userdata.conn_id): my_log("Got my id") assert userdata.sys_id == cbor.loads(msg.payload)["id"] client.subscribe(topic_quickbook_res % userdata.sys_id) userdata.done.set() elif (not userdata.anonymous) and (msg.topic == topic_quickbook_res % userdata.sys_id): global sec_in sec_in += 1 userdata.total_recv += 1
def load_cbor(m): """ :param msg: CBOR Encoded message :type msg: hex encoded string (each character is a two digit hex value) :raise SyntaxError: Malformed CBOR encoded message :raise ValueError: Malformed CBOR encoded message :raise cbor2.decoder.CBORDecodeError: Malformed CBOR encoded message """ if os.path.isfile(m): try: with open(m, 'rb') as f: rtn = cbor2.load(f) except (SyntaxError, ValueError, cbor2.decoder.CBORDecodeError) as e: raise e elif type(m) == str: try: rtn = cbor2.loads(m) if type(rtn) is not dict: rtn = cbor2.loads(''.join( [m[i:i + 2].decode('hex') for i in range(0, len(m), 2)])) except (SyntaxError, ValueError, cbor2.decoder.CBORDecodeError) as e: raise e else: raise Exception('Cannot load cbor, improperly formatted') return json.loads(json.dumps(rtn))
def initiator(ephemeral_initiator_key, test_vectors): if test_vectors['I']['cred_type'] == 0: local_auth_key = None local_cred = cbor2.loads(test_vectors['I']['cred']) else: local_auth_key = CoseKey.decode(test_vectors['I']['cred']) local_cred = CoseKey.decode(test_vectors['I']['cred']) if test_vectors['R']['cred_type'] == 0: remote_auth_key = None remote_cred = cbor2.loads(test_vectors['R']['cred']) else: remote_auth_key = CoseKey.decode(test_vectors['R']['cred']) remote_cred = CoseKey.decode(test_vectors['R']['cred']) return Initiator( corr=test_vectors['S']['corr'], method=test_vectors['S']['method'], cred=(local_cred, local_auth_key), cred_idi=cbor2.loads(test_vectors['I']['cred_id']), auth_key=CoseKey.decode(test_vectors['I']['auth_key']), selected_cipher=test_vectors['I']['selected'], supported_ciphers=[CipherSuite.from_id(c) for c in test_vectors["I"]["supported"]], conn_idi=test_vectors['I']['conn_id'], remote_cred_cb=lambda x: (remote_cred, remote_auth_key), ephemeral_key=ephemeral_initiator_key, )
def read_request(): ''' Since the server can also detruce - close a connection the client has to read requests :return: ''' global next_request_ID p = pcap.PCAP(isp_log) p.open('r') for w in p: e = cbor2.loads(w) href = hashlib.sha256(e[0]).digest() e[0] = cbor2.loads(e[0]) e[0] = pcap.base64ify(e[0]) fid = e[0][0] seq = e[0][1] if e[2] != None: e[2] = cbor2.loads(e[2]) if isinstance(e[2], dict) and e[2]['type'] == 'request': request_ID = e[2]["ID"] logging.debug(f'req_id:{request_ID},next:{next_request_ID}') if request_ID == next_request_ID: logging.info(f'Handling request from server') next_request_ID += 1 handle_request(e[2]) p.close()
def responder(ephemeral_responder_key, test_vectors): if test_vectors['R']['cred_type'] == 0: local_cred = cbor2.loads(test_vectors['R']['cred']) local_auth_key = None else: local_cred = CoseKey.decode(test_vectors['R']['cred']) local_auth_key = CoseKey.decode(test_vectors['R']['cred']) if test_vectors['I']['cred_type'] == 0: remote_cred = cbor2.loads(test_vectors['I']['cred']) remote_auth_key = None else: remote_cred = CoseKey.decode(test_vectors['I']['cred']) remote_auth_key = CoseKey.decode(test_vectors['I']['cred']) responder = Responder( conn_idr=test_vectors["R"]["conn_id"], cred_idr=cbor2.loads(test_vectors['R']['cred_id']), auth_key=CoseKey.decode(test_vectors['R']['auth_key']), cred=(local_cred, local_auth_key), supported_ciphers=[ CipherSuite.from_id(c) for c in test_vectors["R"]["supported"] ], remote_cred_cb=lambda arg: (remote_cred, remote_auth_key), ephemeral_key=ephemeral_responder_key) responder.cred_idi = test_vectors['I']['cred_id'] return responder
def assertCborSame(self, output, reference): # To date, Python's CBOR libraries don't support encoding to # canonical-form CBOR, so we have to parse and deep-compare. output_dec = cbor2.loads(output) reference_dec = cbor2.loads(reference) self.assertEqual(output_dec, reference_dec)
def get_all_info(fname): p = PCAP(fname) p.open('r') # read line for line in file p for w in p: # here we apply our knowledge about the event/pkt's internal struct e = cbor2.loads(w) href = hashlib.sha256(e[0]).digest() e[0] = cbor2.loads(e[0]) # rewrite the packet's byte arrays for pretty printing: e[0] = base64ify(e[0]) fid = e[0][0] seq = e[0][1] if e[2] != None: e[2] = cbor2.loads(e[2]) print(f"fid={fid}") print(f"seq={seq}") print(f"hprev={e[0][2]}") # points to hashref print(f"sinfo={e[0][3]}") print(f"hcont={e[0][4][0]}") print(f"hcont={e[0][4][1]}") print(f"signature={base64ify(e[1])}") print(f"hashref={href.hex()}") print(f"content={e[2]}") print('---------------------------------') p.close()
def decode(cls, received: bytes, allow_unknown_attributes: bool = True) -> 'CM': """ Decode received COSE message based on the CBOR tag. :param received: COSE messages encoded as bytes :param allow_unknown_attributes: Allows unknown COSE header attributes (i.e., not registered at IANA) :raises AttributeError: When the COSE message, it cannot be decoded properly :raises ValueError: The received parameter must be bytes :raises KeyError: thrown when the CBOR tag, identifying the COSE message is unrecognized :raises TypeError: thrown when the messages cannot be decoded properly :returns: An initialized CoseMessage """ try: cbor_tag = cbor2.loads(received).tag cose_obj = cbor2.loads(received).value except AttributeError: raise AttributeError("Message was not tagged.") except ValueError: raise ValueError("Decode accepts only bytes as input.") if isinstance(cose_obj, list): try: return cls._COSE_MSG_ID[cbor_tag].from_cose_obj( cose_obj, allow_unknown_attributes=allow_unknown_attributes) except KeyError as e: raise KeyError("CBOR tag is not recognized", e) else: raise TypeError("Bytes cannot be decoded as COSE message")
def verify_token(self, token): data = cbor2.loads(base64.b64decode(token["token"])) credential_id = data["credentialId"] client_data = ClientData(data["clientDataJSON"]) auth_data = AuthenticatorData(data["authenticatorData"]) signature = data["signature"] state = token["state"] domain = token["domain"] credentials_query = Fido2Device.objects.filter(user=self.user) credentials = [ AttestedCredentialData(cbor2.loads(c.authenticator_data)) for c in credentials_query ] rp = PublicKeyCredentialRpEntity(domain, settings.FIDO2_RP_NAME) fido2 = Fido2Server(rp) try: fido2.authenticate_complete( state, credentials, credential_id, client_data, auth_data, signature, ) return True except ValueError: logger.exception("Error in FIDO2 final authentication") return False
async def render_post(self, request): global battery_SOC global battery_AC_consumption print ("render", request.opt.uri_path) current_time = str(datetime.datetime.utcnow()) ct = request.opt.content_format or \ aiocoap.numbers.media_types_rev['text/plain'] if ct == aiocoap.numbers.media_types_rev['text/plain']: print ("text:", request.payload) elif ct == aiocoap.numbers.media_types_rev['application/cbor']: print ("cbor:", cbor.loads(request.payload)) #the device_name sent by actuator controller can be used to calculate average humidity request_data = cbor.loads(request.payload) parameter_name = request_data[0] ic = 0 totalh = 0 #fetch the humidity levels for all the pycom sensors shed_status = {} if parameter_name == "BSOC": shed_status['BSOC'] = battery_SOC shed_status['AC_consumption'] = battery_AC_consumption print("The shed parameters are: ", shed_status ) #Compress this data using CBOR before sending it bback to watering pycom controller cbor_data = cbor.dumps(shed_status) #send back the humidity levels to watering pycom return aiocoap.Message(code=aiocoap.CHANGED, payload = binascii.hexlify(cbor_data))
def load_cbor(m): """ :param m: CBOR Encoded message :type m: hex encoded string (each character is a two digit hex value) :raise SyntaxError: Malformed CBOR encoded message :raise ValueError: Malformed CBOR encoded message :raise cbor2.decoder.CBORDecodeError: Malformed CBOR encoded message """ if os.path.isfile(m): try: with open(m, 'rb') as f: rtn = cbor2.load(f) except (SyntaxError, ValueError, cbor2.decoder.CBORDecodeError) as e: raise e elif type(m) in [str, bytes]: try: rtn = cbor2.load(StringIO(m)) if rtn is not dict: rtn = cbor2.loads(binascii.unhexlify(m)) except (SyntaxError, ValueError, cbor2.decoder.CBORDecodeError) as e1: try: rtn = cbor2.loads(binascii.unhexlify(m)) except (SyntaxError, ValueError, cbor2.decoder.CBORDecodeError) as e2: raise e2 else: raise Exception('Cannot load cbor, improperly formatted') return Utils.defaultEncode(rtn)
def remove_metadata(bytecode: bytes): bytecode = bytecode.decode().rstrip() # Bail on empty bytecode if not bytecode or len(bytecode) <= 2: return bytecode # Gather length of CBOR metadata from the end of the file raw_length = bytecode[-4:] length = int(raw_length, base=16) # Bail on unreasonable values for length (meaning we read something else other than metadata length) if length * 2 > len(bytecode) - 4: return bytecode # Gather what we assume is the CBOR encoded metadata, and try to parse it metadata_start = len(bytecode) - length * 2 - 4 metadata = bytecode[metadata_start:len(bytecode) - 4] # Parse it to see if it is indeed valid metadata try: cbor2.loads(binascii.unhexlify(metadata)) except: logger.warning('Error parsing contract metadata. Ignoring.') return bytecode # Return bytecode without it return bytecode[0:metadata_start].encode()
def test_responder_finalize(responder, test_vectors): responder.msg_1 = MessageOne.decode(test_vectors['S']['message_1']) responder.msg_2 = MessageTwo.decode( responder.create_message_two(test_vectors['S']['message_1'])) responder.msg_3 = MessageThree.decode(test_vectors['S']['message_3']) decoded = EdhocMessage.decode( responder._decrypt(responder.msg_3.ciphertext)) if KID.identifier in cbor2.loads(test_vectors['I']['cred_id']): assert decoded[0] == EdhocMessage.encode_bstr_id( cbor2.loads(test_vectors['I']['cred_id'])[KID.identifier]) else: assert decoded[0] == cbor2.loads(test_vectors['I']['cred_id']) assert decoded[1] == test_vectors['S']['signature_3'] if getattr(responder, 'remote_authkey', None) is None: warnings.warn(NoRemoteKey()) return c_i, c_r, app_aead, app_hash = responder.finalize( test_vectors['S']['message_3']) assert c_i == test_vectors['I']['conn_id'] assert c_r == test_vectors['R']['conn_id'] assert app_aead == CipherSuite.from_id( test_vectors['I']['selected']).app_aead.identifier assert app_hash == CipherSuite.from_id( test_vectors['I']['selected']).app_hash.identifier
def get_seq(fname): p = PCAP(fname) p.open('r') seq = 0 for w in p: e = cbor2.loads(w) e[0] = base64ify(cbor2.loads(e[0])) seq = e[0][1] p.close() return seq
def load(self): p = pcap.PCAP(self.fn) p.open(self.fn, 'r') for e in p: e = cbor2.loads(e) e[1] = cbor2.loads(e[1]) if e[0] != ENC_CLR or e[1][0] != 'set': continue self.kv[e[1][1]] = e[1][2] p.close()
async def start_node_observation(uri, title): get_obs_req = Message(code=GET, uri=uri, observe=0) request = protocol.request(get_obs_req) initResponse = await request.response weights[title] = cbor.loads(initResponse.payload) async for response in request.observation: weights[title] = cbor.loads(response.payload) del weights[title] del uris[title]
def get_fid_and_seq(fname): p = PCAP(fname) p.open('r') seq = 0 fid = 0 for w in p: e = cbor2.loads(w) e[0] = cbor2.loads(e[0]) fid = e[0][0] seq = e[0][1] p.close() return fid, seq
def dumpIt(fname): p = PCAP(fname) p.open('r') array = [] for w in p: e = cbor2.loads(w) e[0] = cbor2.loads(e[0]) e[0] = base64ify(e[0]) if e[2] != None: e[2] = cbor2.loads(e[2]) array.append(e[2]) p.close() return array
def createInventory(fname, inventoryDict): log = importPCAP(fname) log.open('r') inventory = open(inventoryDict, 'w+') for w in log: e = cbor2.loads(w) href = hashlib.sha256(e[0]).digest() e[0] = cbor2.loads(e[0]) # rewrite the packet's byte arrays for pretty printing: e[0] = pcap.base64ify(e[0]) fid = e[0][0] seq = e[0][1] inventory.write("%d \n" % seq) log.close()
def post(self, thing_id='0'): """ Handle a POST request. thing_id -- ID of the thing this request is for """ thing = self.get_thing(thing_id) if thing is None: self.set_status(404) return # uses CBOR for load/dump of payload/body, another implementation with JSON possible prot, unprot, cipher = loads(self.request.body).value try: oscore_context = super().ace_rs.oscore_context(unprot, self.scope) except NotAuthorizedException: self.set_status(401) return ## try: args = loads(oscore_context.decrypt(self.request.body)) # translate keys from bytes to str _args = {} for k in args: _args.update({k.decode('utf-8'): args.get(k)}) args = _args except ValueError: self.set_status(400) return response = {} for action_name, action_params in args.items(): input_ = None if 'input' in action_params: input_ = action_params['input'] action = thing.perform_action(action_name, input_) if action: response.update(action.as_action_description()) # Start the action tornado.ioloop.IOLoop.current().spawn_callback( perform_action, action, ) self.set_status(201) self.write(oscore_context.encrypt(dumps(response)))
def get_only_context(fname): p = PCAP(fname) p.open('r') for w in p: # here we apply our knowledge about the event/pkt's internal struct e = cbor2.loads(w) e[0] = cbor2.loads(e[0]) # rewrite the packet's byte arrays for pretty printing: e[0] = base64ify(e[0]) if e[2] is not None: e[2] = cbor2.loads(e[2]) print(f" content={e[2]}") p.close()
def test_verify_attestation_signature(self): crv = P384 root_private_key = ec.generate_private_key(crv.curve_obj, backend=default_backend()) private_key = ec.generate_private_key(crv.curve_obj, backend=default_backend()) root_cert, cert = create_certs(root_private_key, private_key) doc_bytes = create_attestation_doc(root_cert, cert) attestation = create_cose_1_sign_msg(doc_bytes, private_key) payload = cbor2.loads(attestation) doc = cbor2.loads(payload[2]) attest.verify_attestation_signature(attestation, doc["certificate"])
def verify_validation(feed, received_event): feed_id = feed[0] seq_num = feed[1] dc = DatabaseConnector() last_event = dc.get_event(feed_id, seq_num) # Controlling if last event exists if last_event is None: # If the list has -1, it means it is a new feed to create if seq_num == -1: print("Awaiting creation of new feed:", feed_id) return True else: return False last_event = cbor2.loads(last_event) last_meta = cbor2.loads(last_event[0]) # meta received_event = cbor2.loads(received_event) received_meta = cbor2.loads(received_event[0]) # meta # Controlling feed ids if last_meta[0] != received_meta[0]: print("Feed ID validation... FAILED") return False print("Feed ID validation... PASSED") # Controlling sequence numbers if last_meta[1] + 1 != received_meta[1]: print("Seq-Num validation... FAILED") return False print("Seq-Num validation... PASSED") # Controlling last meta hash value / prev hash value if received_meta[2][0] != 0 or get_hash( last_event[0]) != received_meta[2][1]: print("Meta Hash validation... FAILED") return False print("Meta Hash validation... PASSED") # Controlling the signature if last_meta[3] != received_meta[3]: print("Signature validation... FAILED") return False print("Signature validation... PASSED") print("Extension... VALID") return True
async def render_post(self, request): print ("render", request.opt.uri_path) current_time = str(datetime.datetime.utcnow()) ct = request.opt.content_format or \ aiocoap.numbers.media_types_rev['text/plain'] if ct == aiocoap.numbers.media_types_rev['text/plain']: print ("text:", request.payload) elif ct == aiocoap.numbers.media_types_rev['application/cbor']: print ("cbor:", cbor.loads(request.payload)) #the device_name sent by actuator controller can be used to calculate average humidity request_data = cbor.loads(request.payload) device_name = request_data[1] #if not found, add the actuator device details in the device table in MongoDB unique_id = request_data[0] actuator_device = client.green_wall.devices.find_one({"mac_address": unique_id}) if actuator_device: newvalues = { "$set": { "last_updated_at": current_time } } client.green_wall.devices.update_one({"mac_address": unique_id}, newvalues) else: actuator_device_data = { "mac_address": unique_id, "last_updated_at": current_time, "name": "NA"} client.green_wall.devices.insert_one(actuator_device_data) ic = 0 totalh = 0 #fetch the humidity levels for all the pycom sensors humidity_levels = [] if device_name == "ALL": devices = client.green_wall.devices.find() else: devices = client.green_wall.devices.find({"name":device_name}) for d in devices: humidity_level = {} humidity_level['device_name'] = d['name'] latest_measures = list(client.green_wall.devicemeasures.find({"device_id":d['_id']}).sort([('recorded_at', -1)]).limit(1))[0] for ms in latest_measures['measures']: ic += 1 totalh += ms avg_humidity = totalh / ic humidity_level['avg_humidity'] = avg_humidity humidity_levels.append(humidity_level) print("The Humidity Levels of Pycoms on the wall are: ", humidity_levels ) #Compress this data using CBOR before sending it bback to watering pycom controller cbor_data = cbor.dumps(humidity_levels) #send back the humidity levels to watering pycom return aiocoap.Message(code=aiocoap.CHANGED, payload = binascii.hexlify(cbor_data))
def test_responder_message2(responder, test_vectors): responder.msg_1 = MessageOne.decode(test_vectors['S']['message_1']) hash_func = CipherSuite.from_id( responder.msg_1.selected_cipher).hash.hash_cls crv = CipherSuite.from_id(responder.msg_1.selected_cipher).dh_curve assert responder.shared_secret( responder.ephemeral_key, OKPKey(x=responder.g_x, crv=crv)) == test_vectors['S']['g_xy'] assert responder._prk2e == test_vectors['S']['prk_2e'] assert responder._prk3e2m == test_vectors['S']['prk_3e2m'] assert responder.data_2 == test_vectors['S']['data_2'] assert responder._th2_input == test_vectors['S']['input_th_2'] assert responder.cred_id == cbor2.loads(test_vectors['R']['cred_id']) assert responder.transcript( hash_func, responder._th2_input) == test_vectors['S']['th_2'] assert responder._hkdf2( 16, 'K_2m', prk=responder._prk3e2m) == test_vectors['S']['k_2m'] assert responder._hkdf2( 13, 'IV_2m', prk=responder._prk3e2m) == test_vectors['S']['iv_2m'] assert responder._mac(responder._hkdf2, 'K_2m', 16, 'IV_2m', 13, responder._th2_input, responder._prk3e2m, responder.aad2_cb) == test_vectors['S']['mac_2'] assert responder.signature_or_mac2( test_vectors['S']['mac_2']) == test_vectors['S']['signature_2'] assert responder._p_2e == test_vectors['S']['p_2e'] assert responder._hkdf2( len(responder._p_2e), 'KEYSTREAM_2', prk=responder._prk2e) == test_vectors['S']['keystream_2'] assert responder.ciphertext_2 == test_vectors['S']['ciphertext_2'] assert responder.create_message_two( test_vectors['S']['message_1']) == test_vectors['S']['message_2']
def _glob(self, glob: Union[str, os.PathLike]) -> list: """List files matich a glob pattern :returns: list of matching paths :throws: DecentFsFileNotFound if not found """ logging.debug('Searching for %s', glob) seq = 0 timer = time.process_time_ns() matchs = set() for entry in self.metafeed: # skip special block if seq == 0: seq += 1 continue findpath, flags, _, _, _ = cbor2.loads(entry.content()) logging.debug('Found %s with flags %s', findpath, flags) if pathlib.PurePosixPath(findpath).match(glob.__str__()): timer = time.process_time_ns() - timer logging.debug('Got a match at %i with flags %s within %i ms', seq, flags, timer / 1000000) if flags == 'R': matchs.remove(findpath) else: matchs.add(findpath) seq += 1 if len(matchs) == 0: raise DecentFsFileNotFound('File {} not found'.format( glob.__str__())) return matchs
def revisions(self, path: Union[str, os.PathLike]) -> int: """Count revisions of a file This function can also take deleted paths into account while _find returns only undeleted paths. :returns: number of revisions :throws: DecentFsFileNotFound if not found """ logging.debug('Searching for %s', path) revisions = 0 seq = 0 timer = time.process_time_ns() for entry in self.metafeed: # skip special block if seq == 0: seq += 1 continue findpath, flags, timestamp, size, _ = cbor2.loads(entry.content()) if findpath == path.__str__(): timer = time.process_time_ns() - timer logging.info('Found with flags %s from %i with %i bytes', flags, timestamp, size) logging.debug('Found at %i within %i ms', seq, timer / 1000000) revisions += 1 seq += 1 if revisions == 0: raise DecentFsFileNotFound('File {} not found'.format( path.__str__())) return revisions
def test_signer_new(self): signer = Signer.new( cose_key=COSEKey.from_jwk({ "kty": "EC", "kid": "01", "crv": "P-256", "x": "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8", "y": "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4", "d": "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM", }), protected={"alg": "ES256"}, unprotected={"kid": "01"}, ) assert signer.unprotected[4] == b"01" assert cbor2.loads(signer.protected)[1] == -7 assert signer.cose_key.alg == -7 assert signer.cose_key.kid == b"01" try: signer.sign(b"Hello world!") signer.verify(b"Hello world!") except Exception: pytest.fail("signer.sign and verify should not fail.")
def _load_msg(self, buf): try: msg = cbor2.loads(buf, tag_hook=default_decoder) except cbor2.CBORDecodeError as e: raise IOError('unable to deserialize data') if isinstance(msg, str): try: schema = self._protocol.recv[msg] except KeyError: raise IOError('unknown message: %s' % msg) if schema is NoData: return msg, None raise IOError('missing data for: %s' % msg) else: try: msg, data = msg except (TypeError, ValueError): raise IOError('invalid message structure received') try: schema = self._protocol.recv[msg] except KeyError: raise IOError('unknown message: %s' % msg) if schema is NoData: raise IOError('data not expected for: %s' % msg) try: return msg, schema(data) except Invalid as e: raise IOError('invalid data for %s: %s' % (msg, e))
def _deserialize_value(self, data): return cbor2.loads(data)
def deserialize(self, payload: bytes): return cbor2.loads(payload, **self.decoder_options)