nim-libp2p/libp2p/peerinfo.nim

79 lines
2.0 KiB
Nim
Raw Normal View History

## Nim-LibP2P
2019-09-24 17:48:23 +00:00
## Copyright (c) 2019 Status Research & Development GmbH
## Licensed under either of
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
## at your option.
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
import std/[options, sequtils, hashes]
import pkg/[chronos, chronicles, stew/results]
import peerid, multiaddress, crypto/crypto, routing_record, errors
export peerid, multiaddress, crypto, routing_record, errors, results
## Our local peer info
type
PeerInfoError* = LPError
PeerInfo* = ref object
2021-12-16 10:05:20 +00:00
peerId*: PeerId
addrs*: seq[MultiAddress]
protocols*: seq[string]
2020-06-09 18:42:52 +00:00
protoVersion*: string
agentVersion*: string
privateKey*: PrivateKey
publicKey*: PublicKey
signedPeerRecord*: Option[Envelope]
func shortLog*(p: PeerInfo): auto =
2020-06-09 18:42:52 +00:00
(
peerId: $p.peerId,
2020-06-09 18:42:52 +00:00
addrs: mapIt(p.addrs, $it),
protocols: mapIt(p.protocols, $it),
protoVersion: p.protoVersion,
agentVersion: p.agentVersion,
)
chronicles.formatIt(PeerInfo): shortLog(it)
proc new*(
p: typedesc[PeerInfo],
key: PrivateKey,
2021-12-16 10:05:20 +00:00
addrs: openArray[MultiAddress] = [],
protocols: openArray[string] = [],
protoVersion: string = "",
agentVersion: string = ""): PeerInfo
{.raises: [Defect, PeerInfoError].} =
let pubkey = try:
key.getPublicKey().tryGet()
except CatchableError:
raise newException(PeerInfoError, "invalid private key")
let peerId = PeerID.init(key).tryGet()
let sprRes = SignedPeerRecord.init(
key,
PeerRecord.init(peerId, @addrs)
)
let spr = if sprRes.isOk:
some(sprRes.get().envelope)
else:
none(Envelope)
let peerInfo = PeerInfo(
peerId: peerId,
publicKey: pubkey,
privateKey: key,
protoVersion: protoVersion,
agentVersion: agentVersion,
addrs: @addrs,
protocols: @protocols,
signedPeerRecord: spr)
return peerInfo