Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(formatting): format the whole codebase using nph 0.5.1 #1118

Merged
merged 33 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
1bfe9b2
format libp2p/crypto/ed25519 folder
diegomrsantos Jun 6, 2024
d7d16f7
format libp2p/crypto folder
diegomrsantos Jun 6, 2024
fdd1b18
format libp2p/daemon folder
diegomrsantos Jun 6, 2024
f312a4d
format libp2p/discovery folder
diegomrsantos Jun 6, 2024
2b555cb
format libp2p/muxers folder
diegomrsantos Jun 6, 2024
01e892b
format libp2p/nameresolving folder
diegomrsantos Jun 6, 2024
1075f18
format libp2p/protobuf folder
diegomrsantos Jun 6, 2024
0879e1b
format libp2p/protocols/connectivity/autonat folder
diegomrsantos Jun 6, 2024
4f56b2e
format libp2p/protocols/connectivity/dcutr folder
diegomrsantos Jun 6, 2024
d01248b
format libp2p/protocols/connectivity/relay folder
diegomrsantos Jun 6, 2024
f786d6b
format libp2p/protocols/perf
diegomrsantos Jun 6, 2024
cc222bc
format libp2p/protocols/pubsub/gossipsub
diegomrsantos Jun 6, 2024
c7d3a22
format libp2p/protocols/pubsub/rpc
diegomrsantos Jun 6, 2024
25ada90
format libp2p/protocols/pubsub
diegomrsantos Jun 6, 2024
a17353f
format libp2p/protocols/secure
diegomrsantos Jun 6, 2024
81576b1
format libp2p/protocols
diegomrsantos Jun 6, 2024
502d638
format libp2p/services
diegomrsantos Jun 6, 2024
eba801e
format libp2p/stream
diegomrsantos Jun 6, 2024
636692b
format libp2p/transports
diegomrsantos Jun 6, 2024
cf1f91b
format libp2p/upgrademngrs
diegomrsantos Jun 6, 2024
8371c0c
format libp2p/utils
diegomrsantos Jun 6, 2024
b5680e6
format libp2p
diegomrsantos Jun 10, 2024
f89fc88
format tests/hole-punching-interop
diegomrsantos Jun 10, 2024
94d5ff1
format tests/pubsub
diegomrsantos Jun 10, 2024
7d00804
format tests/stubs
diegomrsantos Jun 10, 2024
e9cc6ba
format tests/transport-interop
diegomrsantos Jun 10, 2024
d3a6ac7
format tests
diegomrsantos Jun 10, 2024
dafe1f9
format examples
diegomrsantos Jun 10, 2024
539d1bd
format tools
diegomrsantos Jun 10, 2024
fe0313e
format nimb-libp2p
diegomrsantos Jun 10, 2024
f57e061
add lint job to ci
diegomrsantos Jun 10, 2024
6e7f4d1
update tests/hole-punching-interop formatting
diegomrsantos Jun 10, 2024
76ff45e
update readme
diegomrsantos Jun 11, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,25 @@ jobs:
nim --version
nimble --version
nimble test

lint:
name: "Lint"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2 # In PR, has extra merge commit: ^1 = PR, ^2 = base

- name: Check nph formatting
# Pin nph to a specific version to avoid sudden style differences.
# Updating nph version should be accompanied with running the new
# version on the fluffy directory.
run: |
VERSION="v0.5.1"
ARCHIVE="nph-linux_x64.tar.gz"
curl -L "https://github.com/arnetheduck/nph/releases/download/${VERSION}/${ARCHIVE}" -o ${ARCHIVE}
tar -xzf ${ARCHIVE}
shopt -s extglob # Enable extended globbing
./nph examples libp2p tests tools *.@(nim|nims|nimble)
git diff --exit-code
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ The libp2p implementation in Nim is a work in progress. We welcome contributors
- **Perform code reviews**. Feel free to let us know if you found anything that can a) speed up the project development b) ensure better quality and c) reduce possible future bugs.
- **Add tests**. Help nim-libp2p to be more robust by adding more tests to the [tests folder](tests/).
- **Small PRs**. Try to keep PRs atomic and digestible. This makes the review process and pinpointing bugs easier.
- **Code format**. Please format code using [nph](https://github.com/arnetheduck/nph).
- **Code format**. Please format code using [nph](https://github.com/arnetheduck/nph) v0.5.1. This will ensure a consistent codebase and make PRs easier to review. A CI rule has been added to ensure that future commits are all formatted using the same nph version.
The code follows the [Status Nim Style Guide](https://status-im.github.io/nim-style-guide/).

### Contributors
Expand Down
9 changes: 6 additions & 3 deletions config.nims
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ if dirExists("nimbledeps/pkgs2"):
switch("warning", "CaseTransition:off")
switch("warning", "ObservableStores:off")
switch("warning", "LockLevel:off")
--styleCheck:usages
--styleCheck:
usages
switch("warningAsError", "UseBase:on")
--styleCheck:error
--styleCheck:
error

# Avoid some rare stack corruption while using exceptions with a SEH-enabled
# toolchain: https://github.com/status-im/nimbus-eth2/issues/3121
if defined(windows) and not defined(vcc):
--define:nimRawSetjmp
--define:
nimRawSetjmp

# begin Nimble config (version 1)
when fileExists("nimble.paths"):
Expand Down
29 changes: 16 additions & 13 deletions examples/circuitrelay.nim
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@
##
## More informations [here](https://docs.libp2p.io/concepts/circuit-relay/).
import chronos, stew/byteutils
import libp2p,
libp2p/protocols/connectivity/relay/[relay, client]
import libp2p, libp2p/protocols/connectivity/relay/[relay, client]

# Helper to create a circuit relay node
proc createCircuitRelaySwitch(r: Relay): Switch =
SwitchBuilder.new()
.withRng(newRng())
.withAddresses(@[ MultiAddress.init("/ip4/0.0.0.0/tcp/0").tryGet() ])
.withTcpTransport()
.withMplex()
.withNoise()
.withCircuitRelay(r)
.build()
SwitchBuilder
.new()
.withRng(newRng())
.withAddresses(@[MultiAddress.init("/ip4/0.0.0.0/tcp/0").tryGet()])
.withTcpTransport()
.withMplex()
.withNoise()
.withCircuitRelay(r)
.build()

proc main() {.async.} =
# Create a custom protocol
Expand Down Expand Up @@ -56,8 +56,11 @@ proc main() {.async.} =

let
# Create a relay address to swDst using swRel as the relay
addrs = MultiAddress.init($swRel.peerInfo.addrs[0] & "/p2p/" &
$swRel.peerInfo.peerId & "/p2p-circuit").get()
addrs = MultiAddress
.init(
$swRel.peerInfo.addrs[0] & "/p2p/" & $swRel.peerInfo.peerId & "/p2p-circuit"
)
.get()

# Connect Dst to the relay
await swDst.connect(swRel.peerInfo.peerId, swRel.peerInfo.addrs)
Expand All @@ -66,7 +69,7 @@ proc main() {.async.} =
let rsvp = await clDst.reserve(swRel.peerInfo.peerId, swRel.peerInfo.addrs)

# Src dial Dst using the relay
let conn = await swSrc.dial(swDst.peerInfo.peerId, @[ addrs ], customProtoCodec)
let conn = await swSrc.dial(swDst.peerInfo.peerId, @[addrs], customProtoCodec)

await conn.writeLp("test1")
var msg = string.fromBytes(await conn.readLp(1024))
Expand Down
51 changes: 22 additions & 29 deletions examples/directchat.nim
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
when not(compileOption("threads")):
when not (compileOption("threads")):
{.fatal: "Please, compile this program with the --threads:on option!".}

import
strformat, strutils,
stew/byteutils,
chronos,
libp2p
import strformat, strutils, stew/byteutils, chronos, libp2p

const DefaultAddr = "/ip4/127.0.0.1/tcp/0"

const Help = """
const Help =
"""
Commands: /[?|help|connect|disconnect|exit]
help: Prints this help
connect: dials a remote peer
disconnect: ends current session
exit: closes the chat
"""

type
Chat = ref object
switch: Switch # a single entry point for dialing and listening to peer
stdinReader: StreamTransport # transport streams between read & write file descriptor
conn: Connection # connection to the other peer
connected: bool # if the node is connected to another peer
type Chat = ref object
switch: Switch # a single entry point for dialing and listening to peer
stdinReader: StreamTransport # transport streams between read & write file descriptor
conn: Connection # connection to the other peer
connected: bool # if the node is connected to another peer

##
# Stdout helpers, to write the prompt
Expand All @@ -41,8 +37,7 @@ proc writeStdout(c: Chat, str: string) =
##
const ChatCodec = "/nim-libp2p/chat/1.0.0"

type
ChatProto = ref object of LPProtocol
type ChatProto = ref object of LPProtocol

proc new(T: typedesc[ChatProto], c: Chat): T =
let chatproto = T()
Expand Down Expand Up @@ -77,9 +72,9 @@ proc handlePeer(c: Chat, conn: Connection) {.async.} =
strData = await conn.readLp(1024)
str = string.fromBytes(strData)
c.writeStdout $conn.peerId & ": " & $str

except LPStreamEOFError:
defer: c.writeStdout $conn.peerId & " disconnected"
defer:
c.writeStdout $conn.peerId & " disconnected"
await c.conn.close()
c.connected = false

Expand All @@ -88,10 +83,7 @@ proc dialPeer(c: Chat, address: string) {.async.} =
let
multiAddr = MultiAddress.init(address).tryGet()
# split the peerId part /p2p/...
peerIdBytes = multiAddr[multiCodec("p2p")]
.tryGet()
.protoAddress()
.tryGet()
peerIdBytes = multiAddr[multiCodec("p2p")].tryGet().protoAddress().tryGet()
remotePeer = PeerId.init(peerIdBytes).tryGet()
# split the wire address
ip4Addr = multiAddr[multiCodec("ip4")].tryGet()
Expand Down Expand Up @@ -124,7 +116,6 @@ proc readLoop(c: Chat) {.async.} =
let address = await c.stdinReader.readLine()
if address.len > 0:
await c.dialPeer(address)

elif line.startsWith("/exit"):
if c.connected and c.conn.closed.not:
await c.conn.close()
Expand Down Expand Up @@ -171,16 +162,18 @@ proc main() {.async.} =

var switch = SwitchBuilder
.new()
.withRng(rng) # Give the application RNG
.withRng(rng)
# Give the application RNG
.withAddress(localAddress)
.withTcpTransport() # Use TCP as transport
.withMplex() # Use Mplex as muxer
.withNoise() # Use Noise as secure manager
.withTcpTransport()
# Use TCP as transport
.withMplex()
# Use Mplex as muxer
.withNoise()
# Use Noise as secure manager
.build()

let chat = Chat(
switch: switch,
stdinReader: stdinReader)
let chat = Chat(switch: switch, stdinReader: stdinReader)

switch.mount(ChatProto.new(chat))

Expand Down
13 changes: 6 additions & 7 deletions examples/go-daemon/bootstrap.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import chronos, nimcrypto, strutils
import ../../libp2p/daemon/daemonapi
import ../hexdump

const
PubSubTopic = "test-net"
const PubSubTopic = "test-net"

proc dumpSubscribedPeers(api: DaemonAPI) {.async.} =
var peers = await api.pubsubListPeers(PubSubTopic)
Expand Down Expand Up @@ -37,12 +36,12 @@ proc main() {.async.} =

asyncSpawn monitor(api)

proc pubsubLogger(api: DaemonAPI,
ticket: PubsubTicket,
message: PubSubMessage): Future[bool] {.async.} =
proc pubsubLogger(
api: DaemonAPI, ticket: PubsubTicket, message: PubSubMessage
): Future[bool] {.async.} =
let msglen = len(message.data)
echo "= Recieved pubsub message with length ", msglen,
" bytes from peer ", message.peer.pretty()
echo "= Recieved pubsub message with length ",
msglen, " bytes from peer ", message.peer.pretty()
echo dumpHex(message.data)
await api.dumpSubscribedPeers()
result = true
Expand Down
18 changes: 8 additions & 10 deletions examples/go-daemon/chat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ import chronos, nimcrypto, strutils
import ../../libp2p/daemon/daemonapi

## nim c -r --threads:on chat.nim
when not(compileOption("threads")):
when not (compileOption("threads")):
{.fatal: "Please, compile this program with the --threads:on option!".}

const
ServerProtocols = @["/test-chat-stream"]
const ServerProtocols = @["/test-chat-stream"]

type
CustomData = ref object
api: DaemonAPI
remotes: seq[StreamTransport]
consoleFd: AsyncFD
serveFut: Future[void]
type CustomData = ref object
api: DaemonAPI
remotes: seq[StreamTransport]
consoleFd: AsyncFD
serveFut: Future[void]

proc threadMain(wfd: AsyncFD) {.thread.} =
## This procedure performs reading from `stdin` and sends data over
Expand Down Expand Up @@ -82,7 +80,7 @@ proc serveThread(udata: CustomData) {.async.} =
relay = true
break
if relay:
echo peer.pretty(), " * ", " [", addresses.join(", "), "]"
echo peer.pretty(), " * ", " [", addresses.join(", "), "]"
else:
echo peer.pretty(), " [", addresses.join(", "), "]"
elif line.startsWith("/exit"):
Expand Down
19 changes: 9 additions & 10 deletions examples/go-daemon/node.nim
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
import chronos, nimcrypto, strutils, os
import ../../libp2p/daemon/daemonapi

const
PubSubTopic = "test-net"
const PubSubTopic = "test-net"

proc main(bn: string) {.async.} =
echo "= Starting P2P node"
var bootnodes = bn.split(",")
var api = await newDaemonApi({DHTFull, PSGossipSub, WaitBootstrap},
bootstrapNodes = bootnodes,
peersRequired = 1)
var api = await newDaemonApi(
{DHTFull, PSGossipSub, WaitBootstrap}, bootstrapNodes = bootnodes, peersRequired = 1
)
var id = await api.identity()
echo "= P2P node ", id.peer.pretty(), " started:"
for item in id.addresses:
echo item

proc pubsubLogger(api: DaemonAPI,
ticket: PubsubTicket,
message: PubSubMessage): Future[bool] {.async.} =
proc pubsubLogger(
api: DaemonAPI, ticket: PubsubTicket, message: PubSubMessage
): Future[bool] {.async.} =
let msglen = len(message.data)
echo "= Recieved pubsub message with length ", msglen,
" bytes from peer ", message.peer.pretty(), ": "
echo "= Recieved pubsub message with length ",
msglen, " bytes from peer ", message.peer.pretty(), ": "
var strdata = cast[string](message.data)
echo strdata
result = true
Expand Down
29 changes: 17 additions & 12 deletions examples/helloworld.nim
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import chronos # an efficient library for async
import stew/byteutils # various utils
import chronos # an efficient library for async
import stew/byteutils # various utils
import libp2p

##
# Create our custom protocol
##
const TestCodec = "/test/proto/1.0.0" # custom protocol string identifier

type
TestProto = ref object of LPProtocol # declare a custom protocol
type TestProto = ref object of LPProtocol # declare a custom protocol

proc new(T: typedesc[TestProto]): T =

# every incoming connections will be in handled in this closure
proc handle(conn: Connection, proto: string) {.async.} =
echo "Got from remote - ", string.fromBytes(await conn.readLp(1024))
Expand All @@ -28,11 +26,16 @@ proc new(T: typedesc[TestProto]): T =
proc createSwitch(ma: MultiAddress, rng: ref HmacDrbgContext): Switch =
var switch = SwitchBuilder
.new()
.withRng(rng) # Give the application RNG
.withAddress(ma) # Our local address(es)
.withTcpTransport() # Use TCP as transport
.withMplex() # Use Mplex as muxer
.withNoise() # Use Noise as secure manager
.withRng(rng)
# Give the application RNG
.withAddress(ma)
# Our local address(es)
.withTcpTransport()
# Use TCP as transport
.withMplex()
# Use Mplex as muxer
.withNoise()
# Use Noise as secure manager
.build()

result = switch
Expand Down Expand Up @@ -73,7 +76,8 @@ proc main() {.async.} =
# use the second node to dial the first node
# using the first node peerid and address
# and specify our custom protocol codec
let conn = await switch2.dial(switch1.peerInfo.peerId, switch1.peerInfo.addrs, TestCodec)
let conn =
await switch2.dial(switch1.peerInfo.peerId, switch1.peerInfo.addrs, TestCodec)

# conn is now a fully setup connection, we talk directly to the node1 custom protocol handler
await conn.writeLp("Hello p2p!") # writeLp send a length prefixed buffer over the wire
Expand All @@ -84,6 +88,7 @@ proc main() {.async.} =
# We must close the connection ourselves when we're done with it
await conn.close()

await allFutures(switch1.stop(), switch2.stop()) # close connections and shutdown all transports
await allFutures(switch1.stop(), switch2.stop())
# close connections and shutdown all transports

waitFor(main())
Loading
Loading