<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>ClockinChain Big Integer Specifications</title>
<meta name="robots" content="noindex">
<!-- 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 "><a href="arithmetic.html"><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>
</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="clockinchain-big-integer-specifications"><a class="header" href="#clockinchain-big-integer-specifications">ClockinChain Big Integer Specifications</a></h1>
<p>This document collection contains the normative specifications for the ClockinChain Big Integer library, a production-ready big integer crate for blockchain consensus engines.</p>
<h2 id="specifications"><a class="header" href="#specifications">Specifications</a></h2>
<ul>
<li><a href="representation.html"><strong>Representation Specification v1.0</strong></a> - Canonical encoding and memory layout</li>
<li><a href="arithmetic.html"><strong>Arithmetic Algorithm Specification v1.0</strong></a> - Deterministic arithmetic operations</li>
<li><a href="montgomery.html"><strong>Montgomery & Modular Exponentiation Specification v1.0</strong></a> - Cryptographic arithmetic</li>
<li><a href="gas.html"><strong>Gas Schedule Specification v1.0</strong></a> - Precomputable gas metering</li>
</ul>
<h2 id="overview"><a class="header" href="#overview">Overview</a></h2>
<p>The ClockinChain Big Integer specifications define a complete cryptographic big integer arithmetic library with the following key properties:</p>
<ul>
<li><strong>Deterministic</strong>: Bit-for-bit identical results across all platforms</li>
<li><strong>Constant-time</strong>: All operations execute in constant time to prevent timing attacks</li>
<li><strong>Canonical encoding</strong>: Unique representation for each integer value</li>
<li><strong>Gas metering</strong>: Precomputable gas costs for VM execution</li>
<li><strong>Montgomery arithmetic</strong>: Full support for cryptographic operations</li>
<li><strong>Time-sliced operations</strong>: Pausable long operations for async VM execution</li>
</ul>
<h2 id="implementation"><a class="header" href="#implementation">Implementation</a></h2>
<p>These specifications are implemented in the <a href="https://github.com/olyntar-labs/clock-bigint">clock-bigint</a> Rust crate.</p>
<h2 id="license"><a class="header" href="#license">License</a></h2>
<p>This specification is licensed under the same terms as the clock-bigint crate.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="clockinchain-big-integer-representation-specification-v10"><a class="header" href="#clockinchain-big-integer-representation-specification-v10">ClockinChain Big Integer Representation Specification v1.0</a></h1>
<h2 id="overview-1"><a class="header" href="#overview-1">Overview</a></h2>
<p>This specification defines the canonical representation, memory layout, and encoding format for big integers in the ClockinChain ecosystem.</p>
<h2 id="1-memory-layout"><a class="header" href="#1-memory-layout">1. Memory Layout</a></h2>
<h3 id="11-limb-definition"><a class="header" href="#11-limb-definition">1.1 Limb Definition</a></h3>
<p>Big integers are represented as arrays of 64-bit unsigned integers called "limbs":</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>type Limb = u64;
const LIMB_BITS: usize = 64;
<span class="boring">}</span></code></pre></pre>
<h3 id="12-endianness"><a class="header" href="#12-endianness">1.2 Endianness</a></h3>
<p>All limb arrays use <strong>little-endian</strong> ordering:</p>
<ul>
<li><code>limbs[0]</code> contains the least significant limb</li>
<li><code>limbs[n-1]</code> contains the most significant limb</li>
</ul>
<h3 id="13-word-size"><a class="header" href="#13-word-size">1.3 Word Size</a></h3>
<p>The base B = 2^64, so each limb represents a value in the range [0, 2^64 - 1].</p>
<h2 id="2-canonical-form"><a class="header" href="#2-canonical-form">2. Canonical Form</a></h2>
<h3 id="21-zero-representation"><a class="header" href="#21-zero-representation">2.1 Zero Representation</a></h3>
<p>Zero MUST be represented as:</p>
<ul>
<li><code>sign = false</code></li>
<li><code>limbs = [0]</code> (exactly one limb)</li>
<li>No leading zero limbs allowed</li>
</ul>
<h3 id="22-non-zero-representation"><a class="header" href="#22-non-zero-representation">2.2 Non-zero Representation</a></h3>
<p>Non-zero integers MUST satisfy:</p>
<ul>
<li>No leading zero limbs: <code>limbs[limbs.len() - 1] != 0</code></li>
<li>Minimal limb count: smallest n such that the above holds</li>
<li>Sign bit indicates negative values</li>
</ul>
<h3 id="23-negative-zero-prohibition"><a class="header" href="#23-negative-zero-prohibition">2.3 Negative Zero Prohibition</a></h3>
<p>Negative zero is explicitly forbidden:</p>
<ul>
<li><code>sign = true</code> AND <code>value = 0</code> is invalid</li>
<li>All zero values MUST have <code>sign = false</code></li>
</ul>
<h2 id="3-type-system"><a class="header" href="#3-type-system">3. Type System</a></h2>
<h3 id="31-dynamic-bigint"><a class="header" href="#31-dynamic-bigint">3.1 Dynamic BigInt</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct BigInt {
sign: bool, // false = positive, true = negative
limbs: Vec<Limb>, // little-endian limb array
max_limbs: usize, // capacity limit
}
<span class="boring">}</span></code></pre></pre>
<h3 id="32-fixed-size-bigint"><a class="header" href="#32-fixed-size-bigint">3.2 Fixed-Size BigInt</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct BigIntFixed<const L: usize> {
limbs: [Limb; L], // fixed-size array
}
<span class="boring">}</span></code></pre></pre>
<h3 id="33-type-aliases"><a class="header" href="#33-type-aliases">3.3 Type Aliases</a></h3>
<p>Common fixed sizes:</p>
<ul>
<li><code>U256 = BigIntFixed<4></code> (256 bits)</li>
<li><code>U512 = BigIntFixed<8></code> (512 bits)</li>
<li><code>U1024 = BigIntFixed<16></code> (1024 bits)</li>
<li><code>U2048 = BigIntFixed<32></code> (2048 bits)</li>
</ul>
<h2 id="4-encoding-format"><a class="header" href="#4-encoding-format">4. Encoding Format</a></h2>
<h3 id="41-binary-format"><a class="header" href="#41-binary-format">4.1 Binary Format</a></h3>
<p>Canonical binary encoding uses the following format:</p>
<pre><code>[sign: u8][limb_count: u32 LE][limbs: u64[] LE]
</code></pre>
<p>Where:</p>
<ul>
<li><code>sign</code>: 0 for positive, 1 for negative</li>
<li><code>limb_count</code>: number of limbs (u32, little-endian)</li>
<li><code>limbs</code>: limb array in little-endian byte order</li>
</ul>
<h3 id="42-encoding-rules"><a class="header" href="#42-encoding-rules">4.2 Encoding Rules</a></h3>
<ol>
<li><strong>Canonical encoding</strong>: Every integer has exactly one valid encoding</li>
<li><strong>No leading zeros</strong>: Encoded limb arrays must not contain leading zero limbs</li>
<li><strong>Minimal length</strong>: Use the smallest limb count that satisfies canonical form</li>
<li><strong>Deterministic</strong>: Same integer always produces identical encoding</li>
</ol>
<h3 id="43-decoding-validation"><a class="header" href="#43-decoding-validation">4.3 Decoding Validation</a></h3>
<p>Decoding MUST reject:</p>
<ul>
<li>Invalid sign values (not 0 or 1)</li>
<li>Leading zero limbs in non-zero values</li>
<li>Negative zero representations</li>
<li>Malformed binary data</li>
</ul>
<h2 id="5-memory-management"><a class="header" href="#5-memory-management">5. Memory Management</a></h2>
<h3 id="51-allocation-strategy"><a class="header" href="#51-allocation-strategy">5.1 Allocation Strategy</a></h3>
<ul>
<li>Dynamic BigInt uses heap allocation with Vec<Limb></li>
<li>Fixed BigInt uses stack allocation when L ≤ 8</li>
<li>Heap allocation for L > 8 or dynamic types</li>
</ul>
<h3 id="52-capacity-limits"><a class="header" href="#52-capacity-limits">5.2 Capacity Limits</a></h3>
<ul>
<li><code>MAX_LIMBS = 512</code> (32768 bits maximum)</li>
<li>Prevents denial-of-service attacks</li>
<li>Enforced at allocation time</li>
</ul>
<h3 id="53-canonicalization"><a class="header" href="#53-canonicalization">5.3 Canonicalization</a></h3>
<p>All BigInt values MUST be canonicalized after operations:</p>
<ul>
<li>Remove leading zero limbs</li>
<li>Enforce zero sign rule</li>
<li>Maintain minimal representation</li>
</ul>
<h2 id="6-cross-platform-compatibility"><a class="header" href="#6-cross-platform-compatibility">6. Cross-Platform Compatibility</a></h2>
<h3 id="61-endianness"><a class="header" href="#61-endianness">6.1 Endianness</a></h3>
<ul>
<li>All encodings use little-endian byte order</li>
<li>Limb arrays are always little-endian</li>
<li>Platform endianness is irrelevant</li>
</ul>
<h3 id="62-word-size"><a class="header" href="#62-word-size">6.2 Word Size</a></h3>
<ul>
<li>Assumes 64-bit limbs</li>
<li>No support for 32-bit platforms</li>
<li>All operations assume 64-bit arithmetic</li>
</ul>
<h3 id="63-determinism"><a class="header" href="#63-determinism">6.3 Determinism</a></h3>
<ul>
<li>Identical inputs produce identical outputs</li>
<li>No platform-specific behavior</li>
<li>No undefined behavior in arithmetic</li>
</ul>
<h2 id="7-error-conditions"><a class="header" href="#7-error-conditions">7. Error Conditions</a></h2>
<h3 id="71-invalid-encoding"><a class="header" href="#71-invalid-encoding">7.1 Invalid Encoding</a></h3>
<p><code>InvalidEncoding</code> error for:</p>
<ul>
<li>Malformed binary data</li>
<li>Non-canonical representations</li>
<li>Invalid sign values</li>
</ul>
<h3 id="72-capacity-exceeded"><a class="header" href="#72-capacity-exceeded">7.2 Capacity Exceeded</a></h3>
<p><code>Overflow</code> error for:</p>
<ul>
<li>Operations exceeding max_limbs</li>
<li>Fixed-size overflow (const generics)</li>
</ul>
<h3 id="73-invalid-operations"><a class="header" href="#73-invalid-operations">7.3 Invalid Operations</a></h3>
<p><code>InvalidModulus</code> error for:</p>
<ul>
<li>Even moduli in Montgomery operations</li>
<li>Zero moduli</li>
<li>Invalid modulus sizes</li>
</ul>
<h2 id="8-testing-requirements"><a class="header" href="#8-testing-requirements">8. Testing Requirements</a></h2>
<h3 id="81-canonical-form-tests"><a class="header" href="#81-canonical-form-tests">8.1 Canonical Form Tests</a></h3>
<ul>
<li>Zero representation uniqueness</li>
<li>No leading zeros in encodings</li>
<li>Sign consistency validation</li>
<li>Cross-platform determinism</li>
</ul>
<h3 id="82-encoding-tests"><a class="header" href="#82-encoding-tests">8.2 Encoding Tests</a></h3>
<ul>
<li>Round-trip encoding/decoding</li>
<li>Rejection of invalid encodings</li>
<li>Canonical encoding uniqueness</li>
<li>Performance benchmarks</li>
</ul>
<h3 id="83-memory-safety-tests"><a class="header" href="#83-memory-safety-tests">8.3 Memory Safety Tests</a></h3>
<ul>
<li>Bounds checking validation</li>
<li>Allocation limit enforcement</li>
<li>Memory leak prevention</li>
<li>Stack overflow prevention</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="arithmetic-algorithm-specification-v10"><a class="header" href="#arithmetic-algorithm-specification-v10">Arithmetic Algorithm Specification v1.0</a></h1>
<h2 id="overview-2"><a class="header" href="#overview-2">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>
<div style="break-before: page; page-break-before: always;"></div><h1 id="montgomery--modular-exponentiation-specification-v10"><a class="header" href="#montgomery--modular-exponentiation-specification-v10">Montgomery & Modular Exponentiation Specification v1.0</a></h1>
<h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
<p>This specification defines the normative cryptographic arithmetic standard for Montgomery operations and modular exponentiation, critical for ChronoSig, ChronoHash, ChronoMerkle, and ZK systems.</p>
<h2 id="1-base-parameters"><a class="header" href="#1-base-parameters">1. Base Parameters</a></h2>
<h3 id="11-definitions"><a class="header" href="#11-definitions">1.1 Definitions</a></h3>
<ul>
<li>Limb base: <code>B = 2^64</code></li>
<li>Limb count: <code>n</code></li>
<li>Modulus: <code>m</code>, where <code>m</code> MUST be odd</li>
<li><code>R = B^n mod m</code></li>
<li><code>R² = B^(2n) mod m</code></li>
<li><code>m' = -m⁻¹ mod B</code></li>
</ul>
<h3 id="12-montgomery-representation"><a class="header" href="#12-montgomery-representation">1.2 Montgomery Representation</a></h3>
<p>A value <code>x</code> in normal representation is converted to Montgomery form:</p>
<pre><code>x̃ = (x × R) mod m
</code></pre>
<p>Montgomery domain arithmetic operates on <code>x̃</code>.</p>
<h2 id="2-montgomery-reduction"><a class="header" href="#2-montgomery-reduction">2. Montgomery Reduction</a></h2>
<h3 id="21-function-signature-1"><a class="header" href="#21-function-signature-1">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 mont_reduce(t: &BigInt, m: &BigInt, m_prime: Limb) -> BigInt
<span class="boring">}</span></code></pre></pre>
<p>Where <code>t</code> is a 2n-limb value.</p>
<h3 id="22-algorithm"><a class="header" href="#22-algorithm">2.2 Algorithm</a></h3>
<pre><code>For i = 0 .. n-1:
u_i = (t[i] × m') mod B
(t[i .. i+n]) += u_i × m[0 .. n]
After loop:
t = t[n .. 2n]
if t ≥ m:
t -= m
</code></pre>
<h3 id="23-constant-time-implementation"><a class="header" href="#23-constant-time-implementation">2.3 Constant-Time Implementation</a></h3>
<p>The conditional subtraction MUST be implemented via <strong>masked subtraction</strong> — not branching.</p>
<h3 id="24-gas-cost"><a class="header" href="#24-gas-cost">2.4 Gas Cost</a></h3>
<p><code>G_mont_reduce(n) = n²</code></p>
<h2 id="3-montgomery-multiplication"><a class="header" href="#3-montgomery-multiplication">3. Montgomery Multiplication</a></h2>
<h3 id="31-function-signature-1"><a class="header" href="#31-function-signature-1">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 mont_mul(ã: &BigInt, b̃: &BigInt, m: &BigInt, m_prime: Limb) -> BigInt
<span class="boring">}</span></code></pre></pre>
<h3 id="32-definition"><a class="header" href="#32-definition">3.2 Definition</a></h3>
<pre><code>c̃ = mont_reduce(ã × b̃)
</code></pre>
<p>Produces: <code>c̃ = (a × b × R) mod m</code></p>
<h3 id="33-gas-cost"><a class="header" href="#33-gas-cost">3.3 Gas Cost</a></h3>
<p><code>G_mont_mul(n) = 2n²</code></p>
<h2 id="4-montgomery-additionsubtraction"><a class="header" href="#4-montgomery-additionsubtraction">4. Montgomery Addition/Subtraction</a></h2>
<p>Performed normally in Montgomery domain:</p>
<pre><code>Add: c̃ = (ã + b̃) mod m
Sub: c̃ = (ã - b̃) mod m
</code></pre>
<p>Both followed by conditional reduction (constant-time masked subtraction).</p>
<h2 id="5-conversion-functions"><a class="header" href="#5-conversion-functions">5. Conversion Functions</a></h2>
<h3 id="51-into-montgomery-form"><a class="header" href="#51-into-montgomery-form">5.1 Into Montgomery Form</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn to_mont(x: &BigInt, m: &BigInt) -> BigInt
<span class="boring">}</span></code></pre></pre>
<p>Definition:</p>
<pre><code>to_mont(x) = mont_mul(x, R² mod m)
</code></pre>
<h3 id="52-out-of-montgomery-form"><a class="header" href="#52-out-of-montgomery-form">5.2 Out of Montgomery Form</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn from_mont(x̃: &BigInt, m: &BigInt) -> BigInt
<span class="boring">}</span></code></pre></pre>
<p>Definition:</p>
<pre><code>from_mont(x̃) = mont_reduce(x̃)
</code></pre>
<h2 id="6-montgomery-context"><a class="header" href="#6-montgomery-context">6. Montgomery Context</a></h2>
<h3 id="61-structure"><a class="header" href="#61-structure">6.1 Structure</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct MontgomeryContext {
modulus: BigInt, // m
r_mod_m: BigInt, // R mod m
r_squared_mod_m: BigInt, // R² mod m
m_prime: Limb, // m'
limb_count: usize, // n
}
<span class="boring">}</span></code></pre></pre>
<h3 id="62-creation"><a class="header" href="#62-creation">6.2 Creation</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn new(modulus: BigInt) -> Result<MontgomeryContext>
<span class="boring">}</span></code></pre></pre>
<p>Requirements:</p>
<ul>
<li><code>modulus</code> MUST be odd</li>
<li><code>modulus > 0</code></li>
<li>Precomputes all context values</li>
</ul>
<h2 id="7-modular-exponentiation"><a class="header" href="#7-modular-exponentiation">7. Modular Exponentiation</a></h2>
<h3 id="71-function-signature"><a class="header" href="#71-function-signature">7.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 mod_pow(base: &BigInt, exponent: &BigInt, modulus: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<h3 id="72-montgomery-ladder-algorithm"><a class="header" href="#72-montgomery-ladder-algorithm">7.2 Montgomery Ladder Algorithm</a></h3>
<pre><code>Input: base in normal form
Output: base^exponent mod modulus
1. Precompute:
R mod m
R² mod m
m'
2. Convert:
x̃ = to_mont(base)
R̃ = to_mont(1)
3. Initialize:
R0 = R̃
R1 = x̃
4. For bit i from MSB(exponent) → LSB:
bit = exponent[i]
cswap(bit, R0, R1)
R1 = mont_mul(R0, R1)
R0 = mont_mul(R0, R0)
cswap(bit, R0, R1)
5. result = from_mont(R0)
</code></pre>
<h3 id="73-constant-time-conditional-swap"><a class="header" href="#73-constant-time-conditional-swap">7.3 Constant-Time Conditional Swap</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>mask = -bit // 0xFFFF... if bit=1, 0x0000... if bit=0
tmp = mask & (R0 XOR R1)
R0 ^= tmp
R1 ^= tmp
<span class="boring">}</span></code></pre></pre>
<p>No branches allowed.</p>
<h3 id="74-gas-cost"><a class="header" href="#74-gas-cost">7.4 Gas Cost</a></h3>
<p><code>G_modexp(n, k) = k × 4n² + 20n²</code></p>
<p>Where k = exponent bit length.</p>
<h2 id="8-modular-inverse"><a class="header" href="#8-modular-inverse">8. Modular Inverse</a></h2>
<h3 id="81-via-extended-gcd"><a class="header" href="#81-via-extended-gcd">8.1 Via Extended GCD</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn mod_inverse(a: &BigInt, m: &BigInt) -> Result<BigInt>
<span class="boring">}</span></code></pre></pre>
<p>Uses binary extended GCD with constant-time loop bounds.</p>
<h3 id="82-via-fermats-little-theorem"><a class="header" href="#82-via-fermats-little-theorem">8.2 Via Fermat's Little Theorem</a></h3>
<p>For prime modulus <code>p</code>:</p>
<pre><code>a⁻¹ mod p = a^(p-2) mod p
</code></pre>
<h3 id="83-gas-cost-1"><a class="header" href="#83-gas-cost-1">8.3 Gas Cost</a></h3>
<ul>
<li>Via GCD: <code>G_inv_gcd(n) = 6n²</code></li>
<li>Via exponentiation: same as <code>G_modexp</code></li>
</ul>
<h2 id="9-error-conditions-1"><a class="header" href="#9-error-conditions-1">9. Error Conditions</a></h2>
<div class="table-wrapper"><table><thead><tr><th>Condition</th><th>Result</th></tr></thead><tbody>
<tr><td>m even</td><td>Reject modulus (InvalidModulus error)</td></tr>
<tr><td>modulus = 0</td><td>Reject (InvalidModulus error)</td></tr>
<tr><td>exponent = 0</td><td>Return 1 mod m</td></tr>
<tr><td>base = 0 & exponent = 0</td><td>Return 1 (by convention)</td></tr>
</tbody></table>
</div>
<h2 id="10-security-properties"><a class="header" href="#10-security-properties">10. Security Properties</a></h2>
<h3 id="101-constant-time-guarantee"><a class="header" href="#101-constant-time-guarantee">10.1 Constant-Time Guarantee</a></h3>
<p>All Montgomery operations MUST maintain:</p>
<ul>
<li>Constant-time execution w.r.t secret data</li>
<li>No secret-dependent memory access</li>
<li>Identical instruction count for equal limb sizes</li>
<li>Safe for signature and ZK usage</li>
</ul>
<h3 id="102-side-channel-resistance"><a class="header" href="#102-side-channel-resistance">10.2 Side Channel Resistance</a></h3>
<ul>
<li>Montgomery reduction eliminates power analysis patterns</li>
<li>Ladder exponentiation prevents timing attacks</li>
<li>No data-dependent branches or memory access</li>
</ul>
<h2 id="11-test-vector-requirements"><a class="header" href="#11-test-vector-requirements">11. Test Vector Requirements</a></h2>
<h3 id="111-known-answer-tests"><a class="header" href="#111-known-answer-tests">11.1 Known Answer Tests</a></h3>
<p>Test vectors MUST include:</p>
<ul>
<li>RSA modulus operations</li>
<li>secp256k1 field operations</li>
<li>Randomized consistency tests:</li>
</ul>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Verify: from_mont(mont_mul(to_mont(a), to_mont(b))) == (a*b mod m)
assert_eq!(
from_mont(&mont_mul(&to_mont(a), &to_mont(b))),
(a * b) % modulus
);
<span class="boring">}</span></code></pre></pre>
<h3 id="112-edge-cases"><a class="header" href="#112-edge-cases">11.2 Edge Cases</a></h3>
<ul>
<li>Modulus = 3 (smallest valid odd modulus)</li>
<li>Base = 0, 1, modulus-1</li>
<li>Exponent = 0, 1, large values</li>
<li>Carry propagation in Montgomery reduction</li>
</ul>
<h2 id="12-performance-targets"><a class="header" href="#12-performance-targets">12. Performance Targets</a></h2>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Target</th></tr></thead><tbody>
<tr><td>MontMul (256-bit)</td><td>~200 cycles</td></tr>
<tr><td>MontReduce (256-bit)</td><td>~100 cycles</td></tr>
<tr><td>ModExp (2048-bit)</td><td>within 10% of GMP</td></tr>
</tbody></table>
</div>
<h2 id="13-implementation-notes"><a class="header" href="#13-implementation-notes">13. Implementation Notes</a></h2>
<h3 id="131-word-size-assumptions"><a class="header" href="#131-word-size-assumptions">13.1 Word Size Assumptions</a></h3>
<ul>
<li>Assumes 64-bit limbs</li>
<li>Montgomery parameters optimized for 64-bit arithmetic</li>
<li>No support for 32-bit platforms</li>
</ul>
<h3 id="132-memory-layout"><a class="header" href="#132-memory-layout">13.2 Memory Layout</a></h3>
<ul>
<li>All Montgomery values use canonical BigInt representation</li>
<li>No special internal formats</li>
<li>Compatible with all other BigInt operations</li>
</ul>
<h3 id="133-determinism"><a class="header" href="#133-determinism">13.3 Determinism</a></h3>
<ul>
<li>Identical results across platforms</li>
<li>No undefined behavior</li>
<li>Reproducible for consensus-critical applications</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gas-schedule-specification-v10"><a class="header" href="#gas-schedule-specification-v10">Gas Schedule Specification v1.0</a></h1>
<h2 id="overview-4"><a class="header" href="#overview-4">Overview</a></h2>
<p>This specification defines the normative gas cost constants for all BigInt arithmetic operations, ensuring deterministic, precomputable metering for the ClockinChain VM.</p>
<h2 id="1-design-principles"><a class="header" href="#1-design-principles">1. Design Principles</a></h2>
<h3 id="11-gas-cost-properties"><a class="header" href="#11-gas-cost-properties">1.1 Gas Cost Properties</a></h3>
<ol>
<li><strong>Public parameters only</strong>: Gas cost depends only on public limb length</li>
<li><strong>No secret dependency</strong>: Never depends on operand values</li>
<li><strong>Linear/quadratic scaling</strong>: Simple mathematical formulas</li>
<li><strong>Constant-time compatible</strong>: Compatible with constant-time execution</li>
<li><strong>Precomputable</strong>: VM can compute costs before execution</li>
<li><strong>DoS protection</strong>: Prevents arithmetic-based denial-of-service</li>
</ol>
<h3 id="12-base-definitions"><a class="header" href="#12-base-definitions">1.2 Base Definitions</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>const G_BASE: Gas = 10; // Baseline dispatch cost unit
let n: usize = limb_count;
let k: usize = exponent_bit_length;
<span class="boring">}</span></code></pre></pre>
<p>All costs below are added to <code>G_BASE</code>.</p>
<h2 id="2-core-arithmetic-costs"><a class="header" href="#2-core-arithmetic-costs">2. Core Arithmetic Costs</a></h2>
<h3 id="21-addition-and-subtraction"><a class="header" href="#21-addition-and-subtraction">2.1 Addition and Subtraction</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>Addition</td><td><code>G_add(n) = 3n</code></td><td>Carry chain propagation</td></tr>
<tr><td>Subtraction</td><td><code>G_sub(n) = 3n</code></td><td>Borrow chain propagation</td></tr>
<tr><td>Negation</td><td><code>G_neg(n) = 2n</code></td><td>Two's complement</td></tr>
<tr><td>Comparison</td><td><code>G_cmp(n) = 2n</code></td><td>Full limb comparison</td></tr>
</tbody></table>
</div>
<h3 id="22-bitwise-operations"><a class="header" href="#22-bitwise-operations">2.2 Bitwise Operations</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>Bit shift</td><td><code>G_shift(n) = 2n</code></td><td>Barrel shift implementation</td></tr>
</tbody></table>
</div>
<h2 id="3-multiplication-costs"><a class="header" href="#3-multiplication-costs">3. Multiplication Costs</a></h2>
<h3 id="31-multiplication-variants"><a class="header" href="#31-multiplication-variants">3.1 Multiplication Variants</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>Multiply</td><td><code>G_mul(n) = 2n²</code></td><td>Comba/Karatsuba</td></tr>
<tr><td>Square</td><td><code>G_sqr(n) = 1.6n²</code></td><td>Optimized for squaring</td></tr>
<tr><td>Multiply-Accumulate</td><td><code>G_mac(n) = 2n²</code></td><td>Internal operation</td></tr>
</tbody></table>
</div>
<h3 id="32-algorithm-selection"><a class="header" href="#32-algorithm-selection">3.2 Algorithm Selection</a></h3>
<ul>
<li>Comba method for small operands (n ≤ 16)</li>
<li>Karatsuba method for large operands (n > 16)</li>
<li>Cost formula covers both algorithms</li>
</ul>
<h2 id="4-division-and-modulo"><a class="header" href="#4-division-and-modulo">4. Division and Modulo</a></h2>
<h3 id="41-division-operations"><a class="header" href="#41-division-operations">4.1 Division Operations</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>Division</td><td><code>G_div(n) = 4n²</code></td><td>Knuth long division</td></tr>
<tr><td>Modulo</td><td><code>G_mod(n) = 4n²</code></td><td>Same cost as division</td></tr>
<tr><td>DivMod</td><td><code>G_divmod(n) = 4n²</code></td><td>Shared computation</td></tr>
</tbody></table>
</div>
<h3 id="42-division-algorithm"><a class="header" href="#42-division-algorithm">4.2 Division Algorithm</a></h3>
<ul>
<li>Knuth Algorithm D with constant-time corrections</li>
<li>Quadratic complexity due to digit-by-digit approach</li>
<li>Includes normalization and denormalization steps</li>
</ul>
<h2 id="5-montgomery-domain-operations"><a class="header" href="#5-montgomery-domain-operations">5. Montgomery Domain Operations</a></h2>
<h3 id="51-montgomery-arithmetic"><a class="header" href="#51-montgomery-arithmetic">5.1 Montgomery Arithmetic</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>MontReduce</td><td><code>G_mred(n) = n²</code></td><td>Reduction loop</td></tr>
<tr><td>MontMul</td><td><code>G_mmul(n) = 2n²</code></td><td>Mul + Reduce</td></tr>
<tr><td>MontAdd/Sub</td><td><code>G_madd(n) = 3n</code></td><td>+ conditional reduction</td></tr>
<tr><td>ToMont</td><td><code>G_tomont(n) = 2n²</code></td><td>Using R²</td></tr>
<tr><td>FromMont</td><td><code>G_frommont(n) = n²</code></td><td>Reduction only</td></tr>
</tbody></table>
</div>
<h3 id="52-modular-exponentiation"><a class="header" href="#52-modular-exponentiation">5.2 Modular Exponentiation</a></h3>
<p><strong>Ladder Cost Formula:</strong></p>
<pre><code>G_modexp(n, k) = k × (G_mmul(n) + G_mmul(n)) + G_setup
= k × 4n² + 20n²
</code></pre>
<p>Where:</p>
<ul>
<li><code>k</code> = exponent bit length</li>
<li>Ladder performs 2 multiplications per bit</li>
<li>Setup cost covers Montgomery context creation</li>
</ul>
<h2 id="6-modular-inverse"><a class="header" href="#6-modular-inverse">6. Modular Inverse</a></h2>
<h3 id="61-inverse-methods"><a class="header" href="#61-inverse-methods">6.1 Inverse Methods</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Method</th><th>Cost</th><th>Notes</th></tr></thead><tbody>
<tr><td>Binary GCD</td><td><code>G_inv_gcd(n) = 6n²</code></td><td>Constant-time bounds</td></tr>
<tr><td>Via ModExp</td><td><code>G_modexp(n, n)</code></td><td>For prime moduli</td></tr>
</tbody></table>
</div>
<h3 id="62-binary-gcd-algorithm"><a class="header" href="#62-binary-gcd-algorithm">6.2 Binary GCD Algorithm</a></h3>
<ul>
<li>Extended Euclidean algorithm</li>
<li>Fixed iteration bounds based on limb count</li>
<li>Constant-time implementation</li>
</ul>
<h2 id="7-encoding-and-serialization"><a class="header" href="#7-encoding-and-serialization">7. Encoding and Serialization</a></h2>
<h3 id="71-encoding-operations"><a class="header" href="#71-encoding-operations">7.1 Encoding Operations</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>Formula</th><th>Notes</th></tr></thead><tbody>
<tr><td>Canonicalize</td><td><code>G_canon(n) = n</code></td><td>Remove leading zeros</td></tr>
<tr><td>Encode</td><td><code>G_enc(n) = n</code></td><td>Serialize to bytes</td></tr>
<tr><td>Decode</td><td><code>G_dec(n) = n</code></td><td>Deserialize from bytes</td></tr>
</tbody></table>
</div>
<h3 id="72-encoding-format"><a class="header" href="#72-encoding-format">7.2 Encoding Format</a></h3>
<p>Binary format: <code>[sign: u8][limb_count: u32 LE][limbs: u64[] LE]</code></p>
<h2 id="8-global-limits"><a class="header" href="#8-global-limits">8. Global Limits</a></h2>
<h3 id="81-maximum-size-limits"><a class="header" href="#81-maximum-size-limits">8.1 Maximum Size Limits</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>const MAX_LIMBS: usize = 512; // 32768-bit integers
<span class="boring">}</span></code></pre></pre>
<ul>
<li>Prevents denial-of-service attacks</li>
<li>Operations exceeding this MUST trap before execution</li>
</ul>
<h3 id="82-overflow-handling"><a class="header" href="#82-overflow-handling">8.2 Overflow Handling</a></h3>
<ul>
<li>Fixed-length BigInt: Trap on overflow</li>
<li>Dynamic BigInt: Error on exceeding capacity</li>
</ul>
<h2 id="9-example-costs"><a class="header" href="#9-example-costs">9. Example Costs</a></h2>
<h3 id="91-common-sizes"><a class="header" href="#91-common-sizes">9.1 Common Sizes</a></h3>
<div class="table-wrapper"><table><thead><tr><th>Operation</th><th>256-bit (n=4)</th><th>2048-bit (n=32)</th></tr></thead><tbody>
<tr><td>Add</td><td>12</td><td>96</td></tr>
<tr><td>Mul</td><td>32</td><td>2048</td></tr>
<tr><td>MontMul</td><td>32</td><td>2048</td></tr>
<tr><td>Div</td><td>64</td><td>4096</td></tr>
<tr><td>ModExp (256-bit exp)</td><td>~32768</td><td>~8.3M</td></tr>
<tr><td>ModExp (2048-bit exp)</td><td>~131072</td><td>~33.5M</td></tr>
</tbody></table>
</div>
<h3 id="92-gas-budget-considerations"><a class="header" href="#92-gas-budget-considerations">9.2 Gas Budget Considerations</a></h3>
<p>For typical blockchain operations:</p>
<ul>
<li>Simple transfers: ~50 gas</li>
<li>ECDSA signature verification: ~100K gas</li>
<li>Modular exponentiation (2048-bit): ~10M gas</li>
</ul>
<h2 id="10-governance-and-updates"><a class="header" href="#10-governance-and-updates">10. Governance and Updates</a></h2>
<h3 id="101-gas-schedule-adjustments"><a class="header" href="#101-gas-schedule-adjustments">10.1 Gas Schedule Adjustments</a></h3>
<ul>
<li>Gas constants may be adjusted by chain governance</li>
<li>Must maintain linear/quadratic form constraints</li>
<li>Updates require consensus approval</li>
</ul>
<h3 id="102-backward-compatibility"><a class="header" href="#102-backward-compatibility">10.2 Backward Compatibility</a></h3>
<ul>
<li>Gas costs can only increase (never decrease)</li>
<li>New operations can be added with appropriate costs</li>
<li>Existing operations maintain cost formulas</li>
</ul>
<h2 id="11-implementation-requirements"><a class="header" href="#11-implementation-requirements">11. Implementation Requirements</a></h2>
<h3 id="111-gas-calculation"><a class="header" href="#111-gas-calculation">11.1 Gas Calculation</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn gas_cost_add(n: usize) -> Gas {
G_BASE + 3 * n
}
fn gas_cost_mul(n: usize) -> Gas {
G_BASE + 2 * n * n
}
fn gas_cost_modexp(n: usize, k: usize) -> Gas {
G_BASE + k * 4 * n * n + 20 * n * n
}
<span class="boring">}</span></code></pre></pre>
<h3 id="112-precomputation"><a class="header" href="#112-precomputation">11.2 Precomputation</a></h3>
<p>VM MUST be able to compute gas costs before execution using only:</p>
<ul>
<li>Operation type</li>
<li>Limb count (n)</li>
<li>Exponent bit length (k)</li>
</ul>
<h3 id="113-error-handling"><a class="header" href="#113-error-handling">11.3 Error Handling</a></h3>
<ul>
<li>Insufficient gas: Transaction rejected</li>
<li>Gas overflow: Implementation-defined behavior</li>
<li>Invalid operations: Trap with error</li>
</ul>
<h2 id="12-security-considerations"><a class="header" href="#12-security-considerations">12. Security Considerations</a></h2>
<h3 id="121-dos-prevention"><a class="header" href="#121-dos-prevention">12.1 DoS Prevention</a></h3>
<ul>
<li>Quadratic costs prevent large integer attacks</li>
<li>Maximum limb limits prevent memory exhaustion</li>
<li>Gas metering prevents computational DoS</li>
</ul>
<h3 id="122-constant-time-compatibility"><a class="header" href="#122-constant-time-compatibility">12.2 Constant-Time Compatibility</a></h3>
<ul>
<li>Gas costs never depend on secret values</li>
<li>Precomputation doesn't leak timing information</li>
<li>Compatible with constant-time arithmetic</li>
</ul>
<h2 id="13-testing-and-validation"><a class="header" href="#13-testing-and-validation">13. Testing and Validation</a></h2>
<h3 id="131-gas-cost-verification"><a class="header" href="#131-gas-cost-verification">13.1 Gas Cost Verification</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[test]
fn test_gas_costs_positive() {
for n in 1..=MAX_LIMBS {
assert!(gas_cost_add(n) > 0);
assert!(gas_cost_mul(n) > 0);
}
}
#[test]
fn test_gas_costs_increase_with_size() {
for n in 1..100 {
assert!(gas_cost_add(n+1) > gas_cost_add(n));
assert!(gas_cost_mul(n+1) > gas_cost_mul(n));
}
}
<span class="boring">}</span></code></pre></pre>
<h3 id="132-performance-correlation"><a class="header" href="#132-performance-correlation">13.2 Performance Correlation</a></h3>
<ul>
<li>Gas costs SHOULD correlate with actual CPU cycles</li>
<li>Benchmark results validate cost model accuracy</li>
<li>Performance regressions trigger gas schedule review</li>
</ul>
<h2 id="14-future-extensions"><a class="header" href="#14-future-extensions">14. Future Extensions</a></h2>
<h3 id="141-advanced-operations"><a class="header" href="#141-advanced-operations">14.1 Advanced Operations</a></h3>
<p>Future specifications may add:</p>
<ul>
<li>Batch operations with discounted costs</li>
<li>Hardware-accelerated operations</li>
<li>Specialized cryptographic primitives</li>
</ul>
<h3 id="142-dynamic-gas-pricing"><a class="header" href="#142-dynamic-gas-pricing">14.2 Dynamic Gas Pricing</a></h3>
<ul>
<li>Gas costs could become dynamic based on:
<ul>
<li>Network congestion</li>
<li>Hardware performance</li>
<li>Economic factors</li>
</ul>
</li>
</ul>
<h3 id="143-multi-precision-extensions"><a class="header" href="#143-multi-precision-extensions">14.3 Multi-Precision Extensions</a></h3>
<ul>
<li>Support for 32-bit limbs on constrained platforms</li>
<li>Variable limb sizes for different use cases</li>
</ul>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
</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 -->
<script>
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
</div>
</body>
</html>