Skip to content

Commit 7383909

Browse files
committed
chore: update mix
1 parent e0c069a commit 7383909

6 files changed

Lines changed: 75 additions & 45 deletions

File tree

Dockerfile

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,18 @@ RUN apt-get update && apt install -y git build-essential bash ca-certificates li
3939
RUN git config --global http.sslVerify false
4040

4141
# Install latest nimble version
42-
RUN nimble install nimble@#head
42+
RUN nimble install nimble@0.20.1
4343

4444
# Copy only files needed to install Nimble deps (optimizes layer caching)
4545
COPY test_node.nimble .
46+
4647
RUN nimble install -y --depsOnly.
4748

4849
# Copy full source AFTER deps are cached
4950
COPY . .
5051

5152
# Compile the Nim application
52-
RUN nimble c -d:chronicles_colors=None --threads:on -d:metrics -d:libp2p_network_protocols_metrics -d:release main
53+
RUN nimble c -d:chronicles_colors=None --threads:on -d:metrics -d:libp2p_network_protocols_metrics -d:enable_mix_benchmarks -d:release main
5354

5455
# =============================================================================
5556
# Run the app
@@ -65,7 +66,7 @@ WORKDIR /node
6566
# Copy the compiled binary from the build stage
6667
COPY --from=build_app /node/main /node/main
6768

68-
COPY cron_runner.sh .
69+
COPY ./cron_runner.sh .
6970

7071
RUN chmod +x cron_runner.sh
7172
RUN chmod +x main

main.nim

Lines changed: 38 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
import chronos, chronicles, hashes, math, sequtils, strutils, tables, os
1+
import chronos, chronicles, results
22
import metrics, metrics/chronos_httpserver
33
import stew/[byteutils, endians2]
4-
import std/[options, strformat, random, posix]
5-
import node
4+
import
5+
std/[
6+
strformat, random, posix, hashes, math, sequtils, strutils, tables, os,
7+
nativesockets,
8+
]
69
import mix
10+
import ./node
711
import
812
libp2p,
913
libp2p/[
@@ -13,10 +17,7 @@ import
1317
protocols/pubsub/gossipsub,
1418
protocols/pubsub/pubsubpeer,
1519
protocols/pubsub/rpc/messages,
16-
transports/tcptransport,
1720
]
18-
from times import getTime, toUnix, fromUnix, `-`, initTime, `$`, inMilliseconds
19-
from nativesockets import getHostname
2021

2122
const D* = 4 # No. of peers to forward to
2223

@@ -44,8 +45,12 @@ proc createSwitch(id, port: int, isMix: bool, filePath: string): Switch =
4445
libp2pPubKey: SkPublicKey
4546
libp2pPrivKey: SkPrivateKey
4647

48+
var mixNodes: MixNodes = @[]
49+
4750
if isMix:
48-
discard initializeMixNodes(1, port)
51+
mixNodes = initializeMixNodes(1, port).valueOr:
52+
error "Could not generate mix nodes"
53+
return
4954

5055
let mixNodeInfo = getMixNodeInfo(mixNodes[0])
5156
multiAddrStr = mixNodeInfo[0]
@@ -86,14 +91,17 @@ proc createSwitch(id, port: int, isMix: bool, filePath: string): Switch =
8691
externalMultiAddr = fmt"/ip4/{externalAddr}/tcp/{port}/p2p/{peerId}"
8792

8893
if isMix:
89-
discard initMixMultiAddrByIndex(0, externalMultiAddr)
94+
let initRes = mixNodes.initMixMultiAddrByIndex(0, externalMultiAddr)
95+
if initRes.isErr:
96+
error "Failed to initialize mix node", id = 0, err = initRes.error
97+
return
9098
let writeNodeRes =
9199
writeMixNodeInfoToFile(mixNodes[0], id, filePath / fmt"nodeInfo")
92100
if writeNodeRes.isErr:
93101
error "Failed to write mix info to file", nodeId = id, err = writeNodeRes.error
94102
return
95103

96-
let nodePubInfo = getMixPubInfoByIndex(0).valueOr:
104+
let nodePubInfo = mixNodes.getMixPubInfoByIndex(0).valueOr:
97105
error "Get mix pub info by index error", err = error
98106
return
99107

@@ -132,6 +140,19 @@ proc startMetricsServer(
132140

133141
ok(server)
134142

143+
proc makeMixConnCb(mixProto: MixProtocol): CustomConnCreationProc =
144+
return proc(
145+
destAddr: Option[MultiAddress], destPeerId: PeerId, codec: string
146+
): Connection {.gcsafe, raises: [].} =
147+
try:
148+
let dest = destAddr.valueOr:
149+
debug "No destination address available"
150+
return
151+
return mixProto.toConnection(MixDestination.init(destPeerId, dest), codec).get()
152+
except CatchableError as e:
153+
error "Error during execution of MixEntryConnection callback: ", err = e.msg
154+
return nil
155+
135156
proc main() {.async.} =
136157
randomize()
137158

@@ -171,14 +192,7 @@ proc main() {.async.} =
171192
"could not instantiate mix"
172193
)
173194

174-
let mixConn = proc(
175-
destAddr: Option[MultiAddress], destPeerId: PeerId, codec: string
176-
): Connection {.gcsafe, raises: [].} =
177-
try:
178-
return mixProto.toConnection(destPeerId, Opt.none(MultiAddress), codec)
179-
except CatchableError as e:
180-
error "Error during execution of MixEntryConnection callback", err = e.msg
181-
return nil
195+
let mixConn = makeMixConnCb(mixProto)
182196

183197
let mixPeerSelect = proc(
184198
allPeers: HashSet[PubSubPeer],
@@ -189,7 +203,7 @@ proc main() {.async.} =
189203
try:
190204
return mixPeerSelection(allPeers, directPeers, meshPeers, fanoutPeers)
191205
except CatchableError as e:
192-
error "Error during execution of MixPeerSelection callback", err = e.msg
206+
error "Error during execution of MixPeerSelection callback: ", err = e.msg
193207
return initHashSet[PubSubPeer]()
194208

195209
gossipSub = GossipSub.init(
@@ -245,14 +259,12 @@ proc main() {.async.} =
245259
let
246260
timestampNs = uint64.fromBytesLE(data[0 ..< 8])
247261
msgId = uint64.fromBytesLE(data[8 ..< 16])
248-
sentMoment = nanoseconds(int64(timestampNs))
249-
sentNanosecs = nanoseconds(sentMoment - seconds(sentMoment.seconds))
250-
sentDate = initTime(sentMoment.seconds, sentNanosecs)
251-
recvTime = getTime()
252-
delay = recvTime - sentDate
262+
sentTime = Moment.init(int64(timestampNs), Nanosecond)
263+
recvTime = Moment.now()
264+
delay = recvTime - sentTime
253265

254266
info "Received message",
255-
msgId = msgId, sentAt = timestampNs, delayMs = delay.inMilliseconds()
267+
msgId = msgId, sentAt = timestampNs, delayMs = delay.milliseconds()
256268

257269
proc messageValidator(
258270
topic: string, msg: Message
@@ -312,12 +324,11 @@ proc main() {.async.} =
312324
for msg in 0 ..< messages: #client.param(int, "message_count"):
313325
await sleepAsync(msg_rate.milliseconds)
314326
if msg mod publisherCount == myId:
315-
let now = getTime()
316-
let timestampNs = now.toUnix().int64 * 1_000_000_000 + times.nanosecond(now).int64
327+
let timestampNs = Moment.now().epochNanoSeconds()
317328
let msgId = uint64(msg)
318329

319330
var payload: seq[byte]
320-
payload.add(toBytesLE(uint64(timestampNs)))
331+
payload.add(toBytesLE(timestampNs.uint64))
321332
payload.add(toBytesLE(msgId))
322333
payload.add(newSeq[byte](msg_size - 16)) # Fill the rest with padding
323334

mixrunner.sh

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
#!/bin/bash
23

34
N="$1"
@@ -15,7 +16,7 @@ if [[ "$(ls -A "$DATADIR")" ]]; then
1516
fi
1617

1718
for i in $(seq 0 $((N-1))); do
18-
docker run --rm \
19+
docker run \
1920
-d \
2021
--name node-$i \
2122
--hostname node-$i \
@@ -28,4 +29,4 @@ for i in $(seq 0 $((N-1))); do
2829
-e CONNECTTO=4 \
2930
--entrypoint /node/main \
3031
mixrunner
31-
done
32+
done

node.nim

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ proc readPubInfoFromFile*(
119119
let data = file.readAll()
120120
if data.len != PubInfoSize:
121121
return err(
122-
"Invalid data size for NodeInfo: expected " & $NodeInfoSize & " bytes, but got " &
122+
"Invalid data size for PubInfo: expected " & $PubInfoSize & " bytes, but got " &
123123
$(data.len) & " bytes."
124124
)
125125
let dPubInfo = deserializePubInfo(cast[seq[byte]](data)).valueOr:
@@ -152,11 +152,9 @@ proc generateNodes(count: int, basePort: int = 4242): Result[seq[NodeInfo], stri
152152
pubKeyProto = PublicKey(scheme: Secp256k1, skkey: libp2pPubKey)
153153
peerId = PeerId.init(pubKeyProto).get()
154154
multiAddr = fmt"/ip4/0.0.0.0/tcp/{basePort + i}/p2p/{peerId}"
155-
156155
nodes[i] = NodeInfo(
157156
multiAddr: multiAddr, libp2pPubKey: libp2pPubKey, libp2pPrivKey: libp2pPrivKey
158157
)
159-
160158
ok(nodes)
161159

162160
proc initializeNodes*(count: int, basePort: int = 4242): Result[void, string] =

test_node.nimble

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
mode = ScriptMode.Verbose
22

3-
packageName = "test_node"
4-
version = "0.1.0"
5-
author = "Status Research & Development GmbH"
6-
description = "A test node for gossipsub"
7-
license = "MIT"
8-
skipDirs = @[]
3+
packageName = "test_node"
4+
version = "0.1.0"
5+
author = "Status Research & Development GmbH"
6+
description = "A test node for gossipsub"
7+
license = "MIT"
8+
skipDirs = @[]
99

1010
requires "nim >= 1.6.0",
11-
"https://github.com/vacp2p/nim-libp2p#master",
12-
"https://github.com/vacp2p/mix#tmp/benchmark-logging",
13-
"chronos",
14-
"ggplotnim"
11+
"https://github.com/vacp2p/nim-libp2p#master", "https://github.com/vacp2p/mix#main",
12+
"chronos", "ggplotnim"

utils.nim

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import std/[sequtils, sets]
2+
import libp2p/[protocols/pubsub/pubsubpeer, switch]
3+
4+
const D* = 4 # No. of peers to forward to
5+
6+
proc mixPeerSelection*(
7+
allPeers: HashSet[PubSubPeer],
8+
directPeers: HashSet[PubSubPeer],
9+
meshPeers: HashSet[PubSubPeer],
10+
fanoutPeers: HashSet[PubSubPeer],
11+
): HashSet[PubSubPeer] {.gcsafe, raises: [].} =
12+
var
13+
peers: HashSet[PubSubPeer]
14+
allPeersSeq = allPeers.toSeq()
15+
let rng = newRng()
16+
rng.shuffle(allPeersSeq)
17+
for p in allPeersSeq:
18+
peers.incl(p)
19+
if peers.len >= D:
20+
break
21+
return peers

0 commit comments

Comments
 (0)