///|
/// Fixed-width 256-bit unsigned integer stored as 4 little-endian 64-bit limbs.
#derive(Debug, Eq, Hash)
pub struct U256 {
l0 : UInt64
l1 : UInt64
l2 : UInt64
l3 : UInt64
}
///|
pub extend U256 with @debug.Debug::{to_repr}
///|
pub extend U256 with Eq::{not_equal, equal}
///|
pub extend U256 with Hash::{hash, hash_combine}
///|
pub fn U256::new(l0 : UInt64, l1 : UInt64, l2 : UInt64, l3 : UInt64) -> U256 {
{ l0, l1, l2, l3, }
}
///|
pub fn U256::zero() -> U256 {
{ l0: 0UL, l1: 0UL, l2: 0UL, l3: 0UL, }
}
///|
pub fn U256::one() -> U256 {
{ l0: 1UL, l1: 0UL, l2: 0UL, l3: 0UL, }
}
///|
pub fn U256::from_u64(v : UInt64) -> U256 {
{ l0: v, l1: 0UL, l2: 0UL, l3: 0UL, }
}
///|
pub fn U256::is_zero(self : U256) -> Bool {
(self.l0 | self.l1 | self.l2 | self.l3) == 0UL
}
///|
/// Compare two U256 values: -1 if self < other, 0 if equal, 1 if self > other.
pub fn U256::cmp(self : U256, other : U256) -> Int32 {
if self.l3 != other.l3 {
return if self.l3 < other.l3 { -1 } else { 1 }
}
if self.l2 != other.l2 {
return if self.l2 < other.l2 { -1 } else { 1 }
}
if self.l1 != other.l1 {
return if self.l1 < other.l1 { -1 } else { 1 }
}
if self.l0 != other.l0 {
return if self.l0 < other.l0 { -1 } else { 1 }
}
0
}
///|
/// Add with carry: returns (sum, carry_out in {0, 1}).
fn adc(a : UInt64, b : UInt64, carry : UInt64) -> (UInt64, UInt64) {
let s1 = a + b
let c1 : UInt64 = if s1 < a { 1UL } else { 0UL }
let s2 = s1 + carry
let c2 : UInt64 = if s2 < s1 { 1UL } else { 0UL }
(s2, c1 + c2)
}
///|
/// Subtract with borrow: returns (diff, borrow_out in {0, 1}).
fn sbb(a : UInt64, b : UInt64, borrow : UInt64) -> (UInt64, UInt64) {
let d1 = a - b
let b1 : UInt64 = if a < b { 1UL } else { 0UL }
let d2 = d1 - borrow
let b2 : UInt64 = if d1 < borrow { 1UL } else { 0UL }
(d2, b1 + b2)
}
///|
/// 64x64 -> 128-bit unsigned multiplication returning (lo, hi).
fn mul_u64_wide(a : UInt64, b : UInt64) -> (UInt64, UInt64) {
let mask : UInt64 = 0xffffffffUL
let a_lo = a & mask
let a_hi = a >> 32
let b_lo = b & mask
let b_hi = b >> 32
let p0 = a_lo * b_lo
let p1 = a_lo * b_hi
let p2 = a_hi * b_lo
let p3 = a_hi * b_hi
let mid1 = (p0 >> 32) + (p1 & mask) + (p2 & mask)
let lo = (p0 & mask) | (mid1 << 32)
let hi = p3 + (p1 >> 32) + (p2 >> 32) + (mid1 >> 32)
(lo, hi)
}
///|
/// Multiply-accumulate: a + b * c + carry -> (lo, hi).
fn mac(a : UInt64, b : UInt64, c : UInt64, carry : UInt64) -> (UInt64, UInt64) {
let (p_lo, p_hi) = mul_u64_wide(b, c)
let s1 = p_lo + a
let c1 : UInt64 = if s1 < p_lo { 1UL } else { 0UL }
let s2 = s1 + carry
let c2 : UInt64 = if s2 < s1 { 1UL } else { 0UL }
(s2, p_hi + c1 + c2)
}
///|
/// 256-bit addition with carry out.
pub fn U256::add_carry(self : U256, other : U256) -> (U256, UInt64) {
let (l0, c0) = adc(self.l0, other.l0, 0UL)
let (l1, c1) = adc(self.l1, other.l1, c0)
let (l2, c2) = adc(self.l2, other.l2, c1)
let (l3, c3) = adc(self.l3, other.l3, c2)
({ l0, l1, l2, l3, }, c3)
}
///|
/// 256-bit subtraction with borrow out.
pub fn U256::sub_borrow(self : U256, other : U256) -> (UInt64, U256) {
let (l0, b0) = sbb(self.l0, other.l0, 0UL)
let (l1, b1) = sbb(self.l1, other.l1, b0)
let (l2, b2) = sbb(self.l2, other.l2, b1)
let (l3, b3) = sbb(self.l3, other.l3, b2)
(b3, { l0, l1, l2, l3, })
}
///|
/// 512-bit unsigned product (8 little-endian 64-bit limbs).
pub fn U256::mul_wide(self : U256, other : U256) -> FixedArray[UInt64] {
let r : FixedArray[UInt64] = FixedArray::make(8, 0UL)
let (r0, c) = mac(0UL, self.l0, other.l0, 0UL)
let (r1, c) = mac(0UL, self.l0, other.l1, c)
let (r2, c) = mac(0UL, self.l0, other.l2, c)
let (r3, c) = mac(0UL, self.l0, other.l3, c)
r[0] = r0
r[1] = r1
r[2] = r2
r[3] = r3
r[4] = c
let (r1, c) = mac(r[1], self.l1, other.l0, 0UL)
let (r2, c) = mac(r[2], self.l1, other.l1, c)
let (r3, c) = mac(r[3], self.l1, other.l2, c)
let (r4, c) = mac(r[4], self.l1, other.l3, c)
r[1] = r1
r[2] = r2
r[3] = r3
r[4] = r4
r[5] = c
let (r2, c) = mac(r[2], self.l2, other.l0, 0UL)
let (r3, c) = mac(r[3], self.l2, other.l1, c)
let (r4, c) = mac(r[4], self.l2, other.l2, c)
let (r5, c) = mac(r[5], self.l2, other.l3, c)
r[2] = r2
r[3] = r3
r[4] = r4
r[5] = r5
r[6] = c
let (r3, c) = mac(r[3], self.l3, other.l0, 0UL)
let (r4, c) = mac(r[4], self.l3, other.l1, c)
let (r5, c) = mac(r[5], self.l3, other.l2, c)
let (r6, c) = mac(r[6], self.l3, other.l3, c)
r[3] = r3
r[4] = r4
r[5] = r5
r[6] = r6
r[7] = c
r
}
///|
/// Montgomery multiplication (CIOS algorithm): returns a * b * R^-1 mod m,
/// where inv = -m^-1 mod 2^64 and m.l3 < 2^63 (true for both BN254 p and r).
pub fn mont_mul(a : U256, b : U256, m : U256, inv : UInt64) -> U256 {
let t = a.mul_wide(b)
mont_reduce(t, m, inv)
}
///|
/// Montgomery reduction of a 512-bit value t (8 limbs): returns t * R^-1 mod m.
pub fn mont_reduce(t : FixedArray[UInt64], m : U256, inv : UInt64) -> U256 {
let mut t0 = t[0]
let mut t1 = t[1]
let mut t2 = t[2]
let mut t3 = t[3]
let mut t4 = t[4]
let mut t5 = t[5]
let mut t6 = t[6]
let mut t7 = t[7]
// Iteration 0
let k0 = t0 * inv
let (_, c) = mac(t0, k0, m.l0, 0UL)
let (nt1, c) = mac(t1, k0, m.l1, c)
let (nt2, c) = mac(t2, k0, m.l2, c)
let (nt3, c) = mac(t3, k0, m.l3, c)
let (nt4, c4) = adc(t4, c, 0UL)
t1 = nt1
t2 = nt2
t3 = nt3
t4 = nt4
// Iteration 1
let k1 = t1 * inv
let (_, c) = mac(t1, k1, m.l0, 0UL)
let (nt2, c) = mac(t2, k1, m.l1, c)
let (nt3, c) = mac(t3, k1, m.l2, c)
let (nt4, c) = mac(t4, k1, m.l3, c)
let (nt5, c5) = adc(t5, c, c4)
t2 = nt2
t3 = nt3
t4 = nt4
t5 = nt5
// Iteration 2
let k2 = t2 * inv
let (_, c) = mac(t2, k2, m.l0, 0UL)
let (nt3, c) = mac(t3, k2, m.l1, c)
let (nt4, c) = mac(t4, k2, m.l2, c)
let (nt5, c) = mac(t5, k2, m.l3, c)
let (nt6, c6) = adc(t6, c, c5)
t3 = nt3
t4 = nt4
t5 = nt5
t6 = nt6
// Iteration 3
let k3 = t3 * inv
let (_, c) = mac(t3, k3, m.l0, 0UL)
let (nt4, c) = mac(t4, k3, m.l1, c)
let (nt5, c) = mac(t5, k3, m.l2, c)
let (nt6, c) = mac(t6, k3, m.l3, c)
let (nt7, _) = adc(t7, c, c6)
t4 = nt4
t5 = nt5
t6 = nt6
t7 = nt7
t0 = t4
let res : U256 = { l0: t0, l1: t5, l2: t6, l3: t7, }
let (borrow, sub) = res.sub_borrow(m)
if borrow == 0UL {
sub
} else {
res
}
}
///|
/// Get bit at index `i` (0 = LSB, 255 = MSB).
pub fn U256::bit(self : U256, i : Int32) -> Bool {
if i < 0 || i >= 256 {
return false
}
let limb = if i < 64 {
self.l0
} else if i < 128 {
self.l1
} else if i < 192 {
self.l2
} else {
self.l3
}
((limb >> (i & 63)) & 1UL) == 1UL
}
///|
/// Number of significant bits (0 for zero).
pub fn U256::bit_length(self : U256) -> Int32 {
for i = 255; i >= 0; i = i - 1 {
if self.bit(i) {
return i + 1
}
}
0
}
///|
/// Right-shift by 1 bit.
pub fn U256::shr1(self : U256) -> U256 {
{
l0: (self.l0 >> 1) | (self.l1 << 63),
l1: (self.l1 >> 1) | (self.l2 << 63),
l2: (self.l2 >> 1) | (self.l3 << 63),
l3: self.l3 >> 1,
}
}
///|
/// Multiply by a small UInt64 scalar (<= 2^32) and add an increment, returning (result, overflow).
fn U256::mul_small_add(
self : U256,
factor : UInt64,
addend : UInt64,
) -> (U256, UInt64) {
let (l0, c0) = mac(addend, self.l0, factor, 0UL)
let (l1, c1) = mac(0UL, self.l1, factor, c0)
let (l2, c2) = mac(0UL, self.l2, factor, c1)
let (l3, c3) = mac(0UL, self.l3, factor, c2)
({ l0, l1, l2, l3, }, c3)
}
///|
/// Divide by 10, returning (quotient, remainder in 0..9).
fn U256::div_rem_10(self : U256) -> (U256, UInt64) {
// Process in 32-bit chunks from MSB to LSB so 64-bit arithmetic never overflows.
let chunks : FixedArray[UInt64] = [
self.l3 >> 32,
self.l3 & 0xffffffffUL,
self.l2 >> 32,
self.l2 & 0xffffffffUL,
self.l1 >> 32,
self.l1 & 0xffffffffUL,
self.l0 >> 32,
self.l0 & 0xffffffffUL,
]
let q : FixedArray[UInt64] = FixedArray::make(8, 0UL)
let mut rem : UInt64 = 0UL
for i = 0; i < 8; i = i + 1 {
let cur = (rem << 32) | chunks[i]
q[i] = cur / 10UL
rem = cur % 10UL
}
let res : U256 = {
l3: (q[0] << 32) | q[1],
l2: (q[2] << 32) | q[3],
l1: (q[4] << 32) | q[5],
l0: (q[6] << 32) | q[7],
}
(res, rem)
}
///|
/// Format as canonical lowercase hexadecimal string with `0x` prefix (64 hex chars).
pub fn U256::to_hex(self : U256) -> String {
let hex_chars = "0123456789abcdef"
let buf = StringBuilder()
buf.write_string("0x")
let limbs : FixedArray[UInt64] = [self.l3, self.l2, self.l1, self.l0]
for li = 0; li < 4; li = li + 1 {
let v = limbs[li]
for sh = 60; sh >= 0; sh = sh - 4 {
let nib = ((v >> sh) & 0xfUL).to_int()
buf.write_char(hex_chars[nib].to_int().unsafe_to_char())
}
}
buf.to_string()
}
///|
/// Format as canonical base-10 unsigned decimal string.
pub fn U256::to_decimal(self : U256) -> String {
if self.is_zero() {
return "0"
}
let digits : Array[Char] = []
let mut cur = self
while !cur.is_zero() {
let (q, rem) = cur.div_rem_10()
digits.push((48 + rem.to_int()).unsafe_to_char())
cur = q
}
let buf = StringBuilder()
for i = digits.length() - 1; i >= 0; i = i - 1 {
buf.write_char(digits[i])
}
buf.to_string()
}
///|
pub impl Show for U256 with fn output(self, logger) {
logger.write_string(self.to_decimal())
}
///|
pub extend U256 with Show::{to_string, output}
///|
/// Parse an unsigned decimal string into U256.
pub fn U256::from_decimal(s : String) -> U256 raise ZkError {
let trimmed = s.trim()
if trimmed.length() == 0 {
raise ZkError::InvalidFieldElement("empty decimal string")
}
let mut acc = U256::zero()
for i = 0; i < trimmed.length(); i = i + 1 {
let code = trimmed[i].to_int()
if code < 48 || code > 57 {
raise ZkError::InvalidFieldElement("non-digit in decimal string: \{s}")
}
let digit = (code - 48).to_uint64()
let (next, overflow) = acc.mul_small_add(10UL, digit)
if overflow != 0UL {
raise ZkError::InvalidFieldElement("decimal overflows 256 bits: \{s}")
}
acc = next
}
acc
}
///|
/// Parse an unsigned hexadecimal string (with or without `0x` prefix) into U256.
pub fn U256::from_hex(s : String) -> U256 raise ZkError {
let trimmed = s.trim()
let body = if trimmed.has_prefix("0x") || trimmed.has_prefix("0X") {
trimmed[2:].to_owned()
} else {
trimmed.to_owned()
}
if body.length() == 0 {
raise ZkError::InvalidFieldElement("empty hex string")
}
let mut acc = U256::zero()
for i = 0; i < body.length(); i = i + 1 {
let code = body[i].to_int()
let nib : UInt64 = if code >= 48 && code <= 57 {
(code - 48).to_uint64()
} else if code >= 97 && code <= 102 {
(code - 87).to_uint64()
} else if code >= 65 && code <= 70 {
(code - 55).to_uint64()
} else {
raise ZkError::InvalidFieldElement("invalid hex character in: \{s}")
}
let (next, overflow) = acc.mul_small_add(16UL, nib)
if overflow != 0UL {
raise ZkError::InvalidFieldElement("hex overflows 256 bits: \{s}")
}
acc = next
}
acc
}
///|
/// Parse either hex (`0x...`) or decimal string into U256.
pub fn U256::from_str(s : String) -> U256 raise ZkError {
let trimmed = s.trim()
if trimmed.has_prefix("0x") || trimmed.has_prefix("0X") {
U256::from_hex(trimmed.to_owned())
} else {
U256::from_decimal(trimmed.to_owned())
}
}
///|
/// Convert to 32-byte big-endian representation (Ethereum EIP-196/197 wire format).
pub fn U256::to_be_bytes(self : U256) -> Bytes {
let arr : FixedArray[Byte] = FixedArray::make(32, b'\x00')
let limbs : FixedArray[UInt64] = [self.l3, self.l2, self.l1, self.l0]
for li = 0; li < 4; li = li + 1 {
let v = limbs[li]
for bi = 0; bi < 8; bi = bi + 1 {
let sh = (7 - bi) * 8
arr[li * 8 + bi] = ((v >> sh) & 0xffUL).to_int().to_byte()
}
}
Bytes::from_array(arr)
}
///|
/// Decode from 32-byte big-endian slice (Ethereum EIP-196/197 wire format).
pub fn U256::from_be_bytes(bytes : BytesView) -> U256 raise ZkError {
if bytes.length() != 32 {
raise ZkError::InvalidFieldElement(
"expected 32 big-endian bytes, got \{bytes.length()}",
)
}
let limbs : FixedArray[UInt64] = FixedArray::make(4, 0UL)
for li = 0; li < 4; li = li + 1 {
let mut v : UInt64 = 0UL
for bi = 0; bi < 8; bi = bi + 1 {
v = (v << 8) | bytes[li * 8 + bi].to_int().to_uint64()
}
limbs[li] = v
}
{ l0: limbs[3], l1: limbs[2], l2: limbs[1], l3: limbs[0], }
}