---
id: SI0114
title: "Program bytecode similarity search"
url: https://carbium.sh/library/si/program-bytecode-similarity-search
collection: AI and blockchain
category: RAG and embeddings
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Program bytecode similarity search

Nothing on chain stops anyone from deploying a copy of a popular program. This script reads program bytecode, fingerprints it with sampled 16-byte windows and scores how much of a reference program appears inside each candidate.

## What stops a copy

Nothing on the chain does. A deployed program's bytecode is readable by anyone, and deploying it elsewhere costs rent and fees, so a copy of a popular program is one download and one deploy away. What a reader can do is notice afterwards. If the copy is the same bytes deployed under a new program id, a hash comparison finds it. If the copier changed constants, used another toolchain version or patched a few functions, only a similarity score does.

Authors have one tool on their side. A verified build lets them show that the bytes on chain came from a published source tree. That settles where one program came from and says nothing about the other copies. Finding those is a search problem, and the search here takes a reference program plus a list of candidates and reports how much of the reference's bytecode shows up inside each candidate.

The candidate list comes from you: a fork registry, the program ids that appear in transactions your agent already reads, or a list a user pasted in. The scores then go into a prompt or an embedding index, so an assistant can say that a program the user is about to sign against is a near copy of another one.

## Fingerprinting the bytecode

A program account holds very little. For a program deployed through the upgradeable loader it is 36 bytes: a 4-byte tag and the 32-byte address of a second account, the program data account. That second account opens with a 45-byte header (loader state, deploy slot, upgrade authority) and the ELF file follows, padded with zeros up to the allocated size. Programs on the older non-upgradeable loader keep the ELF in the program account itself. The code reads the owner, takes either path, and trims trailing zeros so padding never counts as content.

A whole-file hash is the wrong tool for this job. Most Rust programs compile their own id into the binary through `declare_id!` and many check it at run time, so a copy that works under a new address usually has those 32 bytes patched or rebuilt and gets a different SHA-256. The script still prints the hash, because a match proves the bytes are identical, and then fingerprints the content.

It slides a 16-byte window over the bytes with a rolling hash, mixes each hash value, and keeps a window only when the mixed value falls in a fixed one-in-eight slice. The choice depends only on the bytes inside the window, so a function that moved 4 KiB later in the file still produces the same kept windows. Two files then compare as two sets of numbers.

Two scores come out of the sets. Containment is the share of the reference's kept windows that also occur in the candidate. A copy that adds its own code still scores near 1.0 on it. Jaccard is the shared windows divided by all windows in either file, and it drops when the candidate carries a lot of extra code.

## The search script

One file on @solana/kit 8.6.0 and Node 24. Set `CARBIUM_KEY` before running it. The arguments are program ids and the first one is the reference. With no arguments it compares the two SPL token programs and the Memo program. `CARBIUM_RPC_URL` overrides the default endpoint, `https://services.carbium.sh`.

`main.ts` (run: `node main.ts`)

```ts
// SI0114 · Program bytecode similarity search
// https://carbium.sh/library/si/program-bytecode-similarity-search
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Program bytecode similarity search: fingerprint deployed programs and score a reference against each candidate.
// Run: CARBIUM_KEY=... node main.ts [reference-program candidate-program ...]
import { createHash } from "node:crypto";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const ids = process.argv.length > 2 ? process.argv.slice(2) : [
  "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
  "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",
];
const UPGRADEABLE = "BPFLoaderUpgradeab1e11111111111111111111111";

// The program's ELF bytes: via the program data account for the upgradeable loader, else the account itself.
async function read(id: string): Promise<Uint8Array> {
  const info = await rpc.getAccountInfo(address(id), { encoding: "base64", commitment: "confirmed" }).send();
  if (info.value === null) throw new Error("account not found");
  let data: Uint8Array = Buffer.from(info.value.data[0], "base64");
  if (String(info.value.owner) === UPGRADEABLE) {
    const pd = await rpc.getAccountInfo(getAddressDecoder().decode(data.subarray(4, 36)), { encoding: "base64", commitment: "confirmed" }).send();
    if (pd.value === null) throw new Error("program data account not found (program closed?)");
    data = Buffer.from(pd.value.data[0], "base64").subarray(45);
  }
  let end = data.length;
  while (end > 0 && data[end - 1] === 0) end--;
  return data.subarray(0, end);
}

// Rolling hash over 16-byte windows; a window is kept when its mixed hash falls in a fixed one-in-eight slice.
const K = 16;
const BASE = 0x01000193;
let pow = 1;
for (let i = 1; i < K; i++) pow = Math.imul(pow, BASE);
function fingerprint(data: Uint8Array): Set<number> {
  const kept = new Set<number>();
  let h = 0;
  for (let i = 0; i < data.length; i++) {
    if (i >= K) h = (h - Math.imul(data[i - K]!, pow)) | 0;
    h = (Math.imul(h, BASE) + data[i]!) | 0;
    const m = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d) >>> 0;
    if (i >= K - 1 && m >>> 29 === 0) kept.add(m);
  }
  return kept;
}

const loaded: { id: string; hash: string; fp: Set<number> }[] = [];
for (const id of ids) {
  try {
    const data = await read(id);
    const hash = createHash("sha256").update(data).digest("hex").slice(0, 12);
    const fp = fingerprint(data);
    loaded.push({ id, hash, fp });
    console.log(`${id.slice(0, 8)} | ${data.length} bytes | sha256 ${hash} | ${fp.size} windows kept`);
  } catch (e) {
    console.log(`${id.slice(0, 8)} | failed: ${(e as Error).message}`);
  }
}
const ref = loaded.find((p) => p.id === ids[0]);
if (!ref) {
  console.error("The reference program did not load.");
  process.exit(1);
}
for (const c of loaded) {
  if (c === ref) continue;
  let shared = 0;
  for (const m of ref.fp) if (c.fp.has(m)) shared++;
  const containment = shared / Math.max(ref.fp.size, 1);
  const jaccard = shared / Math.max(ref.fp.size + c.fp.size - shared, 1);
  console.log(`${ref.id.slice(0, 8)} in ${c.id.slice(0, 8)} | containment ${containment.toFixed(3)} | jaccard ${jaccard.toFixed(3)} | identical bytes: ${ref.hash === c.hash}`);
}
```

Each read is a `getAccountInfo` call with base64 encoding at confirmed commitment. Programs are read one after another, each in its own `try`, so a program that fails to load is named with its error and skipped while the rest still print.

Each loaded program gets a line with its size in bytes, the first 12 hex characters of its SHA-256 and the number of windows kept. Each candidate then gets a line with containment, Jaccard and whether its bytes equal the reference's. On mainnet the default run finds 0.120 of the token program's kept windows inside Token-2022 and 0.015 inside Memo. Token-2022 grew out of the token program's source, so 0.120 shows how far a heavily extended rebuild on a newer toolchain pulls the score down.

## Reading the scores

The bands below are starting points. Calibrate them on forks you already know before you act on a number.

| Result | Likely meaning |
|---|---|
| Identical bytes, containment 1.0 | The same build deployed twice, or one program read twice. |
| Containment above 0.9 | Same source with small edits, usually a new id and changed constants. |
| Containment 0.3 to 0.9 | A partial copy, or heavy shared library code. |
| Containment below 0.3 | Unrelated programs sharing runtime code, or a distant relative such as a fork rebuilt with another toolchain. Only your baseline tells them apart. |

Unrelated programs still share windows. Rust runtime routines, memory copy loops and common SDK code appear in nearly every deployed program, and two Anchor programs share the framework's dispatch code. Measure a baseline first: score the reference against a handful of programs you know are unrelated, and treat only what rises clearly above that as a signal.

For hundreds of candidates, keeping every full set gets heavy. Reduce each set to a MinHash signature of a few hundred numbers and bucket the signatures with locality-sensitive hashing. The candidates that land in a bucket with the reference are the ones worth a full comparison. A model with the program ids, the scores and the [IDL for each program](https://carbium.sh/library/blockchainideas/on-chain-idl-extractor) can then explain which differences matter. [Recent behavior of the same programs](https://carbium.sh/library/si/program-behavior-summary) gives it a second view.

## Cost of a comparison

`getAccountInfo` is an [account read](https://carbium.sh/docs/rpc) at 10 cells, and an upgradeable program takes two reads, so it costs 20 cells and a program on the older loader costs 10. A reference plus nine upgradeable candidates comes to 200 cells.

A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. On Free, Dev and Business that is 1,024 cells, about 50 upgradeable programs in one run. Longer lists wait on refill. Account reads refill at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro, and [limits](https://carbium.sh/docs/limits) are per account, so every key on the account draws from the same budget. Run big lists in batches and keep the fingerprints you have already computed.

Each read returns the whole program, which runs to hundreds of kilobytes or several megabytes, so a long list spends time on transfer as well as on cells. The fingerprint step holds one set per program in memory, about an eighth of the file size in entries.

## Where it ends

- A high score is a signal and proves nothing about intent. Programs built from the same framework share code, and a licensed fork is a copy too.
- A copier who rebuilds with another toolchain version or optimization level changes most windows while the logic stays the same. Scores fall, so compare the IDLs or the source when you have them.
- Candidate discovery is outside this search. A program scan such as `getProgramAccountsV2` is not served and answers [-32601](https://carbium.sh/docs/errors), so every comparison starts from a program id you already hold.
- The score describes the bytes at the moment of the read. An upgradeable program can change later, and its upgrade authority in the data account header says whether that is possible.
- A score cannot stop a deploy. It tells a person or an agent what a program resembles before they trust it or sign against it.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The run stops with 401 UNKNOWN_KEY. | Attach the whole key. Check that `CARBIUM_KEY` has no trailing space or newline from a copy. |
| A program line says account not found, or program data account not found. | The id is mistyped or the program was closed. A closed upgradeable program leaves nothing to read, so drop it from the list. |
| Unrelated programs score 0.3 or higher. | They share framework or runtime code. Score the reference against known unrelated programs first and only read what rises above that baseline. |
| A known fork scores close to zero. | It was probably rebuilt with another compiler version or heavily edited. Shorten the window to catch smaller shared runs, or compare IDLs and source instead. |
| A long candidate list starts answering 429. | Each upgradeable program costs 20 cells and below Pro a burst covers about 50. Split the list into batches, wait out the retry hint, and reuse fingerprints you have already stored. |

## Questions

### Can a program author block copies?

No. The bytes are public once deployed and anyone can deploy them again. Authors can publish a verified build for their own id and run a search like this one to spot look-alikes.

### Why not compare SHA-256 hashes only?

A program usually carries its own id inside the binary, so a copy that runs under a new address has those 32 bytes changed and hashes differently. The window fingerprints survive that 32-byte change and most small edits.

### Why a 16-byte window and one in eight kept?

Short windows survive small edits, and shorter ones start matching common instruction sequences in unrelated code. Keeping one in eight holds memory to about an eighth of the file size and still leaves thousands of windows even for a program as small as Memo.

### How do I give the scores to a model?

Pass the program ids, sizes and both scores in the prompt and ask for an answer that calls the result similarity and never proof of copying. Add the baseline you measured so it can tell a high score from a normal one.

## Related

- [On-chain IDL extractor](https://carbium.sh/library/blockchainideas/on-chain-idl-extractor) (Blockchain ideas, BI0049)
- [Program behavior summary](https://carbium.sh/library/si/program-behavior-summary) (AI and blockchain, SI0054)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
