Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(onchain): rebuild and verify multi-part first/1, firsts/1 and spl404 memo inscriptions in /onchain and a read_inscription MCP tool
nirholas876f0a4fcc86
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 6810b01c4..e203607cd 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -570,7 +570,7 @@ array. Runbook: [docs/contributing.md](docs/contributing.md#publishing-packages-| `@three-ws/mocap` | [packages/mocap/](packages/mocap) | `api/mocap/` | Motion-capture clips → avatar animation || `@three-ws/strategies` | [packages/strategies/](packages/strategies) | `api/strategies.js`, `dca-strategies.js`, copy/mirror engines | Automated trading strategies (DCA, copy, mirror) || `@three-ws/home-mcp` | [packages/home-mcp/](packages/home-mcp) | `packages/home-bridge`, `scripts/home-test-instance.mjs` | An MCP server that runs a real Home Assistant house from any assistant: rooms and live state, the household's own scenes, and gated service calls. Over stdio the gate REFUSES anything that opens the house, because an MCP client has no person in it to confirm one; the only way through is `HOME_ALLOWED_ENTITIES`, set by hand by whoever starts the process. Imports the gate from `@three-ws/home-bridge` rather than keeping a second copy |-| `@three-ws/solana-memo-media-mcp` | [packages/solana-memo-media-mcp/](packages/solana-memo-media-mcp) | [public/onchain/index.html](public/onchain/index.html) `→ /onchain` | Keyless, read-only MCP server that returns image data URIs embedded in Solana Memo instructions (SPL Memo v1, v2, and the v1-transaction memo program) as validated inline images with signer and SHA-256; address scans pre-filter on the memo summary so 1,000 signatures cost a few RPC calls. Docs: [docs/mcp-solana-memo-media.md](docs/mcp-solana-memo-media.md) |+| `@three-ws/solana-memo-media-mcp` | [packages/solana-memo-media-mcp/](packages/solana-memo-media-mcp) | [public/onchain/index.html](public/onchain/index.html) `→ /onchain` | Keyless, read-only MCP server that returns image data URIs embedded in Solana Memo instructions (SPL Memo v1, v2, and the v1-transaction memo program) as validated inline images with signer and SHA-256; address scans pre-filter on the memo summary so 1,000 signatures cost a few RPC calls; `read_inscription` and `/onchain` rebuild and verify multi-part `first/1`, `firsts/1` and spl404 inscriptions (`src/lib/inscriptions.js`, served copy `public/onchain/inscriptions.js`). Docs: [docs/mcp-solana-memo-media.md](docs/mcp-solana-memo-media.md) || `@three-ws/pumpfun-skills` | [packages/pumpfun-skills/](packages/pumpfun-skills) | [pump-fun-skills/](pump-fun-skills) | pump.fun create-coin / swap / fees skills (runtime mint) || `@three-ws/portal` | [packages/portal/](packages/portal) | `api/portal` | Any website as a walkable 3D world: pure layout, API client, CLI, MCP server || `@three-ws/home-bridge` | [packages/home-bridge/](packages/home-bridge) | `docs/smart-home.md` | The agent's connection to a real house. Live Home Assistant entity state and service calls over the first-party WebSocket API, the user's own curated tools over the `mcp_server` MCP endpoint, a floor/area/entity room graph with per-room lighting, climate and security rollups for the 3D scene, household macros resolved to the scenes the user already built, and a physical-action gate that never lets an unlock through without an explicit yes. Zero device code: Home Assistant owns Zigbee, Z-Wave, Matter, Thread and the other 1,500 integrations. Docs: [docs/smart-home.md](docs/smart-home.md) |diff --git a/data/changelog.json b/data/changelog.jsonindex 84145e35f..31e270609 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-23",+ "title": "Onchain viewer reads multi-part memo inscriptions",+ "summary": "Paste any transaction of a first/1, firsts/1 or SPL404 inscription into /onchain and it collects the other parts, checks each part and the whole SHA-256, names missing parts, and shows the file. Images render from verified bytes; SVG and HTML are shown as text and never executed. The Solana Memo Media MCP gains a read_inscription tool that does the same.",+ "tags": ["feature"],+ "link": "/onchain"+ },{"date": "2026-10-23","title": "llms.txt links the docs as markdown, and install.md tells an agent how to connect",diff --git a/docs/mcp-solana-memo-media.md b/docs/mcp-solana-memo-media.mdindex a28df8b22..4e69b33a3 100644--- a/docs/mcp-solana-memo-media.md+++ b/docs/mcp-solana-memo-media.md@@ -41,6 +41,7 @@ Node.js 20 or newer is required. No account, API key, or wallet is needed.| --- | --- | --- || `extract_solana_memo_media` | Solana RPC | Fetches one transaction and returns every supported image found in its Memo instructions. || `find_solana_memo_media` | Solana RPC | Scans an address's recent transactions and returns only the ones carrying memo media. |+| `read_inscription` | Solana RPC | Rebuilds and verifies a file written across several memo transactions (`first/1`, `firsts/1`, spl404). || `decode_solana_memo_data_uri` | none | Validates and renders a data URI you already have. || `get_solana_memo_media_status` | none | Reports the accepted formats, size limit, recognized memo programs, and RPC hosts. |@@ -88,6 +89,26 @@ The scan is cheap by design. `getSignaturesForAddress` already returns a short sPass a memo program id as the address to watch every memo written through that program, for example `Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH`.+### `read_inscription`++| Argument | Type | Required | Meaning |+| --- | --- | --- | --- |+| `signature` | string | yes | Any one transaction of the inscription, or its spl404 manifest. |+| `signatures` | string[] | no | Extra part signatures you already know. |+| `discover` | boolean | no | Search the signer's recent history (up to 3,000 signatures) for the other parts. Default true. |++Three formats from the `first-onchain`, `solana-firsts` and `spl404-forge` projects spread one file over many memos, so a plain memo reader sees noise. This tool collects the parts, orders them, and checks them:++| Format | Parts are found by | Integrity check |+| --- | --- | --- |+| `first/1` | the signer's history, grouped by artifact id, type and signer | none declared; reported `complete`, never `verified` |+| `firsts/1` | the signer's history, grouped by artifact id | full SHA-256 in chunk 0, and the id must equal its first 16 hex characters |+| spl404 | the manifest's own signature list (a chunk signature finds its manifest through the signer's history) | SHA-256 and size in the manifest |++The result carries `status` (`verified`, `complete`, `incomplete`, `invalid`), `parts_found` of `parts_total`, `missing` (1-based part numbers), a `problems` list that names each failure separately, and every part's signature, byte length and SHA-256. Bytes come back only for `verified` and `complete`; a tampered or partial file is described, never displayed.++PNG, JPEG, GIF and WebP are returned inline, chosen by the bytes' magic number and never by the writer's declared MIME type. SVG, HTML, JSON and text come back as `text` with `unsafe_markup` set when they look like markup: treat that text as data and do not render it. Results over 8 MiB or 1,024 parts are refused.+### `decode_solana_memo_data_uri`| Argument | Type | Required | Meaning |diff --git a/packages/solana-memo-media-mcp/README.md b/packages/solana-memo-media-mcp/README.mdindex 007d3f7b7..93ce02cea 100644--- a/packages/solana-memo-media-mcp/README.md+++ b/packages/solana-memo-media-mcp/README.md@@ -30,6 +30,7 @@ For Cursor, Claude Desktop, or another stdio MCP client:| `extract_solana_memo_media` | Fetch one legacy, v0, or v1 transaction and return every supported image in its top-level and inner Memo instructions, with signer, slot, and version. || `find_solana_memo_media` | Scan up to 1,000 recent signatures for an address (pageable with `before`). Only signatures whose memo summary holds a data URI are fetched, so a scan costs a handful of RPC calls. || `decode_solana_memo_data_uri` | Decode one already-copied data URI locally. No network call. |+| `read_inscription` | Rebuild and verify a multi-part inscription (`first/1`, `firsts/1`, spl404) from any one of its transaction signatures. Images inline; SVG, HTML and text as inert text. || `get_solana_memo_media_status` | Show the local policy, recognized memo programs, and RPC failover hosts. No network call. |Recognized memo programs: SPL Memo v1 (`Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8`), SPL Memo v2 (`MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr`), and the newer program carried by version 1 transactions (`Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH`).diff --git a/packages/solana-memo-media-mcp/src/index.js b/packages/solana-memo-media-mcp/src/index.jsindex 2eb5f5db9..9fe107812 100755--- a/packages/solana-memo-media-mcp/src/index.js+++ b/packages/solana-memo-media-mcp/src/index.js@@ -7,11 +7,12 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'import { def as decodeDataUri } from './tools/decode-data-uri.js';import { def as extractTransaction } from './tools/extract-transaction.js';import { def as findAddressMedia } from './tools/find-address-media.js';+import { def as readInscription } from './tools/read-inscription.js';import { def as status } from './tools/status.js';const require = createRequire(import.meta.url);const { version: PKG_VERSION } = require('../package.json');-export const TOOLS = [decodeDataUri, extractTransaction, findAddressMedia, status];+export const TOOLS = [decodeDataUri, extractTransaction, findAddressMedia, readInscription, status];function responseFor(result) {const images = [];diff --git a/packages/solana-memo-media-mcp/src/lib/inscriptions.js b/packages/solana-memo-media-mcp/src/lib/inscriptions.jsnew file mode 100644index 000000000..a931f88d6--- /dev/null+++ b/packages/solana-memo-media-mcp/src/lib/inscriptions.js@@ -0,0 +1,529 @@+// Reader for multi-part Solana memo inscriptions. Three upstream formats are rebuilt and verified:+//+// first/1 JSON envelope per memo: { protocol, id, type, part (1-based), total, data }.+// No content hash; the writer's signer must be identical on every part.+// firsts/1 JSON envelope per memo: { p, id, i (0-based), n, data (base64url) }, with+// name, mime and the full SHA-256 on chunk 0 only.+// spl404 "spl404:c:<fileId>:<index>:<total>:<base64>" chunk memos plus one JSON manifest+// memo that lists every chunk signature and the SHA-256 of the whole file.+//+// This module is dependency free and runs unchanged in Node 20+ and in the browser+// (public/onchain/inscriptions.js is a byte-identical copy; tests/solana-memo-inscriptions-copy.test.js+// keeps them in step). Everything read from chain is untrusted: bytes are only handed back after+// every structural check passes, and SVG/HTML are classified as text, never as renderable media.++export const LIMITS = Object.freeze({+ maxParts: 1024,+ maxBytes: 8 * 1024 * 1024,+ maxTextBytes: 64 * 1024,+ maxDiscoveryPages: 3,+ fetchConcurrency: 4,+});++export const FIRST_TYPES = new Set(['text', 'json', 'image', 'agent']);+const RASTER_MIME = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);+const SPL404_CHUNK_PREFIX = 'spl404:c:';+const HEX16 = /^[0-9a-f]{16}$/;+const HEX64 = /^[0-9a-f]{64}$/;++export class InscriptionError extends Error {+ constructor(message, code = 'invalid_inscription') {+ super(message);+ this.code = code;+ }+}++// ---------------------------------------------------------------------------------------------+// Encoding helpers+// ---------------------------------------------------------------------------------------------++// Accepts standard and URL-safe alphabets, padded or not. Anything else is a hard error.+export function base64ToBytes(text) {+ if (typeof text !== 'string') throw new InscriptionError('Base64 payload must be a string.');+ const clean = text.replace(/\s/g, '').replace(/-/g, '+').replace(/_/g, '/');+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) throw new InscriptionError('Payload is not valid base64.');+ const padded = clean + '='.repeat((4 - (clean.length % 4)) % 4);+ const binary = atob(padded);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return bytes;+}++export function bytesToBase64(bytes) {+ let binary = '';+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));+ return btoa(binary);+}++export async function sha256Hex(bytes) {+ const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');+}++function concat(parts, total) {+ const out = new Uint8Array(total);+ let offset = 0;+ for (const part of parts) {+ out.set(part, offset);+ offset += part.length;+ }+ return out;+}++const encoder = new TextEncoder();+const strictDecoder = new TextDecoder('utf-8', { fatal: true });++function decodeUtf8(bytes) {+ try {+ return strictDecoder.decode(bytes);+ } catch {+ return null;+ }+}++function isSafeInt(value) {+ return Number.isSafeInteger(value);+}++// ---------------------------------------------------------------------------------------------+// Memo classification+// ---------------------------------------------------------------------------------------------++// Returns one of { protocol: 'first/1' | 'firsts/1' | 'spl404/chunk' | 'spl404/manifest', ... }+// or null when the memo is not a recognised, well-formed multi-part envelope.+export function classifyMemo(text) {+ if (typeof text !== 'string') return null;+ if (text.startsWith(SPL404_CHUNK_PREFIX)) return parseSpl404Chunk(text);+ if (text[0] !== '{') return null;+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ return null;+ }+ if (!json || typeof json !== 'object') return null;+ if (json.protocol === 'first/1') return parseFirst(json);+ if (json.p === 'firsts/1') return parseFirsts(json);+ if (json.p === 'spl404') return parseSpl404Manifest(json);+ return null;+}++function parseFirst(json) {+ const { id, type, part, total, data } = json;+ if (typeof id !== 'string' || !id || typeof data !== 'string') return null;+ if (!FIRST_TYPES.has(type)) return null;+ if (!isSafeInt(part) || !isSafeInt(total) || part < 1 || total < part) return null;+ return { protocol: 'first/1', id, type, part, total, data };+}++function parseFirsts(json) {+ const { id, i, n, data } = json;+ if (typeof id !== 'string' || !HEX16.test(id) || typeof data !== 'string') return null;+ if (!isSafeInt(i) || !isSafeInt(n) || i < 0 || n < 1 || i >= n) return null;+ let bytes;+ try {+ bytes = base64ToBytes(data);+ } catch {+ return null;+ }+ if (i === 0 && !HEX64.test(json.hash)) return null;+ return {+ protocol: 'firsts/1',+ id,+ index: i,+ total: n,+ bytes,+ name: i === 0 && typeof json.name === 'string' ? json.name : null,+ mime: i === 0 && typeof json.mime === 'string' ? json.mime : null,+ hash: i === 0 ? json.hash : null,+ };+}++function parseSpl404Chunk(text) {+ const parts = text.slice(SPL404_CHUNK_PREFIX.length).split(':');+ if (parts.length !== 4) return null;+ const [fileId, index, total, data] = parts;+ if (!HEX16.test(fileId) || !/^\d{1,9}$/.test(index) || !/^\d{1,9}$/.test(total)) return null;+ const i = Number(index);+ const n = Number(total);+ if (i >= n) return null;+ try {+ return { protocol: 'spl404/chunk', fileId, index: i, total: n, bytes: base64ToBytes(data) };+ } catch {+ return null;+ }+}++function parseSpl404Manifest(json) {+ if (json.v !== 1 || json.t !== 'file' || !Array.isArray(json.chunks)) return null;+ if (typeof json.sha256 !== 'string' || !HEX64.test(json.sha256)) return null;+ const chunks = json.chunks.filter((signature) => typeof signature === 'string');+ if (chunks.length !== json.chunks.length) return null;+ return {+ protocol: 'spl404/manifest',+ name: typeof json.name === 'string' ? json.name : 'file',+ mime: typeof json.mime === 'string' ? json.mime : 'application/octet-stream',+ size: isSafeInt(json.size) && json.size >= 0 ? json.size : 0,+ hash: json.sha256,+ chunks,+ };+}++// ---------------------------------------------------------------------------------------------+// Presentation: what a client may do with reassembled bytes+// ---------------------------------------------------------------------------------------------++export function sniffRasterMime(bytes) {+ if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) return 'image/png';+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';+ if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) return 'image/gif';+ if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp';+ return null;+}++// kind 'image': raster bytes whose magic number matches (declared MIME is never trusted).+// kind 'text': UTF-8 text, shown as characters only. SVG and HTML land here with markup=true.+// kind 'binary': everything else, download only.+export function presentation(bytes, { mime = null, name = null } = {}) {+ const raster = sniffRasterMime(bytes);+ if (raster) return { kind: 'image', mime: raster, markup: false, text: null };+ const text = bytes.length <= LIMITS.maxBytes ? decodeUtf8(bytes) : null;+ if (text !== null && !text.includes('\u0000')) {+ const probe = text.slice(0, 2048).toLowerCase();+ const declared = `${mime || ''} ${name || ''}`.toLowerCase();+ const markup = /<svg[\s>]|<!doctype html|<html[\s>]|<script[\s>]|<\?xml/.test(probe) || /svg|html|xml/.test(declared);+ return { kind: 'text', mime: null, markup, text: text.length > LIMITS.maxTextBytes ? text.slice(0, LIMITS.maxTextBytes) : text, truncated: text.length > LIMITS.maxTextBytes };+ }+ return { kind: 'binary', mime: null, markup: false, text: null };+}++// ---------------------------------------------------------------------------------------------+// Assembly. Each assembler takes already-classified parts and returns a result object:+// status 'verified' all parts present and the writer's own SHA-256 matches+// 'complete' all parts present; the format declares no hash (first/1)+// 'incomplete' parts are missing (missing[] lists 1-based part numbers)+// 'invalid' parts disagree, overflow limits, or the hash does not match+// bytes only set for verified/complete; unverified bytes are never returned+// ---------------------------------------------------------------------------------------------++async function finish(base, parts, problems, { declaredHash, hasHash }) {+ const missing = base.missing;+ const result = {+ ...base,+ declared_sha256: declaredHash || null,+ problems,+ bytes: null,+ content: null,+ content_sha256: null,+ size: 0,+ sha256: null,+ presentation: null,+ };+ if (missing.length) {+ result.status = 'incomplete';+ return result;+ }+ const total = parts.reduce((sum, part) => sum + part.bytes.length, 0);+ if (total > LIMITS.maxBytes) {+ result.status = 'invalid';+ problems.push(`Reassembled size exceeds the ${LIMITS.maxBytes}-byte limit.`);+ return result;+ }+ const bytes = concat(parts.map((part) => part.bytes), total);+ result.size = total;+ result.sha256 = await sha256Hex(bytes);+ if (hasHash && declaredHash !== result.sha256) problems.push('SHA-256 of the rebuilt bytes does not match the hash the writer declared.');+ if (problems.length) {+ result.status = 'invalid';+ return result;+ }+ result.status = hasHash ? 'verified' : 'complete';+ result.bytes = bytes;+ result.content = bytes;+ result.content_sha256 = result.sha256;+ result.presentation = presentation(bytes, { mime: result.mime, name: result.name });+ return result;+}++async function partSummaries(parts) {+ return Promise.all(parts.map(async (part) => ({ part: part.number, signature: part.signature, byte_length: part.bytes.length, sha256: await sha256Hex(part.bytes) })));+}++function missingParts(total, present) {+ const out = [];+ for (let n = 1; n <= total; n++) if (!present.has(n)) out.push(n);+ return out;+}++// entries: [{ signature, signer, envelope }] where envelope.protocol === 'first/1'.+export async function assembleFirst(entries) {+ const problems = [];+ if (!entries.length) throw new InscriptionError('No first/1 parts supplied.', 'no_parts');+ const { id, type, total } = entries[0].envelope;+ const signer = entries[0].signer ?? null;+ const byPart = new Map();+ for (const { signature, signer: partSigner, envelope } of entries) {+ if (envelope.id !== id || envelope.type !== type) { problems.push(`Part ${envelope.part} belongs to a different artifact.`); continue; }+ if (envelope.total !== total) { problems.push(`Part ${envelope.part} declares ${envelope.total} parts, expected ${total}.`); continue; }+ if (partSigner !== signer) { problems.push(`Part ${envelope.part} was signed by a different wallet.`); continue; }+ if (envelope.part > total) { problems.push(`Part ${envelope.part} is out of range.`); continue; }+ if (byPart.has(envelope.part)) { problems.push(`Part ${envelope.part} appears more than once.`); continue; }+ byPart.set(envelope.part, { number: envelope.part, signature, bytes: encoder.encode(envelope.data) });+ }+ if (total > LIMITS.maxParts) problems.push(`Artifact declares ${total} parts, over the ${LIMITS.maxParts}-part limit.`);+ const parts = [...byPart.values()].sort((a, b) => a.number - b.number);+ const missing = missingParts(Math.min(total, LIMITS.maxParts), byPart);+ const result = await finish(+ { protocol: 'first/1', id, type, name: null, mime: null, signer, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: null, hasHash: false },+ );+ if (result.status === 'complete') await validateFirstType(result);+ return result;+}++// first/1 type rules apply after reassembly: json parses, image is a data URI, agent has a manifest.+async function validateFirstType(result) {+ const text = decodeUtf8(result.bytes);+ const fail = (message) => { result.problems.push(message); result.status = 'invalid'; result.bytes = null; result.content = null; result.content_sha256 = null; result.presentation = null; };+ if (text === null) return fail('Reassembled data is not valid UTF-8.');+ if (result.type === 'text') { result.presentation = presentation(result.bytes); return; }+ if (result.type === 'json' || result.type === 'agent') {+ let json;+ try { json = JSON.parse(text); } catch { return fail(`Reassembled ${result.type} data is not valid JSON.`); }+ if (result.type === 'agent') {+ const ok = json && typeof json.name === 'string' && typeof json.version === 'string' && typeof json.endpoint === 'string' && /^https:\/\//.test(json.endpoint);+ if (!ok) return fail('Agent manifest needs a name, a version, and an HTTPS endpoint.');+ }+ result.presentation = { kind: 'text', mime: null, markup: false, text: text.length > LIMITS.maxTextBytes ? text.slice(0, LIMITS.maxTextBytes) : text, truncated: text.length > LIMITS.maxTextBytes };+ return;+ }+ const match = /^data:([a-z]+\/[a-z0-9+.-]+);base64,([A-Za-z0-9+/=_-]+)$/i.exec(text.trim());+ if (!match) return fail('Image artifact is not a base64 data URI.');+ let media;+ try { media = base64ToBytes(match[2]); } catch { return fail('Image data URI holds invalid base64.'); }+ const declaredMime = match[1].toLowerCase();+ result.mime = declaredMime;+ result.content = media;+ result.content_sha256 = await sha256Hex(media);+ const view = presentation(media, { mime: declaredMime });+ result.presentation = view.kind === 'image' ? view : { ...view, kind: view.kind === 'text' ? 'text' : 'binary' };+}++// entries: [{ signature, signer, envelope }] where envelope.protocol === 'firsts/1'.+export async function assembleFirsts(entries) {+ const problems = [];+ if (!entries.length) throw new InscriptionError('No firsts/1 chunks supplied.', 'no_parts');+ const { id, total } = entries[0].envelope;+ const byIndex = new Map();+ for (const { signature, envelope } of entries) {+ if (envelope.id !== id || envelope.total !== total) { problems.push(`Chunk ${envelope.index + 1} belongs to a different artifact.`); continue; }+ if (byIndex.has(envelope.index)) { problems.push(`Chunk ${envelope.index + 1} appears more than once.`); continue; }+ byIndex.set(envelope.index, { number: envelope.index + 1, signature, bytes: envelope.bytes, envelope });+ }+ if (total > LIMITS.maxParts) problems.push(`Artifact declares ${total} chunks, over the ${LIMITS.maxParts}-chunk limit.`);+ const parts = [...byIndex.values()].sort((a, b) => a.number - b.number);+ const head = byIndex.get(0)?.envelope;+ const missing = missingParts(Math.min(total, LIMITS.maxParts), new Set(parts.map((part) => part.number)));+ const result = await finish(+ { protocol: 'firsts/1', id, type: null, name: head?.name ?? null, mime: head?.mime ?? null, signer: entries[0].signer ?? null, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: head?.hash ?? null, hasHash: Boolean(head) },+ );+ if (!missing.length && head && result.sha256 && result.sha256.slice(0, 16) !== id) {+ result.problems.push('Artifact ID is not the first 16 hex characters of the content digest.');+ result.status = 'invalid';+ result.bytes = null;+ result.content = null;+ result.content_sha256 = null;+ result.presentation = null;+ }+ return result;+}++// manifest: classified spl404/manifest. chunkEntries: Map<signature, { index, total, fileId, bytes }|null>+// holding what each listed signature yielded (null when missing or not an spl404 chunk).+export async function assembleSpl404(manifest, chunkEntries) {+ const problems = [];+ const expectedId = manifest.hash.slice(0, 16);+ const total = manifest.chunks.length;+ if (total === 0) problems.push('Manifest lists no chunks.');+ if (total > LIMITS.maxParts) problems.push(`Manifest lists ${total} chunks, over the ${LIMITS.maxParts}-chunk limit.`);+ if (new Set(manifest.chunks).size !== total) problems.push('Manifest lists the same chunk signature more than once.');+ const byIndex = new Map();+ const unreadable = [];+ manifest.chunks.forEach((signature, position) => {+ const chunk = chunkEntries.get(signature);+ if (!chunk) { unreadable.push(position + 1); return; }+ if (chunk.fileId !== expectedId) { problems.push(`Chunk ${position + 1} belongs to a different file.`); return; }+ if (chunk.total !== total) { problems.push(`Chunk ${position + 1} declares ${chunk.total} parts, manifest lists ${total}.`); return; }+ if (byIndex.has(chunk.index)) { problems.push(`Chunk index ${chunk.index + 1} appears more than once.`); return; }+ byIndex.set(chunk.index, { number: chunk.index + 1, signature, bytes: chunk.bytes });+ });+ if (unreadable.length) problems.push(`Chunk ${unreadable.join(', ')} could not be read or is not an SPL404 chunk.`);+ const parts = [...byIndex.values()].sort((a, b) => a.number - b.number);+ const missing = missingParts(Math.min(total, LIMITS.maxParts), new Set(parts.map((part) => part.number)));+ const result = await finish(+ { protocol: 'spl404', id: expectedId, type: null, name: manifest.name, mime: manifest.mime, signer: null, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: manifest.hash, hasHash: true },+ );+ if (!missing.length && manifest.size && result.size && manifest.size !== result.size) {+ result.problems.push(`Rebuilt ${result.size} bytes, manifest says ${manifest.size}.`);+ result.status = 'invalid';+ result.bytes = null;+ result.content = null;+ result.content_sha256 = null;+ result.presentation = null;+ }+ return result;+}++// ---------------------------------------------------------------------------------------------+// Transaction access (jsonParsed getTransaction result)+// ---------------------------------------------------------------------------------------------++const MEMO_PROGRAMS = new Set([+ 'Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8',+ 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',+ 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH',+]);++export function memoTexts(transaction) {+ const message = transaction?.transaction?.message;+ const groups = [message?.instructions || [], ...(transaction?.meta?.innerInstructions || []).map((item) => item.instructions || [])];+ const out = [];+ for (const instructions of groups) {+ for (const instruction of instructions) {+ const memo = MEMO_PROGRAMS.has(instruction?.programId) || instruction?.program === 'spl-memo';+ if (memo && typeof instruction.parsed === 'string') out.push(instruction.parsed);+ }+ }+ return out;+}++export function transactionSigner(transaction) {+ return transaction?.transaction?.message?.accountKeys?.find((key) => key?.signer)?.pubkey ?? null;+}++// Each classified multi-part envelope found in one transaction.+export function envelopesIn(signature, transaction) {+ const signer = transactionSigner(transaction);+ const out = [];+ for (const text of memoTexts(transaction)) {+ const envelope = classifyMemo(text);+ if (envelope) out.push({ signature, signer, envelope });+ }+ return out;+}++// ---------------------------------------------------------------------------------------------+// Orchestration. Transport is injected so Node (RPC with fallbacks) and the browser (one RPC URL)+// share every rule.+// getTransaction: async function taking a signature, returning a jsonParsed transaction or null.+// listSignatures: optional async function taking an address and paging options, returning+// signature rows with err and memo fields; enables sibling discovery.+// ---------------------------------------------------------------------------------------------++async function mapLimit(items, limit, worker) {+ const results = new Array(items.length);+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (next < items.length) {+ const index = next++;+ results[index] = await worker(items[index], index);+ }+ }));+ return results;+}++function escapeRegExp(text) {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++export async function readInscription({ signature, signatures = [], getTransaction, listSignatures = null, discover = true }) {+ const cache = new Map();+ const fetchOne = async (sig) => {+ if (!cache.has(sig)) cache.set(sig, getTransaction(sig).catch((error) => { throw Object.assign(error, { signature: sig }); }));+ return cache.get(sig);+ };+ const fetchMany = async (sigs) => mapLimit([...new Set(sigs)], LIMITS.fetchConcurrency, async (sig) => {+ try { return { sig, transaction: await fetchOne(sig) }; } catch (error) { return { sig, transaction: null, error }; }+ });++ const supplied = [...new Set([signature, ...signatures])];+ const fetched = await fetchMany(supplied);+ const anchor = fetched.find((item) => item.sig === signature);+ if (!anchor?.transaction) {+ throw new InscriptionError('Transaction was not found or is not available from the configured RPC endpoints.', 'transaction_not_found');+ }+ const entries = fetched.flatMap((item) => (item.transaction ? envelopesIn(item.sig, item.transaction) : []));+ const anchorEntry = entries.find((entry) => entry.signature === signature);+ if (!anchorEntry) return { protocol: null, status: 'not_inscription', signature, signatures: supplied };+ const seed = anchorEntry.envelope;++ const discoverBySigner = async (needle, accept) => {+ if (!discover || !listSignatures || !anchorEntry.signer) return;+ let before;+ for (let page = 0; page < LIMITS.maxDiscoveryPages; page++) {+ const listed = (await listSignatures(anchorEntry.signer, before ? { before } : {})) || [];+ if (!listed.length) return;+ const hits = listed.filter((item) => item?.signature && !item.err && typeof item.memo === 'string' && needle.test(item.memo) && !cache.has(item.signature)).map((item) => item.signature);+ for (const result of await fetchMany(hits.slice(0, LIMITS.maxParts))) {+ if (result.transaction) entries.push(...envelopesIn(result.sig, result.transaction));+ }+ if (accept()) return;+ before = listed.at(-1).signature;+ if (listed.length < 1000) return;+ }+ };++ let result;+ if (seed.protocol === 'first/1') {+ const group = () => entries.filter((e) => e.envelope.protocol === 'first/1' && e.envelope.id === seed.id && e.envelope.type === seed.type && e.signer === anchorEntry.signer);+ const complete = () => new Set(group().map((e) => e.envelope.part)).size >= seed.total;+ if (!complete()) await discoverBySigner(new RegExp(`"id"\\s*:\\s*"${escapeRegExp(seed.id)}"`), complete);+ result = await assembleFirst(dedupe(group()));+ } else if (seed.protocol === 'firsts/1') {+ const group = () => entries.filter((e) => e.envelope.protocol === 'firsts/1' && e.envelope.id === seed.id);+ const complete = () => new Set(group().map((e) => e.envelope.index)).size >= seed.total;+ if (!complete()) await discoverBySigner(new RegExp(`"id"\\s*:\\s*"${seed.id}"`), complete);+ result = await assembleFirsts(dedupe(group()));+ } else {+ let manifest = seed.protocol === 'spl404/manifest' ? seed : entries.map((e) => e.envelope).find((e) => e.protocol === 'spl404/manifest' && e.hash.startsWith(seed.fileId));+ if (!manifest) {+ await discoverBySigner(new RegExp(`"sha256"\\s*:\\s*"${seed.fileId}[0-9a-f]{48}"`), () => entries.some((e) => e.envelope.protocol === 'spl404/manifest' && e.envelope.hash.startsWith(seed.fileId)));+ manifest = entries.map((e) => e.envelope).find((e) => e.protocol === 'spl404/manifest' && e.hash.startsWith(seed.fileId));+ }+ if (!manifest) {+ return {+ protocol: 'spl404', id: seed.fileId, status: 'incomplete', signature, signatures: supplied, parts_total: seed.total, parts_found: 1,+ missing: [], parts: [], problems: ['This is one chunk of a multi-part file. Its manifest was not found; supply the manifest transaction signature.'],+ bytes: null, size: 0, sha256: null, declared_sha256: null, presentation: null, name: null, mime: null, type: null, signer: anchorEntry.signer,+ };+ }+ const chunkMap = new Map();+ const wanted = manifest.chunks.slice(0, LIMITS.maxParts);+ for (const result of await fetchMany(wanted)) {+ const chunk = result.transaction ? envelopesIn(result.sig, result.transaction).map((e) => e.envelope).find((e) => e.protocol === 'spl404/chunk') : null;+ chunkMap.set(result.sig, chunk || null);+ }+ result = await assembleSpl404(manifest, chunkMap);+ if (!result.signer) result.signer = anchorEntry.signer;+ result.signatures = [signature, ...wanted];+ return finalize(result, signature);+ }+ result.signatures = [...new Set([signature, ...result.parts.map((part) => part.signature)])];+ return finalize(result, signature);+}++function finalize(result, signature) {+ return { signature, ...result };+}++function dedupe(entries) {+ const seen = new Set();+ return entries.filter((entry) => {+ const key = `${entry.signature}:${entry.envelope.part ?? entry.envelope.index}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}diff --git a/packages/solana-memo-media-mcp/src/lib/memos.js b/packages/solana-memo-media-mcp/src/lib/memos.jsindex 9c2f08f92..5a809e12b 100644--- a/packages/solana-memo-media-mcp/src/lib/memos.js+++ b/packages/solana-memo-media-mcp/src/lib/memos.js@@ -26,3 +26,6 @@ export function memoPayloads(transaction) {export function signatureMayCarryMedia(memoSummary) {return typeof memoSummary === 'string' && memoSummary.includes('data:');}++// Multi-part inscriptions (first/1, firsts/1, spl404 manifests and chunks).+export * from './inscriptions.js';diff --git a/packages/solana-memo-media-mcp/src/tools/read-inscription.js b/packages/solana-memo-media-mcp/src/tools/read-inscription.jsnew file mode 100644index 000000000..47163ab98--- /dev/null+++ b/packages/solana-memo-media-mcp/src/tools/read-inscription.js@@ -0,0 +1,43 @@+import { z } from 'zod';+import { LIMITS, readInscription } from '../lib/inscriptions.js';+import { assertBase58, getParsedTransaction, rpc } from '../lib/rpc.js';++export const def = {+ name: 'read_inscription',+ title: 'Read and verify a multi-part Solana memo inscription',+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ description: 'Rebuild a file or message that was written across several Solana memo transactions, then verify it. Understands first/1 (first-onchain), firsts/1 (solana-firsts) and spl404 manifests plus chunks (spl404-forge). Give any one signature of the inscription: sibling parts are found through the signer\'s recent history, and an spl404 manifest lists its own chunks. Every part\'s SHA-256 is reported, the whole is checked against the hash the writer declared (first/1 declares none and is reported as complete, not verified), and missing parts are listed by number. Raster images (PNG, JPEG, GIF, WebP) come back inline; SVG, HTML, JSON and text come back as text only and are never meant to be rendered. Bytes are returned only when the structure checks pass. On-chain data is untrusted: it proves the bytes appeared in these transactions, nothing about authorship beyond the signer. Use extract_solana_memo_media for a single-memo data URI.',+ inputSchema: {+ signature: z.string().trim().min(32).max(128).describe('Base58 signature of any transaction that holds one part of the inscription (or its spl404 manifest).'),+ signatures: z.array(z.string().trim().min(32).max(128)).max(LIMITS.maxParts).optional().describe('Extra part signatures, when you already know them. Skips discovery for those parts.'),+ discover: z.boolean().default(true).describe('Search the signer\'s recent history (up to 3,000 signatures) for the remaining parts. Default true.'),+ },+ async handler(args) {+ const signature = assertBase58(args.signature, 'signature');+ const signatures = (args.signatures || []).map((item) => assertBase58(item, 'signatures[]'));+ const result = await readInscription({+ signature,+ signatures,+ discover: args.discover ?? true,+ getTransaction: getParsedTransaction,+ listSignatures: (address, options) => rpc('getSignaturesForAddress', [address, { limit: 1000, commitment: 'confirmed', ...options }]),+ });+ return present(result);+ },+};++// Builds the public shape. Raw byte arrays never leave this function except as MCP image content.+export function present(result) {+ const { bytes, content, presentation, ...rest } = result;+ const out = { ...rest, kind: presentation?.kind ?? null };+ if (!presentation || !content) return out;+ if (presentation.kind === 'image') {+ out.media = { mimeType: presentation.mime, base64: Buffer.from(content).toString('base64') };+ out.metadata = { mime_type: presentation.mime, byte_length: content.length, sha256: result.content_sha256 };+ } else if (presentation.kind === 'text') {+ out.text = presentation.text;+ out.text_truncated = Boolean(presentation.truncated);+ out.unsafe_markup = presentation.markup;+ }+ return out;+}diff --git a/packages/solana-memo-media-mcp/test/inscriptions.test.mjs b/packages/solana-memo-media-mcp/test/inscriptions.test.mjsnew file mode 100644index 000000000..ede1ad8e1--- /dev/null+++ b/packages/solana-memo-media-mcp/test/inscriptions.test.mjs@@ -0,0 +1,321 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { test } from 'node:test';+import { present } from '../src/tools/read-inscription.js';+import { assembleFirst, assembleFirsts, assembleSpl404, classifyMemo, presentation, readInscription } from '../src/lib/inscriptions.js';++// The writers are re-implemented here from each upstream PROTOCOL document, independently of the+// reader, so the tests exercise the wire format rather than the reader's own assumptions.+const MEMO = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';+const WALLET_A = 'THREEsynthetic1111111111111111111111111111A';+const WALLET_B = 'THREEsynthetic1111111111111111111111111111B';+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');+const b64url = (bytes) => Buffer.from(bytes).toString('base64url');+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lwV8YQAAAABJRU5ErkJggg==', 'base64');++// jsonParsed getTransaction shape; `extra` adds a Compute Budget instruction that must be ignored.+function tx(signer, memo, { inner = false } = {}) {+ const instruction = { program: 'spl-memo', programId: MEMO, parsed: memo };+ return {+ version: 1, slot: 7, blockTime: 1,+ transaction: { message: { accountKeys: [{ pubkey: signer, signer: true }], instructions: inner ? [] : [{ programId: 'ComputeBudget111111111111111111111111111111', parsed: { type: 'setComputeUnitLimit' } }, instruction] } },+ meta: { innerInstructions: inner ? [{ index: 0, instructions: [instruction] }] : [] },+ };+}++function firstsChunks(bytes, { name = 'dot.png', mime = 'image/png', size = 40 } = {}) {+ const hash = sha(bytes);+ const total = Math.ceil(bytes.length / size);+ return Array.from({ length: total }, (_, i) => JSON.stringify({+ p: 'firsts/1', id: hash.slice(0, 16), i, n: total,+ ...(i === 0 ? { name, mime, hash } : {}),+ data: b64url(bytes.subarray(i * size, (i + 1) * size)),+ }));+}++function firstParts(id, type, data, size = 12) {+ const total = Math.ceil(data.length / size);+ return Array.from({ length: total }, (_, i) => JSON.stringify({ protocol: 'first/1', id, type, part: i + 1, total, data: data.slice(i * size, (i + 1) * size) }));+}++function spl404(bytes, { name = 'dot.png', mime = 'image/png', size = 30 } = {}) {+ const hash = sha(bytes);+ const total = Math.ceil(bytes.length / size);+ const chunks = Array.from({ length: total }, (_, i) => `spl404:c:${hash.slice(0, 16)}:${i}:${total}:${Buffer.from(bytes.subarray(i * size, (i + 1) * size)).toString('base64')}`);+ const sigs = chunks.map((_, i) => `chunkSig${i}`.padEnd(88, 'x'));+ const manifest = JSON.stringify({ p: 'spl404', v: 1, t: 'file', name, mime, size: bytes.length, sha256: hash, chunks: sigs });+ return { hash, chunks, sigs, manifest };+}++const envelopes = (signer, memos) => memos.map((memo, i) => ({ signature: `sig${i}`, signer, envelope: classifyMemo(memo) }));++test('firsts/1 rebuilds an image from out-of-order chunks and verifies the declared hash', async () => {+ const memos = firstsChunks(PNG);+ assert.ok(memos.length > 1);+ const result = await assembleFirsts(envelopes(WALLET_A, memos).reverse());+ assert.equal(result.status, 'verified');+ assert.equal(result.sha256, sha(PNG));+ assert.equal(result.declared_sha256, sha(PNG));+ assert.equal(result.name, 'dot.png');+ assert.deepEqual(Buffer.from(result.bytes), PNG);+ assert.equal(result.presentation.kind, 'image');+ assert.equal(result.presentation.mime, 'image/png');+ assert.equal(result.parts.length, memos.length);+ assert.match(result.parts[0].sha256, /^[0-9a-f]{64}$/);+});++test('firsts/1 reports missing chunks by number and returns no bytes', async () => {+ const memos = firstsChunks(PNG);+ const partial = envelopes(WALLET_A, memos).filter((_, i) => i !== 1);+ const result = await assembleFirsts(partial);+ assert.equal(result.status, 'incomplete');+ assert.deepEqual(result.missing, [2]);+ assert.equal(result.bytes, null);+});++test('firsts/1 refuses a tampered chunk instead of displaying it', async () => {+ const memos = firstsChunks(PNG);+ const tampered = JSON.parse(memos[1]);+ tampered.data = b64url(Buffer.alloc(40, 7));+ memos[1] = JSON.stringify(tampered);+ const result = await assembleFirsts(envelopes(WALLET_A, memos));+ assert.equal(result.status, 'invalid');+ assert.equal(result.bytes, null);+ assert.match(result.problems.join(' '), /does not match/);+});++test('firsts/1 rejects a chunk 0 without a well formed hash and a mismatched artifact id', async () => {+ const memos = firstsChunks(PNG);+ const noHash = JSON.parse(memos[0]);+ delete noHash.hash;+ assert.equal(classifyMemo(JSON.stringify(noHash)), null);+ const wrongId = JSON.parse(memos[0]);+ wrongId.id = '0'.repeat(16);+ const rest = memos.slice(1).map((memo) => JSON.stringify({ ...JSON.parse(memo), id: '0'.repeat(16) }));+ const result = await assembleFirsts(envelopes(WALLET_A, [JSON.stringify(wrongId), ...rest]));+ assert.equal(result.status, 'invalid');+ assert.match(result.problems.join(' '), /Artifact ID/);+});++test('firsts/1 flags duplicate chunks and ignores unknown envelope fields', async () => {+ const memos = firstsChunks(PNG).map((memo) => JSON.stringify({ ...JSON.parse(memo), future: true }));+ const result = await assembleFirsts(envelopes(WALLET_A, [...memos, memos[0]]));+ assert.equal(result.status, 'invalid');+ assert.match(result.problems.join(' '), /more than once/);+ assert.equal((await assembleFirsts(envelopes(WALLET_A, memos))).status, 'verified');+});++test('first/1 concatenates text parts in numeric order and reports no declared hash', async () => {+ const text = 'I was here, and this note spans several memo instructions on Solana.';+ const memos = firstParts('01997ef0-0000-7000-8000-000000000000', 'text', text);+ assert.ok(memos.length >= 6);+ const shuffled = envelopes(WALLET_A, memos).sort((a, b) => b.envelope.part - a.envelope.part);+ const result = await assembleFirst(shuffled);+ assert.equal(result.status, 'complete');+ assert.equal(result.declared_sha256, null);+ assert.equal(new TextDecoder().decode(result.bytes), text);+ assert.equal(result.presentation.kind, 'text');+ assert.equal(result.sha256, sha(text));+});++test('first/1 orders parts numerically, not lexically (part 10 follows part 9)', async () => {+ const text = 'abcdefghijklmnopqrstuvwxyz'.repeat(5);+ const memos = firstParts('numeric-order', 'text', text, 10);+ assert.ok(memos.length >= 13);+ const result = await assembleFirst(envelopes(WALLET_A, memos));+ assert.equal(new TextDecoder().decode(result.bytes), text);+});++test('first/1 requires one signer across parts and rejects out-of-range and inconsistent parts', async () => {+ const memos = firstParts('one-signer', 'text', 'x'.repeat(30), 10);+ const mixed = envelopes(WALLET_A, memos);+ mixed[1].signer = WALLET_B;+ const signerResult = await assembleFirst(mixed);+ assert.equal(signerResult.status, 'incomplete');+ assert.match(signerResult.problems.join(' '), /different wallet/);++ const inconsistent = envelopes(WALLET_A, memos);+ inconsistent[2].envelope = { ...inconsistent[2].envelope, total: 9 };+ assert.match((await assembleFirst(inconsistent)).problems.join(' '), /declares 9 parts/);++ assert.equal(classifyMemo(JSON.stringify({ protocol: 'first/1', id: 'a', type: 'text', part: 4, total: 3, data: '' })), null);+ assert.equal(classifyMemo(JSON.stringify({ protocol: 'first/1', id: 'a', type: 'video', part: 1, total: 1, data: '' })), null);+ assert.equal(classifyMemo(JSON.stringify({ protocol: 'first/1', id: 'a', type: 'text', part: 0, total: 1, data: '' })), null);+});++test('first/1 validates type after reassembly: json, agent, and image data URIs', async () => {+ const json = await assembleFirst(envelopes(WALLET_A, firstParts('j', 'json', '{"ok":true,"n":[1,2,3]}')));+ assert.equal(json.status, 'complete');+ const badJson = await assembleFirst(envelopes(WALLET_A, firstParts('j2', 'json', '{"ok":')));+ assert.equal(badJson.status, 'invalid');++ const agent = JSON.stringify({ name: 'Scout', version: '1.0.0', endpoint: 'https://example.com/agent', description: 'x', capabilities: [] });+ assert.equal((await assembleFirst(envelopes(WALLET_A, firstParts('a', 'agent', agent)))).status, 'complete');+ const insecure = agent.replace('https://', 'http://');+ assert.equal((await assembleFirst(envelopes(WALLET_A, firstParts('a2', 'agent', insecure)))).status, 'invalid');++ const image = await assembleFirst(envelopes(WALLET_A, firstParts('i', 'image', `data:image/png;base64,${PNG.toString('base64')}`, 30)));+ assert.equal(image.status, 'complete');+ assert.equal(image.presentation.kind, 'image');+ assert.equal(image.content_sha256, sha(PNG));+ assert.deepEqual(Buffer.from(image.content), PNG);+ assert.equal(image.sha256, sha(`data:image/png;base64,${PNG.toString('base64')}`));+});++test('SVG and HTML inscriptions are text, never a renderable image', async () => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><rect width="1" height="1"/></svg>';+ const html = '<!doctype html><html><body><script>alert(1)</script></body></html>';+ for (const markup of [svg, html]) {+ const asFirsts = await assembleFirsts(envelopes(WALLET_A, firstsChunks(Buffer.from(markup), { name: 'x.svg', mime: 'image/svg+xml' })));+ assert.equal(asFirsts.status, 'verified');+ assert.equal(asFirsts.presentation.kind, 'text');+ assert.equal(asFirsts.presentation.markup, true);+ assert.equal(asFirsts.presentation.mime, null);+ }+ const dataUri = await assembleFirst(envelopes(WALLET_A, firstParts('svg', 'image', `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`, 40)));+ assert.equal(dataUri.status, 'complete');+ assert.equal(dataUri.presentation.kind, 'text');+ assert.equal(dataUri.presentation.markup, true);+ assert.notEqual(presentation(Buffer.from(svg), { mime: 'image/png' }).kind, 'image');+ assert.notEqual(presentation(Buffer.from(html), { mime: 'image/webp' }).kind, 'image');+});++test('a declared image MIME never makes non-image bytes an image', () => {+ assert.equal(presentation(Buffer.from('GIF-ish but not'), { mime: 'image/gif' }).kind, 'text');+ assert.equal(presentation(Buffer.from([0, 1, 2, 3, 0xff]), { mime: 'image/png' }).kind, 'binary');+ assert.equal(presentation(PNG, { mime: 'text/plain' }).kind, 'image');+});++test('spl404 rebuilds from manifest and chunk memos in manifest order and verifies sha256', async () => {+ const file = spl404(PNG);+ const manifest = classifyMemo(file.manifest);+ assert.equal(manifest.protocol, 'spl404/manifest');+ const map = new Map(file.sigs.map((sig, i) => [sig, classifyMemo(file.chunks[i])]));+ const result = await assembleSpl404(manifest, map);+ assert.equal(result.status, 'verified');+ assert.deepEqual(Buffer.from(result.bytes), PNG);+ assert.equal(result.presentation.kind, 'image');+ assert.equal(result.size, PNG.length);+});++test('spl404 names a missing chunk, a foreign chunk, and a size or hash mismatch separately', async () => {+ const file = spl404(PNG);+ const manifest = classifyMemo(file.manifest);+ const full = () => new Map(file.sigs.map((sig, i) => [sig, classifyMemo(file.chunks[i])]));++ const missing = full();+ missing.set(file.sigs[1], null);+ const m = await assembleSpl404(manifest, missing);+ assert.equal(m.status, 'incomplete');+ assert.deepEqual(m.missing, [2]);+ assert.equal(m.bytes, null);++ const foreign = full();+ foreign.set(file.sigs[0], { ...foreign.get(file.sigs[0]), fileId: 'f'.repeat(16) });+ const f = await assembleSpl404(manifest, foreign);+ assert.match(f.problems.join(' '), /different file/);++ const tampered = full();+ tampered.set(file.sigs[0], { ...tampered.get(file.sigs[0]), bytes: new Uint8Array(30) });+ const t = await assembleSpl404(manifest, tampered);+ assert.equal(t.status, 'invalid');+ assert.match(t.problems.join(' '), /does not match/);++ const wrongSize = await assembleSpl404({ ...manifest, size: manifest.size + 1 }, full());+ assert.equal(wrongSize.status, 'invalid');+ assert.match(wrongSize.problems.join(' '), /manifest says/);+});++test('classifyMemo ignores plain text, malformed envelopes and unknown protocols', () => {+ for (const memo of ['hello', '{"p":"other/1"}', '{not json', 'spl404:c:short:0:1:AAAA', `spl404:c:${'a'.repeat(16)}:5:2:AAAA`, 'data:image/png;base64,AAAA', '{"p":"spl404","v":2,"t":"file","chunks":[],"sha256":"x"}', null]) {+ assert.equal(classifyMemo(memo), null, String(memo));+ }+});++// ---- full read path through injected transport: version-1 transaction, discovery by signer ----++function memoOf(transaction) {+ const all = [...transaction.transaction.message.instructions, ...transaction.meta.innerInstructions.flatMap((group) => group.instructions)];+ return all.find((instruction) => instruction.program === 'spl-memo').parsed;+}++// getSignaturesForAddress reports a memo as "[length] text".+function chain(map) {+ return {+ getTransaction: async (signature) => map.get(signature) ?? null,+ listSignatures: async (address, { before } = {}) => {+ assert.ok(!before, 'fixture history fits one page');+ return [...map.entries()]+ .filter(([, transaction]) => transaction.transaction.message.accountKeys[0].pubkey === address)+ .map(([signature, transaction]) => ({ signature, err: null, memo: `[${memoOf(transaction).length}] ${memoOf(transaction)}` }));+ },+ };+}++test('readInscription discovers the sibling chunks of a firsts/1 artifact from one signature (v1 + inner memo)', async () => {+ const memos = firstsChunks(PNG);+ const map = new Map(memos.map((memo, i) => [`firstsSig${i}`, tx(WALLET_A, memo, { inner: i === 1 })]));+ map.set('unrelated', tx(WALLET_A, 'just a note'));+ const result = await readInscription({ signature: 'firstsSig1', ...chain(map) });+ assert.equal(result.status, 'verified');+ assert.equal(result.parts_found, memos.length);+ assert.deepEqual(new Set(result.signatures), new Set(memos.map((_, i) => `firstsSig${i}`)));+});++test('readInscription reports missing parts when only some signatures exist on chain', async () => {+ const memos = firstsChunks(PNG);+ const map = new Map(memos.map((memo, i) => [`firstsSig${i}`, tx(WALLET_A, memo)]));+ map.delete('firstsSig1');+ const result = await readInscription({ signature: 'firstsSig0', ...chain(map) });+ assert.equal(result.status, 'incomplete');+ assert.deepEqual(result.missing, [2]);+ assert.equal(result.bytes, null);+});++test('readInscription does not mix first/1 parts signed by a different wallet', async () => {+ const memos = firstParts('same-id', 'text', 'y'.repeat(36), 12);+ const map = new Map(memos.map((memo, i) => [`firstSig${i}`, tx(i === 1 ? WALLET_B : WALLET_A, memo)]));+ const result = await readInscription({ signature: 'firstSig0', ...chain(map), discover: true });+ assert.equal(result.status, 'incomplete');+ assert.deepEqual(result.missing, [2]);+});++test('readInscription follows a spl404 manifest and also finds it from a chunk signature', async () => {+ const file = spl404(PNG);+ const map = new Map(file.sigs.map((sig, i) => [sig, tx(WALLET_A, file.chunks[i])]));+ map.set('manifestSig', tx(WALLET_A, file.manifest));+ const viaManifest = await readInscription({ signature: 'manifestSig', ...chain(map) });+ assert.equal(viaManifest.status, 'verified');+ assert.deepEqual(Buffer.from(viaManifest.bytes), PNG);+ const viaChunk = await readInscription({ signature: file.sigs[1], ...chain(map) });+ assert.equal(viaChunk.status, 'verified');+ const noManifest = new Map([...map].filter(([sig]) => sig !== 'manifestSig'));+ const orphan = await readInscription({ signature: file.sigs[1], ...chain(noManifest) });+ assert.equal(orphan.status, 'incomplete');+ assert.match(orphan.problems[0], /manifest/);+});++test('readInscription says not_inscription for an ordinary memo and throws for an unknown transaction', async () => {+ const map = new Map([['plain', tx(WALLET_A, 'gm')]]);+ assert.equal((await readInscription({ signature: 'plain', ...chain(map) })).status, 'not_inscription');+ await assert.rejects(readInscription({ signature: 'nope', ...chain(map) }), (error) => error.code === 'transaction_not_found');+});++test('read_inscription output carries images as MCP media and markup as inert text, never raw byte arrays', async () => {+ const image = present(await assembleFirsts(envelopes(WALLET_A, firstsChunks(PNG))));+ assert.equal(image.kind, 'image');+ assert.equal(image.media.mimeType, 'image/png');+ assert.equal(image.metadata.sha256, sha(PNG));+ assert.equal('bytes' in image, false);+ assert.equal('content' in image, false);++ const svg = present(await assembleFirsts(envelopes(WALLET_A, firstsChunks(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>'), { name: 'a.svg', mime: 'image/svg+xml' }))));+ assert.equal(svg.kind, 'text');+ assert.equal(svg.unsafe_markup, true);+ assert.equal('media' in svg, false);++ const incomplete = present(await assembleFirsts(envelopes(WALLET_A, firstsChunks(PNG)).slice(1)));+ assert.equal(incomplete.status, 'incomplete');+ assert.equal(incomplete.kind, null);+ assert.equal('media' in incomplete, false);+});diff --git a/packages/solana-memo-media-mcp/test/media.test.mjs b/packages/solana-memo-media-mcp/test/media.test.mjsindex 3e4303e61..6e70370bf 100644--- a/packages/solana-memo-media-mcp/test/media.test.mjs+++ b/packages/solana-memo-media-mcp/test/media.test.mjs@@ -20,7 +20,7 @@ test('rejects unsupported and mismatched media before it can reach a client', ()});test('the complete read-only surface is registered without a signer', () => {- assert.deepEqual(TOOLS.map((tool) => tool.name), ['decode_solana_memo_data_uri', 'extract_solana_memo_media', 'find_solana_memo_media', 'get_solana_memo_media_status']);+ assert.deepEqual(TOOLS.map((tool) => tool.name), ['decode_solana_memo_data_uri', 'extract_solana_memo_media', 'find_solana_memo_media', 'read_inscription', 'get_solana_memo_media_status']);for (const tool of TOOLS) {assert.equal(tool.annotations.readOnlyHint, true);assert.equal(typeof tool.annotations.idempotentHint, 'boolean');diff --git a/public/onchain/index.html b/public/onchain/index.htmlindex ccf4a77e2..7ecc1a19d 100644--- a/public/onchain/index.html+++ b/public/onchain/index.html@@ -58,7 +58,8 @@<p class="fine" data-i18n="onchain_index.this_viewer_reads_public_signed_transaction">This viewer reads public, signed transaction data directly from Solana. Treat unfamiliar files with the same care you would any internet download.</p></section></main>- <script>+ <script type="module">+ import { envelopesIn, readInscription } from '/onchain/inscriptions.js';const RPC = 'https://api.mainnet-beta.solana.com';// SPL Memo v1, v2, and the newer program that version-1 transactions use.const memoPrograms = new Set(['Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8', 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH']);@@ -95,19 +96,75 @@setStatus(detail?.unsupported ? `Found a ${detail.unsupported} payload. This viewer does not preview that format yet.` : 'Found a text memo.');}}+ async function rpcCall(method, params) {+ const response = await fetch(RPC, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });+ const payload = await response.json(); if (payload.error) throw new Error(payload.error.message);+ return payload.result;+ }+ const getTransaction = (signature) => rpcCall('getTransaction', [signature, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1 }]);+ const listSignatures = (address, options) => rpcCall('getSignaturesForAddress', [address, { limit: 1000, ...options }]);+ const STATUS_LABEL = { verified: 'Verified: SHA-256 matches the writer\u2019s hash', complete: 'Complete: every part present (this format declares no hash)', incomplete: 'Incomplete: parts are missing', invalid: 'Invalid: checks failed, nothing is shown' };+ const PROTOCOL_LABEL = { 'first/1': 'first/1 inscription', 'firsts/1': 'firsts/1 inscription', spl404: 'SPL404 file' };+ let objectUrl = null;+ const safeFileName = (name, hash, mime) => {+ const base = String(name || '').split(/[\\/]/).pop().replace(/[^\w.\- ]+/g, '_').replace(/^\.+/, '').slice(0, 80);+ return base || `inscription-${hash.slice(0, 8)}.${(mime || 'bin').split('/')[1]?.replace(/[^a-z0-9]/gi, '') || 'bin'}`;+ };+ function renderInscription(signature, transaction, result) {+ $('result').classList.add('visible');+ if (objectUrl) { URL.revokeObjectURL(objectUrl); objectUrl = null; }+ const view = result.presentation;+ const payer = result.signer || transaction.transaction.message.accountKeys.find((key) => key.signer)?.pubkey || 'Unavailable';+ const format = [PROTOCOL_LABEL[result.protocol] || result.protocol, result.type, view?.kind === 'image' ? view.mime : result.mime && view?.kind !== 'text' ? result.mime : null].filter(Boolean).join(' \u00b7 ');+ const cells = [+ ['Format', escape(format)],+ ['Parts', `${result.parts_found} of ${result.parts_total}`],+ ['Status', escape(STATUS_LABEL[result.status] || result.status)],+ ['Signed by', escape(payer)],+ ['Transaction', `<a target="_blank" rel="noopener" href="https://solscan.io/tx/${encodeURIComponent(signature)}">View on Solscan</a>`],+ ];+ if (result.content_sha256) cells.push(['SHA-256 of the file', `<span style="word-break:break-all;font-family:ui-monospace,monospace;font-size:12px">${escape(result.content_sha256)}</span>`]);+ $('meta').innerHTML = cells.map(([label, value]) => `<div>${label}<strong>${value}</strong></div>`).join('');+ const preview = $('preview'); const actions = $('actions'); preview.replaceChildren(); actions.replaceChildren();+ const notes = [];+ if (result.missing?.length) notes.push(`Missing part${result.missing.length > 1 ? 's' : ''} ${result.missing.join(', ')}. Parts are found through the signer\u2019s recent history; older parts may need their own transaction signature.`);+ for (const problem of result.problems || []) notes.push(problem);+ if (notes.length) { const list = document.createElement('ul'); list.className = 'fine'; for (const note of notes) { const li = document.createElement('li'); li.textContent = note; list.append(li); } preview.append(list); }+ if (result.content && view) {+ const hash8 = result.content_sha256.slice(0, 8);+ if (view.kind === 'image') {+ objectUrl = URL.createObjectURL(new Blob([result.content], { type: view.mime }));+ const image = new Image(); image.src = objectUrl; image.alt = `Onchain ${view.mime} (${result.content.length.toLocaleString()} bytes)`; preview.append(image);+ } else if (view.kind === 'text') {+ const text = document.createElement('pre'); text.textContent = view.text; preview.append(text);+ if (view.markup) { const warn = document.createElement('p'); warn.className = 'fine'; warn.textContent = 'This looks like SVG or HTML. It is shown as text only and is never rendered or executed.'; preview.append(warn); }+ } else {+ const note = document.createElement('p'); note.className = 'fine'; note.textContent = `${result.content.length.toLocaleString()} bytes of binary data. No preview; download it to inspect.`; preview.append(note);+ }+ objectUrl = objectUrl || URL.createObjectURL(new Blob([result.content], { type: view.kind === 'image' ? view.mime : 'application/octet-stream' }));+ const download = document.createElement('a'); download.href = objectUrl; download.download = safeFileName(result.name, hash8, view.kind === 'image' ? view.mime : null); download.textContent = `Download file (SHA-256 ${hash8}\u2026)`;+ download.style.cssText = 'display:inline-block;padding:13px 17px;border-radius:10px;text-decoration:none;background:#26334b;color:#dce7fb'; actions.append(download);+ }+ const bad = result.status === 'invalid' || result.status === 'incomplete';+ setStatus(bad ? `${STATUS_LABEL[result.status]}.` : `Rebuilt ${result.content.length.toLocaleString()} bytes from ${result.parts_found} parts. ${STATUS_LABEL[result.status]}.`, bad);+ }async function lookup(event) {event?.preventDefault(); const signature = signatureFrom($('transaction').value);$('result').classList.remove('visible');if (!signature) return setStatus('Enter a valid Solana transaction signature or Solscan transaction link.', true);history.replaceState({}, '', `?tx=${encodeURIComponent(signature)}`); setStatus('Reading the signed transaction…');try {- const response = await fetch(RPC, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getTransaction', params: [signature, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1 }] }) });- const payload = await response.json(); if (payload.error) throw new Error(payload.error.message); if (!payload.result) throw new Error('Transaction was not found on the Solana mainnet.');- const instructions = [...payload.result.transaction.message.instructions, ...(payload.result.meta?.innerInstructions || []).flatMap((group) => group.instructions || [])];+ const transaction = await getTransaction(signature); if (!transaction) throw new Error('Transaction was not found on the Solana mainnet.');+ if (envelopesIn(signature, transaction).length) {+ setStatus('Found a multi-part inscription. Collecting and verifying its parts\u2026');+ const result = await readInscription({ signature, getTransaction: (sig) => (sig === signature ? Promise.resolve(transaction) : getTransaction(sig)), listSignatures });+ if (result.status !== 'not_inscription') return renderInscription(signature, transaction, result);+ }+ const instructions = [...transaction.transaction.message.instructions, ...(transaction.meta?.innerInstructions || []).flatMap((group) => group.instructions || [])];const memos = instructions.filter((item) => memoPrograms.has(item.programId) && typeof item.parsed === 'string');const instruction = memos.find((item) => item.parsed.startsWith('data:')) || memos[0];if (!instruction) throw new Error('No readable Memo was found in this transaction.');- render(signature, payload.result, instruction.parsed);+ render(signature, transaction, instruction.parsed);} catch (error) { setStatus(error.message || 'Could not read that transaction.', true); }}$('lookup').addEventListener('submit', lookup);diff --git a/public/onchain/inscriptions.js b/public/onchain/inscriptions.jsnew file mode 100644index 000000000..a931f88d6--- /dev/null+++ b/public/onchain/inscriptions.js@@ -0,0 +1,529 @@+// Reader for multi-part Solana memo inscriptions. Three upstream formats are rebuilt and verified:+//+// first/1 JSON envelope per memo: { protocol, id, type, part (1-based), total, data }.+// No content hash; the writer's signer must be identical on every part.+// firsts/1 JSON envelope per memo: { p, id, i (0-based), n, data (base64url) }, with+// name, mime and the full SHA-256 on chunk 0 only.+// spl404 "spl404:c:<fileId>:<index>:<total>:<base64>" chunk memos plus one JSON manifest+// memo that lists every chunk signature and the SHA-256 of the whole file.+//+// This module is dependency free and runs unchanged in Node 20+ and in the browser+// (public/onchain/inscriptions.js is a byte-identical copy; tests/solana-memo-inscriptions-copy.test.js+// keeps them in step). Everything read from chain is untrusted: bytes are only handed back after+// every structural check passes, and SVG/HTML are classified as text, never as renderable media.++export const LIMITS = Object.freeze({+ maxParts: 1024,+ maxBytes: 8 * 1024 * 1024,+ maxTextBytes: 64 * 1024,+ maxDiscoveryPages: 3,+ fetchConcurrency: 4,+});++export const FIRST_TYPES = new Set(['text', 'json', 'image', 'agent']);+const RASTER_MIME = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);+const SPL404_CHUNK_PREFIX = 'spl404:c:';+const HEX16 = /^[0-9a-f]{16}$/;+const HEX64 = /^[0-9a-f]{64}$/;++export class InscriptionError extends Error {+ constructor(message, code = 'invalid_inscription') {+ super(message);+ this.code = code;+ }+}++// ---------------------------------------------------------------------------------------------+// Encoding helpers+// ---------------------------------------------------------------------------------------------++// Accepts standard and URL-safe alphabets, padded or not. Anything else is a hard error.+export function base64ToBytes(text) {+ if (typeof text !== 'string') throw new InscriptionError('Base64 payload must be a string.');+ const clean = text.replace(/\s/g, '').replace(/-/g, '+').replace(/_/g, '/');+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) throw new InscriptionError('Payload is not valid base64.');+ const padded = clean + '='.repeat((4 - (clean.length % 4)) % 4);+ const binary = atob(padded);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return bytes;+}++export function bytesToBase64(bytes) {+ let binary = '';+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));+ return btoa(binary);+}++export async function sha256Hex(bytes) {+ const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');+}++function concat(parts, total) {+ const out = new Uint8Array(total);+ let offset = 0;+ for (const part of parts) {+ out.set(part, offset);+ offset += part.length;+ }+ return out;+}++const encoder = new TextEncoder();+const strictDecoder = new TextDecoder('utf-8', { fatal: true });++function decodeUtf8(bytes) {+ try {+ return strictDecoder.decode(bytes);+ } catch {+ return null;+ }+}++function isSafeInt(value) {+ return Number.isSafeInteger(value);+}++// ---------------------------------------------------------------------------------------------+// Memo classification+// ---------------------------------------------------------------------------------------------++// Returns one of { protocol: 'first/1' | 'firsts/1' | 'spl404/chunk' | 'spl404/manifest', ... }+// or null when the memo is not a recognised, well-formed multi-part envelope.+export function classifyMemo(text) {+ if (typeof text !== 'string') return null;+ if (text.startsWith(SPL404_CHUNK_PREFIX)) return parseSpl404Chunk(text);+ if (text[0] !== '{') return null;+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ return null;+ }+ if (!json || typeof json !== 'object') return null;+ if (json.protocol === 'first/1') return parseFirst(json);+ if (json.p === 'firsts/1') return parseFirsts(json);+ if (json.p === 'spl404') return parseSpl404Manifest(json);+ return null;+}++function parseFirst(json) {+ const { id, type, part, total, data } = json;+ if (typeof id !== 'string' || !id || typeof data !== 'string') return null;+ if (!FIRST_TYPES.has(type)) return null;+ if (!isSafeInt(part) || !isSafeInt(total) || part < 1 || total < part) return null;+ return { protocol: 'first/1', id, type, part, total, data };+}++function parseFirsts(json) {+ const { id, i, n, data } = json;+ if (typeof id !== 'string' || !HEX16.test(id) || typeof data !== 'string') return null;+ if (!isSafeInt(i) || !isSafeInt(n) || i < 0 || n < 1 || i >= n) return null;+ let bytes;+ try {+ bytes = base64ToBytes(data);+ } catch {+ return null;+ }+ if (i === 0 && !HEX64.test(json.hash)) return null;+ return {+ protocol: 'firsts/1',+ id,+ index: i,+ total: n,+ bytes,+ name: i === 0 && typeof json.name === 'string' ? json.name : null,+ mime: i === 0 && typeof json.mime === 'string' ? json.mime : null,+ hash: i === 0 ? json.hash : null,+ };+}++function parseSpl404Chunk(text) {+ const parts = text.slice(SPL404_CHUNK_PREFIX.length).split(':');+ if (parts.length !== 4) return null;+ const [fileId, index, total, data] = parts;+ if (!HEX16.test(fileId) || !/^\d{1,9}$/.test(index) || !/^\d{1,9}$/.test(total)) return null;+ const i = Number(index);+ const n = Number(total);+ if (i >= n) return null;+ try {+ return { protocol: 'spl404/chunk', fileId, index: i, total: n, bytes: base64ToBytes(data) };+ } catch {+ return null;+ }+}++function parseSpl404Manifest(json) {+ if (json.v !== 1 || json.t !== 'file' || !Array.isArray(json.chunks)) return null;+ if (typeof json.sha256 !== 'string' || !HEX64.test(json.sha256)) return null;+ const chunks = json.chunks.filter((signature) => typeof signature === 'string');+ if (chunks.length !== json.chunks.length) return null;+ return {+ protocol: 'spl404/manifest',+ name: typeof json.name === 'string' ? json.name : 'file',+ mime: typeof json.mime === 'string' ? json.mime : 'application/octet-stream',+ size: isSafeInt(json.size) && json.size >= 0 ? json.size : 0,+ hash: json.sha256,+ chunks,+ };+}++// ---------------------------------------------------------------------------------------------+// Presentation: what a client may do with reassembled bytes+// ---------------------------------------------------------------------------------------------++export function sniffRasterMime(bytes) {+ if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) return 'image/png';+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';+ if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) return 'image/gif';+ if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp';+ return null;+}++// kind 'image': raster bytes whose magic number matches (declared MIME is never trusted).+// kind 'text': UTF-8 text, shown as characters only. SVG and HTML land here with markup=true.+// kind 'binary': everything else, download only.+export function presentation(bytes, { mime = null, name = null } = {}) {+ const raster = sniffRasterMime(bytes);+ if (raster) return { kind: 'image', mime: raster, markup: false, text: null };+ const text = bytes.length <= LIMITS.maxBytes ? decodeUtf8(bytes) : null;+ if (text !== null && !text.includes('\u0000')) {+ const probe = text.slice(0, 2048).toLowerCase();+ const declared = `${mime || ''} ${name || ''}`.toLowerCase();+ const markup = /<svg[\s>]|<!doctype html|<html[\s>]|<script[\s>]|<\?xml/.test(probe) || /svg|html|xml/.test(declared);+ return { kind: 'text', mime: null, markup, text: text.length > LIMITS.maxTextBytes ? text.slice(0, LIMITS.maxTextBytes) : text, truncated: text.length > LIMITS.maxTextBytes };+ }+ return { kind: 'binary', mime: null, markup: false, text: null };+}++// ---------------------------------------------------------------------------------------------+// Assembly. Each assembler takes already-classified parts and returns a result object:+// status 'verified' all parts present and the writer's own SHA-256 matches+// 'complete' all parts present; the format declares no hash (first/1)+// 'incomplete' parts are missing (missing[] lists 1-based part numbers)+// 'invalid' parts disagree, overflow limits, or the hash does not match+// bytes only set for verified/complete; unverified bytes are never returned+// ---------------------------------------------------------------------------------------------++async function finish(base, parts, problems, { declaredHash, hasHash }) {+ const missing = base.missing;+ const result = {+ ...base,+ declared_sha256: declaredHash || null,+ problems,+ bytes: null,+ content: null,+ content_sha256: null,+ size: 0,+ sha256: null,+ presentation: null,+ };+ if (missing.length) {+ result.status = 'incomplete';+ return result;+ }+ const total = parts.reduce((sum, part) => sum + part.bytes.length, 0);+ if (total > LIMITS.maxBytes) {+ result.status = 'invalid';+ problems.push(`Reassembled size exceeds the ${LIMITS.maxBytes}-byte limit.`);+ return result;+ }+ const bytes = concat(parts.map((part) => part.bytes), total);+ result.size = total;+ result.sha256 = await sha256Hex(bytes);+ if (hasHash && declaredHash !== result.sha256) problems.push('SHA-256 of the rebuilt bytes does not match the hash the writer declared.');+ if (problems.length) {+ result.status = 'invalid';+ return result;+ }+ result.status = hasHash ? 'verified' : 'complete';+ result.bytes = bytes;+ result.content = bytes;+ result.content_sha256 = result.sha256;+ result.presentation = presentation(bytes, { mime: result.mime, name: result.name });+ return result;+}++async function partSummaries(parts) {+ return Promise.all(parts.map(async (part) => ({ part: part.number, signature: part.signature, byte_length: part.bytes.length, sha256: await sha256Hex(part.bytes) })));+}++function missingParts(total, present) {+ const out = [];+ for (let n = 1; n <= total; n++) if (!present.has(n)) out.push(n);+ return out;+}++// entries: [{ signature, signer, envelope }] where envelope.protocol === 'first/1'.+export async function assembleFirst(entries) {+ const problems = [];+ if (!entries.length) throw new InscriptionError('No first/1 parts supplied.', 'no_parts');+ const { id, type, total } = entries[0].envelope;+ const signer = entries[0].signer ?? null;+ const byPart = new Map();+ for (const { signature, signer: partSigner, envelope } of entries) {+ if (envelope.id !== id || envelope.type !== type) { problems.push(`Part ${envelope.part} belongs to a different artifact.`); continue; }+ if (envelope.total !== total) { problems.push(`Part ${envelope.part} declares ${envelope.total} parts, expected ${total}.`); continue; }+ if (partSigner !== signer) { problems.push(`Part ${envelope.part} was signed by a different wallet.`); continue; }+ if (envelope.part > total) { problems.push(`Part ${envelope.part} is out of range.`); continue; }+ if (byPart.has(envelope.part)) { problems.push(`Part ${envelope.part} appears more than once.`); continue; }+ byPart.set(envelope.part, { number: envelope.part, signature, bytes: encoder.encode(envelope.data) });+ }+ if (total > LIMITS.maxParts) problems.push(`Artifact declares ${total} parts, over the ${LIMITS.maxParts}-part limit.`);+ const parts = [...byPart.values()].sort((a, b) => a.number - b.number);+ const missing = missingParts(Math.min(total, LIMITS.maxParts), byPart);+ const result = await finish(+ { protocol: 'first/1', id, type, name: null, mime: null, signer, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: null, hasHash: false },+ );+ if (result.status === 'complete') await validateFirstType(result);+ return result;+}++// first/1 type rules apply after reassembly: json parses, image is a data URI, agent has a manifest.+async function validateFirstType(result) {+ const text = decodeUtf8(result.bytes);+ const fail = (message) => { result.problems.push(message); result.status = 'invalid'; result.bytes = null; result.content = null; result.content_sha256 = null; result.presentation = null; };+ if (text === null) return fail('Reassembled data is not valid UTF-8.');+ if (result.type === 'text') { result.presentation = presentation(result.bytes); return; }+ if (result.type === 'json' || result.type === 'agent') {+ let json;+ try { json = JSON.parse(text); } catch { return fail(`Reassembled ${result.type} data is not valid JSON.`); }+ if (result.type === 'agent') {+ const ok = json && typeof json.name === 'string' && typeof json.version === 'string' && typeof json.endpoint === 'string' && /^https:\/\//.test(json.endpoint);+ if (!ok) return fail('Agent manifest needs a name, a version, and an HTTPS endpoint.');+ }+ result.presentation = { kind: 'text', mime: null, markup: false, text: text.length > LIMITS.maxTextBytes ? text.slice(0, LIMITS.maxTextBytes) : text, truncated: text.length > LIMITS.maxTextBytes };+ return;+ }+ const match = /^data:([a-z]+\/[a-z0-9+.-]+);base64,([A-Za-z0-9+/=_-]+)$/i.exec(text.trim());+ if (!match) return fail('Image artifact is not a base64 data URI.');+ let media;+ try { media = base64ToBytes(match[2]); } catch { return fail('Image data URI holds invalid base64.'); }+ const declaredMime = match[1].toLowerCase();+ result.mime = declaredMime;+ result.content = media;+ result.content_sha256 = await sha256Hex(media);+ const view = presentation(media, { mime: declaredMime });+ result.presentation = view.kind === 'image' ? view : { ...view, kind: view.kind === 'text' ? 'text' : 'binary' };+}++// entries: [{ signature, signer, envelope }] where envelope.protocol === 'firsts/1'.+export async function assembleFirsts(entries) {+ const problems = [];+ if (!entries.length) throw new InscriptionError('No firsts/1 chunks supplied.', 'no_parts');+ const { id, total } = entries[0].envelope;+ const byIndex = new Map();+ for (const { signature, envelope } of entries) {+ if (envelope.id !== id || envelope.total !== total) { problems.push(`Chunk ${envelope.index + 1} belongs to a different artifact.`); continue; }+ if (byIndex.has(envelope.index)) { problems.push(`Chunk ${envelope.index + 1} appears more than once.`); continue; }+ byIndex.set(envelope.index, { number: envelope.index + 1, signature, bytes: envelope.bytes, envelope });+ }+ if (total > LIMITS.maxParts) problems.push(`Artifact declares ${total} chunks, over the ${LIMITS.maxParts}-chunk limit.`);+ const parts = [...byIndex.values()].sort((a, b) => a.number - b.number);+ const head = byIndex.get(0)?.envelope;+ const missing = missingParts(Math.min(total, LIMITS.maxParts), new Set(parts.map((part) => part.number)));+ const result = await finish(+ { protocol: 'firsts/1', id, type: null, name: head?.name ?? null, mime: head?.mime ?? null, signer: entries[0].signer ?? null, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: head?.hash ?? null, hasHash: Boolean(head) },+ );+ if (!missing.length && head && result.sha256 && result.sha256.slice(0, 16) !== id) {+ result.problems.push('Artifact ID is not the first 16 hex characters of the content digest.');+ result.status = 'invalid';+ result.bytes = null;+ result.content = null;+ result.content_sha256 = null;+ result.presentation = null;+ }+ return result;+}++// manifest: classified spl404/manifest. chunkEntries: Map<signature, { index, total, fileId, bytes }|null>+// holding what each listed signature yielded (null when missing or not an spl404 chunk).+export async function assembleSpl404(manifest, chunkEntries) {+ const problems = [];+ const expectedId = manifest.hash.slice(0, 16);+ const total = manifest.chunks.length;+ if (total === 0) problems.push('Manifest lists no chunks.');+ if (total > LIMITS.maxParts) problems.push(`Manifest lists ${total} chunks, over the ${LIMITS.maxParts}-chunk limit.`);+ if (new Set(manifest.chunks).size !== total) problems.push('Manifest lists the same chunk signature more than once.');+ const byIndex = new Map();+ const unreadable = [];+ manifest.chunks.forEach((signature, position) => {+ const chunk = chunkEntries.get(signature);+ if (!chunk) { unreadable.push(position + 1); return; }+ if (chunk.fileId !== expectedId) { problems.push(`Chunk ${position + 1} belongs to a different file.`); return; }+ if (chunk.total !== total) { problems.push(`Chunk ${position + 1} declares ${chunk.total} parts, manifest lists ${total}.`); return; }+ if (byIndex.has(chunk.index)) { problems.push(`Chunk index ${chunk.index + 1} appears more than once.`); return; }+ byIndex.set(chunk.index, { number: chunk.index + 1, signature, bytes: chunk.bytes });+ });+ if (unreadable.length) problems.push(`Chunk ${unreadable.join(', ')} could not be read or is not an SPL404 chunk.`);+ const parts = [...byIndex.values()].sort((a, b) => a.number - b.number);+ const missing = missingParts(Math.min(total, LIMITS.maxParts), new Set(parts.map((part) => part.number)));+ const result = await finish(+ { protocol: 'spl404', id: expectedId, type: null, name: manifest.name, mime: manifest.mime, signer: null, parts_total: total, parts_found: parts.length, missing, parts: await partSummaries(parts) },+ parts, problems, { declaredHash: manifest.hash, hasHash: true },+ );+ if (!missing.length && manifest.size && result.size && manifest.size !== result.size) {+ result.problems.push(`Rebuilt ${result.size} bytes, manifest says ${manifest.size}.`);+ result.status = 'invalid';+ result.bytes = null;+ result.content = null;+ result.content_sha256 = null;+ result.presentation = null;+ }+ return result;+}++// ---------------------------------------------------------------------------------------------+// Transaction access (jsonParsed getTransaction result)+// ---------------------------------------------------------------------------------------------++const MEMO_PROGRAMS = new Set([+ 'Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8',+ 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',+ 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH',+]);++export function memoTexts(transaction) {+ const message = transaction?.transaction?.message;+ const groups = [message?.instructions || [], ...(transaction?.meta?.innerInstructions || []).map((item) => item.instructions || [])];+ const out = [];+ for (const instructions of groups) {+ for (const instruction of instructions) {+ const memo = MEMO_PROGRAMS.has(instruction?.programId) || instruction?.program === 'spl-memo';+ if (memo && typeof instruction.parsed === 'string') out.push(instruction.parsed);+ }+ }+ return out;+}++export function transactionSigner(transaction) {+ return transaction?.transaction?.message?.accountKeys?.find((key) => key?.signer)?.pubkey ?? null;+}++// Each classified multi-part envelope found in one transaction.+export function envelopesIn(signature, transaction) {+ const signer = transactionSigner(transaction);+ const out = [];+ for (const text of memoTexts(transaction)) {+ const envelope = classifyMemo(text);+ if (envelope) out.push({ signature, signer, envelope });+ }+ return out;+}++// ---------------------------------------------------------------------------------------------+// Orchestration. Transport is injected so Node (RPC with fallbacks) and the browser (one RPC URL)+// share every rule.+// getTransaction: async function taking a signature, returning a jsonParsed transaction or null.+// listSignatures: optional async function taking an address and paging options, returning+// signature rows with err and memo fields; enables sibling discovery.+// ---------------------------------------------------------------------------------------------++async function mapLimit(items, limit, worker) {+ const results = new Array(items.length);+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (next < items.length) {+ const index = next++;+ results[index] = await worker(items[index], index);+ }+ }));+ return results;+}++function escapeRegExp(text) {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++export async function readInscription({ signature, signatures = [], getTransaction, listSignatures = null, discover = true }) {+ const cache = new Map();+ const fetchOne = async (sig) => {+ if (!cache.has(sig)) cache.set(sig, getTransaction(sig).catch((error) => { throw Object.assign(error, { signature: sig }); }));+ return cache.get(sig);+ };+ const fetchMany = async (sigs) => mapLimit([...new Set(sigs)], LIMITS.fetchConcurrency, async (sig) => {+ try { return { sig, transaction: await fetchOne(sig) }; } catch (error) { return { sig, transaction: null, error }; }+ });++ const supplied = [...new Set([signature, ...signatures])];+ const fetched = await fetchMany(supplied);+ const anchor = fetched.find((item) => item.sig === signature);+ if (!anchor?.transaction) {+ throw new InscriptionError('Transaction was not found or is not available from the configured RPC endpoints.', 'transaction_not_found');+ }+ const entries = fetched.flatMap((item) => (item.transaction ? envelopesIn(item.sig, item.transaction) : []));+ const anchorEntry = entries.find((entry) => entry.signature === signature);+ if (!anchorEntry) return { protocol: null, status: 'not_inscription', signature, signatures: supplied };+ const seed = anchorEntry.envelope;++ const discoverBySigner = async (needle, accept) => {+ if (!discover || !listSignatures || !anchorEntry.signer) return;+ let before;+ for (let page = 0; page < LIMITS.maxDiscoveryPages; page++) {+ const listed = (await listSignatures(anchorEntry.signer, before ? { before } : {})) || [];+ if (!listed.length) return;+ const hits = listed.filter((item) => item?.signature && !item.err && typeof item.memo === 'string' && needle.test(item.memo) && !cache.has(item.signature)).map((item) => item.signature);+ for (const result of await fetchMany(hits.slice(0, LIMITS.maxParts))) {+ if (result.transaction) entries.push(...envelopesIn(result.sig, result.transaction));+ }+ if (accept()) return;+ before = listed.at(-1).signature;+ if (listed.length < 1000) return;+ }+ };++ let result;+ if (seed.protocol === 'first/1') {+ const group = () => entries.filter((e) => e.envelope.protocol === 'first/1' && e.envelope.id === seed.id && e.envelope.type === seed.type && e.signer === anchorEntry.signer);+ const complete = () => new Set(group().map((e) => e.envelope.part)).size >= seed.total;+ if (!complete()) await discoverBySigner(new RegExp(`"id"\\s*:\\s*"${escapeRegExp(seed.id)}"`), complete);+ result = await assembleFirst(dedupe(group()));+ } else if (seed.protocol === 'firsts/1') {+ const group = () => entries.filter((e) => e.envelope.protocol === 'firsts/1' && e.envelope.id === seed.id);+ const complete = () => new Set(group().map((e) => e.envelope.index)).size >= seed.total;+ if (!complete()) await discoverBySigner(new RegExp(`"id"\\s*:\\s*"${seed.id}"`), complete);+ result = await assembleFirsts(dedupe(group()));+ } else {+ let manifest = seed.protocol === 'spl404/manifest' ? seed : entries.map((e) => e.envelope).find((e) => e.protocol === 'spl404/manifest' && e.hash.startsWith(seed.fileId));+ if (!manifest) {+ await discoverBySigner(new RegExp(`"sha256"\\s*:\\s*"${seed.fileId}[0-9a-f]{48}"`), () => entries.some((e) => e.envelope.protocol === 'spl404/manifest' && e.envelope.hash.startsWith(seed.fileId)));+ manifest = entries.map((e) => e.envelope).find((e) => e.protocol === 'spl404/manifest' && e.hash.startsWith(seed.fileId));+ }+ if (!manifest) {+ return {+ protocol: 'spl404', id: seed.fileId, status: 'incomplete', signature, signatures: supplied, parts_total: seed.total, parts_found: 1,+ missing: [], parts: [], problems: ['This is one chunk of a multi-part file. Its manifest was not found; supply the manifest transaction signature.'],+ bytes: null, size: 0, sha256: null, declared_sha256: null, presentation: null, name: null, mime: null, type: null, signer: anchorEntry.signer,+ };+ }+ const chunkMap = new Map();+ const wanted = manifest.chunks.slice(0, LIMITS.maxParts);+ for (const result of await fetchMany(wanted)) {+ const chunk = result.transaction ? envelopesIn(result.sig, result.transaction).map((e) => e.envelope).find((e) => e.protocol === 'spl404/chunk') : null;+ chunkMap.set(result.sig, chunk || null);+ }+ result = await assembleSpl404(manifest, chunkMap);+ if (!result.signer) result.signer = anchorEntry.signer;+ result.signatures = [signature, ...wanted];+ return finalize(result, signature);+ }+ result.signatures = [...new Set([signature, ...result.parts.map((part) => part.signature)])];+ return finalize(result, signature);+}++function finalize(result, signature) {+ return { signature, ...result };+}++function dedupe(entries) {+ const seen = new Set();+ return entries.filter((entry) => {+ const key = `${entry.signature}:${entry.envelope.part ?? entry.envelope.index}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}diff --git a/tests/solana-memo-inscriptions-copy.test.js b/tests/solana-memo-inscriptions-copy.test.jsnew file mode 100644index 000000000..cdfa3eb0a--- /dev/null+++ b/tests/solana-memo-inscriptions-copy.test.js@@ -0,0 +1,23 @@+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';++// The /onchain page imports public/onchain/inscriptions.js; the MCP package ships its own+// copy. They must stay byte-identical so the browser and the MCP tool apply the same rules.+describe('memo inscription reader copies', () => {+ it('public/onchain/inscriptions.js matches the MCP package module', () => {+ const canonical = readFileSync('packages/solana-memo-media-mcp/src/lib/inscriptions.js');+ const served = readFileSync('public/onchain/inscriptions.js');+ expect(served.equals(canonical)).toBe(true);+ });++ it('the /onchain page renders only sniffed rasters as images and never injects markup', () => {+ const page = readFileSync('public/onchain/index.html', 'utf8');+ expect(page).toContain("from '/onchain/inscriptions.js'");+ expect(page).toContain("view.kind === 'image'");+ const renderer = page.slice(page.indexOf('function renderInscription'), page.indexOf('async function lookup'));+ expect(renderer).not.toMatch(/innerHTML\s*=\s*[^;]*(view|result)\.(text|content)/);+ expect(renderer).toContain('text.textContent = view.text');+ expect(renderer).not.toContain('<iframe');+ expect(renderer).not.toContain('srcdoc');+ });+});