dep2p

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2024 License: MIT Imports: 60 Imported by: 7

README

flow diagram

DeP2P

Go Reference Go

DeP2P(Decentralized peer-to-peer) 去中心化对等网络,是用 Go(golang)编写的一种 P2P 对等网络的便捷实现。

该项目目前正在积极开发中,处于 Beta 状态。

这是 libp2p 库的 Go 升级版。libp2p 是一个模块化网络框架,由 BPFS 进行了一些额外的优化,意在提升 P2P 的便捷性。

libp2p 是互联网过去所有点对点协议的集大成之作。由于 libp2p 源于 IPFS 。所以,在其协议内部或多或少的与 IPFS 进行了一些强捆绑。另外,libp2p 作为一个"网络堆栈",在网络协议中不可避免的使用了"内容存储",这成为了非"存储"项目的累赘。

DeP2P 干净的分离了 IPFS 代码,并对"内容存储"等内容进行删减。同时,将 Kademlia DHTPubSub 集成后统一配置和调用。有助于 Web3 项目的快速实施和可靠运行。

对于大多数用户来说,并不关心 Kademlia、Discovery、PubSub 等专有技术,甚至用户完全不需要理会这个分布式网络的具体过程。用户所需要的:

  1. 加入网络成为其中的一个节点;
  2. 从网络中发现更多的节点;
  3. 连接节点;
  4. 使用 "流" 或 "订阅" 模式发送/接收消息。

基于用户上述真实需求,DeP2P 依托成熟的网络模块,构建"友好"、"健壮"、"专注"的去中心化网络基础设施,将用户从繁杂的网络开发中解放出来,以便其更好的专注于业务应用。

了解有关 DeP2P 的更多信息,请访问 bpfs.xyz

要求

Go 1.20 或最新版本.

安装

要获取包,请使用标准:


    go get -u github.com/bpfs/dep2p

推荐使用 Go 模块。

用法

本节假设您具有 Go(golang)编码的基础知识。

该包执行 P2P 去中心化网络的配置和通信。因此使用起来也比较简单。

前置

首先,您需要使用 NewDeP2P 创建新的 DeP2P 实例。虽然您可以使用默认的配置运行网络,但我们依然强烈建议您对相关参数进行配置。当然,这很大程度上取决于您的使用场景。不过您放心,文后我们会附上可直接运行的配置供您修改。


    func dep2p.NewDeP2P(ctx context.Context, opts ...dep2p.OptionDeP2P) (*dep2p.DeP2P, error)

然后,如果您需要使用"订阅"模式传递消息,还需要使用 NewDeP2PPubSub 创建新的 DeP2P 主题。


    func NewDeP2PPubSub(ctx context.Context, p2p *dep2p.DeP2P) (*pubsub.DeP2PPubSub, error)

现在,您的网络应该已经正常运行了。接下来,我们开始准备发送和接收信息。

注册

首先,我们需要进行"注册",以便让节点知道您将使用那个方法来接收消息。

a. 下面是对"流"的注册,通俗的讲就是将消息从 节点① 发送给 节点② ,并可接收 节点② 回复的信息。


    func streams.RegisterStreamHandler(h host.Host, p protocol.ID, handler network.StreamHandler)

b. 下面是对"订阅"的注册,通俗的讲就是 "群" 消息,由有限个节点组建一个群(或通道),您可以将消息发给群所有节点或其中的某个节点。当然,您也可以设置让部分群节点,只能发送消息,不允许其接收(这在某些应用场景非常有意义)。


    func (*pubsub.DeP2PPubSub).SubscribeWithTopic(topic string, handler pubsub.PubSubMsgHandler, subscribe bool) error

系统设计时,您可以根据不同的通信需求,针对 "流" 和 "订阅" 设置不同的 "协议"。您可以将每个 "协议" 想象为城市(节点)间的网络:高速、国道、地铁、航线……

接下来,您只需要专注于 【发送】 和 【接收】 信息。

通信

a. 使用 NewStream 打开一个新流到给定的对等点 p,并使用给定的 ProtocolID 写入 p2p 协议标头。 如果没有到 p 的连接,则尝试创建一个。 这个协议需要是您在此前已经注册了的。


    func (host.Host).NewStream(ctx context.Context, p peer.ID, pids ...protocols.ID) (network.Stream, error)

接收该消息的是您在前面注册时的 'handler network.StreamHandler',下面是一个应用实例:

    import (
        "github.com/bpfs/dep2p"
        "github.com/bpfs/dep2p/streams"
    )

    // 流协议
    const (
        // 协议
        StreamExampleProtocol = "dep2p@stream:example/1.0.0"
    )

    type Input struct {
        fx.In
        Ctx          context.Context   
        P2P          *dep2p.DeP2P   
    }

    // RegisterStreamProtocol 注册流
    func RegisterStreamProtocol(lc fx.Lifecycle, input Input) {
        // 流协议
        sp := &StreamProtocol{
            ctx:          input.Ctx,
            p2p:          input.P2P,
        }

        // 注册流
        streams.RegisterStreamHandler(input.P2P.Host(), StreamExampleProtocol, streams.HandlerWithRW(sp.HandleStreamExampleStream))

        // 您可以按需继续注册其他流协议

        lc.Append(fx.Hook{
            OnStop: func(ctx context.Context) error {
                return nil
            },
        })
    }

    ////////////////////////////////////////////////////////////////

    // 流协议
    type StreamProtocol struct {
        ctx          context.Context         
        p2p          *dep2p.DeP2P        
    }

    // HandleStreamExampleStream 处理流消息
    func (sp *StreamProtocol) HandleStreamExampleStream(req *streams.RequestMessage, res *streams.ResponseMessage) error {
        // 省略处理逻辑
    }

b. 使用 BroadcastWithTopic 将消息广播到给定的主题。其中,可以指定主题中特别的某个节点。这个主题需要是您在此前已经注册了的。


    func (*pubsub.DeP2PPubSub).BroadcastWithTopic(topic string, data []byte) error

下面是构建 data 消息体的内容。其中,Payload 是您要传输的内容;而 Message 中的 Type 是您可自定义的类(便于您接收消息后处理);Sender 是发送方(通常为您自己);Receiver 是接收方(不设置的话,该通道内所有节点都可以接收到此消息)。

    type RequestMessage struct {
        Message              *Message `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
        Payload              []byte   `protobuf:"bytes,2,opt,name=payload,proto3" json:"payload,omitempty"`
        XXX_NoUnkeyedLiteral struct{} `json:"-"`
        XXX_unrecognized     []byte   `json:"-"`
        XXX_sizecache        int32    `json:"-"`
    }

    type Message struct {
        Type                 string   `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
        Sender               string   `protobuf:"bytes,2,opt,name=sender,proto3" json:"sender,omitempty"`
        Receiver             string   `protobuf:"bytes,3,opt,name=receiver,proto3" json:"receiver,omitempty"`
        XXX_NoUnkeyedLiteral struct{} `json:"-"`
        XXX_unrecognized     []byte   `json:"-"`
        XXX_sizecache        int32    `json:"-"`
    }

接收该消息的是您在前面注册时的 'handler pubsub.PubSubMsgHandler',下面是一个应用实例:

    import (
        "github.com/bpfs/dep2p"
        "github.com/bpfs/dep2p/streams"
        "github.com/bpfs/dep2p/pubsub"
    )

    // 订阅主题
    const (
        PubsubExampleTopic = "dep2pe@pubsub:example/1.0.0"
    )

    type Input struct {
        fx.In
        Ctx          context.Context    
        P2P          *dep2p.DeP2P   
        PubSub       *pubsub.DeP2PPubSub 
    }

    // RegisterPubsubProtocol 注册订阅
    func RegisterPubsubProtocol(lc fx.Lifecycle, input Input) {
        // 主题
        if err := input.PubSub.SubscribeWithTopic(PubsubExampleTopic, func(res *streams.RequestMessage) {
            HandleExamplePubSub(input.P2P, input.PubSub, res)
        }, true); err != nil {
            logrus.Errorf("注册失败:%v \n", err)
        }

        // 您可以按需继续注册其他订阅协议
    
        lc.Append(fx.Hook{
            OnStop: func(ctx context.Context) error {
                return nil
            },
        })
    }

    ////////////////////////////////////////////////////////////////

    // HandleExamplePubSub 处理订阅消息
    func HandleExamplePubSub(p2p *dep2p.DeP2P, pubsub *pubsub.DeP2PPubSub, res *streams.RequestMessage) {
        // 省略处理逻辑
    }

文档

该文档正在编写中……

Documentation

Index

Constants

View Source
const (
	// DefaultTryTimes 是默认的尝试次数。最大超时时间为10分钟10秒。
	DefaultTryTimes = 15
	// DefaultTryTimesAfterMaxTime 是最大超时时间(90天)后的默认尝试次数。
	DefaultTryTimesAfterMaxTime = 6 * 24 * 90
)
View Source
const (
	// HandshakeProtocol 默认 dep2p 连接握手协议
	HandshakeProtocol = "/dep2p/handshake/1.0.0"
)

连接握手协议

Variables

View Source
var DefaultBootstrapPeers []multiaddr.Multiaddr

DefaultBootstrapPeers 是 libp2p 提供的一组公共 DHT 引导节点。

View Source
var LookupEventBufferSize = 16

LookupEventBufferSize 是要缓冲的事件数。

Functions

func GetDefaultBootstrapPeerAddrInfos

func GetDefaultBootstrapPeerAddrInfos() []peer.AddrInfo

GetDefaultBootstrapPeerAddrInfos 返回默认引导对等点的peer.AddrInfos,因此我们可以通过将它们传递给 BootstrapPeers(...) 选项来使用它们来初始化 DHT。

func NewTable

func NewTable(h host.Host) (table *kbucket.RoutingTable, err error)

新建路由表

func PublishLookupEvent

func PublishLookupEvent(ctx context.Context, ev *LookupEvent)

PublishLookupEvent 将查询事件发布到与给定上下文关联的查询事件通道(如果有)。

func RegisterForLookupEvents

func RegisterForLookupEvents(ctx context.Context) (context.Context, <-chan *LookupEvent)

RegisterForLookupEvents 使用给定的上下文注册查找事件通道。 返回的上下文可以传递给 DHT 查询以接收返回通道上的查找事件。

当调用者不再对查询事件感兴趣时,必须取消传递的上下文。

Types

type CPUInfo

type CPUInfo struct {
	CpuModel map[string]int32 // CPU信息
	CpuUsage float64          // 内存使用率
}

CPU信息

func GetCPUInfo

func GetCPUInfo() (*CPUInfo, error)

获取cpu信息

type ConnSupervisor

type ConnSupervisor struct {
	IsConnected bool // 是否有已连接到对等节点
	// contains filtered or unexported fields
}

ConnSupervisor 是一个连接监管器。

func (*ConnSupervisor) AddConn

func (cm *ConnSupervisor) AddConn(p peer.AddrInfo, connected bool, mode int, nodeInfo *NodeInfo)

AddConn 添加一个连接。

func (*ConnSupervisor) Connected

func (cm *ConnSupervisor) Connected(p peer.AddrInfo) bool

Connected 如果节点已连接,则返回true;否则返回false。

func (*ConnSupervisor) ConnectedAddrInfo

func (cm *ConnSupervisor) ConnectedAddrInfo() []peer.AddrInfo

ConnectedAddrInfo 返回连接到节点信息。

func (*ConnSupervisor) RemoveConn

func (cm *ConnSupervisor) RemoveConn(p peer.AddrInfo)

RemoveConn 移除一个连接。

type ContentRouting

type ContentRouting interface {
	// Provide 将给定的 cid 添加到内容路由系统中。如果传递了 'true',
	// 它还会宣布它,否则它只是保留在本地的对象提供的记账中。
	Provide(context.Context, cid.Cid, bool) error

	// 搜索能够提供给定键的对等方
	//
	// 当计数为0时,此方法将返回无限制数量的结果。
	FindProvidersAsync(context.Context, cid.Cid, int) <-chan peer.AddrInfo
}

ContentRouting 是一个值提供者的间接层。它用于找到谁拥有什么内容的信息。

内容由CID(内容标识符)标识,它以未来可证明的方式编码了被标识内容的哈希值。

type DeP2P

type DeP2P struct {
	// contains filtered or unexported fields
}

func NewDeP2P

func NewDeP2P(ctx context.Context, opts ...OptionDeP2P) (*DeP2P, error)

New 创建新的 DeP2P 实例

func (*DeP2P) ConnectPeer

func (bp *DeP2P) ConnectPeer() []peer.AddrInfo

DHT 返回分布式哈希表

func (*DeP2P) Context

func (bp *DeP2P) Context() context.Context

Context 返回上下文

func (*DeP2P) DHT

func (bp *DeP2P) DHT() *DeP2PDHT

DHT 返回分布式哈希表

func (*DeP2P) Host

func (bp *DeP2P) Host() host.Host

Host 返回 Host

func (*DeP2P) IsRunning

func (bp *DeP2P) IsRunning() bool

IsRunning 当 Libp2p 已启动时返回true;否则返回false。

func (*DeP2P) NodeInfo

func (bp *DeP2P) NodeInfo() *NodeInfo

NodeInfo 返回 节点信息

func (*DeP2P) Options

func (bp *DeP2P) Options() Options

Options 方法获取DeP2P 配置项

func (*DeP2P) RoutingTable

func (bp *DeP2P) RoutingTable(mode int) *kbucket.RoutingTable

RoutingTable 根据dht类型获取指定类型RoutingTable

func (*DeP2P) RoutingTables

func (bp *DeP2P) RoutingTables() map[int]*kbucket.RoutingTable

RoutingTables 返回 RoutingTables

func (*DeP2P) Start

func (bp *DeP2P) Start() error

Start 方法用于启动 Libp2p 主机。

func (*DeP2P) Stop

func (bp *DeP2P) Stop() error

Stop 方法用于停止 Libp2p 主机。

type DeP2PDHT

type DeP2PDHT struct {

	// Validator 是一个应该由记录验证器实现的接口。
	Validator record.Validator // 记录验证器
	// contains filtered or unexported fields
}

DeP2PDHT 是经过 S/Kademlia 修改的 Kademlia 实现。 它用于实现基本路由模块。

func New

func New(ctx context.Context, h host.Host, options ...Option) (*DeP2PDHT, error)

New 使用指定的主机和选项创建一个新的 DHT。 请注意,连接到 DHT 对等点并不一定意味着它也在 DHT 路由表中。 如果路由表具有超过"minRTRefreshThreshold"的对等点,则仅当我们成功从某个对等点获取查询响应或它向我们发送查询时,我们才会将其视为路由表候选者。

func (*DeP2PDHT) Bootstrap

func (dht *DeP2PDHT) Bootstrap(ctx context.Context) error

Bootstrap 告诉 DHT 进入满足 DeP2PRouter 接口的引导状态。

func (*DeP2PDHT) Close

func (dht *DeP2PDHT) Close() error

Close 调用 Process Close。

func (*DeP2PDHT) Context

func (dht *DeP2PDHT) Context() context.Context

Context 返回 DHT 的上下文。

func (*DeP2PDHT) FindProvidersAsync

func (dht *DeP2PDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo

FindProvidersAsync 与 FindProviders 方法相同,但返回一个通道。 对等节点将在找到时立即通过通道返回,即使搜索查询尚未完成。 如果 count 为零,则查询将一直运行,直到完成。 注意:不读取返回的通道可能会阻塞查询的进展。

func (*DeP2PDHT) ForceRefresh

func (dht *DeP2PDHT) ForceRefresh() <-chan error

ForceRefresh 行为类似于 RefreshRoutingTable,但强制 DHT 刷新路由表中的所有存储桶,无论上次刷新时间如何。

返回的通道将阻塞直到刷新完成,然后产生错误并关闭。 该通道已缓冲并且可以安全地忽略。

func (*DeP2PDHT) GetClosestPeers

func (dht *DeP2PDHT) GetClosestPeers(ctx context.Context, key string) ([]peer.ID, error)

GetClosestPeers 是一个 Kademlia 的 'node lookup' 操作。返回与给定键最接近的 K 个节点的通道。

如果上下文被取消,该函数将返回上下文错误以及迄今为止找到的最接近的 K 个节点。

func (*DeP2PDHT) Host

func (dht *DeP2PDHT) Host() host.Host

Host returns the libp2p host this DHT is operating with.

func (*DeP2PDHT) Mode

func (dht *DeP2PDHT) Mode() ModeOpt

Mode allows introspection of the operation mode of the DHT

func (*DeP2PDHT) PeerID

func (dht *DeP2PDHT) PeerID() peer.ID

PeerID 返回 DHT 节点的 Peer ID。

func (*DeP2PDHT) PeerKey

func (dht *DeP2PDHT) PeerKey() []byte

PeerKey 返回一个从 DHT 节点的 Peer ID 转换而来的 DHT 键。

func (*DeP2PDHT) Ping

func (dht *DeP2PDHT) Ping(ctx context.Context, p peer.ID) error

Ping 向传入的对等点发送 ping 消息并等待响应。

func (*DeP2PDHT) Provide

func (dht *DeP2PDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error)

Provide 使该节点宣布可以为给定的键提供值。

func (*DeP2PDHT) RefreshRoutingTable

func (dht *DeP2PDHT) RefreshRoutingTable() <-chan error

RefreshRoutingTable 告诉 DHT 刷新它的路由表。

返回的通道将阻塞直到刷新完成,然后产生错误并关闭。 该通道已缓冲并且可以安全地忽略。

func (*DeP2PDHT) RoutingTable

func (dht *DeP2PDHT) RoutingTable() *kb.RoutingTable

RoutingTable 返回 DHT 的路由表。

type DiskInfo

type DiskInfo struct {
	TotalSize           string  // 硬盘大小
	FreeSpace           string  // 剩余空间
	UsedSpace           string  // 已使用空间
	UsagePercent        float64 // 使用率
	HomeDirTotalSize    string  // 当前用户硬盘大小
	HomeDirFreeSpace    string  // 当前用户剩余空间
	HomeDirUsedSpace    string  // 当前用户已使用空间
	HomeDirUsagePercent float64 // 当前用户使用率
}

硬盘信息

type Handshake

type Handshake struct {
	ModeId   int       // 模式 1客户端2服务器
	NodeInfo *NodeInfo // 当前节点信息
}

握手协议

type KeyKadID

type KeyKadID struct {
	Key string
	Kad kbucket.ID
}

KeyKadID 包含字符串和二进制形式的 Kademlia 密钥。

func NewKeyKadID

func NewKeyKadID(k string) *KeyKadID

NewKeyKadID 从字符串 Kademlia ID 创建 KeyKadID。

type LookupEvent

type LookupEvent struct {
	// Node 是执行查找的节点的 ID。
	Node *PeerKadID
	// ID 是查找实例的唯一标识符。
	ID uuid.UUID
	// Key 是用作查找目标的 Kademlia 密钥。
	Key *KeyKadID
	// Request, 如果不为零,则描述与传出查询请求关联的状态更新事件。
	Request *LookupUpdateEvent
	// Response, 如果不为零,则描述与传出查询响应关联的状态更新事件。
	Response *LookupUpdateEvent
	// Terminate, 如果不为零,则描述终止事件。
	Terminate *LookupTerminateEvent
}

LookupEvent 为 DHT 查找期间发生的每个显着事件发出。 LookupEvent 支持 JSON 编组,因为它的所有字段都以递归方式支持。

func NewLookupEvent

func NewLookupEvent(
	node peer.ID,
	id uuid.UUID,
	key string,
	request *LookupUpdateEvent,
	response *LookupUpdateEvent,
	terminate *LookupTerminateEvent,
) *LookupEvent

NewLookupEvent 创建一个 LookupEvent,自动将节点 dep2p Peer ID 转换为 PeerKadID,并将字符串 Kademlia 键转换为 KeyKadID。

type LookupTerminateEvent

type LookupTerminateEvent struct {
	// Reason 是查找终止的原因。
	Reason LookupTerminationReason
}

LookupTerminateEvent 描述查找终止事件。

func NewLookupTerminateEvent

func NewLookupTerminateEvent(reason LookupTerminationReason) *LookupTerminateEvent

NewLookupTerminateEvent 创建一个具有给定原因的新查找终止事件。

type LookupTerminationReason

type LookupTerminationReason int

LookupTerminationReason 捕获终止查找的原因。

const (
	// LookupStopped 表示查找被用户的 stopFn 中止。
	LookupStopped LookupTerminationReason = iota
	// LookupCancelled 表示查找被上下文中止。
	LookupCancelled
	// LookupStarvation 表示查找由于缺少未查询的对等点而终止。
	LookupStarvation
	// LookupCompleted 表示查找成功终止,达到 Kademlia 结束条件。
	LookupCompleted
)

func (LookupTerminationReason) MarshalJSON

func (r LookupTerminationReason) MarshalJSON() ([]byte, error)

MarshalJSON 返回传递的查找终止原因的 JSON 编码。

func (LookupTerminationReason) String

func (r LookupTerminationReason) String() string

type LookupUpdateEvent

type LookupUpdateEvent struct {
	// Cause 是其响应(或缺乏响应)导致更新事件的对等方。
	// 如果 Cause 为零,则这是查找中的第一个更新事件,由播种引起。
	Cause *PeerKadID
	// Source 是向我们通报此更新中的对等 ID 的对等点(如下)。
	Source *PeerKadID
	// Heard 是一组对等体,其在查找对等体集中的状态被设置为“已听到”。
	Heard []*PeerKadID
	// Waiting 是一组对等体,其在查找对等体集中的状态被设置为“等待”。
	Waiting []*PeerKadID
	// Queried 是一组对等体,其在查找对等体集中的状态被设置为“已查询”。
	Queried []*PeerKadID
	// Unreachable 是一组对等体,其在查找对等体集中的状态被设置为“无法访问”。
	Unreachable []*PeerKadID
}

LookupUpdateEvent 描述查找状态更新事件。

func NewLookupUpdateEvent

func NewLookupUpdateEvent(
	cause peer.ID,
	source peer.ID,
	heard []peer.ID,
	waiting []peer.ID,
	queried []peer.ID,
	unreachable []peer.ID,
) *LookupUpdateEvent

NewLookupUpdateEvent 创建一个新的查找更新事件,自动将传递的对等 ID 转换为对等 Kad ID。

type MemoryInfo

type MemoryInfo struct {
	TotalMemory     string  // 内存总大小
	UsedMemory      string  // 已用大小
	AvailableMemory string  // 剩余大小
	MemoryUsage     float64 // 内存使用率
}

内存信息

func GetMemoryInfo

func GetMemoryInfo() (*MemoryInfo, error)

获取内存信息

type ModeOpt

type ModeOpt = dhtcfg.ModeOpt

ModeOpt 描述 dht 应以何种模式运行

const (
	// ModeAuto 利用通过事件总线发送的 EvtLocalReachabilityChanged 事件根据网络条件在客户端和服务器模式之间动态切换 DHT
	ModeAuto ModeOpt = iota
	// ModeClient DHT 仅作为客户端运行,它无法响应传入的查询
	ModeClient
	// ModeServer 将 DHT 作为服务器运行,它既可以发送查询,也可以响应查询
	ModeServer
	// ModeAutoServer 操作方式与 ModeAuto 相同,但在可达性未知时充当服务器
	ModeAutoServer
)

type NetworkInfo

type NetworkInfo struct {
	IspName             string  // 网络类型
	UpstreamBandwidth   float64 // 上行带宽
	DownstreamBandwidth float64 // 下行带宽
	NetworkStatus       string  // 网络状态
	LocalIPAddress      string  // 本地IP地址
	PublicAddress       string  // 公网IP地址
	MACAddress          string  // MAC地址
	Lat                 string  // 纬度
	Lon                 string  // 经度
}

网络信息

func GetNetworkInfo

func GetNetworkInfo() (*NetworkInfo, error)

获取网络信

type NodeInfo

type NodeInfo struct {
	HostNmae    string      // 主机名字
	OSName      string      // 主机系统
	DiskInfo    DiskInfo    // 硬盘信息
	NetworkInfo NetworkInfo // 网络信息
	CPUInfo     CPUInfo     // CPU信息
	MemoryInfo  MemoryInfo  // 内存信息
}

节点信息

func GetNodeInfo

func GetNodeInfo() *NodeInfo

type Option

type Option = dhtcfg.Option

func Mode

func Mode(m ModeOpt) Option

Mode 配置 DHT 运行的模式(客户端、服务器、自动)。

默认为自动模式。

type OptionDeP2P

type OptionDeP2P func(*DeP2P) error

Option 类型是一个函数,它接受一个 DeP2P 指针,并返回一个错误。它用于配置 DeP2P 结构体的选项。

func WithBootstrapsPeers

func WithBootstrapsPeers(bootstrapsPeers []string) OptionDeP2P

WithBootstrapsPeers 设置引导节点

func WithDhtOpts

func WithDhtOpts(option []Option) OptionDeP2P

WithDhtOpts 设置本地网络监听地址

func WithLibp2pOpts

func WithLibp2pOpts(Option []config.Option) OptionDeP2P

WithLibp2pOpts 设置本地网络监听地址

func WithRendezvousString

func WithRendezvousString(rendezvousString string) OptionDeP2P

WithRendezvousString 设置本地网络监听地址

type Options

type Options struct {
	Libp2pOpts       []config.Option // Option 是一个 libp2p 配置选项,可以提供给 libp2p 构造函数(`libp2p.New`)。
	DhtOpts          []Option        // Option 是一个 dht 配置选项,可以提供给 dht 构造函数(`dht.New`)
	BootstrapsPeers  []string        // 引导节点地址
	RendezvousString string          // 组名
	AddsBook         []string        // 地址簿
}

type PeerKadID

type PeerKadID struct {
	Peer peer.ID
	Kad  kbucket.ID
}

PeerKadID 包含一个 libp2p Peer ID 和一个二进制 Kademlia ID。

func NewPeerKadID

func NewPeerKadID(p peer.ID) *PeerKadID

NewPeerKadID 从 libp2p Peer ID 创建 PeerKadID。

func NewPeerKadIDSlice

func NewPeerKadIDSlice(p []peer.ID) []*PeerKadID

NewPeerKadIDSlice 从传递的 libp2p Peer ID 片段创建 PeerKadID 片段。

func OptPeerKadID

func OptPeerKadID(p peer.ID) *PeerKadID

OptPeerKadID 返回一个指向 PeerKadID 的指针,如果传递的 Peer ID 是它的默认值,则返回 nil。

type QueryFilterFunc

type QueryFilterFunc = dhtcfg.QueryFilterFunc

QueryFilterFunc 是在查询时考虑要拨号的对等点时应用的过滤器

type RouteTableFilterFunc

type RouteTableFilterFunc = dhtcfg.RouteTableFilterFunc

RouteTableFilterFunc 是在考虑要保留在本地路由表中的连接时应用的过滤器。

type RoutingDiscovery

type RoutingDiscovery struct {
	routing.ContentRouting
}

RoutingDiscovery 是使用 ContentRouting 的发现实现。 使用 SHA256 哈希将命名空间转换为 Cids。

func NewRoutingDiscovery

func NewRoutingDiscovery(router routing.ContentRouting) *RoutingDiscovery

func (*RoutingDiscovery) Advertise

func (d *RoutingDiscovery) Advertise(ctx context.Context, ns string, opts ...discovery.Option) (time.Duration, error)

func (*RoutingDiscovery) FindPeers

func (d *RoutingDiscovery) FindPeers(ctx context.Context, ns string, opts ...discovery.Option) (<-chan peer.AddrInfo, error)

Directories

Path Synopsis
Package core provides convenient access to foundational, central dep2p primitives via type aliases.
Package core provides convenient access to foundational, central dep2p primitives via type aliases.
connmgr
Package connmgr provides connection tracking and management interfaces for dep2p.
Package connmgr provides connection tracking and management interfaces for dep2p.
crypto
Package crypto implements various cryptographic utilities used by dep2p.
Package crypto implements various cryptographic utilities used by dep2p.
discovery
Package discovery provides service advertisement and peer discovery interfaces for dep2p.
Package discovery provides service advertisement and peer discovery interfaces for dep2p.
event
Package event contains the abstractions for a local event bus, along with the standard events that dep2p subsystems may emit.
Package event contains the abstractions for a local event bus, along with the standard events that dep2p subsystems may emit.
host
Package host provides the core Host interface for dep2p.
Package host provides the core Host interface for dep2p.
metrics
Package metrics provides metrics collection and reporting interfaces for dep2p.
Package metrics provides metrics collection and reporting interfaces for dep2p.
network
Package network provides core networking abstractions for dep2p.
Package network provides core networking abstractions for dep2p.
network/mocks
Code generated by MockGen.
Code generated by MockGen.
peer
Package peer implements an object used to represent peers in the dep2p network.
Package peer implements an object used to represent peers in the dep2p network.
peerstore
Package peerstore provides types and interfaces for local storage of address information, metadata, and public key material about dep2p peers.
Package peerstore provides types and interfaces for local storage of address information, metadata, and public key material about dep2p peers.
pnet
Package pnet provides interfaces for private networking in dep2p.
Package pnet provides interfaces for private networking in dep2p.
protocol
Package protocol provides core interfaces for protocol routing and negotiation in dep2p.
Package protocol provides core interfaces for protocol routing and negotiation in dep2p.
routing
Package routing provides interfaces for peer routing and content routing in dep2p.
Package routing provides interfaces for peer routing and content routing in dep2p.
sec
Package sec provides secure connection and transport interfaces for dep2p.
Package sec provides secure connection and transport interfaces for dep2p.
sec/insecure
Package insecure provides an insecure, unencrypted implementation of the SecureConn and SecureTransport interfaces.
Package insecure provides an insecure, unencrypted implementation of the SecureConn and SecureTransport interfaces.
transport
Package transport provides the Transport interface, which represents the devices and network protocols used to send and receive data.
Package transport provides the Transport interface, which represents the devices and network protocols used to send and receive data.
net
Package kbucket implements a kademlia 'k-bucket' routing table.
Package kbucket implements a kademlia 'k-bucket' routing table.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL