/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.) A web server with PHP 7.4 or newer and the openssl extension (mode 3 and the check of the seals) and mbstring. 2.) https for mode 1 and for the app (browsers only post from the app to https). Modes 2 and 3 also work on plain http in your own network. 3.) Your settings below (or as environment variables of the web server): 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: OUTSIDE your web root if you can (else this script puts a "deny all" .htaccess into it - check that nobody can download it) 4.) In the app: LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: the address of this file, the same security mode and the secret. Or Settings -> 🔗 LIMS / ELN FORWARDING: the address and the token (mode 1). ---------------------------------------------------------------------------------------- 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), 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 Apache with PHP-FPM drops the Authorization header? Add to the .htaccess of this folder: CGIPassAuth On (or: RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]) ---------------------------------------------------------------------------------------- */ // ---------- your settings ---------- $MODES = array_map('intval', explode(',', getenv('UPSCALE_MODES') ?: '1,2,3')); $TOKENS = array_filter(array_map('trim', explode(',', getenv('UPSCALE_TOKENS') ?: 'CHANGE-ME-TOKEN'))); $SECRET = getenv('UPSCALE_SECRET') ?: 'CHANGE-ME-SECRET'; $DATA = rtrim(getenv('UPSCALE_DATA') ?: __DIR__ . '/upscale-data', '/'); // 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']; // answer "stored" (the archive receiver): '0' switches it off - then the scale and the app free their entries as without it $STORED = getenv('UPSCALE_STORED') !== '0'; // 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[strtolower($device)] ?? ''; function secret_for($device) { global $SECRET; return $SECRET; } // 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']]; function requests_for($device) { global $DATA; $file = $DATA . '/requests/' . preg_replace('/[^A-Za-z0-9_-]/', '', $device) . '.json'; if(!is_file($file)) {return [];} $list = json_decode((string)file_get_contents($file), true); if(!is_array($list) || !$list) {@unlink($file); return [];} $now = array_slice($list, 0, 4); $rest = array_slice($list, 4); if($rest) {file_put_contents($file, json_encode($rest, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));} else {@unlink($file);} return $now; } // ---------- CORS: the app runs in the browser ---------- $origin = (string)($_SERVER['HTTP_ORIGIN'] ?? ''); header('Access-Control-Allow-Origin: ' . (in_array($origin, $ORIGINS, true) ? $origin : $ORIGINS[0])); header('Vary: Origin'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization'); header('Access-Control-Allow-Private-Network: true'); $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; if($method == 'OPTIONS') {http_response_code(204); exit;} function finish($code, $text = '') { http_response_code($code); header('Content-Type: application/json'); echo $text === '' ? '' : json_encode(['error' => $text]); exit; } function hdr($name) { $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name)); if(isset($_SERVER[$key])) {return (string)$_SERVER[$key];} if($name == 'Authorization' && isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {return (string)$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];} return ''; } function not_set($s) {return $s === '' || strncmp($s, 'CHANGE-ME', 9) == 0;} function log_line($file, $text) { global $DATA; file_put_contents($DATA . '/' . $file, gmdate('Y-m-d\TH:i:s\Z') . ' ' . $text . "\n", FILE_APPEND | LOCK_EX); } function refuse($code, $text) { log_line('receiver.log', $code . ' ' . $text . ' (' . ($_SERVER['REMOTE_ADDR'] ?? '?') . ')'); finish($code, $text); } function json_file($path) { $j = is_file($path) ? json_decode((string)file_get_contents($path), true) : null; return is_array($j) ? $j : []; } // the 12-byte AES-GCM nonce: the 6 bytes of the Device ID (XOR 0xFF for the answer) + n as 6 bytes little-endian function seal_nonce($device, $n, $answer) { $d = hex2bin($device); if($answer) {$d ^= str_repeat("\xFF", 6);} return $d . substr(pack('P', $n), 0, 6); } if($method != 'POST' && $method != 'GET') {finish(405);} $isPoll = ($method == 'GET'); if($isPoll && ($_GET['poll'] ?? '') !== '1') {finish(405);} $raw = $isPoll ? '' : (string)file_get_contents('php://input'); $body = $isPoll ? null : json_decode($raw); // (a number that does not fit a double - 1e400 - makes the body no event, as in the other receivers) if($body !== null && json_encode($body) === false) {$body = null;} // 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;} elseif($isPoll ? isset($_GET['n']) : (is_object($body) && ($body->schema ?? '') === 'upscale.sealed/1')) {$mode = 3;} else {$mode = 1;} if(!in_array($mode, $MODES, true)) {finish(401, 'mode ' . $mode . ' not accepted here');} // (not set up yet: refused without writing anything) if($mode == 1 && !array_filter($TOKENS, function($t) {return !not_set($t);})) {finish(503, 'set UPSCALE_TOKENS');} $device = $isPoll ? (string)($_GET['device'] ?? '') : (string)(is_object($body) ? ($body->device ?? '') : ''); if($mode != 1 && not_set(secret_for($device))) {finish(503, 'set UPSCALE_SECRET');} // ---------- from here on: one request at a time (state files) ---------- foreach(['', '/events', '/state', '/requests'] as $dir) { if(!is_dir($DATA . $dir)) {mkdir($DATA . $dir, 0770, true);} } if(!is_file($DATA . '/.htaccess')) {file_put_contents($DATA . '/.htaccess', "Require all denied\n");} $lock = fopen($DATA . '/state/.lock', 'c'); flock($lock, LOCK_EX); $event = null; $nonce = ''; $n = 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 = strncmp($auth, 'Bearer ', 7) == 0 ? substr($auth, 7) : (hdr('X-API-Key') !== '' ? hdr('X-API-Key') : (string)($_GET['token'] ?? '')); $ok = false; foreach($TOKENS as $t) {if(!not_set($t) && hash_equals($t, $given)) {$ok = true;}} if(!$ok) {refuse(401, 'mode 1: wrong or missing token');} $event = $body; } elseif($mode == 2) { // signature over: time "." nonce "." body (the poll: an empty body) $nonce = hdr('X-Upscale-Nonce'); $want = 'sha256=' . hash_hmac('sha256', hdr('X-Upscale-Time') . '.' . $nonce . '.' . $raw, secret_for($device)); if(!hash_equals($want, hdr('X-Upscale-Signature'))) {refuse(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() - (int)hdr('X-Upscale-Time')) < 300 - but only when the clock of the scale is set.) $event = $body; } else { if(!function_exists('openssl_decrypt')) {refuse(500, 'mode 3 needs the PHP openssl extension');} $n = $isPoll ? (string)($_GET['n'] ?? '') : ($body->n ?? ''); if(!preg_match('/^[0-9a-fA-F]{12}$/', $device) || !preg_match('/^[0-9]{1,15}$/', (string)$n) || (int)$n < 1 || (int)$n > 0xFFFFFFFFFFFF) {refuse(400, 'mode 3: device or n wrong');} // (n: up to 2^48 - a 64-bit integer, never 32-bit) $n = (int)$n; $key = hash('sha256', secret_for($device), true); if($isPoll) { // the poll carries t = the AES-256-GCM tag of an EMPTY text with the nonce of n: checked before n counts $tag = ''; openssl_encrypt('', 'aes-256-gcm', $key, OPENSSL_RAW_DATA, seal_nonce($device, $n, false), $tag, '', 16); if(!hash_equals(bin2hex($tag), strtolower((string)($_GET['t'] ?? '')))) {refuse(401, 'mode 3: poll tag t wrong or missing');} } else { $bin = base64_decode((string)($body->ct ?? ''), true); $plain = ($bin !== false && strlen($bin) > 16) ? openssl_decrypt(substr($bin, 0, -16), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, seal_nonce($device, $n, false), substr($bin, -16)) : false; if($plain === false) {refuse(401, 'mode 3: the envelope does not open');} $event = json_decode($plain); } // replay check (only after the seal or the poll tag was checked): n only goes up. Kept per scale in state/last-n.json. $lastFile = $DATA . '/state/last-n.json'; $last = json_file($lastFile); $dev = strtolower($device); if($n <= ($last[$dev] ?? 0)) {refuse(409, 'mode 3: n ' . $n . ' not higher than ' . ($last[$dev] ?? 0) . ' (replay)');} $last[$dev] = $n; file_put_contents($lastFile, json_encode($last), LOCK_EX); } // ---------- the hash chains of "activity", "legal" and "sales" ---------- // 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"). // bytes from a text: the scale sends base64, the app hex ($size: the length it must have, 0 = any) function hex_or_b64($v, $src, $size) { $v = is_string($v) ? $v : ((is_int($v) || is_float($v)) ? json_encode($v) : ''); $isHex = strlen($v) % 2 == 0 && preg_match('/^[0-9a-fA-F]*$/D', $v); if($isHex && ($size ? strlen($v) == 2 * $size : $src !== 'scale')) {return (string)hex2bin($v);} if(strlen($v) % 4 == 0 && preg_match('#^[A-Za-z0-9+/]*={0,2}$#D', $v)) {$b = base64_decode($v, true); return $b === false ? '' : $b;} return ''; } // a number of a chain entry or a seal field: an integer 0...4294967295 (a JSON number or a text of digits) | null function entry_number($v) { if(is_string($v) && preg_match('/^[0-9]{1,10}$/D', $v)) {$v = (int)$v;} elseif(is_float($v) && is_finite($v) && floor($v) == $v && $v >= 0 && $v <= 4294967295) {$v = (int)$v;} return (is_int($v) && $v >= 0 && $v <= 4294967295) ? $v : null; } // the parts of an activity / legal / sales entry: ['dev', 'type', 'num', 'raw', 'rawok', 'h' (H after it, '' none), 'hb' (H before it: // the app at the start of a piece, '' none), 'alibi', 'no_alibi'] | null: not such an event | a string: why not. The number: an integer // 0...4294967295, else the event is no chain entry ('no number') function entry_parts($ev) { $type = $ev->type ?? ''; $d = $ev->data ?? null; if(($type !== 'activity' && $type !== 'legal' && $type !== 'sales') || !is_object($d)) {return null;} $src = $ev->src ?? ''; $num = entry_number($d->seq ?? ($d->number ?? ($d->no ?? null))); if($num === null) {return 'no number';} $hlen = $type == 'sales' ? 16 : 64; $isH = function($v) use ($hlen) {return is_string($v) && strlen($v) == $hlen && ctype_xdigit($v);}; $h = $isH($d->chain ?? null) ? strtolower($d->chain) : ($isH($d->h ?? null) ? strtolower($d->h) : ''); $hb = $isH($d->hb ?? null) ? strtolower($d->hb) : ''; $alibi = ''; $noAlibi = false; if($type == 'sales') { $raw = hex_or_b64($d->raw ?? '', $src, 0); $rawok = strlen($raw) > 8; if($rawok) {$h = bin2hex(substr($raw, -8));} // (the chain is part of the record) $alibi = hex_or_b64($d->alibi_raw ?? '', $src, 0); // (an alibi number without its bytes: the link can't be computed) $noAlibi = $alibi === '' && isset($d->alibi) && $d->alibi !== '' && $d->alibi !== false && $d->alibi !== 0 && $d->alibi !== 0.0 && $d->alibi !== []; } else { $size = $type == 'activity' ? 16 : 48; $raw = hex_or_b64($d->raw ?? '', $src, $size); $rawok = strlen($raw) == $size; } return ['dev' => ev_device($ev, $d), 'type' => $type, 'num' => $num, 'raw' => $raw, 'rawok' => $rawok, 'h' => $h, 'hb' => $hb, 'alibi' => $alibi, 'no_alibi' => $noAlibi]; } function chain_link($type, $before, $num, $raw, $alibi = '') { if($type == 'sales') {return substr(hash('sha256', hex2bin($before) . substr($raw, 0, -8) . $alibi), 0, 16);} return hash('sha256', hex2bin($before) . ($type == 'activity' ? pack('V', $num) : '') . $raw); } // the H before the first entry of a chain ('' = not the first one) function chain_start($type, $num) { if(($type == 'activity' && $num == 0) || ($type == 'legal' && $num == 1)) {return str_repeat('00', 32);} if($type == 'sales' && $num == 1) {return str_repeat('00', 8);} return ''; } // the Device ID of an event (lower case) function ev_device($ev, $d = null) { $dev = $ev->device ?? null; if(!$dev && is_object($d)) {$dev = $d->device ?? null;} return strtolower(is_scalar($dev) && $dev !== false ? (string)$dev : ''); } function same_hex($a, $b) {return (string)$a !== '' && (string)$b !== '' && hash_equals(strtolower((string)$a), strtolower((string)$b));} function dev_name($dev) {return preg_replace('/[^0-9a-z]/', '', strtolower((string)$dev));} // 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) class Chains { const CHUNK = 256; // entries per state file public $files = []; public $dirty = []; public $snap = []; function path($rel) {global $DATA; return $DATA . '/state/' . $rel;} function &file($p, $watch = false) { if(!array_key_exists($p, $this->files)) { $this->files[$p] = json_file($p); if($watch) {$this->snap[$p] = json_encode($this->files[$p]);} } return $this->files[$p]; } function changed($p) {$this->dirty[$p] = true;} function &keys($dev) {return $this->file($this->path('seal-keys/' . dev_name($dev) . '.json'), true);} function &cps($dev) { $c = &$this->file($this->path('checkpoints/' . dev_name($dev) . '.json'), true); foreach(['signed', 'waiting'] as $k) {if(!isset($c[$k]) || !is_array($c[$k])) {$c[$k] = [];}} return $c; } function &pairs($dev) { $c = &$this->file($this->path('pairs/' . dev_name($dev) . '.json'), true); foreach(['need_entry', 'need_sale'] as $k) {if(!isset($c[$k]) || !is_array($c[$k])) {$c[$k] = [];}} return $c; } function folder($dev, $type) {return 'chain/' . dev_name($dev) . '-' . $type;} function chunk($dev, $type, $num) {return $this->path($this->folder($dev, $type) . '/' . sprintf('%08d', intdiv($num, self::CHUNK)) . '.json');} function get($dev, $type, $num) { if($num < 0) {return null;} $f = &$this->file($this->chunk($dev, $type, $num)); return (isset($f[(string)$num]) && is_array($f[(string)$num])) ? $f[(string)$num] : null; } function put($dev, $type, $num, $e) { $p = $this->chunk($dev, $type, $num); $f = &$this->file($p); $f[(string)$num] = $e; $this->changed($p); $runs = $this->runs($dev, $type); $runs[] = [$num, $num]; usort($runs, function($x, $y) {return ($x[0] <=> $y[0]) ?: ($x[1] <=> $y[1]);}); $merged = []; foreach($runs as $one) { $last = count($merged) - 1; if($last >= 0 && $one[0] <= $merged[$last][1] + 1) {$merged[$last][1] = max($merged[$last][1], $one[1]);} else {$merged[] = [$one[0], $one[1]];} } $rp = $this->path($this->folder($dev, $type) . '/runs.json'); $r = &$this->file($rp); $r['runs'] = $merged; $this->changed($rp); } function runs($dev, $type) { $r = &$this->file($this->path($this->folder($dev, $type) . '/runs.json')); $out = []; foreach((isset($r['runs']) && is_array($r['runs'])) ? $r['runs'] : [] as $x) { if(is_array($x) && count($x) == 2 && isset($x[0], $x[1]) && is_int($x[0]) && is_int($x[1])) {$out[] = [$x[0], $x[1]];} } return $out; } // the newest number kept below num | the oldest above it (null: none) function below($dev, $type, $num) { $best = null; foreach($this->runs($dev, $type) as $one) {if($one[0] < $num) {$best = min($one[1], $num - 1);}} return $best; } function above($dev, $type, $num) { foreach($this->runs($dev, $type) as $one) {if($one[1] > $num) {return max($one[0], $num + 1);}} return null; } function flush() { foreach($this->snap as $p => $was) {if(json_encode($this->files[$p]) !== $was) {$this->dirty[$p] = true;}} $paths = array_keys($this->dirty); sort($paths); foreach($paths as $p) { if(!is_dir(dirname($p))) {mkdir(dirname($p), 0770, true);} $obj = $this->files[$p]; // (every map stays a JSON object, also when it is empty or numbered from 0) if(basename(dirname($p)) == 'checkpoints') { $obj['signed'] = (object)array_map(function($x) {return (object)$x;}, $obj['signed'] ?? []); $obj['waiting'] = (object)($obj['waiting'] ?? []); } elseif(basename(dirname($p)) == 'pairs') { $obj['need_entry'] = (object)array_map(function($x) {return (object)$x;}, $obj['need_entry'] ?? []); $obj['need_sale'] = (object)($obj['need_sale'] ?? []); } file_put_contents($p . '.tmp', json_encode((object)$obj, JSON_UNESCAPED_SLASHES)); rename($p . '.tmp', $p); } $this->dirty = []; } } function ask_text($type, $a) {return $type != 'sales' ? ' (ask for them: {"get":"' . $type . '","since":' . $a . '})' : '';} // does entry $num (kept: $e) follow the H $h? -> true | false | null (not known: no raw entry, a sale without its alibi bytes) function follows_from($type, $h, $num, $e) { if(($e['r'] ?? '') !== '' && empty($e['n'])) {return same_hex(chain_link($type, $h, $num, hex2bin($e['r']), hex2bin($e['a'] ?? '')), $e['h'] ?? '');} if(($e['b'] ?? '') !== '') {return same_hex($e['b'], $h);} return null; } const BROKEN_TEXT = 'BROKEN - the entry or the one before it is not what the chain says'; // 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) function chain_check($ev, $ch) { $p = entry_parts($ev); if($p === null) {return '';} if(is_string($p)) {return $p;} $dev = $p['dev']; $type = $p['type']; $num = $p['num']; $raw = $p['raw']; $rawok = $p['rawok'] && !$p['no_alibi']; $what = $dev . ' ' . $type . ' ' . $num; $prev = $ch->get($dev, $type, $num - 1); $start = chain_start($type, $num); $before = $prev ? $prev['h'] : ($start !== '' ? $start : $p['hb']); $calc = ($before !== '' && $rawok) ? chain_link($type, $before, $num, $raw, $p['alibi']) : ''; $newH = ($calc !== '' && ($p['h'] === '' || same_hex($calc, $p['h']))) ? $calc : $p['h']; $old = $ch->get($dev, $type, $num); $note = ''; $e = null; $broken = ''; if($old && ($old['r'] ?? '') !== '') { if($p['rawok'] && $old['r'] === bin2hex($raw)) { if($p['alibi'] !== '' && !empty($old['n'])) { // (the alibi bytes of a sale kept without them: its own chain bytes must come out of them) if($calc !== '' && !same_hex($calc, $old['h'] ?? '')) { log_line('chain.log', $what . ' CONFLICT - these alibi bytes do not give the chain of the record here'); return 'conflict'; } $e = array_merge($old, ['a' => bin2hex($p['alibi']), 'b' => $calc !== '' ? $before : '']); unset($e['n']); $note = 'alibi bytes added - '; } elseif($p['alibi'] !== '' && ($old['a'] ?? '') !== bin2hex($p['alibi'])) { 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'; } } elseif(!$p['rawok'] && ($p['h'] === '' || same_hex($p['h'], $old['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'; } } elseif($old) { // (an entry kept with its H only) if($newH === '' || same_hex($newH, $old['h'] ?? '')) { if(!$p['rawok']) { log_line('chain.log', $what . ' AGAIN - the same entry is here already'); return 'same'; } $e = array_merge($old, ['r' => bin2hex($raw), 'b' => ($calc !== '' && same_hex($calc, $old['h'] ?? '')) ? $before : '']); if($p['alibi'] !== '') {$e['a'] = bin2hex($p['alibi']);} if($p['no_alibi']) {$e['n'] = 1;} if($calc !== '' && !same_hex($calc, $old['h'] ?? '')) { $broken = BROKEN_TEXT; $e['x'] = 1; } elseif($e['b'] !== '') { unset($e['x']); } } else { $nxt = $ch->get($dev, $type, $num + 1); if(!($calc !== '' && same_hex($calc, $newH) && ($prev || $start !== '') && $nxt && follows_from($type, $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 === null) { $e = ['h' => $newH, 'r' => $p['rawok'] ? bin2hex($raw) : '', 'b' => ($calc !== '' && same_hex($calc, $newH)) ? $before : '']; if($p['alibi'] !== '') {$e['a'] = bin2hex($p['alibi']);} if($p['no_alibi']) {$e['n'] = 1;} if($calc !== '' && !same_hex($calc, $newH)) { $broken = BROKEN_TEXT; $e['x'] = 1; } } if(($e['h'] ?? '') === '') { log_line('chain.log', $what . ' NOT CHECKED - no raw entry and no chain H'); return 'no raw'; } $ch->put($dev, $type, $num, $e); // the entry after it (it came first: this one fills a gap) $nxt = $ch->get($dev, $type, $num + 1); $follows = null; $unchecked = false; if($nxt) { $follows = follows_from($type, $e['h'], $num + 1, $nxt); if($follows) { if(!empty($nxt['x']) || (($nxt['r'] ?? '') !== '' && empty($nxt['n']) && ($nxt['b'] ?? '') !== $e['h'])) { unset($nxt['x']); $nxt['b'] = $e['h']; $ch->put($dev, $type, $num + 1, $nxt); } } elseif($follows === false && !$p['rawok']) { $unchecked = true; // (an entry without raw does not make the one after it broken) } elseif($follows === false) { $nxt['x'] = 1; $ch->put($dev, $type, $num + 1, $nxt); if($broken === '') {$broken = 'BROKEN - entry ' . ($num + 1) . ' does not follow this one';} } } $linked = ($e['b'] ?? '') !== '' && ($prev || $start !== ''); $lo = $ch->below($dev, $type, $num); $hi = $ch->above($dev, $type, $num); $missing = []; if($lo !== null && $lo < $num - 1) {$missing[] = [$lo + 1, $num - 1];} if($hi !== null && $hi > $num + 1) {$missing[] = [$num + 1, $hi - 1];} if($broken !== '') { $state = 'broken'; $text = $broken; } elseif(!$rawok) { $state = 'no raw'; $text = 'NOT CHECKED - ' . ($p['no_alibi'] ? 'no alibi bytes ("alibi_raw")' : 'no raw entry') . ': H noted'; } elseif($hi !== null) { $parts = array_merge($linked ? [$start !== '' ? 'starts the chain' : 'links to ' . ($num - 1)] : [], $follows ? [($num + 1) . ' follows it'] : []); $state = 'filled'; $text = 'FILLED - ' . ($parts ? implode(' and ', $parts) : 'not linked yet'); } elseif($linked) { $state = 'ok'; $text = 'OK'; } elseif($lo !== null) { $state = 'gap'; $text = 'GAP -'; } else { $state = 'first'; $text = 'FIRST - H noted' . (($e['b'] ?? '') !== '' ? ' (checked with the H before it, "hb")' : ''); } if($unchecked) {$text .= ' - ' . ($num + 1) . ' not checked against an entry without raw';} if($missing && in_array($state, ['filled', 'gap', 'broken'], true)) { $ranges = implode(', ', array_map(function($m) {return $m[0] == $m[1] ? (string)$m[0] : $m[0] . '...' . $m[1];}, $missing)); $text .= ($state == 'gap' ? ' ' . $ranges . ' missing' : ' - still missing: ' . $ranges) . ask_text($type, $missing[0][0]); } if(strncmp($note, 'CONFLICT', 8) == 0) {$state = 'conflict';} log_line('chain.log', $what . ' ' . $note . $text); checkpoint_after($ch, $dev, $type, $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']; // (tests only: UPSCALE_TEST_LICENCE_KEY=<130 hex: 04 | x | y> takes the place of both keys - never on a real receiver) if(preg_match('/^04[0-9a-fA-F]{128}$/D', (string)getenv('UPSCALE_TEST_LICENCE_KEY'))) {$LICENCE_KEYS = [1 => strtolower(getenv('UPSCALE_TEST_LICENCE_KEY')), 2 => strtolower(getenv('UPSCALE_TEST_LICENCE_KEY'))];} const SEAL_KINDS = [1 => 'report', 2 => 'file', 3 => 'signature', 4 => 'chain_checkpoint', 5 => 'legal_store']; const SEAL_GOOD = ['certified', 'same_key', 'first_key']; // (only a seal with one of these is taken as a checkpoint) // ECDSA P-256 over SHA-256(data), $pk = x | y (64 bytes), $sig = r | s (64 bytes) -> true | false function ecdsa_ok($pk, $data, $sig) { if(!function_exists('openssl_verify') || strlen($pk) != 64 || strlen($sig) != 64) {return false;} // the key: the raw point as SubjectPublicKeyInfo (PEM) | the signature: r | s as DER $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode(hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200') . "\x04" . $pk), 64, "\n") . "-----END PUBLIC KEY-----\n"; $int = function($b) { $b = ltrim($b, "\0"); if($b === '' || (ord($b[0]) & 0x80)) {$b = "\0" . $b;} return "\x02" . chr(strlen($b)) . $b; }; $seq = $int(substr($sig, 0, 32)) . $int(substr($sig, 32)); return @openssl_verify($data, "\x30" . chr(strlen($seq)) . $seq, $pem, OPENSSL_ALGO_SHA256) === 1; } function unhex($v) { $v = is_string($v) ? $v : ''; return (strlen($v) % 2 == 0 && preg_match('/^[0-9a-fA-F]*$/D', $v)) ? (string)hex2bin($v) : ''; } function seal_parse($seal) { if(strlen($seal) != 144 || ord($seal[0]) != 1) {return null;} $u32 = function($at) use ($seal) {return unpack('V', substr($seal, $at, 4))[1];}; return ['kind' => ord($seal[1]), 'device' => bin2hex(substr($seal, 2, 6)), 'seq' => $u32(8), 'time' => $u32(12), 'number' => $u32(16), 'user' => ord($seal[20]), 'how' => ord($seal[21]), 'sales_upto' => $u32(22), 'sales_chain' => bin2hex(substr($seal, 26, 8)), 'hash' => bin2hex(substr($seal, 42, 32)), 'oldest' => $u32(74)]; } // a seal with its certificate (or the public key that came with it) -> ['res', 'why', 'p', 'cert_id']. res: 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. 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 function seal_verify($seal, $cert, $pk, $ch) { global $LICENCE_KEYS; $p = seal_parse($seal); if(!$p) {return ['res' => 'bad', 'why' => ['format'], 'p' => null, 'cert_id' => ''];} $why = []; $certified = false; $certId = ''; if(strlen($pk) == 65 && ord($pk[0]) == 4) {$pk = substr($pk, 1);} if($cert !== '') { if(strlen($cert) != 144 || !isset($LICENCE_KEYS[ord($cert[0])])) { $why[] = 'cert_format'; } else { $certId = strtoupper(bin2hex(substr($cert, 80, 4))); if(!ecdsa_ok(substr(hex2bin($LICENCE_KEYS[ord($cert[0])]), 1), substr($cert, 0, 80), substr($cert, 80))) {$why[] = 'cert_bad';} elseif(ord($cert[1]) != 1 || bin2hex(substr($cert, 2, 6)) !== $p['device']) {$why[] = 'cert_other';} $certified = !$why; $pk = substr($cert, 16, 64); } } if(strlen($pk) != 64) {return ['res' => 'bad', 'why' => array_merge($why, ['nokey']), 'p' => $p, 'cert_id' => $certId];} if(!ecdsa_ok($pk, substr($seal, 0, 80), substr($seal, 80))) {$why[] = 'signature';} if($why) {return ['res' => 'bad', 'why' => $why, 'p' => $p, 'cert_id' => $certId];} $dev = $p['device']; $hex = bin2hex($pk); $pin = &$ch->keys($dev); if($certified) { if(($pin['pk'] ?? '') !== $hex) { if(($pin['pk'] ?? '') !== '') { log_line('chain.log', $dev . ' SEAL KEY CHANGED - a new key, confirmed by UP-SCALE (certificate ' . $certId . '): noted'); if(empty($pin['certified'])) {drop_uncertified($ch, $dev);} } $pin = ['pk' => $hex, 'certified' => true, 'at' => gmdate('Y-m-d\TH:i:s\Z')]; } elseif(empty($pin['certified'])) { $pin['certified'] = true; } return ['res' => 'certified', 'why' => [], 'p' => $p, 'cert_id' => $certId]; } if(($pin['pk'] ?? '') === '') { $pin = ['pk' => $hex, 'certified' => false, 'at' => gmdate('Y-m-d\TH:i:s\Z')]; return ['res' => 'first_key', 'why' => [], 'p' => $p, 'cert_id' => $certId]; } return ['res' => $pin['pk'] === $hex ? 'same_key' : 'key_changed', 'why' => [], 'p' => $p, 'cert_id' => $certId]; } // a key confirmed by UP-SCALE replaced a key without a certificate: the checkpoints of seals without a certificate go function drop_uncertified($ch, $dev) { $cps = &$ch->cps($dev); $types = array_keys($cps['signed']); sort($types); foreach($types as $type) { $cp = $cps['signed'][$type]; if(($cp['seal'] ?? '') !== 'certified') { unset($cps['signed'][$type]); log_line('chain.log', $dev . ' ' . $type . ' SIGNED up to ' . ($cp['upto'] ?? '') . ' dropped - its seal had no certificate and another key than the one confirmed by UP-SCALE'); } } foreach(array_keys($cps['waiting']) as $type) { $cps['waiting'][$type] = array_values(array_filter(is_array($cps['waiting'][$type]) ? $cps['waiting'][$type] : [], function($w) {return ($w['seal'] ?? '') === 'certified';})); } } const 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']; function seal_line($dev, $what, $r) { log_line('chain.log', $dev . ' SEAL ' . $what . ' ' . str_replace('%s', $r['res'] == 'certified' ? $r['cert_id'] : implode(', ', $r['why']), SEAL_TEXT[$r['res']])); } // 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 // (null: $top itself is not linked) function covered_down($ch, $dev, $type, $top) { $low = null; $k = $top; for(;;) { $e = $ch->get($dev, $type, $k); if(!$e || ($e['b'] ?? '') === '' || !empty($e['x'])) {return $low;} $low = $k; if(chain_start($type, $k) !== '') {return $low;} $p = $ch->get($dev, $type, $k - 1); if(!$p || !same_hex($p['h'] ?? '', $e['b'])) {return $low;} $k--; } } // 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 function checkpoint($ch, $dev, $type, $upto, $h, $info) { $cps = &$ch->cps($dev); $what = $dev . ' ' . $type; $e = $ch->get($dev, $type, $upto); if(!$e) { $waiting = array_values(array_filter($cps['waiting'][$type] ?? [], function($w) use ($upto) {return ($w['upto'] ?? null) != $upto;})); $waiting[] = array_merge($info, ['upto' => $upto, 'h' => $h]); usort($waiting, function($x, $y) {return (($x['log_seq'] ?? 0) <=> ($y['log_seq'] ?? 0)) ?: (($x['upto'] ?? 0) <=> ($y['upto'] ?? 0));}); $cps['waiting'][$type] = array_slice($waiting, -8); log_line('chain.log', $what . ' CHECKPOINT ' . $upto . ' WAITING - entry ' . $upto . ' is not here yet'); return 'waiting'; } if(!same_hex($e['h'] ?? '', $h)) { log_line('chain.log', $what . ' CHECKPOINT ' . $upto . ' DIFFERS - BROKEN: the scale signed another H after ' . $upto . ' than the entries here'); return 'differs'; } $low = covered_down($ch, $dev, $type, $upto); $cur = $cps['signed'][$type] ?? null; $newCert = $info['seal'] === 'certified'; $curCert = $cur && ($cur['seal'] ?? '') === 'certified'; if(!$cur || ($newCert && !$curCert) || ($newCert == $curCert && $upto >= ($cur['upto'] ?? 0))) { $cps['signed'][$type] = array_merge($info, ['upto' => $upto, 'h' => $h, 'from' => $low !== null ? $low : $upto + 1, 'at' => gmdate('Y-m-d\TH:i:s\Z')]); } log_line('chain.log', $what . ' SIGNED up to ' . $upto . ' (' . ($low !== null ? $low . '...' . $upto . ' covered by the signature' : 'not linked yet: nothing covered') . ')'); return 'signed'; } // 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) function checkpoint_after($ch, $dev, $type, $num) { $cps = &$ch->cps($dev); foreach(array_filter($cps['waiting'][$type] ?? [], function($w) use ($num) {return ($w['upto'] ?? null) == $num;}) as $w) { $cps['waiting'][$type] = array_values(array_filter($cps['waiting'][$type], function($x) use ($num) {return ($x['upto'] ?? null) != $num;})); $info = $w; unset($info['upto'], $info['h']); checkpoint($ch, $dev, $type, $num, $w['h'], $info); } $cp = $cps['signed'][$type] ?? null; if($cp && $cp['from'] - 2 <= $num && $num < $cp['from']) { $top = $ch->get($dev, $type, $cp['upto']); if(!$top || !same_hex($top['h'] ?? '', $cp['h'])) { log_line('chain.log', $dev . ' ' . $type . ' CHECKPOINT ' . $cp['upto'] . ' DIFFERS - the entry here has another H than the signed one'); return; } $low = covered_down($ch, $dev, $type, min($cp['from'], $cp['upto'])); if($low !== null && $low < $cp['from']) { $cps['signed'][$type]['from'] = $low; log_line('chain.log', $dev . ' ' . $type . ' SIGNED up to ' . $cp['upto'] . ' - covers ' . $low . '...' . $cp['upto'] . ' now'); } } } // a 'sealed' event: the seal checked by itself (signature, certificate, device), kind 4 / 5 against the chains -> fields for _rx function seal_event($ev, $ch) { $d = $ev->data ?? null; $dev = ev_device($ev); if(!is_object($d)) {return [];} $r = seal_verify(unhex($d->seal ?? ''), unhex($d->cert ?? ''), unhex($d->pk ?? ''), $ch); $p = $r['p']; $rx = []; if($p) { if($dev !== '' && $dev != 'unknown' && $p['device'] !== $dev) {$r['why'][] = 'device';} foreach([['kind', $p['kind']], ['log_seq', $p['seq']], ['number', $p['number']]] as $kv) { if(property_exists($d, $kv[0]) && entry_number($d->{$kv[0]}) !== $kv[1]) {$r['why'][] = $kv[0];} } if(in_array($p['kind'], [1, 2, 3], true) && is_string($d->sha256 ?? null) && preg_match('/^[0-9a-fA-F]{64}$/D', $d->sha256) && strtolower($d->sha256) !== $p['hash']) {$r['why'][] = 'hash';} if($r['why']) {$r['res'] = 'bad';} } seal_line($dev !== '' ? $dev : '?', $p ? (SEAL_KINDS[$p['kind']] ?? 'kind ' . $p['kind']) . ' log ' . $p['seq'] : '?', $r); $rx['seal'] = $r['res']; if($r['why']) {$rx['seal_why'] = implode(',', $r['why']);} if($p && ($p['kind'] == 4 || $p['kind'] == 5)) { $heads = $p['kind'] == 4 ? array_merge([['activity', $p['number'], $p['hash']]], $p['sales_upto'] ? [['sales', $p['sales_upto'], $p['sales_chain']]] : []) : [['legal', $p['number'], $p['hash']]]; if(in_array($r['res'], SEAL_GOOD, true)) { $info = ['log_seq' => $p['seq'], 'time' => $p['time'], 'seal' => $r['res']]; if($p['kind'] == 5) {$info['oldest'] = $p['oldest'];} $rx['checkpoint'] = []; foreach($heads as $one) {$rx['checkpoint'][$one[0]] = checkpoint($ch, $p['device'], $one[0], $one[1], $one[2], $info);} } else { foreach($heads as $one) {log_line('chain.log', $p['device'] . ' ' . $one[0] . ' CHECKPOINT ' . $one[1] . ' not checked - the seal is ' . $r['res']);} $rx['checkpoint'] = 'not checked'; } } return $rx; } // 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 function file_seal($ev, $ch) { $d = $ev->data ?? null; if(!is_object($d) || empty($d->content_base64) || !is_string($d->content_base64)) {return [];} $text = base64_decode($d->content_base64, true); if($text === false || !mb_check_encoding($text, 'UTF-8')) {return ['file' => 'not matched'];} $first = function($hay, $needle, $with) {$at = strpos($hay, $needle); return $at === false ? $hay : substr_replace($hay, $with, $at, strlen($needle));}; if(preg_match('/,\n "seal": (\{[^\n]*\})\n\}\s*$/D', $text, $m, PREG_OFFSET_CAPTURE)) { $field = json_decode($m[1][0]); if(!is_object($field)) {return ['file' => 'no seal'];} $str = function($v) {return is_string($v) ? $v : '';}; $seal = $str($field->seal ?? ''); $cert = $str($field->cert ?? ''); $pk = $str($field->pk ?? ''); $plain = substr($text, 0, $m[0][1]) . "\n}"; } elseif(preg_match('/
]*)>[\s\S]*?<\/div>/', $text, $tag)) { $attr = function($k) use ($tag) {return preg_match('/data-' . $k . '="([0-9a-f]*)"/', $tag[1], $a) ? $a[1] : '';}; $seal = $attr('seal'); $cert = $attr('cert'); $pk = $attr('pk'); $plain = $text; if(preg_match('/[0-9a-f]{16}<\/span>/', $text, $code)) {$plain = $first($plain, $code[0], '0000000000000000');} if(preg_match('/
[\s\S]*?<\/div>/', $text, $block)) {$plain = $first($plain, $block[0], '
');} $plain = $first($plain, $tag[0], '
'); } else { return ['file' => 'no seal']; } if($seal === '') {return ['file' => 'no seal'];} $r = seal_verify(unhex($seal), unhex($cert), unhex($pk), $ch); $p = $r['p']; $dev = ev_device($ev); $match = $p && hash('sha256', $plain) === $p['hash']; if($p && !$match) {$r['why'][] = 'hash';} if($p && $dev !== '' && $dev != 'unknown' && $p['device'] !== $dev) {$r['why'][] = 'device';} if($r['why']) {$r['res'] = 'bad';} seal_line($dev !== '' ? $dev : '?', 'in file ' . (is_string($d->file ?? null) && $d->file !== '' ? $d->file : '?'), $r); $rx = ['file' => $match ? 'match' : 'differs', 'seal' => $r['res']]; if($r['why']) {$rx['seal_why'] = implode(',', $r['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) const 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) const PAIR_PRINT_S = 10; // the time of the print line against the entry (both the clock of the scale) const PAIR_KEEP = 1000; function legal_no($text) { return (is_string($text) && preg_match('/^UP-([0-9]{1,10})$/D', $text, $m)) ? entry_number($m[1]) : null; } // 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) function day_epoch($day, $secs, $tz) { if(!is_string($day) || !preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/D', $day, $m)) {return null;} $y = (int)$m[1]; $mo = (int)$m[2]; $d = (int)$m[3]; if($mo <= 2) {$y--;} $era = intdiv($y, 400); $yoe = $y - $era * 400; $doy = intdiv(153 * ($mo + ($mo > 2 ? -3 : 9)) + 2, 5) + $d - 1; $doe = $yoe * 365 + intdiv($yoe, 4) - intdiv($yoe, 100) + $doy; return ($era * 146097 + $doe - 719468) * 86400 + $secs - $tz * 60; } function u32_at($b, $at) {return unpack('V', substr($b, $at, 4))[1];} function f32_at($b, $at) {return unpack('g', substr($b, $at, 4))[1];} // the pair data of a sales event (its record with a LEGAL MODE alibi) or a print event -> array | null function pair_info($ev, $p) { $d = $ev->data ?? null; if(is_array($p) && $p['type'] == 'sales') { $raw = $p['raw']; $n = legal_no($p['alibi'] !== '' ? $p['alibi'] : ($d->alibi ?? null)); if(strlen($raw) != 76 || $n === null) {return null;} $tz = unpack('v', substr($raw, 65, 2))[1]; if($tz >= 32768) {$tz -= 65536;} $secs = ord($raw[4]) | (ord($raw[5]) << 8) | (ord($raw[6]) << 16); return ['what' => 'sale', 'num' => $p['num'], 'n' => $n, 'ref' => u32_at($raw, 0), 'v' => bin2hex(substr($raw, 11, 4)), 'time' => $tz != 0x7FFF ? day_epoch($d->day ?? null, $secs, $tz) : null]; } if(($ev->type ?? '') === 'print' && is_object($d)) { $n = legal_no($d->legal ?? null); $raw = hex_or_b64($d->raw ?? '', $ev->src ?? '', 16); if($n === null || strlen($raw) != 16) {return null;} return ['what' => 'print', 'num' => entry_number($d->seq ?? null), 'n' => $n, 'v' => bin2hex(substr($raw, 8, 4)), 'time' => u32_at($raw, 0)]; } return null; } // a sale / print against its entry -> [the fields that differ, a note] function pair_compare($info, $raw) { $sale = $info['what'] == 'sale'; $why = []; if(ord($raw[8]) != ($sale ? 1 : 8)) {$why[] = 'kind';} if($sale && u32_at($raw, 44) != $info['ref']) {$why[] = 'sale_id';} $a = f32_at($raw, 40); $b = f32_at(hex2bin($info['v']), 0); if(!($a == $b || ($sale && $b == 0 && $a <= 0))) {$why[] = $sale ? 'grams' : 'value';} // (a sale books 0 for a value below 0) if(!isset($info['time'])) {return [$why, ' (time not compared)'];} if(abs(u32_at($raw, 4) - $info['time']) > ($sale ? PAIR_SALE_S : PAIR_PRINT_S)) {$why[] = 'time';} return [$why, '']; } function keep_newest(&$m) { if(count($m) <= PAIR_KEEP) {return;} ksort($m, SORT_NUMERIC); $m = array_slice($m, -PAIR_KEEP, null, true); } // a sale / print with its LEGAL MODE number against the entry kept -> linked | MISMATCH | waiting | entry missing function pair_check($ch, $dev, $info) { $pairs = &$ch->pairs($dev); $n = $info['n']; $what = $dev . ' ' . ($info['what'] == 'sale' ? 'sales' : 'print') . ' ' . ($info['num'] === null ? 'null' : $info['num']) . ' PAIR UP-' . sprintf('%06d', $n); $e = $ch->get($dev, 'legal', $n); if($e && ($e['r'] ?? '') !== '' && empty($e['x'])) { unset($pairs['need_entry'][(string)$n]); if($info['what'] == 'sale') {unset($pairs['need_sale'][(string)$n]);} list($why, $note) = pair_compare($info, hex2bin($e['r'])); if($why) { log_line('chain.log', $what . ' MISMATCH ' . implode(',', $why) . ' - the entry says something else than the ' . $info['what']); return 'MISMATCH ' . implode(',', $why); } log_line('chain.log', $what . ' linked' . $note); return 'linked' . $note; } $cps = &$ch->cps($dev); $oldest = $cps['signed']['legal']['oldest'] ?? null; if(($e && !empty($e['x'])) || (!$e && is_int($oldest) && $n < $oldest)) { log_line('chain.log', $what . ' entry missing - ' . ($e ? 'the entry is BROKEN in the chain' : 'below the oldest entry kept on the scale')); return 'entry missing'; } $pairs['need_entry'][(string)$n] = $info; keep_newest($pairs['need_entry']); log_line('chain.log', $what . ' WAITING - entry ' . $n . ' is not here yet'); return 'waiting'; } // a LEGAL MODE entry just kept: the sale / print waiting for it, or (kind 1) wait for its sale -> the result for _rx | '' function pair_legal($ch, $dev, $num) { $e = $ch->get($dev, 'legal', $num); if(!$e || ($e['r'] ?? '') === '' || !empty($e['x'])) {return '';} $pairs = &$ch->pairs($dev); $info = $pairs['need_entry'][(string)$num] ?? null; if(is_array($info)) {return pair_check($ch, $dev, $info);} $raw = hex2bin($e['r']); if(ord($raw[8]) == 1) { $ref = u32_at($raw, 44); $pairs['need_sale'][(string)$num] = $ref; keep_newest($pairs['need_sale']); log_line('chain.log', $dev . ' legal ' . $num . ' PAIR WAITING - its sale (id ' . $ref . ') is not here yet'); return 'waiting'; } return ''; } // ---------- a repeated id: the same content? ---------- // the event as one fixed text (keys sorted, numbers in one form) - the same in the three receivers function canon($v) { if(is_object($v)) { $a = get_object_vars($v); ksort($a, SORT_STRING); $out = []; foreach($a as $k => $x) {$out[] = canon((string)$k) . ':' . canon($x);} return '{' . implode(',', $out) . '}'; } if(is_array($v)) {return '[' . implode(',', array_map('canon', $v)) . ']';} if($v === null) {return 'null';} if(is_bool($v)) {return $v ? 'true' : 'false';} if(is_int($v) || is_float($v)) { if(is_float($v) && !is_finite($v)) {return 'null';} if(floor((float)$v) == (float)$v && abs((float)$v) < 1e15) {return (string)(int)$v;} $m = explode('e', sprintf('%.16e', (float)$v)); return $m[0] . 'e' . (int)$m[1]; } return json_encode((string)$v, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS); } // 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) function content_digest($ev) { $p = entry_parts($ev); if(is_array($p) && $p['rawok']) {return hash('sha256', $p['type'] . '|' . $p['num'] . '|' . $p['raw']);} $d = $ev->data ?? null; if(($ev->type ?? '') === 'sealed' && is_object($d) && strlen(unhex($d->seal ?? '')) == 144) {return hash('sha256', 'sealed|' . unhex($d->seal));} $rest = clone $ev; unset($rest->sent_at, $rest->env, $rest->_rx); return hash('sha256', canon($rest)); } // ---------- 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' => true while 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. function stored_step($ev, &$marks, $fresh) { $p = entry_parts($ev); if(!is_array($p) || $p['type'] == 'sales') {return null;} $type = $p['type']; $num = $p['num']; $raw = $p['raw']; $h = $p['h']; $hb = $p['hb'] !== '' ? $p['hb'] : chain_start($type, $num); $key = $p['dev'] . ':' . $type; $m = $marks[$key] ?? null; if(!$p['rawok'] || ($h === '' && $hb === '')) {return $m;} if($m && $num == $m['num'] + 1 && ($hb === '' || same_hex($hb, $m['h']))) { $calc = chain_link($type, $m['h'], $num, $raw); $marks[$key] = ($h === '' || hash_equals($calc, $h)) ? ['num' => $num, 'h' => $calc] : ['num' => $num, 'h' => $h, 'base' => true]; } elseif($fresh && (!$m || $num <= $m['num'] + 1)) { $calc = $hb !== '' ? chain_link($type, $hb, $num, $raw) : ''; if($calc !== '' && ($h === '' || hash_equals($calc, $h))) {$marks[$key] = ['num' => $num, 'h' => $calc];} elseif($h !== '') {$marks[$key] = ['num' => $num, 'h' => $h, 'base' => true];} } return $marks[$key] ?? null; } // the event as one line into events//.jsonl (on the disk before the answer; fsync: PHP 8.1+) -> the line function store_line($type, $event) { global $DATA; $line = json_encode($event, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if(!is_dir($DATA . '/events/' . $type)) {mkdir($DATA . '/events/' . $type, 0770, true);} $f = fopen($DATA . '/events/' . $type . '/' . gmdate('Y-m-d') . '.jsonl', 'a'); $written = ($line !== false && $f !== false && flock($f, LOCK_EX) && fwrite($f, $line . "\n") === strlen($line) + 1 && fflush($f)); if($written && function_exists('fsync')) {$written = fsync($f);} if($f !== false) {flock($f, LOCK_UN); fclose($f);} if(!$written) {refuse(500, 'could not store');} return $line; } // ---------- store the event ---------- $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 = !$isPoll && (!is_object($event) || empty($event->id) || !is_string($event->id) || empty($event->type)); if($bad) { log_line('receiver.log', '400 not an event (' . ($_SERVER['REMOTE_ADDR'] ?? '?') . ')'); if($mode == 1) {finish(400, 'not an event');} $status = 400; $answer = ['error' => 'not an event']; } elseif(!$isPoll) { $type = preg_replace('/[^a-z0-9_-]/', '', strtolower((string)$event->type)) ?: '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 = hash('sha256', $event->id); $marker = $DATA . '/state/seen/' . $type . '/' . substr($hid, 0, 2) . '/' . $hid; $fresh = false; if($type != 'weight' && is_file($marker)) { $seen = explode("\n", (string)file_get_contents($marker)); $ref = trim($seen[0]); $was = trim($seen[1] ?? ''); if($was !== '' && !hash_equals($was, content_digest($event))) { $text = 'CONFLICT ' . $event->id . ' - came again with other content (the first one: ' . $ref . ')'; log_line('chain.log', $text); log_line('receiver.log', $text . ' (' . ($_SERVER['REMOTE_ADDR'] ?? '?') . ')'); $event->_rx = (object)['at' => gmdate('Y-m-d\TH:i:s\Z'), 'mode' => $mode, 'conflict' => $ref]; store_line($type, $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 = new Chains(); $rx = ['at' => gmdate('Y-m-d\TH:i:s\Z'), '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 = in_array($rx['chain'], ['ok', 'filled', 'gap', 'first', 'broken', 'no raw'], true); $pair = ''; if(($kept && $type == 'sales') || $type == 'print') { $info = pair_info($event, $p); if($info) {$pair = pair_check($ch, is_array($p) ? $p['dev'] : ev_device($event), $info);} } elseif($kept && $type == 'legal') { $pair = pair_legal($ch, $p['dev'], $p['num']); } if($pair !== '') {$rx['pair'] = $pair;} if($type == 'sealed') {$rx = array_merge($rx, seal_event($event, $ch));} elseif($type == 'sealed_file' || $type == 'programs') {$rx = array_merge($rx, file_seal($event, $ch));} $event->_rx = (object)$rx; // (no 2xx without a stored event: the scale sends it again; on the disk before "stored" may name it) $line = store_line($type, $event); $fresh = true; $ch->flush(); // your receipt (max. 36 characters): here the day + the start of the SHA-256 of the stored line $ref = gmdate('Ymd') . '-' . substr(hash('sha256', $line), 0, 16); if($type != 'weight') { if(!is_dir(dirname($marker))) {mkdir(dirname($marker), 0770, true);} file_put_contents($marker, $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) { $marksFile = $DATA . '/state/stored-marks.json'; $marks = json_file($marksFile); $was = json_encode($marks); $m = stored_step($event, $marks, $fresh); if(json_encode($marks) !== $was) {file_put_contents($marksFile, json_encode($marks), LOCK_EX);} if($m && empty($m['base'])) {$answer['stored'] = ['type' => $type, '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(!$bad && ($isPoll || $mode != 1 || ($event->src ?? '') === 'scale')) { $req = requests_for($device); if($req) {$answer['requests'] = $req;} } flock($lock, LOCK_UN); // ---------- the answer: signed (mode 2) or sealed (mode 3) ---------- $out = json_encode((object)$answer, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); http_response_code($status); header('Content-Type: application/json'); if($mode == 2) { $t = (string)time(); header('X-Upscale-Time: ' . $t); header('X-Upscale-Nonce: ' . $nonce); header('X-Upscale-Signature: sha256=' . hash_hmac('sha256', $t . '.' . $nonce . '.' . $out, secret_for($device))); } elseif($mode == 3) { $tag = ''; $ct = openssl_encrypt($out, 'aes-256-gcm', hash('sha256', secret_for($device), true), OPENSSL_RAW_DATA, seal_nonce($device, $n, true), $tag, '', 16); $out = json_encode(['schema' => 'upscale.sealed/1', 'n' => $n, 'ct' => base64_encode($ct . $tag)], JSON_UNESCAPED_SLASHES); // (never \/ in the base64) } echo $out;