Skip to content

Commit

Permalink
starknet lib
Browse files Browse the repository at this point in the history
  • Loading branch information
StringNick committed May 12, 2024
1 parent 99e82ef commit d2f8a08
Show file tree
Hide file tree
Showing 48 changed files with 385 additions and 53,295 deletions.
4 changes: 4 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ const external_dependencies = [_]build_helpers.Dependency{
.name = "zig-cli",
.module_name = "zig-cli",
},
.{
.name = "starknet",
.module_name = "ziggy-starkdust",
},
};

// Although this function looks imperative, note that its job is to
Expand Down
4 changes: 4 additions & 0 deletions build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@
.url = "https://github.com/sam701/zig-cli/archive/refs/heads/main.tar.gz",
.hash = "1220c008492d9460c3be2b209600a948181e6efb3bf0d79a1633def499632e708f4b",
},
.starknet = .{
.url = "https://github.com/StringNick/starknet-zig/archive/refs/heads/main.tar.gz",
.hash = "1220f85b94b0ac911f29ff79f55e3b87a99b1d39abdf9a9fcade5d92618451879d3f",
},
},
}
4 changes: 2 additions & 2 deletions src/hint_processor/bigint.zig
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ pub fn bigintPackDivModHint(allocator: std.mem.Allocator, vm: *CairoVM, exec_sco
}).pack86(allocator);
defer x_lower.deinit();

var d3 = try x_bigint5.limbs[3].toSignedBigInt(allocator);
var d3 = try x_bigint5.limbs[3].toStdBigSignedInt(allocator);
defer d3.deinit();

var d4 = try x_bigint5.limbs[3].toSignedBigInt(allocator);
var d4 = try x_bigint5.limbs[3].toStdBigSignedInt(allocator);
defer d4.deinit();

var tmp = try Int.init(allocator);
Expand Down
18 changes: 5 additions & 13 deletions src/hint_processor/blake2s_utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const blake2s_hash = @import("blake2s_hash.zig");
const builtin_hints = @import("builtin_hint_codes.zig");

pub fn feltToU32(felt: Felt252) MathError!u32 {
const u256_val = felt.toInteger();
const u256_val = felt.toU256();
if (u256_val > 0xFFFFFFFF) {
return MathError.Felt252ToU32Conversion;
}
Expand Down Expand Up @@ -187,19 +187,15 @@ pub fn blake2sAddUnit256(_: Allocator, vm: *CairoVM, ids_data: std.StringHashMap
defer data.deinit();
// first batch
for (0..4) |_| {
const temp = try low.divRem(mask);
const q = temp.q;
const r = temp.r;
const q, const r = try low.divRem(mask);
try data.append(MaybeRelocatable.fromFelt(r));
low = q;
}
data_ptr = try vm.loadData(data_ptr, &data);
data.shrinkAndFree(0);
// second batch
for (0..4) |_| {
const temp = try high.divRem(mask);
const q = temp.q;
const r = temp.r;
const q, const r = try high.divRem(mask);
try data.append(MaybeRelocatable.fromFelt(r));
high = q;
}
Expand All @@ -224,17 +220,13 @@ pub fn blake2sAddUnit256BigEnd(_: Allocator, vm: *CairoVM, ids_data: std.StringH

// first batch
for (0..4) |_| {
const temp = try low.divRem(mask);
const q = temp.q;
const r = temp.r;
const q, const r = try low.divRem(mask);
try data.append(MaybeRelocatable.fromFelt(r));
low = q;
}
// second batch
for (0..4) |_| {
const temp = try high.divRem(mask);
const q = temp.q;
const r = temp.r;
const q, const r = try high.divRem(mask);
try data.append(MaybeRelocatable.fromFelt(r));
high = q;
}
Expand Down
19 changes: 11 additions & 8 deletions src/hint_processor/builtin_hint_processor/secp/bigint_utils.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const std = @import("std");
const Felt252 = @import("../../../math/fields/starknet.zig").Felt252;
const feltFromBigInt = @import("../../../math/fields/starknet.zig").fromBigInt;
const Relocatable = @import("../../../vm/memory/relocatable.zig").Relocatable;
const CairoVM = @import("../../../vm/core.zig").CairoVM;
const HintError = @import("../../../vm/error.zig").HintError;
Expand All @@ -22,6 +23,8 @@ const BigInt = std.math.big.int.Managed;
const BASE = @import("../../../math//fields/constants.zig").BASE;
const hint_codes = @import("../../builtin_hint_codes.zig");

const field_helper = @import("../../../math/fields/helper.zig");

pub const BigInt3 = BigIntN(3);
pub const Uint384 = BigIntN(3);
pub const Uint256 = BigIntN(2);
Expand Down Expand Up @@ -76,7 +79,7 @@ pub fn BigIntN(comptime NUM_LIMBS: usize) type {
errdefer result.deinit();

inline for (0..3) |i| {
var tmp = try self.limbs[i].toSignedBigInt(allocator);
var tmp = try self.limbs[i].toStdBigSignedInt(allocator);
defer tmp.deinit();

try tmp.shiftLeft(&tmp, i * 86);
Expand Down Expand Up @@ -115,9 +118,9 @@ pub fn nondetBigInt3(allocator: std.mem.Allocator, vm: *CairoVM, exec_scopes: *E
defer for (0..arg.len) |x| arg[x].deinit();

const result: [3]MaybeRelocatable = .{
MaybeRelocatable.fromInt(u512, try arg[0].to(u512)),
MaybeRelocatable.fromInt(u512, try arg[1].to(u512)),
MaybeRelocatable.fromInt(u512, try arg[2].to(u512)),
MaybeRelocatable.fromFelt(try feltFromBigInt(allocator, arg[0])),
MaybeRelocatable.fromFelt(try feltFromBigInt(allocator, arg[1])),
MaybeRelocatable.fromFelt(try feltFromBigInt(allocator, arg[2])),
};

_ = try vm.segments.loadData(allocator, res_reloc, result[0..]);
Expand All @@ -136,7 +139,7 @@ pub fn bigintToUint256(allocator: std.mem.Allocator, vm: *CairoVM, ids_data: std

const mask = pow2ConstNz(128);

const low = (d0.add(d1.mul(base_86))).mod(mask);
const low = (try (d0.add(&d1.mul(&base_86))).divRem(mask))[1];

try hint_utils.insertValueFromVarName(allocator, "low", MaybeRelocatable.fromFelt(low), vm, ids_data, ap_tracking);
}
Expand All @@ -148,13 +151,13 @@ pub fn hiMaxBitlen(vm: *CairoVM, allocator: std.mem.Allocator, ids_data: std.Str
var scalar_v = try BigInt3.fromVarName("scalar_v", vm, ids_data, ap_tracking);

// get number of bits in the highest limb
const len_hi_u = scalar_u.limbs[2].numBits();
const len_hi_v = scalar_v.limbs[2].numBits();
const len_hi_u = scalar_u.limbs[2].numBitsLe();
const len_hi_v = scalar_v.limbs[2].numBitsLe();

const len_hi = @max(len_hi_u, len_hi_v);

// equal to `len_hi.wrapping_sub(1)`
const res = if (len_hi == 0) Felt252.Max.toInteger() else len_hi - 1;
const res = if (len_hi == 0) field_helper.felt252MaxValue().toU256() else len_hi - 1;

try hint_utils.insertValueFromVarName(allocator, "len_hi", MaybeRelocatable.fromInt(u256, res), vm, ids_data, ap_tracking);
}
Expand Down
8 changes: 4 additions & 4 deletions src/hint_processor/builtin_hint_processor/secp/ec_utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ pub fn ecMulInner(
) !void {
//(ids.scalar % PRIME) % 2
var scalar = try hint_utils.getIntegerFromVarName("scalar", vm, ids_data, ap_tracking);
scalar = scalar.mod(Felt252.two());
_, scalar = try scalar.divRem(Felt252.two());

try hint_utils.insertValueIntoAp(allocator, vm, MaybeRelocatable.fromFelt(scalar));
}
Expand Down Expand Up @@ -649,7 +649,7 @@ pub fn nPairBits(
) !void {
const scalar_v = try hint_utils.getIntegerFromVarName("scalar_v", vm, ids_data, ap_tracking);
const scalar_u = try hint_utils.getIntegerFromVarName("scalar_u", vm, ids_data, ap_tracking);
const m = (try hint_utils.getIntegerFromVarName("m", vm, ids_data, ap_tracking)).intoUsizeOrOptional() orelse 253;
const m = (try hint_utils.getIntegerFromVarName("m", vm, ids_data, ap_tracking)).toInt(usize) catch 253;

// If m is too high the shift result will always be zero
if (m >= 253) {
Expand All @@ -660,10 +660,10 @@ pub fn nPairBits(
return HintError.NPairBitsTooLowM;
}

var scalar_v_big = try Int.initSet(allocator, scalar_v.toInteger());
var scalar_v_big = try Int.initSet(allocator, scalar_v.toU256());
defer scalar_v_big.deinit();

var scalar_u_big = try Int.initSet(allocator, scalar_u.toInteger());
var scalar_u_big = try Int.initSet(allocator, scalar_u.toU256());
defer scalar_u_big.deinit();

var result = try Int.initSet(allocator, 0);
Expand Down
4 changes: 2 additions & 2 deletions src/hint_processor/builtin_hint_processor/secp/signature.zig
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ pub fn getPointFromX(
try exec_scopes.assignOrUpdateVariable("SECP_P", .{ .big_int = secp_p });
}

var beta = try (constants.get(secp_utils.BETA) orelse return HintError.MissingConstant).toSignedBigInt(allocator);
var beta = try (constants.get(secp_utils.BETA) orelse return HintError.MissingConstant).toStdBigSignedInt(allocator);
defer beta.deinit();

var x_cube_int = try (try Uint384.fromVarName("x_cube", vm, ids_data, ap_tracking)).pack86(allocator);
Expand All @@ -165,7 +165,7 @@ pub fn getPointFromX(
var y = try field_helper.powModulusBigInt(allocator, y_cube_int, tmp, secp_p);
errdefer y.deinit();

var v = try (try hint_utils.getIntegerFromVarName("v", vm, ids_data, ap_tracking)).toSignedBigInt(allocator);
var v = try (try hint_utils.getIntegerFromVarName("v", vm, ids_data, ap_tracking)).toStdBigSignedInt(allocator);
defer v.deinit();

if (v.isEven() != y.isEven()) {
Expand Down
22 changes: 11 additions & 11 deletions src/hint_processor/cairo_keccak_hints.zig
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ pub fn keccakWriteArgs(
const high = try hint_utils.getIntegerFromVarName("high", vm, ids_data, ap_tracking);

const bound = Felt252.pow2Const(64);
const d1_d0 = try low.divRem(bound);
const d3_d2 = try high.divRem(bound);
const d1, const d0 = try low.divRem(bound);
const d3, const d2 = try high.divRem(bound);

var arg = std.ArrayList(Felt252).init(allocator);
defer arg.deinit();

try arg.appendSlice(&.{
d1_d0.r, d1_d0.q, d3_d2.r, d3_d2.q,
d0, d1, d2, d3,
});

_ = try vm.segments.writeArg(std.ArrayList(Felt252), inputs_ptr, &arg);
Expand Down Expand Up @@ -85,7 +85,7 @@ pub fn compareBytesInWordNondet(
const bytes_in_word = constants
.get(BYTES_IN_WORD) orelse return HintError.MissingConstant;

const value = if (n_bytes.lt(bytes_in_word)) Felt252.one() else Felt252.zero();
const value = if (n_bytes.cmp(&bytes_in_word).compare(.lt)) Felt252.one() else Felt252.zero();

try hint_utils.insertValueIntoAp(allocator, vm, MaybeRelocatable.fromFelt(value));
}
Expand All @@ -108,7 +108,7 @@ pub fn compareKeccakFullRateInBytesNondet(
const keccak_full_rate_in_bytes = constants
.get(KECCAK_FULL_RATE_IN_BYTES_CAIRO_KECCAK) orelse constants.get(KECCAK_FULL_RATE_IN_BYTES_BUILTIN_KECCAK) orelse return HintError.MissingConstant;

const value = if (n_bytes.ge(keccak_full_rate_in_bytes)) Felt252.one() else Felt252.zero();
const value = if (n_bytes.cmp(&keccak_full_rate_in_bytes).compare(.gte)) Felt252.one() else Felt252.zero();
try hint_utils.insertValueIntoAp(allocator, vm, MaybeRelocatable.fromFelt(value));
}

Expand Down Expand Up @@ -139,7 +139,7 @@ pub fn blockPermutationV1(
constants: *std.StringHashMap(Felt252),
) !void {
const keccak_state_size_felts = try (constants
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).intoU64();
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).toInt(u64);

if (keccak_state_size_felts >= 100)
return HintError.InvalidKeccakStateSizeFelt252s;
Expand Down Expand Up @@ -183,7 +183,7 @@ pub fn cairoKeccakIsFullWord(
ids_data: std.StringHashMap(HintReference),
ap_tracking: ApTracking,
) !void {
const n_bytes = (try hint_utils.getIntegerFromVarName("n_bytes", vm, ids_data, ap_tracking)).intoUsize() catch 8;
const n_bytes = (try hint_utils.getIntegerFromVarName("n_bytes", vm, ids_data, ap_tracking)).toInt(usize) catch 8;

const full_word = if (n_bytes >= 8) Felt252.one() else Felt252.zero();
try hint_utils.insertValueFromVarName(allocator, "full_word", MaybeRelocatable.fromFelt(full_word), vm, ids_data, ap_tracking);
Expand All @@ -206,7 +206,7 @@ pub fn blockPermutationV2(
constants: *std.StringHashMap(Felt252),
) !void {
const keccak_state_size_felts = try (constants
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).intoUsize();
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).toInt(usize);

if (keccak_state_size_felts >= 100) {
return HintError.InvalidKeccakStateSizeFelt252s;
Expand Down Expand Up @@ -246,9 +246,9 @@ fn cairoKeccakFinalize(
block_size_limit: usize,
) !void {
const keccak_state_size_felts = try (constants
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).intoUsize();
.get(KECCAK_STATE_SIZE_FELTS) orelse return HintError.MissingConstant).toInt(usize);
const block_size = try (constants
.get(BLOCK_SIZE) orelse return HintError.MissingConstant).intoUsize();
.get(BLOCK_SIZE) orelse return HintError.MissingConstant).toInt(usize);

if (keccak_state_size_felts >= 100) return HintError.InvalidKeccakStateSizeFelt252s;

Expand Down Expand Up @@ -329,7 +329,7 @@ pub fn maybeRelocVecToU64Array(allocator: std.mem.Allocator, vec: []const ?Maybe
for (vec) |maybe_relocatable| {
if (maybe_relocatable) |n| {
switch (n) {
.felt => |num| try array.append(try num.intoU64()),
.felt => |num| try array.append(try num.toInt(u64)),
else => {},
}
} else {
Expand Down
26 changes: 21 additions & 5 deletions src/hint_processor/ec_utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const testing_utils = @import("testing_utils.zig");
const CoreVM = @import("../vm/core.zig");
const field_helper = @import("../math/fields/helper.zig");
const Felt252 = @import("../math/fields/starknet.zig").Felt252;
const fromBigInt = @import("../math/fields/starknet.zig").fromBigInt;
const STARKNET_PRIME = @import("../math/fields/fields.zig").STARKNET_PRIME;
const SIGNED_FELT_MAX = @import("../math/fields/fields.zig").SIGNED_FELT_MAX;
const MaybeRelocatable = @import("../vm/memory/relocatable.zig").MaybeRelocatable;
Expand Down Expand Up @@ -95,6 +96,12 @@ fn randomEcPointSeeded(allocator: std.mem.Allocator, seed_bytes: []const u8) !st
var buffer: [1]u8 = undefined;
var hash_buffer: [@sizeOf(u256)]u8 = undefined;

var tmp = try std.math.big.int.Managed.init(allocator);
defer tmp.deinit();

var tmp1 = try std.math.big.int.Managed.init(allocator);
defer tmp1.deinit();

for (0..100) |i| {
// Calculate x
std.mem.writeInt(u8, &buffer, @intCast(i), .little);
Expand All @@ -113,7 +120,16 @@ fn randomEcPointSeeded(allocator: std.mem.Allocator, seed_bytes: []const u8) !st
const y_coef = std.math.pow(i32, -1, seed[0] & 1);

// Calculate y
if (recoverY(x)) |y| return .{ Felt252.fromInt(u256, x), Felt252.fromSignedInt(@as(i256, @intCast(y)) * y_coef) };
if (recoverY(x)) |y| {
try tmp.set(y_coef);
try tmp1.set(y);
try tmp.mul(&tmp1, &tmp);

return .{
Felt252.fromInt(u256, x),
try fromBigInt(allocator, tmp),
};
}
}

return HintError.RandomEcPointNotOnCurve;
Expand Down Expand Up @@ -155,10 +171,10 @@ pub fn chainedEcOpRandomEcPointHint(
) !void {
const n_elms_f = try hint_utils.getIntegerFromVarName("len", vm, ids_data, ap_tracking);

if (n_elms_f.isZero() or (if (n_elms_f.intoUsizeOrOptional() == null) true else false))
if (n_elms_f.isZero() or (if (n_elms_f.toInt(usize) catch null == null) true else false))
return HintError.InvalidLenValue;

const n_elms = n_elms_f.intoUsizeOrOptional().?;
const n_elms = try n_elms_f.toInt(usize);
const p = try EcPoint.fromVarName("p", vm, ids_data, ap_tracking);
const m = try hint_utils.getPtrFromVarName("m", vm, ids_data, ap_tracking);
const q = try hint_utils.getPtrFromVarName("q", vm, ids_data, ap_tracking);
Expand Down Expand Up @@ -202,7 +218,7 @@ pub fn recoverYHint(
try vm.insertInMemory(allocator, p_addr, MaybeRelocatable.fromFelt(p_x));
const p_y = Felt252.fromInt(
u256,
recoverY(p_x.toInteger()) orelse return HintError.RecoverYPointNotOnCurve,
recoverY(p_x.toU256()) orelse return HintError.RecoverYPointNotOnCurve,
);

try vm.insertInMemory(
Expand All @@ -224,7 +240,7 @@ fn recoverY(x: u256) ?u256 {
const y_squared: u512 = field_helper.powModulus(x, 3, STARKNET_PRIME) + ALPHA * x + BETA;

return if (isQuadResidue(y_squared))
Felt252.fromInt(u512, y_squared).sqrt().?.toInteger()
Felt252.fromInt(u256, @intCast(y_squared % STARKNET_PRIME)).sqrt().?.toU256()
else
null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/hint_processor/felt_bit_length.zig
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn getFeltBitLength(
try hint_utils.insertValueFromVarName(
allocator,
"bit_length",
MaybeRelocatable.fromInt(usize, x.numBits()),
MaybeRelocatable.fromInt(usize, x.numBitsLe()),
vm,
ids_datas,
ap_tracking,
Expand Down
Loading

0 comments on commit d2f8a08

Please sign in to comment.