{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c1f918b0",
   "metadata": {},
   "source": [
    "# CR55 · ECC scalar multiplication and point order\n",
    "\n",
    "Double-and-add reads scalar bits from least significant. Start at infinity, conditionally add the current point, then double the addend. Point order is the smallest positive t with tP=O, not necessarily group order.\n",
    "\n",
    "## Worked calculation\n",
    "P=(5,1) over GF(17), a=b=2. 3=11₂: add P and 2P to obtain (10,6). P has order 19.\n",
    "\n",
    "## Baseline\n",
    "Record bit, addend and accumulator at every step; verify 3P by direct addition.\n",
    "\n",
    "## Controlled investigation\n",
    "Change k to 13, then 19 and 0 while holding curve and point fixed. Predict infinity results. Compare binary iterations with repeated addition.\n",
    "\n",
    "**Evidence:** k in binary, addends, accumulators, result, order and iteration count.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept055",
   "source": [
    "## Scalar multiplication\n",
    "\n",
    "Scalar multiplication means repeated group addition, not coordinate-wise multiplication. The order of P is the smallest n>0 with nP=O; it divides the group order.\n",
    "\n",
    "**Mathematical / protocol foundations:** Binary double-and-add starts accumulator O and processes powers of two via point doubling, adding selected multiples. 3P=2P+P. For GF(17),a=b=2,P=(5,1), 2P=(6,3).\n",
    "\n",
    "**Worked teaching example and interpretation:** Adding P gives (10,6), as in point addition. Complexity grows with scalar bit length rather than scalar value. Use approved constant-time libraries in real cryptography.\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": "72377788",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR55 | Educational algorithm and validation =====\n",
    "# CR55 | ECC scalar multiplication and point order\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",
    "def ecmul(k,P,a,b,p):\n",
    "    R=None; steps=[]\n",
    "    while k:\n",
    "        bit=k&1\n",
    "        if bit:R,_=ecadd(R,P,a,b,p)\n",
    "        steps.append({'bit':bit,'addend':P,'accumulator':R}); P,_=ecadd(P,P,a,b,p);k//=2\n",
    "    return R,steps\n",
    "\n",
    "DEFAULT={'p': 17, 'a': 2, 'b': 2, 'P': [5, 1], 'k': 3}\n",
    "ALTERNATE={'k': 13}\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",
    "    k=params['k']\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 and type(k) is int and 0<=k<=10000): raise ValueError('Invalid classroom curve or scalar')\n",
    "    if P is None or not on(P,a,b,p): raise ValueError('Finite on-curve point required')\n",
    "    P=tuple(P);R,steps=ecmul(k,P,a,b,p);T=None;order=0\n",
    "    while True:\n",
    "        T,_=ecadd(T,P,a,b,p);order+=1\n",
    "        if T is None:break\n",
    "    if not steps: steps=[{'bit':0,'addend':P,'accumulator':None}]\n",
    "    result={'point':R,'point_order':order,'valid':on(R,a,b,p)}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"valid\"] and ecmul(result[\"point_order\"],P,a,b,p)[0] is None, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "015ee829",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "226c1bbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR55 | 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": "dd04a35d",
   "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": "311eeecb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR55 | 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": [
    "# ===== CR55 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'k': 19}, {'k': 0}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "1a9480b3612c36d5"
  },
  {
   "cell_type": "markdown",
   "id": "08047945",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change k to 13, then 19 and 0 while holding curve and point fixed. Predict infinity results. Compare binary iterations with repeated addition.\n",
    "\n",
    "Submit k in binary, addends, accumulators, result, order and iteration count.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
