Skip to main content

ipfrs_wasm/
lib.rs

1//! WebAssembly bindings for IPFRS
2//!
3//! This module provides browser-compatible bindings for IPFRS using wasm-bindgen.
4//! Two storage backends are available:
5//!
6//! - [`IpfrsClient`]: in-memory (HashMap-backed), ephemeral — data is lost on page refresh.
7//! - `IpfrsClientPersistent`: IndexedDB-backed, browser-persistent (wasm32 only).
8//!
9//! # Quick Start (JavaScript)
10//!
11//! ```javascript
12//! import init, { IpfrsClient, compute_cid, verify_cid, version } from './ipfrs_wasm.js';
13//!
14//! const _wasm = await init();
15//!
16//! // Ephemeral in-memory client
17//! const client = new IpfrsClient();
18//! const cid = await client.add(new TextEncoder().encode("hello ipfrs"));
19//! const bytes = await client.get(cid);
20//! console.log(new TextDecoder().decode(bytes));
21//!
22//! // Persistent IndexedDB client (browser only)
23//! const persistent = await IpfrsClientPersistent.new("ipfrs-blocks");
24//! const cid2 = await persistent.add(new TextEncoder().encode("persisted data"));
25//! ```
26
27use wasm_bindgen::prelude::*;
28
29// ---------------------------------------------------------------------------
30// WebRTC transport (signalling types are target-independent;
31// IpfrsPeer / IpfrsPeerAnswerer are wasm32-only)
32// ---------------------------------------------------------------------------
33
34pub mod async_api;
35pub mod peer_state;
36pub mod storage;
37pub mod webrtc;
38
39// Re-export the WASM peer types at crate root for wasm-bindgen visibility.
40#[cfg(target_arch = "wasm32")]
41pub use webrtc::{IpfrsPeer, IpfrsPeerAnswerer};
42
43// ---------------------------------------------------------------------------
44// Panic hook initialisation (wasm32 only)
45// ---------------------------------------------------------------------------
46
47/// Initialise the IPFRS WASM module.
48///
49/// Called automatically by the wasm-bindgen generated JS glue via the
50/// `#[wasm_bindgen(start)]` attribute.  Sets up the `console_error_panic_hook`
51/// so that Rust panics surface as readable browser console errors.
52#[wasm_bindgen(start)]
53pub fn start() {
54    #[cfg(feature = "console_error_panic_hook")]
55    console_error_panic_hook::set_once();
56}
57
58// ---------------------------------------------------------------------------
59// CID helpers (pure, no allocation beyond the String result)
60// ---------------------------------------------------------------------------
61
62/// Compute a CIDv1 (base32-lower, SHA2-256, raw codec) string for `data`.
63///
64/// The format matches `bafy…` CIDs produced by go-ipfs / js-ipfs for raw
65/// leaf blocks (codec `0x55`), giving the encoding:
66///
67/// ```text
68/// <varint version=1><varint codec=0x55><varint mh-fn=0x12><varint mh-len=32><32-byte-digest>
69/// ```
70///
71/// encoded in lowercase base32 with the `b` multibase prefix.
72fn cid_from_bytes(data: &[u8]) -> String {
73    use sha2::Digest;
74
75    // 1. SHA-256 digest
76    let digest: [u8; 32] = sha2::Sha256::digest(data).into();
77
78    // 2. Multihash = [0x12, 0x20, <32 bytes>]
79    //    0x12 = sha2-256 function code, 0x20 = 32 (length)
80    let mut multihash = Vec::with_capacity(34);
81    multihash.push(0x12u8); // sha2-256
82    multihash.push(0x20u8); // 32 bytes
83    multihash.extend_from_slice(&digest);
84
85    // 3. CIDv1 binary = [0x01, 0x55, <multihash>]
86    //    0x01 = CIDv1, 0x55 = raw codec
87    let mut cid_bytes = Vec::with_capacity(36);
88    cid_bytes.push(0x01u8); // version 1
89    cid_bytes.push(0x55u8); // raw codec
90    cid_bytes.extend_from_slice(&multihash);
91
92    // 4. Multibase base32lower with 'b' prefix
93    let encoded = base32_lower(&cid_bytes);
94    format!("b{encoded}")
95}
96
97/// RFC 4648 base32 (lowercase, no padding) encoder.
98fn base32_lower(input: &[u8]) -> String {
99    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
100    let mut output = Vec::with_capacity((input.len() * 8).div_ceil(5));
101    let mut buffer: u64 = 0;
102    let mut bits_left: u32 = 0;
103
104    for &byte in input {
105        buffer = (buffer << 8) | u64::from(byte);
106        bits_left += 8;
107        while bits_left >= 5 {
108            bits_left -= 5;
109            let idx = ((buffer >> bits_left) & 0x1f) as usize;
110            output.push(ALPHABET[idx]);
111        }
112    }
113    if bits_left > 0 {
114        let idx = ((buffer << (5 - bits_left)) & 0x1f) as usize;
115        output.push(ALPHABET[idx]);
116    }
117
118    // SAFETY: ALPHABET contains only ASCII bytes, so the Vec<u8> is valid UTF-8.
119    String::from_utf8(output).unwrap_or_default()
120}
121
122// ---------------------------------------------------------------------------
123// InMemoryStore – pure in-memory block store for WASM
124// ---------------------------------------------------------------------------
125
126/// Pure in-memory content-addressed block store.
127///
128/// Keys are CIDv1 strings; values are the raw byte payloads.
129struct InMemoryStore {
130    blocks: std::collections::HashMap<String, Vec<u8>>,
131    total_bytes: usize,
132}
133
134impl InMemoryStore {
135    fn new() -> Self {
136        Self {
137            blocks: std::collections::HashMap::new(),
138            total_bytes: 0,
139        }
140    }
141
142    /// Store `data` and return its CID.  If the same CID is already present
143    /// the entry is *not* duplicated (content-addressed idempotency).
144    fn put(&mut self, data: &[u8]) -> String {
145        let cid = cid_from_bytes(data);
146        self.blocks.entry(cid.clone()).or_insert_with(|| {
147            self.total_bytes += data.len();
148            data.to_vec()
149        });
150        cid
151    }
152
153    fn get(&self, cid: &str) -> Option<&Vec<u8>> {
154        self.blocks.get(cid)
155    }
156
157    fn has(&self, cid: &str) -> bool {
158        self.blocks.contains_key(cid)
159    }
160
161    /// Remove the block with the given CID.  Returns `true` if it existed.
162    fn delete(&mut self, cid: &str) -> bool {
163        if let Some(data) = self.blocks.remove(cid) {
164            self.total_bytes = self.total_bytes.saturating_sub(data.len());
165            true
166        } else {
167            false
168        }
169    }
170
171    fn list(&self) -> Vec<String> {
172        self.blocks.keys().cloned().collect()
173    }
174
175    fn total_bytes(&self) -> usize {
176        self.total_bytes
177    }
178
179    fn len(&self) -> usize {
180        self.blocks.len()
181    }
182}
183
184// ---------------------------------------------------------------------------
185// IpfrsClient – the public WASM API (in-memory, ephemeral)
186// ---------------------------------------------------------------------------
187
188/// IPFRS in-memory client for WebAssembly.
189///
190/// Provides a content-addressed block store backed by a `HashMap`.
191/// All data lives in the JS heap and is lost when the object is garbage-collected
192/// or the page is refreshed — suitable for ephemeral browser usage or unit tests.
193#[wasm_bindgen]
194pub struct IpfrsClient {
195    store: InMemoryStore,
196}
197
198#[wasm_bindgen]
199impl IpfrsClient {
200    /// Create a new IPFRS in-memory client.
201    ///
202    /// # JavaScript
203    /// ```javascript
204    /// const client = new IpfrsClient();
205    /// ```
206    #[wasm_bindgen(constructor)]
207    pub fn new() -> IpfrsClient {
208        IpfrsClient {
209            store: InMemoryStore::new(),
210        }
211    }
212
213    /// Add a byte slice to the store and return its CID string.
214    ///
215    /// The operation is deterministic: identical byte sequences always produce
216    /// the same CID and are stored only once.
217    ///
218    /// # JavaScript
219    /// ```javascript
220    /// const cid = await client.add(new Uint8Array([1, 2, 3]));
221    /// ```
222    pub async fn add(&mut self, data: &[u8]) -> Result<String, JsValue> {
223        if data.is_empty() {
224            return Err(JsValue::from_str("data must not be empty"));
225        }
226        Ok(self.store.put(data))
227    }
228
229    /// Retrieve bytes by CID string.
230    ///
231    /// Returns an error if the CID is not present in the store.
232    ///
233    /// # JavaScript
234    /// ```javascript
235    /// const bytes = await client.get(cid);
236    /// ```
237    pub async fn get(&self, cid: &str) -> Result<Vec<u8>, JsValue> {
238        self.store
239            .get(cid)
240            .cloned()
241            .ok_or_else(|| JsValue::from_str(&format!("CID not found: {cid}")))
242    }
243
244    /// Return `true` if `cid` is present in the store.
245    pub fn has(&self, cid: &str) -> bool {
246        self.store.has(cid)
247    }
248
249    /// Return all stored CIDs as a `Vec<String>`.
250    ///
251    /// Order is unspecified (HashMap iteration order).
252    #[wasm_bindgen(js_name = listCids)]
253    pub fn list_cids(&self) -> Vec<String> {
254        self.store.list()
255    }
256
257    /// Return storage statistics as a JSON string.
258    ///
259    /// # Fields
260    /// - `block_count` – number of stored blocks
261    /// - `total_bytes` – aggregate stored payload size in bytes
262    ///
263    /// # JavaScript
264    /// ```javascript
265    /// const stats = JSON.parse(client.stats());
266    /// console.log(stats.block_count, stats.total_bytes);
267    /// ```
268    pub fn stats(&self) -> String {
269        format!(
270            r#"{{"block_count":{block_count},"total_bytes":{total_bytes}}}"#,
271            block_count = self.store.len(),
272            total_bytes = self.store.total_bytes(),
273        )
274    }
275
276    /// Delete the block identified by `cid`.
277    ///
278    /// Returns `true` if the block existed and was removed, `false` otherwise.
279    pub fn delete(&mut self, cid: &str) -> bool {
280        self.store.delete(cid)
281    }
282}
283
284impl Default for IpfrsClient {
285    fn default() -> Self {
286        Self::new()
287    }
288}
289
290// ---------------------------------------------------------------------------
291// Free-standing utility functions
292// ---------------------------------------------------------------------------
293
294/// Compute the CIDv1 (base32-lower, SHA2-256, raw codec) for the given bytes
295/// without storing them.
296///
297/// # JavaScript
298/// ```javascript
299/// const cid = compute_cid(new Uint8Array([1, 2, 3]));
300/// ```
301#[wasm_bindgen]
302pub fn compute_cid(data: &[u8]) -> String {
303    cid_from_bytes(data)
304}
305
306/// Return the ipfrs-wasm version string.
307#[wasm_bindgen]
308pub fn version() -> String {
309    "ipfrs-wasm 0.2.0".to_string()
310}
311
312/// Verify that `data` matches `cid` (i.e., recomputing the CID yields the
313/// same string).
314///
315/// # JavaScript
316/// ```javascript
317/// const ok = verify_cid(cid, new Uint8Array([1, 2, 3]));
318/// ```
319#[wasm_bindgen]
320pub fn verify_cid(cid: &str, data: &[u8]) -> bool {
321    cid_from_bytes(data) == cid
322}
323
324/// Add bytes using a temporary in-memory client and return the CID.
325///
326/// Convenience helper for one-shot content-addressing without managing a client.
327///
328/// # JavaScript
329/// ```javascript
330/// const cid = await add_bytes(new Uint8Array([1, 2, 3]));
331/// ```
332#[wasm_bindgen]
333pub async fn add_bytes(data: &[u8]) -> Result<String, JsValue> {
334    if data.is_empty() {
335        return Err(JsValue::from_str("data must not be empty"));
336    }
337    Ok(cid_from_bytes(data))
338}
339
340/// Retrieve bytes from an [`IpfrsClient`] by CID.
341///
342/// Returns `None` (maps to `null` in JavaScript) if the CID is not present.
343///
344/// # JavaScript
345/// ```javascript
346/// const bytes = await get_bytes(client, cid);
347/// if (bytes !== null) { ... }
348/// ```
349#[wasm_bindgen]
350pub async fn get_bytes(client: &IpfrsClient, cid: &str) -> Result<Option<Vec<u8>>, JsValue> {
351    Ok(client.store.get(cid).cloned())
352}
353
354// ---------------------------------------------------------------------------
355// IndexedDB-backed block store (wasm32 only)
356// ---------------------------------------------------------------------------
357
358/// IndexedDB storage backend — only compiled for the `wasm32` target.
359#[cfg(target_arch = "wasm32")]
360pub mod indexed_db {
361    use super::cid_from_bytes;
362    use js_sys::{Array, Uint8Array};
363    use wasm_bindgen::prelude::*;
364    use wasm_bindgen_futures::JsFuture;
365    use web_sys::{IdbDatabase, IdbOpenDbRequest, IdbTransactionMode};
366
367    const STORE_NAME: &str = "blocks";
368
369    // -----------------------------------------------------------------------
370    // Internal helpers
371    // -----------------------------------------------------------------------
372
373    /// Open (or create) an IndexedDB database with a single "blocks" object store.
374    ///
375    /// The database is opened at version 1.  The `onupgradeneeded` callback
376    /// creates the "blocks" object store the first time the database is opened.
377    async fn open_db(db_name: &str) -> Result<IdbDatabase, JsValue> {
378        let window = web_sys::window()
379            .ok_or_else(|| JsValue::from_str("no global window — are you in a browser?"))?;
380
381        let idb_factory = window
382            .indexed_db()?
383            .ok_or_else(|| JsValue::from_str("IndexedDB is not available in this browser"))?;
384
385        let open_req: IdbOpenDbRequest = idb_factory.open_with_u32(db_name, 1)?;
386
387        // Clone the request so the closure can reference it after the move.
388        let on_upgrade = Closure::<dyn FnMut(web_sys::Event)>::new({
389            let req = open_req.clone();
390            move |_event: web_sys::Event| {
391                // `result` at this point is the IdbDatabase being upgraded.
392                let db: IdbDatabase = req
393                    .result()
394                    .expect("IdbOpenDbRequest.result() inside onupgradeneeded")
395                    .dyn_into()
396                    .expect("result is IdbDatabase");
397
398                // Only create the store if it does not already exist.
399                let store_names: Array = db.object_store_names().into();
400                let already_exists = (0..store_names.length())
401                    .any(|i| store_names.get(i).as_string().as_deref() == Some(STORE_NAME));
402
403                if !already_exists {
404                    db.create_object_store(STORE_NAME)
405                        .expect("create_object_store failed");
406                }
407            }
408        });
409
410        open_req.set_onupgradeneeded(Some(on_upgrade.as_ref().unchecked_ref()));
411        on_upgrade.forget(); // leak the closure — it is only called once during upgrade
412
413        let db_value: JsValue = JsFuture::from(open_req).await?;
414        let db: IdbDatabase = db_value
415            .dyn_into()
416            .map_err(|_| JsValue::from_str("IdbOpenDbRequest result was not an IdbDatabase"))?;
417
418        Ok(db)
419    }
420
421    // -----------------------------------------------------------------------
422    // IndexedDbStore
423    // -----------------------------------------------------------------------
424
425    /// IndexedDB-backed content-addressed block store.
426    ///
427    /// Data persists across page refreshes inside the browser's IndexedDB.
428    /// Each instance holds the database name; operations open short-lived
429    /// read-write transactions as needed.
430    ///
431    /// # JavaScript
432    /// ```javascript
433    /// const store = await IndexedDbStore.open("my-ipfrs-db");
434    /// const cid   = await store.put(new TextEncoder().encode("hello"));
435    /// const bytes = await store.get(cid);
436    /// ```
437    #[wasm_bindgen]
438    pub struct IndexedDbStore {
439        db_name: String,
440    }
441
442    #[wasm_bindgen]
443    impl IndexedDbStore {
444        /// Open (or create) an IndexedDB database for IPFRS block storage.
445        ///
446        /// The database is identified by `db_name` and stores blocks under an
447        /// internal object store named `"blocks"`.
448        #[wasm_bindgen]
449        pub async fn open(db_name: &str) -> Result<IndexedDbStore, JsValue> {
450            // Eagerly open to validate that IndexedDB is available and that the
451            // upgrade callback runs before we hand the handle to the caller.
452            let _db = open_db(db_name).await?;
453            Ok(IndexedDbStore {
454                db_name: db_name.to_string(),
455            })
456        }
457
458        /// Store `data` in IndexedDB and return its CIDv1 string.
459        ///
460        /// If a block with the same CID is already present it is overwritten
461        /// (idempotent, since the content is identical).
462        pub async fn put(&self, data: &[u8]) -> Result<String, JsValue> {
463            if data.is_empty() {
464                return Err(JsValue::from_str("data must not be empty"));
465            }
466
467            let cid = cid_from_bytes(data);
468            let db = open_db(&self.db_name).await?;
469
470            let tx = db.transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readwrite)?;
471            let store = tx.object_store(STORE_NAME)?;
472
473            // Convert &[u8] -> Uint8Array for storage
474            let js_data = Uint8Array::from(data);
475            let cid_key = JsValue::from_str(&cid);
476
477            let put_req = store.put_with_key(&js_data, &cid_key)?;
478            JsFuture::from(put_req).await?;
479
480            Ok(cid)
481        }
482
483        /// Retrieve raw bytes for the block identified by `cid`.
484        ///
485        /// Returns `None` when the CID is not in the store.
486        pub async fn get(&self, cid: &str) -> Result<Option<Vec<u8>>, JsValue> {
487            let db = open_db(&self.db_name).await?;
488
489            let tx = db.transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readonly)?;
490            let store = tx.object_store(STORE_NAME)?;
491
492            let key = JsValue::from_str(cid);
493            let get_req = store.get(&key)?;
494            let result: JsValue = JsFuture::from(get_req).await?;
495
496            if result.is_undefined() || result.is_null() {
497                return Ok(None);
498            }
499
500            let arr: Uint8Array = result
501                .dyn_into()
502                .map_err(|_| JsValue::from_str("stored value is not a Uint8Array"))?;
503
504            Ok(Some(arr.to_vec()))
505        }
506
507        /// Return `true` if `cid` is present in the store.
508        pub async fn has(&self, cid: &str) -> Result<bool, JsValue> {
509            Ok(self.get(cid).await?.is_some())
510        }
511
512        /// Delete the block identified by `cid`.
513        ///
514        /// Returns `true` if the block existed and was removed, `false` otherwise.
515        pub async fn delete(&self, cid: &str) -> Result<bool, JsValue> {
516            let existed = self.has(cid).await?;
517            if !existed {
518                return Ok(false);
519            }
520
521            let db = open_db(&self.db_name).await?;
522
523            let tx = db.transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readwrite)?;
524            let store = tx.object_store(STORE_NAME)?;
525
526            let key = JsValue::from_str(cid);
527            let del_req = store.delete(&key)?;
528            JsFuture::from(del_req).await?;
529
530            Ok(true)
531        }
532
533        /// Return the number of blocks currently stored in the database.
534        pub async fn count(&self) -> Result<u32, JsValue> {
535            let db = open_db(&self.db_name).await?;
536
537            let tx = db.transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readonly)?;
538            let store = tx.object_store(STORE_NAME)?;
539
540            let count_req = store.count()?;
541            let result: JsValue = JsFuture::from(count_req).await?;
542
543            result
544                .as_f64()
545                .map(|n| n as u32)
546                .ok_or_else(|| JsValue::from_str("count() did not return a number"))
547        }
548    }
549}
550
551// ---------------------------------------------------------------------------
552// IpfrsClientPersistent – high-level client backed by IndexedDB (wasm32 only)
553// ---------------------------------------------------------------------------
554
555/// IPFRS persistent client backed by IndexedDB (browser only).
556///
557/// Data survives page refreshes.  Internally delegates all storage to
558/// an [`indexed_db::IndexedDbStore`].
559///
560/// # JavaScript
561/// ```javascript
562/// const client = await IpfrsClientPersistent.new("ipfrs-blocks");
563/// const cid    = await client.add(new TextEncoder().encode("hello"));
564/// const bytes  = await client.get(cid);
565/// ```
566#[cfg(target_arch = "wasm32")]
567#[wasm_bindgen]
568pub struct IpfrsClientPersistent {
569    db_name: String,
570}
571
572#[cfg(target_arch = "wasm32")]
573#[wasm_bindgen]
574impl IpfrsClientPersistent {
575    /// Open (or initialise) a persistent IPFRS client backed by the IndexedDB
576    /// database named `db_name`.
577    #[wasm_bindgen(constructor)]
578    pub async fn new(db_name: &str) -> Result<IpfrsClientPersistent, JsValue> {
579        // Delegate to IndexedDbStore::open to validate availability and run migrations.
580        indexed_db::IndexedDbStore::open(db_name).await?;
581        Ok(IpfrsClientPersistent {
582            db_name: db_name.to_string(),
583        })
584    }
585
586    /// Add `data` to the persistent store and return its CIDv1 string.
587    pub async fn add(&self, data: &[u8]) -> Result<String, JsValue> {
588        let store = indexed_db::IndexedDbStore::open(&self.db_name).await?;
589        store.put(data).await
590    }
591
592    /// Retrieve bytes by `cid`.  Returns `None` when the block is absent.
593    pub async fn get(&self, cid: &str) -> Result<Option<Vec<u8>>, JsValue> {
594        let store = indexed_db::IndexedDbStore::open(&self.db_name).await?;
595        store.get(cid).await
596    }
597
598    /// Return `true` if `cid` is in the persistent store.
599    pub async fn has(&self, cid: &str) -> Result<bool, JsValue> {
600        let store = indexed_db::IndexedDbStore::open(&self.db_name).await?;
601        store.has(cid).await
602    }
603
604    /// Delete the block identified by `cid`.
605    ///
606    /// Returns `true` if the block existed and was removed, `false` otherwise.
607    pub async fn delete(&self, cid: &str) -> Result<bool, JsValue> {
608        let store = indexed_db::IndexedDbStore::open(&self.db_name).await?;
609        store.delete(cid).await
610    }
611
612    /// Return the number of blocks in the persistent store.
613    pub async fn count(&self) -> Result<u32, JsValue> {
614        let store = indexed_db::IndexedDbStore::open(&self.db_name).await?;
615        store.count().await
616    }
617}
618
619// ---------------------------------------------------------------------------
620// Tests – run on the native target, NOT wasm32
621// ---------------------------------------------------------------------------
622
623#[cfg(all(test, not(target_arch = "wasm32")))]
624mod tests {
625    use super::*;
626
627    // ------------------------------------------------------------------
628    // InMemoryStore unit tests
629    // ------------------------------------------------------------------
630
631    #[test]
632    fn test_in_memory_store_roundtrip() {
633        let mut store = InMemoryStore::new();
634        let data = b"hello wasm";
635        let cid = store.put(data);
636        assert!(store.has(&cid));
637        assert_eq!(store.get(&cid), Some(&data.to_vec()));
638    }
639
640    #[test]
641    fn test_in_memory_delete() {
642        let mut store = InMemoryStore::new();
643        let cid = store.put(b"delete me");
644        assert!(store.has(&cid));
645        assert!(store.delete(&cid));
646        assert!(!store.has(&cid));
647        // Deleting again returns false
648        assert!(!store.delete(&cid));
649    }
650
651    #[test]
652    fn test_cid_deterministic() {
653        let mut store = InMemoryStore::new();
654        let cid1 = store.put(b"same data");
655        let cid2 = store.put(b"same data");
656        assert_eq!(cid1, cid2, "same content must produce same CID");
657        // Only one block stored
658        assert_eq!(store.len(), 1);
659    }
660
661    #[test]
662    fn test_different_data_different_cid() {
663        let mut store = InMemoryStore::new();
664        let cid1 = store.put(b"alpha");
665        let cid2 = store.put(b"beta");
666        assert_ne!(cid1, cid2);
667        assert_eq!(store.len(), 2);
668    }
669
670    #[test]
671    fn test_total_bytes_accounting() {
672        let mut store = InMemoryStore::new();
673        store.put(b"abc"); // 3 bytes
674        store.put(b"defgh"); // 5 bytes
675        assert_eq!(store.total_bytes(), 8);
676        // Storing duplicate must not increase total_bytes
677        store.put(b"abc");
678        assert_eq!(store.total_bytes(), 8);
679    }
680
681    #[test]
682    fn test_total_bytes_after_delete() {
683        let mut store = InMemoryStore::new();
684        let cid = store.put(b"hello"); // 5 bytes
685        assert_eq!(store.total_bytes(), 5);
686        store.delete(&cid);
687        assert_eq!(store.total_bytes(), 0);
688    }
689
690    #[test]
691    fn test_list_cids() {
692        let mut store = InMemoryStore::new();
693        let c1 = store.put(b"one");
694        let c2 = store.put(b"two");
695        let mut listed = store.list();
696        listed.sort();
697        let mut expected = vec![c1, c2];
698        expected.sort();
699        assert_eq!(listed, expected);
700    }
701
702    // ------------------------------------------------------------------
703    // compute_cid / verify_cid
704    // ------------------------------------------------------------------
705
706    #[test]
707    fn test_compute_cid_function() {
708        let cid = compute_cid(b"ipfrs wasm");
709        assert!(!cid.is_empty());
710        // CIDv1 multibase base32lower starts with 'b'
711        assert!(cid.starts_with('b'), "CID must start with 'b': {cid}");
712    }
713
714    #[test]
715    fn test_compute_cid_deterministic() {
716        assert_eq!(compute_cid(b"same"), compute_cid(b"same"));
717        assert_ne!(compute_cid(b"a"), compute_cid(b"b"));
718    }
719
720    #[test]
721    fn test_verify_cid() {
722        let data = b"verify me";
723        let cid = compute_cid(data);
724        assert!(verify_cid(&cid, data));
725        assert!(!verify_cid(&cid, b"different data"));
726        assert!(!verify_cid("bnotacid", data));
727    }
728
729    // ------------------------------------------------------------------
730    // IpfrsClient (sync-path via InMemoryStore)
731    // ------------------------------------------------------------------
732
733    #[test]
734    fn test_store_stats() {
735        let mut store = InMemoryStore::new();
736        store.put(b"stats test data");
737        let stats_json = format!(
738            r#"{{"block_count":{block_count},"total_bytes":{total_bytes}}}"#,
739            block_count = store.len(),
740            total_bytes = store.total_bytes(),
741        );
742        assert!(stats_json.contains("\"block_count\":1"));
743        assert!(stats_json.contains("\"total_bytes\":15"));
744    }
745
746    #[test]
747    fn test_client_has_and_delete() {
748        let mut client = IpfrsClient::new();
749        let cid = client.store.put(b"hello client");
750        assert!(client.has(&cid));
751        assert!(client.delete(&cid));
752        assert!(!client.has(&cid));
753    }
754
755    #[test]
756    fn test_client_list_cids() {
757        let mut client = IpfrsClient::new();
758        client.store.put(b"item1");
759        client.store.put(b"item2");
760        assert_eq!(client.list_cids().len(), 2);
761    }
762
763    #[test]
764    fn test_client_stats_json() {
765        let mut client = IpfrsClient::new();
766        client.store.put(b"stat");
767        let stats = client.stats();
768        assert!(stats.contains("block_count"));
769        assert!(stats.contains("total_bytes"));
770    }
771
772    #[test]
773    fn test_version() {
774        let v = version();
775        assert!(v.contains("ipfrs-wasm"));
776        assert!(v.contains("0.2.0"));
777    }
778
779    #[test]
780    fn test_cid_starts_with_b() {
781        for payload in [b"a".as_ref(), b"hello world", b"\x00\xff\xfe"] {
782            let cid = cid_from_bytes(payload);
783            assert!(cid.starts_with('b'), "unexpected CID: {cid}");
784        }
785    }
786
787    #[test]
788    fn test_known_cid_vector() {
789        // Cross-check against a known SHA-256 value.
790        // echo -n "Hello World" | ipfs add --raw-leaves --inline-limit 0 --cid-version 1
791        // produces: bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e
792        use sha2::Digest;
793        let data = b"Hello World";
794        let digest: [u8; 32] = sha2::Sha256::digest(data).into();
795        let expected_hex = "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e";
796        assert_eq!(hex::encode(digest), expected_hex);
797        let cid = cid_from_bytes(data);
798        assert!(cid.starts_with('b'));
799        assert!(!cid.is_empty());
800    }
801
802    // ------------------------------------------------------------------
803    // NPM package metadata validation
804    // ------------------------------------------------------------------
805
806    #[test]
807    fn test_package_metadata() {
808        let pkg_json = include_str!("../pkg/package.json");
809        let parsed: serde_json::Value =
810            serde_json::from_str(pkg_json).expect("pkg/package.json must be valid JSON");
811        assert_eq!(parsed["name"], "@cool-japan/ipfrs");
812        assert_eq!(parsed["version"], "0.2.0");
813        assert_eq!(parsed["license"], "Apache-2.0");
814        // Verify required file entries are present
815        let files = parsed["files"].as_array().expect("files must be an array");
816        let file_names: Vec<&str> = files.iter().filter_map(|v| v.as_str()).collect();
817        assert!(
818            file_names.contains(&"ipfrs_wasm.js"),
819            "ipfrs_wasm.js missing from files"
820        );
821        assert!(
822            file_names.contains(&"ipfrs_wasm_bg.wasm"),
823            "ipfrs_wasm_bg.wasm missing from files"
824        );
825    }
826
827    #[test]
828    fn test_compute_cid_stable() {
829        // Regression test: CID for a fixed input must not change between releases.
830        let cid = compute_cid(b"ipfrs stable vector");
831        assert!(cid.starts_with('b'), "CID must start with multibase 'b'");
832        // Verify against the same computation independently:
833        let expected = cid_from_bytes(b"ipfrs stable vector");
834        assert_eq!(cid, expected);
835    }
836}