#!/usr/bin/env python3 # ----------------------------------- UPSCALE VERIFY ----------------------------------- # ---------------- UP-SCALES.COM OFFLINE CHECK OF A RECEIVER DATA FOLDER (PYTHON) ------- # -------------------------------------------------------------------------------------- # CHECKS THE FOLDER OF upscale-receiver.py / .php / -node.js AGAIN, BY ITSELF AND OFFLINE: # EVERY HASH CHAIN, EVERY SEAL OF THE SCALE, EVERY CHAIN CHECKPOINT - WITH NOTHING BUT THE # STORED EVENTS AND THE PUBLIC UP↑SCALE LICENCE KEYS (NO APP, NO SCALE, NO NETWORK). # -------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # -------------------------------------------------------------------------------------- # WEBHOOK EXPORT: https://up-scales.com/manual.html#WiFiWebhook # LIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding # ALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples # -------------------------------------------------------------------------------------- # (C) Johann Anderson, 2025-2026 http://farm23.es # -------------------------------------------------------------------------------------- # MIT License - Copyright (c) 2025-2026 Johann Anderson # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to the following # conditions: The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # -------------------------------------------------------------------------------------- # # This script will: # Read every event of the data folder (/events//.jsonl) - # it never writes into the folder. # Rebuild every hash chain per scale: the activity log, the LEGAL MODE store and the # sales log, from the raw entries alone (the H in the events is only compared). # Find the same id with other content, and two different entries with one number # (CONFLICT). # Check every seal of the scale (events "sealed", and the seal inside a sealed JSON / # HTML file the app sent): the ECDSA signature of the scale, its certificate with # the public UP-SCALE licence keys (key confirmed by UP-SCALE), the Device ID, the # SHA-256; a scale without a certificate: every seal against its first key. # Check every chain checkpoint (seal kind 4: activity + sales, kind 5: LEGAL MODE # store) against the rebuilt chain, and show which entries its signature covers. # Pair every sale / print of the balance with a LEGAL MODE number ("UP-000123") with # its LEGAL MODE entry (sale id, grams / value, time): linked, MISMATCH, waiting, # entry missing - and list the LEGAL MODE entries of a sale whose sale is not here. # Print per scale + kind: first...last, gaps, broken links, conflicts, the ranges # covered by a signed checkpoint and what came after the newest one (not covered # yet). Exit code 0 only when nothing is broken, conflicting, badly sealed or a # MISMATCH (gaps and waiting pairs alone: 0), 1 otherwise, 2 for a wrong call. # # -------------------------------------------------------------------------------------- # 1st: What you need: # -------------------------------------------------------------------------------------- # # 1.) Python 3.8 or newer. The check of the seals needs the package "cryptography": # pip install cryptography (Debian / Ubuntu: apt install python3-cryptography) # Without it the chains are still checked and every seal is "not checked". # 2.) The data folder of the receiver (a copy is fine, e.g. from your backup): # # python3 upscale-verify.py /srv/upscale-data # python3 upscale-verify.py /srv/upscale-data --device a1b2c3d4e5f6 (one scale) # python3 upscale-verify.py /srv/upscale-data --all (every number) # # What a result means: # BROKEN the entry does not give the H the chain says (it, or the one before it, # was changed) - or a checkpoint signed another H than the entries give # CONFLICT the same id came with other content / two entries with the same number # MISMATCH a sale / print and its LEGAL MODE entry say different things # gap numbers that never came (ask the scale: {"get":"activity","since":N}) # signed every entry in the range is covered by a seal of the scale: its chain # links up to the H the scale signed (a later checkpoint covers the older # entries too, as long as the chain links) # not covered yet entries after the newest checkpoint (the next one covers them) # A seal shows that the data is unchanged since the scale signed it, and which scale. # -------------------------------------------------------------------------------------- import base64, glob, hashlib, json, os, re, struct, sys try: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature except ImportError: ec = None # ---------- the public UP-SCALE licence keys (the seal certificates are signed with them) ---------- LICENCE_KEYS = {1: '04aaf58d81d222eacd3d696a5d6cd48e6169303c7677d29f2c8319ca1961fa0598e04759ffbac18c01525542c9bcb1c9dc8fd091442bfcaa96688c9ed85f466f6b', 2: '0459765607ee8d42b4ed481b72285684a5c0063cbcf17adc02320a57957f30bc308186c7f60c9a5bc9f1b7adbeeec8543362396ea2c199147036ada9d925bd6941'} LICENCE_KEYS_REAL = dict(LICENCE_KEYS) # (tests only: UPSCALE_TEST_LICENCE_KEY=<130 hex: 04 | x | y> takes the place of both keys - never for real data) if re.fullmatch(r'04[0-9a-fA-F]{128}', os.environ.get('UPSCALE_TEST_LICENCE_KEY') or ''): LICENCE_KEYS = {1: os.environ['UPSCALE_TEST_LICENCE_KEY'].lower(), 2: os.environ['UPSCALE_TEST_LICENCE_KEY'].lower()} SEAL_KINDS = {1: 'report', 2: 'file', 3: 'signature', 4: 'chain_checkpoint', 5: 'legal_store'} SEAL_GOOD = ('certified', 'same_key', 'first_key') SEAL_SAY = {'certified': 'key confirmed by UP-SCALE', 'same_key': 'the same key (no certificate)', 'first_key': 'the first key (no certificate)', 'key_changed': 'ANOTHER KEY (no certificate)', 'bad': 'BAD', 'not_checked': 'not checked'} # ---------- the chains (the same rules as upscale-receiver.py) ---------- # activity: H = SHA-256(H before | seq as uint32 little-endian | the entry, 16 bytes); H before seq 0 = 32 zero bytes # legal: H = SHA-256(H before | the entry, 48 bytes); H before number 1 = 32 zero bytes # sales: chain = the first 8 bytes of SHA-256(chain before | the record without its last 8 bytes | its alibi bytes, if any), the # chain is the last 8 bytes of the record itself; before seq 1 = 8 zero bytes def hex_or_b64(v, src, size=0): v = str(v or '') is_hex = len(v) % 2 == 0 and re.fullmatch(r'[0-9a-fA-F]*', v) is not None try: if is_hex and (len(v) == 2 * size if size else src != 'scale'): return bytes.fromhex(v) return base64.b64decode(v, validate=True) except ValueError: return b'' def entry_number(v): """A number of a chain entry or a seal field: an integer 0...4294967295 (a JSON number or a text of digits) | None.""" if isinstance(v, bool): return None if isinstance(v, float) and v.is_integer(): v = int(v) elif isinstance(v, str) and re.fullmatch(r'[0-9]{1,10}', v): v = int(v) return v if type(v) is int and 0 <= v <= 0xFFFFFFFF else None def entry_parts(ev): """A chain entry -> dict | None (no chain event) | 'no number' (the number is no integer 0...4294967295).""" typ, d = ev.get('type'), ev.get('data') if typ not in ('activity', 'legal', 'sales') or not isinstance(d, dict): return None src = ev.get('src') num = entry_number(d.get('seq', d.get('number', d.get('no')))) if num is None: return 'no number' hlen = 16 if typ == 'sales' else 64 h = '' for k in ('chain', 'h'): v = d.get(k) if isinstance(v, str) and len(v) == hlen and re.fullmatch(r'[0-9a-fA-F]+', v): h = v.lower() break hb = d['hb'].lower() if isinstance(d.get('hb'), str) and len(d['hb']) == hlen and re.fullmatch(r'[0-9a-fA-F]+', d['hb']) else '' alibi, no_alibi = b'', False if typ == 'sales': raw = hex_or_b64(d.get('raw'), src) rawok = len(raw) > 8 if rawok: h = raw[-8:].hex() alibi = hex_or_b64(d.get('alibi_raw'), src) no_alibi = not alibi and bool(d.get('alibi')) else: size = 16 if typ == 'activity' else 48 raw = hex_or_b64(d.get('raw'), src, size) rawok = len(raw) == size return {'dev': str(ev.get('device') or d.get('device') or '').lower(), 'type': typ, 'num': num, 'raw': raw, 'rawok': rawok, 'h': h, 'hb': hb, 'alibi': alibi, 'no_alibi': no_alibi} def chain_link(typ, before, num, raw, alibi=b''): if typ == 'sales': return hashlib.sha256(bytes.fromhex(before) + raw[:-8] + alibi).hexdigest()[:16] return hashlib.sha256(bytes.fromhex(before) + (num.to_bytes(4, 'little') if typ == 'activity' else b'') + raw).hexdigest() def chain_start(typ, num): if typ in ('activity', 'legal') and num == (0 if typ == 'activity' else 1): return '00' * 32 if typ == 'sales' and num == 1: return '00' * 8 return '' # ---------- the seals ---------- def ecdsa_ok(pk, data, sig): if ec is None: return None try: key = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), b'\x04' + pk) key.verify(encode_dss_signature(int.from_bytes(sig[:32], 'big'), int.from_bytes(sig[32:], 'big')), data, ec.ECDSA(hashes.SHA256())) return True except Exception: return False def unhex(v): v = str(v or '') return bytes.fromhex(v) if len(v) % 2 == 0 and re.fullmatch(r'[0-9a-fA-F]*', v) else b'' def seal_parse(seal): if len(seal) != 144 or seal[0] != 1: return None u32 = lambda at: int.from_bytes(seal[at:at + 4], 'little') return {'kind': seal[1], 'device': seal[2:8].hex(), 'seq': u32(8), 'time': u32(12), 'number': u32(16), 'user': seal[20], 'how': seal[21], 'sales_upto': u32(22), 'sales_chain': seal[26:34].hex(), 'hash': seal[42:74].hex(), 'oldest': u32(74)} def seal_verify(seal, cert, pk): """-> (result, problems, parsed seal, certificate id, public key hex); result: certified | signed (a good signature, no certificate - the key rule comes in check()) | bad | not_checked.""" p = seal_parse(seal) if not p: return 'bad', ['format'], None, '', '' why, certified, cert_id = [], False, '' if len(pk) == 65 and pk[0] == 4: pk = pk[1:] if cert: if len(cert) != 144 or cert[0] not in LICENCE_KEYS: why.append('cert_format') else: cert_id = cert[80:84].hex().upper() ok = ecdsa_ok(bytes.fromhex(LICENCE_KEYS[cert[0]])[1:], cert[:80], cert[80:]) if ok is False: why.append('cert_bad') elif cert[1] != 1 or cert[2:8].hex() != p['device']: why.append('cert_other') certified = ok is True and not why pk = cert[16:80] if len(pk) != 64: return 'bad', why + ['nokey'], p, cert_id, '' ok = ecdsa_ok(pk, seal[:80], seal[80:]) if ok is None: return ('bad' if why else 'not_checked'), why, p, cert_id, pk.hex() if not ok: why.append('signature') if why: return 'bad', why, p, cert_id, pk.hex() return ('certified' if certified else 'signed'), [], p, cert_id, pk.hex() def file_seal_parts(text): """The seal inside a sealed JSON file / HTML report and the text it seals -> (seal, cert, pk, plain) | None.""" m = re.search(r',\n "seal": (\{[^\n]*\})\n\}\s*$', text) tag = re.search(r'
]*)>[\s\S]*?
', text) if m: try: field = json.loads(m.group(1)) except ValueError: return None return str(field.get('seal') or ''), str(field.get('cert') or ''), str(field.get('pk') or ''), text[:m.start()] + '\n}' if tag: attr = lambda k: (re.search('data-' + k + '="([0-9a-f]*)"', tag.group(1)) or [None, ''])[1] code = re.search(r'[0-9a-f]{16}', text) block = re.search(r'
[\s\S]*?
', text) plain = text if code: plain = plain.replace(code.group(0), '0000000000000000', 1) if block: plain = plain.replace(block.group(0), '
', 1) plain = plain.replace(tag.group(0), '
', 1) return attr('seal'), attr('cert'), attr('pk'), plain return None # ---------- the pair check: a sale / a print of the balance <-> its LEGAL MODE entry (as the receivers) ---------- # sales record (76 bytes): [0-3] sale id | [4-6] seconds of the day | [11-14] grams (float) | [65-66] minutes east of UTC (0x7FFF: not # known); its alibi bytes "UP-000123" = the number of its entry | LEGAL MODE entry (48 bytes): [4-7] time | [8] kind (1 sale, 8 print) # | [40-43] the value used (float g) | [44-47] kind 1: the sale id | print event: data.legal "UP-000123", raw = its activity entry # ([0-3] time, [8-11] the value) PAIR_SALE_S = 300 # the time of the sale (the clock of the app) against the time of the entry (the clock of the scale) PAIR_PRINT_S = 10 # the time of the print line against the entry (both the clock of the scale) def legal_no(text): m = re.fullmatch(r'UP-([0-9]{1,10})', text) if isinstance(text, str) else None return entry_number(m.group(1)) if m else None def day_epoch(day, secs, tz): """The epoch of a sale: its day ("YYYY-MM-DD"), the seconds of the day, minutes east of UTC (as sales_local_epoch of the scale).""" m = re.fullmatch(r'([0-9]{4})-([0-9]{2})-([0-9]{2})', day) if isinstance(day, str) else None if not m: return None y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3)) if mo <= 2: y -= 1 era = y // 400 yoe = y - era * 400 doy = (153 * (mo + (-3 if mo > 2 else 9)) + 2) // 5 + d - 1 doe = yoe * 365 + yoe // 4 - yoe // 100 + doy return (era * 146097 + doe - 719468) * 86400 + secs - tz * 60 def f32(b): return struct.unpack(' dict | None.""" d = ev.get('data') if isinstance(p, dict) and p['type'] == 'sales': raw = p['raw'] n = legal_no(p['alibi'].decode('latin-1') if p['alibi'] else d.get('alibi')) if len(raw) != 76 or n is None: return None tz = int.from_bytes(raw[65:67], 'little', signed=True) secs = raw[4] | (raw[5] << 8) | (raw[6] << 16) return {'what': 'sale', 'num': p['num'], 'n': n, 'ref': int.from_bytes(raw[0:4], 'little'), 'v': raw[11:15].hex(), 'time': day_epoch(d.get('day'), secs, tz) if tz != 0x7FFF else None} if ev.get('type') == 'print' and isinstance(d, dict): n, raw = legal_no(d.get('legal')), hex_or_b64(d.get('raw'), ev.get('src'), 16) if n is None or len(raw) != 16: return None return {'what': 'print', 'num': entry_number(d.get('seq')), 'n': n, 'v': raw[8:12].hex(), 'time': int.from_bytes(raw[0:4], 'little')} return None def pair_compare(info, raw): """A sale / print against its entry -> (the fields that differ, a note).""" sale, why = info['what'] == 'sale', [] if raw[8] != (1 if sale else 8): why.append('kind') if sale and int.from_bytes(raw[44:48], 'little') != info['ref']: why.append('sale_id') a, b = f32(raw[40:44]), f32(bytes.fromhex(info['v'])) if not (a == b or (sale and b == 0 and a <= 0)): # (a sale books 0 for a value below 0) why.append('grams' if sale else 'value') if info['time'] is None: return why, ' (time not compared)' if abs(int.from_bytes(raw[4:8], 'little') - info['time']) > (PAIR_SALE_S if sale else PAIR_PRINT_S): why.append('time') return why, '' # ---------- a repeated id: the same content? (as the receivers) ---------- def canon(v): if isinstance(v, dict): return '{' + ','.join(json.dumps(str(k), ensure_ascii=False) + ':' + canon(v[k]) for k in sorted(v, key=str)) + '}' if isinstance(v, list): return '[' + ','.join(canon(x) for x in v) + ']' if v is True or v is False or v is None: return json.dumps(v) if isinstance(v, (int, float)): if v != v or v in (float('inf'), float('-inf')): return 'null' if float(v).is_integer() and abs(v) < 1e15: return str(int(v)) m, e = ('%.16e' % float(v)).split('e') return m + 'e' + str(int(e)) return json.dumps(str(v), ensure_ascii=False) def content_digest(ev): p = entry_parts(ev) if isinstance(p, dict) and p['rawok']: return hashlib.sha256(('%s|%d|' % (p['type'], p['num'])).encode() + p['raw']).hexdigest() d = ev.get('data') if ev.get('type') == 'sealed' and isinstance(d, dict) and len(unhex(d.get('seal'))) == 144: return hashlib.sha256(b'sealed|' + unhex(d['seal'])).hexdigest() return hashlib.sha256(canon({k: v for k, v in ev.items() if k not in ('sent_at', 'env', '_rx')}).encode('utf-8', 'surrogatepass')).hexdigest() # ---------- the check ---------- def ranges(nums, limit=12): """Numbers as 'a...b, c' (sorted, at most limit ranges).""" out, nums = [], sorted(set(nums)) for n in nums: if out and n == out[-1][1] + 1: out[-1][1] = n else: out.append([n, n]) text = ', '.join(('%d' % a) if a == b else ('%d...%d' % (a, b)) for a, b in out[:limit]) return text + (' ... (%d ranges)' % len(out) if len(out) > limit else '') if out else 'none' def utc(epoch): import time return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epoch)) if epoch else '-' def load(folder): """Every event of the folder in the order it came (the time received, then the file, then the line).""" rows = [] for path in sorted(glob.glob(os.path.join(folder, 'events', '*', '*.jsonl'))): with open(path, encoding='utf-8') as f: for n, line in enumerate(f): try: ev = json.loads(line) except ValueError: rows.append(('', path, n, None)) continue if isinstance(ev, dict): rows.append((str((ev.get('_rx') or {}).get('at') or ''), path, n, ev)) rows.sort(key=lambda r: (r[0], r[1], r[2])) return rows def arrival(ev): """The order seals are judged in: the time received, then the log seq.""" d = ev.get('data') if isinstance(ev.get('data'), dict) else {} return str((ev.get('_rx') or {}).get('at') or '') if isinstance(ev.get('_rx'), dict) else '', entry_number(d.get('log_seq')) or 0 def check(folder, only_dev='', show_all=False): rows = load(folder) problems = {'broken': 0, 'conflict': 0, 'seal': 0, 'unreadable': sum(1 for r in rows if r[3] is None), 'nonumber': 0} by_id, chains, seals, prints = {}, {}, [], [] for at, path, n, ev in rows: if ev is None or not isinstance(ev.get('id'), str): continue dev = str(ev.get('device') or '').lower() if only_dev and dev != only_dev: continue try: dg = content_digest(ev) p = entry_parts(ev) except Exception: problems['unreadable'] += 1 continue first = by_id.setdefault(ev['id'], dg) if first != dg: by_id[ev['id'] + '\n' + dg] = 'conflict' if p == 'no number': problems['nonumber'] += 1 elif p: p['ev'] = ev chains.setdefault((p['dev'], p['type']), {}).setdefault(p['num'], []).append(p) if ev.get('type') == 'print' and first == dg: prints.append(ev) d = ev.get('data') if ev.get('type') == 'sealed' and first == dg and isinstance(d, dict): seals.append(('event', ev, d.get('seal'), d.get('cert'), d.get('pk'), None)) if ev.get('type') in ('sealed_file', 'programs') and isinstance(d, dict) and d.get('content_base64'): try: parts = file_seal_parts(base64.b64decode(str(d['content_base64'])).decode('utf-8')) except ValueError: parts = None if parts and parts[0]: seals.append(('file', ev, parts[0], parts[1], parts[2], parts[3])) id_conflicts = sorted(k.split('\n')[0] for k, v in by_id.items() if v == 'conflict') # the chains, rebuilt from the raw entries in number order built = {} for (dev, typ), nums in sorted(chains.items()): st = {'H': {}, 'linked': {}, 'broken': [], 'conflict': [], 'noraw': [], 'nums': sorted(nums), 'chosen': {}} for num in st['nums']: versions = nums[num] start = st['H'].get(num - 1) or chain_start(typ, num) def link_of(v): b = start or v['hb'] return (b, chain_link(typ, b, num, v['raw'], v['alibi'])) if b and v['rawok'] and not v['no_alibi'] else (b, '') def next_follows(h): # (an entry after it with raw and its own chain H links to h) return any(n['rawok'] and not n['no_alibi'] and n['h'] and chain_link(typ, h, num + 1, n['raw'], n['alibi']) == n['h'] for n in nums.get(num + 1, [])) # the version checked: a raw one whose link computes and the entry after it follows, else the first raw one whose link # computes, else the first raw one, else the first one linking = [v for v in versions if link_of(v)[1] and (not v['h'] or v['h'] == link_of(v)[1])] p = next((v for v in linking if next_follows(link_of(v)[1])), None) or (linking[0] if linking else None) \ or next((v for v in versions if v['rawok'] and not v['no_alibi']), None) or next((v for v in versions if v['rawok']), versions[0]) before, calc = link_of(p) st['chosen'][num] = p h = calc if calc and (not p['h'] or p['h'] == calc) else p['h'] for v in versions: if v is p: continue if (v['rawok'] and v['raw'] != p['raw']) or (v['alibi'] and p['alibi'] and v['alibi'] != p['alibi']) or (not v['rawok'] and v['h'] and h and v['h'] != h): st['conflict'].append(num) break if calc and p['h'] and p['h'] != calc: st['broken'].append(num) st['H'][num] = p['h'] elif calc: st['H'][num] = calc st['linked'][num] = before elif h: st['H'][num] = h if not (p['rawok'] and not p['no_alibi']): st['noraw'].append(num) else: st['noraw'].append(num) built[(dev, typ)] = st # the seals: each one by itself; the key rule: a scale with a key confirmed by UP-SCALE - every seal without a certificate must have # one of those keys; without such a key - the first key seen cps, seal_rows, certified_pks, first_pk = {}, [], {}, {} checked = [] for kind, ev, seal, cert, pk, plain in sorted(seals, key=lambda x: arrival(x[1])): d, dev = ev['data'], str(ev.get('device') or '').lower() res, why, p, cert_id, key = seal_verify(unhex(seal), unhex(cert), unhex(pk)) if p: if dev and dev != 'unknown' and p['device'] != dev: why.append('device') if kind == 'event': for k, v in (('kind', p['kind']), ('log_seq', p['seq']), ('number', p['number'])): if k in d and entry_number(d[k]) != v: why.append(k) if p['kind'] in (1, 2, 3) and re.fullmatch(r'[0-9a-fA-F]{64}', str(d.get('sha256') or '')) and d['sha256'].lower() != p['hash']: why.append('hash') elif hashlib.sha256(plain.encode('utf-8')).hexdigest() != p['hash']: why.append('hash') if why: res = 'bad' if res == 'certified' and key not in certified_pks.setdefault(p['device'], []): certified_pks[p['device']].append(key) checked.append((kind, d, res, why, p, cert_id, key, dev)) for kind, d, res, why, p, cert_id, key, dev in checked: if res == 'signed': mine = certified_pks.get(p['device']) if mine: res = 'same_key' if key in mine else 'key_changed' elif p['device'] not in first_pk: first_pk[p['device']] = key res = 'first_key' else: res = 'same_key' if first_pk[p['device']] == key else 'key_changed' what = (SEAL_KINDS.get(p['kind'], 'kind %d' % p['kind']) if p else '?') if kind == 'event' else 'in file ' + str(d.get('file') or '?') seal_rows.append({'dev': p['device'] if p else dev, 'what': what, 'log': p['seq'] if p else '?', 'res': res, 'why': why, 'cert': cert_id}) if kind == 'event' and p and p['kind'] in (4, 5): heads = ([('activity', p['number'], p['hash'])] + ([('sales', p['sales_upto'], p['sales_chain'])] if p['sales_upto'] else [])) if p['kind'] == 4 else [('legal', p['number'], p['hash'])] for typ, upto, h in heads: take_checkpoint(built, cps, problems, p['device'], typ, upto, h, dict({'log_seq': p['seq'], 'time': p['time'], 'seal': res}, **({'oldest': p['oldest']} if p['kind'] == 5 else {}))) problems['seal'] = sum(1 for s in seal_rows if s['res'] in ('bad', 'key_changed')) pairs = pair_all(built, cps, prints, problems) report(folder, built, cps, seal_rows, certified_pks, id_conflicts, problems, show_all, pairs) bad = problems['broken'] + problems['conflict'] + problems['seal'] print('\nRESULT: %d broken, %d conflicts, %d bad seals / changed keys -> %s' % (problems['broken'], problems['conflict'], problems['seal'], 'OK' if not bad else 'NOT OK')) return 0 if not bad else 1 def covered(built, dev, typ, top): """The lowest entry covered from entry top downward (as the receivers).""" st = built.get((dev, typ)) if not st: return None low, k = None, top while k in st['linked'] and k not in st['broken']: low = k if chain_start(typ, k) or st['H'].get(k - 1) != st['linked'][k]: break k -= 1 return low def take_checkpoint(built, cps, problems, dev, typ, upto, h, info): """A checkpoint against the rebuilt chain - only a seal with a good key counts.""" st = built.get((dev, typ)) row = dict(info, typ=typ, upto=upto) if info['seal'] not in SEAL_GOOD: row['state'] = 'not checked (seal %s)' % info['seal'] elif not st or upto not in st['H']: row['state'] = 'not here' elif st['H'][upto] != h: row['state'] = 'DIFFERS' problems['broken'] += 1 else: row['state'] = 'signed' row['low'] = covered(built, dev, typ, upto) cps.setdefault((dev, typ), []).append(row) def gap_list(nums): """The missing numbers between the kept ones as [(first, last), ...] - never expanded.""" return [(a + 1, b - 1) for a, b in zip(nums, nums[1:]) if b > a + 1] def range_text(pairs, limit=12): text = ', '.join(('%d' % a) if a == b else ('%d...%d' % (a, b)) for a, b in pairs[:limit]) return text + (' ... (%d ranges)' % len(pairs) if len(pairs) > limit else '') def pair_all(built, cps, prints, problems): """Every sale / print with a LEGAL MODE number against the rebuilt LEGAL MODE chain -> {device: {linked, waiting, mismatch, missing, nosale}}.""" out = {} infos = [] for (dev, typ), st in built.items(): if typ == 'sales': for num in st['nums']: p = st['chosen'][num] info = pair_info(p['ev'], p) if info: infos.append((dev, info)) for ev in prints: info = pair_info(ev, None) if info: infos.append((str(ev.get('device') or '').lower(), info)) used = {} for dev, info in sorted(infos, key=lambda x: (x[0], x[1]['what'], x[1]['n'])): r = out.setdefault(dev, {'linked': 0, 'waiting': [], 'mismatch': [], 'missing': [], 'nosale': []}) legal = built.get((dev, 'legal')) or {'chosen': {}, 'broken': []} e = legal['chosen'].get(info['n']) good = [x for x in cps.get((dev, 'legal'), []) if x['state'] == 'signed'] oldest = max(good, key=lambda x: x['upto']).get('oldest') if good else None what = '%s %s / UP-%06d' % ('sales' if info['what'] == 'sale' else 'print', info['num'], info['n']) if e and e['rawok'] and info['n'] not in legal['broken']: if info['what'] == 'sale': used.setdefault(dev, set()).add(info['n']) why, note = pair_compare(info, e['raw']) if why: r['mismatch'].append('%s (%s)' % (what, ','.join(why))) problems['broken'] += 1 else: r['linked'] += 1 elif (e and info['n'] in legal['broken']) or (not e and type(oldest) is int and info['n'] < oldest): r['missing'].append(what) else: r['waiting'].append(what) for (dev, typ), st in built.items(): if typ == 'legal': for num in st['nums']: p = st['chosen'][num] if p['rawok'] and p['raw'][8] == 1 and num not in st['broken'] and num not in used.get(dev, set()): out.setdefault(dev, {'linked': 0, 'waiting': [], 'mismatch': [], 'missing': [], 'nosale': []})['nosale'].append(num) return out def report(folder, built, cps, seal_rows, certified_pks, id_conflicts, problems, show_all, pairs): # ---------- the report ---------- print('UP-SCALE verify: %s' % os.path.abspath(folder)) if ec is None: print('NOTE: the package "cryptography" is missing - the seals are NOT checked (pip install cryptography)') if LICENCE_KEYS[1] != LICENCE_KEYS_REAL[1]: print('NOTE: UPSCALE_TEST_LICENCE_KEY is set - a TEST licence key, not for real data') if problems['unreadable']: print('NOTE: %d line(s) are no JSON / not readable' % problems['unreadable']) if problems['nonumber']: print('NOTE: %d chain event(s) without a valid number (an integer 0...4294967295) - not checked' % problems['nonumber']) devices = sorted({k[0] for k in built} | {s['dev'] for s in seal_rows} | {k[0] for k in cps}) for dev in devices: print('\n' + (dev or '(no Device ID)')) for typ in ('activity', 'legal', 'sales'): st = built.get((dev, typ)) if not st: continue nums = st['nums'] gaps = gap_list(sorted(st['H'])) print(' %-9s %d...%d (%d entries)%s' % (typ, nums[0], nums[-1], len(nums), '' if nums[0] == (0 if typ == 'activity' else 1) else ' - the first ones are not here')) if st['broken']: print(' BROKEN: %s' % ranges(st['broken'])) problems['broken'] += len(st['broken']) if st['conflict']: print(' CONFLICT: %s (different entries with this number)' % ranges(st['conflict'])) problems['conflict'] += len(st['conflict']) if gaps: print(' gaps: %s (%d missing)' % (range_text(gaps), sum(b - a + 1 for a, b in gaps)) + (' (ask for them: {"get":"%s","since":%d})' % (typ, gaps[0][0]) if typ != 'sales' else '')) if st['noraw']: print(' not checked: %s (no raw entry / no alibi bytes)' % ranges(st['noraw'])) rows = cps.get((dev, typ), []) signed = [] for a, b in sorted((r['low'], r['upto']) for r in rows if r['state'] == 'signed' and r.get('low') is not None): if signed and a <= signed[-1][1] + 1: signed[-1][1] = max(signed[-1][1], b) else: signed.append([a, b]) good = [r for r in rows if r['state'] == 'signed'] if good: newest = max(good, key=lambda r: r['upto']) print(' signed: %s' % (range_text(signed) or 'none (the signed entries are not linked)')) print(' newest checkpoint: up to %d (seal log %s, %s, %s)' % (newest['upto'], newest['log_seq'], utc(newest['time']), SEAL_SAY[newest['seal']])) after = [n for n in nums if n > newest['upto']] print(' not covered yet: %s' % (ranges(after) if after else 'none')) elif nums: print(' signed: none (no checkpoint with a good seal)') for r in rows: if r['state'] != 'signed' or show_all: print(' checkpoint up to %d (seal log %s): %s' % (r['upto'], r['log_seq'], r['state'] + (' - BROKEN: the scale signed another H' if r['state'] == 'DIFFERS' else ''))) mine = [s for s in seal_rows if s['dev'] == dev] if mine: count = {} for s in mine: count[s['res']] = count.get(s['res'], 0) + 1 print(' seals: %d - %s' % (len(mine), ', '.join('%d %s' % (v, SEAL_SAY[k]) for k, v in sorted(count.items())))) for s in mine: if s['res'] in ('bad', 'key_changed') or show_all: print(' %s log %s: %s%s%s' % (s['what'], s['log'], SEAL_SAY[s['res']], (' (' + ', '.join(s['why']) + ')') if s['why'] else '', (' certificate ' + s['cert']) if s['cert'] and s['res'] == 'certified' else '')) pr = pairs.get(dev) if pr: print(' pairs: %d linked (a sale / print with its LEGAL MODE entry)' % pr['linked']) for k, t in (('mismatch', 'MISMATCH'), ('missing', 'entry missing'), ('waiting', 'waiting for the entry')): if pr[k]: print(' %s: %s%s' % (t, ', '.join(pr[k][:12]), ' ... (%d)' % len(pr[k]) if len(pr[k]) > 12 else '')) if pr['nosale']: print(' LEGAL MODE entries of a sale whose sale is not here: %s' % ranges(pr['nosale'])) if len(certified_pks.get(dev, [])) > 1: print(' note: %d keys of this scale, each confirmed by UP-SCALE' % len(certified_pks[dev])) if id_conflicts: print('\nCONFLICT - the same id with other content:') for i in id_conflicts[:50]: print(' ' + i) problems['conflict'] += len(id_conflicts) def main(argv): dev, args, i = '', [], 0 while i < len(argv): if argv[i] == '--device' and i + 1 < len(argv): dev, i = argv[i + 1].lower(), i + 2 continue if not argv[i].startswith('--'): args.append(argv[i]) i += 1 if len(args) != 1 or not os.path.isdir(os.path.join(args[0], 'events')): print('usage: python3 upscale-verify.py [--device ] [--all]', file=sys.stderr) return 2 return check(args[0], dev, '--all' in argv) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))