From fa15c9215802d5e69594a060975a09decc4dbb18 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Thu, 21 Jan 2021 14:34:07 +0100 Subject: [PATCH] Serialize bitswap messages using protobuf --- ipfs.nimble | 1 + ipfs/protobuf/bitswap.nim | 7 +++++++ tests/helpers/examples.nim | 13 +++++++++++++ tests/ipfs/testProtobuf.nim | 25 +++++++++++++++++++++++++ tests/testAll.nim | 1 + 5 files changed, 47 insertions(+) create mode 100644 ipfs/protobuf/bitswap.nim create mode 100644 tests/helpers/examples.nim create mode 100644 tests/ipfs/testProtobuf.nim diff --git a/ipfs.nimble b/ipfs.nimble index f18bfd98..3eb02dc7 100644 --- a/ipfs.nimble +++ b/ipfs.nimble @@ -6,4 +6,5 @@ license = "MIT" requires "nim >= 1.4.2 & < 2.0.0" requires "libp2p >= 0.0.2 & < 0.1.0" requires "chronos >= 2.5.2 & < 3.0.0" +requires "protobufserialization >= 0.2.0 & < 0.3.0" requires "asynctest >= 0.2.1 & < 0.3.0" diff --git a/ipfs/protobuf/bitswap.nim b/ipfs/protobuf/bitswap.nim new file mode 100644 index 00000000..898eb16a --- /dev/null +++ b/ipfs/protobuf/bitswap.nim @@ -0,0 +1,7 @@ +import pkg/protobuf_serialization + +import_proto3 "message.proto" + +export Message +export Wantlist, WantType, Entry +export Block, BlockPresenceType, BlockPresence diff --git a/tests/helpers/examples.nim b/tests/helpers/examples.nim new file mode 100644 index 00000000..67e322f8 --- /dev/null +++ b/tests/helpers/examples.nim @@ -0,0 +1,13 @@ +import std/sequtils +import std/random +import pkg/libp2p +import pkg/ipfs/ipfsobject + +proc example*(t: type seq[byte]): seq[byte] = + newSeqWith(10, rand(byte)) + +proc example*(t: type IpfsObject): IpfsObject = + IpfsObject(data: seq[byte].example) + +proc example*(t: type Cid): Cid = + IpfsObject.example.cid diff --git a/tests/ipfs/testProtobuf.nim b/tests/ipfs/testProtobuf.nim new file mode 100644 index 00000000..e9490f09 --- /dev/null +++ b/tests/ipfs/testProtobuf.nim @@ -0,0 +1,25 @@ +import std/unittest +import pkg/libp2p +import pkg/protobuf_serialization +import pkg/ipfs/protobuf/bitswap +import ../helpers/examples + +suite "protobuf messages": + + test "serializes bitswap want lists": + let cid = Cid.example + let entry = Entry(`block`: cid.data.buffer) + let wantlist = WantList(entries: @[entry]) + let message = Message(wantlist: wantlist) + + let encoded = Protobuf.encode(message) + + check Protobuf.decode(encoded, Message) == message + + test "serializes bitswap blocks": + let bloc = Block(data: seq[byte].example) + let message = Message(payload: @[bloc]) + + let encoded = Protobuf.encode(message) + + check Protobuf.decode(encoded, Message) == message diff --git a/tests/testAll.nim b/tests/testAll.nim index d1bae747..84ae91b2 100644 --- a/tests/testAll.nim +++ b/tests/testAll.nim @@ -2,6 +2,7 @@ import ./ipfs/testObject import ./ipfs/testChunking import ./ipfs/testRepo import ./ipfs/testDhtRouting +import ./ipfs/testProtobuf import ./ipfs/testIpfs {.warning[UnusedImport]: off.}