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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,10 @@ jobs:
# vectors before printing anything, so a broken primitive exits non-zero.
- name: secp256k1 probe self-test
run: python3 -I tools/secp256k1_probe.py

# The claim fixture is the cross-language vector the contract's digest tests run
# against. Before #76 it was a hand-pasted blob nobody could re-derive, so when the
# encoding changed there was no way to tell the fixture had gone stale. Now the
# script is the derivation and this step fails if the committed file disagrees.
- name: The claim fixture is what the generator produces
run: python3 tools/make_claim_fixture.py --check
74 changes: 70 additions & 4 deletions docs/interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,67 @@ proof must match.
**Until the template is set, `request_advance` refuses with `TemplateNotSet` (10).** The contract
deploys in a safe state rather than one that accepts anything.

### The template holds eight parts and takes seven values (#76)

```
pub_id, start_year, start_month, start_day, end_year, end_month, end_day
```

Seven, not three, because **AdSense has no string form for a date.** `startDate` and `endDate` on
`accounts.reports.generate` are `object (Date)` — `{year, month, day}` as *integers* — which the
REST transport flattens into `startDate.year=2026&startDate.month=7&startDate.day=1`. Unpadded:
`7`, never `07`. Verified against Google's own reference, not inferred.

So the rebuilt URL is the one `be/src/adsense/request.ts` actually sends:

```
https://adsense.googleapis.com/v2/accounts/<pub_id>/reports:generate
?dateRange=CUSTOM
&startDate.year=<y>&startDate.month=<m>&startDate.day=<d>
&endDate.year=<y>&endDate.month=<m>&endDate.day=<d>
&metrics=ESTIMATED_EARNINGS&currencyCode=USD&reportingTimeZone=ACCOUNT_TIME_ZONE
```

**The interface does not change.** `request_advance` still takes `window_start` and `window_end` as
`YYYY-MM-DD`, and the nullifier is still computed over those strings. `claim::split_date` converts
them on the way into the template — ten bytes of fixed-width parsing, every byte checked, no JSON.
A window that is not exactly `dddd-dd-dd` is refused with `ClaimMismatch` rather than guessed at.

A four-part template is now refused by `set_claim_template` itself. It described
`?startDate=2026-07-01`, a request the AdSense API cannot serve, so every real proof built against
it was refused with a bare `ClaimMismatch` and no clue why.

## 3. The claim's context, rebuilt rather than parsed

Canonical context is sorted-key JSON with no whitespace. A JSON parser in `no_std` wasm would be
large, slow, and its bugs indistinguishable from a bad proof, so the contract **rebuilds** the
string from the values it was handed and compares byte for byte:

```
{"contextAddress":"<borrower G…>","contextMessage":"<constant>","extractedParameters":{"currency":"USD","endDate":"<end>","revenueUsd":"<figure>","startDate":"<start>"},"providerHash":"<hash>"}
{"contextAddress":"<borrower G…>","contextMessage":"<constant>","extractedParameters":{"revenueUsd":"<figure>"},"providerHash":"<hash>"}
```

Key order above is alphabetical because that is what canonicalisation produces — it is not a
stylistic choice and must not be "tidied".

### `extractedParameters` holds the figure and nothing else (#76)

It used to carry `currency`, `startDate` and `endDate` as well. Those cannot be there. A Reclaim
`responseMatches` regex captures **one contiguous substring**, and AdSense echoes the window back as
`"startDate":{"year":2026,"month":7,"day":1}` — there is no `"2026-07-01"` anywhere in the response
to capture. A context asking for one describes a proof the provider cannot produce.

Neither field left the signature; both moved to where the provider actually puts them, and both are
in `parameters`, which this contract pins:

| Was asserted by | Now asserted by |
| --- | --- |
| `extractedParameters.currency` | the `"currencyCode": "USD"` response match |
| `extractedParameters.startDate` / `.endDate` | the URL — Google computes the totals **for the window in the URL** |

So the window and the currency are held exactly as strongly as before. What changed is which signed
field holds them.

`canonical_context_matches` in `sc/reclaim-claim` does this comparison. Any difference at all —
ordering, whitespace, a trailing byte — is a refusal.

Expand Down Expand Up @@ -204,9 +252,8 @@ request_advance(
borrower: Address, // must equal contextAddress inside the signed claim
revenue_usd: String, // decimal string from extractedParameters
pub_id: String, // AdSense publisher id
window_start: String, // YYYY-MM-DD, must match the template
window_start: String, // YYYY-MM-DD; split into year/month/day for the URL (§2)
window_end: String,
context_message: String,
timestamp_s: u64,
epoch: u64,
signature: BytesN<64>,
Expand All @@ -217,7 +264,8 @@ request_advance(
Order is the security property, and it does not change:

1. template is set, else `TemplateNotSet`
2. rebuild `context` and `parameters`; rebuild `identifier`; build the digest
2. split each window date into unpadded year/month/day, else `ClaimMismatch`; rebuild `context` and
`parameters`; rebuild `identifier`; build the digest
3. freshness
4. **cross-contract `verify_proof`** — everything after this point is attested
5. nullifier not spent → **write the nullifier**
Expand All @@ -234,3 +282,21 @@ transfer in between is the classic race.
(#5) and are set by `set_claim_template` — no code change, one admin call.

Everything else here is frozen. @Lin1er @AncungAulia — build against it.

### What this freeze got wrong, and how (#76)

The freeze happened before any real AdSense response existed — deliberately, because waiting would
have cost all of M2 to a problem about a Google account. The gamble was that the *shape* of a
claim could be pinned ahead of seeing one. It mostly held; in two places it did not:

- `?startDate=2026-07-01` is not a request AdSense can serve.
- `extractedParameters` asked for fields a single-capture regex cannot extract.

Every real proof would have been refused, with `ClaimMismatch` and no indication of which byte was
wrong — the hardest failure in this pipeline to read. Found by @Lin1er on #6 while building the
provider, by comparing this document against the API rather than against the contract, which is the
only way it could have been found before the first proof arrived.

The lesson worth keeping is narrow: **the part of a freeze that describes someone else's API is a
guess until it is checked against that API.** Checking it did not need a live account — the
reference page was enough, and nobody read it.
73 changes: 65 additions & 8 deletions sc/advance/src/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,31 +69,88 @@ pub fn rebuild_parameters(parts: &Vec<Bytes>, values: &[Bytes]) -> Option<Bytes>
Some(out)
}

/// Split `"YYYY-MM-DD"` into the three unpadded ASCII numbers AdSense takes (#76).
///
/// The AdSense Management API has **no string form for a date**. `startDate` and `endDate`
/// on `accounts.reports.generate` are `object (Date)` — `{year, month, day}` as *integers*
/// — which the REST transport flattens into `startDate.year=2026&startDate.month=7&
/// startDate.day=1`. Integers, so `7`, never `07`.
///
/// So the contract takes the window in the one form a human and a nullifier can both read,
/// `YYYY-MM-DD`, and produces the six values the signed URL actually carries. The interface
/// and the nullifier are unchanged; only what gets interleaved into the template changes.
///
/// Fixed-width parsing of exactly ten bytes. No JSON, no allocation beyond the three
/// outputs, and every byte is checked: a caller cannot smuggle a `&` or a digit-shaped
/// surprise into the URL this helps rebuild.
///
/// Returns `None` for anything that is not exactly `dddd-dd-dd`.
pub fn split_date(env: &Env, date: &Bytes) -> Option<(Bytes, Bytes, Bytes)> {
if date.len() != 10 {
return None;
}
let mut b = [0u8; 10];
date.copy_into_slice(&mut b);
if b[4] != b'-' || b[7] != b'-' {
return None;
}
for (i, c) in b.iter().enumerate() {
if i != 4 && i != 7 && !c.is_ascii_digit() {
return None;
}
}
Some((
unpadded(env, &b[0..4]),
unpadded(env, &b[5..7]),
unpadded(env, &b[8..10]),
))
}

/// ASCII digits with leading zeros removed, as an integer is serialised. `"07"` → `"7"`,
/// `"00"` → `"0"`. Never empty, so the rebuilt URL always has a value where one belongs.
fn unpadded(env: &Env, digits: &[u8]) -> Bytes {
let mut i = 0;
while i + 1 < digits.len() && digits[i] == b'0' {
i += 1;
}
Bytes::from_slice(env, &digits[i..])
}

/// Rebuild the canonical context, byte for byte.
///
/// Canonical context is sorted-key JSON with no whitespace, so the key order below is
/// alphabetical because that is what canonicalisation produces — it is not style and must
/// not be tidied. Building it rather than parsing it keeps a JSON parser out of the wasm,
/// where its bugs would be indistinguishable from a bad proof.
#[allow(clippy::too_many_arguments)]
///
/// # Why `extractedParameters` holds only the figure (#76)
///
/// It used to carry `currency`, `startDate` and `endDate` too. Those cannot be there: a
/// Reclaim `responseMatches` regex captures one contiguous substring, and AdSense echoes
/// the window back as `"startDate":{"year":2026,"month":7,"day":1}` — there is no
/// `"2026-07-01"` anywhere in the response to capture. A context asking for one describes
/// a proof the provider cannot produce, which is why every real AdSense proof was refused.
///
/// Neither field is lost, only moved to where it is actually signed:
///
/// * **the currency** by the `"currencyCode": "USD"` match, which lives in `parameters`;
/// * **the window** by the URL, which lives in `parameters` too — Google computes the
/// totals *for the window in the URL*, so the URL alone fixes the period.
///
/// `parameters` is pinned in this contract and rebuilt here, so both are as strongly held
/// as they were in the context. Nothing moved outside the signature.
pub fn rebuild_context(
env: &Env,
borrower: &Bytes,
revenue_usd: &Bytes,
window_start: &Bytes,
window_end: &Bytes,
provider_hash: &Bytes,
) -> Bytes {
let mut out = Bytes::from_slice(env, br#"{"contextAddress":""#);
out.append(borrower);
out.extend_from_slice(br#"","contextMessage":""#);
out.extend_from_slice(CONTEXT_MESSAGE);
out.extend_from_slice(br#"","extractedParameters":{"currency":"USD","endDate":""#);
out.append(window_end);
out.extend_from_slice(br#"","revenueUsd":""#);
out.extend_from_slice(br#"","extractedParameters":{"revenueUsd":""#);
out.append(revenue_usd);
out.extend_from_slice(br#"","startDate":""#);
out.append(window_start);
out.extend_from_slice(br#""},"providerHash":""#);
out.append(provider_hash);
out.extend_from_slice(br#""}"#);
Expand Down
32 changes: 20 additions & 12 deletions sc/advance/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,15 +466,23 @@ impl AdvanceContract {
/// proof must match.
///
/// `parts` are the literal segments of the request, interleaved at verification time
/// with the publisher id, window start and window end — so it must hold exactly four
/// entries for the three values this contract supplies.
/// with the **seven** values this contract supplies, in this order:
///
/// ```text
/// pub_id, start_year, start_month, start_day, end_year, end_month, end_day
/// ```
///
/// So it must hold exactly eight entries. Seven rather than three because AdSense has
/// no string form for a date: `reports:generate` takes `startDate.year=2026&
/// startDate.month=7&startDate.day=1`, unpadded, and one `"2026-07-01"` cannot fill
/// three query parameters (#76).
pub fn set_claim_template(
env: Env,
parts: Vec<Bytes>,
provider_hash: Bytes,
) -> Result<(), Error> {
let admin = Self::require_admin(&env)?;
if parts.len() != 4 {
if parts.len() != 8 {
return Err(Error::ClaimMismatch);
}
let n = parts.len();
Expand Down Expand Up @@ -551,17 +559,17 @@ impl AdvanceContract {
let start_b = claim::string_bytes(&env, &window_start).ok_or(Error::ClaimMismatch)?;
let end_b = claim::string_bytes(&env, &window_end).ok_or(Error::ClaimMismatch)?;

// The window reaches the signed URL as six unpadded numbers, because that is the
// only form AdSense accepts (#76). `window_start` and `window_end` stay
// `YYYY-MM-DD` in the interface and in the nullifier — this is a re-encoding on
// the way into the template, not a change to what is being borrowed against.
let (sy, sm, sd) = claim::split_date(&env, &start_b).ok_or(Error::ClaimMismatch)?;
let (ey, em, ed) = claim::split_date(&env, &end_b).ok_or(Error::ClaimMismatch)?;

let parameters =
claim::rebuild_parameters(&parts, &[pub_id_b.clone(), start_b.clone(), end_b.clone()])
claim::rebuild_parameters(&parts, &[pub_id_b.clone(), sy, sm, sd, ey, em, ed])
.ok_or(Error::ClaimMismatch)?;
let context = claim::rebuild_context(
&env,
&borrower_b,
&revenue_b,
&start_b,
&end_b,
&provider_hash,
);
let context = claim::rebuild_context(&env, &borrower_b, &revenue_b, &provider_hash);

let identifier = claim::identifier(&env, &parameters, &context);
let identifier_hex = claim::hex_prefixed(&identifier);
Expand Down
Loading