生成与IPFS-Desktop CID匹配的CID的无节点方法



>我想在javascript中为文件生成CID(内容标识符(,而无需访问IPFS节点或互联网。我尝试使用 js-multihashing-async 首先对文件进行哈希处理,并使用 js-cid 从哈希生成 CID,但我得到的 CID 与将文件添加到 ipfs-desktop 的 CID 不同。看起来问题是IPFS节点块数据,CID用于链接文件块的DAG。我已经尝试过这个库,但它不会产生与ipfs-desktop对同一文件相同的CID。这个问题基本上与我的相同,但没有一个答案给出与ipfs桌面生成的CID匹配的CID。

>ipfs-only-hash是用于从文件或缓冲区创建IPFS CID的正确模块,而无需启动IPFS守护程序。对于相同的输入文件和相同的选项,它应生成相同的 CID。

此示例来自ipfs-only-hash测试,它验证它是否将相同的缓冲区哈希到与 js-ipfs 节点相同的 CID。

test('should produce the same hash as IPFS', async t => {
const data = Buffer.from('TEST' + Date.now())
const ipfs = new Ipfs({ repo: path.join(os.tmpdir(), `${Date.now()}`) })
await new Promise((resolve, reject) => {
ipfs.on('ready', resolve).on('error', reject)
})
const files = await ipfs.add(data)
const hash = await Hash.of(data)
t.is(files[0].hash, hash)
})

https://github.com/alanshaw/ipfs-only-hash/blob/dbb72ccfff45ffca5fbea6a7b1704222f6aa4354/test.js#L21-L33

我是IPFS桌面的维护者之一,在后台,该应用程序在http api上调用本地IPFS守护程序的ipfs.add

通过 API 手动添加或散列文件时,可以选择更改文件分块的方式、这些块如何链接在一起以及块的哈希方式。如果任何选项值不同,则生成的哈希和包含它的 CID 也将不同,即使输入文件相同也是如此。

您可以尝试这些选项,并在此处查看生成的 DAG(有向无环图(结构的可视化:https://dag.ipfs.io/

要深入了解IPFS块和哈希文件,您可以看到ipfs-only-hash的作者和js-ipfs维护者在这里解释它 https://www.youtube.com/watch?v=Z5zNPwMDYGg

为了后代的利益,以下是将通过fetch下载的图像CID与从ipfs-desktop为同一图像生成的CID匹配的方法(作为本地驱动器中的文件添加(。您必须删除附加到图像 base64string 前面的前缀data:*/*;base64,,并将该字符串解码为缓冲区数组。然后你会得到匹配的 CID。

async testHashes() {
const url = "https://raw.githubusercontent.com/IanPhilips/jst-cids-test/master/src/23196210.jpg";
fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob)
})).then(async dataUrl =>{
const strData = dataUrl as string;
// remove "data:*/*;base64," from dataUrl
const endOfPrefix = strData.indexOf(",");
const cleanStrData = strData.slice(endOfPrefix+1);
const data = Buffer.from(cleanStrData, "base64");
const hash = await Hash.of(data);
console.log("fetch data CID: " + hash); // QmYHzA8euDgUpNy3fh7JRwpPwt6jCgF35YTutYkyGGyr8f
});
console.log("ipfs-desktop CID: QmYHzA8euDgUpNy3fh7JRwpPwt6jCgF35YTutYkyGGyr8f");
}

最新更新