<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Arithmetic Algorithms v1.0 - ClockinChain Big Integer Specifications</title>
<!-- Custom HTML head -->
<meta name="description" content="Normative specifications for ClockinChain big integer arithmetic">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item affix "><a href="index.html">Introduction</a></li><li class="chapter-item affix "><li class="part-title">Specifications</li><li class="chapter-item "><a href="representation.html"><strong aria-hidden="true">1.</strong> Big Integer Representation v1.0</a></li><li class="chapter-item expanded "><a href="arithmetic.html" class="active"><strong aria-hidden="true">2.</strong> Arithmetic Algorithms v1.0</a></li><li class="chapter-item "><a href="montgomery.html"><strong aria-hidden="true">3.</strong> Montgomery & Modular Exponentiation v1.0</a></li><li class="chapter-item "><a href="gas.html"><strong aria-hidden="true">4.</strong> Gas Schedule v1.0</a></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">ClockinChain Big Integer Specifications</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/olyntar-labs/clock-bigint" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/olyntar-labs/clock-bigint/edit/main/src/arithmetic.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="arithmetic-algorithm-specification-v10"><a class="header" href="#arithmetic-algorithm-specification-v10">Arithmetic Algorithm Specification v1.0</a></h1>
<h2 id="overview"><a class="header" href="#overview">Overview</a></h2>
<p>This specification defines the normative algorithms for all big integer arithmetic operations in the ClockinChain ecosystem. All algorithms must execute in constant time and produce deterministic results.</p>
<h2 id="1-common-conventions"><a class="header" href="#1-common-conventions">1. Common Conventions</a></h2>
<h3 id="11-limb-operations"><a class="header" href="#11-limb-operations">1.1 Limb Operations</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Basic limb arithmetic with carry/borrow
fn limb_add_carry(a: Limb, b: Limb, carry: Limb) -> (Limb, Limb) {
let sum = a as u128 + b as u128 + carry as u128;
(sum as Limb, (sum >> 64) as Limb)
}
fn limb_sub_borrow(a: Limb, b: Limb, borrow: Limb) -> (Limb, Limb) {
let diff = a as i128 - b as i128 - borrow as i128;
(diff as Limb, if diff < 0 { 1 } else { 0 })
}
fn limb_mul_wide(a: Limb, b: Limb) -> (Limb, Limb) {
let product = a as u128 * b as u128;
(product as Limb, (product >> 64) as Limb)
}
<span class="boring">}</span></code></pre></pre>
<h3 id="12-fixed-loop-rule"><a class="header" href="#12-fixed-loop-rule">1.2 Fixed Loop Rule</a></h3>
<p><strong>All algorithms MUST iterate over full declared limb length:</strong></p>
<ul>
<li>Never exit loops early</li>
<li>Mask carries instead of branching</li>
<li>Use constant-time condition selection</li>
<li>Fixed execution paths regardless of input values</li>
</ul>
<h3 id="13-algorithm-selection"><a class="header" href="#13-algorithm-selection">1.3 Algorithm Selection</a></h3>
<p>Operations choose algorithms based on <strong>public parameters only</strong> (limb length), never secret values.</p>
<h2 id="2-addition-algorithm"><a class="header" href="#2-addition-algorithm">2. Addition Algorithm</a></h2>
<h3 id="21-function-signature"><a class="header" href="#21-function-signature">2.1 Function Signature</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn add(a: &BigInt, b: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="22-precondition"><a class="header" href="#22-precondition">2.2 Precondition</a></h3>
<ul>
<li><code>a</code> and <code>b</code> have equal limb length <code>n</code></li>
<li>If dynamic-length, caller ensures sufficient capacity</li>
</ul>
<h3 id="23-algorithm"><a class="header" href="#23-algorithm">2.3 Algorithm</a></h3>
<pre><code>For i = 0 .. n-1:
(sum_i, carry) = adc(a.limbs[i], b.limbs[i], carry)
c.limbs[i] = sum_i
After final limb:
If carry = 1:
If dynamic-length → append new limb = 1
If fixed-length → overflow trap
</code></pre>
<h3 id="24-constant-time-adc"><a class="header" href="#24-constant-time-adc">2.4 Constant-Time adc</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>sum = x + y + carry
carry_out = (sum < x) OR ((carry == 1) AND (sum == x))
<span class="boring">}</span></code></pre></pre>
<p>No branches allowed.</p>
<h3 id="25-sign-handling"><a class="header" href="#25-sign-handling">2.5 Sign Handling</a></h3>
<ul>
<li>Same sign: <code>sign(c) = sign(a)</code></li>
<li>Different signs: invoke subtraction algorithm</li>
</ul>
<h3 id="26-gas-cost"><a class="header" href="#26-gas-cost">2.6 Gas Cost</a></h3>
<p><code>G_add(n) = 3n</code></p>
<h2 id="3-subtraction-algorithm"><a class="header" href="#3-subtraction-algorithm">3. Subtraction Algorithm</a></h2>
<h3 id="31-function-signature"><a class="header" href="#31-function-signature">3.1 Function Signature</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn sub(a: &BigInt, b: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="32-algorithm-magnitude"><a class="header" href="#32-algorithm-magnitude">3.2 Algorithm (Magnitude)</a></h3>
<pre><code>For i = 0 .. n-1:
(diff_i, borrow) = sbb(a.limbs[i], b.limbs[i], borrow)
c.limbs[i] = diff_i
If final borrow = 1 → result negative:
Compute two's complement of magnitude
Flip sign bit
</code></pre>
<h3 id="33-constant-time-sbb"><a class="header" href="#33-constant-time-sbb">3.3 Constant-Time sbb</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>diff = x - y - borrow
borrow_out = (x < y) OR ((borrow == 1) AND (x == y))
<span class="boring">}</span></code></pre></pre>
<p>No branches.</p>
<h3 id="34-sign-rule"><a class="header" href="#34-sign-rule">3.4 Sign Rule</a></h3>
<p><code>sign(c) = sign(a) XOR sign(b)</code></p>
<h3 id="35-gas-cost"><a class="header" href="#35-gas-cost">3.5 Gas Cost</a></h3>
<p><code>G_sub(n) = 3n</code></p>
<h2 id="4-multiplication-algorithm"><a class="header" href="#4-multiplication-algorithm">4. Multiplication Algorithm</a></h2>
<h3 id="41-function-signature"><a class="header" href="#41-function-signature">4.1 Function Signature</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn mul(a: &BigInt, b: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="42-comba-method-small-operands"><a class="header" href="#42-comba-method-small-operands">4.2 Comba Method (Small Operands)</a></h3>
<p>For operands ≤ 16 limbs:</p>
<pre><code>Let n = limb count
Initialize c limbs length = 2n all zero
for i = 0 .. n-1:
carry = 0
for j = 0 .. n-1:
(lo, hi) = mul64(a[i], b[j])
(c[i+j], carry) = mac(c[i+j], lo, carry)
carry += hi
c[i+n] = carry
</code></pre>
<h3 id="43-karatsuba-method-large-operands"><a class="header" href="#43-karatsuba-method-large-operands">4.3 Karatsuba Method (Large Operands)</a></h3>
<p>For operands > 16 limbs:</p>
<pre><code>fn karatsuba_mul(a: &[Limb], b: &[Limb]) -> Vec<Limb> {
let n = a.len();
let m = n / 2;
// Split operands
let (a0, a1) = a.split_at(m);
let (b0, b1) = b.split_at(m);
// Compute z0 = a0*b0
let z0 = karatsuba_mul(a0, b0);
// Compute z2 = a1*b1
let z2 = karatsuba_mul(a1, b1);
// Compute z1 = (a0+a1)*(b0+b1) - z0 - z2
let a01 = add_limbs(a0, a1);
let b01 = add_limbs(b0, b1);
let z1 = karatsuba_mul(&a01, &b01);
sub_limbs_inplace(&mut z1, &z0);
sub_limbs_inplace(&mut z1, &z2);
// Combine results
return combine_karatsuba_results(z0, z1, z2, m);
}
</code></pre>
<h3 id="44-threshold-selection"><a class="header" href="#44-threshold-selection">4.4 Threshold Selection</a></h3>
<ul>
<li>Threshold MUST be fixed constant: <code>KARATSUBA_THRESHOLD = 16</code></li>
<li>Execution path depends only on public limb length</li>
<li>Never on operand values</li>
</ul>
<h3 id="45-sign-rule"><a class="header" href="#45-sign-rule">4.5 Sign Rule</a></h3>
<p><code>sign(c) = sign(a) XOR sign(b)</code></p>
<h3 id="46-gas-cost"><a class="header" href="#46-gas-cost">4.6 Gas Cost</a></h3>
<p><code>G_mul(n) = 2n²</code></p>
<h2 id="5-division-algorithm"><a class="header" href="#5-division-algorithm">5. Division Algorithm</a></h2>
<h3 id="51-function-signatures"><a class="header" href="#51-function-signatures">5.1 Function Signatures</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn div_rem(a: &BigInt, b: &BigInt) -> Result<(BigInt, BigInt)>
fn div(a: &BigInt, b: &BigInt) -> Result<BigInt>
fn rem(a: &BigInt, b: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="52-knuth-algorithm-d"><a class="header" href="#52-knuth-algorithm-d">5.2 Knuth Algorithm D</a></h3>
<ol>
<li><strong>Normalize divisor</strong>: Left-shift so highest bit set</li>
<li><strong>Left-shift dividend</strong> equally</li>
<li><strong>Main loop</strong>:</li>
</ol>
<pre><code>for i from high_limb downto low_limb:
// Estimate quotient digit q̂
q̂ = estimate_quotient_digit(dividend, divisor, i)
// Multiply and subtract
(partial_product, borrow) = mul_sub(divisor, q̂, dividend_slice)
// Correct if overestimated
while borrow != 0:
q̂ -= 1
add_back(divisor, dividend_slice)
borrow = check_borrow(dividend_slice)
</code></pre>
<h3 id="53-constant-time-corrections"><a class="header" href="#53-constant-time-corrections">5.3 Constant-Time Corrections</a></h3>
<ul>
<li>All correction steps use <strong>masked subtraction</strong></li>
<li>No branches based on borrow values</li>
<li>Fixed iteration count based on limb length</li>
</ul>
<h3 id="54-division-by-zero"><a class="header" href="#54-division-by-zero">5.4 Division by Zero</a></h3>
<p>Must return deterministic <code>DivisionByZero</code> error.</p>
<h3 id="55-sign-rules"><a class="header" href="#55-sign-rules">5.5 Sign Rules</a></h3>
<pre><code>quotient_sign = sign(a) XOR sign(b)
remainder_sign = sign(a)
</code></pre>
<h3 id="56-gas-cost"><a class="header" href="#56-gas-cost">5.6 Gas Cost</a></h3>
<p><code>G_div(n) = 4n²</code></p>
<h2 id="6-squaring-algorithm"><a class="header" href="#6-squaring-algorithm">6. Squaring Algorithm</a></h2>
<h3 id="61-function-signature"><a class="header" href="#61-function-signature">6.1 Function Signature</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn sqr(a: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="62-specialized-algorithm"><a class="header" href="#62-specialized-algorithm">6.2 Specialized Algorithm</a></h3>
<p>Squaring uses optimized algorithm for <code>a²</code>:</p>
<ul>
<li>Exploits symmetry: <code>a² = (a0 + a1*B)² = a0² + 2*a0*a1*B + a1²*B²</code></li>
<li>Fewer multiplications than general multiplication</li>
<li>Same constant-time properties</li>
</ul>
<h3 id="63-gas-cost"><a class="header" href="#63-gas-cost">6.3 Gas Cost</a></h3>
<p><code>G_sqr(n) = 1.6n²</code> (cheaper than multiplication)</p>
<h2 id="7-bitwise-operations"><a class="header" href="#7-bitwise-operations">7. Bitwise Operations</a></h2>
<h3 id="71-bit-shift"><a class="header" href="#71-bit-shift">7.1 Bit Shift</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn shift_left(a: &BigInt, bits: usize) -> Result<BigInt>
fn shift_right(a: &BigInt, bits: usize) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="72-algorithm"><a class="header" href="#72-algorithm">7.2 Algorithm</a></h3>
<ul>
<li>Convert bit shifts to limb shifts + intra-limb shifts</li>
<li>Handle carry/borrow across limb boundaries</li>
<li>Constant-time regardless of shift amount</li>
</ul>
<h3 id="73-gas-cost"><a class="header" href="#73-gas-cost">7.3 Gas Cost</a></h3>
<p><code>G_shift(n) = 2n</code></p>
<h2 id="8-comparison-operations"><a class="header" href="#8-comparison-operations">8. Comparison Operations</a></h2>
<h3 id="81-comparison-functions"><a class="header" href="#81-comparison-functions">8.1 Comparison Functions</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn cmp(a: &BigInt, b: &BigInt) -> Ordering
fn eq(a: &BigInt, b: &BigInt) -> bool
fn lt(a: &BigInt, b: &BigInt) -> bool
<span class="boring">}</span></code></pre></pre>
<h3 id="82-constant-time-implementation"><a class="header" href="#82-constant-time-implementation">8.2 Constant-Time Implementation</a></h3>
<ul>
<li>Compare magnitudes first</li>
<li>Then compare signs if magnitudes equal</li>
<li>No early exit on first difference</li>
</ul>
<h3 id="83-gas-cost"><a class="header" href="#83-gas-cost">8.3 Gas Cost</a></h3>
<p><code>G_cmp(n) = 2n</code></p>
<h2 id="9-error-conditions"><a class="header" href="#9-error-conditions">9. Error Conditions</a></h2>
<div class="table-wrapper"><table><thead><tr><th>Condition</th><th>Result</th></tr></thead><tbody>
<tr><td>Overflow (fixed)</td><td>VM Trap</td></tr>
<tr><td>Overflow (dynamic beyond max)</td><td>Overflow error</td></tr>
<tr><td>Division by zero</td><td>Deterministic error</td></tr>
<tr><td>Non-canonical input</td><td>Decode rejection</td></tr>
</tbody></table>
</div>
<h2 id="10-determinism-guarantee"><a class="header" href="#10-determinism-guarantee">10. Determinism Guarantee</a></h2>
<p>Given identical inputs, all implementations MUST:</p>
<ul>
<li>Produce identical limb outputs</li>
<li>Execute identical iteration counts</li>
<li>Consume identical gas cost</li>
<li>Never branch on secret data</li>
</ul>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="representation.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="montgomery.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="representation.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="montgomery.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>