Metadata-Version: 2.5
Name: tensorseal
Version: 0.1.0
Summary: Prove a deployed ML model is bit-for-bit the one that was audited, by anchoring its hash on Ethereum
Author: msr8
License-Expression: MIT
License-File: LICENSE
Keywords: audit,blockchain,ethereum,keras,machine learning,model integrity,model provenance,pytorch,scikit-learn
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security :: Cryptography
Requires-Python: >=3.10
Requires-Dist: numpy
Requires-Dist: requests
Requires-Dist: web3>=7
Description-Content-Type: text/markdown

# TensorSeal

**Prove that the ML model you are running is bit-for-bit the model that was audited.**

When a model passes an audit, TensorSeal fingerprints it and writes the fingerprint to a public blockchain (Ethereum). Later, anyone can fingerprint the deployed model and compare it with the chain. Not even the model's owner can change that record. If a single weight differs, you get `MISMATCH` plus the names of the layers that changed.

- Works with **PyTorch, Keras and scikit-learn**.
- **Verifying is free** and needs no wallet or account.
- The model never leaves your machine. Only a 32-byte hash goes on-chain.

```sh
pip install tensorseal
tensorseal verify mnist-test@1 model.pt --arch mynet:Net
```

```text
VALID  mnist-test@1: this model is exactly the registered one
  on-chain root  690041da1367cf2924db047167663d62e148cd662b5e89803a50bece8f1348de
  this model     690041da1367cf2924db047167663d62e148cd662b5e89803a50bece8f1348de
  registered     2026-10-27 10:14:24 UTC by 0x9a63879de57AcE23ff2813959EeD13718dCe274B
  registry       https://sepolia.etherscan.io/address/0x76C51706d34b269ca3CE2222BC0AfC0F0270106b
```

---

## 1. Install

```sh
pip install tensorseal
```

You need Python 3.10 or newer. TensorSeal doesn't install any ML framework: it uses the PyTorch, Keras or scikit-learn you already have.

By default, TensorSeal talks to the **public TensorSeal registry on Ethereum's Sepolia test network**, through a free public node. There's nothing to configure.

---

## 2. Verify a model

Verifying reads the blockchain only. You don't need a wallet, test ETH or an account.

**Command line:**

```sh
tensorseal verify <model-id> <model-file> [--arch module:Class]
```

**Python:**

```python
from tensorseal import Registry

result = Registry.connect().verify('mnist-test@1', model)   # model = your nn.Module / Keras model / sklearn estimator
result['status']   # 'VALID', 'MISMATCH' or 'NOT_REGISTERED'
```

The three possible results:

| Result | Meaning | CLI exit code |
|---|---|---|
| `VALID` | The model is exactly the one registered under that ID | 0 |
| `MISMATCH` | Something differs. The output names the changed, added or removed layers | 1 |
| `NOT REGISTERED` | Nobody has registered that ID | 2 |

Here's a backdoored copy swapped in for the registered model:

```text
MISMATCH  mnist-test@1: this model is NOT the registered one
  on-chain root  690041da1367cf2924db047167663d62e148cd662b5e89803a50bece8f1348de
  this model     d77548c72b20b76826f5d5025abaf5200fa5fb57754568c630a0223f1f109e80
  registered     2026-10-27 10:14:24 UTC by 0x9a63879de57AcE23ff2813959EeD13718dCe274B
  registry       https://sepolia.etherscan.io/address/0x76C51706d34b269ca3CE2222BC0AfC0F0270106b
  changed:       c1.bias, c1.weight, c2.bias, c2.weight, fc1.bias, fc1.weight, fc2.bias, fc2.weight
```

> **Check who registered it.** Anyone can register any unused model ID. A `VALID` result proves the model matches the record, so also confirm that the `registered … by` address belongs to whoever you trust: the auditor, or the model's publisher.

**Verify the model the same way it was registered.**
- If it was registered as a model object (from Python, or from the CLI with `--arch`), verify it as a model object too.
- If it was registered from a bare weights file, verify the bare weights file.

When this is the reason for a mismatch, the CLI says so (see section 9, Troubleshooting).

---

## 3. Hash a model (offline)

This needs no blockchain at all. It's useful for comparing two files, or for seeing what would be registered.

```sh
tensorseal hash model.pt --arch mynet:Net
tensorseal hash model.pt --arch mynet:Net -o manifest.json     # also save the hashes as JSON
```

```text
model   model.pt  [torch]
root    690041da1367cf2924db047167663d62e148cd662b5e89803a50bece8f1348de
  __architecture__  39329e7dbbfbba493aeea2b272017cd904aa4f3900095ff9c2913d174a82d516
  c1.bias           fa41eef660f1fadf43adc9eb6d2499c6d731ef677f48327140827887d078118e
  c1.weight         6f1ac84c17da989eda150537544177e2bf88fe2e10d39b7e661d948518dd7aa3
  ...
```

```python
from tensorseal import model_hash, diff

h = model_hash(model)      # {'framework': 'torch', 'root': '6900…', 'parts': {'c1.bias': 'fa41…', ...}}
diff(model_hash(a)['parts'], model_hash(b)['parts'])
# {'changed': ['fc2.bias', 'fc2.weight'], 'added': [], 'removed': []}
```

The output has one hash per tensor, plus one for the architecture. A change to the architecture, such as an extra layer, a different layer type or a changed setting like padding or dropout, shows up as `__architecture__`.

The hash is deterministic. Saving and reloading the model, moving it between CPU and GPU, or reordering dict keys leaves it unchanged. Changing any weight, even by 1e-6, changes it.

---

## 4. Register a model

Registering writes to the blockchain, so it needs a wallet holding a little **free test ETH**. A registration costs a tiny fraction of what a faucet gives you. This setup is one-time.

**Step 1: create a wallet**

```sh
tensorseal wallet
```

```text
created a wallet and saved its key to /path/to/project/.env
keep that file secret and out of git (add .env to .gitignore)
address  0x3B1f…c9A2
balance  0 ETH (chain 11155111)
to register models it needs a little test ETH: paste the address into a faucet, e.g.
  https://cloud.google.com/application/web3/faucet/ethereum/sepolia
  https://sepolia-faucet.pk910.de
```

The key goes into `.env` in the current folder as `TENSORSEAL_PRIVATE_KEY`, and every `tensorseal` command run from that folder picks it up. Run `tensorseal wallet` again at any time to see the address and balance. It never overwrites an existing key.

**Step 2: get test ETH.** Paste the address into one of the faucets above. 0.01 test ETH covers many registrations.

**Step 3: register**

```sh
tensorseal register fraud-detector@1 model.pt --arch mynet:Net \
    --manifest-uri https://example.com/manifests/fraud-detector@1.json
```

```python
from tensorseal import Registry

r = Registry.connect().register('fraud-detector@1', model,
                                manifest_uri='https://example.com/manifests/fraud-detector@1.json')
r['root'], r['tx']
```

This does three things:
1. It writes the root hash, the manifest's location, your address and the time on-chain, in about 15 seconds.
2. It prints the transaction's Etherscan link.
3. It saves `manifests/fraud-detector@1.json`, which holds the per-layer hashes.

**Upload that file to the `--manifest-uri` URL.** Any host that serves the raw file works, such as a GitHub raw link, an S3 bucket or an IPFS gateway. Verifiers use it to name *which* layers changed. Without it they still get `MISMATCH`, just not the list of layers. If you leave out `--manifest-uri`, the record points at your local file, and only you get the layer report.

Rules:
- **Each model ID can be registered once only.** Records can never be edited or deleted; that's the point. Put a version in the ID (`name@1`, `name@2`, …).
- Register the exact artifact the auditor approved, ideally as part of audit sign-off.

---

## 5. Model files the CLI can read

| File | How it's loaded | Notes |
|---|---|---|
| `.pt` `.pth` `.bin` | `torch.load(weights_only=True)` | Must be a plain `state_dict`. Safe to open untrusted files |
| `.safetensors` | `safetensors.torch.load_file` | Needs `pip install safetensors` |
| `.keras` `.h5` | `keras.models.load_model(compile=False)` | Includes the architecture automatically |
| `.pkl` `.pickle` `.joblib` | `joblib.load` | scikit-learn. Needs `--allow-pickle`, see below |

**`--arch module:Class` (PyTorch).** A weights file holds only weights, not the network's structure. With `--arch`, TensorSeal imports `Class` from `module` (searched in the current folder first), builds it with no arguments, and loads the weights into it. The hash then covers the architecture too, and matches what `model_hash(model)` gives in Python. Use it whenever you have the model's class.

**`--allow-pickle`.** Opening a pickle file can run arbitrary code hidden inside it, so the CLI refuses unless you pass this flag. Only pass it for files from a source you trust.

**Anything else** (a model whose constructor needs arguments, a checkpoint with extra keys, a Hugging Face model): load it yourself and use the Python API, which accepts the model object directly:

```python
from transformers import AutoModel
from tensorseal import Registry

model = AutoModel.from_pretrained('...')
Registry.connect().verify('my-model@1', model)
```

---

## 6. Use it as a deployment gate

The CLI's exit codes let you block a deploy whenever the model isn't the audited one:

```sh
tensorseal verify fraud-detector@3 build/model.pt --arch mynet:Net || exit 1
```

Every command also accepts `--json` for machine-readable output:

```sh
tensorseal verify fraud-detector@3 build/model.pt --arch mynet:Net --json
```

```json
{
  "status": "MISMATCH",
  "model_id": "fraud-detector@3",
  "onchain_root": "6900…",
  "actual_root": "d775…",
  "registrant": "0x9a63879de57AcE23ff2813959EeD13718dCe274B",
  "registered_at": 1793096064,
  "diff": {"changed": ["fc2.bias", "fc2.weight"], "added": [], "removed": []}
}
```

---

## 7. Your own registry or a local chain

You can change these settings with flags or environment variables. A `.env` file in the current folder also works.

| Setting | Flag | Variable | Default |
|---|---|---|---|
| Blockchain node | `--rpc URL` | `TENSORSEAL_RPC_URL` | public Sepolia node |
| Registry contract | `--registry ADDRESS` | `TENSORSEAL_REGISTRY` | the public TensorSeal registry `0x76C51706d34b269ca3CE2222BC0AfC0F0270106b` |
| Signing wallet | — | `TENSORSEAL_PRIVATE_KEY` | none (only needed to register or deploy) |

**Deploy your own registry** if you want a separate namespace. This needs a funded wallet:

```sh
tensorseal deploy
```

The address is saved to `deployments/<chain id>.json`, and commands run from that folder use it automatically. Elsewhere, pass `--registry ADDRESS`. On public networks, deploy also publishes the contract's source code to Sourcify, so anyone can read it on the block explorer and confirm there's no edit or delete function.

**Use a local test chain** for offline experiments with [Foundry](https://getfoundry.sh)'s `anvil`. No wallet is needed, because Anvil provides funded accounts:

```sh
anvil                                                  # terminal 1
tensorseal deploy   --rpc http://127.0.0.1:8545        # terminal 2
tensorseal register test@1 model.pt --rpc http://127.0.0.1:8545
tensorseal verify   test@1 model.pt --rpc http://127.0.0.1:8545
```

Anvil forgets everything when it stops, so deploy again after each restart. If your `.env` holds a Sepolia key, clear it for local runs, for example with `TENSORSEAL_PRIVATE_KEY= tensorseal deploy --rpc …`.

---

## 8. How it works

1. **Fingerprint.** TensorSeal converts the model into a framework-neutral form. It hashes each tensor (name, shape, dtype and little-endian bytes) and the architecture description separately with SHA-256, then hashes all of those part hashes together into one **root**.
2. **Register.** Only the root goes on-chain, into a registry contract with two functions, `register` and `lookup`. There's no update or delete, so a record can't be changed even by the person who wrote it. Each record also stores where the per-layer hashes (the *manifest*) are published, plus the registrant and the time.
3. **Verify.** The model is re-hashed and its root compared with the on-chain root. On a mismatch, the verifier fetches the manifest and **checks that its hashes recombine to the on-chain root**. That way a doctored manifest is rejected and can't be used to hide a change. It then compares the hashes part by part to name the changed layers.

**What it proves, and what it doesn't.** TensorSeal proves the model **hasn't changed since it was registered**. It doesn't prove the model is *good*. A model backdoored during training, before registration, verifies as `VALID`. Pair TensorSeal with behavioural testing, such as backdoor detection and red-teaming, and register only models that passed it.

The default registry lives on **Sepolia**, Ethereum's public test network. Anyone can read it or check it, and no single party can rewrite it. Its validators are a smaller, permissioned set than mainnet's. To deploy the same contract on Ethereum mainnet or another EVM chain, use `tensorseal deploy --rpc <that chain's node>`.

---

## 9. Troubleshooting

| Problem | Fix |
|---|---|
| `MISMATCH` and only `__architecture__` changed, with a hint about `--arch` | The model was registered with its architecture, but you verified a bare weights file. Add `--arch module:Class`, or verify the model object from Python |
| `'…' is already registered` | IDs are write-once. Use a new ID, such as `name@2` |
| `the wallet has no test ETH` | Run `tensorseal wallet` for the address and faucet links |
| `writing to the blockchain needs a wallet` | Run `tensorseal wallet`. Verifying doesn't need one; registering and deploying do |
| `cannot reach the blockchain node` | Check your connection, or use another Sepolia node with `--rpc` / `TENSORSEAL_RPC_URL` |
| `… is not a plain state_dict` / `holds more than plain weights` | Save `model.state_dict()` on its own, or use the Python API with the model object |
| `layers  unknown: manifest … unavailable` | The registrant didn't publish the manifest, or its URL is down. The `MISMATCH` itself is still reliable |
| **Windows:** `Cannot load native module 'Crypto.Cipher._Salsa20'` or `DLL load failed … Application Control policy has blocked this file` | Windows Smart App Control is blocking a freshly released native wheel it doesn't recognise yet. Install an older release of the package named in the error, for example `pip install "pycryptodome<3.24"` (stop any running Python/Jupyter first). Or turn off Smart App Control |

---

## 10. Python API

```python
from tensorseal import Registry, model_hash, diff, root_from_parts, read_manifest, load_env
```

| Call | Returns |
|---|---|
| `model_hash(model)` | `{'framework', 'root', 'parts'}` for a torch module or state_dict, Keras model or sklearn estimator |
| `diff(parts_a, parts_b)` | `{'changed', 'added', 'removed'}`, lists of part names |
| `root_from_parts(parts)` | The root recomputed from a `{name: hex}` part map |
| `Registry.connect(rpc=None, address=None)` | A client for the registry (defaults as in section 7). Reads `./.env` |
| `Registry.deploy(rpc=None)` | Deploys a new registry and returns its client |
| `reg.verify(model_id, model)` | `{'status', 'onchain_root', 'actual_root', 'registrant', 'registered_at'}` plus `'diff'` or `'manifest_error'` on a mismatch |
| `reg.register(model_id, model, manifest_uri=None)` | The `model_hash()` result plus `'manifest'`, `'manifest_uri'` and `'tx'`. Raises `ValueError` if the ID is taken |
| `reg.lookup(model_id)` | `{'root', 'manifest_uri', 'registrant', 'timestamp'}`, or `None` |
| `read_manifest(uri)` | The part map from a URL or local path, or `None` |
| `load_env(path='.env')` | Loads `KEY=VALUE` lines into the environment. Existing variables win |

---

## Development

```sh
pip install -e . py-solc-x
python test_tensorseal.py              # self-checks; framework blocks skip if that framework can't be imported
python scripts/build_contract.py       # after editing tensorseal/ModelRegistry.sol: rebuilds the shipped artifact
```

The hash format is a compatibility contract. Changing it changes every registered root, so `tensorseal/canonical.py` changes need a new major version.

License: MIT.
