From 935f8e2848f9bfe4cbd32c32cbe241c19a8e45bf Mon Sep 17 00:00:00 2001 From: Giovanny Amador <219895655+Eras256@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:47:38 -0600 Subject: [PATCH] feat(sdk): receiptCid / receipt_cid, and release nirium 0.19.7 and PyPI 0.12.8 Same local CIDv0 check the CLI got in #429, for SDK users: recompute a kept receipt's CID with no IPFS node and no new dependency. - TypeScript: export receiptCid(bytes | string | document object). - Python: nirium.receipt_cid(bytes | str | dict); a dict is serialized as compact JSON with UTF-8 kept, which is what the node pinned. - READMEs: "Keep your own copy" next to the Audit Trail section. - 6 tests each, with two real mainnet receipts as fixtures. Cross-checked CLI, TS, Python and ipfs-only-hash on ASCII and non-ASCII input: same CID. - Versions: nirium 0.19.6 -> 0.19.7 (npm), nirium 0.12.7 -> 0.12.8 (PyPI: pyproject, setup.py, __version__), changelogs. SDK: tsc clean, jest 108/108. Python: 62 passed (langchain test needs the test extras, as in CI). Co-Authored-By: Claude Opus 5.5 --- packages/sdk-python/CHANGELOG.md | 4 ++ packages/sdk-python/README.md | 15 +++++ packages/sdk-python/pyproject.toml | 2 +- packages/sdk-python/setup.py | 2 +- packages/sdk-python/src/nirium/__init__.py | 4 +- packages/sdk-python/src/nirium/receipts.py | 67 +++++++++++++++++++ packages/sdk-python/tests/test_receipt_cid.py | 38 +++++++++++ packages/sdk/CHANGELOG.md | 4 ++ packages/sdk/README.md | 16 +++++ packages/sdk/package-lock.json | 4 +- packages/sdk/package.json | 2 +- packages/sdk/src/index.ts | 1 + packages/sdk/src/receipt-cid.test.ts | 35 ++++++++++ packages/sdk/src/receipt-cid.ts | 54 +++++++++++++++ 14 files changed, 242 insertions(+), 6 deletions(-) create mode 100644 packages/sdk-python/src/nirium/receipts.py create mode 100644 packages/sdk-python/tests/test_receipt_cid.py create mode 100644 packages/sdk/src/receipt-cid.test.ts create mode 100644 packages/sdk/src/receipt-cid.ts diff --git a/packages/sdk-python/CHANGELOG.md b/packages/sdk-python/CHANGELOG.md index 3493874d..666ca640 100644 --- a/packages/sdk-python/CHANGELOG.md +++ b/packages/sdk-python/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the `nirium` (PyPI) package are documented here. ## Unreleased +## 0.12.8 - 2026-11-21 + +New `receipt_cid(document)`: recomputes a receipt's IPFS CID (CIDv0) locally, with no IPFS node and no new dependency, so a copy you kept can be shown to be the original. `anchor_audit_record()` returns the exact pinned `document` on nodes deployed after 21 Nov 2026; the README shows how to save it. Also: tests for every Treasury method (#370), and the README's hosted WebSocket note re-checked on 21 Nov. + ## 0.12.7 - 2026-11-19 README: the hosted signal stream (wss://nirium-agent.fly.dev/ws/signals) did not accept connections when checked on 18 Nov 2026; the WebSocket section and the endpoint table now say so. No code change. diff --git a/packages/sdk-python/README.md b/packages/sdk-python/README.md index 2aff06c8..88060ee6 100644 --- a/packages/sdk-python/README.md +++ b/packages/sdk-python/README.md @@ -79,6 +79,21 @@ anchor = await agent.anchor_audit_record( print(anchor["cid"], anchor["attestedBy"]) ``` +### Keep your own copy + +The receipt lives on IPFS only while someone pins it. `anchor_audit_record()` returns the exact `document` that was pinned (nodes deployed after 21 Nov 2026); save it, and `receipt_cid()` shows any time that your copy is the original. If IPFS ever loses it, add the same bytes again (`ipfs add --cid-version=0`) and you get the same CID. + +```python +import json +from nirium import receipt_cid + +anchor = await agent.anchor_audit_record(hash=hash, tag="invoice-batch-jul") +if "document" in anchor: + data = json.dumps(anchor["document"], separators=(",", ":"), ensure_ascii=False).encode() + open("receipt.json", "wb").write(data) # exactly what was pinned + assert receipt_cid(open("receipt.json", "rb").read()) == anchor["cid"] +``` + ### Verify any receipt, without trusting Nirium ```bash diff --git a/packages/sdk-python/pyproject.toml b/packages/sdk-python/pyproject.toml index 9c5182d1..0e136ef4 100644 --- a/packages/sdk-python/pyproject.toml +++ b/packages/sdk-python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nirium" -version = "0.12.7" +version = "0.12.8" description = "Pay per request in USDC on Stellar (x402) from Python and AI agents, with a spending cap and receipts anyone can verify. Non-custodial." readme = "README.md" requires-python = ">=3.10" diff --git a/packages/sdk-python/setup.py b/packages/sdk-python/setup.py index 6b37e1df..823b2421 100644 --- a/packages/sdk-python/setup.py +++ b/packages/sdk-python/setup.py @@ -2,7 +2,7 @@ setup( name="nirium", - version="0.12.7", + version="0.12.8", package_dir={"": "src"}, packages=find_packages(where="src"), install_requires=[ diff --git a/packages/sdk-python/src/nirium/__init__.py b/packages/sdk-python/src/nirium/__init__.py index 01f16b98..b14a0a51 100644 --- a/packages/sdk-python/src/nirium/__init__.py +++ b/packages/sdk-python/src/nirium/__init__.py @@ -9,17 +9,19 @@ X402NetworkMismatchError, X402SpendCapError, ) +from .receipts import receipt_cid if TYPE_CHECKING: from .langchain_tools import NiriumX402Tool, create_nirium_x402_tool -__version__ = "0.12.7" +__version__ = "0.12.8" __all__ = [ "Agent", "WebSocketMaxRetriesExceeded", "WebSocketStatus", "X402NetworkMismatchError", "X402SpendCapError", + "receipt_cid", "NiriumX402Tool", "create_nirium_x402_tool", ] diff --git a/packages/sdk-python/src/nirium/receipts.py b/packages/sdk-python/src/nirium/receipts.py new file mode 100644 index 00000000..a68a8c90 --- /dev/null +++ b/packages/sdk-python/src/nirium/receipts.py @@ -0,0 +1,67 @@ +"""Keep your own copy of an Audit Trail receipt and check it is the original. + +A receipt is one IPFS block: a dag-pb node wrapping a UnixFS File whose data is +the whole document (anything up to 256 KiB fits in one block). Its CIDv0 is +base58btc(0x12 0x20 || sha256(node)), the same result ``ipfs add`` gives with its +defaults. Checked on 21 Nov 2026 against three real mainnet receipts. +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Dict, Union + +_UNIXFS_BLOCK_BYTES = 262144 +_BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + +def _varint(n: int) -> bytes: + out = bytearray() + while n >= 0x80: + out.append((n & 0x7F) | 0x80) + n >>= 7 + out.append(n) + return bytes(out) + + +def _bytes_field(tag: int, data: bytes) -> bytes: + return bytes([tag]) + _varint(len(data)) + data + + +def _base58btc(data: bytes) -> str: + n = int.from_bytes(data, "big") + out = "" + while n > 0: + n, rem = divmod(n, 58) + out = _BASE58_ALPHABET[rem] + out + for b in data: + if b != 0: + break + out = "1" + out + return out + + +def receipt_cid(document: Union[bytes, str, Dict[str, Any]]) -> str: + """CIDv0 of a receipt, computed locally (no IPFS node, no library). + + Pass the exact bytes you saved, or the ``document`` dict returned by + ``anchor_audit_record()``. A dict is serialized the way the node pinned it: + compact JSON (no spaces) with non-ASCII characters kept as UTF-8. + """ + if isinstance(document, dict): + data = json.dumps(document, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + elif isinstance(document, str): + data = document.encode("utf-8") + else: + data = bytes(document) + if not data: + raise ValueError("receipt_cid: the document is empty") + if len(data) > _UNIXFS_BLOCK_BYTES: + raise ValueError( + f"receipt_cid: {len(data)} bytes is more than one IPFS block ({_UNIXFS_BLOCK_BYTES}); " + "every Audit Trail receipt fits" + ) + unixfs = b"\x08\x02" + _bytes_field(0x12, data) + b"\x18" + _varint(len(data)) + node = _bytes_field(0x0A, unixfs) + return _base58btc(b"\x12\x20" + hashlib.sha256(node).digest()) diff --git a/packages/sdk-python/tests/test_receipt_cid.py b/packages/sdk-python/tests/test_receipt_cid.py new file mode 100644 index 00000000..257f5ef0 --- /dev/null +++ b/packages/sdk-python/tests/test_receipt_cid.py @@ -0,0 +1,38 @@ +"""receipt_cid: recompute a receipt's CID locally. Fixtures are two real mainnet +receipts, byte for byte as the gateway serves them (shared with the CLI tests).""" + +import json +from pathlib import Path + +import pytest + +from nirium import receipt_cid + +FIXTURES = Path(__file__).resolve().parents[2] / "cli" / "test" / "fixtures" / "receipts" +CIDS = ["QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U", "QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk"] + + +@pytest.mark.parametrize("cid", CIDS) +def test_real_receipt_bytes_give_back_their_cid(cid): + data = (FIXTURES / f"{cid}.json").read_bytes() + assert receipt_cid(data) == cid + assert receipt_cid(data.decode("utf-8")) == cid + + +@pytest.mark.parametrize("cid", CIDS) +def test_parsed_document_gives_back_the_same_cid(cid): + doc = json.loads((FIXTURES / f"{cid}.json").read_text(encoding="utf-8")) + assert receipt_cid(doc) == cid + + +def test_one_changed_byte_changes_the_cid(): + data = bytearray((FIXTURES / f"{CIDS[0]}.json").read_bytes()) + data[-2] ^= 1 + assert receipt_cid(bytes(data)) != CIDS[0] + + +def test_refuses_empty_and_multi_block_input(): + with pytest.raises(ValueError, match="empty"): + receipt_cid(b"") + with pytest.raises(ValueError, match="one IPFS block"): + receipt_cid(b"a" * 262145) diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index 595c4616..718242e8 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the `nirium` package are documented here. ## Unreleased +## 0.19.7 - 2026-11-21 + +New `receiptCid(document)`: recomputes a receipt's IPFS CID (CIDv0) locally, with no IPFS node and no new dependency, so a copy you kept can be shown to be the original. Accepts the saved bytes, a string, or the `document` object. + `AuditAnchor` gains an optional `document`: the exact JSON pinned to IPFS, returned by Audit Trail nodes deployed after 21 Nov 2026. Keeping it lets you re-add the receipt to IPFS with the same CID. ## 0.19.6 - 2026-11-17 diff --git a/packages/sdk/README.md b/packages/sdk/README.md index c4703f96..1eace4ee 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -77,6 +77,22 @@ const anchor = await agent.anchorAuditRecord({ console.log(anchor.cid, anchor.attestedBy); ``` +### Keep your own copy + +The receipt lives on IPFS only while someone pins it. `anchorAuditRecord()` returns the exact `document` that was pinned (nodes deployed after 21 Nov 2026); save it, and `receiptCid()` shows any time that your copy is the original. If IPFS ever loses it, add the same bytes again (`ipfs add --cid-version=0`) and you get the same CID. + +```typescript +import { receiptCid } from 'nirium'; +import fs from 'node:fs'; + +const anchor = await agent.anchorAuditRecord({ hash, tag: 'invoice-batch-jul' }); +if (anchor.document) { + const bytes = JSON.stringify(anchor.document); // exactly what was pinned, no trailing newline + fs.writeFileSync('receipt.json', bytes); + console.log(receiptCid(fs.readFileSync('receipt.json')) === anchor.cid); // true +} +``` + ### Verify any receipt, without trusting Nirium ```bash diff --git a/packages/sdk/package-lock.json b/packages/sdk/package-lock.json index 034d5814..305840b5 100644 --- a/packages/sdk/package-lock.json +++ b/packages/sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "nirium", - "version": "0.19.6", + "version": "0.19.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "nirium", - "version": "0.19.6", + "version": "0.19.7", "license": "Apache-2.0", "dependencies": { "@stellar/mpp": "^0.7.1", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 89956270..ca491f86 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "nirium", - "version": "0.19.6", + "version": "0.19.7", "description": "Charge or pay per request in USDC on Stellar (x402), with receipts anyone can verify. For apps, backends and AI agents. Non-custodial.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 02923b8c..ee52e73f 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -22,6 +22,7 @@ import { type X402BaseSigner, type X402PolicyHook, type X402PaymentRequirementsView, } from './x402-policy'; import { captureRequirements, toSpendCapError, type X402OfferedRequirement } from './x402-spend-cap'; +export { receiptCid } from './receipt-cid'; export interface AgentConfig { apiKey: string; diff --git a/packages/sdk/src/receipt-cid.test.ts b/packages/sdk/src/receipt-cid.test.ts new file mode 100644 index 00000000..04649f14 --- /dev/null +++ b/packages/sdk/src/receipt-cid.test.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Nirium Protocol Contributors + +import fs from 'node:fs'; +import path from 'node:path'; +import { receiptCid } from './receipt-cid'; + +// Two real mainnet receipts, byte for byte as the gateway serves them +// (shared with the CLI tests). +const fixtures = path.join(__dirname, '..', '..', 'cli', 'test', 'fixtures', 'receipts'); +const CIDS = ['QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U', 'QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk']; + +describe('receiptCid', () => { + it.each(CIDS)('gives back the real CID of %s from its bytes', (cid) => { + const bytes = fs.readFileSync(path.join(fixtures, `${cid}.json`)); + expect(receiptCid(bytes)).toBe(cid); + expect(receiptCid(bytes.toString('utf8'))).toBe(cid); + }); + + it.each(CIDS)('gives back the same CID from the parsed document of %s', (cid) => { + const doc = JSON.parse(fs.readFileSync(path.join(fixtures, `${cid}.json`), 'utf8')); + expect(receiptCid(doc)).toBe(cid); + }); + + it('changes when a single byte changes', () => { + const bytes = Buffer.from(fs.readFileSync(path.join(fixtures, `${CIDS[0]}.json`))); + bytes[bytes.length - 2] ^= 1; + expect(receiptCid(bytes)).not.toBe(CIDS[0]); + }); + + it('refuses empty and multi-block input', () => { + expect(() => receiptCid('')).toThrow(/empty/); + expect(() => receiptCid(Buffer.alloc(262145, 0x61))).toThrow(/one IPFS block/); + }); +}); diff --git a/packages/sdk/src/receipt-cid.ts b/packages/sdk/src/receipt-cid.ts new file mode 100644 index 00000000..793077fb --- /dev/null +++ b/packages/sdk/src/receipt-cid.ts @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Nirium Protocol Contributors + +import { createHash } from 'node:crypto'; + +/** + * CIDv0 of an Audit Trail receipt, computed locally (no IPFS node, no library). + * + * A receipt is one IPFS block: a dag-pb node wrapping a UnixFS File whose data + * is the whole document (anything up to 256 KiB fits in one block). Its CIDv0 + * is base58btc(0x12 0x20 || sha256(node)), the same result `ipfs add` gives with + * its defaults. Checked on 21 Nov 2026 against three real mainnet receipts. + * + * Use it to show that a copy you kept is the original: pass the exact bytes you + * saved, or the `document` object from `anchorAuditRecord()` (it is serialized + * with `JSON.stringify`, which is what the node pinned). + */ +export function receiptCid(document: string | Uint8Array | Record): string { + const bytes = typeof document === 'string' + ? Buffer.from(document, 'utf8') + : document instanceof Uint8Array + ? Buffer.from(document) + : Buffer.from(JSON.stringify(document), 'utf8'); + if (bytes.length === 0) throw new Error('receiptCid: the document is empty'); + if (bytes.length > UNIXFS_BLOCK_BYTES) { + throw new Error(`receiptCid: ${bytes.length} bytes is more than one IPFS block (${UNIXFS_BLOCK_BYTES}); every Audit Trail receipt fits`); + } + const unixfs = Buffer.concat([Buffer.from([0x08, 0x02]), bytesField(0x12, bytes), Buffer.from([0x18]), varint(bytes.length)]); + const node = bytesField(0x0a, unixfs); + const digest = createHash('sha256').update(node).digest(); + return base58btc(Buffer.concat([Buffer.from([0x12, 0x20]), digest])); +} + +const UNIXFS_BLOCK_BYTES = 262144; +const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +function varint(n: number): Buffer { + const out: number[] = []; + while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n = Math.floor(n / 128); } + out.push(n); + return Buffer.from(out); +} + +function bytesField(tag: number, buf: Buffer): Buffer { + return Buffer.concat([Buffer.from([tag]), varint(buf.length), buf]); +} + +function base58btc(buf: Buffer): string { + let n = BigInt('0x' + buf.toString('hex')); + let out = ''; + while (n > 0n) { out = BASE58_ALPHABET[Number(n % 58n)] + out; n /= 58n; } + for (const b of buf) { if (b !== 0) break; out = '1' + out; } + return out; +}