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
4 changes: 4 additions & 0 deletions packages/sdk-python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions packages/sdk-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk-python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk-python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=[
Expand Down
4 changes: 3 additions & 1 deletion packages/sdk-python/src/nirium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down
67 changes: 67 additions & 0 deletions packages/sdk-python/src/nirium/receipts.py
Original file line number Diff line number Diff line change
@@ -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())
38 changes: 38 additions & 0 deletions packages/sdk-python/tests/test_receipt_cid.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 4 additions & 0 deletions packages/sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions packages/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
1 change: 1 addition & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
35 changes: 35 additions & 0 deletions packages/sdk/src/receipt-cid.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
54 changes: 54 additions & 0 deletions packages/sdk/src/receipt-cid.ts
Original file line number Diff line number Diff line change
@@ -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, unknown>): 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;
}