D 的个人博客

但行好事莫问前程

  menu
417 文章
3446695 浏览
5 当前访客
ღゝ◡╹)ノ❤️

IPFS 数据链接与内容寻址

本文翻译自 IPFS 社区教程 ProtoSchool。ProtoSchool 是一个可以交互式学习 IPFS 编程的网站,涉及代码的部分大家可到该网站上直接运行测试!

本文将介绍如何在对等节点上创建和获取可验证的数据链接。

LESSION 1 - 创建节点并返回内容标识符(CID)

在本教程中,我们将探索 IPFS DAG API,它允许我们将数据对象存储在 IPFS 中,你可以在 IPFS 中存储一些令人兴奋的东西,比如你最喜欢的小猫的 GIF。

你可以将数据对象作为参数传入 ipfs.dag.put 方法来创建新节点,该方法返回新创建的节点的内容标识符(CID)。

1ipfs.dag.put({ hello: 'world' })

CID 是 IPFS 中从其内容生成的数据地址。每当有人将相同的 {hello:'world'} 数据放入 IPFS 时,他们将获得与你获得的相同的 CID。 如果他们改为输入 {hell0:'w0rld'},则 CID 会有所不同。

如下示例代码将创建 { test: 1 } 节点并返回其 CID:

1const run = async () => {
2  let cid = await ipfs.dag.put({ test: 1 })
3  return cid
4}
5
6return run

LESSION 2 - 链接到已有节点

有向无环图(DAG)的一个重要特性就是可以相互链接。链接的方式就是存储相关节点的 CID。

例如一个节点存有一个 foo 指向另一个 CID 节点 barCid

1{
2  foo: barCid
3}

上述示例我们创建了一个 foo 字段并将其值链接到了另一个 CID,我们将其称之为 命名链接

我们可以将命名链接保存到 IPFS 中:

1await ipfs.dag.put({ foo: barCid })

如下示例代码将创建 { test: 1} 并将其命名为 bar 链接到新创建的节点上:

1const run = async () => {
2  let cid = await ipfs.dag.put({ test: 1 })
3  let cid2 = await ipfs.dag.put({ bar: cid })
4  return cid2
5}
6
7return run

LESSION 3 - 通过链接读取嵌套数据

我们可通过路径查询读取嵌套数据。

 1let cid = await ipfs.dag.put({
 2  my: {
 3    deep: {
 4      obj: 'is cool'
 5    }
 6  }
 7})
 8
 9console.log(await ipfs.dag.get(cid, '/my/deep/obj'))
10// prints { value: 'is cool', remainderPath: '' }

ipfs.dag.get 可 IPFS 路径进行查询,查询结果包含了结果值以及尚未解析的路径。我们可以通过该 API 进行遍历:

 1let cid = await ipfs.dag.put({ foo: 'bar' })
 2let cid2 = await ipfs.dag.put({
 3  my: {
 4    other: cid
 5  }
 6})
 7
 8console.log(await ipfs.dag.get(cid2, '/my/other/foo'))
 9// prints { value: 'bar', remainderPath: '' }
10
11// Notice above how this method returns not the value itself,
12// but an object that contains a `value` property

如下示例代码将返回 test 的值:

1const run = async () => {
2  let cid = await ipfs.dag.put({ test: 1 })
3  let cid2 = await ipfs.dag.put({ bar: cid })
4  let cid3 = await ipfs.dag.get(cid2, '/bar/test')
5  return cid3.value
6}
7
8return run