{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c42f8927",
   "metadata": {},
   "source": [
    "# CR54 · ECC doubling and GF(23) worked example\n",
    "\n",
    "For doubling λ=(3x₁²+a)(2y₁)⁻¹ mod p. Use the coordinate formulas with P=Q. If y=0, doubling gives infinity. Add P to 2P to obtain 3P.\n",
    "\n",
    "## Worked calculation\n",
    "GF(17), P=(5,1): numerator=77 mod 17=9, denominator=2, inverse=9, λ=13, 2P=(6,3), 3P=(10,6). GF(23), a=b=1,P=(3,10): 2P=(7,12),3P=(19,5).\n",
    "\n",
    "## Baseline\n",
    "Calculate slopes and coordinates; inspect the two steps on the finite-field plot.\n",
    "\n",
    "## Controlled investigation\n",
    "Change entire domain to p=23,a=b=1,P=(3,10); then GF(17),a=2,b=0,P=(0,0) to inspect infinity.\n",
    "\n",
    "**Evidence:** Slopes, inverses, 2P and 3P, membership and exceptional cases.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept054",
   "source": [
    "## Point doubling and exceptional cases\n",
    "\n",
    "Doubling corresponds to a tangent over real numbers and uses the derivative-derived slope in a prime field. A vertical tangent at y=0 gives infinity.\n",
    "\n",
    "**Mathematical / protocol foundations:** λ=(3x²+a)(2y)⁻¹ mod p. Then x3=λ²−2x, y3=λ(x−x3)−y. For p=23,a=b=1,P=(3,10), numerator=28≡5, denominator=20, inverse=15.\n",
    "\n",
    "**Worked teaching example and interpretation:** λ=75≡6; x3=36−6=30≡7; y3=6(3−7)−10=−34≡12. Verify both sides ≡6. Adding P to 2P gives (19,5), using the secant formula.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "467173c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR54 | Educational algorithm and validation =====\n",
    "# CR54 | ECC doubling and GF(23) worked example\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import math\n",
    "import json\n",
    "\n",
    "def egcd(a,b):\n",
    "    # Track coefficients of a and b alongside the successive remainders.\n",
    "    r,s,t=a,1,0; nr,ns,nt=b,0,1; steps=[]\n",
    "    while nr:\n",
    "        q=r//nr; steps.append({'dividend':r,'divisor':nr,'quotient':q,'remainder':r%nr,'coeff_a':s-q*ns,'coeff_b':t-q*nt})\n",
    "        r,nr=nr,r-q*nr; s,ns=ns,s-q*ns; t,nt=nt,t-q*nt\n",
    "    return r,s,t,steps\n",
    "\n",
    "def inv(a,m):\n",
    "    g,x,_,_=egcd(a%m,m)\n",
    "    if g!=1: raise ValueError('No inverse: gcd is not 1')\n",
    "    return x%m\n",
    "\n",
    "def prime(n):\n",
    "    return n>=2 and all(n%i for i in range(2,math.isqrt(n)+1))\n",
    "\n",
    "def on(P,a,b,p):\n",
    "    return P is None or (isinstance(P,(tuple,list)) and len(P)==2 and all(type(x) is int for x in P) and 0<=P[0]<p and 0<=P[1]<p and (P[1]**2-P[0]**3-a*P[0]-b)%p==0)\n",
    "\n",
    "def ecadd(P,Q,a,b,p):\n",
    "    if not prime(p) or p<5 or (4*a**3+27*b*b)%p==0: raise ValueError('Use a nonsingular curve over a prime > 3')\n",
    "    if not on(P,a,b,p) or not on(Q,a,b,p): raise ValueError('Point not on curve')\n",
    "    if P is None or Q is None: return Q if P is None else P, {'case':'identity','P':P,'Q':Q}\n",
    "    x,y=P; u,v=Q\n",
    "    if x==u and (y+v)%p==0:return None,{'case':'vertical line','P':P,'Q':Q,'result':'infinity'}\n",
    "    num,den=(3*x*x+a,2*y) if P==Q else (v-y,u-x)\n",
    "    di=inv(den,p); slope=num*di%p; X=(slope*slope-x-u)%p;Y=(slope*(x-X)-y)%p\n",
    "    R=(X,Y); assert on(R,a,b,p)\n",
    "    return R,{'P':P,'Q':Q,'numerator':num%p,'denominator':den%p,'inverse':di,'lambda':slope,'x3':X,'y3':Y}\n",
    "\n",
    "DEFAULT={'p': 17, 'a': 2, 'b': 2, 'P': [5, 1]}\n",
    "ALTERNATE={'p': 23, 'a': 1, 'b': 1, 'P': [3, 10]}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    p=params['p']\n",
    "    a=params['a']\n",
    "    b=params['b']\n",
    "    P=params['P']\n",
    "    if not (all(type(x) is int for x in (p,a,b)) and 5<=p<=97 and prime(p) and -997<=a<=997 and -997<=b<=997 and (4*a**3+27*b*b)%p!=0): raise ValueError('Invalid classroom curve or scalar')\n",
    "    P=None if P is None else tuple(P);R,t=ecadd(P,P,a,b,p);S,u=ecadd(R,P,a,b,p);steps=[dict(t,operation='2P'),dict(u,operation='3P')];result={'double':R,'triple':S,'valid':on(R,a,b,p) and on(S,a,b,p)}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"valid\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1843ece",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7354beb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR54 | 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": "5bbd26ef",
   "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": "c4ae7303",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR54 | 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": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR54 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'p': 17, 'a': 2, 'b': 0, 'P': [0, 0]}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "8ee00db1be0ec386"
  },
  {
   "cell_type": "markdown",
   "id": "172c8547",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change entire domain to p=23,a=b=1,P=(3,10); then GF(17),a=2,b=0,P=(0,0) to inspect infinity.\n",
    "\n",
    "Submit Slopes, inverses, 2P and 3P, membership and exceptional cases.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
