Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Advertises the relay address of connected js-ipfs peers to a pubsub channel (announce-circuit)
import requests, json, time, threading
# Use full path to circuit, destination will be appended (you must change these, they are node specific)
CIRCUITS = ["/dns6/", "/dns4/"]
# The address of your local node (must be accepting websockets and be reverse proxied with SSL support for wss)
NODE = "http://localhost:5001"
# Used for trying to track already announced peers
known = {}
# Used for tracking publishing information
known_publish = {}
# Used for tracking last announcement (keep-alive)
lastAnn = time.time()
# Subscribe as well to help maintain connection with peers
def sub():
while True:
req ="/api/v0/pubsub/sub?arg=announce-circuit")
time.sleep(1) # just in case the local node goes down, let's sleep so we don't consume a thread
while True:
# Get peer list
response ='/api/v0/swarm/peers')
peers = response.json()["Peers"]
# Loop through list
for peer in peers:
addr = peer["Addr"].split("/")
if len(addr) < 6: # If length is less than 6, it's not a wss peer
# Pull information out of address
port = addr[4]
protocol = addr[5]
ip = addr[2]
# Check if this peer connected using the wss reverse proxy, and if we've already advertised it
if not(peer["Peer"]+":"+port in known) and ip == u"" and protocol == u"ws":
print("Advertising: " + peer["Peer"])
# Announce the peer for all the circuits
for circuit in CIRCUITS:'/api/v0/pubsub/pub?arg=announce-circuit&arg='+circuit+peer["Peer"])
known[peer["Peer"]+":"+port] = True # Store the random port so we don't reannounce this peer
lastAnn = time.time() # Store the time so we don't waste time doing a keep-alive
# If we haven't seen a new peer for 4 seconds, let's send a keep-alive so our peers keep listening (and connecting to the nodes we advertise!)
if time.time() - lastAnn >= 4:'/api/v0/pubsub/pub?arg=announce-circuit&arg=keep-alive')
lastAnn = time.time()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment