#!/usr/bin/env python3 # ---------------------------------- UPSCALE RECEIVER ---------------------------------- # --------------- UP-SCALES.COM WEBHOOK + LIMS FORWARDING RECEIVER (PYTHON) ------------ # -------------------------------------------------------------------------------------- # A RECEIVER FOR YOUR OWN SERVER: IT TAKES THE RECORDS OF YOUR UP↑SCALE SCALES - FROM THE # WEBHOOK EXPORT OF THE SCALE (THE SCALE POSTS BY ITSELF IN ITS WIFI NETWORK) AND FROM THE # LIMS / ELN FORWARDING OF THE APP (THE BROWSER POSTS) - AND KEEPS THEM AS JSON LINES. # -------------------------------------------------------------------------------------- # ^^^ 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: # Check every request with one of the three security modes of the scale: # 1 https + a token (Bearer, X-API-Key or ?token=) - also the mode of the app # 2 HMAC-signed (X-Upscale-Time / -Nonce / -Signature) - it signs its answer # 3 sealed envelope (AES-256-GCM) - it seals its answer and refuses a replayed n # Answer the preflight of the browser (CORS, OPTIONS) for the app. # Drop an event that comes twice (same "id") - and still acknowledge it. The same id # with other content: CONFLICT (in chain.log + receiver.log, kept as well). # Store every event as one JSON line: /events//.jsonl # Check the hash chains of "activity", "legal" and "sales" events, per scale: every # entry against the one before AND the one after it - also an entry that fills a # gap later. # Check every seal of the scale by itself (event "sealed", and the seal inside a sealed # JSON / HTML file the app sends): the ECDSA signature of the scale, its certificate # with the public UP-SCALE licence keys (key confirmed by UP-SCALE), the Device ID. # A scale without a certificate: its first key is noted, a changed key is reported. # Check the chain checkpoints (seal kind 4: the scale signs the head of its activity # log and of its sales log; kind 5: of the LEGAL MODE store) against the entries # here: "SIGNED up to N" = every entry up to N that links to it is covered by the # signature of the scale. # Pair a sale or a print of the balance that has a LEGAL MODE number ("UP-000123", # RS-232 dongles) with its LEGAL MODE entry: the sale id, the grams / the value # and the time must be the same (linked, MISMATCH, waiting, entry missing). # Answer {"ack": "", "ref": ""} - and requests for the scale. # Answer "stored" as an archive receiver: {"stored": {"type": "activity" | "legal", # "upto": N, "chain": ""}} - N = the newest entry up to which every entry # is written to the disk in one chain this script recomputed itself. The scale (and # the app with "free only what the receiver confirmed as saved") may then reuse the # space of those entries. Keeping these files safe (backup) is your job. # Answer the idle poll of the scale (GET ?device=...&poll=1, sealed: &n=..&t=..). # # -------------------------------------------------------------------------------------- # 1st: What you need: # -------------------------------------------------------------------------------------- # # 1.) Python 3.8 or newer - the standard library is enough for modes 1 and 2. # Mode 3 (sealed envelope) and the check of the seals need the package "cryptography": # pip install cryptography (Debian / Ubuntu: apt install python3-cryptography) # Without it, modes 1 and 2 work, every sealed request is refused (HTTP 500), the chains # are still checked and every seal is logged as "not checked". # 2.) https for mode 1 and for the app (browsers only post from the app to https): # put it behind your web server (nginx / Apache as a proxy to this port), or give it # a certificate itself: UPSCALE_CERT=/path/cert.pem UPSCALE_KEY=/path/key.pem # Modes 2 and 3 also work on plain http in your own network. # 3.) Your settings (environment variables, or change the defaults below): # UPSCALE_PORT the port (default 8080) # UPSCALE_MODES the modes this receiver takes, e.g. "1,2,3" or "3" # UPSCALE_TOKENS mode 1: the token(s), comma separated (the scale's secret with # the credential "Bearer token" / "X-API-Key" / "token in the # address", and the token of the app's LIMS forwarding) # UPSCALE_SECRET modes 2 + 3: the secret you typed into the webhook card # UPSCALE_DATA the folder for the events and the state files # UPSCALE_STORED "0" = no "stored" answers (the scale and the app then free their # entries as without this receiver) # 4.) In the app: LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: http(s)://:/, # the same security mode and the secret. Or Settings -> 🔗 LIMS / ELN FORWARDING: # the https address and the token (mode 1). # # UPSCALE_SECRET=my-secret UPSCALE_MODES=2,3 python3 upscale-receiver.py # # -------------------------------------------------------------------------------------- # What you get in the data folder: # -------------------------------------------------------------------------------------- # # events//.jsonl every event as it came, one line each, with "_rx" # added: at (time received), mode, chain (ok, filled, # broken, gap, first, same, conflict, no raw), seal # (certified = key confirmed by UP-SCALE, same_key, # first_key, key_changed, bad + seal_why, not_checked), # checkpoint ({"activity": "signed" | "waiting" | # "differs", "sales": ..., "legal": ...} | "not # checked" for a seal that is not good), # file (match, differs, no seal, not matched), pair # (linked, MISMATCH , waiting, entry # missing), # conflict (a repeated id with other content: the # receipt of the first one); the day is the UTC day # chain.log one line per checked entry and seal: OK, FILLED, # BROKEN, GAP, FIRST, AGAIN, CONFLICT, NOT CHECKED, # SEAL OK / BAD / KEY CHANGED, CHECKPOINT WAITING / # DIFFERS / not checked, SIGNED up to N (dropped), # PAIR UP-n linked / MISMATCH / WAITING / entry # missing # receiver.log refused requests (wrong token, signature, replay), # CONFLICT (a repeated id with other content) # requests/.json (you write it) requests for that scale, see below # state/ chain/-/ every entry with its H (in # files of 256 entries) + runs.json (the numbers # here), checkpoints/.json (the newest # signed one per kind, the waiting ones), seal-keys/ # .json (the key of the scale), pairs/ # .json (the sales / prints waiting for # their LEGAL MODE entry, the entries waiting for # their sale), the last n # per scale (mode 3), one marker per event id # (receipt + content digest), stored-marks.json (the # "stored" answer per scale + kind: number + H) # Check the whole folder again later, offline: python3 upscale-verify.py # -------------------------------------------------------------------------------------- import base64, hashlib, hmac, json, os, re, ssl, struct, sys, threading, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: AESGCM = None 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 # ---------- your settings ---------- PORT = int(os.environ.get('UPSCALE_PORT') or 8080) MODES = [int(m) for m in (os.environ.get('UPSCALE_MODES') or '1,2,3').split(',') if m.strip()] TOKENS = [t.strip() for t in (os.environ.get('UPSCALE_TOKENS') or 'CHANGE-ME-TOKEN').split(',') if t.strip()] SECRET = os.environ.get('UPSCALE_SECRET') or 'CHANGE-ME-SECRET' DATA = (os.environ.get('UPSCALE_DATA') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upscale-data')).rstrip('/') # the app's address (the offline app - the single file - sends the origin "null": add 'null' only if you use it) ORIGINS = ['https://up-scales.com'] MAX_BODY = 20 * 1024 * 1024 # (the app can send a sealed report file as base64) STORED = os.environ.get('UPSCALE_STORED') != '0' # answer "stored" (the archive receiver) def secret_for(device): """The secret of a scale (modes 2 + 3). Several scales with their own secrets: secrets = {'a1b2c3d4e5f6': 'secret of scale 1', '0a1b2c3d4e5f': 'secret of scale 2'} return secrets.get(device.lower(), '')""" return SECRET def requests_for(device): """Requests for the scale, sent with the answer to an event of the scale or to its idle poll (max. 4 per answer). This example takes them from /requests/.json (a JSON list you or another program writes), e.g. [{"get":"weight","id":"w1"}, {"get":"status"}, {"get":"things","from":0}, {"get":"activity","since":1200}, {"get":"legal","since":1}, {"get":"sales","day":"2026-11-27"}, {"do":"tare","id":"t1"}, {"do":"zero"}, {"do":"log","text":"batch 42 started"}] "get": the scale answers with an event "reply" (request, id, ok, the values or error); "since" / "day": the records come again as normal events. "do": only when "remote actions" is switched on at the scale - refused in LEGAL MODE, every action goes into the scale's activity log. A request that was handed out is gone from the file: if the answer is lost on the way, write it again. Or fixed ones: return [{'get': 'weight', 'id': 'w1'}]""" path = os.path.join(DATA, 'requests', re.sub(r'[^A-Za-z0-9_-]', '', device) + '.json') if not os.path.isfile(path): return [] try: with open(path, encoding='utf-8') as f: items = json.load(f) except ValueError: items = None if not isinstance(items, list) or not items: os.remove(path) return [] now, rest = items[:4], items[4:] if rest: with open(path, 'w', encoding='utf-8') as f: json.dump(rest, f, ensure_ascii=False) else: os.remove(path) return now LOCK = threading.Lock() # one request at a time in the state files def not_set(s): return not s or s.startswith('CHANGE-ME') def utc_now(fmt='%Y-%m-%dT%H:%M:%SZ'): return time.strftime(fmt, time.gmtime()) def log_line(name, text): os.makedirs(DATA, exist_ok=True) with open(os.path.join(DATA, name), 'a', encoding='utf-8') as f: f.write(utc_now() + ' ' + text + '\n') def json_file(path): try: with open(path, encoding='utf-8') as f: j = json.load(f) return j if isinstance(j, dict) else {} except (OSError, ValueError): return {} def write_json(path, obj): tmp = path + '.tmp' with open(tmp, 'w', encoding='utf-8') as f: json.dump(obj, f) os.replace(tmp, path) def seal_nonce(device, n, answer): """The 12-byte AES-GCM nonce: the 6 bytes of the Device ID (XOR 0xFF for the answer) + n as 6 bytes little-endian.""" d = bytearray(bytes.fromhex(device)) if answer: d = bytearray(b ^ 0xFF for b in d) return bytes(d) + n.to_bytes(6, 'little') def hex_or_b64(v, src, size=0): """Bytes from a text: the scale sends base64, the app hex (size: the length it must have, 0 = any).""" 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): """The parts of an activity / legal / sales entry: a dict (dev, type, num, raw, rawok, h = H after it or '', hb = H before it or '' - the app sends "hb" at the start of a piece -, alibi, no_alibi) | None: not such an event | a text: why not. 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 The scale sends "raw" and "alibi_raw" as base64 and "chain" (H after the entry) as hex; the app sends them as hex ("h"). The number: an integer 0...4294967295, else the event is no chain entry ('no number').""" 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() # (the chain is part of the record) alibi = hex_or_b64(d.get('alibi_raw'), src) no_alibi = not alibi and bool(d.get('alibi')) # (an alibi number without its bytes: the link can't be computed) 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): """The H before the first entry of a chain ('' = not the first one).""" if typ == 'activity' and num == 0: return '00' * 32 if typ == 'legal' and num == 1: return '00' * 32 if typ == 'sales' and num == 1: return '00' * 8 return '' def same_hex(a, b): return bool(a) and bool(b) and hmac.compare_digest(str(a).lower(), str(b).lower()) CHUNK = 256 # entries per state file def dev_name(dev): return re.sub(r'[^0-9a-z]', '', str(dev).lower()) class Chains: """The chain state per scale + kind (activity, legal, sales), read when needed and written after the event is on the disk: state/chain/-/.json = {"": {"h": H after it, "r": the raw entry (hex), "b": the H before it the entry was linked with ('' = not linked yet), "a": the alibi bytes of a sale (hex), "n": 1 = a sale kept without its alibi bytes (not linked), "x": 1 = BROKEN link}} state/chain/-/runs.json = {"runs": [[first, last], ...]} - the numbers kept state/checkpoints/.json = {"signed": {"": the newest checkpoint whose H matched: upto, h, from (the lowest entry covered by its signature), log_seq, time, seal, at}, "waiting": {"": [checkpoints whose entry is not here yet]}} state/seal-keys/.json = {"pk": the public key of the scale, "certified": true | false, "at"} (the first key seen, or the key confirmed by UP-SCALE)""" def __init__(self): self.files, self.dirty, self.snap = {}, set(), {} def path(self, *parts): return os.path.join(DATA, 'state', *parts) def file(self, path, watch=False): if path not in self.files: self.files[path] = json_file(path) if watch: self.snap[path] = json.dumps(self.files[path], sort_keys=True) return self.files[path] def changed(self, path): self.dirty.add(path) def keys(self, dev): return self.file(self.path('seal-keys', dev_name(dev) + '.json'), True) def cps(self, dev): c = self.file(self.path('checkpoints', dev_name(dev) + '.json'), True) for k in ('signed', 'waiting'): if not isinstance(c.get(k), dict): c[k] = {} return c def pairs(self, dev): c = self.file(self.path('pairs', dev_name(dev) + '.json'), True) for k in ('need_entry', 'need_sale'): if not isinstance(c.get(k), dict): c[k] = {} return c def folder(self, dev, typ): return os.path.join('chain', dev_name(dev) + '-' + typ) def get(self, dev, typ, num): if num < 0: return None e = self.file(self.path(self.folder(dev, typ), '%08d.json' % (num // CHUNK))).get(str(num)) return e if isinstance(e, dict) else None def put(self, dev, typ, num, e): p = self.path(self.folder(dev, typ), '%08d.json' % (num // CHUNK)) self.file(p)[str(num)] = e self.changed(p) rp = self.path(self.folder(dev, typ), 'runs.json') runs = sorted(self.runs(dev, typ) + [[num, num]]) merged = [] for a, b in runs: if merged and a <= merged[-1][1] + 1: merged[-1][1] = max(merged[-1][1], b) else: merged.append([a, b]) self.file(rp)['runs'] = merged self.changed(rp) def runs(self, dev, typ): r = self.file(self.path(self.folder(dev, typ), 'runs.json')).get('runs') return [[x[0], x[1]] for x in r if isinstance(x, list) and len(x) == 2 and all(type(v) is int for v in x)] if isinstance(r, list) else [] def below(self, dev, typ, num): """The newest number kept below num (None: none).""" best = None for a, b in self.runs(dev, typ): if a < num: best = min(b, num - 1) return best def above(self, dev, typ, num): """The oldest number kept above num (None: none).""" for a, b in self.runs(dev, typ): if b > num: return max(a, num + 1) return None def flush(self): for p, was in self.snap.items(): if json.dumps(self.files[p], sort_keys=True) != was: self.dirty.add(p) for p in sorted(self.dirty): os.makedirs(os.path.dirname(p), exist_ok=True) write_json(p, self.files[p]) self.dirty = set() def ask_text(typ, a): return ' (ask for them: {"get":"%s","since":%d})' % (typ, a) if typ != 'sales' else '' def follows_from(typ, h, num, e): """Does entry num (kept: e) follow the H h? -> True | False | None (not known: no raw entry, a sale without its alibi bytes).""" if e.get('r') and not e.get('n'): return same_hex(chain_link(typ, h, num, bytes.fromhex(e['r']), bytes.fromhex(e.get('a', ''))), e.get('h')) if e.get('b'): return same_hex(e['b'], h) return None def chain_check(ev, ch): """The hash chain of "activity", "legal" and "sales" (entry_parts): every entry is kept with its H, so it is checked against the entry before it AND the one after it - also when it fills a gap later. A kept H is never replaced by another one, except an entry without raw whose H the entry after it does not follow, by a raw entry that links to both neighbours. -> the state: ok | filled | broken | gap | first | same | conflict | no raw | no number | '' (not a chain event).""" p = entry_parts(ev) if p is None or isinstance(p, str): return p or '' dev, typ, num, raw = p['dev'], p['type'], p['num'], p['raw'] rawok = p['rawok'] and not p['no_alibi'] what = '%s %s %d' % (dev, typ, num) prev = ch.get(dev, typ, num - 1) start = chain_start(typ, num) before = prev['h'] if prev else (start or p['hb']) calc = chain_link(typ, before, num, raw, p['alibi']) if before and rawok else '' new_h = calc if calc and (not p['h'] or same_hex(calc, p['h'])) else p['h'] old = ch.get(dev, typ, num) note, e, broken = '', None, '' if old and old.get('r'): if p['rawok'] and old['r'] == raw.hex(): if p['alibi'] and old.get('n'): # (the alibi bytes of a sale kept without them: its own chain bytes must come out of them) if calc and not same_hex(calc, old.get('h')): log_line('chain.log', what + ' CONFLICT - these alibi bytes do not give the chain of the record here') return 'conflict' e = dict(old, a=p['alibi'].hex(), b=before if calc else '') e.pop('n', None) note = 'alibi bytes added - ' elif p['alibi'] and old.get('a', '') != p['alibi'].hex(): log_line('chain.log', what + ' CONFLICT - the same record with other alibi bytes is here already') return 'conflict' else: log_line('chain.log', what + ' AGAIN - the same entry is here already') return 'same' elif not p['rawok'] and (not p['h'] or same_hex(p['h'], old.get('h'))): log_line('chain.log', what + ' AGAIN - the same entry is here already') return 'same' else: log_line('chain.log', what + ' CONFLICT - another entry with this number is here already (the first one stays the checked one)') return 'conflict' elif old: # (an entry kept with its H only) if not new_h or same_hex(new_h, old.get('h')): if not p['rawok']: log_line('chain.log', what + ' AGAIN - the same entry is here already') return 'same' e = dict(old, r=raw.hex(), b=before if calc and same_hex(calc, old.get('h')) else '') if p['alibi']: e['a'] = p['alibi'].hex() if p['no_alibi']: e['n'] = 1 if calc and not same_hex(calc, old.get('h')): broken = 'BROKEN - the entry or the one before it is not what the chain says' e['x'] = 1 elif e['b']: e.pop('x', None) else: nxt = ch.get(dev, typ, num + 1) if not (calc and same_hex(calc, new_h) and (prev or start) and nxt and follows_from(typ, calc, num + 1, nxt)): log_line('chain.log', what + ' CONFLICT - another H for this number is here already (the first one stays the checked one)') return 'conflict' note = 'CONFLICT - replaces an entry without raw that had another H - ' if e is None: e = {'h': new_h, 'r': raw.hex() if p['rawok'] else '', 'b': before if calc and same_hex(calc, new_h) else ''} if p['alibi']: e['a'] = p['alibi'].hex() if p['no_alibi']: e['n'] = 1 if calc and not same_hex(calc, new_h): broken = 'BROKEN - the entry or the one before it is not what the chain says' e['x'] = 1 if not e['h']: log_line('chain.log', what + ' NOT CHECKED - no raw entry and no chain H') return 'no raw' ch.put(dev, typ, num, e) # the entry after it (it came first: this one fills a gap) nxt = ch.get(dev, typ, num + 1) follows, unchecked = None, False if nxt: follows = follows_from(typ, e['h'], num + 1, nxt) if follows: if nxt.get('x') or (nxt.get('r') and not nxt.get('n') and nxt.get('b') != e['h']): nxt.pop('x', None) nxt['b'] = e['h'] ch.put(dev, typ, num + 1, nxt) elif follows is False and not p['rawok']: unchecked = True # (an entry without raw does not make the one after it broken) elif follows is False: nxt['x'] = 1 ch.put(dev, typ, num + 1, nxt) if not broken: broken = 'BROKEN - entry %d does not follow this one' % (num + 1) linked = bool(e.get('b')) and bool(prev or start) lo, hi = ch.below(dev, typ, num), ch.above(dev, typ, num) missing = [] if lo is not None and lo < num - 1: missing.append((lo + 1, num - 1)) if hi is not None and hi > num + 1: missing.append((num + 1, hi - 1)) if broken: state, text = 'broken', broken elif not rawok: state, text = 'no raw', 'NOT CHECKED - ' + ('no alibi bytes ("alibi_raw")' if p['no_alibi'] else 'no raw entry') + ': H noted' elif hi is not None: parts = (['starts the chain' if start else 'links to %d' % (num - 1)] if linked else []) + (['%d follows it' % (num + 1)] if follows else []) state, text = 'filled', 'FILLED - ' + (' and '.join(parts) if parts else 'not linked yet') elif linked: state, text = 'ok', 'OK' elif lo is not None: state, text = 'gap', 'GAP -' else: state, text = 'first', 'FIRST - H noted' + (' (checked with the H before it, "hb")' if e.get('b') else '') if unchecked: text += ' - %d not checked against an entry without raw' % (num + 1) if missing and state in ('filled', 'gap', 'broken'): ranges = ', '.join(('%d' % a) if a == b else ('%d...%d' % (a, b)) for a, b in missing) text += (' ' + ranges + ' missing' if state == 'gap' else ' - still missing: ' + ranges) + ask_text(typ, missing[0][0]) if note.startswith('CONFLICT'): state = 'conflict' log_line('chain.log', what + ' ' + note + text) checkpoint_after(ch, dev, typ, num) return state # ---------- the seals of the scale (ECDSA P-256) ---------- # seal = payload (80 bytes) + the signature of the scale over SHA-256(payload) (64 bytes, raw r | s); payload: [0] 1 | [1] kind: 1 report, # 2 file, 3 signature, 4 chain checkpoint, 5 LEGAL MODE store | [2-7] Device ID | [8-11] the seq of its own activity log entry | [12-15] # time (epoch) | [16-19] number (kind 1 / 3: the report, kind 4: N = the newest activity seq covered, kind 5: the newest legal number) # | [20] user | [21] meaning (kind 3) / how (kind 4: 0 an app asked, 1 the webhook export) | [22-41] user name (kinds 1-3) # | kind 4: [22-25] S = the newest sales seq (0: none), [26-33] the sales chain after S | [42-73] SHA-256 of the document (kind 4: the # activity H after N, kind 5: the legal H after the newest number) | [74-77] kind 4 / 5: the oldest entry still kept on the scale # certificate = payload (80 bytes) + the signature of the UP-SCALE licence key over SHA-256(payload); payload: [0] the licence key id # (1 | 2) | [1] edition (1 ENTERPRISE) | [2-7] Device ID | [8-11] certificate number | [12-15] made | [16-79] the public key of the scale 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 on a real receiver) 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') # (only a seal with one of these is taken as a checkpoint) def ecdsa_ok(pk, data, sig): """ECDSA P-256 over SHA-256(data), pk = x | y (64 bytes), sig = r | s (64 bytes) -> True | False | None (no "cryptography").""" 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, ch): """A seal with its certificate (or the public key that came with it) -> (result, problems, parsed seal, certificate id). result: certified (key confirmed by UP-SCALE) | same_key | first_key (no certificate, noted now) | key_changed (no certificate, another key than the noted one) | bad | not_checked (no "cryptography"). The key per scale (ch.keys): the first one seen, replaced by a key confirmed by UP-SCALE - then the checkpoints taken from seals without a certificate of another key are dropped.""" 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 if not ok: why.append('signature') if why: return 'bad', why, p, cert_id dev = p['device'] pin = ch.keys(dev) if certified: if pin.get('pk') != pk.hex(): if pin.get('pk'): log_line('chain.log', '%s SEAL KEY CHANGED - a new key, confirmed by UP-SCALE (certificate %s): noted' % (dev, cert_id)) if not pin.get('certified'): drop_uncertified(ch, dev) pin.clear() pin.update({'pk': pk.hex(), 'certified': True, 'at': utc_now()}) elif not pin.get('certified'): pin['certified'] = True return 'certified', [], p, cert_id if not pin.get('pk'): pin.update({'pk': pk.hex(), 'certified': False, 'at': utc_now()}) return 'first_key', [], p, cert_id return ('same_key' if pin['pk'] == pk.hex() else 'key_changed'), [], p, cert_id def drop_uncertified(ch, dev): """A key confirmed by UP-SCALE replaced a key without a certificate: the checkpoints of seals without a certificate go.""" cps = ch.cps(dev) for typ in sorted(cps['signed']): cp = cps['signed'][typ] if cp.get('seal') != 'certified': del cps['signed'][typ] log_line('chain.log', '%s %s SIGNED up to %s dropped - its seal had no certificate and another key than the one confirmed by UP-SCALE' % (dev, typ, cp.get('upto'))) for typ in sorted(cps['waiting']): cps['waiting'][typ] = [w for w in cps['waiting'][typ] if w.get('seal') == 'certified'] SEAL_TEXT = {'certified': 'OK - key confirmed by UP-SCALE (certificate %s)', 'same_key': 'OK - the same key as before (no certificate)', 'first_key': 'OK - the first key of this scale, noted (no certificate: later seals show "the same key")', 'key_changed': 'KEY CHANGED !!! - signed with another key than the noted one, and no certificate', 'bad': 'BAD - %s', 'not_checked': 'NOT CHECKED (no "cryptography" package)'} def seal_line(dev, what, res, why, cert_id): t = SEAL_TEXT[res] log_line('chain.log', '%s SEAL %s %s' % (dev, what, t % (cert_id if res == 'certified' else ', '.join(why)) if '%s' in t else t)) def covered_down(ch, dev, typ, top): """The lowest entry covered from entry top downward: each entry linked with its H before, each H before = the H of the entry before it (None: top itself is not linked).""" low, k = None, top while True: e = ch.get(dev, typ, k) if not e or not e.get('b') or e.get('x'): return low low = k if chain_start(typ, k): return low p = ch.get(dev, typ, k - 1) if not p or not same_hex(p.get('h'), e['b']): return low k -= 1 def checkpoint(ch, dev, typ, upto, h, info): """A signed chain head (seal kind 4: activity + sales, kind 5: legal; only a seal of SEAL_GOOD) against the entries kept -> signed | differs | waiting (entry upto is not here yet). A checkpoint without a certificate never takes the place of one with it.""" cps, what = ch.cps(dev), '%s %s' % (dev, typ) e = ch.get(dev, typ, upto) if not e: waiting = [w for w in cps['waiting'].get(typ, []) if w.get('upto') != upto] + [dict(info, upto=upto, h=h)] cps['waiting'][typ] = sorted(waiting, key=lambda w: (w.get('log_seq', 0), w.get('upto', 0)))[-8:] log_line('chain.log', '%s CHECKPOINT %d WAITING - entry %d is not here yet' % (what, upto, upto)) return 'waiting' if not same_hex(e.get('h'), h): log_line('chain.log', '%s CHECKPOINT %d DIFFERS - BROKEN: the scale signed another H after %d than the entries here' % (what, upto, upto)) return 'differs' low = covered_down(ch, dev, typ, upto) cur = cps['signed'].get(typ) new_cert, cur_cert = info['seal'] == 'certified', bool(cur) and cur.get('seal') == 'certified' if not cur or (new_cert and not cur_cert) or (new_cert == cur_cert and upto >= cur.get('upto', 0)): cps['signed'][typ] = dict(info, upto=upto, h=h, **{'from': low if low is not None else upto + 1, 'at': utc_now()}) log_line('chain.log', '%s SIGNED up to %d (%s)' % (what, upto, '%d...%d covered by the signature' % (low, upto) if low is not None else 'not linked yet: nothing covered')) return 'signed' def checkpoint_after(ch, dev, typ, num): """After entry num was kept: a waiting checkpoint for it, and a signed checkpoint whose covered range now reaches further down (only while the entry it signed still has the signed H).""" cps = ch.cps(dev) for w in [w for w in cps['waiting'].get(typ, []) if w.get('upto') == num]: cps['waiting'][typ] = [x for x in cps['waiting'][typ] if x.get('upto') != num] info = {k: w[k] for k in w if k not in ('upto', 'h')} checkpoint(ch, dev, typ, num, w['h'], info) cp = cps['signed'].get(typ) if cp and cp['from'] - 2 <= num < cp['from']: top = ch.get(dev, typ, cp['upto']) if not top or not same_hex(top.get('h'), cp['h']): log_line('chain.log', '%s %s CHECKPOINT %d DIFFERS - the entry here has another H than the signed one' % (dev, typ, cp['upto'])) return low = covered_down(ch, dev, typ, min(cp['from'], cp['upto'])) if low is not None and low < cp['from']: cp['from'] = low log_line('chain.log', '%s %s SIGNED up to %d - covers %d...%d now' % (dev, typ, cp['upto'], low, cp['upto'])) def seal_event(ev, ch): """A 'sealed' event: the seal checked by itself (signature, certificate, device), kind 4 / 5 against the chains -> fields for _rx.""" d, dev = ev.get('data'), str(ev.get('device') or '').lower() if not isinstance(d, dict): return {} res, why, p, cert_id = seal_verify(unhex(d.get('seal')), unhex(d.get('cert')), unhex(d.get('pk')), ch) rx = {} if p: if dev and dev != 'unknown' and p['device'] != dev: why.append('device') 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') if why: res = 'bad' what = '%s log %s' % (SEAL_KINDS.get(p['kind'], 'kind %d' % p['kind']), p['seq']) if p else '?' seal_line(dev or '?', what, res, why, cert_id) rx['seal'] = res if why: rx['seal_why'] = ','.join(why) if 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'])] if res in SEAL_GOOD: info = {'log_seq': p['seq'], 'time': p['time'], 'seal': res} if p['kind'] == 5: info['oldest'] = p['oldest'] rx['checkpoint'] = {typ: checkpoint(ch, p['device'], typ, upto, h, info) for typ, upto, h in heads} else: for typ, upto, h in heads: log_line('chain.log', '%s %s CHECKPOINT %d not checked - the seal is %s' % (p['device'], typ, upto, res)) rx['checkpoint'] = 'not checked' return rx def file_seal(ev, ch): """A sealed file of the app (event 'sealed_file', a 'programs' report file) with its bytes ("content_base64"): the seal inside the file against the file - a JSON file (its last field "seal") or an HTML report (
). -> fields for _rx.""" d = ev.get('data') if not isinstance(d, dict) or not d.get('content_base64'): return {} try: text = base64.b64decode(str(d['content_base64'])).decode('utf-8') except ValueError: return {'file': 'not matched'} 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 {'file': 'no seal'} if not isinstance(field, dict): return {'file': 'no seal'} seal, cert, pk = (str(field.get(k) or '') for k in ('seal', 'cert', 'pk')) plain = text[:m.start()] + '\n}' elif tag: attr = lambda k: (re.search('data-' + k + '="([0-9a-f]*)"', tag.group(1)) or [None, ''])[1] seal, cert, pk = attr('seal'), attr('cert'), attr('pk') 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) else: return {'file': 'no seal'} if not seal: return {'file': 'no seal'} res, why, p, cert_id = seal_verify(unhex(seal), unhex(cert), unhex(pk), ch) dev = str(ev.get('device') or '').lower() match = bool(p) and hashlib.sha256(plain.encode('utf-8')).hexdigest() == p['hash'] if p and not match: why.append('hash') if p and dev and dev != 'unknown' and p['device'] != dev: why.append('device') if why: res = 'bad' seal_line(dev or '?', 'in file %s' % (d.get('file') or '?'), res, why, cert_id) rx = {'file': 'match' if match else 'differs', 'seal': res} if why: rx['seal_why'] = ','.join(why) return rx # ---------- PAIR CHECK: a sale / a print of the balance <-> its LEGAL MODE entry (RS-232 dongles in LEGAL MODE) ---------- # sales record (76 bytes, the "raw" of a sales event): [0-3] sale id | [4-6] seconds of the day | [11-14] grams (float) | [40-43] seq # | [65-66] minutes east of UTC (int16, 0x7FFF: not known) | [68-75] its chain; its alibi bytes "UP-000123" = the number of its entry # (other alibi texts: the balance's own number - not checked here) # LEGAL MODE entry (48 bytes): [0-3] number | [4-7] time (epoch) | [8] kind (1 sale, 8 print of the balance) | [40-43] the value used # (float g: the same float as the grams of the sale / the value of the print) | [44-47] kind 1: the sale id # print event: data.legal "UP-000123", raw = its activity entry: [0-3] time, [8-11] the value (float g) # state/pairs/.json = {"need_entry": {"": a sale / print whose entry is not here yet}, "need_sale": {"": the # sale id of an entry of kind 1 whose sale is not here yet}} (each at most PAIR_KEEP, the newest numbers stay) 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) PAIR_KEEP = 1000 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, '' def keep_newest(m): for k in sorted(m, key=int)[:-PAIR_KEEP] if len(m) > PAIR_KEEP else []: del m[k] def pair_check(ch, dev, info): """A sale / print with its LEGAL MODE number against the entry kept -> linked | MISMATCH | waiting | entry missing.""" pairs, n = ch.pairs(dev), info['n'] what = '%s %s %s PAIR UP-%06d' % (dev, 'sales' if info['what'] == 'sale' else 'print', 'null' if info['num'] is None else info['num'], n) e = ch.get(dev, 'legal', n) if e and e.get('r') and not e.get('x'): pairs['need_entry'].pop(str(n), None) if info['what'] == 'sale': pairs['need_sale'].pop(str(n), None) why, note = pair_compare(info, bytes.fromhex(e['r'])) if why: log_line('chain.log', what + ' MISMATCH ' + ','.join(why) + ' - the entry says something else than the ' + info['what']) return 'MISMATCH ' + ','.join(why) log_line('chain.log', what + ' linked' + note) return 'linked' + note oldest = ch.cps(dev)['signed'].get('legal', {}).get('oldest') if (e and e.get('x')) or (not e and type(oldest) is int and n < oldest): log_line('chain.log', what + ' entry missing - ' + ('the entry is BROKEN in the chain' if e else 'below the oldest entry kept on the scale')) return 'entry missing' pairs['need_entry'][str(n)] = info keep_newest(pairs['need_entry']) log_line('chain.log', what + ' WAITING - entry %d is not here yet' % n) return 'waiting' def pair_legal(ch, dev, num): """A LEGAL MODE entry just kept: the sale / print waiting for it, or (kind 1) wait for its sale -> the result for _rx | ''.""" e = ch.get(dev, 'legal', num) if not e or not e.get('r') or e.get('x'): return '' pairs = ch.pairs(dev) info = pairs['need_entry'].get(str(num)) if info: return pair_check(ch, dev, info) raw = bytes.fromhex(e['r']) if raw[8] == 1: ref = int.from_bytes(raw[44:48], 'little') pairs['need_sale'][str(num)] = ref keep_newest(pairs['need_sale']) log_line('chain.log', '%s legal %d PAIR WAITING - its sale (id %d) is not here yet' % (dev, num, ref)) return 'waiting' return '' # ---------- a repeated id: the same content? ---------- def canon(v): """The event as one fixed text (keys sorted, numbers in one form) - the same in the three receivers.""" 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): """What a repeated id is compared by: a chain entry by its raw bytes (a sale without its alibi bytes too: its chain bytes bind them), a seal by the seal, any other event by its content without sent_at, env and _rx (the scale and the app send the same record with other fields around it).""" 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() def stored_step(ev, marks, fresh): """THE ARCHIVE RECEIVER ("stored"): per scale + kind the newest entry up to which every entry is on the disk in ONE chain this script recomputed itself - marks[key] = {'num', 'h'} ('base': only the first entry of a run is known, its H came with it, nothing is recomputed yet). fresh: the entry was written now (False: it was on the disk already - the scale sends again). Only an entry with raw and with the chain H of the sender ("chain" / "h") or the H before it ("hb") moves the mark. The run goes on with the next number (also a resend of one that is on the disk); the next number whose chain H is not the recomputed one, or a new entry further back, starts a new run; a gap stops it until the missing entries come (ask for them: {"get":"legal","since":...}). The first entry of a log (activity 0, legal 1) links to the zero start. Activity + legal only.""" p = entry_parts(ev) if not isinstance(p, dict) or p['type'] == 'sales': return None dev, typ, num, raw, h = p['dev'], p['type'], p['num'], p['raw'], p['h'] hb = p['hb'] or chain_start(typ, num) key = dev + ':' + typ m = marks.get(key) if not p['rawok'] or not (h or hb): return m if m and num == m['num'] + 1 and (not hb or same_hex(hb, m['h'])): calc = chain_link(typ, m['h'], num, raw) marks[key] = {'num': num, 'h': calc} if not h or hmac.compare_digest(calc, h) else {'num': num, 'h': h, 'base': True} elif fresh and (not m or num <= m['num'] + 1): calc = chain_link(typ, hb, num, raw) if hb else '' if calc and (not h or hmac.compare_digest(calc, h)): marks[key] = {'num': num, 'h': calc} elif h: marks[key] = {'num': num, 'h': h, 'base': True} return marks.get(key) def no_constant(name): raise ValueError('no JSON: ' + name) def finite_float(text): """A JSON number that does not fit a double (1e400) makes the body no event - as in the other receivers.""" v = float(text) if v != v or v in (float('inf'), float('-inf')): raise ValueError('number too large') return v class Refused(Exception): def __init__(self, code, text, log=True): Exception.__init__(self, text) self.code, self.text, self.log = code, text, log def store_line(typ, event): """The event as one line into events//.jsonl (on the disk before the answer) -> the line.""" line = json.dumps(event, ensure_ascii=False, separators=(',', ':')) os.makedirs(os.path.join(DATA, 'events', typ), exist_ok=True) try: with open(os.path.join(DATA, 'events', typ, utc_now('%Y-%m-%d') + '.jsonl'), 'a', encoding='utf-8') as f: f.write(line + '\n') f.flush() os.fsync(f.fileno()) except OSError: raise Refused(500, 'could not store') return line class Handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def log_message(self, *a): pass def send(self, code, body=b'', headers=None): self.send_response(code) origin = self.headers.get('Origin', '') self.send_header('Access-Control-Allow-Origin', origin if origin in ORIGINS else ORIGINS[0]) self.send_header('Vary', 'Origin') self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization') self.send_header('Access-Control-Allow-Private-Network', 'true') for k, v in (headers or {}).items(): self.send_header(k, v) if body or code != 204: self.send_header('Content-Type', 'application/json') self.send_header('Content-Length', str(len(body))) self.end_headers() if body: self.wfile.write(body) def do_OPTIONS(self): self.send(204) def do_POST(self): self.handle_any(False) def do_GET(self): self.handle_any(True) def handle_any(self, is_poll): try: code, body, headers = self.process(is_poll) except Refused as e: if e.log: with LOCK: log_line('receiver.log', '%d %s (%s)' % (e.code, e.text, self.client_address[0])) code, body, headers = e.code, json.dumps({'error': e.text}).encode(), {} except Exception as e: try: with LOCK: log_line('receiver.log', '500 %r (%s)' % (e, self.client_address[0])) except OSError: pass code, body, headers = 500, b'', {} self.send(code, body, headers) def process(self, is_poll): q = parse_qs(urlparse(self.path).query) qget = lambda k: (q.get(k) or [''])[0] if is_poll and qget('poll') != '1': raise Refused(405, 'GET only for the poll', False) length = int(self.headers.get('Content-Length') or 0) if length > MAX_BODY: raise Refused(413, 'too large', False) raw = self.rfile.read(length) if length and not is_poll else b'' try: body = None if is_poll else json.loads(raw.decode('utf-8'), parse_constant=no_constant, parse_float=finite_float) except ValueError: body = None hdr = lambda k: self.headers.get(k, '') # which mode: the form of the request says it (the mode must be one you accept - each has its own secret) if hdr('X-Upscale-Signature'): mode = 2 elif ('n' in q) if is_poll else (isinstance(body, dict) and body.get('schema') == 'upscale.sealed/1'): mode = 3 else: mode = 1 if mode not in MODES: raise Refused(401, 'mode %d not accepted here' % mode, False) # (not set up yet: refused without writing anything) if mode == 1 and all(not_set(t) for t in TOKENS): raise Refused(503, 'set UPSCALE_TOKENS', False) device = qget('device') if is_poll else str(body.get('device') or '') if isinstance(body, dict) else '' if mode != 1 and not_set(secret_for(device)): raise Refused(503, 'set UPSCALE_SECRET', False) if mode == 3 and AESGCM is None: raise Refused(500, 'mode 3 needs the Python package "cryptography" (pip install cryptography)') for sub in ('', 'events', 'state', 'requests'): os.makedirs(os.path.join(DATA, sub), exist_ok=True) with LOCK: return self.locked(is_poll, mode, raw, body, device, qget, hdr) def locked(self, is_poll, mode, raw, body, device, qget, hdr): event, nonce, n = None, '', 0 if mode == 1: # the token: Authorization: Bearer, X-API-Key or ?token= (the app's "receiver without CORS" mode, the scale's # "token in the address"). Basic or a header of your own: check hdr('Authorization') / hdr('Your-Header') here. auth = hdr('Authorization') given = auth[7:] if auth.startswith('Bearer ') else (hdr('X-API-Key') or qget('token')) if not any(not not_set(t) and hmac.compare_digest(t.encode(), given.encode()) for t in TOKENS): raise Refused(401, 'mode 1: wrong or missing token') event = body elif mode == 2: # signature over: time "." nonce "." body (the poll: an empty body) nonce = hdr('X-Upscale-Nonce') want = 'sha256=' + hmac.new(secret_for(device).encode(), (hdr('X-Upscale-Time') + '.' + nonce + '.').encode() + raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(want.encode(), hdr('X-Upscale-Signature').encode('utf-8', 'replace')): raise Refused(401, 'mode 2: signature wrong') # (a replayed signed request repeats an event id you have: it is dropped below. A time window is possible too - # abs(time.time() - int(hdr('X-Upscale-Time'))) < 300 - but only when the clock of the scale is set.) event = body else: n = qget('n') if is_poll else body.get('n') if not re.fullmatch(r'[0-9a-fA-F]{12}', device) or not re.fullmatch(r'[0-9]{1,15}', str(n)) or not 1 <= int(n) <= 0xFFFFFFFFFFFF: raise Refused(400, 'mode 3: device or n wrong') n = int(n) # (up to 2^48 - Python ints have no limit) key = hashlib.sha256(secret_for(device).encode()).digest() if is_poll: # the poll carries t = the AES-256-GCM tag of an EMPTY text with the nonce of n: checked before n counts tag = AESGCM(key).encrypt(seal_nonce(device, n, False), b'', None) if not hmac.compare_digest(tag.hex().encode(), qget('t').lower().encode('utf-8', 'replace')): raise Refused(401, 'mode 3: poll tag t wrong or missing') else: try: plain = AESGCM(key).decrypt(seal_nonce(device, n, False), base64.b64decode(str(body.get('ct') or ''), validate=True), None) except Exception: raise Refused(401, 'mode 3: the envelope does not open') try: event = json.loads(plain.decode('utf-8')) except ValueError: event = None # replay check (only after the seal or the poll tag was checked): n only goes up. Kept per scale in state/last-n.json. last_file = os.path.join(DATA, 'state', 'last-n.json') last = json_file(last_file) dev = device.lower() if n <= last.get(dev, 0): raise Refused(409, 'mode 3: n %d not higher than %d (replay)' % (n, last.get(dev, 0))) last[dev] = n write_json(last_file, last) answer, status = {}, 200 # (modes 2 + 3: the scale counts a 4xx for one event toward its "skipped after 5 refusals" only when the answer is signed / # sealed - so a refusal of a bad event goes out like a 2xx below; the 401 / 409 refusals above need no signature) bad = not is_poll and (not isinstance(event, dict) or not isinstance(event.get('id'), str) or not event['id'] or not event.get('type')) if bad: if mode == 1: raise Refused(400, 'not an event') log_line('receiver.log', '400 not an event (%s)' % self.client_address[0]) answer, status = {'error': 'not an event'}, 400 elif not is_poll: typ = re.sub(r'[^a-z0-9_-]', '', str(event['type']).lower()) or 'other' # a doubled id (after a lost answer, a power cut ...): not stored again, but acknowledged again with its receipt - unless # its content differs (CONFLICT: kept as well, for the check). (live weight: every one has its own time id and is never # sent again - no marker for it) hid = hashlib.sha256(event['id'].encode()).hexdigest() marker = os.path.join(DATA, 'state', 'seen', typ, hid[:2], hid) fresh = False if typ != 'weight' and os.path.isfile(marker): with open(marker, encoding='utf-8') as f: seen = f.read().split('\n') ref, was = seen[0].strip(), (seen[1].strip() if len(seen) > 1 else '') if was and not hmac.compare_digest(was, content_digest(event)): text = 'CONFLICT %s - came again with other content (the first one: %s)' % (event['id'], ref) log_line('chain.log', text) log_line('receiver.log', '%s (%s)' % (text, self.client_address[0])) event['_rx'] = {'at': utc_now(), 'mode': mode, 'conflict': ref} store_line(typ, event) fresh = True # (this one is on the disk too: it may start a new "stored" run) else: # the checks: the chains (activity, legal, sales), the seals, the checkpoints - the state files are written after the event # (only the files of this scale + kind are read) ch = Chains() rx = {'at': utc_now(), 'mode': mode, 'chain': chain_check(event, ch)} # the pair check: a sale / print with its LEGAL MODE number <-> the entry p = entry_parts(event) kept = rx['chain'] in ('ok', 'filled', 'gap', 'first', 'broken', 'no raw') pair = '' if (kept and typ == 'sales') or typ == 'print': info = pair_info(event, p) if info: pair = pair_check(ch, p['dev'] if isinstance(p, dict) else str(event.get('device') or '').lower(), info) elif kept and typ == 'legal': pair = pair_legal(ch, p['dev'], p['num']) if pair: rx['pair'] = pair if typ == 'sealed': rx.update(seal_event(event, ch)) elif typ in ('sealed_file', 'programs'): rx.update(file_seal(event, ch)) event['_rx'] = rx # (no 2xx without a stored event: the scale sends it again; on the disk before "stored" may name it) line = store_line(typ, event) fresh = True ch.flush() # your receipt (max. 36 characters): here the day + the start of the SHA-256 of the stored line ref = utc_now('%Y%m%d') + '-' + hashlib.sha256(line.encode()).hexdigest()[:16] if typ != 'weight': os.makedirs(os.path.dirname(marker), exist_ok=True) with open(marker, 'w', encoding='utf-8') as f: f.write(ref + '\n' + content_digest(event)) answer = {'ack': event['id'], 'ref': ref} # the archive receiver: what is on the disk in one recomputed chain (activity / legal events of the scale and of the app) if STORED: marks_file = os.path.join(DATA, 'state', 'stored-marks.json') marks = json_file(marks_file) was = json.dumps(marks, sort_keys=True) m = stored_step(event, marks, fresh) if json.dumps(marks, sort_keys=True) != was: write_json(marks_file, marks) if m and not m.get('base'): answer['stored'] = {'type': typ, 'upto': m['num'], 'chain': m['h']} # requests only to the scale (the app ignores them): its events have "src":"scale", modes 2 + 3 and the poll are the scale if not bad and (is_poll or mode != 1 or event.get('src') == 'scale'): req = requests_for(device) if req: answer['requests'] = req # ---------- the answer: signed (mode 2) or sealed (mode 3) ---------- out = json.dumps(answer, ensure_ascii=False, separators=(',', ':')).encode('utf-8') headers = {} if mode == 2: t = str(int(time.time())) headers = {'X-Upscale-Time': t, 'X-Upscale-Nonce': nonce, 'X-Upscale-Signature': 'sha256=' + hmac.new(secret_for(device).encode(), (t + '.' + nonce + '.').encode() + out, hashlib.sha256).hexdigest()} elif mode == 3: ct = AESGCM(hashlib.sha256(secret_for(device).encode()).digest()).encrypt(seal_nonce(device, n, True), out, None) out = json.dumps({'schema': 'upscale.sealed/1', 'n': n, 'ct': base64.b64encode(ct).decode()}).encode() return status, out, headers def main(): if 3 in MODES and AESGCM is None: print('NOTE: mode 3 (sealed envelope) needs the package "cryptography" (pip install cryptography) - sealed requests are refused until then', file=sys.stderr) if ec is None: print('NOTE: without the package "cryptography" the seals are not checked (the chains are)', file=sys.stderr) if LICENCE_KEYS[1] != LICENCE_KEYS_REAL[1]: print('NOTE: UPSCALE_TEST_LICENCE_KEY is set - a TEST licence key, not for a real receiver', file=sys.stderr) srv = ThreadingHTTPServer(('0.0.0.0', PORT), Handler) scheme = 'http' if os.environ.get('UPSCALE_CERT'): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(os.environ['UPSCALE_CERT'], os.environ.get('UPSCALE_KEY')) srv.socket = ctx.wrap_socket(srv.socket, server_side=True) scheme = 'https' print('UP-SCALE receiver on %s://0.0.0.0:%d - modes %s - data in %s' % (scheme, PORT, ','.join(map(str, MODES)), DATA), flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == '__main__': main()