nwaku/waku/v2/utils/peers.nim
Sanaz Taheri Boshrooyeh a41b9ac80b
Refactor waku protocols and utils (#667)
* refactors waku_filter

* refactors waku_lightpush

* refactors waku_swap

* refactor namespacing.nim

* refactor peers

* refactors requests

* adds top level {.push raises: [Defect].}

* log scope for rln relay

* cleans up comments

* removes comments

* comments out raise Defect

* defines temp var then pass to constructor

* Update waku/v2/protocol/waku_rln_relay/rln.nim

Co-authored-by: oskarth <ot@oskarthoren.com>

* Update waku/v2/protocol/waku_swap/waku_swap.nim

Co-authored-by: oskarth <ot@oskarthoren.com>

* explains the potential exception in waku_swap

* creates temp var before return

* adjusts spaces

* adds line breaks, temp vars and fixes format

* removes type declaration

* fixes and indentation issue

* adjusts spacing

* adjusts line <80ch

* formating improvement

Co-authored-by: oskarth <ot@oskarthoren.com>
2021-07-15 11:25:52 -07:00

43 lines
1.4 KiB
Nim

{.push raises: [Defect].}
# Collection of utilities related to Waku peers
import
std/strutils,
libp2p/multiaddress,
libp2p/peerinfo
proc initAddress(T: type MultiAddress, str: string): T {.raises: [Defect, ValueError, LPError].}=
# @TODO: Rather than raising exceptions, this should return a Result
let address = MultiAddress.init(str).tryGet()
if IPFS.match(address) and matchPartial(multiaddress.TCP, address):
return address
else:
raise newException(ValueError,
"Invalid bootstrap node multi-address")
## Parses a fully qualified peer multiaddr, in the
## format `(ip4|ip6)/tcp/p2p`, into dialable PeerInfo
proc parsePeerInfo*(address: string): PeerInfo {.raises: [Defect, ValueError, LPError].}=
let multiAddr = MultiAddress.initAddress(address)
var
ipPart, tcpPart, p2pPart: MultiAddress
for addrPart in multiAddr.items():
case addrPart[].protoName()[]
of "ip4", "ip6":
ipPart = addrPart.tryGet()
of "tcp":
tcpPart = addrPart.tryGet()
of "p2p":
p2pPart = addrPart.tryGet()
# nim-libp2p dialing requires remote peers to be initialised with a peerId and a wire address
let
peerIdStr = p2pPart.toString()[].split("/")[^1]
wireAddr = ipPart & tcpPart
if (not wireAddr.isWire()):
raise newException(ValueError, "Invalid node multi-address")
return PeerInfo.init(peerIdStr, [wireAddr])