You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

js-ipfs中ipfs.add与ipfs.dag.put的差异及生成CID不一致问题咨询

Why ipfs.add() and ipfs.dag.put() produce different CIDs

Great question! It's totally reasonable to expect matching CIDs here at first glance, but the difference comes down to how each method packages and hashes your input data. Let's break this down clearly:

1. How ipfs.add() handles your data

When you run await ipfs.add('hello world', {cidVersion:1}), IPFS treats your input as a file. For small files (under the default block size limit of 256KB), it stores the content as a raw block—meaning it hashes the exact raw bytes of your string (the 11 ASCII bytes of hello world). The resulting CID uses the raw codec (visible in the bafkrei prefix) and SHA-256 hashing (since you specified cidVersion:1).

2. How ipfs.dag.put() handles your data

Conversely, await ipfs.dag.put('hello world') treats your input as a DAG node and uses the default dag-cbor serialization codec. CBOR doesn't hash your raw string directly: it first adds a small metadata prefix (a byte indicating the data type and length—for hello world, this is 0x6b) before the raw string bytes. This results in 12 total bytes being hashed instead of the original 11. The CID uses the dag-cbor codec (seen in the bafyre prefix) with SHA-256, hence the distinct value.

Getting matching CIDs (if needed)

If you want both methods to generate the same CID, you just need to make them process the exact same data:

  • Option 1: Make dag.put() use raw bytes
    Tell dag.put() to use the raw codec and pass the raw byte representation of your string:

    await ipfs.dag.put(new TextEncoder().encode('hello world'), { codec: 'raw', cidVersion: 1 })
    

    This will produce the identical CID to your original ipfs.add() call.

  • Option 2: Make ipfs.add() use CBOR wrapping
    While less common (since ipfs.add() is designed for file storage), you could wrap your string in a CBOR node first and then add it—but this defeats the purpose of using ipfs.add() for simple text content.

内容的提问来源于stack exchange,提问作者cwarny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:02:50