-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlib.zig
More file actions
247 lines (217 loc) · 10.2 KB
/
Copy pathlib.zig
File metadata and controls
247 lines (217 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
const std = @import("std");
const Allocator = std.mem.Allocator;
const json = std.json;
const params = @import("@zeam/params");
const types = @import("@zeam/types");
const utils = @import("@zeam/utils");
pub const ChainOptions = utils.Partial(utils.MixIn(types.GenesisSpec, types.ChainSpec));
const configs = @import("./configs/mainnet.zig");
const Yaml = @import("yaml").Yaml;
pub const Chain = enum { custom };
pub const ChainConfig = struct {
id: Chain,
genesis: types.GenesisSpec,
spec: types.ChainSpec,
const Self = @This();
// for custom chains
pub fn init(chainId: Chain, chainOptsOrNull: ?ChainOptions) !Self {
switch (chainId) {
.custom => {
if (chainOptsOrNull) |chain_opts_in| {
var chainOpts = chain_opts_in;
if (chainOpts.attestation_committee_count == null) {
chainOpts.attestation_committee_count = 1;
}
if (chainOpts.max_attestations_data == null) {
// MAX_ATTESTATIONS_DATA = 8. Keep the fallback in
// lockstep with params.MAX_ATTESTATIONS_DATA so the builder (config-driven)
// and verifySignatures (params constant) agree when config.yaml omits it.
chainOpts.max_attestations_data = @intCast(params.MAX_ATTESTATIONS_DATA);
} else if (chainOpts.max_attestations_data.? > params.MAX_ATTESTATIONS_DATA) {
// params.MAX_ATTESTATIONS_DATA is the spec ceiling AND the verifySignatures
// hard cap. config.yaml may only LOWER it (e.g. cap=1 for tests); a higher
// value would let the builder assemble blocks the verify path rejects, so
// clamp here — the builder never exceeds what verify accepts.
chainOpts.max_attestations_data = @intCast(params.MAX_ATTESTATIONS_DATA);
}
if (chainOpts.fork_digest == null) {
return ChainConfigError.InvalidChainSpec;
}
const genesis = utils.Cast(types.GenesisSpec, chainOpts);
// transfer ownership of any allocated memory in chainOpts to spec
const spec = utils.Cast(types.ChainSpec, chainOpts);
return Self{
.id = chainId,
.genesis = genesis,
.spec = spec,
};
} else {
return ChainConfigError.InvalidChainSpec;
}
},
}
}
pub fn deinit(self: *Self, allocator: Allocator) void {
self.spec.deinit(allocator);
}
};
const ChainConfigError = error{
InvalidChainSpec,
};
const GenesisConfigError = error{
InvalidYamlShape,
MissingGenesisTime,
InvalidGenesisTime,
MissingValidatorConfig,
InvalidValidatorPubkeys,
ValidatorSigningKeysMustDiffer,
};
/// Parses genesis configuration from YAML.
///
/// Required fields:
/// - `GENESIS_TIME`: integer >= 0
/// - `GENESIS_VALIDATORS`: list of validator entries, each with:
/// - `attestation_pubkey`: 52-byte public key as 104-char hex string
/// - `proposal_pubkey`: 52-byte public key as 104-char hex string
///
/// This matches the cross-client genesis YAML convention.
///
/// Returns `GenesisSpec` with genesis time and validator pubkeys.
/// Errors: `InvalidYamlShape`, `MissingGenesisTime`, `InvalidGenesisTime`, `MissingValidatorConfig`, `InvalidValidatorPubkeys`.
pub fn genesisConfigFromYAML(
allocator: Allocator,
config: Yaml,
override_genesis_time: ?u64,
) !types.GenesisSpec {
if (config.docs.items.len == 0) return GenesisConfigError.InvalidYamlShape;
const root = config.docs.items[0].map;
const genesis_time_node = root.get("GENESIS_TIME") orelse return GenesisConfigError.MissingGenesisTime;
var genesis_time: u64 = switch (genesis_time_node) {
.scalar => |value| blk: {
const parsed = std.fmt.parseInt(u64, value, 10) catch return GenesisConfigError.InvalidGenesisTime;
break :blk parsed;
},
else => return GenesisConfigError.InvalidGenesisTime,
};
if (override_genesis_time) |override| genesis_time = override;
const validators_node = root.get("GENESIS_VALIDATORS") orelse root.get("genesis_validators") orelse return GenesisConfigError.MissingValidatorConfig;
const result = try parseValidatorEntriesFromYaml(allocator, validators_node);
return types.GenesisSpec{
.genesis_time = genesis_time,
.validator_attestation_pubkeys = result.attestation_pubkeys,
.validator_proposal_pubkeys = result.proposal_pubkeys,
};
}
const ValidatorEntries = struct {
attestation_pubkeys: []types.Bytes52,
proposal_pubkeys: []types.Bytes52,
};
/// Parses GENESIS_VALIDATORS as a list of structured entries.
/// Each entry must be a map with `attestation_pubkey` and `proposal_pubkey` fields.
/// This matches the cross-client genesis YAML convention.
fn parseValidatorEntriesFromYaml(
allocator: Allocator,
node: Yaml.Value,
) !ValidatorEntries {
if (node != .list) return GenesisConfigError.InvalidValidatorPubkeys;
const list = node.list;
if (list.len == 0) return GenesisConfigError.InvalidValidatorPubkeys;
var attestation_pubkeys = try allocator.alloc(types.Bytes52, list.len);
errdefer allocator.free(attestation_pubkeys);
var proposal_pubkeys = try allocator.alloc(types.Bytes52, list.len);
errdefer allocator.free(proposal_pubkeys);
for (list, 0..) |item, idx| {
if (item != .map) return GenesisConfigError.InvalidValidatorPubkeys;
const entry_map = item.map;
const att_node = entry_map.get("attestation_pubkey") orelse
return GenesisConfigError.InvalidValidatorPubkeys;
if (att_node != .scalar) return GenesisConfigError.InvalidValidatorPubkeys;
attestation_pubkeys[idx] = try hexToBytes52(att_node.scalar);
const prop_node = entry_map.get("proposal_pubkey") orelse
return GenesisConfigError.InvalidValidatorPubkeys;
if (prop_node != .scalar) return GenesisConfigError.InvalidValidatorPubkeys;
proposal_pubkeys[idx] = try hexToBytes52(prop_node.scalar);
if (std.mem.eql(u8, &attestation_pubkeys[idx], &proposal_pubkeys[idx])) {
return GenesisConfigError.ValidatorSigningKeysMustDiffer;
}
}
return ValidatorEntries{
.attestation_pubkeys = attestation_pubkeys,
.proposal_pubkeys = proposal_pubkeys,
};
}
fn hexToBytes52(input: []const u8) !types.Bytes52 {
// Remove 0x prefix if present
const hex_str = if (std.mem.startsWith(u8, input, "0x"))
input[2..]
else
input;
if (hex_str.len != 104) return GenesisConfigError.InvalidValidatorPubkeys; // 52 bytes = 104 hex chars
var bytes: types.Bytes52 = undefined;
_ = std.fmt.hexToBytes(&bytes, hex_str) catch {
return GenesisConfigError.InvalidValidatorPubkeys;
};
return bytes;
}
test "genesisConfigFromYAML rejects reused validator signing key" {
const yaml_content =
\\GENESIS_TIME: 1
\\GENESIS_VALIDATORS:
\\ - attestation_pubkey: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233"
\\ proposal_pubkey: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233"
;
var yaml: Yaml = .{ .source = yaml_content };
defer yaml.deinit(std.testing.allocator);
try yaml.load(std.testing.allocator);
try std.testing.expectError(
GenesisConfigError.ValidatorSigningKeysMustDiffer,
genesisConfigFromYAML(std.testing.allocator, yaml, null),
);
}
// TODO: Enable and update this test once the YAML parsing for public keys PR is added
// test "load genesis config from yaml" {
// const yaml_content =
// \\# Genesis Settings
// \\GENESIS_TIME: 1704085200
// \\
// \\# Validator Settings
// \\GENESIS_VALIDATORS:
// \\ - attestation_pubkey: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233"
// \\ proposal_pubkey: "a00102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233"
// \\ - attestation_pubkey: "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f3031323334"
// \\ proposal_pubkey: "a102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f3031323334"
// ;
//
// var yaml: Yaml = .{ .source = yaml_content };
// defer yaml.deinit(std.testing.allocator);
// try yaml.load(std.testing.allocator);
//
// const genesis_config = try genesisConfigFromYAML(yaml, null);
//
// try std.testing.expect(genesis_config.genesis_time == 1704085200);
// try std.testing.expect(genesis_config.num_validators() == 2);
//
// const genesis_config_override = try genesisConfigFromYAML(yaml, 1234);
// try std.testing.expect(genesis_config_override.genesis_time == 1234);
// try std.testing.expect(genesis_config_override.num_validators() == 2);
// }
// TODO: Enable and update this test once the keymanager file-reading PR is added (followup PR)
// JSON parsing for genesis config needs to support validator_attestation_pubkeys instead of num_validators
// test "custom dev chain" {
// const dev_spec =
// \\{"preset": "mainnet", "name": "devchain1", "genesis_time": 1244, "num_validators": 4}
// ;
//
// var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
// defer arena_allocator.deinit();
//
// const options = json.ParseOptions{
// .ignore_unknown_fields = true,
// .allocate = .alloc_if_needed,
// };
// const dev_options = (try json.parseFromSlice(ChainOptions, arena_allocator.allocator(), dev_spec, options)).value;
//
// const dev_config = try ChainConfig.init(Chain.custom, dev_options);
// std.debug.print("dev config = {any}\n", .{dev_config});
// std.debug.print("chainoptions = {any}\n", .{ChainOptions{}});
// }