Fix overflow problem.

Fix compilation warnings.
This commit is contained in:
cheatfate 2019-10-29 20:51:48 +02:00
parent 400218ba01
commit 833e8c9406
No known key found for this signature in database
GPG Key ID: 46ADD633A7201F95
32 changed files with 166 additions and 136 deletions

View File

@ -114,7 +114,7 @@ proc checkPublic(key: openarray[byte], curve: cint): uint32 =
var x = [0x00'u8, 0x01'u8] var x = [0x00'u8, 0x01'u8]
var impl = brEcGetDefault() var impl = brEcGetDefault()
var orderlen = 0 var orderlen = 0
var order = impl.order(curve, addr orderlen) discard impl.order(curve, addr orderlen)
result = impl.mul(cast[ptr cuchar](unsafeAddr ckey[0]), len(ckey), result = impl.mul(cast[ptr cuchar](unsafeAddr ckey[0]), len(ckey),
cast[ptr cuchar](addr x[0]), len(x), curve) cast[ptr cuchar](addr x[0]), len(x), curve)
@ -766,7 +766,6 @@ proc initRaw*(sig: var EcSignature, data: openarray[byte]): bool =
## or ``Sig521Length``. ## or ``Sig521Length``.
## ##
## Procedure returns ``true`` on success, ``false`` otherwise. ## Procedure returns ``true`` on success, ``false`` otherwise.
var curve: cint
let length = len(data) let length = len(data)
if (length == Sig256Length) or (length == Sig384Length) or if (length == Sig256Length) or (length == Sig384Length) or
(length == Sig521Length): (length == Sig521Length):
@ -815,7 +814,6 @@ proc scalarMul*(pub: EcPublicKey, sec: EcPrivateKey): EcPublicKey =
if pub.key.curve == sec.key.curve: if pub.key.curve == sec.key.curve:
var key = new EcPublicKey var key = new EcPublicKey
if key.copy(pub): if key.copy(pub):
var slength = cint(0)
let poffset = key.getOffset() let poffset = key.getOffset()
let soffset = sec.getOffset() let soffset = sec.getOffset()
if poffset >= 0 and soffset >= 0: if poffset >= 0 and soffset >= 0:
@ -840,7 +838,6 @@ proc toSecret*(pubkey: EcPublicKey, seckey: EcPrivateKey,
## for `secp384r1` and 66 bytes for `secp521r1`. ## for `secp384r1` and 66 bytes for `secp521r1`.
doAssert((not isNil(pubkey)) and (not isNil(seckey))) doAssert((not isNil(pubkey)) and (not isNil(seckey)))
var mult = scalarMul(pubkey, seckey) var mult = scalarMul(pubkey, seckey)
var length = 0
if not isNil(mult): if not isNil(mult):
if seckey.key.curve == BR_EC_SECP256R1: if seckey.key.curve == BR_EC_SECP256R1:
result = Secret256Length result = Secret256Length

View File

@ -472,7 +472,6 @@ proc read*(ab: var Asn1Buffer, field: var Asn1Field): Asn1Status =
tag, ttag, offset: int tag, ttag, offset: int
length, tlength: uint64 length, tlength: uint64
klass: Asn1Class klass: Asn1Class
res: Asn1Status
inclass: bool inclass: bool
inclass = false inclass = false

View File

@ -386,7 +386,6 @@ proc init*(key: var RsaPrivateKey, data: openarray[byte]): Asn1Status =
## Procedure returns ``Asn1Status``. ## Procedure returns ``Asn1Status``.
var var
field, rawn, rawpube, rawprie, rawp, rawq, rawdp, rawdq, rawiq: Asn1Field field, rawn, rawpube, rawprie, rawp, rawq, rawdp, rawdq, rawiq: Asn1Field
version: uint64
var ab = Asn1Buffer.init(data) var ab = Asn1Buffer.init(data)
result = ab.read(field) result = ab.read(field)
@ -484,7 +483,7 @@ proc init*(key: var RsaPublicKey, data: openarray[byte]): Asn1Status =
## ``data``. ## ``data``.
## ##
## Procedure returns ``Asn1Status``. ## Procedure returns ``Asn1Status``.
var field, rawn, rawe, oid: Asn1Field var field, rawn, rawe: Asn1Field
var ab = Asn1Buffer.init(data) var ab = Asn1Buffer.init(data)
result = ab.read(field) result = ab.read(field)

View File

@ -6,7 +6,6 @@
## at your option. ## at your option.
## This file may not be copied, modified, or distributed except according to ## This file may not be copied, modified, or distributed except according to
## those terms. ## those terms.
import strutils
import secp256k1, nimcrypto/sysrand, nimcrypto/utils, nimcrypto/hash, import secp256k1, nimcrypto/sysrand, nimcrypto/utils, nimcrypto/hash,
nimcrypto/sha2 nimcrypto/sha2
export sha2 export sha2
@ -268,10 +267,10 @@ proc toBytes*(key: SkPublicKey, data: var openarray[byte]): int =
var length = csize(len(data)) var length = csize(len(data))
result = SkRawPublicKeySize result = SkRawPublicKeySize
if len(data) >= SkRawPublicKeySize: if len(data) >= SkRawPublicKeySize:
let res = secp256k1_ec_pubkey_serialize(ctx.context, discard secp256k1_ec_pubkey_serialize(ctx.context,
cast[ptr cuchar](addr data[0]), cast[ptr cuchar](addr data[0]),
addr length, unsafeAddr key, addr length, unsafeAddr key,
SECP256K1_EC_COMPRESSED) SECP256K1_EC_COMPRESSED)
proc toBytes*(sig: SkSignature, data: var openarray[byte]): int = proc toBytes*(sig: SkSignature, data: var openarray[byte]): int =
## Serialize Secp256k1 `signature` ``sig`` to raw binary form and store it ## Serialize Secp256k1 `signature` ``sig`` to raw binary form and store it

View File

@ -572,7 +572,6 @@ proc `$`*(value: MultiAddress): string =
## Return string representation of MultiAddress ``value``. ## Return string representation of MultiAddress ``value``.
var header: uint64 var header: uint64
var vb = value var vb = value
var data = newSeq[byte]()
var parts = newSeq[string]() var parts = newSeq[string]()
var part: string var part: string
while true: while true:

View File

@ -11,7 +11,7 @@
## ##
## TODO: ## TODO:
## 1. base32z ## 1. base32z
import tables, strutils import tables
import base32, base58, base64 import base32, base58, base64
type type
@ -20,18 +20,14 @@ type
MultiBase* = object MultiBase* = object
MBDecoder = proc(inbytes: openarray[char],
outbytes: var openarray[byte],
outlen: var int): MultibaseStatus {.nimcall.}
MBEncoder = proc(inbytes: openarray[byte],
outbytes: var openarray[char],
outlen: var int): MultibaseStatus {.nimcall.}
MBCodeSize = proc(length: int): int {.nimcall.} MBCodeSize = proc(length: int): int {.nimcall.}
MBCodec = object MBCodec = object
code: char code: char
name: string name: string
encr: MBEncoder encr: proc(inbytes: openarray[byte],
outbytes: var openarray[char],
outlen: var int): MultibaseStatus {.nimcall.}
decr: proc(inbytes: openarray[char], decr: proc(inbytes: openarray[char],
outbytes: var openarray[byte], outbytes: var openarray[byte],
outlen: var int): MultibaseStatus {.nimcall.} outlen: var int): MultibaseStatus {.nimcall.}

View File

@ -16,7 +16,7 @@ import protobuf/minprotobuf
const const
maxInlineKeyLength* = 42 maxInlineKeyLength* = 42
# TODO: add proper on disc serialization # TODO: add proper on disc serialization
# using peer-id protobuf format # using peer-id protobuf format
type type
PeerID* = object PeerID* = object
@ -165,7 +165,6 @@ proc init*(t: typedesc[PeerID], pubkey: PublicKey): PeerID =
## Create new peer id from public key ``pubkey``. ## Create new peer id from public key ``pubkey``.
var pubraw = pubkey.getBytes() var pubraw = pubkey.getBytes()
var mh: MultiHash var mh: MultiHash
var codec: MultiCodec
if len(pubraw) <= maxInlineKeyLength: if len(pubraw) <= maxInlineKeyLength:
mh = MultiHash.digest("identity", pubraw) mh = MultiHash.digest("identity", pubraw)
else: else:

View File

@ -156,13 +156,13 @@ proc write*(pb: var ProtoBuffer, field: ProtoField) =
doAssert(pb.isEnough(8)) doAssert(pb.isEnough(8))
var value = cast[uint64](field.vfloat64) var value = cast[uint64](field.vfloat64)
pb.buffer[pb.offset] = byte(value and 0xFF'u32) pb.buffer[pb.offset] = byte(value and 0xFF'u32)
pb.buffer[pb.offset + 1] = byte((value shr 8) and 0xFF'u32) pb.buffer[pb.offset + 1] = byte((value shr 8) and 0xFF'u64)
pb.buffer[pb.offset + 2] = byte((value shr 16) and 0xFF'u32) pb.buffer[pb.offset + 2] = byte((value shr 16) and 0xFF'u64)
pb.buffer[pb.offset + 3] = byte((value shr 24) and 0xFF'u32) pb.buffer[pb.offset + 3] = byte((value shr 24) and 0xFF'u64)
pb.buffer[pb.offset + 4] = byte((value shr 32) and 0xFF'u32) pb.buffer[pb.offset + 4] = byte((value shr 32) and 0xFF'u64)
pb.buffer[pb.offset + 5] = byte((value shr 40) and 0xFF'u32) pb.buffer[pb.offset + 5] = byte((value shr 40) and 0xFF'u64)
pb.buffer[pb.offset + 6] = byte((value shr 48) and 0xFF'u32) pb.buffer[pb.offset + 6] = byte((value shr 48) and 0xFF'u64)
pb.buffer[pb.offset + 7] = byte((value shr 56) and 0xFF'u32) pb.buffer[pb.offset + 7] = byte((value shr 56) and 0xFF'u64)
pb.offset += 8 pb.offset += 8
of ProtoFieldKind.Fixed32: of ProtoFieldKind.Fixed32:
doAssert(pb.isEnough(4)) doAssert(pb.isEnough(4))
@ -196,17 +196,17 @@ proc finish*(pb: var ProtoBuffer) =
pb.offset = pos pb.offset = pos
elif WithUint32BeLength in pb.options: elif WithUint32BeLength in pb.options:
let size = uint(len(pb.buffer) - 4) let size = uint(len(pb.buffer) - 4)
pb.buffer[0] = byte((size shr 24) and 0xFF) pb.buffer[0] = byte((size shr 24) and 0xFF'u)
pb.buffer[1] = byte((size shr 16) and 0xFF) pb.buffer[1] = byte((size shr 16) and 0xFF'u)
pb.buffer[2] = byte((size shr 8) and 0xFF) pb.buffer[2] = byte((size shr 8) and 0xFF'u)
pb.buffer[3] = byte(size and 0xFF) pb.buffer[3] = byte(size and 0xFF'u)
pb.offset = 4 pb.offset = 4
elif WithUint32LeLength in pb.options: elif WithUint32LeLength in pb.options:
let size = uint(len(pb.buffer) - 4) let size = uint(len(pb.buffer) - 4)
pb.buffer[0] = byte(size and 0xFF) pb.buffer[0] = byte(size and 0xFF'u)
pb.buffer[1] = byte((size shr 8) and 0xFF) pb.buffer[1] = byte((size shr 8) and 0xFF'u)
pb.buffer[2] = byte((size shr 16) and 0xFF) pb.buffer[2] = byte((size shr 16) and 0xFF'u)
pb.buffer[3] = byte((size shr 24) and 0xFF) pb.buffer[3] = byte((size shr 24) and 0xFF'u)
pb.offset = 4 pb.offset = 4
else: else:
pb.offset = 0 pb.offset = 0

View File

@ -9,12 +9,12 @@
## those terms. ## those terms.
import chronos, chronicles import chronos, chronicles
import nimcrypto/[sysrand, hmac, sha2, sha, hash, rijndael, twofish, bcmode] import nimcrypto/[sysrand, hmac, sha2, sha, hash, rijndael, twofish, bcmode]
import secure, import secure,
../../connection, ../../connection,
../../crypto/crypto, ../../crypto/crypto,
../../crypto/ecnist, ../../crypto/ecnist,
../../protobuf/minprotobuf, ../../protobuf/minprotobuf,
../../peer, ../../peer,
../../stream/bufferstream ../../stream/bufferstream
export hmac, sha2, sha, hash, rijndael, bcmode export hmac, sha2, sha, hash, rijndael, bcmode
@ -208,9 +208,9 @@ proc writeMessage*(sconn: SecureConnection, message: seq[byte]) {.async.} =
sconn.writerMac.finish(msg.toOpenArray(mo, mo + macsize - 1)) sconn.writerMac.finish(msg.toOpenArray(mo, mo + macsize - 1))
sconn.writerMac.reset() sconn.writerMac.reset()
let length = len(message) + macsize let length = len(message) + macsize
msg[0] = byte(length shr 24) msg[0] = byte((length shr 24) and 0xFF)
msg[1] = byte(length shr 16) msg[1] = byte((length shr 16) and 0xFF)
msg[2] = byte(length shr 8) msg[2] = byte((length shr 8) and 0xFF)
msg[3] = byte(length and 0xFF) msg[3] = byte(length and 0xFF)
trace "Writing message", message = toHex(msg) trace "Writing message", message = toHex(msg)
try: try:

View File

@ -80,7 +80,6 @@ proc writeSeq*[T: byte|char](vb: var VBuffer, value: openarray[T]) =
proc writeArray*[T: byte|char](vb: var VBuffer, value: openarray[T]) = proc writeArray*[T: byte|char](vb: var VBuffer, value: openarray[T]) =
## Write array ``value`` to buffer ``vb``, value will NOT be prefixed with ## Write array ``value`` to buffer ``vb``, value will NOT be prefixed with
## varint length of the array. ## varint length of the array.
var length = 0
if len(value) > 0: if len(value) > 0:
vb.buffer.setLen(len(vb.buffer) + len(value)) vb.buffer.setLen(len(vb.buffer) + len(value))
copyMem(addr vb.buffer[vb.offset], unsafeAddr value[0], len(value)) copyMem(addr vb.buffer[vb.offset], unsafeAddr value[0], len(value))

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/base32 import ../libp2p/base32
when defined(nimHasUsed): {.used.}
const TVBaseUpperPadding = [ const TVBaseUpperPadding = [
["f", "MY======"], ["f", "MY======"],
["fo", "MZXQ===="], ["fo", "MZXQ===="],

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/base58 import ../libp2p/base58
when defined(nimHasUsed): {.used.}
proc hexToBytes*(a: string, result: var openarray[byte]) = proc hexToBytes*(a: string, result: var openarray[byte]) =
doAssert(len(a) == 2 * len(result)) doAssert(len(a) == 2 * len(result))
var i = 0 var i = 0

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/base64 import ../libp2p/base64
when defined(nimHasUsed): {.used.}
const TVBasePadding = [ const TVBasePadding = [
["f", "Zg=="], ["f", "Zg=="],
["fo", "Zm8="], ["fo", "Zm8="],

View File

@ -2,6 +2,8 @@ import unittest, deques, sequtils, strformat
import chronos import chronos
import ../libp2p/stream/bufferstream import ../libp2p/stream/bufferstream
when defined(nimHasUsed): {.used.}
suite "BufferStream": suite "BufferStream":
test "push data to buffer": test "push data to buffer":
proc testPushTo(): Future[bool] {.async.} = proc testPushTo(): Future[bool] {.async.} =
@ -150,7 +152,7 @@ suite "BufferStream":
test "write ptr": test "write ptr":
proc testWritePtr(): Future[bool] {.async.} = proc testWritePtr(): Future[bool] {.async.} =
proc writeHandler(data: seq[byte]) {.async, gcsafe.} = proc writeHandler(data: seq[byte]) {.async, gcsafe.} =
check cast[string](data) == "Hello!" check cast[string](data) == "Hello!"
let buff = newBufferStream(writeHandler, 10) let buff = newBufferStream(writeHandler, 10)
@ -165,7 +167,7 @@ suite "BufferStream":
test "write string": test "write string":
proc testWritePtr(): Future[bool] {.async.} = proc testWritePtr(): Future[bool] {.async.} =
proc writeHandler(data: seq[byte]) {.async, gcsafe.} = proc writeHandler(data: seq[byte]) {.async, gcsafe.} =
check cast[string](data) == "Hello!" check cast[string](data) == "Hello!"
let buff = newBufferStream(writeHandler, 10) let buff = newBufferStream(writeHandler, 10)
@ -179,7 +181,7 @@ suite "BufferStream":
test "write bytes": test "write bytes":
proc testWritePtr(): Future[bool] {.async.} = proc testWritePtr(): Future[bool] {.async.} =
proc writeHandler(data: seq[byte]) {.async, gcsafe.} = proc writeHandler(data: seq[byte]) {.async, gcsafe.} =
check cast[string](data) == "Hello!" check cast[string](data) == "Hello!"
let buff = newBufferStream(writeHandler, 10) let buff = newBufferStream(writeHandler, 10)
@ -194,7 +196,7 @@ suite "BufferStream":
test "write should happen in order": test "write should happen in order":
proc testWritePtr(): Future[bool] {.async.} = proc testWritePtr(): Future[bool] {.async.} =
var count = 1 var count = 1
proc writeHandler(data: seq[byte]) {.async, gcsafe.} = proc writeHandler(data: seq[byte]) {.async, gcsafe.} =
check cast[string](data) == &"Msg {$count}" check cast[string](data) == &"Msg {$count}"
count.inc count.inc

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/[cid, multihash, multicodec] import ../libp2p/[cid, multihash, multicodec]
when defined(nimHasUsed): {.used.}
suite "Content identifier CID test suite": suite "Content identifier CID test suite":
test "CIDv0 test vector": test "CIDv0 test vector":
@ -13,7 +15,7 @@ suite "Content identifier CID test suite":
cid0.mhash().mcodec == multiCodec("sha2-256") cid0.mhash().mcodec == multiCodec("sha2-256")
var res = 0 var res = 0
try: try:
var cidb0 = Cid.init("QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zIII") discard Cid.init("QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zIII")
except CidError: except CidError:
res = 1 res = 1
check res == 1 check res == 1
@ -29,7 +31,7 @@ suite "Content identifier CID test suite":
cid1.contentType() == multiCodec("raw") cid1.contentType() == multiCodec("raw")
cid1.mhash().mcodec == multiCodec("sha2-256") cid1.mhash().mcodec == multiCodec("sha2-256")
hex(cid1) == chex hex(cid1) == chex
test "Comparison test": test "Comparison test":
var msg = "Hello World!" var msg = "Hello World!"
var mmsg = "Hello World!Hello World!" var mmsg = "Hello World!Hello World!"

View File

@ -13,6 +13,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/crypto/crypto import ../libp2p/crypto/crypto
when defined(nimHasUsed): {.used.}
const const
PrivateKeys = [ PrivateKeys = [
"""080012BE023082013A020100024100AD8A7D5B0EB7C852C1464E4567651F412C """080012BE023082013A020100024100AD8A7D5B0EB7C852C1464E4567651F412C

View File

@ -3,6 +3,8 @@ import chronos
import ../libp2p/daemon/daemonapi, ../libp2p/multiaddress, ../libp2p/multicodec, import ../libp2p/daemon/daemonapi, ../libp2p/multiaddress, ../libp2p/multicodec,
../libp2p/cid, ../libp2p/multihash, ../libp2p/peer ../libp2p/cid, ../libp2p/multihash, ../libp2p/peer
when defined(nimHasUsed): {.used.}
proc identitySpawnTest(): Future[bool] {.async.} = proc identitySpawnTest(): Future[bool] {.async.} =
var api = await newDaemonApi() var api = await newDaemonApi()
var data = await api.identity() var data = await api.identity()

View File

@ -10,6 +10,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/crypto/ecnist import ../libp2p/crypto/ecnist
when defined(nimHasUsed): {.used.}
const const
TestsCount = 10 # number of random tests TestsCount = 10 # number of random tests
@ -392,7 +394,7 @@ suite "EC NIST-P256/384/521 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = EcPrivateKey.init(sersk) discard EcPrivateKey.init(sersk)
var pubkey = EcPublicKey.init(serpk) var pubkey = EcPublicKey.init(serpk)
var csig = EcSignature.init(sersig) var csig = EcSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true
@ -499,7 +501,7 @@ suite "EC NIST-P256/384/521 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = EcPrivateKey.init(sersk) discard EcPrivateKey.init(sersk)
var pubkey = EcPublicKey.init(serpk) var pubkey = EcPublicKey.init(serpk)
var csig = EcSignature.init(sersig) var csig = EcSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true
@ -606,7 +608,7 @@ suite "EC NIST-P256/384/521 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = EcPrivateKey.init(sersk) discard EcPrivateKey.init(sersk)
var pubkey = EcPublicKey.init(serpk) var pubkey = EcPublicKey.init(serpk)
var csig = EcSignature.init(sersig) var csig = EcSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true

View File

@ -12,6 +12,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/crypto/ed25519/ed25519 import ../libp2p/crypto/ed25519/ed25519
when defined(nimHasUsed): {.used.}
const TestsCount = 20 const TestsCount = 20
const SecretKeys = [ const SecretKeys = [
@ -174,7 +176,7 @@ suite "Ed25519 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = EdPrivateKey.init(sersk) discard EdPrivateKey.init(sersk)
var pubkey = EdPublicKey.init(serpk) var pubkey = EdPublicKey.init(serpk)
var csig = EdSignature.init(sersig) var csig = EdSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true

View File

@ -1,16 +1,18 @@
import unittest, options import unittest, options
import chronos, strutils, sequtils import chronos, strutils, sequtils
import ../libp2p/[protocols/identify, import ../libp2p/[protocols/identify,
multiaddress, multiaddress,
peerinfo, peerinfo,
peer, peer,
connection, connection,
multistream, multistream,
transports/transport, transports/transport,
transports/tcptransport, transports/tcptransport,
protocols/protocol, protocols/protocol,
crypto/crypto] crypto/crypto]
when defined(nimHasUsed): {.used.}
suite "Identify": suite "Identify":
test "handle identify message": test "handle identify message":
proc testHandle(): Future[bool] {.async.} = proc testHandle(): Future[bool] {.async.} =

View File

@ -1,23 +1,25 @@
import unittest, sequtils, sugar, strformat, options, strformat import unittest, sequtils, sugar, strformat, options, strformat
import chronos, nimcrypto/utils, chronicles import chronos, nimcrypto/utils, chronicles
import ../libp2p/[connection, import ../libp2p/[connection,
stream/lpstream, stream/lpstream,
stream/bufferstream, stream/bufferstream,
transports/tcptransport, transports/tcptransport,
transports/transport, transports/transport,
protocols/identify, protocols/identify,
multiaddress, multiaddress,
muxers/mplex/mplex, muxers/mplex/mplex,
muxers/mplex/coder, muxers/mplex/coder,
muxers/mplex/types, muxers/mplex/types,
muxers/mplex/lpchannel] muxers/mplex/lpchannel]
when defined(nimHasUsed): {.used.}
suite "Mplex": suite "Mplex":
test "encode header with channel id 0": test "encode header with channel id 0":
proc testEncodeHeader(): Future[bool] {.async.} = proc testEncodeHeader(): Future[bool] {.async.} =
proc encHandler(msg: seq[byte]) {.async.} = proc encHandler(msg: seq[byte]) {.async.} =
check msg == fromHex("000873747265616d2031") check msg == fromHex("000873747265616d2031")
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await conn.writeMsg(0, MessageType.New, cast[seq[byte]]("stream 1")) await conn.writeMsg(0, MessageType.New, cast[seq[byte]]("stream 1"))
@ -30,7 +32,7 @@ suite "Mplex":
proc testEncodeHeader(): Future[bool] {.async.} = proc testEncodeHeader(): Future[bool] {.async.} =
proc encHandler(msg: seq[byte]) {.async.} = proc encHandler(msg: seq[byte]) {.async.} =
check msg == fromHex("88010873747265616d2031") check msg == fromHex("88010873747265616d2031")
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await conn.writeMsg(17, MessageType.New, cast[seq[byte]]("stream 1")) await conn.writeMsg(17, MessageType.New, cast[seq[byte]]("stream 1"))
@ -44,7 +46,7 @@ suite "Mplex":
var step = 0 var step = 0
proc encHandler(msg: seq[byte]) {.async.} = proc encHandler(msg: seq[byte]) {.async.} =
check msg == fromHex("020873747265616d2031") check msg == fromHex("020873747265616d2031")
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await conn.writeMsg(0, MessageType.MsgOut, cast[seq[byte]]("stream 1")) await conn.writeMsg(0, MessageType.MsgOut, cast[seq[byte]]("stream 1"))
@ -70,7 +72,7 @@ suite "Mplex":
test "decode header with channel id 0": test "decode header with channel id 0":
proc testDecodeHeader(): Future[bool] {.async.} = proc testDecodeHeader(): Future[bool] {.async.} =
proc encHandler(msg: seq[byte]) {.async.} = discard proc encHandler(msg: seq[byte]) {.async.} = discard
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await stream.pushTo(fromHex("000873747265616d2031")) await stream.pushTo(fromHex("000873747265616d2031"))
@ -86,7 +88,7 @@ suite "Mplex":
test "decode header and body with channel id 0": test "decode header and body with channel id 0":
proc testDecodeHeader(): Future[bool] {.async.} = proc testDecodeHeader(): Future[bool] {.async.} =
proc encHandler(msg: seq[byte]) {.async.} = discard proc encHandler(msg: seq[byte]) {.async.} = discard
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await stream.pushTo(fromHex("021668656C6C6F2066726F6D206368616E6E656C20302121")) await stream.pushTo(fromHex("021668656C6C6F2066726F6D206368616E6E656C20302121"))
@ -103,7 +105,7 @@ suite "Mplex":
test "decode header and body with channel id other than 0": test "decode header and body with channel id other than 0":
proc testDecodeHeader(): Future[bool] {.async.} = proc testDecodeHeader(): Future[bool] {.async.} =
proc encHandler(msg: seq[byte]) {.async.} = discard proc encHandler(msg: seq[byte]) {.async.} = discard
let stream = newBufferStream(encHandler) let stream = newBufferStream(encHandler)
let conn = newConnection(stream) let conn = newConnection(stream)
await stream.pushTo(fromHex("8a011668656C6C6F2066726F6D206368616E6E656C20302121")) await stream.pushTo(fromHex("8a011668656C6C6F2066726F6D206368616E6E656C20302121"))
@ -123,7 +125,7 @@ suite "Mplex":
let ma: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0") let ma: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0")
proc connHandler(conn: Connection) {.async, gcsafe.} = proc connHandler(conn: Connection) {.async, gcsafe.} =
proc handleMplexListen(stream: Connection) {.async, gcsafe.} = proc handleMplexListen(stream: Connection) {.async, gcsafe.} =
let msg = await stream.readLp() let msg = await stream.readLp()
check cast[string](msg) == "Hello from stream!" check cast[string](msg) == "Hello from stream!"
await stream.close() await stream.close()
@ -152,7 +154,7 @@ suite "Mplex":
let ma: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0") let ma: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0")
proc connHandler(conn: Connection) {.async, gcsafe.} = proc connHandler(conn: Connection) {.async, gcsafe.} =
proc handleMplexListen(stream: Connection) {.async, gcsafe.} = proc handleMplexListen(stream: Connection) {.async, gcsafe.} =
await stream.writeLp("Hello from stream!") await stream.writeLp("Hello from stream!")
await stream.close() await stream.close()
@ -185,7 +187,7 @@ suite "Mplex":
var count = 1 var count = 1
var listenConn: Connection var listenConn: Connection
proc connHandler(conn: Connection) {.async, gcsafe.} = proc connHandler(conn: Connection) {.async, gcsafe.} =
proc handleMplexListen(stream: Connection) {.async, gcsafe.} = proc handleMplexListen(stream: Connection) {.async, gcsafe.} =
let msg = await stream.readLp() let msg = await stream.readLp()
check cast[string](msg) == &"stream {count}!" check cast[string](msg) == &"stream {count}!"
count.inc count.inc
@ -224,7 +226,7 @@ suite "Mplex":
var listenConn: Connection var listenConn: Connection
proc connHandler(conn: Connection) {.async, gcsafe.} = proc connHandler(conn: Connection) {.async, gcsafe.} =
listenConn = conn listenConn = conn
proc handleMplexListen(stream: Connection) {.async, gcsafe.} = proc handleMplexListen(stream: Connection) {.async, gcsafe.} =
let msg = await stream.readLp() let msg = await stream.readLp()
check cast[string](msg) == &"stream {count} from dialer!" check cast[string](msg) == &"stream {count} from dialer!"
await stream.writeLp(&"stream {count} from listener!") await stream.writeLp(&"stream {count} from listener!")
@ -245,7 +247,7 @@ suite "Mplex":
let mplexDial = newMplex(conn) let mplexDial = newMplex(conn)
let dialFut = mplexDial.handle() let dialFut = mplexDial.handle()
dialFut.addCallback(proc(udata: pointer = nil) {.gcsafe.} dialFut.addCallback(proc(udata: pointer = nil) {.gcsafe.}
= debug "completed dialer") = debug "completed dialer")
for i in 1..10: for i in 1..10:
let stream = await mplexDial.newStream("dialer stream") let stream = await mplexDial.newStream("dialer stream")

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/multiaddress import ../libp2p/multiaddress
when defined(nimHasUsed): {.used.}
type type
PatternVector = object PatternVector = object
pattern: MaPattern pattern: MaPattern
@ -303,7 +305,7 @@ suite "MultiAddress test suite":
for item in FailureVectors: for item in FailureVectors:
var r = false var r = false
try: try:
var a = MultiAddress.init(item) discard MultiAddress.init(item)
except: except:
r = true r = true
check r == true check r == true
@ -319,7 +321,7 @@ suite "MultiAddress test suite":
for item in RustFailureVectors: for item in RustFailureVectors:
var r = false var r = false
try: try:
var a = MultiAddress.init(item) discard MultiAddress.init(item)
except: except:
r = true r = true
check r == true check r == true

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/multibase import ../libp2p/multibase
when defined(nimHasUsed): {.used.}
const GoTestVectors = [ const GoTestVectors = [
[ [
"identity", "identity",
@ -292,12 +294,12 @@ suite "MultiBase test suite":
var r1 = false var r1 = false
var r2 = false var r2 = false
try: try:
var enc = MultiBase.encode("unknwon", data) discard MultiBase.encode("unknwon", data)
except MultiBaseError: except MultiBaseError:
r1 = true r1 = true
try: try:
var dec = MultiBase.decode("\x01\x00") discard MultiBase.decode("\x01\x00")
except MultiBaseError: except MultiBaseError:
r2 = true r2 = true

View File

@ -2,6 +2,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/multihash import ../libp2p/multihash
when defined(nimHasUsed): {.used.}
const const
RustTestVectors = [ RustTestVectors = [
[ [

View File

@ -1,17 +1,19 @@
import unittest, strutils, sequtils, sugar, strformat, options import unittest, strutils, sequtils, sugar, strformat, options
import chronos import chronos
import ../libp2p/connection, import ../libp2p/connection,
../libp2p/multistream, ../libp2p/multistream,
../libp2p/stream/lpstream, ../libp2p/stream/lpstream,
../libp2p/connection, ../libp2p/connection,
../libp2p/multiaddress, ../libp2p/multiaddress,
../libp2p/transports/transport, ../libp2p/transports/transport,
../libp2p/transports/tcptransport, ../libp2p/transports/tcptransport,
../libp2p/protocols/protocol, ../libp2p/protocols/protocol,
../libp2p/crypto/crypto, ../libp2p/crypto/crypto,
../libp2p/peerinfo, ../libp2p/peerinfo,
../libp2p/peer ../libp2p/peer
when defined(nimHasUsed): {.used.}
## Mock stream for select test ## Mock stream for select test
type type
TestSelectStream = ref object of LPStream TestSelectStream = ref object of LPStream
@ -43,10 +45,10 @@ method readExactly*(s: TestSelectStream,
cstring("\0x3na\n"), cstring("\0x3na\n"),
"\0x3na\n".len()) "\0x3na\n".len())
method write*(s: TestSelectStream, msg: seq[byte], msglen = -1) method write*(s: TestSelectStream, msg: seq[byte], msglen = -1)
{.async, gcsafe.} = discard {.async, gcsafe.} = discard
method write*(s: TestSelectStream, msg: string, msglen = -1) method write*(s: TestSelectStream, msg: string, msglen = -1)
{.async, gcsafe.} = discard {.async, gcsafe.} = discard
method close(s: TestSelectStream) {.async, gcsafe.} = s.closed = true method close(s: TestSelectStream) {.async, gcsafe.} = s.closed = true
@ -65,7 +67,7 @@ type
method readExactly*(s: TestLsStream, method readExactly*(s: TestLsStream,
pbytes: pointer, pbytes: pointer,
nbytes: int): nbytes: int):
Future[void] {.async.} = Future[void] {.async.} =
case s.step: case s.step:
of 1: of 1:
@ -112,7 +114,7 @@ type
method readExactly*(s: TestNaStream, method readExactly*(s: TestNaStream,
pbytes: pointer, pbytes: pointer,
nbytes: int): nbytes: int):
Future[void] {.async, gcsafe.} = Future[void] {.async, gcsafe.} =
case s.step: case s.step:
of 1: of 1:
@ -168,7 +170,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = Future[void] {.async, gcsafe.} =
check proto == "/test/proto/1.0.0" check proto == "/test/proto/1.0.0"
await conn.close() await conn.close()
@ -197,7 +199,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = discard Future[void] {.async, gcsafe.} = discard
protocol.handler = testHandler protocol.handler = testHandler
ms.addHandler("/test/proto1/1.0.0", protocol) ms.addHandler("/test/proto1/1.0.0", protocol)
@ -224,7 +226,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = discard Future[void] {.async, gcsafe.} = discard
protocol.handler = testHandler protocol.handler = testHandler
ms.addHandler("/unabvailable/proto/1.0.0", protocol) ms.addHandler("/unabvailable/proto/1.0.0", protocol)
@ -244,7 +246,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = Future[void] {.async, gcsafe.} =
check proto == "/test/proto/1.0.0" check proto == "/test/proto/1.0.0"
await conn.writeLp("Hello!") await conn.writeLp("Hello!")
@ -285,7 +287,7 @@ suite "Multistream select":
protocol.handler = proc(conn: Connection, proto: string) {.async, gcsafe.} = protocol.handler = proc(conn: Connection, proto: string) {.async, gcsafe.} =
await conn.close() await conn.close()
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async.} = discard Future[void] {.async.} = discard
protocol.handler = testHandler protocol.handler = testHandler
msListen.addHandler("/test/proto1/1.0.0", protocol) msListen.addHandler("/test/proto1/1.0.0", protocol)
@ -317,7 +319,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = Future[void] {.async, gcsafe.} =
check proto == "/test/proto/1.0.0" check proto == "/test/proto/1.0.0"
await conn.writeLp("Hello!") await conn.writeLp("Hello!")
@ -337,7 +339,7 @@ suite "Multistream select":
let transport2: TcpTransport = newTransport(TcpTransport) let transport2: TcpTransport = newTransport(TcpTransport)
let conn = await transport2.dial(transport1.ma) let conn = await transport2.dial(transport1.ma)
check (await msDial.select(conn, check (await msDial.select(conn,
@["/test/proto/1.0.0", "/test/no/proto/1.0.0"])) == "/test/proto/1.0.0" @["/test/proto/1.0.0", "/test/no/proto/1.0.0"])) == "/test/proto/1.0.0"
let hello = cast[string](await conn.readLp()) let hello = cast[string](await conn.readLp())
@ -356,7 +358,7 @@ suite "Multistream select":
peerInfo.peerId = some(PeerID.init(seckey)) peerInfo.peerId = some(PeerID.init(seckey))
var protocol: LPProtocol = new LPProtocol var protocol: LPProtocol = new LPProtocol
proc testHandler(conn: Connection, proc testHandler(conn: Connection,
proto: string): proto: string):
Future[void] {.async, gcsafe.} = Future[void] {.async, gcsafe.} =
await conn.writeLp(&"Hello from {proto}!") await conn.writeLp(&"Hello from {proto}!")
await conn.close() await conn.close()

View File

@ -13,6 +13,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/crypto/crypto, ../libp2p/peer, ../libp2p/base58 import ../libp2p/crypto/crypto, ../libp2p/peer, ../libp2p/base58
when defined(nimHasUsed): {.used.}
const const
# Test vectors are generated using # Test vectors are generated using
# https://github.com/libp2p/go-libp2p-crypto/blob/master/key.go # https://github.com/libp2p/go-libp2p-crypto/blob/master/key.go

View File

@ -6,7 +6,6 @@
## at your option. ## at your option.
## This file may not be copied, modified, or distributed except according to ## This file may not be copied, modified, or distributed except according to
## those terms. ## those terms.
import unittest, options, tables, sugar, sequtils import unittest, options, tables, sugar, sequtils
import chronos, chronicles import chronos, chronicles
import ../libp2p/[switch, import ../libp2p/[switch,
@ -28,12 +27,14 @@ import ../libp2p/[switch,
protocols/pubsub/pubsub, protocols/pubsub/pubsub,
protocols/pubsub/floodsub] protocols/pubsub/floodsub]
when defined(nimHasUsed): {.used.}
proc createMplex(conn: Connection): Muxer = proc createMplex(conn: Connection): Muxer =
result = newMplex(conn) result = newMplex(conn)
proc createNode(privKey: Option[PrivateKey] = none(PrivateKey), proc createNode(privKey: Option[PrivateKey] = none(PrivateKey),
address: string = "/ip4/127.0.0.1/tcp/0", address: string = "/ip4/127.0.0.1/tcp/0",
triggerSelf: bool = false): Switch = triggerSelf: bool = false): Switch =
var peerInfo: PeerInfo var peerInfo: PeerInfo
var seckey = privKey var seckey = privKey
if privKey.isNone: if privKey.isNone:
@ -59,7 +60,7 @@ proc generateNodes*(num: Natural): seq[Switch] =
for i in 0..<num: for i in 0..<num:
result.add(createNode()) result.add(createNode())
proc subscribeNodes*(nodes: seq[Switch]) {.async.} = proc subscribeNodes*(nodes: seq[Switch]) {.async.} =
var pending: seq[Future[void]] var pending: seq[Future[void]]
for dialer in nodes: for dialer in nodes:
for node in nodes: for node in nodes:
@ -67,10 +68,10 @@ proc subscribeNodes*(nodes: seq[Switch]) {.async.} =
await allFutures(pending) await allFutures(pending)
suite "PubSub": suite "PubSub":
test "FloodSub basic publish/subscribe A -> B": test "FloodSub basic publish/subscribe A -> B":
proc testBasicPubSub(): Future[bool] {.async.} = proc testBasicPubSub(): Future[bool] {.async.} =
var passed: bool var passed: bool
proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} = proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} =
check topic == "foobar" check topic == "foobar"
passed = true passed = true
@ -94,7 +95,7 @@ suite "PubSub":
test "FloodSub basic publish/subscribe B -> A": test "FloodSub basic publish/subscribe B -> A":
proc testBasicPubSub(): Future[bool] {.async.} = proc testBasicPubSub(): Future[bool] {.async.} =
proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} = proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} =
check topic == "foobar" check topic == "foobar"
var nodes = generateNodes(2) var nodes = generateNodes(2)
@ -115,10 +116,10 @@ suite "PubSub":
check: check:
waitFor(testBasicPubSub()) == true waitFor(testBasicPubSub()) == true
test "FloodSub multiple peers, no self trigger": test "FloodSub multiple peers, no self trigger":
proc testBasicFloodSub(): Future[bool] {.async.} = proc testBasicFloodSub(): Future[bool] {.async.} =
var passed: int var passed: int
proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} = proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} =
check topic == "foobar" check topic == "foobar"
passed.inc() passed.inc()
@ -147,10 +148,10 @@ suite "PubSub":
check: check:
waitFor(testBasicFloodSub()) == true waitFor(testBasicFloodSub()) == true
test "FloodSub multiple peers, with self trigger": test "FloodSub multiple peers, with self trigger":
proc testBasicFloodSub(): Future[bool] {.async.} = proc testBasicFloodSub(): Future[bool] {.async.} =
var passed: int var passed: int
proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} = proc handler(topic: string, data: seq[byte]) {.async, gcsafe.} =
check topic == "foobar" check topic == "foobar"
passed.inc() passed.inc()

View File

@ -10,6 +10,8 @@ import unittest
import nimcrypto/utils import nimcrypto/utils
import ../libp2p/crypto/rsa import ../libp2p/crypto/rsa
when defined(nimHasUsed): {.used.}
const const
TestsCount = 20 # number of random tests TestsCount = 20 # number of random tests
@ -418,7 +420,7 @@ suite "RSA 512/1024/2048/4096 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = RsaPrivateKey.init(sersk) discard RsaPrivateKey.init(sersk)
var pubkey = RsaPublicKey.init(serpk) var pubkey = RsaPublicKey.init(serpk)
var csig = RsaSignature.init(sersig) var csig = RsaSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true
@ -434,7 +436,7 @@ suite "RSA 512/1024/2048/4096 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = RsaPrivateKey.init(sersk) discard RsaPrivateKey.init(sersk)
var pubkey = RsaPublicKey.init(serpk) var pubkey = RsaPublicKey.init(serpk)
var csig = RsaSignature.init(sersig) var csig = RsaSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true
@ -449,7 +451,7 @@ suite "RSA 512/1024/2048/4096 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = RsaPrivateKey.init(sersk) discard RsaPrivateKey.init(sersk)
var pubkey = RsaPublicKey.init(serpk) var pubkey = RsaPublicKey.init(serpk)
var csig = RsaSignature.init(sersig) var csig = RsaSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true
@ -465,7 +467,7 @@ suite "RSA 512/1024/2048/4096 test suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = RsaPrivateKey.init(sersk) discard RsaPrivateKey.init(sersk)
var pubkey = RsaPublicKey.init(serpk) var pubkey = RsaPublicKey.init(serpk)
var csig = RsaSignature.init(sersig) var csig = RsaSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true

View File

@ -10,6 +10,8 @@ import unittest
import ../libp2p/crypto/secp import ../libp2p/crypto/secp
import nimcrypto/utils import nimcrypto/utils
when defined(nimHasUsed): {.used.}
suite "Secp256k1 testing suite": suite "Secp256k1 testing suite":
const TestsCount = 20 const TestsCount = 20
test "Private key serialize/deserialize test": test "Private key serialize/deserialize test":
@ -62,7 +64,7 @@ suite "Secp256k1 testing suite":
var sersk = kp.seckey.getBytes() var sersk = kp.seckey.getBytes()
var serpk = kp.pubkey.getBytes() var serpk = kp.pubkey.getBytes()
var sersig = sig.getBytes() var sersig = sig.getBytes()
var seckey = SkPrivateKey.init(sersk) discard SkPrivateKey.init(sersk)
var pubkey = SkPublicKey.init(serpk) var pubkey = SkPublicKey.init(serpk)
var csig = SkSignature.init(sersig) var csig = SkSignature.init(sersig)
check csig.verify(message, pubkey) == true check csig.verify(message, pubkey) == true

View File

@ -1,29 +1,31 @@
import unittest, tables, options import unittest, tables, options
import chronos, chronicles import chronos, chronicles
import ../libp2p/[switch, import ../libp2p/[switch,
multistream, multistream,
protocols/identify, protocols/identify,
connection, connection,
transports/transport, transports/transport,
transports/tcptransport, transports/tcptransport,
multiaddress, multiaddress,
peerinfo, peerinfo,
crypto/crypto, crypto/crypto,
peer, peer,
protocols/protocol, protocols/protocol,
muxers/muxer, muxers/muxer,
muxers/mplex/mplex, muxers/mplex/mplex,
muxers/mplex/types, muxers/mplex/types,
protocols/secure/secio, protocols/secure/secio,
protocols/secure/secure] protocols/secure/secure]
when defined(nimHasUsed): {.used.}
const TestCodec = "/test/proto/1.0.0" const TestCodec = "/test/proto/1.0.0"
type type
TestProto = ref object of LPProtocol TestProto = ref object of LPProtocol
method init(p: TestProto) {.gcsafe.} = method init(p: TestProto) {.gcsafe.} =
proc handle(conn: Connection, proto: string) {.async, gcsafe.} = proc handle(conn: Connection, proto: string) {.async, gcsafe.} =
let msg = cast[string](await conn.readLp()) let msg = cast[string](await conn.readLp())
check "Hello!" == msg check "Hello!" == msg
await conn.writeLp("Hello!") await conn.writeLp("Hello!")
@ -33,7 +35,7 @@ method init(p: TestProto) {.gcsafe.} =
p.handler = handle p.handler = handle
suite "Switch": suite "Switch":
test "e2e use switch": test "e2e use switch":
proc createSwitch(ma: MultiAddress): (Switch, PeerInfo) = proc createSwitch(ma: MultiAddress): (Switch, PeerInfo) =
let seckey = PrivateKey.random(RSA) let seckey = PrivateKey.random(RSA)
var peerInfo: PeerInfo var peerInfo: PeerInfo
@ -54,7 +56,7 @@ suite "Switch":
proc testSwitch(): Future[bool] {.async, gcsafe.} = proc testSwitch(): Future[bool] {.async, gcsafe.} =
let ma1: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0") let ma1: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0")
let ma2: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0") let ma2: MultiAddress = Multiaddress.init("/ip4/0.0.0.0/tcp/0")
var peerInfo1, peerInfo2: PeerInfo var peerInfo1, peerInfo2: PeerInfo
var switch1, switch2: Switch var switch1, switch2: Switch
(switch1, peerInfo1) = createSwitch(ma1) (switch1, peerInfo1) = createSwitch(ma1)

View File

@ -1,11 +1,13 @@
import unittest import unittest
import chronos import chronos
import ../libp2p/[connection, import ../libp2p/[connection,
transports/transport, transports/transport,
transports/tcptransport, transports/tcptransport,
multiaddress, multiaddress,
wire] wire]
when defined(nimHasUsed): {.used.}
suite "TCP transport": suite "TCP transport":
test "test listener: handle write": test "test listener: handle write":
proc testListener(): Future[bool] {.async, gcsafe.} = proc testListener(): Future[bool] {.async, gcsafe.} =

View File

@ -1,6 +1,8 @@
import unittest import unittest
import ../libp2p/varint import ../libp2p/varint
when defined(nimHasUsed): {.used.}
const PBedgeValues = [ const PBedgeValues = [
0'u64, (1'u64 shl 7) - 1'u64, 0'u64, (1'u64 shl 7) - 1'u64,
(1'u64 shl 7), (1'u64 shl 14) - 1'u64, (1'u64 shl 7), (1'u64 shl 14) - 1'u64,