Skip to content

Instantly share code, notes, and snippets.

@rcmorano
Created July 2, 2020 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rcmorano/683b6951cc5ad44a9ab0d6762e3e21d7 to your computer and use it in GitHub Desktop.
Save rcmorano/683b6951cc5ad44a9ab0d6762e3e21d7 to your computer and use it in GitHub Desktop.
find alive and close peers for cardano-node (based on traceroute hops)
#!/bin/bash
# apt install -y netcat-traditional mtr jq curl
MAX_PEERS=20
PROBE_CONN_TIMEOUT=1
SOURCE_ROUTE_POINTER=4
TOPOLOGY_JSON_URL=https://explorer.shelley-testnet.dev.cardano.org/relays/topology.json
TOPOLOGY_JSON_FILE=/tmp/topology.json
PROXIMITY_TOPOLOGY_JSON=/tmp/proximity-topology.json
curl -SLo ${TOPOLOGY_JSON_FILE} ${TOPOLOGY_JSON_URL}
echo '{"Producers":[]}' > ${TOPOLOGY_JSON_FILE}.tmp
jq -r '.Producers[] | "\(.addr):\(.port)"' ${TOPOLOGY_JSON_FILE} | while read line
do
ADDR=$(echo ${line} | awk -F: '{print $1}')
PORT=$(echo ${line} | awk -F: '{print $2}')
nc -G ${SOURCE_ROUTE_POINTER} -w ${PROBE_CONN_TIMEOUT} -zv ${ADDR} ${PORT} &> /dev/null
# if connected, extract valency from the peers file
if [ $? -eq 0 ]
then
VALENCY=$(jq -r \
--arg addr ${ADDR} \
--arg port ${PORT} \
'.Producers[] | select((.addr==($addr | tostring)) and (.port==($port | tonumber))) | .valency' 2> /dev/null \
${TOPOLOGY_JSON_FILE})
if [[ "${VALENCY}" == "null" ]] || [[ "${VALENCY}" == "" ]]
then
VALENCY=1
fi
jq -r \
--arg addr ${ADDR} \
--arg port ${PORT} \
--arg valency ${VALENCY} \
'.Producers += [{"addr":$addr,"port":($port|tonumber),"valency":($valency|tonumber)}]' \
${TOPOLOGY_JSON_FILE}.tmp > ${TOPOLOGY_JSON_FILE}
mv ${TOPOLOGY_JSON_FILE} ${TOPOLOGY_JSON_FILE}.tmp
fi
done
jq -r .Producers[].addr ${TOPOLOGY_JSON_FILE}.tmp | sort | uniq | while read relay; do HOPS=$(mtr --json -c 1 -n -Z 1 -G 1 -U 5 ${relay} | jq -r .report.hubs[].count | sort -n | tail -n1 | awk '{print $1}'); echo "$HOPS - ${relay}"; done | sort -n -k1 > /tmp/peers-hops.log
echo '{"Producers":[]}' > ${PROXIMITY_TOPOLOGY_JSON}.tmp
head -n ${MAX_PEERS} /tmp/peers-hops.log | awk '{print $3}' | while read peer
do
PEER_OBJECTS=$(jq -r \
--arg addr ${peer} \
'.Producers[] | select(.addr==($addr | tostring))' \
${TOPOLOGY_JSON_FILE}.tmp | \
jq -r --slurp . | \
awk '{printf "%s",$0} END {print ""}')
jq -r \
--argjson peer "${PEER_OBJECTS}" \
'.Producers += $peer' \
${PROXIMITY_TOPOLOGY_JSON}.tmp > ${PROXIMITY_TOPOLOGY_JSON}
mv ${PROXIMITY_TOPOLOGY_JSON} ${PROXIMITY_TOPOLOGY_JSON}.tmp
done
jq -r . ${PROXIMITY_TOPOLOGY_JSON}.tmp > ${PROXIMITY_TOPOLOGY_JSON}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment