p2p、分布式,区块链笔记:基于IPFS实现的数据库orbitdb笔记

orbitdb

特性说明
特点无服务器、分布式、p2p
编程语言JavaScript
对其他语言的支持A python client for the Orbitdb HTTP APIgo-orbit-db让我们了解一下谁在使用 js-ipfs!
是否为区块链不是区块链。使用强最终一致性模型,而非强一致性模型。
许可MIT 软件许可证
支持的数据库类型事件、文件、键/值、索引键/值
底层分布式数据结构无冲突复制数据类型 (CRDT)。IPFS pubsub协议自动使各对等方的数据库保持最新。https://www.zxch3n.com/crdt-intro/crdt-intro/

安装

node命令

$ npm init --yes # use npm defaults, you can edit this later
$ npm install @orbitdb/core helia
# 这是老版本的安装方式 $ npm install --save orbit-db ipfs     # --save 选项的作用是将安装的包添加到 package.json 文件的 dependencies 部分。在较新的 npm 版本中(从 npm 5.0.0 开始),--save 选项是默认的
# Helia 是一种精简、模块化和现代的 IPFS TypeScript 实现,适用于多产的 JS 和浏览器环境。https://helia.io/

cdn方式安装

  • OrbitDB 可以使用带有 tag 的分布式 js 文件在浏览器中加载<script>/path/to/orbitdb.min.js</script>
<script src="https://unpkg.com/ipfs@0.55.1/dist/index.min.js"></script>
<script src="https://unpkg.com/orbit-db@0.26.1/dist/orbitdb.min.js"></script>

创建数据库示例代码

安装所需的依赖

npm install helia @orbitdb/core @chainsafe/libp2p-gossipsub @libp2p/identify libp2p

确保 Node.js 支持 ES 模块

  • import 是 ES6(ECMAScript 2015)引入的模块导入语法,用于从一个模块中引入特定的功能、对象或变量。

  • type: "module" 是在 package.json 文件或 HTML 文件中指定 JavaScript 模块的方式。它告诉 JavaScript 引擎这个文件或所有相关文件应该被当作 ES6 模块来处理。

  • 在 Node.js 项目中,可在 package.json 文件中指定 "type": "module",这样就可以在项目中使用 ES6 模块语法(即 importexport,importexport 是 ES6 模块系统的核心,实现在不同的 JavaScript 文件中共享代码。)。

  • 打开 package.json 文件,添加 "type": "module"

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "helia": "^0.1.0",
    "@orbitdb/core": "^0.1.0",
    "@chainsafe/libp2p-gossipsub": "^0.1.0",
    "@libp2p/identify": "^0.1.0",
    "libp2p": "^0.1.0"
  }
}

创建 JavaScript 文件 index.js

// index.js
import { createHelia } from 'helia';
import { createOrbitDB } from '@orbitdb/core';
import { gossipsub } from '@chainsafe/libp2p-gossipsub';
import { identify } from '@libp2p/identify';
import { createLibp2p } from 'libp2p';

const Libp2pOptions = {
  services: {
    pubsub: gossipsub({
      // necessary to run a single peer
      allowPublishToZeroTopicPeers: true
    }),
    identify: identify()
  }
};

(async function () {
  const libp2p = await createLibp2p({ ...Libp2pOptions });
  const ipfs = await createHelia({ libp2p });
  const orbitdb = await createOrbitDB({ ipfs });

  // Create / Open a database. Defaults to db type "events".  events类型的数据库定义详见https://github.com/orbitdb/orbitdb/blob/main/src/databases/events.js
  const db = await orbitdb.open('hello');

  const address = db.address;
  console.log(address);
  // "/orbitdb/zdpuAkstgbTVGHQmMi5TC84auhJ8rL5qoaNEtXo2d5PHXs2To"
  // The above address can be used on another peer to open the same database

  // Listen for updates from peers,任何更新都会触发此监听函数,再运行“Add an entry”部分时会触发
  db.events.on('update', async entry => {
    console.log(entry);
    const all = await db.all();
    console.log(all);
  });

  // Add an entry
  const hash = await db.add('world');
  console.log(hash);

  // Query
  for await (const record of db.iterator()) {
    console.log(record);
  }

  await db.close();
  await orbitdb.stop();
  await ipfs.stop();
})();

自定义events类型的数据库

  • 数据库类型 Events,它继承了 Database 并实现了 OrbitDB 数据库接口。下面是功能总结:

    • add: 将一个事件添加到数据库中,并返回该事件的哈希值。
    • get: 根据给定的哈希值从数据库中获取事件的值。
    • iterator: 异步生成器函数,用于迭代事件。支持多种过滤条件(如哈希值范围和结果数量)。
    • all: 返回所有事件的数组,事件以哈希/值对的形式存储(通过iterator实现)。

运行代码:在终端中运行node index.js

运行结果

在这里插入图片描述

PS C:\Users\kingchuxing\Documents\IPFS\orbitdb_enent> node index.js
## console.log(address);的输出
/orbitdb/zdpuB3GgA87irrdJDyvrNvwDNTwQLRxXNWoLrioDEjNeiYvC4

## Listen for updates from peers 部分的输出
{
  id: '/orbitdb/zdpuB3GgA87irrdJDyvrNvwDNTwQLRxXNWoLrioDEjNeiYvC4',
  payload: { op: 'ADD', key: null, value: 'world' },
  next: [],
  refs: [],
  clock: {
    id: '021c0174efab4162111ef8c77df934dbdb767cc96449fad014b46cdd9033a53ea1',
    time: 1
  },
  v: 2,
  key: '021c0174efab4162111ef8c77df934dbdb767cc96449fad014b46cdd9033a53ea1',
  identity: 'zdpuApdyQ1Nfunra16qqtALnLb8KkPGxWeoMDZyXrKQij1QtT',
  sig: '3045022100a5166de55326728dd33fccc770fcc117324f02a62e41d4217050af9ecba895ec02202927783b54c79146809351b58d3dba4d9c99fcfc294f1a261cbe3607435d41f9',
  hash: 'zdpuAkydAnMRxSiyqHaXJgngdpXQK1HYWWNqRiqMtU273GZSe',
  bytes: Uint8Array(476) [
    169,  97, 118,   2,  98, 105, 100, 120,  58,  47, 111, 114,
     98, 105, 116, 100,  98,  47, 122, 100, 112, 117,  66,  51,
     71, 103,  65,  56,  55, 105, 114, 114, 100,  74,  68, 121,
    118, 114,  78, 118, 119,  68,  78,  84, 119,  81,  76,  82,
    120,  88,  78,  87, 111,  76, 114, 105, 111,  68,  69, 106,
     78, 101, 105,  89, 118,  67,  52,  99, 107, 101, 121, 120,
     66,  48,  50,  49,  99,  48,  49,  55,  52, 101, 102,  97,
     98,  52,  49,  54,  50,  49,  49,  49, 101, 102,  56,  99,
     55,  55, 100, 102,
    ... 376 more items
  ]
}

## console.log(hash); 的输出
zdpuAkydAnMRxSiyqHaXJgngdpXQK1HYWWNqRiqMtU273GZSe
[
  {
    hash: 'zdpuAkydAnMRxSiyqHaXJgngdpXQK1HYWWNqRiqMtU273GZSe',
    value: 'world'
  }
]
## console.log(record) 的输出
{
  hash: 'zdpuAkydAnMRxSiyqHaXJgngdpXQK1HYWWNqRiqMtU273GZSe',
  value: 'world'
}
PS C:\Users\kingchuxing\Documents\IPFS\orbitdb_enent>

CG

  • 在 HTML 文件中,可通过 type="module" 属性来指定一个 <script> 标签内的 JavaScript 代码是ES模块代码。
<script type="module">
  import { myFunction } from './myModule.js';
  myFunction();
</script>
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值