Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -680,10 +680,10 @@ type Resolver {
"""Every name bound to the same record as this name (record sharing replaces aliasing). Empty on legacy resolvers."""
linkedNames: [LinkedName!]

"""ENSIP-24 data(key) record as 0x-hex bytes (null if unset). From DataUpdated (record resolvers) and DataChanged (legacy)."""
"""ENSIP-24 data(key) record as 0x-hex bytes. From DataUpdated (record resolvers) and DataChanged (legacy). Null means one of two things: no such record, OR a record whose value never existed on chain in plaintext — a resolver may declare `value` as indexed, in which case the log carries only keccak256(value). Distinguish them with events(where: {type: "DataChanged"}): those changes are recorded there and their `data` carries a `valueHash` instead of a `value`."""
data(key: String!): String

"""All data(key) keys set on this resolver/name — a scalar list of keys, like `texts`; read values with `data(key:)`."""
"""The data(key) keys whose value this indexer can serve — a scalar list of keys, like `texts`; read values with `data(key:)`. Deliberately NOT every key ever set: a record whose resolver declared `value` as indexed is omitted, because only keccak256(value) was ever on chain and there is no value to return. Find those via events(where: {type: "DataChanged"}) and the `valueHash` in their `data`."""
dataKeys: [String!]
}

Expand Down
61 changes: 49 additions & 12 deletions src/indexer/replay.zig
Original file line number Diff line number Diff line change
Expand Up @@ -823,9 +823,26 @@ fn replayV2Event(self: *Indexer, q: *Query) !void {
.label_registered => try replayV2LabelRegistered(self, q, data),
.label_reserved => try replayV2LabelReserved(self, q, data),
.transfer => {
const nh = (try v2Namehash(q)) orelse return; // TransferBatch has null namehash -> skip
// Live keys ownership off (id, emitting registry) — handlers_registry's
// handleTransfer via lookupPairedName — and deliberately does nothing when
// that pair is unknown, because a tokenId collides across registries.
// Replaying off the events row's namehash instead is not the same read:
// that column is a denormalised copy, null on an orphaned transfer and
// only later healed by the placeholder repair ledger, so a rebuild
// silently skipped transfers live had applied and applied one live had
// not. Re-derive it the way live does, exactly as .resolver_updated above
// does for the same reason. token_regenerated keeps names.token_id in
// step during replay, so the pair resolves as it did live.
const contract_addr = Address.fromHex(q.getTextSlice(V2_CONTRACT) orelse return) catch return;
const to = Address.fromHex(jsonString(data, "to") orelse return) catch return;
names_storage.updateNameOwner(self.database, .v2, nh, to) catch {};
// TransferBatch emits a single row carrying "count" and no "id": its
// per-token ids never reach the event payload, so no rebuild can
// reproduce them from here. Absent "id" is that row, and it skips.
const id = jsonU256(data, "id") orelse return;
const row = (self.database.getNameByTokenIdAndRegistry(id, contract_addr) catch null) orelse return;
var row_mut = row;
defer row_mut.deinit(self.allocator);
names_storage.updateNameOwner(self.database, .v2, row_mut.namehash, to) catch {};
},
.name_renewed => {
const nh = (try v2Namehash(q)) orelse return;
Expand Down Expand Up @@ -1138,6 +1155,15 @@ fn replayV2RecordEvent(self: *Indexer, q: *Query, et: models.EventType) !void {
},
.data_changed => {
const key = jsonObjStr(obj, "key") orelse return;
// A row written from a log whose `value` parameter was indexed carries
// `valueHash` and no `value`: only keccak256(value) was ever on chain, so
// live stores no value and deletes any stale one. Replay must reach the
// same state, and it must not mistake the hash for a value — hence the
// explicit arm rather than leaning on a missing field defaulting to empty.
if (obj.get("valueHash") != null) {
self.database.deleteResolverData(.v2, nh, resolver, key) catch {};
return;
}
const value = jsonObjStr(obj, "value") orelse "";
if (value.len <= 2) {
self.database.deleteResolverData(.v2, nh, resolver, key) catch {};
Expand Down Expand Up @@ -1629,15 +1655,18 @@ test "replay(events) rebuilds V2 names (main-registry + subregistry + reserved +

const sub_reg = "0x4444444444444444444444444444444444444444"; // subregistry contract for foo.eth

// The emitting contract is part of the fixture, not a placeholder: replay keys
// ownership and resolver updates off (tokenId, emitting registry), so an event
// attributed to the zero address is not a shape live can produce.
const ev = struct {
fn go(db: *db_module.Database, et: models.EventType, name: []const u8, nh: ?Hash, data: []const u8, blk: u64, li: u32) !void {
fn go(db: *db_module.Database, et: models.EventType, name: []const u8, nh: ?Hash, data: []const u8, blk: u64, li: u32, contract: Address) !void {
try @import("../storage/events.zig").insertEvent(db, .{
.event_type = et,
.protocol = .v2,
.block_number = blk,
.tx_hash = Hash.zero,
.log_index = li,
.contract_address = Address.zero,
.contract_address = contract,
.name = name,
.namehash = nh,
.data = data,
Expand All @@ -1656,19 +1685,23 @@ test "replay(events) rebuilds V2 names (main-registry + subregistry + reserved +

const reg_data = try std.fmt.allocPrint(a, "{{\"name\":\"foo.eth\",\"tokenId\":{s},\"owner\":\"{s}\",\"expiry\":1000000,\"sender\":\"{s}\",\"registry\":\"{s}\"}}", .{ bt, o1, o1, r });
defer a.free(reg_data);
try ev(database, .label_registered, "foo.eth", fnh, reg_data, 100, 0);
const xfer_data = try std.fmt.allocPrint(a, "{{\"to\":\"{s}\"}}", .{o2});
const reg_addr = try Address.fromHex(r);
try ev(database, .label_registered, "foo.eth", fnh, reg_data, 100, 0, reg_addr);
// Live's Transfer payload always carries the token id, and ownership is
// keyed off (id, emitting registry) — the events row's namehash is a
// denormalised copy that may still be a placeholder.
const xfer_data = try std.fmt.allocPrint(a, "{{\"to\":\"{s}\",\"id\":{s},\"value\":1}}", .{ o2, bt });
defer a.free(xfer_data);
try ev(database, .transfer, "foo.eth", fnh, xfer_data, 101, 1);
try ev(database, .name_renewed, "foo.eth", fnh, "{\"newExpiry\":2000000}", 102, 2);
try ev(database, .transfer, "foo.eth", fnh, xfer_data, 101, 1, reg_addr);
try ev(database, .name_renewed, "foo.eth", fnh, "{\"newExpiry\":2000000}", 102, 2, reg_addr);

// Subregistry-parented child: bar.foo.eth registered on foo.eth's subregistry
// contract. At index time the handler resolved the parent via `registries` and froze
// "bar.foo.eth" into the event name; replay reconstructs it without touching registries.
const bar_nh = try hash_mod2.namehash(a, "bar.foo.eth");
const child_data = try std.fmt.allocPrint(a, "{{\"name\":\"bar.foo.eth\",\"tokenId\":42,\"canonicalId\":42,\"owner\":\"{s}\",\"expiry\":1500000,\"sender\":\"{s}\",\"registry\":\"{s}\"}}", .{ o1, o1, sub_reg });
defer a.free(child_data);
try ev(database, .label_registered, "bar.foo.eth", bar_nh, child_data, 103, 3);
try ev(database, .label_registered, "bar.foo.eth", bar_nh, child_data, 103, 3, try Address.fromHex(sub_reg));

// V1→V2 LOCKED migration. A pre-existing wrapped V1 row for mig.eth is seeded into BOTH
// DBs (pre-migration state, not a replayed event). When the locked migration controller
Expand Down Expand Up @@ -1707,14 +1740,14 @@ test "replay(events) rebuilds V2 names (main-registry + subregistry + reserved +
});
const mig_data = try std.fmt.allocPrint(a, "{{\"name\":\"mig.eth\",\"tokenId\":77,\"canonicalId\":77,\"owner\":\"{s}\",\"expiry\":2500000,\"sender\":\"{s}\",\"registry\":\"{s}\"}}", .{ o1, mc, r });
defer a.free(mig_data);
try ev(database, .label_registered, "mig.eth", mig_nh, mig_data, 104, 4);
try ev(database, .label_registered, "mig.eth", mig_nh, mig_data, 104, 4, reg_addr);

// Reserved label: owner-zero name row created by a LabelReserved event (the bulk of
// real names). Replay must reconstruct it via replayV2LabelReserved.
const resv_nh = try hash_mod2.namehash(a, "resv.eth");
const resv_data = try std.fmt.allocPrint(a, "{{\"name\":\"resv.eth\",\"tokenId\":88,\"expiry\":1800000,\"sender\":\"{s}\",\"registry\":\"{s}\",\"reserved\":true}}", .{ o1, r });
defer a.free(resv_data);
try ev(database, .label_reserved, "resv.eth", resv_nh, resv_data, 105, 5);
try ev(database, .label_reserved, "resv.eth", resv_nh, resv_data, 105, 5, reg_addr);

if (apply_names) {
// Mirror what the live handlers produce (the ground-truth expected state).
Expand Down Expand Up @@ -2387,7 +2420,11 @@ test "reconstructV2AtBlock matches truncated live replay at every lifecycle chec
.{ .et = .address_changed, .blk = 106, .li = 3, .contract = rsv, .data = "{\"resolver\":\"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"coinType\":60,\"address\":\"0x9999999999999999999999999999999999999999\"}" },
.{ .et = .text_changed, .blk = 108, .li = 4, .contract = rsv, .data = "{\"resolver\":\"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"key\":\"url\",\"value\":\"https://a\"}" },
.{ .et = .text_changed, .blk = 110, .li = 5, .contract = rsv, .data = "{\"resolver\":\"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"key\":\"url\",\"value\":\"\"}" },
.{ .et = .transfer, .blk = 112, .li = 6, .contract = reg, .data = "{\"to\":\"0x2222222222222222222222222222222222222222\"}" },
// Transfer carries its tokenId and is emitted BY the registry; ownership is
// keyed on that pair, so a same-node transfer from a foreign registry is a
// no-op exactly like the ResolverUpdated above.
.{ .et = .transfer, .blk = 111, .li = 11, .contract = wrong_reg, .data = "{\"to\":\"0x4444444444444444444444444444444444444444\",\"id\":500,\"value\":1}" },
.{ .et = .transfer, .blk = 112, .li = 6, .contract = reg, .data = "{\"to\":\"0x2222222222222222222222222222222222222222\",\"id\":500,\"value\":1}" },
.{ .et = .name_renewed, .blk = 114, .li = 7, .contract = reg, .data = "{\"newExpiry\":2000000}" },
.{ .et = .token_regenerated, .blk = 116, .li = 8, .contract = reg, .data = "{\"oldTokenId\":500,\"newTokenId\":501}" },
.{ .et = .name_burned, .blk = 120, .li = 9, .contract = reg, .data = "{\"tokenId\":501}" },
Expand Down
4 changes: 4 additions & 0 deletions src/indexer/utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ pub fn isMalformedEventError(err: anyerror) bool {
// one event; letting it through reached an unchecked add in the codec
// that either panicked or requested 16 EiB, taking the batch with it.
error.AbiPayloadMismatch => true,
// A DNS-wire name whose label length runs past the payload. Now that
// dns.decodeDNSNameToString reports this separately from the root name,
// it reaches here instead of being silently folded into "no name".
error.InvalidDNSEncoding => true,
// Decoded fine but a numeric field exceeds what the schema can hold
// (e.g. a hostile uint256 coinType) — same skip-with-coordinates
// treatment as an undecodable payload.
Expand Down
49 changes: 34 additions & 15 deletions src/indexer/v2/handlers_registry.zig
Original file line number Diff line number Diff line change
Expand Up @@ -499,9 +499,19 @@ pub fn handleTransfer(self: *Indexer, protocol: models.Protocol, log: rpc.Log) !
// With log-index ordering (utils.dispatchOrdered) a Transfer always arrives after its
// LabelRegistered/NameRegistered, so this branch should only fire on reorgs, backfill
// gaps, or genuinely orphaned transfers (non-ENS ERC1155 tokens slipping through the
// topic-only filter). The event is still emitted for audit; ownership just can't be
// applied without a known name.
std.log.warn(" → Transfer for unknown tokenId={d} in registry {any}; ownership not updated", .{ id, log.address });
// topic-only filter). Ownership can't be applied without a known name.
//
// Record the token id as a placeholder name rather than leaving the row
// NULL/NULL. The event was emitted either way, but with no name and no
// namehash it was unreachable from the name it belongs to and nothing
// could ever repair it — a permanent hole in that name's history.
// `tokenId:<dec>` is the repair ledger's key (storage/events.zig
// repairPlaceholderEvents, and the names-side placeholder patch), so a
// later sighting of the same token heals the row to its real name and
// namehash, ambiguity-guarded. This is the same convention
// handleTokenRegenerated and the phase-1 datastore writers already use.
name_str_opt = try std.fmt.allocPrint(self.allocator, "tokenId:{d}", .{id});
std.log.warn(" → Transfer for unknown tokenId={d} in registry {any}; ownership not updated, event left for placeholder repair", .{ id, log.address });
}

defer if (name_str_opt) |n| self.allocator.free(n);
Expand Down Expand Up @@ -915,27 +925,36 @@ pub fn handleTokenRegenerated(self: *Indexer, protocol: models.Protocol, log: rp

try utils.emitEvent(self, protocol, log, .token_regenerated, event_name, namehash, event_data);

// Update token_id in database from old to new (registry-safe: only updates the exact name)
// Cannot use old_token_id alone because it collides across registries
// Two independent re-keyings. They were both gated on a known namehash, but
// only the first one needs it: approvals are keyed by (token_id, registry),
// which this log carries in full. When the name was not yet indexed the
// whole block was skipped, so the approval rows kept pointing at a token id
// the chain had already retired — and, because the name row is re-keyed on
// a later sighting but approvals are not, they stayed stale permanently.
// Each re-keying is now gated on exactly what it reads.

// Keyed by namehash: renaming the token on the name row.
// old_token_id alone will not do — it collides across registries.
if (!namehash.eql(Hash.zero)) {
try self.database.updateNameTokenIdByNamehash(namehash, new_token_id);
std.log.debug("Updated token_id in database: {d} -> {d} for {s}", .{ old_token_id, new_token_id, name_str });

// Note: eac_roles.resource carries the EAC version (bumped on unregister /
// re-register), not the token version, so TokenRegenerated leaves it
// untouched — no update needed.

// Update approvals.token_id from old to new (scoped by registry)
// Approvals are tied to specific token versions, so they must be updated.
const old_token_id_dec = try std.fmt.allocPrint(self.allocator, "{d}", .{old_token_id});
defer self.allocator.free(old_token_id_dec);
const new_token_id_dec = try std.fmt.allocPrint(self.allocator, "{d}", .{new_token_id});
defer self.allocator.free(new_token_id_dec);

try self.database.updateApprovalTokenId(old_token_id_dec, new_token_id_dec, log.address);
} else {
std.log.warn("Cannot update token_id - unknown namehash for oldTokenId={d}", .{old_token_id});
std.log.warn("Cannot update names.token_id - unknown namehash for oldTokenId={d}", .{old_token_id});
}

// Keyed by (token_id, registry), both of which this log supplies directly.
// Approvals are tied to a specific token version, so they must follow the
// regeneration whether or not the name itself is known yet.
const old_token_id_dec = try std.fmt.allocPrint(self.allocator, "{d}", .{old_token_id});
defer self.allocator.free(old_token_id_dec);
const new_token_id_dec = try std.fmt.allocPrint(self.allocator, "{d}", .{new_token_id});
defer self.allocator.free(new_token_id_dec);

try self.database.updateApprovalTokenId(old_token_id_dec, new_token_id_dec, log.address);
}

pub fn handleTransferBatch(self: *Indexer, protocol: models.Protocol, log: rpc.Log) !void {
Expand Down
21 changes: 14 additions & 7 deletions src/indexer/v2/handlers_resolver.zig
Original file line number Diff line number Diff line change
Expand Up @@ -594,11 +594,14 @@ fn handleNamedResourceKind(
var resource_buf: [66]u8 = undefined;
const resource_hex = log.topics[1].toHexBuf(&resource_buf);

const name = (try dns.decodeDNSNameToString(self.allocator, name_bytes)) orelse {
std.log.warn("NamedResource({s}): failed to decode DNS-encoded name for resource {s}", .{ record_kind, resource_hex });
return;
};
defer self.allocator.free(name);
// `null` is the ROOT name (`0x00`), which is the default-record resource —
// not a decode failure. Treating it as one discarded legitimate records;
// `handleLinked` already reads the same null as the default binding. A
// genuinely malformed encoding now arrives as error.InvalidDNSEncoding and
// is skipped by the malformed-event path, with coordinates logged.
const decoded = try dns.decodeDNSNameToString(self.allocator, name_bytes);
defer if (decoded) |d| self.allocator.free(d);
const name: []const u8 = decoded orelse "";

self.database.upsertNamedResource(
protocol,
Expand Down Expand Up @@ -1141,8 +1144,12 @@ pub fn handleAliasChanged(self: *Indexer, protocol: models.Protocol, resolver: A
const to_dns_bytes = data_values[1].bytes;

// Decode DNS wire format to human-readable names
// `null` is the root name, which is not an alias key this table can hold —
// the same convention the toName branch below already applies (root/empty
// means "no alias"). A malformed encoding is a different outcome and now
// propagates as error.InvalidDNSEncoding instead of landing here.
const from_name = (try dns.decodeDNSNameToString(self.allocator, from_dns_bytes)) orelse {
std.log.warn("AliasChanged: failed to decode fromName DNS wire format", .{});
std.log.warn("AliasChanged: fromName is the root name — no alias key to record", .{});
return;
};
defer self.allocator.free(from_name);
Expand All @@ -1162,7 +1169,7 @@ pub fn handleAliasChanged(self: *Indexer, protocol: models.Protocol, resolver: A
};
} else {
const to_name = (try dns.decodeDNSNameToString(self.allocator, to_dns_bytes)) orelse {
std.log.warn("AliasChanged: failed to decode toName DNS wire format", .{});
std.log.warn("AliasChanged: toName is the root name — treating as no alias", .{});
return;
};
defer self.allocator.free(to_name);
Expand Down
Loading
Loading