From c5fa763800221fdc0a11d4c8aa97f264bc2bed1a Mon Sep 17 00:00:00 2001 From: p-diogo Date: Thu, 26 Nov 2026 01:27:49 +0000 Subject: [PATCH 1/3] feat(subgraph): index_scheme gate (field 14) for keyed blind indices The mapping now counts a payload only when outer protobuf field 14 (index_scheme) is a varint equal to 1. Anything else creates no Fact, no BlindIndex rows and has no tombstone effect. A marked tombstone for an unknown id is ignored instead of creating an empty Fact. Adds Fact.indexScheme, hardens the varint/length handling in the decoder, shared protobuf vectors generated from the core encoder, matchstick tests and a CI job. Refs p-diogo/totalreclaw-internal#573 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 39 ++++ .gitignore | 8 + .../examples/generate_index_scheme_vectors.rs | 220 ++++++++++++++++++ subgraph/package-lock.json | 89 ++++--- subgraph/package.json | 7 +- subgraph/schema.graphql | 3 + subgraph/scripts/gen-vector-tests.mjs | 64 +++++ subgraph/src/mapping.ts | 32 ++- subgraph/src/protobuf.ts | 55 ++++- subgraph/tests/mapping.test.ts | 136 +++++++++++ subgraph/tests/protobuf.test.ts | 75 ++++++ .../protobuf-index-scheme-vectors.json | 165 +++++++++++++ 12 files changed, 833 insertions(+), 60 deletions(-) create mode 100644 rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs create mode 100644 subgraph/scripts/gen-vector-tests.mjs create mode 100644 subgraph/tests/mapping.test.ts create mode 100644 subgraph/tests/protobuf.test.ts create mode 100644 tests/parity/fixtures/protobuf-index-scheme-vectors.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc86d68c..e35a5da6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,7 @@ jobs: pair-crypto: ${{ steps.filter.outputs.pair-crypto }} docs: ${{ steps.filter.outputs.docs }} enclave: ${{ steps.filter.outputs.enclave }} + subgraph: ${{ steps.filter.outputs.subgraph }} steps: - uses: actions/checkout@v5 - uses: dorny/paths-filter@v3 @@ -60,6 +61,11 @@ jobs: - 'scripts/check-docs.sh' # The enclave imports the in-repo Python client and core, so # changes there must re-run its tests too. + subgraph: + - 'subgraph/**' + - 'tests/parity/fixtures/protobuf-index-scheme-vectors.json' + - 'rust/totalreclaw-core/src/protobuf.rs' + - 'rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs' enclave: - 'enclave/**' - 'python/**' @@ -454,6 +460,39 @@ jobs: - name: Test run: cd enclave && python -m pytest tests/ -v + # Subgraph build + matchstick tests (index_scheme gate, internal#573). + # matchstick runs in Docker: graph-cli 0.80 does not recognise Ubuntu 24.04 + # runners for the native binary. `script` supplies the TTY docker run wants. + subgraph-tests: + name: Subgraph tests + needs: changes + if: needs.changes.outputs.subgraph == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - name: Shared protobuf vectors are up to date with the core encoder + run: cd rust/totalreclaw-core && cargo run --example generate_index_scheme_vectors -- --check + - uses: actions/setup-node@v5 + with: + node-version: '22' + - name: Install + run: cd subgraph && npm ci --no-audit --no-fund + - name: Codegen + build (all three manifests) + run: | + cd subgraph + npx graph codegen + npx graph build + npx graph build subgraph-gnosis-staging.yaml + npx graph build subgraph-gnosis-mainnet.yaml + - name: Matchstick tests + run: | + cd subgraph + node scripts/gen-vector-tests.mjs + script -qec "npx graph test -d" /dev/null | tee /tmp/matchstick.log + grep -q "tests passed" /tmp/matchstick.log + cross-language-parity: name: Cross-Language Parity Tests runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index d4428375..665e6a34 100644 --- a/.gitignore +++ b/.gitignore @@ -146,3 +146,11 @@ contracts/account/lib/ contracts/account/out/ contracts/account/cache/ .desloppify/ + +# Subgraph matchstick vectors (generated from tests/parity/fixtures) +subgraph/tests/vectors.generated.ts + +# matchstick artifacts +subgraph/tests/.bin/ +subgraph/tests/.docker/ +subgraph/tests/.latest.json diff --git a/rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs b/rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs new file mode 100644 index 00000000..4055ce6b --- /dev/null +++ b/rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs @@ -0,0 +1,220 @@ +//! Generates the shared outer-protobuf `index_scheme` (field 14) test vectors. +//! +//! Run: +//! cd rust/totalreclaw-core +//! cargo run --example generate_index_scheme_vectors # write +//! cargo run --example generate_index_scheme_vectors -- --check # verify, no write +//! +//! Writes `tests/parity/fixtures/protobuf-index-scheme-vectors.json` (path +//! relative to the repo root). The subgraph decoder tests consume it today; +//! the relay's UserOp decoder must load the same file so the two parsers +//! cannot disagree (internal#573, design v2.1 section 6). +//! +//! Vector shape: +//! name, description, payloadHex, +//! expected: the decoded fields a conforming decoder must report. For +//! well-formed payloads this is the full field set; for malformed ones it +//! lists only the keys that are pinned (indexScheme at minimum). +//! `indexScheme` is the decoded varint of field 14, or 0 when field 14 is +//! absent, has the wrong wire type, or is truncated. +//! counts: the total rule. true only when indexScheme == 1. +//! isTombstone: decayScore == 0 on a payload that counts. + +use std::fs; +use std::path::PathBuf; + +use serde_json::{json, Value}; +use totalreclaw_core::protobuf::{ + encode_fact_protobuf, encode_fact_protobuf_keyed, encode_tombstone_protobuf_keyed_at, FactPayload, +}; + +const TS: &str = "2026-01-02T03:04:05Z"; +const OWNER: &str = "0x1111111111111111111111111111111111111111"; +const TAG_A: &str = "00000000000000000000000000000000000000000000000000000000000000aa"; +const TAG_B: &str = "00000000000000000000000000000000000000000000000000000000000000bb"; + +fn fact(id: &str, decay: f64, version: u32) -> FactPayload { + FactPayload { + id: id.into(), + timestamp: TS.into(), + owner: OWNER.into(), + encrypted_blob_hex: "deadbeef".into(), + // Unsorted on purpose: the keyed encoder sorts, the legacy one does not. + blind_indices: vec![TAG_B.into(), TAG_A.into()], + decay_score: decay, + source: "test".into(), + content_fp: "fp-0001".into(), + agent_id: "test".into(), + encrypted_embedding: Some("abcd".into()), + version, + } +} + +fn full(p: &FactPayload, tags: &[&str], scheme: u32) -> Value { + json!({ + "id": p.id, + "timestamp": p.timestamp, + "owner": p.owner, + "encryptedBlobHex": p.encrypted_blob_hex, + "blindIndices": tags, + "decayScore": p.decay_score, + "version": if p.version == 0 { 3 } else { p.version }, + "contentFp": p.content_fp, + "encryptedEmbedding": p.encrypted_embedding.clone().unwrap_or_default(), + "indexScheme": scheme, + }) +} + +fn vector(name: &str, description: &str, bytes: &[u8], expected: Value, tombstone: bool) -> Value { + let scheme = expected["indexScheme"].as_u64().unwrap_or(0); + let counts = scheme == 1; + json!({ + "name": name, + "description": description, + "payloadHex": hex::encode(bytes), + "expected": expected, + "counts": counts, + "isTombstone": counts && tombstone, + }) +} + +fn tombstone_fields(id: &str, version: u32, scheme: u32) -> Value { + json!({ + "id": id, "timestamp": TS, "owner": OWNER, "encryptedBlobHex": "", + "blindIndices": [], "decayScore": 0.0, "version": version, + "contentFp": "", "encryptedEmbedding": "", "indexScheme": scheme, + }) +} + +fn build() -> Value { + let mut v: Vec = Vec::new(); + + // 1. Marked fact (scheme 1). Field 14 is the last field written. + let p = fact("fact-marked", 1.0, 4); + let marked = encode_fact_protobuf_keyed(&p).expect("valid tags"); + v.push(vector( + "marked_fact", + "Keyed fact: version 4, field 5 sorted, field 14 = 1.", + &marked, + full(&p, &[TAG_A, TAG_B], 1), + false, + )); + + // 2. Marked tombstone. + let t = encode_tombstone_protobuf_keyed_at("fact-marked", OWNER, TS); + v.push(vector( + "marked_tombstone", + "Keyed tombstone: decay 0, empty blob, version 4, field 14 = 1.", + &t, + tombstone_fields("fact-marked", 4, 1), + true, + )); + + // 3. Legacy unmarked fact (pre-cutover layout, byte for byte). + let lp = fact("fact-legacy", 1.0, 4); + let legacy = encode_fact_protobuf(&lp); + v.push(vector( + "legacy_unmarked_fact", + "Legacy fact, version 4, no field 14. Must never count.", + &legacy, + full(&lp, &[TAG_B, TAG_A], 0), + false, + )); + + // 3b. Legacy low-liveness fact: guards against any liveness shortcut. + let ll = fact("fact-legacy-low", 0.2, 4); + v.push(vector( + "legacy_unmarked_low_decay_fact", + "Legacy fact with decay 0.2, no field 14. Must never count.", + &encode_fact_protobuf(&ll), + full(&ll, &[TAG_B, TAG_A], 0), + false, + )); + + // 4. Legacy tombstone. + // The legacy encoder stamps wall-clock time; pin it by taking the + // fixed-timestamp keyed tombstone minus field 14 (its last two bytes). + let lt_fixed = { + let mut b = encode_tombstone_protobuf_keyed_at("fact-legacy", OWNER, TS); + b.truncate(b.len() - 2); + b + }; + v.push(vector( + "legacy_unmarked_tombstone", + "Legacy tombstone, version 4, no field 14. Must have no effect.", + <_fixed, + tombstone_fields("fact-legacy", 4, 0), + true, + )); + + // 5. Field 14 = 2 (a future scheme this decoder does not know). + let mut two = marked.clone(); + let n = two.len(); + assert_eq!(&two[n - 2..], &[0x70, 0x01], "field 14 varint is the last field"); + two[n - 1] = 0x02; + v.push(vector( + "field14_equals_2", + "Field 14 = 2. Only 1 counts.", + &two, + full(&p, &[TAG_A, TAG_B], 2), + false, + )); + + // 6. Field 14 present with the wrong wire type (length-delimited, 1 byte 0x01). + let mut wrong = marked[..n - 2].to_vec(); + wrong.extend_from_slice(&[0x72, 0x01, 0x01]); + v.push(vector( + "field14_wrong_wire_type", + "Field 14 sent as length-delimited. Treated as absent.", + &wrong, + json!({ "id": "fact-marked", "version": 4, "indexScheme": 0 }), + false, + )); + + // 7. Truncated mid-blob: field 14 never reached. + let cut = &marked[..30]; + v.push(vector( + "truncated_mid_field", + "Payload cut inside an earlier field. Field 14 never arrives.", + cut, + json!({ "indexScheme": 0 }), + false, + )); + + // 8. Truncated inside the field-14 varint: continuation bit set, no next byte. + // A naive decoder would read 0x81 as 1; it must not. + let mut trunc14 = marked[..n - 2].to_vec(); + trunc14.extend_from_slice(&[0x70, 0x81]); + v.push(vector( + "truncated_field14_varint", + "Field 14 varint cut after a continuation byte (0x81). Must not decode as 1.", + &trunc14, + json!({ "indexScheme": 0 }), + false, + )); + + json!({ + "description": "Outer protobuf index_scheme (field 14) vectors. Generated by rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs. Do not edit by hand.", + "version": 1, + "countsRule": "A payload counts only when field 14 is a varint equal to 1.", + "vectors": v, + }) +} + +fn main() { + let check = std::env::args().any(|a| a == "--check"); + let out = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/parity/fixtures/protobuf-index-scheme-vectors.json"); + let text = serde_json::to_string_pretty(&build()).unwrap() + "\n"; + if check { + let cur = fs::read_to_string(&out).expect("fixture missing"); + if cur != text { + eprintln!("{} is stale: re-run the generator", out.display()); + std::process::exit(1); + } + println!("ok: {} is up to date", out.display()); + } else { + fs::write(&out, text).unwrap(); + println!("wrote {}", out.display()); + } +} diff --git a/subgraph/package-lock.json b/subgraph/package-lock.json index b190bea9..09ec6e54 100644 --- a/subgraph/package-lock.json +++ b/subgraph/package-lock.json @@ -12,9 +12,10 @@ "@graphprotocol/graph-ts": "^0.35.0", "@huggingface/transformers": "^4.0.1", "@scure/bip39": "^2.0.1", - "assemblyscript": "^0.27.0", + "assemblyscript": "^0.19.23", "dotenv": "^17.3.1", "ethers": "^6.16.0", + "matchstick-as": "^0.6.0", "porter-stemmer": "^0.9.1", "tsx": "^4.21.0" }, @@ -1009,36 +1010,6 @@ "node": ">=18" } }, - "node_modules/@graphprotocol/graph-cli/node_modules/assemblyscript": { - "version": "0.19.23", - "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.23.tgz", - "integrity": "sha512-fwOQNZVTMga5KRsfY80g7cpOl4PsFQczMwHzdtgoqLXaYhkhavufKb0sB0l3T1DUxpAufA0KNhlbpuuhZUwxMA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "binaryen": "102.0.0-nightly.20211028", - "long": "^5.2.0", - "source-map-support": "^0.5.20" - }, - "bin": { - "asc": "bin/asc", - "asinit": "bin/asinit" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/assemblyscript" - } - }, - "node_modules/@graphprotocol/graph-cli/node_modules/binaryen": { - "version": "102.0.0-nightly.20211028", - "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz", - "integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "wasm-opt": "bin/wasm-opt" - } - }, "node_modules/@graphprotocol/graph-ts": { "version": "0.35.1", "resolved": "https://registry.npmjs.org/@graphprotocol/graph-ts/-/graph-ts-0.35.1.tgz", @@ -2530,22 +2501,19 @@ } }, "node_modules/assemblyscript": { - "version": "0.27.37", - "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.27.37.tgz", - "integrity": "sha512-YtY5k3PiV3SyUQ6gRlR2OCn8dcVRwkpiG/k2T5buoL2ymH/Z/YbaYWbk/f9mO2HTgEtGWjPiAQrIuvA7G/63Gg==", + "version": "0.19.23", + "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.23.tgz", + "integrity": "sha512-fwOQNZVTMga5KRsfY80g7cpOl4PsFQczMwHzdtgoqLXaYhkhavufKb0sB0l3T1DUxpAufA0KNhlbpuuhZUwxMA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "binaryen": "116.0.0-nightly.20240114", - "long": "^5.2.4" + "binaryen": "102.0.0-nightly.20211028", + "long": "^5.2.0", + "source-map-support": "^0.5.20" }, "bin": { - "asc": "bin/asc.js", - "asinit": "bin/asinit.js" - }, - "engines": { - "node": ">=18", - "npm": ">=10" + "asc": "bin/asc", + "asinit": "bin/asinit" }, "funding": { "type": "opencollective", @@ -2679,14 +2647,13 @@ } }, "node_modules/binaryen": { - "version": "116.0.0-nightly.20240114", - "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-116.0.0-nightly.20240114.tgz", - "integrity": "sha512-0GZrojJnuhoe+hiwji7QFaL3tBlJoA+KFUN7ouYSDGZLSo9CKM8swQX8n/UcbR0d1VuZKU+nhogNzv423JEu5A==", + "version": "102.0.0-nightly.20211028", + "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz", + "integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==", "dev": true, "license": "Apache-2.0", "bin": { - "wasm-opt": "bin/wasm-opt", - "wasm2js": "bin/wasm2js" + "wasm-opt": "bin/wasm-opt" } }, "node_modules/bl": { @@ -5896,6 +5863,16 @@ "node": ">=10" } }, + "node_modules/matchstick-as": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/matchstick-as/-/matchstick-as-0.6.0.tgz", + "integrity": "sha512-E36fWsC1AbCkBFt05VsDDRoFvGSdcZg6oZJrtIe/YDBbuFh8SKbR5FcoqDhNWqSN+F7bN/iS2u8Md0SM+4pUpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "wabt": "1.0.24" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -8127,6 +8104,24 @@ "dev": true, "license": "MIT" }, + "node_modules/wabt": { + "version": "1.0.24", + "resolved": "https://registry.npmjs.org/wabt/-/wabt-1.0.24.tgz", + "integrity": "sha512-8l7sIOd3i5GWfTWciPL0+ff/FK/deVK2Q6FN+MPz4vfUcD78i2M/49XJTwF6aml91uIiuXJEsLKWMB2cw/mtKg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "wasm-decompile": "bin/wasm-decompile", + "wasm-interp": "bin/wasm-interp", + "wasm-objdump": "bin/wasm-objdump", + "wasm-opcodecnt": "bin/wasm-opcodecnt", + "wasm-strip": "bin/wasm-strip", + "wasm-validate": "bin/wasm-validate", + "wasm2c": "bin/wasm2c", + "wasm2wat": "bin/wasm2wat", + "wat2wasm": "bin/wat2wasm" + } + }, "node_modules/wcwidth": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", diff --git a/subgraph/package.json b/subgraph/package.json index f57b8d91..07396aa3 100644 --- a/subgraph/package.json +++ b/subgraph/package.json @@ -14,16 +14,19 @@ "deploy:prod": "graph deploy --studio total-reclaw-gnosis subgraph-gnosis-mainnet.yaml", "test:gas": "tsx --tsconfig tsconfig.node.json tests/gas-measurement.ts", "test:e2e": "tsx --tsconfig tsconfig.node.json tests/e2e-ombh-validation.ts", - "test:scaling": "tsx --tsconfig tsconfig.node.json tests/scaling-analysis.ts" + "test:scaling": "tsx --tsconfig tsconfig.node.json tests/scaling-analysis.ts", + "gen:vectors": "node scripts/gen-vector-tests.mjs", + "test": "node scripts/gen-vector-tests.mjs && graph test" }, "devDependencies": { "@graphprotocol/graph-cli": "^0.80.0", "@graphprotocol/graph-ts": "^0.35.0", "@huggingface/transformers": "^4.0.1", "@scure/bip39": "^2.0.1", - "assemblyscript": "^0.27.0", + "assemblyscript": "^0.19.23", "dotenv": "^17.3.1", "ethers": "^6.16.0", + "matchstick-as": "^0.6.0", "porter-stemmer": "^0.9.1", "tsx": "^4.21.0" }, diff --git a/subgraph/schema.graphql b/subgraph/schema.graphql index c2ebef60..7afda441 100644 --- a/subgraph/schema.graphql +++ b/subgraph/schema.graphql @@ -1,6 +1,7 @@ """ TotalReclaw Subgraph Schema v3 Key change: agentId and source removed — now encrypted inside blob (v3 privacy). +vNext (internal#573): Fact.indexScheme added; only payloads with protobuf field 14 = 1 are indexed. """ type Fact @entity(immutable: false) { @@ -21,6 +22,8 @@ type Fact @entity(immutable: false) { sequenceId: BigInt! "Protobuf schema version" version: Int! + "Blind-index scheme from protobuf field 14. Always 1 (keyed HMAC v1) on this subgraph: payloads without field 14 = 1 are never indexed. Non-null because every indexed row carries it; adding it is additive and does not change any existing query." + indexScheme: Int! "Block number when this fact was written" blockNumber: BigInt! "Block timestamp" diff --git a/subgraph/scripts/gen-vector-tests.mjs b/subgraph/scripts/gen-vector-tests.mjs new file mode 100644 index 00000000..0ce1faab --- /dev/null +++ b/subgraph/scripts/gen-vector-tests.mjs @@ -0,0 +1,64 @@ +// Turns the shared protobuf vectors (tests/parity/fixtures/protobuf-index-scheme-vectors.json) +// into an AssemblyScript module the matchstick tests import. AssemblyScript has +// no filesystem access, so the JSON cannot be read at test time. The output is +// gitignored and regenerated by `npm test`. +import { readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +const here = dirname(fileURLToPath(import.meta.url)); +const src = join(here, "../../tests/parity/fixtures/protobuf-index-scheme-vectors.json"); +const out = join(here, "../tests/vectors.generated.ts"); +const data = JSON.parse(readFileSync(src, "utf8")); +const q = (s) => JSON.stringify(s); + +let ts = `// GENERATED by scripts/gen-vector-tests.mjs from protobuf-index-scheme-vectors.json. Do not edit. +export class Vector { + name: string = ""; + hex: string = ""; + counts: boolean = false; + isTombstone: boolean = false; + indexScheme: i64 = 0; + hasId: boolean = false; + id: string = ""; + hasVersion: boolean = false; + version: i32 = 0; + hasFull: boolean = false; + owner: string = ""; + timestamp: string = ""; + contentFp: string = ""; + blobHex: string = ""; + embedding: string = ""; + decayScore: string = ""; + blindIndices: string[] = []; +} + +export function vectors(): Vector[] { + let all: Vector[] = []; +`; +for (const v of data.vectors) { + const e = v.expected; + const full = "owner" in e; + ts += ` { + let v = new Vector(); + v.name = ${q(v.name)}; + v.hex = ${q(v.payloadHex)}; + v.counts = ${v.counts}; + v.isTombstone = ${v.isTombstone}; + v.indexScheme = ${e.indexScheme}; +`; + if ("id" in e) ts += ` v.hasId = true; v.id = ${q(e.id)};\n`; + if ("version" in e) ts += ` v.hasVersion = true; v.version = ${e.version};\n`; + if (full) { + ts += ` v.hasFull = true; + v.owner = ${q(e.owner)}; v.timestamp = ${q(e.timestamp)}; v.contentFp = ${q(e.contentFp)}; + v.blobHex = ${q(e.encryptedBlobHex)}; v.embedding = ${q(e.encryptedEmbedding)}; + v.decayScore = ${q(String(e.decayScore))}; + v.blindIndices = [${e.blindIndices.map(q).join(", ")}]; +`; + } + ts += ` all.push(v);\n }\n`; +} +ts += ` return all;\n}\n`; +writeFileSync(out, ts); +console.log(`wrote ${out} (${data.vectors.length} vectors)`); diff --git a/subgraph/src/mapping.ts b/subgraph/src/mapping.ts index fa90485f..c7f63e9c 100644 --- a/subgraph/src/mapping.ts +++ b/subgraph/src/mapping.ts @@ -31,14 +31,21 @@ * crafted `victim:uuid` from an attacker just lands in the attacker's own * namespace (`attacker:victim:uuid`). * - * The subgraph stores only ciphertext and SHA-256 blind-index hashes; it never - * sees plaintext. + * Index scheme gate (internal#573, design v2.1 section 6): the rule is total. + * A payload counts only if outer protobuf field 14 (index_scheme) == 1. Anything + * else (no field 14, wrong wire type, any other value, truncated) creates no + * Fact, no BlindIndex rows and has no tombstone effect. There is no liveness + * exception. A marked tombstone for an id this subgraph has never seen is + * ignored too (it no longer creates an empty Fact row). + * + * The subgraph stores only ciphertext and blind-index tags; it never sees + * plaintext. */ import { Address, BigDecimal, BigInt, log } from "@graphprotocol/graph-ts"; import { Log } from "../generated/EventfulDataEdgeV2/EventfulDataEdgeV2"; import { Fact, BlindIndex, GlobalState } from "../generated/schema"; -import { decodeFact } from "./protobuf"; +import { decodeFact, isKeyedScheme, isTombstone } from "./protobuf"; const GLOBAL_STATE_ID = "global"; const INACTIVE_THRESHOLD = BigDecimal.fromString("0.3"); @@ -134,6 +141,16 @@ export function handleLog(event: Log): void { let decoded = decodeFact(data); + // Total rule: no field 14 = 1, no effect at all. Checked before anything + // else, including the liveness (decayScore) logic below. + if (!isKeyedScheme(decoded)) { + log.info("Ignoring unmarked payload (index_scheme {}) in tx {}", [ + decoded.indexScheme.toString(), + event.transaction.hash.toHexString() + ]); + return; + } + // Resolve the client-chosen fact id; fall back to a per-event unique id. let payloadId = decoded.id; if (payloadId == "") { @@ -159,6 +176,14 @@ export function handleLog(event: Log): void { } if (fact == null) { + // A tombstone cannot create a fact: nothing to deactivate. + if (isTombstone(decoded)) { + log.info("Ignoring tombstone for unknown fact {} in tx {}", [ + factId, + event.transaction.hash.toHexString() + ]); + return; + } fact = new Fact(factId); } @@ -170,6 +195,7 @@ export function handleLog(event: Log): void { fact!.isActive = decoded.decayScore.ge(INACTIVE_THRESHOLD); fact!.contentFp = decoded.contentFp; fact!.version = decoded.version; + fact!.indexScheme = decoded.indexScheme as i32; fact!.blockNumber = event.block.number; fact!.timestamp = event.block.timestamp; fact!.txHash = event.transaction.hash; diff --git a/subgraph/src/protobuf.ts b/subgraph/src/protobuf.ts index 7956123a..9c6a8ac6 100644 --- a/subgraph/src/protobuf.ts +++ b/subgraph/src/protobuf.ts @@ -24,6 +24,13 @@ * 11: (removed — encrypted in blob v3) * 12: int64 sequence_id (wire type 0) — monotonic per-user (varint) * 13: string encrypted_embedding (wire type 2) — XChaCha20-Poly1305 encrypted embedding (hex) + * 14: uint32 index_scheme (wire type 0) — 1 = keyed blind indices (HMAC v1); + * absent = legacy. Written by the core encoder on facts + * AND tombstones. A field 14 with any other wire type is + * ignored (indexScheme stays 0). + * + * Shared test vectors: tests/parity/fixtures/protobuf-index-scheme-vectors.json + * (generated from the core encoder; the relay decoder loads the same file). */ import { Bytes, BigDecimal, BigInt } from "@graphprotocol/graph-ts"; @@ -40,6 +47,8 @@ export class DecodedFact { contentFp: string; sequenceId: i64; encryptedEmbedding: string; + /** Decoded varint of field 14. 0 when absent, wrong wire type, or truncated. */ + indexScheme: i64; constructor() { this.id = ""; @@ -53,12 +62,32 @@ export class DecodedFact { this.contentFp = ""; this.sequenceId = 0; this.encryptedEmbedding = ""; + this.indexScheme = 0; } } +/** Only index_scheme == 1 counts. The mapping rule is total (design v2.1, section 6). */ +export const INDEX_SCHEME_KEYED_V1: i64 = 1; + +/** True when the payload carries field 14 = 1. */ +export function isKeyedScheme(decoded: DecodedFact): boolean { + return decoded.indexScheme == INDEX_SCHEME_KEYED_V1; +} + +/** + * A tombstone is what the core encoder writes for a forget: empty encrypted + * blob and decay_score == 0. + */ +export function isTombstone(decoded: DecodedFact): boolean { + return decoded.encryptedBlob.length == 0 && decoded.decayScore.equals(BigDecimal.zero()); +} + /** * Decode a varint from the byte array starting at offset. - * Returns [value, newOffset]. + * Returns [value, newOffset]. newOffset is -1 when the varint is truncated + * (continuation bit set on the last available byte) or longer than 10 bytes; + * callers must stop decoding. A truncated varint must never yield a value + * (0x81 cut short would otherwise read as 1). */ function decodeVarint(data: Bytes, offset: i32): i64[] { let result: i64 = 0; @@ -66,14 +95,15 @@ function decodeVarint(data: Bytes, offset: i32): i64[] { let pos = offset; while (pos < data.length) { + if (shift >= 64) return [0, -1]; let byte = data[pos] as i64; result |= (byte & 0x7f) << shift; pos++; - if ((byte & 0x80) == 0) break; + if ((byte & 0x80) == 0) return [result, pos as i64]; shift += 7; } - return [result, pos as i64]; + return [0, -1]; } /** @@ -90,15 +120,19 @@ export function decodeFact(data: Bytes): DecodedFact { while (offset < data.length) { // Read field key let keyResult = decodeVarint(data, offset); - let key = keyResult[0] as i32; + if (keyResult[1] < 0) break; + let key = keyResult[0]; offset = keyResult[1] as i32; - let fieldNumber = key >> 3; - let wireType = key & 0x07; + // i64 end to end: narrowing the key to i32 would let an oversized key + // alias a real field number (e.g. 2^32 + 0x70 reading as field 14). + let fieldNumber: i64 = key >> 3; + let wireType = (key & 0x07) as i32; if (wireType == 0) { // Varint let valResult = decodeVarint(data, offset); + if (valResult[1] < 0) break; let value = valResult[0]; offset = valResult[1] as i32; @@ -110,6 +144,8 @@ export function decodeFact(data: Bytes): DecodedFact { // sequence_id: decoded for completeness, but the mapping assigns // its own monotonic sequence IDs from GlobalState fact.sequenceId = value; + } else if (fieldNumber == 14) { + fact.indexScheme = value; } } else if (wireType == 1) { // 64-bit (double) @@ -134,10 +170,13 @@ export function decodeFact(data: Bytes): DecodedFact { } else if (wireType == 2) { // Length-delimited let lenResult = decodeVarint(data, offset); - let len = lenResult[0] as i32; + if (lenResult[1] < 0) break; + let len64 = lenResult[0]; offset = lenResult[1] as i32; - if (offset + len > data.length) break; + // Compare in i64 so a huge or negative length can never pass. + if (len64 < 0 || len64 > (data.length - offset) as i64) break; + let len = len64 as i32; let slice = data.subarray(offset, offset + len); // Convert Uint8Array to Bytes so toString() does UTF-8 decoding diff --git a/subgraph/tests/mapping.test.ts b/subgraph/tests/mapping.test.ts new file mode 100644 index 00000000..6a35df68 --- /dev/null +++ b/subgraph/tests/mapping.test.ts @@ -0,0 +1,136 @@ +import { assert, beforeEach, clearStore, describe, newMockEvent, test } from "matchstick-as/assembly/index"; +import { Address, Bytes, ethereum, BigInt } from "@graphprotocol/graph-ts"; +import { Log } from "../generated/EventfulDataEdgeV2/EventfulDataEdgeV2"; +import { handleLog } from "../src/mapping"; +import { vectors, Vector } from "./vectors.generated"; + +// Mapping behaviour under the total index_scheme rule (internal#573, design v2.1 +// section 6): only payloads with field 14 = 1 count. Payloads come from the +// shared vectors generated by the core encoder. + +function vec(name: string): Vector { + let all = vectors(); + for (let i = 0; i < all.length; i++) { + if (all[i].name == name) return all[i]; + } + throw new Error("missing vector " + name); +} + +let nextLogIndex: i32 = 0; + +// DataEdge V2 emits Log(sender, data); the mapping keys facts by `sender:id`. +const SENDER = Address.fromString("0x00000000000000000000000000000000000000a1"); + +function send(hex: string): void { + let mock = newMockEvent(); + mock.logIndex = BigInt.fromI32(nextLogIndex++); + mock.parameters = [ + new ethereum.EventParam("sender", ethereum.Value.fromAddress(SENDER)), + new ethereum.EventParam("data", ethereum.Value.fromBytes(Bytes.fromHexString(hex))), + ]; + handleLog(changetype(mock)); +} + +const MARKED_ID = "0x00000000000000000000000000000000000000a1:fact-marked"; +const LEGACY_ID = "fact-legacy"; +const TAG_A = "00000000000000000000000000000000000000000000000000000000000000aa"; +const TAG_B = "00000000000000000000000000000000000000000000000000000000000000bb"; + +describe("handleLog: index_scheme gate", () => { + beforeEach(() => { + clearStore(); + nextLogIndex = 0; + }); + + test("marked fact is indexed with its tags and indexScheme 1", () => { + send(vec("marked_fact").hex); + assert.entityCount("Fact", 1); + assert.fieldEquals("Fact", MARKED_ID, "indexScheme", "1"); + assert.fieldEquals("Fact", MARKED_ID, "isActive", "true"); + assert.fieldEquals("Fact", MARKED_ID, "version", "4"); + assert.entityCount("BlindIndex", 2); + assert.fieldEquals("BlindIndex", MARKED_ID + "-" + TAG_A, "hash", TAG_A); + assert.fieldEquals("BlindIndex", MARKED_ID + "-" + TAG_B, "hash", TAG_B); + assert.fieldEquals("GlobalState", "global", "totalFacts", "1"); + }); + + test("unmarked fact creates nothing at all", () => { + send(vec("legacy_unmarked_fact").hex); + assert.entityCount("Fact", 0); + assert.entityCount("BlindIndex", 0); + assert.entityCount("GlobalState", 0); + }); + + test("unmarked low-decay fact creates nothing (no liveness exception)", () => { + send(vec("legacy_unmarked_low_decay_fact").hex); + assert.entityCount("Fact", 0); + assert.entityCount("BlindIndex", 0); + }); + + test("marked tombstone for a known id deactivates it", () => { + send(vec("marked_fact").hex); + send(vec("marked_tombstone").hex); + assert.entityCount("Fact", 1); + assert.fieldEquals("Fact", MARKED_ID, "isActive", "false"); + assert.fieldEquals("Fact", MARKED_ID, "decayScore", "0"); + assert.fieldEquals("Fact", MARKED_ID, "indexScheme", "1"); + assert.fieldEquals("GlobalState", "global", "totalFacts", "1"); + }); + + test("marked tombstone for an unknown id is ignored (no empty Fact row)", () => { + send(vec("marked_tombstone").hex); + assert.entityCount("Fact", 0); + assert.entityCount("BlindIndex", 0); + assert.entityCount("GlobalState", 0); + }); + + test("unmarked tombstone has no effect on a known marked fact", () => { + send(vec("marked_fact").hex); + // Same id as the marked fact so a leak would show as a deactivation. + let legacyTomb = vec("legacy_unmarked_tombstone"); + assert.assertTrue(legacyTomb.id == LEGACY_ID); + send(legacyTomb.hex); + assert.entityCount("Fact", 1); + assert.fieldEquals("Fact", MARKED_ID, "isActive", "true"); + }); + + test("unmarked tombstone for an unknown id is ignored", () => { + send(vec("legacy_unmarked_tombstone").hex); + assert.entityCount("Fact", 0); + }); + + test("field 14 = 2 is ignored", () => { + send(vec("field14_equals_2").hex); + assert.entityCount("Fact", 0); + assert.entityCount("BlindIndex", 0); + }); + + test("field 14 with the wrong wire type is ignored", () => { + send(vec("field14_wrong_wire_type").hex); + assert.entityCount("Fact", 0); + }); + + test("truncated payloads are ignored", () => { + send(vec("truncated_mid_field").hex); + send(vec("truncated_field14_varint").hex); + assert.entityCount("Fact", 0); + assert.entityCount("BlindIndex", 0); + }); + + test("mixed batch: only the marked fact and its tombstone count", () => { + send(vec("legacy_unmarked_fact").hex); + send(vec("field14_equals_2").hex); + send(vec("marked_tombstone").hex); // unknown id yet: ignored + send(vec("marked_fact").hex); + send(vec("legacy_unmarked_tombstone").hex); + send(vec("truncated_field14_varint").hex); + send(vec("field14_wrong_wire_type").hex); + assert.entityCount("Fact", 1); + assert.entityCount("BlindIndex", 2); + assert.fieldEquals("Fact", MARKED_ID, "isActive", "true"); + send(vec("marked_tombstone").hex); // now known: applies + assert.fieldEquals("Fact", MARKED_ID, "isActive", "false"); + assert.entityCount("Fact", 1); + assert.fieldEquals("GlobalState", "global", "totalFacts", "1"); + }); +}); diff --git a/subgraph/tests/protobuf.test.ts b/subgraph/tests/protobuf.test.ts new file mode 100644 index 00000000..b310bdfe --- /dev/null +++ b/subgraph/tests/protobuf.test.ts @@ -0,0 +1,75 @@ +import { assert, describe, test } from "matchstick-as/assembly/index"; +import { Bytes, BigDecimal, log } from "@graphprotocol/graph-ts"; +import { decodeFact, isKeyedScheme, isTombstone } from "../src/protobuf"; +import { vectors, Vector } from "./vectors.generated"; + +// Decoder conformance against the shared vectors +// (tests/parity/fixtures/protobuf-index-scheme-vectors.json, generated from the +// core encoder). The relay decoder loads the same file. + +function checkVector(v: Vector): void { + log.info("vector {}", [v.name]); + let d = decodeFact(Bytes.fromHexString(v.hex)); + assert.i32Equals(d.indexScheme as i32, v.indexScheme as i32); + assert.assertTrue(isKeyedScheme(d) == v.counts, v.name + ": counts"); + if (v.hasFull) assert.assertTrue(isTombstone(d) == (v.blobHex == ""), v.name + ": tombstone shape"); + if (v.hasId) assert.stringEquals(d.id, v.id); + if (v.hasVersion) assert.i32Equals(d.version, v.version); + if (v.hasFull) { + assert.stringEquals(d.owner, v.owner); + assert.stringEquals(d.timestamp, v.timestamp); + assert.stringEquals(d.contentFp, v.contentFp); + assert.stringEquals(d.encryptedEmbedding, v.embedding); + assert.stringEquals(d.encryptedBlob.toHexString(), "0x" + v.blobHex); + assert.assertTrue(d.decayScore.equals(BigDecimal.fromString(v.decayScore)), v.name + ": decayScore"); + assert.i32Equals(d.blindIndices.length, v.blindIndices.length); + for (let j = 0; j < v.blindIndices.length; j++) { + assert.stringEquals(d.blindIndices[j], v.blindIndices[j]); + } + } +} + +describe("protobuf decoder: shared index_scheme vectors", () => { + test("vector file is loaded", () => { + assert.i32Equals(vectors().length, 9); + }); + + // matchstick's AssemblyScript has no closures, so all vectors run in one test; + // the failing vector's name is in the assertion message. + test("every vector decodes as specified", () => { + let all = vectors(); + for (let i = 0; i < all.length; i++) { + checkVector(all[i]); + } + }); +}); + +describe("protobuf decoder: hardening", () => { + test("oversized key does not alias field 14", () => { + // key varint = 2^32 + 0x70 (would read as field 14 if narrowed to i32), value 1. + let d = decodeFact(Bytes.fromHexString("f08080808010" + "01")); + assert.i32Equals(d.indexScheme as i32, 0); + }); + + test("negative or huge length does not pass the bounds check", () => { + // field 1, length = 2^32 + 1 (wraps to 1 as i32), then 1 byte. + let d = decodeFact(Bytes.fromHexString("0a" + "8180808010" + "41")); + assert.stringEquals(d.id, ""); + }); + + test("varint longer than 10 bytes is rejected", () => { + let d = decodeFact(Bytes.fromHexString("70" + "ffffffffffffffffffff01")); + assert.i32Equals(d.indexScheme as i32, 0); + }); + + test("duplicate field 14: last varint wins", () => { + let d = decodeFact(Bytes.fromHexString("7002" + "7001")); + assert.i32Equals(d.indexScheme as i32, 1); + }); + + test("unknown fields are still skipped", () => { + // field 15 varint, field 16 length-delimited, then field 14 = 1. + let d = decodeFact(Bytes.fromHexString("7805" + "82010161" + "7001")); + assert.i32Equals(d.indexScheme as i32, 1); + }); +}); diff --git a/tests/parity/fixtures/protobuf-index-scheme-vectors.json b/tests/parity/fixtures/protobuf-index-scheme-vectors.json new file mode 100644 index 00000000..1c893480 --- /dev/null +++ b/tests/parity/fixtures/protobuf-index-scheme-vectors.json @@ -0,0 +1,165 @@ +{ + "countsRule": "A payload counts only when field 14 is a varint equal to 1.", + "description": "Outer protobuf index_scheme (field 14) vectors. Generated by rust/totalreclaw-core/examples/generate_index_scheme_vectors.rs. Do not edit by hand.", + "vectors": [ + { + "counts": true, + "description": "Keyed fact: version 4, field 5 sorted, field 14 = 1.", + "expected": { + "blindIndices": [ + "00000000000000000000000000000000000000000000000000000000000000aa", + "00000000000000000000000000000000000000000000000000000000000000bb" + ], + "contentFp": "fp-0001", + "decayScore": 1.0, + "encryptedBlobHex": "deadbeef", + "encryptedEmbedding": "abcd", + "id": "fact-marked", + "indexScheme": 1, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": false, + "name": "marked_fact", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303061612a403030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030626231000000000000f03f38014004520766702d303030316a04616263647001" + }, + { + "counts": true, + "description": "Keyed tombstone: decay 0, empty blob, version 4, field 14 = 1.", + "expected": { + "blindIndices": [], + "contentFp": "", + "decayScore": 0.0, + "encryptedBlobHex": "", + "encryptedEmbedding": "", + "id": "fact-marked", + "indexScheme": 1, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": true, + "name": "marked_tombstone", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312200310000000000000000380040047001" + }, + { + "counts": false, + "description": "Legacy fact, version 4, no field 14. Must never count.", + "expected": { + "blindIndices": [ + "00000000000000000000000000000000000000000000000000000000000000bb", + "00000000000000000000000000000000000000000000000000000000000000aa" + ], + "contentFp": "fp-0001", + "decayScore": 1.0, + "encryptedBlobHex": "deadbeef", + "encryptedEmbedding": "abcd", + "id": "fact-legacy", + "indexScheme": 0, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": false, + "name": "legacy_unmarked_fact", + "payloadHex": "0a0b666163742d6c65676163791214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303062622a403030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030616131000000000000f03f38014004520766702d303030316a0461626364" + }, + { + "counts": false, + "description": "Legacy fact with decay 0.2, no field 14. Must never count.", + "expected": { + "blindIndices": [ + "00000000000000000000000000000000000000000000000000000000000000bb", + "00000000000000000000000000000000000000000000000000000000000000aa" + ], + "contentFp": "fp-0001", + "decayScore": 0.2, + "encryptedBlobHex": "deadbeef", + "encryptedEmbedding": "abcd", + "id": "fact-legacy-low", + "indexScheme": 0, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": false, + "name": "legacy_unmarked_low_decay_fact", + "payloadHex": "0a0f666163742d6c65676163792d6c6f771214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303062622a4030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306161319a9999999999c93f38014004520766702d303030316a0461626364" + }, + { + "counts": false, + "description": "Legacy tombstone, version 4, no field 14. Must have no effect.", + "expected": { + "blindIndices": [], + "contentFp": "", + "decayScore": 0.0, + "encryptedBlobHex": "", + "encryptedEmbedding": "", + "id": "fact-legacy", + "indexScheme": 0, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": false, + "name": "legacy_unmarked_tombstone", + "payloadHex": "0a0b666163742d6c65676163791214323032362d30312d30325430333a30343a30355a1a2a307831313131313131313131313131313131313131313131313131313131313131313131313131313131220031000000000000000038004004" + }, + { + "counts": false, + "description": "Field 14 = 2. Only 1 counts.", + "expected": { + "blindIndices": [ + "00000000000000000000000000000000000000000000000000000000000000aa", + "00000000000000000000000000000000000000000000000000000000000000bb" + ], + "contentFp": "fp-0001", + "decayScore": 1.0, + "encryptedBlobHex": "deadbeef", + "encryptedEmbedding": "abcd", + "id": "fact-marked", + "indexScheme": 2, + "owner": "0x1111111111111111111111111111111111111111", + "timestamp": "2026-01-02T03:04:05Z", + "version": 4 + }, + "isTombstone": false, + "name": "field14_equals_2", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303061612a403030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030626231000000000000f03f38014004520766702d303030316a04616263647002" + }, + { + "counts": false, + "description": "Field 14 sent as length-delimited. Treated as absent.", + "expected": { + "id": "fact-marked", + "indexScheme": 0, + "version": 4 + }, + "isTombstone": false, + "name": "field14_wrong_wire_type", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303061612a403030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030626231000000000000f03f38014004520766702d303030316a0461626364720101" + }, + { + "counts": false, + "description": "Payload cut inside an earlier field. Field 14 never arrives.", + "expected": { + "indexScheme": 0 + }, + "isTombstone": false, + "name": "truncated_mid_field", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30" + }, + { + "counts": false, + "description": "Field 14 varint cut after a continuation byte (0x81). Must not decode as 1.", + "expected": { + "indexScheme": 0 + }, + "isTombstone": false, + "name": "truncated_field14_varint", + "payloadHex": "0a0b666163742d6d61726b65641214323032362d30312d30325430333a30343a30355a1a2a3078313131313131313131313131313131313131313131313131313131313131313131313131313131312204deadbeef2a40303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303061612a403030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030626231000000000000f03f38014004520766702d303030316a04616263647081" + } + ], + "version": 1 +} From d0aac43d9cccbd2cdfd958e32ccbada4ef9fd071 Mon Sep 17 00:00:00 2001 From: p-diogo Date: Thu, 26 Nov 2026 01:42:24 +0000 Subject: [PATCH 2/3] fix(subgraph): CI matchstick step fails on a failed run (pipefail + failure grep); npm test uses Docker; fix a comment Review nits on #846. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 ++ subgraph/package.json | 2 +- subgraph/tests/protobuf.test.ts | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e35a5da6..977fe2d4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -490,8 +490,10 @@ jobs: run: | cd subgraph node scripts/gen-vector-tests.mjs + set -o pipefail script -qec "npx graph test -d" /dev/null | tee /tmp/matchstick.log grep -q "tests passed" /tmp/matchstick.log + ! grep -qiE "\b[1-9][0-9]* (tests? )?failed" /tmp/matchstick.log cross-language-parity: name: Cross-Language Parity Tests diff --git a/subgraph/package.json b/subgraph/package.json index 07396aa3..42955800 100644 --- a/subgraph/package.json +++ b/subgraph/package.json @@ -16,7 +16,7 @@ "test:e2e": "tsx --tsconfig tsconfig.node.json tests/e2e-ombh-validation.ts", "test:scaling": "tsx --tsconfig tsconfig.node.json tests/scaling-analysis.ts", "gen:vectors": "node scripts/gen-vector-tests.mjs", - "test": "node scripts/gen-vector-tests.mjs && graph test" + "test": "node scripts/gen-vector-tests.mjs && graph test -d" }, "devDependencies": { "@graphprotocol/graph-cli": "^0.80.0", diff --git a/subgraph/tests/protobuf.test.ts b/subgraph/tests/protobuf.test.ts index b310bdfe..f2723fe3 100644 --- a/subgraph/tests/protobuf.test.ts +++ b/subgraph/tests/protobuf.test.ts @@ -46,7 +46,7 @@ describe("protobuf decoder: shared index_scheme vectors", () => { describe("protobuf decoder: hardening", () => { test("oversized key does not alias field 14", () => { - // key varint = 2^32 + 0x70 (would read as field 14 if narrowed to i32), value 1. + // key varint = 2^39 + 0x70 (would read as field 14 if narrowed to i32), value 1. let d = decodeFact(Bytes.fromHexString("f08080808010" + "01")); assert.i32Equals(d.indexScheme as i32, 0); }); From 1d204ab00d796880a4b2342e70c63a7e05a8e4af Mon Sep 17 00:00:00 2001 From: p-diogo Date: Fri, 4 Dec 2026 22:01:42 +0000 Subject: [PATCH 3/3] test(subgraph): correct a comment in the unmarked tombstone test Co-Authored-By: Claude Opus 5.5 --- subgraph/tests/mapping.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/subgraph/tests/mapping.test.ts b/subgraph/tests/mapping.test.ts index 6a35df68..9a52d333 100644 --- a/subgraph/tests/mapping.test.ts +++ b/subgraph/tests/mapping.test.ts @@ -86,7 +86,8 @@ describe("handleLog: index_scheme gate", () => { test("unmarked tombstone has no effect on a known marked fact", () => { send(vec("marked_fact").hex); - // Same id as the marked fact so a leak would show as a deactivation. + // The gate drops every unmarked payload before any lookup, so the + // marked fact and the count stay unchanged. let legacyTomb = vec("legacy_unmarked_tombstone"); assert.assertTrue(legacyTomb.id == LEGACY_ID); send(legacyTomb.hex);