{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "13af5ccb",
   "metadata": {},
   "source": [
    "# CR85 · Replay cache, sequence and timestamp checks\n",
    "\n",
    "Freshness requires receiver state. A nonce cache rejects duplicates; a timestamp window rejects stale messages and assumes clock synchronization. The model assumes tag verification precedes freshness checks.\n",
    "\n",
    "Foundational concepts; prerequisite: CR84.\n",
    "\n",
    "**Scope:** Freshness model assumes authenticated inputs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept085",
   "source": [
    "## Replay prevention\n",
    "\n",
    "Replay means reusing a previously valid message. Integrity verification detects changes but does not by itself establish freshness. Sequence counters, nonce caches and timestamps have different persistence and clock assumptions.\n",
    "\n",
    "**Mathematical / protocol foundations:** A sample acceptance predicate is valid tag AND sequence>last AND nonce not seen. Commit state only after checks. Timestamp windows require clock policy and replay cache within the window.\n",
    "\n",
    "**Worked teaching example and interpretation:** With last sequence 2, a valid message at 3 can be accepted once; replay at 3 fails. An invalid tag at 100 must not update the state. Real systems need atomic state and reset handling.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network85",
   "metadata": {},
   "source": [
    "## Replay rejection and clock boundaries\n",
    "\n",
    "This model uses an inclusive symmetric clock-skew window and a single authenticated synthetic nonce. A nonce is recorded after a valid first request. Cache resets between independent runs; a real cache must be durable or scoped to authenticated sessions, and entries should expire consistently with the replay window."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41465d8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR85 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR85\n",
    "# Experiment: replay cache sequence and timestamp checks\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR85 | Replay cache, sequence and timestamp checks\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'now': 100, 'timestamp': 98, 'window': 5}\n",
    "ALTERNATE={'timestamp': 90}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    now=params['now']\n",
    "    timestamp=params['timestamp']\n",
    "    window=params['window']\n",
    "    if any(type(x) is not int or not 0 <= x <= 1000000 for x in (now,timestamp,window)):\n",
    "        raise ValueError('Invalid classroom input')\n",
    "    seen=set();steps=[];nonce='classroom-1'\n",
    "    for attempt in range(2):\n",
    "        timely=abs(now-timestamp)<=window;fresh=nonce not in seen;accepted=timely and fresh\n",
    "        if accepted:seen.add(nonce)\n",
    "        steps.append({'attempt':attempt+1,'age':now-timestamp,'within_window':timely,'nonce_unused':fresh,'accepted':accepted})\n",
    "    result={'first':steps[0]['accepted'],'second':steps[1]['accepted']}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"first\"]==(abs(now-timestamp)<=window) and not result[\"second\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5120d04d",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db664013",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR85 | Execute the baseline =====\n",
    "# ===== Execute the baseline =====\n",
    "# Run the default worked example; inspect the intermediate states in order.\n",
    "baseline=run()\n",
    "for step in baseline[\"steps\"]: print(step)\n",
    "print(\"Result:\",baseline[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83d8f1d4",
   "metadata": {},
   "source": [
    "## Controlled comparison\n",
    "Change the indicated input; leave other inputs unchanged. A baseline is the reference run. A mathematical verification substitutes the result back into its defining equation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3208aa5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR85 | Compare the specified alternative =====\n",
    "# ===== Compare the specified alternative =====\n",
    "# Override only the chosen input(s), leaving remaining parameters at baseline.\n",
    "comparison=run(ALTERNATE)\n",
    "for step in comparison[\"steps\"]: print(step)\n",
    "print(\"Result:\",comparison[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fbefb78",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "Set now=100 and window=5. Test timestamps 94, 95, 100, 105 and 106. Record signed age, time-window decision and both replay attempts. Explain why the cache is committed only after acceptance and why clock checks alone cannot stop reuse.\n",
    "\n",
    "This model uses an inclusive symmetric clock-skew window and a single authenticated synthetic nonce. A nonce is recorded after a valid first request. Cache resets between independent runs; a real cache must be durable or scoped to authenticated sessions, and entries should expire consistently with the replay window."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}