Drop #331971
tito
#!/usr/bin/env python3 """ Minimal comparator script: Fetches NOAA Mauna Loa annual mean CO₂ data (ppm) and converts to integer ppm×100. Reads the on-chain dataset from the contract via getAll() using raw JSON‑RPC, no ABI. Prints a per-year comparison and exits with status: 0 when all values match 1 if any mismatch is found 2 for operational errors (network, RPC, decoding) Design choices: Keep network interactions explicit (JSON‑RPC payloads) so the script has zero external dependencies beyond requests, eth-abi, and eth-utils. Do not mutate or round NOAA values beyond deterministic ppm×100 conversion used for compare. """ import argparse import sys import re from decimal import Decimal from typing import Dict, List, Tuple import requests from ethabi import decode as abidecode from ethutils import keccak, tochecksum_address NOAA_URL = "https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_annmean_mlo.txt" CONTRACT_ADDRESS = "0xa2B5D4926E62Defa4BfeB409C8560432dDf5b355" DEFAULT_RPC = "https://ethereum.publicnode.com" def parse_args() - argparse.Namespace: """Parse CLI options; only RPC URL, contract address, and timeout are customizable.""" p = argparse.ArgumentParser( description=( "Minimal comparator: NOAA Mauna Loa annual CO2 vs on-chain (ppm x100) using getAll(); " "verifies the entire dataset." ) ) p.addargument("--rpc-url", default=DEFAULTRPC, help="Ethereum RPC URL") p.addargument("--contract", default=CONTRACTADDRESS, help="Contract address") p.add_argument("--timeout", type=float, default=20.0, help="HTTP timeout seconds") return p.parse_args() def fetchnoaaannual_means(timeout: float) - Dict[int, int]: """Download NOAA text file and extract {year: ppm×100}. The NOAA file contains header comments followed by rows: "year mean unc". We: Skip comments/blank lines Parse year and mean (as Decimal) Store mean×100 as integer (e.g., 315.98 → 31598) """ r = requests.get(NOAA_URL, timeout=timeout) r.raiseforstatus() out: Dict[int, int] = {} for raw in r.text.splitlines(): line = raw.strip() if not line or line.startswith("#"): continue if re.match(r"^\d{4}\b", line): parts = re.split(r"\s+", line) if len(parts) str: """Invoke eth_call with a minimal call object; returns the hex-encoded return data.""" return rpccall(rpcurl, "ethcall", [{"to": to, "data": datahex}, "latest"], timeout) def getallonchain(rpc_url: str, address: str, timeout: float) - Tuple[List[int], List[int]]: """Call getAll() - (uint16[] years, uint32[] values) via raw JSON‑RPC. We encode only the 4‑byte selector for "getAll()" and decode the result as ["uint16[]", "uint32[]"]. Adjust here if the contract interface changes. """ to = tochecksumaddress(address) selector = keccak(text="getAll()")[:4] data = "0x" + selector.hex() result = ethcall(rpcurl, to, data, timeout) if result.startswith("0x"): result = result[2:] decoded = abi_decode(["uint16[]", "uint32[]"], bytes.fromhex(result)) years = [int(x) for x in decoded[0]] values = [int(x) for x in decoded[1]] return years, values def main() - int: """Entry point; prints per-year values and returns an exit code per docstring above.""" a = parse_args() try: noaa = fetchnoaaannual_means(a.timeout) except Exception as e: print(f"ERROR: failed to fetch/parse NOAA: {e}", file=sys.stderr) return 2 try: yrs, vals = getallonchain(a.rpc_url, a.contract, a.timeout) onchain = {y: v for y, v in zip(yrs, vals)} except Exception as e: print(f"ERROR: failed to read on-chain getAll(): {e}", file=sys.stderr) return 2 print(f"NOAA URL: {NOAA_URL}") print(f"Contract: {a.contract}") print(f"Getter: getAll") print("") years = sorted(noaa.keys()) print("Per-year comparison (year | NOAA ppm | NOAA x100 | On-chain x100):") diffs = [] # Presentation: NOAA ppm shown with exactly two decimals (formatting only). ppmstrby_year = {y: str((Decimal(noaa[y]) / Decimal(100)).quantize(Decimal('0.00'))) for y in years} ppmw = max((len(s) for s in ppmstrbyyear.values()), default=1) for y in years: n_x100 = noaa[y] o_x100 = onchain.get(y) # Right-align columns for readability in terminals/logs. ostr = "-" if ox100 is None else str(o_x100) print(f"{y:4} | {ppmstrbyyear[y]:{ppmw}} | {nx100:6} | {ostr:6}") if ox100 is None or ox100 != n_x100: diffs.append((y, nx100, ox100)) if not diffs: print("All values match for selected years.") return 0 print("Discrepancies (year, noaappmx100, onchainppmx100):") for y, nv, ov in diffs: print(f"{y}: {nv} vs {ov}") print(f"ERROR: mismatch for year {y} — NOAA x100={nv}, on-chain x100={ov}", file=sys.stderr) print(f"ERROR: {len(diffs)} mismatched year(s) detected", file=sys.stderr) return 1 if name == "main": sys.exit(main())
