如何从 JS libp2p/kad-dht 分布式哈希表中检索数据?

问题描述 投票:0回答:1

我希望你一切都好。 我创建了一个 Kademlia 哈希表来存储网络上节点之间的内容。 使用

get
方法时,我得到
AsyncIterable<QueryEvent>

有人可以提供一个如何从

QueryEvent
中提取数据的示例吗?

这就是我认为可行的方法:

const extractDHTValue = async (res) => {
    let finalValue = null;

    for await (const event of res) {
        if (event.name === 'VALUE' && event.record) {
            // Extract the value from the record
            const value = uint8ArrayToString(event.record.value);
            console.log('DHT Record Value:', value);
            finalValue = value;
        }
    }

    if (finalValue === null) {
        console.log('No value found in the DHT query response.');
    }

    return finalValue;
};

不幸的是我没有得到任何价值。

顺便说一句,这就是我在 DHT 上保存数据的方式:

import { createLibp2p } from 'libp2p';
import { tcp } from '@libp2p/tcp';
import { noise } from '@chainsafe/libp2p-noise';
import { stdinToStream, streamToConsole } from './stream.js';
import { yamux } from '@chainsafe/libp2p-yamux';
import { pipe } from 'it-pipe';
import { kadDHT } from '@libp2p/kad-dht';
import { identify, identifyPush } from '@libp2p/identify';
import { fromString as uint8fromString } from 'uint8arrays/from-string';

const start_server = async () => {
    const node = await createLibp2p({
        addresses: {
            listen: ["/ip4/0.0.0.0/tcp/10333"]
        },
        transports: [
            tcp()
        ],
        streamMuxers: [
            yamux()
        ],
        connectionEncrypters: [
            noise()
        ],
        contentRouters: [
            kadDHT()
        ],
        services: {
            identify: identify(),
            dht: kadDHT()
        }
    });

    // await node.start();
    node.addEventListener('peer:connect', (evt) => {
        console.log("New peer connected", evt);
        // const remotePeer = evt.details;
        // console.log('Connection established to:', remotePeer.toString());
    })

    await node.handle('/chat/1.0.0', async ({ stream }) => {
        console.log("New stream of chat protocol");
        stdinToStream(stream);
        streamToConsole(stream);

        // SAVING DUMB DATA HERE 
        await node.services.dht.put(uint8fromString('hello'), uint8fromString('world'));
        // CAN I READ THE DATA HERE TOO ?

        
    });

    node.getMultiaddrs().forEach((ma) => {
        console.log('Listening on:', ma.toString());
    });

    console.log('Node started!');
}

start_server();

javascript typescript p2p kademlia libp2p
1个回答
0
投票

我已经使用

it-last
和 last() 函数解决了这个问题。

import { toString as uint8toString } from 'uint8arrays';

// Some code

const extractDHTValue = async (res) => {
    
    let final_res = await last(res);
    let finalValue = final_res.value;
    // Will get a Uint8Array 
    // parse it back to string using to `toString` from `uint8arrays`
    
    return uint8toString(finalValue);
};
© www.soinside.com 2019 - 2024. All rights reserved.