def get_history(self, addr): out = [] o = self.listunspent(addr) for item in o: out.append((item['tx_hash'], item['height'])) h = self.db_hist.get(addr) while h: item = h[0:80] h = h[80:] txi = item[0:32].encode('hex') hi = hex_to_int(item[36:40]) txo = item[40:72].encode('hex') ho = hex_to_int(item[76:80]) out.append((txi, hi)) out.append((txo, ho)) # sort out.sort(key=lambda x:x[1]) # uniqueness out = set(out) return map(lambda x: {'tx_hash':x[0], 'height':x[1]}, out)
def get_history(self, addr): out = [] o = self.listunspent(addr) for item in o: out.append((item['height'], item['tx_hash'])) index = 0 h = self.db_hist_get_index(addr, index) while h: item = h[0:80] h = h[80:] txi = item[0:32].encode('hex') hi = hex_to_int(item[36:40]) txo = item[40:72].encode('hex') ho = hex_to_int(item[76:80]) out.append((hi, txi)) out.append((ho, txo)) if not h: index += 1 h = self.db_hist_get_index(addr, index) # uniqueness out = set(out) # sort by height then tx_hash out = list(out) out.sort() return map(lambda x: {'height':x[0], 'tx_hash':x[1]}, out)
def set_spent(self, addr, txi, txid, index, height, undo): key = self.address_to_key(addr) leaf = key + txi s = self.delete_key(leaf) value = hex_to_int(s[0:8]) in_height = hex_to_int(s[8:12]) undo[leaf] = value, in_height # delete backlink txi-> addr self.db_addr.delete(txi) # add to history txo = (txid + int_to_hex(index,4) + int_to_hex(height,4)).decode('hex') self.db_hist_add(addr, txi + int_to_hex(in_height,4).decode('hex') + txo)
def __getX2(self, PICC_PK, decryptedNonce): x = PICC_PK[1:33] y = PICC_PK[33:] pointY1 = Point(self.curve_brainpoolp256r1, utils.hex_to_int(x), utils.hex_to_int(y), self._q) sharedSecret_P = pointY1 * self.__PCD_SK_x1 pointG_strich = (self.pointG * utils.hex_to_int(decryptedNonce)) + sharedSecret_P self.__PCD_SK_x2 = utils.hex_to_int(bytearray(get_random_bytes(32))) PCD_PK_X2 = pointG_strich * self.__PCD_SK_x2 return bytearray( bytearray([0x04]) + utils.long_to_bytearray(PCD_PK_X2.x()) + utils.long_to_bytearray(PCD_PK_X2.y()))
def set_spent(self, addr, txi, txid, index, height, undo): key = self.address_to_key(addr) leaf = key + txi s = self.delete_key(leaf) value = hex_to_int(s[0:8]) in_height = hex_to_int(s[8:12]) undo[leaf] = value, in_height # delete backlink txi-> addr self.db_addr.delete(txi) # add to history s = self.db_hist.get(addr) if s is None: s = '' txo = (txid + int_to_hex(index,4) + int_to_hex(height,4)).decode('hex') s += txi + int_to_hex(in_height,4).decode('hex') + txo s = s[ -80*self.pruning_limit:] self.db_hist.put(addr, s)
def listunspent(self, addr): key = self.address_to_key(addr) out = [] for k, v in self.db_utxo.iterator(start=key): if not k.startswith(key): break if len(k) == KEYLENGTH: txid = k[20:52].encode('hex') txpos = hex_to_int(k[52:56]) h = hex_to_int(v[8:12]) v = hex_to_int(v[0:8]) out.append({'tx_hash': txid, 'tx_pos':txpos, 'height': h, 'value':v}) out.sort(key=lambda x:x['height']) return out
def auth(): global c, conn if request.method == 'POST': js = json.loads(request.data) I = js['username'] c.execute("SELECT rowid, salt, verifier FROM users WHERE username=?", (I, )) user_rows = c.fetchall() if len(user_rows) <= 0: error = {'error': 'Authentication Failed'} return make_response(json.dumps(error), status=400) user_id = user_rows[0][0] s = user_rows[0][1] v = hex_to_int(user_rows[0][2]) A = hex_to_int(js['client_ephemeral']) b = cryptrand(1024) # For testing: #b = hex_to_int('124b5772441b0b42ca71e32bef29c8103c21ae07b1fd24e502a25c2e4d0a16489abd67f500f3e80bd5fca4f1f29b9f43a61cad4b23fd20a37504db049dc4be9f217b1b59cdada11efc741d24bb78e17b1e940d107b4877c0bfdd711ec31f18fbc7d7a6a71b5d9d700fba2edea315e6a2d24efe3e7a0c0c1a1f4a03fba1deba2c') B = (params['k'] * v + pow(params['g'], b, params['N'])) % params['N'] auth_session_key = int_to_hex(cryptrand(64)) auth_sessions[auth_session_key] = { 'I': I, 'A': A, 's': s, 'v': v, 'b': b, 'B': B, 'user_id': user_id } data = { "salt": s, "server_ephemeral": int_to_hex(B), "auth_session": auth_session_key } return make_response(json.dumps(data)) elif request.method == 'DELETE': resp = make_response('{}') for k, v in request.cookies.iteritems(): if 'AUTH-' in k: resp.set_cookie(k, '', expires=0) return resp
def listunspent(self, addr): key = self.address_to_key(addr) if key is None: raise BaseException("Invalid Bitcoin address", addr) out = [] for k, v in self.db_utxo.iterator(start=key): if not k.startswith(key): break if len(k) == KEYLENGTH: txid = k[20:52].encode("hex") txpos = hex_to_int(k[52:56]) h = hex_to_int(v[8:12]) v = hex_to_int(v[0:8]) out.append({"tx_hash": txid, "tx_pos": txpos, "height": h, "value": v}) out.sort(key=lambda x: x["height"]) return out
def listunspent(self, addr): key = self.address_to_key(addr) if key is None: raise BaseException('Invalid Gamecredits address', addr) out = [] with self.db_utxo.lock: for k, v in self.db_utxo.db.iterator(start=key): if not k.startswith(key): break if len(k) == KEYLENGTH: txid = k[20:52].encode('hex') txpos = hex_to_int(k[52:56]) h = hex_to_int(v[8:12]) v = hex_to_int(v[0:8]) out.append({'tx_hash': txid, 'tx_pos':txpos, 'height': h, 'value':v}) out.sort(key=lambda x:x['height']) return out
def decrypt(self, cipher: TextIO, key_filename: str, text: TextIO) -> None: """Decrypt the cipher using the key from the file.""" with open(key_filename, 'r') as key_file: while True: cipher_hex = cipher.read(HEX_LENGTH) key_hex = key_file.read(HEX_LENGTH) if cipher_hex == '' or key_hex == '': break cipher_int = hex_to_int(cipher_hex) char_int_allowed(cipher_int) key_int = hex_to_int(key_hex) char_int_allowed(key_int) text_int = cipher_int ^ key_int text.write(chr(text_int))
def listunspent(self, addr): key = self.address_to_key(addr) if key is None: raise BaseException('Invalid Bitcoin address', addr) out = [] with self.db_utxo.lock: for k, v in self.db_utxo.db.iterator(start=key): if not k.startswith(key): break if len(k) == KEYLENGTH: txid = k[20:52].encode('hex') txpos = hex_to_int(k[52:56]) h = hex_to_int(v[8:12]) v = hex_to_int(v[0:8]) out.append({'tx_hash': txid, 'tx_pos':txpos, 'height': h, 'value':v}) if len(out) == 1000: print_log('max utxo reached', addr) break out.sort(key=lambda x:x['height']) return out
def delete_key(self, leaf): path = self.get_path(leaf) #print "delete key", leaf.encode('hex'), map(lambda x: x.encode('hex'), path) s = self.db_utxo.get(leaf) self.db_utxo.delete(leaf) if leaf in self.hash_list: self.hash_list.pop(leaf) parent = path[-1] letter = leaf[len(parent)] parent_node = self.get_node(parent) parent_node.remove(letter) # remove key if it has a single child if parent_node.is_singleton(parent): #print "deleting parent", parent.encode('hex') self.db_utxo.delete(parent) if parent in self.hash_list: self.hash_list.pop(parent) l = parent_node.get_singleton() _hash, value = parent_node.get(l) skip = self.get_skip(parent + l) otherleaf = parent + l + skip # update skip value in grand-parent gp = path[-2] gp_items = self.get_node(gp) letter = otherleaf[len(gp)] new_skip = otherleaf[len(gp)+1:] gp_items.set(letter, None, 0) self.set_skip(gp+ letter, new_skip) #print "gp new_skip", gp.encode('hex'), new_skip.encode('hex') self.put_node(gp, gp_items) # note: k is not necessarily a leaf if len(otherleaf) == KEYLENGTH: ss = self.db_utxo.get(otherleaf) _hash, value = otherleaf[20:52], hex_to_int(ss[0:8]) else: _hash, value = None, None self.update_node_hash(otherleaf, path[:-1], _hash, value) else: self.put_node(parent, parent_node) _hash, value = None, None self.update_node_hash(parent, path[:-1], _hash, value) return s
def delete_key(self, leaf): path = self.get_path(leaf) #print "delete key", leaf.encode('hex'), map(lambda x: x.encode('hex'), path) s = self.db_utxo.get(leaf) self.db_utxo.delete(leaf) if leaf in self.hash_list: self.hash_list.pop(leaf) parent = path[-1] letter = leaf[len(parent)] parent_node = self.get_node(parent) parent_node.remove(letter) # remove key if it has a single child if parent_node.is_singleton(parent): #print "deleting parent", parent.encode('hex') self.db_utxo.delete(parent) if parent in self.hash_list: self.hash_list.pop(parent) l = parent_node.get_singleton() _hash, value = parent_node.get(l) skip = self.get_skip(parent + l) otherleaf = parent + l + skip # update skip value in grand-parent gp = path[-2] gp_items = self.get_node(gp) letter = otherleaf[len(gp)] new_skip = otherleaf[len(gp) + 1:] gp_items.set(letter, None, 0) self.set_skip(gp + letter, new_skip) #print "gp new_skip", gp.encode('hex'), new_skip.encode('hex') self.put_node(gp, gp_items) # note: k is not necessarily a leaf if len(otherleaf) == KEYLENGTH: ss = self.db_utxo.get(otherleaf) _hash, value = otherleaf[20:52], hex_to_int(ss[0:8]) else: _hash, value = None, None self.update_node_hash(otherleaf, path[:-1], _hash, value) else: self.put_node(parent, parent_node) _hash, value = None, None self.update_node_hash(parent, path[:-1], _hash, value) return s
def auth_verify(): global c, conn js = json.loads(request.data) #I = js['I'] auth_session_key = js['auth_session'] I = auth_sessions[auth_session_key]['I'] A = auth_sessions[auth_session_key]['A'] v = auth_sessions[auth_session_key]['v'] B = auth_sessions[auth_session_key]['B'] b = auth_sessions[auth_session_key]['b'] s = auth_sessions[auth_session_key]['s'] user_id = auth_sessions[auth_session_key]['user_id'] #M_c = hex_to_int(js['M_c']) M_c = hex_to_int(js['client_proof']) u = H(A, B) S_s = pow(A * pow(v, u, params['N']), b, params['N']) K_s = H(S_s) M_s = H(A, M_c, K_s) UID = int_to_hex(H(user_id, s)) session_token = int_to_hex(cryptrand(512)) data = { "server_proof": int_to_hex(M_s), "UID": UID, "session_token": session_token } # remove all old sessions resp = make_response(json.dumps(data)) for key, v in request.cookies.iteritems(): if 'AUTH-' in key: old_uid = key.replace("AUTH-", '') #c.execute("DELETE FROM sessions WHERE UID=?",(old_uid,)) resp.set_cookie(key, '', expires=0) c.execute( "INSERT INTO sessions (session_token, user_id, UID) VALUES (?, ?, ?)", (session_token, user_id, UID)) conn.commit() resp.set_cookie('AUTH-' + UID, json.dumps({ "session_token": session_token, "UID": UID })) return resp
def decrypt(self, cipher: TextIO, key: str, text: TextIO) -> None: """Decrypt the cipher using the key.""" super().decrypt(cipher, key, text) while True: cipher_hex = cipher.read(HEX_LENGTH) if cipher_hex == '': break cipher_int = hex_to_int(cipher_hex) char_int_allowed(cipher_int) text_int = self._process(cipher_int) text.write(chr(text_int))
def delete_address(self, leaf): path = self.get_path(leaf) if path is False: print_log("addr not in tree", leaf.encode('hex'), self.key_to_address(leaf[0:20]), self.db_utxo.get(leaf)) raise s = self.db_utxo.get(leaf) self.db_utxo.delete(leaf) if leaf in self.hash_list: self.hash_list.pop(leaf) parent = path[-1] letter = leaf[len(parent)] items = self.get_node(parent) items.pop(letter) # remove key if it has a single child if len(items) == 1: letter, v = items.items()[0] self.db_utxo.delete(parent) if parent in self.hash_list: self.hash_list.pop(parent) # we need the exact length for the iteration i = self.db_utxo.iterator() i.seek(parent + letter) k, v = i.next() # note: k is not necessarily a leaf if len(k) == KEYLENGTH: _hash, value = k[20:52], hex_to_int(v[0:8]) else: _hash, value = None, None self.update_node_hash(k, path[:-1], _hash, value) else: self.put_node(parent, items) _hash, value = None, None self.update_node_hash(parent, path[:-1], _hash, value) return s
def get_hash(self, x, parent): if x: assert self.k != 0 skip_string = x[len(parent)+1:] if x != '' else '' x = 0 v = 0 hh = '' for i in xrange(256): if (self.k&(1<<i)) != 0: ss = self.s[x:x+40] hh += ss[0:32] v += hex_to_int(ss[32:40]) x += 40 try: _hash = Hash(skip_string + hh) except: _hash = None if x: assert self.k != 0 return _hash, v
def get_hash(self, x, parent): if x: assert self.k != 0 skip_string = x[len(parent) + 1:] if x != '' else '' x = 0 v = 0 hh = '' for i in range(256): if (self.k & (1 << i)) != 0: ss = self.s[x:x + 40] hh += ss[0:32] v += hex_to_int(ss[32:40]) x += 40 try: _hash = Hash(skip_string + hh) except: _hash = None if x: assert self.k != 0 return _hash, v
def get_node(self, key): s = self.db_utxo.get(key) if s is None: return #print "get node", key.encode('hex'), len(key), s.encode('hex') k = int(s[0:32].encode('hex'), 16) s = s[32:] d = {} for i in range(256): if k % 2 == 1: _hash = s[0:32] value = hex_to_int(s[32:40]) d[chr(i)] = (_hash, value) s = s[40:] k = k / 2 #cache return d
def get_node(self, key): s = self.db_utxo.get(key) if s is None: return #print "get node", key.encode('hex'), len(key), s.encode('hex') k = int(s[0:32].encode('hex'), 16) s = s[32:] d = {} for i in range(256): if k % 2 == 1: _hash = s[0:32] value = hex_to_int(s[32:40]) d[chr(i)] = (_hash, value) s = s[40:] k = k/2 #cache return d
def decode_answer(self, cmd, answer): # this will receive only valid answers value = None unit = None payload = self.extract_payload(cmd, answer) if cmd == "0100": value = payload elif cmd == "0101": mil_state = [] num_dtcs = [] supported_tests = [] while 1: if len(payload) >= 8: # index = string.find(test_pattern,'4101') payload_databyte_1A = payload[0] payload_databyte_2A = payload[1] code = utils.hex_to_bin(payload_databyte_1A)[0] if code: mil_state.append("ON") else: mil_state.append("OFF") partial1 = str(utils.hex_to_bin(payload_databyte_1A[0])) partial2 = str(utils.hex_to_bin(payload_databyte_2A)) num_dtcs.append(str(int(partial1[1:] + partial2, 2))) tests = "" for i in range(2, 6): tests = tests + utils.hex_to_bin(payload[i]) supported_tests.append(tests) try: payload = payload[16:] # jump ahead checksum and headers of next frame if payload[0:4] != "4101": # verify answer of next frame break else: payload = payload[4:] except IndexError: break value = [mil_state, num_dtcs, supported_tests] elif cmd == "0102": value = self.decode_dtc(payload) elif cmd == "0103": # OL: open loop. CL: closed loop. description = { "00000000": "Wrong state", "00000001": "OL", "00000010": "CL", "00000100": "OL-Drive", "00001000": "OL-Fault", "00010000": "CL-Fault", "0010000": "ISO Reserved", "01000000": "ISO Reserved", "10000000": "ISO Reserved", } fuel_system1_status = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1]) fuel_system2_status = utils.hex_to_bin(payload[2]) + utils.hex_to_bin(payload[3]) try: value = [description[fuel_system1_status], description[fuel_system2_status]] except KeyError: value = "Unknown" elif cmd in ["0104", "012F", "0152"]: code = utils.hex_to_int(payload) value = code * 100.0 / 255.0 unit = "Percent scale" elif cmd == "0105" or cmd == "010F": code = utils.hex_to_int(payload) value = code - 40 unit = "Degrees Celsius" elif cmd in ["0106", "0107", "0108", "0109"]: code = utils.hex_to_int(payload) value = (code - 128.0) * 100.0 / 128 unit = "Percent scale" elif cmd == "010A": code = utils.hex_to_int(payload) value = code * 3 unit = "KPa" elif cmd == "010B": value = utils.hex_to_int(payload) unit = "KPa" elif cmd == "010C": code = utils.hex_to_int(payload) value = code / 4 unit = "RPM" elif cmd == "010D": value = utils.hex_to_int(payload) unit = "Km/h" elif cmd == "010E": code = utils.hex_to_int(payload) value = (code - 128) / 2.0 unit = "Degrees" elif cmd == "0110": code = utils.hex_to_int(payload) value = code * 0.01 unit = "g/s" elif cmd == "0111": code = utils.hex_to_int(payload) value = code * 0.01 unit = "Percent scale" elif cmd == "0112": description = { "00000000": "Wrong state", "00000001": "UPS", "00000010": "DNS", "00000100": "OFF", "00001000": "ISO Reserved", "00010000": "ISO Reserved", "0010000": "ISO Reserved", "01000000": "ISO Reserved", "10000000": "ISO Reserved", } air_status = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1]) try: value = description[air_status] except KeyError: value = "Unknown" elif cmd in ["0113", "011D"]: value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1]) elif cmd in ["0114", "0115", "0116", "0117", "0118", "0119", "011A", "011B"]: code = utils.hex_to_int(payload[0:2]) voltage = code * 0.005 code2 = utils.hex_to_int(payload[2:4]) stft = (code2 - 128.0) * 100.0 / 128 value = [voltage, stft] unit = ["V", "Percent scale"] elif cmd == "011C": description = { "01": "OBD-II", "02": "OBD", "03": "OBD and OBD-II", "04": "OBD-I", "05": "NO OBD", "06": "EOBD", "07": "EOBD and OBD-II", "08": "EOBD and OBD", "09": "EOBD, OBD and OBD-II", "0A": "JOBD", "0B": "JOBD and OBD-II", "0C": "JOBD and OBD", "0D": "JOBD, EOBD and OBD-II", "0E": "EURO IV B1", "0F": "EURO V B2", "10": "EURO C", "11": "EMD", } try: value = description[payload] except KeyError: value = "Unknown" elif cmd == "011E": code = utils.hex_to_bin(payload[1])[3] if code: value = "ON" else: value = "OFF" elif cmd == "011F": code = utils.hex_to_int(payload) value = code / 60 unit = "min" elif cmd in ["0121", "0131"]: value = utils.hex_to_int(payload) unit = "Km" elif cmd in ["014D", "014E"]: value = utils.hex_to_int(payload) unit = "min" elif cmd == "0151": description = { "01": "GAS", "02": "METH", "03": "ETH", "04": "DSL", "05": "LPG", "06": "CNG", "07": "PROP", "08": "ELEC", "09": "BI_GAS", "0A": "BI_METH", "0B": "BI_ETH", "0C": "BI_LPG", "0D": "BI_CNG", "0E": "BI_PROP", "0F": "BI_ELEC", } try: value = description[payload] except KeyError: value = "Unknown" elif cmd in ["0901", "0903", "0905", "0909"]: value = utils.hex_to_int(payload) unit = "Messages" elif cmd in ["0902", "0904", "0906", "090A"]: matrix = [] while 1: if len(payload) >= 9: # if there is a compliant frame of response index = utils.hex_to_int(payload[0:2]) frame = binascii.unhexlify(payload[2:10]) matrix.append([index, frame]) else: break try: payload = payload[18:] # jump ahead checksum and headers of next frame if payload[0:4] not in ["4902", "4904", "4906", "490A"]: # verify answer of next frame break else: payload = payload[4:] except IndexError: break # now, order the values gotten if len(matrix) > 0: value = "" for i in range(len(matrix)): if matrix[i][0] == i: value = value + matrix[i][1] elif cmd in ["03", "07"]: value = [] while 1: if len(payload) >= 12: # if there is a compliant frame of dtcs k = 0 while k != 12: value_k = self.decode_dtc(payload[k : k + 4]) if value_k != None: value.append(value_k) k += 4 else: break try: payload = payload[20:] # jump ahead checksum and headers of next frame if payload[0:2] not in ["43", "47"]: # verify answer of next frame break else: payload = payload[2:] except IndexError: break elif cmd == "04": if payload == "44": value = True else: value = False return value, unit
def get_utxo_value(self, addr, txi): key = self.address_to_key(addr) leaf = key + txi s = self.db_utxo.get(leaf) value = hex_to_int(s[0:8]) return value
def apply_background_filter(background_filter, res_x, res_y, background_path): """ Apply background filter with given background_filter parameters, desired x and y resolution and the path to background directory. Dependent on filter type, the background consists of one given single color, a random color, a desired specified image, a random image out of set standard background directory or a random image out of another given directory. :param background_filter: object containing background parameters :param res_x: x resolution of output background image :param res_y: y resolution of output background image :param background_path: path to set standard background directory :return: bg_img: created background image with desired resolution """ if background_filter.type == 0: # fixed hex color # background_filter.value has format "0x00000000" r_int = utils.hex_to_int(background_filter.value[2:4]) g_int = utils.hex_to_int(background_filter.value[4:6]) b_int = utils.hex_to_int(background_filter.value[6:8]) alpha_int = utils.hex_to_int(background_filter.value[8:10]) bg_img = img_processing.create_colored_background_img( res_x, res_y, r_int, g_int, b_int) logging.info( " => set background to: r: %s, g: %s, b: %s, alpha: %s" % (r_int, g_int, b_int, alpha_int)) elif background_filter.type == 1: # random hex color r_rand = random.randint(0, 255) g_rand = random.randint(0, 255) b_rand = random.randint(0, 255) bg_img = img_processing.create_colored_background_img( res_x, res_y, r_rand, g_rand, b_rand) logging.info(" => set background to random color \'(%s, %s, %s)\'" % (r_rand, g_rand, b_rand)) elif background_filter.type == 2: # background image path specified in background_filter.value bg_img_path = background_filter.value bg_img = img_processing.import_image(bg_img_path) bg_img = img_processing.resize_aspect_ratio_crop_image( bg_img, res_x, res_y) # resize image to the desired resolution logging.info(" => set background to \'%s\'" % bg_img_path) elif background_filter.type == 3: # random background out of backgrounds path bg_img_path_list = utils.list_directory(background_path, file_ext_list=['.jpg', '.png']) random_bg_idx = random.randint(0, len(bg_img_path_list) - 1) bg_img_filename = bg_img_path_list[random_bg_idx] bg_img_path = os.path.abspath(background_path + bg_img_filename) bg_img = img_processing.import_image(bg_img_path) bg_img = img_processing.resize_aspect_ratio_crop_image( bg_img, res_x, res_y) # resize image to the desired resolution logging.info( " => get random background from background path: \'%s\'" % bg_img_path) elif background_filter.type == 4: # random background image from another folder bg_img_path_list = utils.list_directory(background_filter.value, file_ext_list=['.jpg', '.png']) random_bg_idx = random.randint(0, len(bg_img_path_list) - 1) bg_img_filename = bg_img_path_list[random_bg_idx] bg_img_path = os.path.abspath(background_path + bg_img_filename) bg_img = img_processing.import_image(bg_img_path) bg_img = img_processing.resize_aspect_ratio_crop_image( bg_img, res_x, res_y) # resize image to the desired resolution logging.info(" => get random background from another path: \'%s\'" % bg_img_path) else: logging.error("ERROR: Unknown type (%s) of background filter" % background_filter.type) sys.exit(-1) return bg_img
def get(self, c): x = self.indexof(c) ss = self.s[x:x + 40] _hash = ss[0:32] value = hex_to_int(ss[32:40]) return _hash, value
def __getX1(self): self.__PCD_SK_x1 = utils.hex_to_int(bytearray(get_random_bytes(32))) PCD_PK_X1 = self.pointG * self.__PCD_SK_x1 return bytearray( bytearray([0x04]) + utils.long_to_bytearray(PCD_PK_X1.x()) + utils.long_to_bytearray(PCD_PK_X1.y()))
def decode_answer(cmd, answer): # TODO: migrate all of these functions to "elmdb.py" dictionary # TODO: use elmdb.ELMdb[cmd]['unit'] # this will receive only valid answers value = None unit = None payload = extract_payload(cmd, answer) if cmd in ['0100', '0120', '0140', '0160', '0180', '01A0', '01C0']: value = payload elif cmd == '0101': mil_state = [] num_dtcs = [] supported_tests = [] while 1: if len(payload) >= 8: # index = string.find(test_pattern,'4101') payload_databyte_1A = payload[0] payload_databyte_2A = payload[1] code = utils.hex_to_bin(payload_databyte_1A)[0] if code: mil_state.append('ON') else: mil_state.append('OFF') partial1 = str(utils.hex_to_bin(payload_databyte_1A[0])) partial2 = str(utils.hex_to_bin(payload_databyte_2A)) num_dtcs.append(str(int(partial1[1:] + partial2, 2))) tests = '' for i in range(2, 6): tests = tests + utils.hex_to_bin(payload[i]) supported_tests.append(tests) try: # jump ahead checksum and headers of next frame payload = payload[16:] if payload[0:4] != '4101': # verify answer of next frame break else: payload = payload[4:] except IndexError: break value = [mil_state, num_dtcs, supported_tests] elif cmd == '0102': value = decode_dtc(payload) elif cmd == '0103': #OL: open loop. CL: closed loop. description = { '00000000': 'Wrong state', '00000001': 'OL', '00000010': 'CL', '00000100': 'OL-Drive', '00001000': 'OL-Fault', '00010000': 'CL-Fault', '0010000': 'ISO Reserved', '01000000': 'ISO Reserved', '10000000': 'ISO Reserved' } fuel_system1_status = utils.hex_to_bin(payload[0]) + \ utils.hex_to_bin(payload[1]) fuel_system2_status = utils.hex_to_bin(payload[2]) + \ utils.hex_to_bin(payload[3]) try: value = [ description[fuel_system1_status], description[fuel_system2_status] ] except KeyError: value = 'Unknown' elif cmd in ['0104', '012F', '0152']: code = utils.hex_to_int(payload) value = code * 100.0 / 255.0 unit = 'Percent scale' elif cmd == '0105' or cmd == '010F': code = utils.hex_to_int(payload) value = code - 40 unit = 'Degrees Celsius' elif cmd in ['0106', '0107', '0108', '0109']: code = utils.hex_to_int(payload) value = (code - 128.0) * 100.0 / 128 unit = 'Percent scale' elif cmd == '010A': code = utils.hex_to_int(payload) value = code * 3 unit = 'KPa' elif cmd == '010B': value = utils.hex_to_int(payload) unit = 'KPa' elif cmd == '010C': code = utils.hex_to_int(payload) value = code / 4 unit = 'RPM' elif cmd == '010D': value = utils.hex_to_int(payload) unit = 'Km/h' elif cmd == '010E': code = utils.hex_to_int(payload) value = (code - 128) / 2.0 unit = 'Degrees' elif cmd == '0110': code = utils.hex_to_int(payload) value = code * 0.01 unit = 'g/s' elif cmd == '0111': code = utils.hex_to_int(payload) value = code * 0.01 unit = 'Percent scale' elif cmd == '0112': description = { '00000000': 'Wrong state', '00000001': 'UPS', '00000010': 'DNS', '00000100': 'OFF', '00001000': 'ISO Reserved', '00010000': 'ISO Reserved', '0010000': 'ISO Reserved', '01000000': 'ISO Reserved', '10000000': 'ISO Reserved' } air_status = utils.hex_to_bin(payload[0]) + \ utils.hex_to_bin(payload[1]) try: value = description[air_status] except KeyError: value = 'Unknown' elif cmd in ['0113', '011D']: value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1]) elif cmd in [ '0114', '0115', '0116', '0117', '0118', '0119', '011A', '011B' ]: code = utils.hex_to_int(payload[0:2]) voltage = code * 0.005 code2 = utils.hex_to_int(payload[2:4]) stft = (code2 - 128.0) * 100.0 / 128 value = [voltage, stft] unit = ['V', 'Percent scale'] elif cmd == '011C': description = { '01': 'OBD-II', '02': 'OBD', '03': 'OBD and OBD-II', '04': 'OBD-I', '05': 'NO OBD', '06': 'EOBD', '07': 'EOBD and OBD-II', '08': 'EOBD and OBD', '09': 'EOBD, OBD and OBD-II', '0A': 'JOBD', '0B': 'JOBD and OBD-II', '0C': 'JOBD and OBD', '0D': 'JOBD, EOBD and OBD-II', '0E': 'EURO IV B1', '0F': 'EURO V B2', '10': 'EURO C', '11': 'EMD' } try: value = description[payload] except KeyError: value = 'Unknown' elif cmd == '011E': code = utils.hex_to_bin(payload[1])[3] if code: value = 'ON' else: value = 'OFF' elif cmd == '011F': code = utils.hex_to_int(payload) value = code / 60 unit = 'min' elif cmd in ['0121', '0131']: value = utils.hex_to_int(payload) unit = 'Km' elif cmd in ['014D', '014E']: value = utils.hex_to_int(payload) unit = 'min' elif cmd == '0151': description = { '01': 'GAS', '02': 'METH', '03': 'ETH', '04': 'DSL', '05': 'LPG', '06': 'CNG', '07': 'PROP', '08': 'ELEC', '09': 'BI_GAS', '0A': 'BI_METH', '0B': 'BI_ETH', '0C': 'BI_LPG', '0D': 'BI_CNG', '0E': 'BI_PROP', '0F': 'BI_ELEC', } try: value = description[payload] except KeyError: value = 'Unknown' elif cmd in ['0901', '0903', '0905', '0909']: value = utils.hex_to_int(payload) unit = 'Messages' elif cmd in ['0902', '0904', '0906', '090A']: matrix = [] while 1: # if there is a compliant frame of response if len(payload) >= 9: index = utils.hex_to_int(payload[0:2]) frame = binascii.unhexlify(payload[2:10]) matrix.append([index, frame]) else: break try: # jump ahead checksum and headers of next frame payload = payload[18:] # verify answer of next frame if payload[0:4] not in ['4902', '4904', '4906', '490A']: break else: payload = payload[4:] except IndexError: break # now, order the values gotten if len(matrix) > 0: value = '' for i in range(len(matrix)): if matrix[i][0] == i: value = value + matrix[i][1] elif cmd in ['03', '07']: value = [] while 1: # if there is a compliant frame of dtcs if len(payload) >= 12: k = 0 while k != 12: value_k = decode_dtc(payload[k:k + 4]) if value_k is not None: value.append(value_k) k += 4 else: break try: # jump ahead checksum and headers of next frame payload = payload[20:] # verify answer of next frame if payload[0:2] not in ['43', '47']: break else: payload = payload[2:] except IndexError: break elif cmd == '04': if payload == '44': value = True else: value = False return value, unit
def decode_answer(cmd, answer): # TODO: migrate all of these functions to "elmdb.py" dictionary # TODO: use elmdb.ELMdb[cmd]['unit'] # this will receive only valid answers value = None unit = None payload = extract_payload(cmd, answer) if cmd in ['0100', '0120', '0140', '0160', '0180', '01A0', '01C0']: value = payload elif cmd == '0101': mil_state = [] num_dtcs = [] supported_tests = [] while 1: if len(payload) >= 8: # index = string.find(test_pattern,'4101') payload_databyte_1A = payload[0] payload_databyte_2A = payload[1] code = utils.hex_to_bin(payload_databyte_1A)[0] if code: mil_state.append('ON') else: mil_state.append('OFF') partial1 = str(utils.hex_to_bin(payload_databyte_1A[0])) partial2 = str(utils.hex_to_bin(payload_databyte_2A)) num_dtcs.append(str(int(partial1[1:] + partial2, 2))) tests = '' for i in range(2, 6): tests = tests + utils.hex_to_bin(payload[i]) supported_tests.append(tests) try: # jump ahead checksum and headers of next frame payload = payload[16:] if payload[0:4] != '4101': # verify answer of next frame break else: payload = payload[4:] except IndexError: break value = [mil_state, num_dtcs, supported_tests] elif cmd == '0102': value = decode_dtc(payload) elif cmd == '0103': #OL: open loop. CL: closed loop. description = { '00000000': 'Wrong state', '00000001': 'OL', '00000010': 'CL', '00000100': 'OL-Drive', '00001000': 'OL-Fault', '00010000': 'CL-Fault', '0010000': 'ISO Reserved', '01000000': 'ISO Reserved', '10000000': 'ISO Reserved' } fuel_system1_status = utils.hex_to_bin(payload[0]) + \ utils.hex_to_bin(payload[1]) fuel_system2_status = utils.hex_to_bin(payload[2]) + \ utils.hex_to_bin(payload[3]) try: value = [description[fuel_system1_status], description[fuel_system2_status]] except KeyError: value = 'Unknown' elif cmd in ['0104', '012F', '0152']: code = utils.hex_to_int(payload) value = code * 100.0 / 255.0 unit = 'Percent scale' elif cmd == '0105' or cmd == '010F': code = utils.hex_to_int(payload) value = code - 40 unit = 'Degrees Celsius' elif cmd in ['0106', '0107', '0108', '0109']: code = utils.hex_to_int(payload) value = (code - 128.0) * 100.0 / 128 unit = 'Percent scale' elif cmd == '010A': code = utils.hex_to_int(payload) value = code * 3 unit = 'KPa' elif cmd == '010B': value = utils.hex_to_int(payload) unit = 'KPa' elif cmd == '010C': code = utils.hex_to_int(payload) value = code / 4 unit = 'RPM' elif cmd == '010D': value = utils.hex_to_int(payload) unit = 'Km/h' elif cmd == '010E': code = utils.hex_to_int(payload) value = (code - 128) / 2.0 unit = 'Degrees' elif cmd == '0110': code = utils.hex_to_int(payload) value = code * 0.01 unit = 'g/s' elif cmd == '0111': code = utils.hex_to_int(payload) value = code * 0.01 unit = 'Percent scale' elif cmd == '0112': description = { '00000000': 'Wrong state', '00000001': 'UPS', '00000010': 'DNS', '00000100': 'OFF', '00001000': 'ISO Reserved', '00010000': 'ISO Reserved', '0010000': 'ISO Reserved', '01000000': 'ISO Reserved', '10000000': 'ISO Reserved' } air_status = utils.hex_to_bin(payload[0]) + \ utils.hex_to_bin(payload[1]) try: value = description[air_status] except KeyError: value = 'Unknown' elif cmd in ['0113', '011D']: value = utils.hex_to_bin(payload[0]) + utils.hex_to_bin(payload[1]) elif cmd in ['0114', '0115', '0116', '0117', '0118', '0119', '011A', '011B']: code = utils.hex_to_int(payload[0:2]) voltage = code * 0.005 code2 = utils.hex_to_int(payload[2:4]) stft = (code2 - 128.0) * 100.0 / 128 value = [voltage, stft] unit = ['V', 'Percent scale'] elif cmd == '011C': description = { '01': 'OBD-II', '02': 'OBD', '03': 'OBD and OBD-II', '04': 'OBD-I', '05': 'NO OBD', '06': 'EOBD', '07': 'EOBD and OBD-II', '08': 'EOBD and OBD', '09': 'EOBD, OBD and OBD-II', '0A': 'JOBD', '0B': 'JOBD and OBD-II', '0C': 'JOBD and OBD', '0D': 'JOBD, EOBD and OBD-II', '0E': 'EURO IV B1', '0F': 'EURO V B2', '10': 'EURO C', '11': 'EMD' } try: value = description[payload] except KeyError: value = 'Unknown' elif cmd == '011E': code = utils.hex_to_bin(payload[1])[3] if code: value = 'ON' else: value = 'OFF' elif cmd == '011F': code = utils.hex_to_int(payload) value = code / 60 unit = 'min' elif cmd in ['0121', '0131']: value = utils.hex_to_int(payload) unit = 'Km' elif cmd in ['014D', '014E']: value = utils.hex_to_int(payload) unit = 'min' elif cmd == '0151': description = { '01': 'GAS', '02': 'METH', '03': 'ETH', '04': 'DSL', '05': 'LPG', '06': 'CNG', '07': 'PROP', '08': 'ELEC', '09': 'BI_GAS', '0A': 'BI_METH', '0B': 'BI_ETH', '0C': 'BI_LPG', '0D': 'BI_CNG', '0E': 'BI_PROP', '0F': 'BI_ELEC', } try: value = description[payload] except KeyError: value = 'Unknown' elif cmd in ['0901', '0903', '0905', '0909']: value = utils.hex_to_int(payload) unit = 'Messages' elif cmd in ['0902', '0904', '0906', '090A']: matrix = [] while 1: # if there is a compliant frame of response if len(payload) >= 9: index = utils.hex_to_int(payload[0:2]) frame = binascii.unhexlify(payload[2:10]) matrix.append([index, frame]) else: break try: # jump ahead checksum and headers of next frame payload = payload[18:] # verify answer of next frame if payload[0:4] not in ['4902', '4904', '4906', '490A']: break else: payload = payload[4:] except IndexError: break # now, order the values gotten if len(matrix) > 0: value = '' for i in range(len(matrix)): if matrix[i][0] == i: value = value + matrix[i][1] elif cmd in ['03', '07']: value = [] while 1: # if there is a compliant frame of dtcs if len(payload) >= 12: k = 0 while k != 12: value_k = decode_dtc(payload[k:k+4]) if value_k is not None: value.append(value_k) k += 4 else: break try: # jump ahead checksum and headers of next frame payload = payload[20:] # verify answer of next frame if payload[0:2] not in ['43', '47']: break else: payload = payload[2:] except IndexError: break elif cmd == '04': if payload == '44': value = True else: value = False return value, unit
def get(self, c): x = self.indexof(c) ss = self.s[x:x+40] _hash = ss[0:32] value = hex_to_int(ss[32:40]) return _hash, value
def validate_receipt(self, receipt, op_return_hex, certificate_hash, issuer_identifier='', testnet=False): # check context and hash type if (receipt['@context'].lower() != CHAINPOINT_CONTEXT): return False, "wrong chainpoint context" if (receipt['type'] not in CHAINPOINT_HASH_TYPES.values()): return False, "type not in CHAINPOINT_HASH_TYPES" target_hash = receipt['targetHash'] merkle_root = receipt['merkleRoot'] proof = receipt['proof'] # validate actual hash if target_hash.lower() != certificate_hash.lower(): return False, "certificate hash is different than the one in receipt" # validate merkle proof if (not self.validate_proof(proof, target_hash, merkle_root)): return False, "certificate's hash is not in merkle root" txid = self.get_txid_from_receipt(receipt) # validate anchor #op_return_hex = network_utils.get_op_return_hex_from_blockchain(txid, testnet) # ignore issuer_identifier for now (it is string in CRED but used to be # hex so we need a smart way to get it) -- TODO: obsolete it !!! #issuer_id_hex = utils.text_to_hex(issuer_identifier) # if op_return starts with CRED it is using the meta-protocol op_dict = cred_protocol.parse_op_return_hex(op_return_hex) if op_dict: version_hex = op_dict['version'] command_hex = op_dict['cmd'] # could check if it is equal to issuer_id_hex issuer_hex = op_dict['data']['issuer_identifier'] # get merkle root hash_hex = op_dict['data']['merkle_root'] # if issue with expiry get expiry date if command_hex == cred_protocol.hex_op('op_issue_abs_expiry'): expiry_hex = op_return_hex[96:116] else: expiry_hex = None #print(version_hex) #print(command_hex) #print(issuer_hex) #print(hash_hex) #print(merkle_root.lower()) # otherwise op_return should be fixed to 7 bytes or 14 hex chars (old prefix method) else: ignore_hex_chars = 14 hash_hex = op_return_hex[ignore_hex_chars:] if (not merkle_root.lower() == hash_hex.lower()): return False, "certificate's merkle root is different than the one in the blockchain" # only for CRED protocol certificates check expiration date if # issued with expiry date if op_dict and expiry_hex: expiry = utils.hex_to_int(expiry_hex) if expiry > int(time.time()): return True, "valid until: " + str(expiry) else: return False, "certificate expired at: " + str(expiry) return True, None