From 53b80d8b31aa46fb3056e27722b6ed9c4f821b18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Wed, 30 Sep 2026 14:27:27 +0200 Subject: [PATCH 1/3] fix(indexer): correct v2 event attribution and record-value handling Index the indexed-value DataChanged variant, split the DNS root name from a malformed encoding, key transfer ownership on (token id, emitting registry) in replay and at-block too, and degate the approvals re-key. --- src/indexer/replay.zig | 61 ++++- src/indexer/utils.zig | 4 + src/indexer/v2/handlers_registry.zig | 49 ++-- src/indexer/v2/handlers_resolver.zig | 21 +- src/indexer/v2/handlers_resolver_records.zig | 228 ++++++++++++++++--- src/indexer_test.zig | 183 ++++++++++++++- src/storage/at_block.zig | 13 +- src/utils/dns.zig | 26 ++- tests/conformance/runner.zig | 5 +- 9 files changed, 509 insertions(+), 81 deletions(-) diff --git a/src/indexer/replay.zig b/src/indexer/replay.zig index 6dbf909..9aaeaad 100644 --- a/src/indexer/replay.zig +++ b/src/indexer/replay.zig @@ -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; @@ -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 {}; @@ -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, @@ -1656,11 +1685,15 @@ 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 @@ -1668,7 +1701,7 @@ test "replay(events) rebuilds V2 names (main-registry + subregistry + reserved + 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 @@ -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). @@ -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}" }, diff --git a/src/indexer/utils.zig b/src/indexer/utils.zig index 0f1c022..d1fad21 100644 --- a/src/indexer/utils.zig +++ b/src/indexer/utils.zig @@ -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. diff --git a/src/indexer/v2/handlers_registry.zig b/src/indexer/v2/handlers_registry.zig index 41a0f5e..36f1ddd 100644 --- a/src/indexer/v2/handlers_registry.zig +++ b/src/indexer/v2/handlers_registry.zig @@ -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:` 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); @@ -915,8 +925,16 @@ 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 }); @@ -924,18 +942,19 @@ pub fn handleTokenRegenerated(self: *Indexer, protocol: models.Protocol, log: rp // 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 { diff --git a/src/indexer/v2/handlers_resolver.zig b/src/indexer/v2/handlers_resolver.zig index 9a33692..0895957 100644 --- a/src/indexer/v2/handlers_resolver.zig +++ b/src/indexer/v2/handlers_resolver.zig @@ -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, @@ -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); @@ -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); diff --git a/src/indexer/v2/handlers_resolver_records.zig b/src/indexer/v2/handlers_resolver_records.zig index 42b487d..39bfc69 100644 --- a/src/indexer/v2/handlers_resolver_records.zig +++ b/src/indexer/v2/handlers_resolver_records.zig @@ -25,6 +25,27 @@ const unicode = @import("../../utils/unicode.zig"); const json_utils = @import("../../utils/json.zig"); const dns = @import("../../utils/dns.zig"); const record_model = @import("../../storage/resolver_records.zig"); +const keccak = @import("../../utils/keccak.zig"); + +/// keccak256 of the empty byte string — what an `indexed bytes` topic carries +/// when the value is empty. It is the one hashed value whose preimage IS known, +/// and it means the record was cleared. +const KECCAK_EMPTY = Hash{ .bytes = keccak.keccak256("") }; + +/// What a single log lets us assert about a record's value. +/// +/// `indexed` is not part of an event signature hash, so two contracts can emit +/// the same topic0 while disagreeing on which parameters reach `data`. For +/// DataChanged both shapes occur in the wild, and this is exactly what they +/// differ in: whether the value arrives verbatim or only as its keccak256. +const RecordValue = union(enum) { + /// The value arrived verbatim in the payload. Empty means "cleared". + plain: []const u8, + /// The emitter declared `value` as `indexed`, so the log carries only + /// keccak256(value). No preimage is derivable from the log, so the record's + /// value cannot be asserted — see storeDataRecord for what is written. + hashed: Hash, +}; const RecordRef = struct { id: u256, @@ -238,27 +259,54 @@ pub fn handleDataUpdated(self: *Indexer, protocol: models.Protocol, resolver: Ad const rec = recordFromTopic(log) orelse return; const data_values = try abi.decodeValues(log.data, &.{ .string, .bytes }, self.allocator); defer abi.freeValues(data_values, self.allocator); - try storeDataRecord(self, protocol, resolver, log, rec.key, data_values[0].string, data_values[1].bytes, "DataUpdated", .data_updated, rec.id); + try storeDataRecord(self, protocol, resolver, log, rec.key, data_values[0].string, .{ .plain = data_values[1].bytes }, "DataUpdated", .data_updated, rec.id); } /// DataChanged(bytes32 indexed node, string indexed indexedKey, string key, bytes value) /// Legacy node-keyed `data(key)` record (PublicResolverV2, older PermissionedResolver). +/// +/// `indexed` is NOT part of the signature hash, so this one topic0 is emitted by +/// contracts that disagree on how many of those four parameters reach `data`. +/// Both live shapes are handled, dispatched on the observable topic count: +/// +/// 3 topics — `node` and `indexedKey` indexed: `data` = (string key, bytes value). +/// 4 topics — `value` indexed as well: `data` = (string key) alone, and +/// topics[3] = keccak256(value). +/// +/// Every log this signature has produced on Sepolia (79 logs, 26 distinct +/// emitters, blocks 9.5M–11.8M) is the 4-topic shape, and all 79 satisfy +/// keccak256(key) == topics[2]. So a `topics.len != 3` guard rejected every one +/// of them, while decoding a 4-topic payload against the two-parameter schema +/// read the key's length word as the value's tail offset, landed mid-word and +/// took a payload byte as a length — which is how one such log reached an +/// unchecked add in the codec and stalled a sync. +/// +/// The 4-topic arm does not assume its layout, it proves it: the key it decodes +/// must hash to topics[2], the indexed copy. A contract that indexed some other +/// parameter fails that check and is skipped rather than written under a wrong +/// key. The 3-topic arm needs no such proof — both key and value are in `data`, +/// so nothing there is inferred from a topic. pub fn handleDataChanged(self: *Indexer, protocol: models.Protocol, resolver: Address, log: rpc.Log) !void { - // Exactly 3 topics, not "at least 2". `indexed` is NOT part of the signature - // hash, so a contract declaring the same `DataChanged(bytes32,string,string,bytes)` - // with THREE indexed parameters emits an identical topic0 while leaving only - // one parameter in `data`. Decoding that against the two-parameter schema - // below reads the first value's length word as the second value's tail - // offset, lands mid-word and takes a payload byte as a length — which is how - // one such log reached an unchecked add in the codec and stalled a sync. - // The layout of the extra indexed parameter is unknowable from the hash, so - // skip rather than guess: a wrong key/value pair is worse than a missing one. - if (log.topics.len != 3) return error.InvalidTopicCount; + if (log.topics.len != 3 and log.topics.len != 4) return error.InvalidTopicCount; + const value_is_indexed = log.topics.len == 4; var namehash = log.topics[1]; - const data_values = try abi.decodeValues(log.data, &.{ .string, .bytes }, self.allocator); + + const data_values = try abi.decodeValues( + log.data, + if (value_is_indexed) &.{.string} else &.{ .string, .bytes }, + self.allocator, + ); defer abi.freeValues(data_values, self.allocator); + const key = data_values[0].string; + + const value: RecordValue = if (value_is_indexed) blk: { + const key_hash = try hash_mod.keccak256(self.allocator, key); + if (!key_hash.eql(log.topics[2])) return error.AbiPayloadMismatch; + break :blk .{ .hashed = log.topics[3] }; + } else .{ .plain = data_values[1].bytes }; + if (!try utils.resolveNamehash(self, protocol, &namehash, resolver, "DataChanged")) return; - try storeDataRecord(self, protocol, resolver, log, namehash, data_values[0].string, data_values[1].bytes, "DataChanged", .data_changed, null); + try storeDataRecord(self, protocol, resolver, log, namehash, key, value, "DataChanged", .data_changed, null); } fn storeDataRecord( @@ -268,7 +316,7 @@ fn storeDataRecord( log: rpc.Log, row_key: Hash, key: []const u8, - value: []const u8, + value: RecordValue, event_name: []const u8, event_type: models.EventType, record_id: ?u256, @@ -280,13 +328,48 @@ fn storeDataRecord( std.log.warn("{s} key rejected ({any}) at block {d} tx {s} log_index {d} — event skipped", .{ event_name, err, log.block_number, log.transaction_hash.toHexBuf(&tx_buf), log.log_index }); return; }; - const value_hex = try bytesToHexAlloc(self.allocator, value); + const value_hex = switch (value) { + .plain => |bytes| try bytesToHexAlloc(self.allocator, bytes), + .hashed => |h| try h.toHex(self.allocator), + }; defer self.allocator.free(value_hex); - if (value.len == 0) { + // Three outcomes, and the middle one is why RecordValue exists. + // + // - a verbatim value → the row asserts it; + // - cleared, either a verbatim empty value or the indexed keccak256("") → + // delete, the record has no value; + // - an indexed value that is NOT the empty one → the plaintext is not + // derivable from the log. `resolver_datas.value` holds the record's + // current plaintext (TEXT NOT NULL, one row per protocol/resolver/ + // namehash/key), so there is nothing truthful to put in it: "" already + // means cleared, and the keccak would read back as a 32-byte value the + // record does not have. Keeping a pre-existing row is worse still — the + // chain says the value changed, so a stored one is now known to be + // stale. The row goes, and the change is kept in event history where the + // hash travels under its own name (`valueHash`, never `value`). + const cleared = switch (value) { + .plain => |bytes| bytes.len == 0, + .hashed => |h| h.eql(KECCAK_EMPTY), + }; + const can_assert_value = value == .plain; + if (cleared) { + // House convention for a clear, shared with every other record kind in this + // file: warn and carry on. The stored value was correct at some block, so a + // failed delete leaves stale-but-once-true data that a resync heals. self.database.deleteResolverData(protocol, row_key, resolver, clean_key) catch |err| { std.log.warn("Failed to delete cleared resolver data: {}", .{err}); }; + } else if (!can_assert_value) { + var tx_buf: [66]u8 = undefined; + std.log.warn("{s}: `value` is indexed on this emitter, so only keccak256(value) is on chain — key '{s}' keeps no stored value (block {d} tx {s} log_index {d}); the change is recorded in event history", .{ event_name, clean_key, log.block_number, log.transaction_hash.toHexBuf(&tx_buf), log.log_index }); + // Deliberately NOT best-effort, unlike the clear above. This delete is the + // only thing between a reader and a value the chain has explicitly + // superseded, and "no row is the truthful representation" is only true if it + // actually happened. Swallowing the error would commit the batch and advance + // the sync cursor past the log, serving a known-wrong value as current until + // a full resync. Failing here retries it, exactly as a failed store does. + try self.database.deleteResolverData(protocol, row_key, resolver, clean_key); } else { try self.database.storeResolverData(row_key, resolver, clean_key, value_hex, protocol, log.block_number, log.transaction_hash, try self.getBlockTimestamp(protocol, log.block_number, log.block_timestamp)); } @@ -297,10 +380,18 @@ fn storeDataRecord( defer self.allocator.free(key_hex); const escaped_key = try json_utils.escapeString(self.allocator, clean_key); defer self.allocator.free(escaped_key); + // A hash is published under `valueHash`, never `value`: every reader of + // these rows (the API's event value field, replay, at-block reconstruction) + // treats `value` as the record's plaintext, and a keccak sitting in that + // field would be served as if it were one. + const value_field = switch (value) { + .plain => "value", + .hashed => "valueHash", + }; const event_data = if (record_id) |id| - try std.fmt.allocPrint(self.allocator, "{{\"resolver\":\"{s}\",\"recordId\":\"{d}\",\"key\":\"{s}\",\"value\":\"{s}\"}}", .{ resolver_hex, id, escaped_key, value_hex }) + try std.fmt.allocPrint(self.allocator, "{{\"resolver\":\"{s}\",\"recordId\":\"{d}\",\"key\":\"{s}\",\"{s}\":\"{s}\"}}", .{ resolver_hex, id, escaped_key, value_field, value_hex }) else - try std.fmt.allocPrint(self.allocator, "{{\"namehash\":\"{s}\",\"resolver\":\"{s}\",\"key\":\"{s}\",\"value\":\"{s}\"}}", .{ key_hex, resolver_hex, escaped_key, value_hex }); + try std.fmt.allocPrint(self.allocator, "{{\"namehash\":\"{s}\",\"resolver\":\"{s}\",\"key\":\"{s}\",\"{s}\":\"{s}\"}}", .{ key_hex, resolver_hex, escaped_key, value_field, value_hex }); const domain_name = if (record_id == null) self.getNameFromNamehash(row_key) else null; try utils.emitEvent(self, protocol, log, event_type, domain_name, row_key, event_data); } @@ -732,27 +823,98 @@ test "record handlers: ResourceArgument and legacy DataChanged" { defer db.allocator.free(v); try testing.expectEqualStrings("0x01", v); - // The production shape that stalled a sync. The SAME DataChanged signature - // hash, emitted by a contract that marks three parameters `indexed` — so a - // single value sits in `data` instead of two. `indexed` is not part of the - // topic0 hash, so it lands in this handler regardless, and decoding it as two - // parameters read the first value's length word as the second's tail offset. - // Skipped, not guessed: the extra indexed parameter's identity is not - // recoverable, and a wrong key/value pair is worse than a missing one. - const three_indexed = try rig.log( + // The production shape that stalled a sync: the SAME DataChanged signature + // hash from a contract that marks `value` indexed too, so ONE value sits in + // `data` instead of two and topics[3] carries keccak256(value). `indexed` is + // not part of topic0, so it lands in this handler regardless, and decoding it + // as two parameters read the key's length word as the value's tail offset. + // This is the ONLY shape this signature has produced on Sepolia (79 logs, + // 26 emitters), so it must be indexed, not rejected. + const pkey = "knowledge.proposal.acme-dev.eth"; + const pkey_hash = try hash_mod.keccak256(a, pkey); + var value_hash: [32]u8 = undefined; + std.crypto.hash.sha3.Keccak256.hash(&[_]u8{ 0x07, 0x07 }, &value_hash, .{}); + try handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( TEST_LEGACY, - &.{ wordHash(0), node, wordHash(0), wordHash(0) }, - try abiEncode(a, &.{.{ .dyn = "knowledge.proposal.acme-dev.eth" }}), - ); - try testing.expectError(error.InvalidTopicCount, handleDataChanged(idx, .v2, TEST_LEGACY, three_indexed)); - // ...and the error must be on the skip list, or dispatch aborts the batch - // instead of dropping the single event. + &.{ wordHash(0), node, pkey_hash, Hash{ .bytes = value_hash } }, + try abiEncode(a, &.{.{ .dyn = pkey }}), + )); + // No value is stored: only keccak256(value) was ever on chain, and + // resolver_datas.value is the record's plaintext. Writing the hash there + // would be served as the value; writing "" would read back as "cleared". + try testing.expectEqual(@as(?[]u8, null), try db.getDataRecord(TEST_LEGACY, node, pkey)); + // The change is not lost, though — it is in event history, with the hash + // under its own field name so no reader mistakes it for a value. + { + const nh_hex = try node.toHex(a); + const events = try db.getEventsByNamehash(nh_hex, 100); + defer { + for (events) |*e| e.deinit(db.allocator); + db.allocator.free(events); + } + var saw = false; + for (events) |e| { + if (e.event_type != .data_changed) continue; + if (std.mem.indexOf(u8, e.data, pkey) == null) continue; + saw = true; + try testing.expect(std.mem.indexOf(u8, e.data, "\"valueHash\":") != null); + try testing.expect(std.mem.indexOf(u8, e.data, "\"value\":") == null); + } + try testing.expect(saw); + } + + // A value change we cannot read must not leave a previous value standing: + // the chain says the record changed, so a stored plaintext is now known to be + // stale. "blob" was written verbatim above; re-emitting it with an indexed + // value drops the row rather than keeping the old 0x01. + var blob_key_hash: [32]u8 = undefined; + std.crypto.hash.sha3.Keccak256.hash("blob", &blob_key_hash, .{}); + try handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( + TEST_LEGACY, + &.{ wordHash(0), node, Hash{ .bytes = blob_key_hash }, Hash{ .bytes = value_hash } }, + try abiEncode(a, &.{.{ .dyn = "blob" }}), + )); + try testing.expectEqual(@as(?[]u8, null), try db.getDataRecord(TEST_LEGACY, node, "blob")); + + // keccak256("") is the one hashed value whose preimage IS known: it means + // cleared, and takes the ordinary delete path. + try handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( + TEST_LEGACY, + &.{ wordHash(0), node, Hash{ .bytes = blob_key_hash }, KECCAK_EMPTY }, + try abiEncode(a, &.{.{ .dyn = "blob" }}), + )); + try testing.expectEqual(@as(?[]u8, null), try db.getDataRecord(TEST_LEGACY, node, "blob")); + + // The 4-topic arm PROVES its layout instead of assuming it: the decoded key + // must hash to topics[2], the indexed copy. A contract that indexed some + // other parameter fails here and is skipped, never written under a wrong key. + try testing.expectError(error.AbiPayloadMismatch, handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( + TEST_LEGACY, + &.{ wordHash(0), node, wordHash(0xdeadbeef), Hash{ .bytes = value_hash } }, + try abiEncode(a, &.{.{ .dyn = pkey }}), + ))); + // Neither shape is 2 or 5 topics; those stay rejected outright. + try testing.expectError(error.InvalidTopicCount, handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( + TEST_LEGACY, + &.{ wordHash(0), node }, + try abiEncode(a, &.{.{ .dyn = pkey }}), + ))); + try testing.expectError(error.InvalidTopicCount, handleDataChanged(idx, .v2, TEST_LEGACY, try rig.log( + TEST_LEGACY, + &.{ wordHash(0), node, pkey_hash, Hash{ .bytes = value_hash }, wordHash(1) }, + try abiEncode(a, &.{.{ .dyn = pkey }}), + ))); + // ...and every rejection must be on the skip list, or dispatch aborts the + // whole batch instead of dropping the single event. try testing.expect(utils.isMalformedEventError(error.InvalidTopicCount)); try testing.expect(utils.isMalformedEventError(error.AbiPayloadMismatch)); + + // "blob" was stored then dropped, and the indexed-value key never stored a + // value, so no data row survives on this node. const keys = try db.getDataKeys(TEST_LEGACY, node); defer { for (keys) |k| db.allocator.free(k); db.allocator.free(keys); } - try testing.expectEqual(@as(usize, 1), keys.len); + try testing.expectEqual(@as(usize, 0), keys.len); } diff --git a/src/indexer_test.zig b/src/indexer_test.zig index 5e3c624..cfca985 100644 --- a/src/indexer_test.zig +++ b/src/indexer_test.zig @@ -23,6 +23,7 @@ comptime { const dns = @import("utils/dns.zig"); const token_id = @import("types/token_id.zig"); +const models_mod = @import("types/models.zig"); fn expectDns(a: std.mem.Allocator, wire: []const u8, want: []const u8) !void { const got = (try dns.decodeDNSNameToString(a, wire)) orelse return error.TestUnexpectedResult; @@ -32,9 +33,13 @@ fn expectDns(a: std.mem.Allocator, wire: []const u8, want: []const u8) !void { // Pins the semantics the V2 resolver handlers rely on after the duplicate // decoder was folded into utils/dns.zig: identical dotted-name output on valid -// (and tolerated-malformed) input, and null — never a decode error — on -// rejected input, which the call sites turn into warn/skip via `orelse`. -test "decodeDNSNameToString: DNS wire-format → dotted name; failures fold to null" { +// input, `null` for THE ROOT NAME and nothing else, and a propagated +// `error.InvalidDNSEncoding` for a malformed encoding. +// +// This test previously asserted that malformed input and the root name BOTH +// produced null. That is what let handleNamedResourceKind discard three real +// root-name records as undecodable, so the two outcomes are now pinned apart. +test "decodeDNSNameToString: dotted name; null means root; malformed errors" { const a = std.testing.allocator; try expectDns(a, "\x03eth\x00", "eth"); try expectDns(a, "\x05alice\x03eth\x00", "alice.eth"); @@ -43,11 +48,13 @@ test "decodeDNSNameToString: DNS wire-format → dotted name; failures fold to n try expectDns(a, "\x03eth", "eth"); // Bytes after the root terminator are ignored, not an error. try expectDns(a, "\x03eth\x00junk", "eth"); - // Rejected inputs fold to null: empty, label running past the buffer, - // and a bare root terminator (no labels). - try std.testing.expectEqual(@as(?[]const u8, null), try dns.decodeDNSNameToString(a, "")); - try std.testing.expectEqual(@as(?[]const u8, null), try dns.decodeDNSNameToString(a, "\x05ab")); + // Zero labels is the root name — reported as null, and NOT as a failure. try std.testing.expectEqual(@as(?[]const u8, null), try dns.decodeDNSNameToString(a, "\x00")); + try std.testing.expectEqual(@as(?[]const u8, null), try dns.decodeDNSNameToString(a, "")); + // A label length that runs past the payload is malformed. It must surface as + // an error so utils.isMalformedEventError can skip that one event with its + // coordinates, instead of masquerading as the root name. + try std.testing.expectError(error.InvalidDNSEncoding, dns.decodeDNSNameToString(a, "\x05ab")); } test "getCanonicalId: clears the low 32 version bits (EAC/token-id stability)" { @@ -497,3 +504,165 @@ test "buffered V2 name inserts are landed by the names barrier before any direct try std.testing.expectEqual(base + 1, try countNames.run(&database)); try std.testing.expect((try database.getNameByNamehash(nh_b)) == null); } + +// Both of the following pinned nothing before: sabotaging either fix left the +// whole suite green, which is how the defects survived in the first place. + +test "Transfer for an unknown tokenId records a repairable placeholder, not a nameless event" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + var cfg = @import("config.zig").Config.fromEnv(allocator) catch return; + cfg.status_port = null; + cfg.webhooks_enabled = false; + defer cfg.deinit(); + var threaded = std.Io.Threaded.init(allocator, .{}); + defer threaded.deinit(); + + const db_mod = @import("storage/database.zig"); + var database = try db_mod.Database.init(allocator, ":memory:"); + defer database.deinit(); + const Indexer = @import("indexer/indexer.zig").Indexer; + var idx = try Indexer.init(allocator, threaded.io(), cfg, &database, null); + defer idx.deinit(); + + const hash_mod = @import("types/hash.zig"); + const Hash = hash_mod.Hash; + const Address = @import("types/address.zig").Address; + const abi = @import("indexer/abi.zig"); + const v1_names = @import("utils/v1_names.zig"); + + // A registry of our own, not cfg.v2_contracts: both handlers key only off + // `log.address`, and the configured registry is the zero address whenever the + // deployment env is absent — which silently skipped this test. + const eth_registry = try Address.fromHex("0x7777777777777777777777777777777777777777"); + + // Canonical (low 32 version bits zero) so the repair's canonical-id lookup is exact. + const tok: u256 = @as(u256, 0x5EED) << 32; + const to = try Address.fromHex("0x2222222222222222222222222222222222222222"); + var to_topic = Hash.zero; + @memcpy(to_topic.bytes[12..32], &to.bytes); + + // TransferSingle(operator, from, to, id, value) — arriving BEFORE the name is + // known (a reorg, a backfill gap, or an orphaned transfer). + var topics = [_]Hash{ abi.EventSignatures.transfer_single_hash, Hash.zero, Hash.zero, to_topic }; + var data = [_]u8{0} ** 64; + std.mem.writeInt(u256, data[0..32], tok, .big); + std.mem.writeInt(u256, data[32..64], 1, .big); + try Indexer.handleTransfer(&idx, .v2, syntheticLog(eth_registry, topics[0..], data[0..], 300, 1_700_000_300)); + + // The event must be addressable by its token id. Written with a null name and + // null namehash it was unreachable from the name it belongs to and nothing + // could ever repair it — a permanent hole in that name's history. + const placeholder = try std.fmt.allocPrint(allocator, "tokenId:{d}", .{tok}); + { + const evs = try database.getEventsByDomain(placeholder, 10); + defer { + for (evs) |*e| e.deinit(database.allocator); + database.allocator.free(evs); + } + try std.testing.expectEqual(@as(usize, 1), evs.len); + try std.testing.expectEqual(models_mod.EventType.transfer, evs[0].event_type); + } + + // Once the name is known, the existing placeholder ledger heals the row — + // which is the whole reason the placeholder name is the right thing to write. + const nh = try hash_mod.namehash(allocator, "xfer.eth"); + try idx.insertName(.{ + .name = "xfer.eth", + .label = "xfer", + .label_hash = v1_names.computeLabelHash("xfer"), + .parent_name = "eth", + .parent_namehash = idx.eth_namehash, + .protocol = .v2, + .registry = eth_registry, + .owner = to, + .registrant = to, + .resolver = Address.zero, + .token_id = tok, + .canonical_id = tok, + .token_version = 0, + .namehash = nh, + .expiry = 1_900_000_000, + .registry_locked = false, + .migrated = false, + .created_block = 299, + .created_at = 1_700_000_299, + .registered_at = 1_700_000_299, + .updated_block = 299, + .updated_at = 1_700_000_299, + .is_wrapped = false, + .wrapper_fuses = null, + .wrapper_expiry = null, + .is_v1_name = false, + .v1_label_hash = null, + }); + try std.testing.expectEqual(@as(usize, 1), try database.repairPlaceholderEvents(.v2, 0, 1000)); + { + const evs = try database.getEventsByDomain("xfer.eth", 10); + defer { + for (evs) |*e| e.deinit(database.allocator); + database.allocator.free(evs); + } + try std.testing.expectEqual(@as(usize, 1), evs.len); + try std.testing.expect(evs[0].namehash.?.eql(nh)); + } +} + +test "TokenRegenerated re-keys approvals even when the name is not indexed yet" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + var cfg = @import("config.zig").Config.fromEnv(allocator) catch return; + cfg.status_port = null; + cfg.webhooks_enabled = false; + defer cfg.deinit(); + var threaded = std.Io.Threaded.init(allocator, .{}); + defer threaded.deinit(); + + const db_mod = @import("storage/database.zig"); + var database = try db_mod.Database.init(allocator, ":memory:"); + defer database.deinit(); + const Indexer = @import("indexer/indexer.zig").Indexer; + var idx = try Indexer.init(allocator, threaded.io(), cfg, &database, null); + defer idx.deinit(); + + const hash_mod = @import("types/hash.zig"); + const Hash = hash_mod.Hash; + const Address = @import("types/address.zig").Address; + const abi = @import("indexer/abi.zig"); + + // A registry of our own, not cfg.v2_contracts: both handlers key only off + // `log.address`, and the configured registry is the zero address whenever the + // deployment env is absent — which silently skipped this test. + const eth_registry = try Address.fromHex("0x7777777777777777777777777777777777777777"); + + const old_token_id: u256 = 900; + const new_token_id: u256 = 901; + const owner = try Address.fromHex("0x1111111111111111111111111111111111111111"); + const operator = try Address.fromHex("0x3333333333333333333333333333333333333333"); + try database.insertApproval(.v2, old_token_id, owner, operator, 100, Hash.zero, eth_registry); + + // TokenRegenerated(oldTokenId, newTokenId), both indexed, for a token whose + // name this indexer has never seen. Approvals are keyed by (token_id, + // registry) — both of which this log supplies — so the re-key must happen + // regardless. It used to sit inside the "namehash is known" branch, which + // left the approval pointing at a token id the chain had already retired, + // permanently: a later sighting re-keys the name row but never the approval. + var old_topic = Hash.zero; + std.mem.writeInt(u256, &old_topic.bytes, old_token_id, .big); + var new_topic = Hash.zero; + std.mem.writeInt(u256, &new_topic.bytes, new_token_id, .big); + var topics = [_]Hash{ abi.EventSignatures.token_regenerated_hash, old_topic, new_topic }; + var empty: [0]u8 = .{}; + try Indexer.handleTokenRegenerated(&idx, .v2, syntheticLog(eth_registry, topics[0..], empty[0..], 400, 1_700_000_400)); + + const Query = db_mod.Query; + var q = try Query.init(&database, "SELECT token_id FROM approvals WHERE registry = ? AND protocol = ?"); + defer q.deinit(); + try q.bindAddress(eth_registry); + try q.bindTextStatic("v2"); + try std.testing.expect(try q.step()); + try std.testing.expectEqualStrings("901", q.getTextSlice(0).?); + try std.testing.expect(!try q.step()); +} diff --git a/src/storage/at_block.zig b/src/storage/at_block.zig index 9e1dfad..7ec5ce2 100644 --- a/src/storage/at_block.zig +++ b/src/storage/at_block.zig @@ -182,8 +182,19 @@ fn applyEvent(st: *AtBlockState, q: *Query, et: models.EventType, data: []const switch (et) { .label_registered, .label_reserved => try applyRegistration(st, q, data, namehash, et == .label_reserved), .transfer => { + // Same key as live and as replay: ownership moves only when the + // (tokenId, emitting registry) pair is this name's. A tokenId collides + // across registries, and an events row can carry a placeholder name — + // applying `to` on the namehash alone handed this name an owner from + // someone else's transfer. Mirrors .resolver_updated below. const to = Address.fromHex(jsonString(data, "to") orelse return) catch return; - if (st.name) |*n| n.owner = to; + // TransferBatch emits one row with "count" and no "id"; its per-token + // ids never reach the payload, so it cannot be applied here either. + const token_id = jsonU256(data, "id") orelse return; + const contract_addr = Address.fromHex(q.getTextSlice(COL_CONTRACT) orelse return) catch return; + if (st.name) |*n| { + if (n.token_id == token_id and n.registry.eql(contract_addr)) n.owner = to; + } }, .name_renewed => { const exp = jsonU64(data, "newExpiry") orelse jsonU64(data, "newExpiration") orelse return; diff --git a/src/utils/dns.zig b/src/utils/dns.zig index 43c67d8..07f7f75 100644 --- a/src/utils/dns.zig +++ b/src/utils/dns.zig @@ -61,8 +61,20 @@ pub fn decodeDNSName(allocator: std.mem.Allocator, data: []const u8) ![][]const /// Decode a DNS wire-format name and return the full dot-separated name string. /// Example: \x07vitalik\x03eth\x00 → "vitalik.eth" /// Caller owns the returned string. +/// `null` means THE ROOT NAME and nothing else. A malformed encoding propagates +/// `error.InvalidDNSEncoding`. +/// +/// These were folded together — `decodeDNSName` already distinguishes them +/// (it errors on a truncated label and returns zero labels for `0x00`) and this +/// wrapper threw that away with `catch return null`. A caller then could not +/// tell "the default record" from "garbage", so `handleNamedResourceKind` +/// discarded three legitimate root-name records as undecodable while +/// `handleLinked`, reading the same null, correctly treated it as the default +/// binding. Keeping the two outcomes distinct is what lets each caller choose, +/// and `utils.isMalformedEventError` lists the error so a genuinely malformed +/// payload skips one event with its coordinates instead of aborting the batch. pub fn decodeDNSNameToString(allocator: std.mem.Allocator, data: []const u8) !?[]const u8 { - const labels = decodeDNSName(allocator, data) catch return null; + const labels = try decodeDNSName(allocator, data); defer { for (labels) |l| allocator.free(l); allocator.free(labels); @@ -158,12 +170,16 @@ test "decode first label" { try std.testing.expectEqualStrings("vitalik", label.?); } -test "empty DNS name" { +test "root name decodes to null; a malformed encoding errors instead" { const allocator = std.testing.allocator; - const data = "\x00"; // root - const name = try decodeDNSNameToString(allocator, data); - try std.testing.expect(name == null); + // `0x00` is zero labels — the root — and must be reported as such. + try std.testing.expectEqual(@as(?[]const u8, null), try decodeDNSNameToString(allocator, "\x00")); + try std.testing.expectEqual(@as(?[]const u8, null), try decodeDNSNameToString(allocator, "")); + + // A label length that runs past the buffer is malformed, and must NOT be + // reported as the root: that conflation dropped real records. + try std.testing.expectError(error.InvalidDNSEncoding, decodeDNSNameToString(allocator, "\x05ab")); } test "decodeDNSNameToString keeps the raw label bytes: DNS labels are not required to be UTF-8" { diff --git a/tests/conformance/runner.zig b/tests/conformance/runner.zig index de6f8d0..9e322e8 100644 --- a/tests/conformance/runner.zig +++ b/tests/conformance/runner.zig @@ -129,7 +129,10 @@ fn seedFixture(db: *Database, a: std.mem.Allocator) !void { .{ .et = .label_registered, .blk = 200, .li = 9000, .contract = ab_registry, .data = "{\"name\":\"alice.eth\",\"tokenId\":4242,\"owner\":\"0x1111111111111111111111111111111111111111\",\"expiry\":1950000000,\"registry\":\"0x7777777777777777777777777777777777777777\"}" }, .{ .et = .resolver_updated, .blk = 210, .li = 9001, .contract = ab_registry, .data = "{\"tokenId\":4242,\"resolver\":\"0xcccccccccccccccccccccccccccccccccccccccc\"}" }, .{ .et = .address_changed, .blk = 220, .li = 9002, .contract = resolver, .data = "{\"resolver\":\"0xcccccccccccccccccccccccccccccccccccccccc\",\"coinType\":60,\"address\":\"0xdddddddddddddddddddddddddddddddddddddddd\"}" }, - .{ .et = .transfer, .blk = 230, .li = 9003, .contract = ab_registry, .data = "{\"to\":\"0x2222222222222222222222222222222222222222\"}" }, + // Live's Transfer payload always carries the token id, and ownership is keyed + // on (id, emitting registry) — same as the ResolverUpdated above. Without the + // id this was a shape the indexer never emits. + .{ .et = .transfer, .blk = 230, .li = 9003, .contract = ab_registry, .data = "{\"to\":\"0x2222222222222222222222222222222222222222\",\"id\":4242,\"value\":1}" }, }; for (ab_events) |e| { try db.insertEvent(.{ From f6e986ab969579ccbf32ea2260393067b5b50207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Wed, 30 Sep 2026 14:27:45 +0200 Subject: [PATCH 2/3] test(replay): gate resolver data, links and named resources on parity --- tests/integration.zig | 2 +- tools/replay_diff.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration.zig b/tests/integration.zig index 401ca5d..fe82f39 100644 --- a/tests/integration.zig +++ b/tests/integration.zig @@ -1555,7 +1555,7 @@ const RECONCILE_TABLES = [_][]const u8{ "resolver_interfaces", "resolver_versions", "resolver_metadata", "resolver_approvals", "resolver_dns_records", "resolver_dns_zonehashes", "resolver_authorisations", "reverse_records", "approvals", "eac_roles", "accounts", "v1_controllers", - "name_history", + "name_history", "resolver_datas", "resolver_links", "resolver_named_resources", }; // Volatile columns excluded from the content comparison: the autoincrement id (insertion diff --git a/tools/replay_diff.py b/tools/replay_diff.py index 887eef9..51444c5 100755 --- a/tools/replay_diff.py +++ b/tools/replay_diff.py @@ -51,6 +51,7 @@ "resolver_dns_records", "resolver_dns_zonehashes", "resolver_authorisations", "reverse_records", "approvals", "eac_roles", "accounts", "v1_controllers", "name_history", "resolver_links", "resolver_named_resources", "unknown_labels", + "resolver_datas", ] # Columns excluded everywhere: the surrogate key is insertion order by construction, so it From b946c1f87421c9f525fd36b975861cbb417924d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Wed, 30 Sep 2026 14:27:55 +0200 Subject: [PATCH 3/3] docs(schema): state what a null data record and dataKeys actually mean --- schema.graphql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/schema.graphql b/schema.graphql index 02f5954..e5abc4e 100644 --- a/schema.graphql +++ b/schema.graphql @@ -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!] }