nim-libp2p/tests/testidentify.nim

91 lines
3.2 KiB
Nim
Raw Normal View History

import unittest, options, bearssl
import chronos, strutils
import ../libp2p/[protocols/identify,
multiaddress,
peerinfo,
peerid,
stream/connection,
multistream,
2019-10-03 19:30:22 +00:00
transports/transport,
transports/tcptransport,
2019-10-03 19:30:22 +00:00
crypto/crypto]
import ./helpers
2019-08-30 05:16:30 +00:00
when defined(nimHasUsed): {.used.}
2019-08-30 05:16:30 +00:00
suite "Identify":
teardown:
checkTrackers()
asyncTest "handle identify message":
let ma: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0").tryGet()
let remoteSecKey = PrivateKey.random(ECDSA, rng[]).get()
let remotePeerInfo = PeerInfo.init(remoteSecKey,
[ma],
["/test/proto1/1.0.0",
"/test/proto2/1.0.0"])
var serverFut: Future[void]
let identifyProto1 = newIdentify(remotePeerInfo)
let msListen = newMultistream()
msListen.addHandler(IdentifyCodec, identifyProto1)
proc connHandler(conn: Connection): Future[void] {.async, gcsafe.} =
await msListen.handle(conn)
var transport1 = TcpTransport.init()
serverFut = await transport1.listen(ma, connHandler)
let msDial = newMultistream()
let transport2: TcpTransport = TcpTransport.init()
let conn = await transport2.dial(transport1.ma)
var peerInfo = PeerInfo.init(PrivateKey.random(ECDSA, rng[]).get(), [ma])
let identifyProto2 = newIdentify(peerInfo)
discard await msDial.select(conn, IdentifyCodec)
let id = await identifyProto2.identify(conn, remotePeerInfo)
check id.pubKey.get() == remoteSecKey.getKey().get()
check id.addrs[0] == ma
check id.protoVersion.get() == ProtoVersion
# check id.agentVersion.get() == AgentVersion
check id.protos == @["/test/proto1/1.0.0", "/test/proto2/1.0.0"]
await conn.close()
await transport1.close()
await serverFut
await transport2.close()
asyncTest "handle failed identify":
let ma = Multiaddress.init("/ip4/0.0.0.0/tcp/0").tryGet()
var remotePeerInfo = PeerInfo.init(PrivateKey.random(ECDSA, rng[]).get(), [ma])
let identifyProto1 = newIdentify(remotePeerInfo)
let msListen = newMultistream()
let done = newFuture[void]()
msListen.addHandler(IdentifyCodec, identifyProto1)
proc connHandler(conn: Connection): Future[void] {.async, gcsafe.} =
await msListen.handle(conn)
await conn.close()
done.complete()
let transport1: TcpTransport = TcpTransport.init()
asyncCheck transport1.listen(ma, connHandler)
2019-09-23 23:02:13 +00:00
let msDial = newMultistream()
let transport2: TcpTransport = TcpTransport.init()
let conn = await transport2.dial(transport1.ma)
var localPeerInfo = PeerInfo.init(PrivateKey.random(ECDSA, rng[]).get(), [ma])
let identifyProto2 = newIdentify(localPeerInfo)
expect IdentityNoMatchError:
try:
let pi2 = PeerInfo.init(PrivateKey.random(ECDSA, rng[]).get())
discard await msDial.select(conn, IdentifyCodec)
discard await identifyProto2.identify(conn, pi2)
finally:
await done.wait(5000.millis) # when no issues will not wait that long!
await conn.close()
await transport2.close()
await transport1.close()