【p2p、分布式,区块链笔记 IPFS】网关+多地址+HTTP RPC API+kubo-rpc-client

目录

  • CG

  • 在 IPFS 中,网关是提供公共访问接口的服务器,它们允许你通过 HTTP 协议访问 IPFS 网络中的内容,通常形式为 http://<gateway>/ipfs/<cid> 。网关扮演着桥梁的角色,其通过提供传统 HTTP 协议的入口,使得非 IPFS 用户也能够方便地访问存储在 IPFS 上的文件和数据。gateway为多地址(multiaddress)形式。

multiaddr API 多地址

  • IPFS 节点使用多地址(multiaddress)来指定不同的通信协议和网络层。
  • IPFS 支持多种类型的多地址(multiaddr)格式,支持多种协议(如 https, http, ws, wss 等),以及不同类型的连接方式(如通过 DNS、IP 地址、WebSocket 等)。例如:
    • DNS 地址 :/dns4/{hostname}/https/

    • IP 地址 :/ip4/{ip}/tcp/{port}

      • 例如:/ip4/192.168.1.100/tcp/5001,表示连接到 IP 地址 192.168.1.100 上的 IPFS 节点,使用 TCP 协议和 5001 端口。
    • WebSocket 连接 :/ip4/{ip}/tcp/{port}/ws

      • 如果你使用 WebSocket 协议与节点通信,可以使用这样的地址,例如 /ip4/127.0.0.1/tcp/5001/ws。
    • IPv6 地址 :/ip6/{ipv6_address}/tcp/{port}

      • 如果你希望通过 IPv6 地址连接到 IPFS 节点,可以使用类似 /ip6/2001:db8::/tcp/5001 这样的格式。

示例

  1. IPFS 提供商

    javascript 复制代码
    const API_MULTIADDR = "/dns4/ipfs.io/https/"; // 使用 ipfs.io 作为网关
    // 有些提供商(如 Pinata、Fleek、Infura 等)提供了专用的 IPFS API 端点:
    const API_MULTIADDR = "/dns4/ipfs.infura.io/https/";  // Infura 网关
    const API_MULTIADDR = "/dns4/ipfs.pinata.cloud/https/"; // Pinata 网关
  2. 使用本地运行的 IPFS 节点

    javascript 复制代码
    const API_MULTIADDR = "/ip4/127.0.0.1/tcp/5001"; // 本地节点
  3. 使用 WebSocket 连接

    javascript 复制代码
    const API_MULTIADDR = "/ip4/127.0.0.1/tcp/5001/ws"; // WebSocket 连接

kubo-rpc-client

  • 当 Kubo IPFS 节点作为守护进程运行时,它会公开一个 HTTP RPC API,kubo-rpc-client(npm i kubo-rpc-client)用于连接RPC API的服务地址,允许您控制节点并运行与命令行相同的命令。

连接服务 create(options)

cpp 复制代码
import { create } from 'kubo-rpc-client'

// connect to ipfs daemon API server
const ipfs = create('http://localhost:5001') // (the default in Node.js)

// or connect with multiaddr
const ipfs = create('/ip4/127.0.0.1/tcp/5001')

// or using options
const ipfs = create({ host: 'localhost', port: '5001', protocol: 'http' })

// or specifying a specific API path
const ipfs = create({ host: '1.1.1.1', port: '80', apiPath: '/ipfs/api/v0' })

添加数据

cpp 复制代码
const { cid } = await client.add('Hello world!')

读取数据

cpp 复制代码
const chunks = [];
for await (const chunk of ipfs.cat(cidToFetch)) {
  chunks.push(chunk);
}
const allChunks = new Uint8Array(chunks.reduce((acc, chunk) => [...acc, ...chunk], []));
const content = new TextDecoder().decode(allChunks);
  • 读取的chunk为Uint8Array数据(8 位无符号整数数组),CID的数据太长会分片,示例:Uint8Array(10) 72, 69, 76, 76, 79, 87, 79, 82, 76, 68, buffer: ArrayBuffer(10), byteLength: 10, byteOffset: 0, length: 10, Symbol(Symbol.toStringTag): 'Uint8Array'

使用示例

nodejs

js 复制代码
// sudo apt update && sudo apt install -y nodejs npm
// https://codesandbox.io/examples/package/kubo-rpc-client
// https://codesandbox.io/p/sandbox/ipfs-upload-and-fetch-v8-4cggs3
import { randomBytes } from "crypto";
import { create } from "kubo-rpc-client";

const DATA_SIZE = 512001;

//const DATA_SIZE = 1860000;
const API_MULTIADDR = "/dns4/ipfs-upload.v8-bellecour.iex.ec/https/";

const GATEWAYS = ["https://ipfs-gateway.v8-bellecour.iex.ec"];

const upload = async () => {
  try {
    const ipfs = create(API_MULTIADDR);
    const buffer = randomBytes(DATA_SIZE);
    console.log(`adding ${buffer.length} random bytes`);
    const result = await ipfs.add(buffer);
    console.log(`ipfs add ok`);
    const { cid } = result;
    console.log(`added ${cid.toString()}`);

    await Promise.all(
      GATEWAYS.map((gateway) =>
        fetch(`${gateway}/ipfs/${cid.toString()}`)
          .then((res) => {
            if (!res.ok) {
              throw Error(`${gateway} bad response: ${res.status}`);
            } else {
              console.log(`found ${cid.toString()} on ${gateway}`);
            }
          })
          .catch((e) => console.error(e.message))
      )
    );
  } catch (e) {
    console.error(e.message);
  }
};

const upload_cid = async () => {
  try {
    const { cid } = "QmWp48QrabA75rUF86iEkiEMLq222YiE37D76gTtoJocxS";
    console.log(`try to download ${cid}`);

    await Promise.all(
      GATEWAYS.map((gateway) =>
        fetch(`${gateway}/ipfs/${cid}`)
          .then((res) => {
            if (!res.ok) {
              throw Error(`${gateway} bad response: ${res.status}`);
            } else {
              console.log(`found ${cid.toString()} on ${gateway}`);
            }
          })
          .catch((e) => console.error(e.message))
      )
    );
  } catch (e) {
    console.error(e.message);
  }
};

const button = document.getElementById("upload-button");
const button2 = document.getElementById("upload-cid");

button.addEventListener("click", () => upload());
button2.addEventListener("click", () => upload());

button.disabled = false;
button2.disabled = false;

浏览器直接使用

复制代码
<script src="https://unpkg.com/kubo-rpc-client/dist/index.min.js"></script> // https://github.com/ipfs/js-kubo-rpc-client

CG

相关推荐
starzy19901 天前
Structured Streaming Kafka Sink:写出一条生产级的回流链路
大数据·分布式·spark·kafka
国科安芯1 天前
编队不是多放几颗星:分布式雷达与编队飞行任务中星内协同网络的确定性时序
网络·分布式·fpga开发·架构·低轨卫星·抗辐射
AllData公司负责人2 天前
实战一:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 File 到 Doris 高效数据同步链路,批量文件离线入仓
数据库·人工智能·分布式·大模型·数据传输·数据同步·连接器
starzy19903 天前
Structured Streaming 集成 Kafka 实现:读写路径、位点语义与生产调优
大数据·分布式·spark·kafka
真上帝的左手3 天前
30. 技术专题-‌应用框架组件-消息队列
分布式·中间件·消息队列·系统架构·mq
业余程序员plus4 天前
NCCL-AllReduce-P2P 与 NET(GDR)数据传输过程分析 (八)
p2p·tree·流量控制·nccl·ring·allreduce·gpudirect rdma
真上帝的左手4 天前
31. 占位-14
分布式·spring cloud·架构·系统架构
TiDB 社区干货传送门4 天前
当向量走向百亿规模:平凯数据库对下一代分布式向量索引的探索
数据库·分布式
starzy19904 天前
Structured Streaming Sink 种类与案例:选错输出端,前面全白干
大数据·分布式·spark
Lansonli5 天前
大数据Spark(九十三):Spark HistoryServer
大数据·分布式·spark