* changed how new communicator uses bootstrap (untested)

+ added function to calculate human readable strings from hex
This commit is contained in:
Kevin Froman 2018-07-03 03:18:07 -05:00
parent efb049fddd
commit f1c8c8b843
No known key found for this signature in database
GPG Key ID: 0D414D0FE405B63B
4 changed files with 329 additions and 8 deletions

View File

@ -215,18 +215,17 @@ class OnionrCommunicatorDaemon:
needed = maxPeers - len(self.onlinePeers) needed = maxPeers - len(self.onlinePeers)
for i in range(needed): for i in range(needed):
self.connectNewPeer() if len(self.onlinePeers) == 0:
if len(self.onlinePeers) == 0: self.connectNewPeer(useBootstrap=True)
self.addBootstrapListToPeerList()
self.decrementThreadCount('getOnlinePeers') self.decrementThreadCount('getOnlinePeers')
def addBootstrapListToPeerList(self): def addBootstrapListToPeerList(self, peerList):
'''Add the bootstrap list to the peer list (no duplicates)''' '''Add the bootstrap list to the peer list (no duplicates)'''
for i in self._core.bootstrapList: for i in self._core.bootstrapList:
if i not in peerList: if i not in peerList:
peerList.append(i) peerList.append(i)
def connectNewPeer(self, peer=''): def connectNewPeer(self, peer='', useBootstrap=False):
'''Adds a new random online peer to self.onlinePeers''' '''Adds a new random online peer to self.onlinePeers'''
retData = False retData = False
tried = self.offlinePeers tried = self.offlinePeers
@ -238,9 +237,9 @@ class OnionrCommunicatorDaemon:
else: else:
peerList = self._core.listAdders() peerList = self._core.listAdders()
if len(peerList) == 0: if len(peerList) == 0 or useBootstrap:
# Avoid duplicating bootstrap addresses in peerList # Avoid duplicating bootstrap addresses in peerList
self.addBootstrapListToPeerList() self.addBootstrapListToPeerList(peerList)
for address in peerList: for address in peerList:
if len(address) == 0 or address in tried or address in self.onlinePeers: if len(address) == 0 or address in tried or address in self.onlinePeers:

View File

@ -623,6 +623,7 @@ class Onionr:
'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if self.onionrUtils.isCommunicatorRunning(timeout = 2) else logger.colors.fg.red + 'Offline'), 'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if self.onionrUtils.isCommunicatorRunning(timeout = 2) else logger.colors.fg.red + 'Offline'),
'Public Key' : self.onionrCore._crypto.pubKey, 'Public Key' : self.onionrCore._crypto.pubKey,
'POW Token' : powToken, 'POW Token' : powToken,
'Human readable public key' : self.onionrCore._utils.getHumanReadableID(),
'Combined' : self.onionrCore._crypto.pubKey + '-' + powToken, 'Combined' : self.onionrCore._crypto.pubKey + '-' + powToken,
'Node Address' : self.get_hostname(), 'Node Address' : self.get_hostname(),

View File

@ -23,7 +23,7 @@ import nacl.signing, nacl.encoding
from onionrblockapi import Block from onionrblockapi import Block
import onionrexceptions import onionrexceptions
from defusedxml import minidom from defusedxml import minidom
import pgpwords
if sys.version_info < (3, 6): if sys.version_info < (3, 6):
try: try:
import sha3 import sha3
@ -211,6 +211,12 @@ class OnionrUtils:
break break
return pass1 return pass1
def getHumanReadableID(self, pub=''):
'''gets a human readable ID from a public key'''
if pub == '':
pub = self._core._crypto.pubKey
pub = base64.b16encode(base64.b32decode(pub)).decode()
return '-'.join(pgpwords.wordify(pub))
def getBlockMetadataFromData(self, blockData): def getBlockMetadataFromData(self, blockData):
''' '''

315
onionr/pgpwords.py Normal file
View File

@ -0,0 +1,315 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*- (because 0xFF, even : "Yucatán")
import os, re, sys
_words = [
["aardvark", "adroitness"],
["absurd", "adviser"],
["accrue", "aftermath"],
["acme", "aggregate"],
["adrift", "alkali"],
["adult", "almighty"],
["afflict", "amulet"],
["ahead", "amusement"],
["aimless", "antenna"],
["Algol", "applicant"],
["allow", "Apollo"],
["alone", "armistice"],
["ammo", "article"],
["ancient", "asteroid"],
["apple", "Atlantic"],
["artist", "atmosphere"],
["assume", "autopsy"],
["Athens", "Babylon"],
["atlas", "backwater"],
["Aztec", "barbecue"],
["baboon", "belowground"],
["backfield", "bifocals"],
["backward", "bodyguard"],
["banjo", "bookseller"],
["beaming", "borderline"],
["bedlamp", "bottomless"],
["beehive", "Bradbury"],
["beeswax", "bravado"],
["befriend", "Brazilian"],
["Belfast", "breakaway"],
["berserk", "Burlington"],
["billiard", "businessman"],
["bison", "butterfat"],
["blackjack", "Camelot"],
["blockade", "candidate"],
["blowtorch", "cannonball"],
["bluebird", "Capricorn"],
["bombast", "caravan"],
["bookshelf", "caretaker"],
["brackish", "celebrate"],
["breadline", "cellulose"],
["breakup", "certify"],
["brickyard", "chambermaid"],
["briefcase", "Cherokee"],
["Burbank", "Chicago"],
["button", "clergyman"],
["buzzard", "coherence"],
["cement", "combustion"],
["chairlift", "commando"],
["chatter", "company"],
["checkup", "component"],
["chisel", "concurrent"],
["choking", "confidence"],
["chopper", "conformist"],
["Christmas", "congregate"],
["clamshell", "consensus"],
["classic", "consulting"],
["classroom", "corporate"],
["cleanup", "corrosion"],
["clockwork", "councilman"],
["cobra", "crossover"],
["commence", "crucifix"],
["concert", "cumbersome"],
["cowbell", "customer"],
["crackdown", "Dakota"],
["cranky", "decadence"],
["crowfoot", "December"],
["crucial", "decimal"],
["crumpled", "designing"],
["crusade", "detector"],
["cubic", "detergent"],
["dashboard", "determine"],
["deadbolt", "dictator"],
["deckhand", "dinosaur"],
["dogsled", "direction"],
["dragnet", "disable"],
["drainage", "disbelief"],
["dreadful", "disruptive"],
["drifter", "distortion"],
["dropper", "document"],
["drumbeat", "embezzle"],
["drunken", "enchanting"],
["Dupont", "enrollment"],
["dwelling", "enterprise"],
["eating", "equation"],
["edict", "equipment"],
["egghead", "escapade"],
["eightball", "Eskimo"],
["endorse", "everyday"],
["endow", "examine"],
["enlist", "existence"],
["erase", "exodus"],
["escape", "fascinate"],
["exceed", "filament"],
["eyeglass", "finicky"],
["eyetooth", "forever"],
["facial", "fortitude"],
["fallout", "frequency"],
["flagpole", "gadgetry"],
["flatfoot", "Galveston"],
["flytrap", "getaway"],
["fracture", "glossary"],
["framework", "gossamer"],
["freedom", "graduate"],
["frighten", "gravity"],
["gazelle", "guitarist"],
["Geiger", "hamburger"],
["glitter", "Hamilton"],
["glucose", "handiwork"],
["goggles", "hazardous"],
["goldfish", "headwaters"],
["gremlin", "hemisphere"],
["guidance", "hesitate"],
["hamlet", "hideaway"],
["highchair", "holiness"],
["hockey", "hurricane"],
["indoors", "hydraulic"],
["indulge", "impartial"],
["inverse", "impetus"],
["involve", "inception"],
["island", "indigo"],
["jawbone", "inertia"],
["keyboard", "infancy"],
["kickoff", "inferno"],
["kiwi", "informant"],
["klaxon", "insincere"],
["locale", "insurgent"],
["lockup", "integrate"],
["merit", "intention"],
["minnow", "inventive"],
["miser", "Istanbul"],
["Mohawk", "Jamaica"],
["mural", "Jupiter"],
["music", "leprosy"],
["necklace", "letterhead"],
["Neptune", "liberty"],
["newborn", "maritime"],
["nightbird", "matchmaker"],
["Oakland", "maverick"],
["obtuse", "Medusa"],
["offload", "megaton"],
["optic", "microscope"],
["orca", "microwave"],
["payday", "midsummer"],
["peachy", "millionaire"],
["pheasant", "miracle"],
["physique", "misnomer"],
["playhouse", "molasses"],
["Pluto", "molecule"],
["preclude", "Montana"],
["prefer", "monument"],
["preshrunk", "mosquito"],
["printer", "narrative"],
["prowler", "nebula"],
["pupil", "newsletter"],
["puppy", "Norwegian"],
["python", "October"],
["quadrant", "Ohio"],
["quiver", "onlooker"],
["quota", "opulent"],
["ragtime", "Orlando"],
["ratchet", "outfielder"],
["rebirth", "Pacific"],
["reform", "pandemic"],
["regain", "Pandora"],
["reindeer", "paperweight"],
["rematch", "paragon"],
["repay", "paragraph"],
["retouch", "paramount"],
["revenge", "passenger"],
["reward", "pedigree"],
["rhythm", "Pegasus"],
["ribcage", "penetrate"],
["ringbolt", "perceptive"],
["robust", "performance"],
["rocker", "pharmacy"],
["ruffled", "phonetic"],
["sailboat", "photograph"],
["sawdust", "pioneer"],
["scallion", "pocketful"],
["scenic", "politeness"],
["scorecard", "positive"],
["Scotland", "potato"],
["seabird", "processor"],
["select", "provincial"],
["sentence", "proximate"],
["shadow", "puberty"],
["shamrock", "publisher"],
["showgirl", "pyramid"],
["skullcap", "quantity"],
["skydive", "racketeer"],
["slingshot", "rebellion"],
["slowdown", "recipe"],
["snapline", "recover"],
["snapshot", "repellent"],
["snowcap", "replica"],
["snowslide", "reproduce"],
["solo", "resistor"],
["southward", "responsive"],
["soybean", "retraction"],
["spaniel", "retrieval"],
["spearhead", "retrospect"],
["spellbind", "revenue"],
["spheroid", "revival"],
["spigot", "revolver"],
["spindle", "sandalwood"],
["spyglass", "sardonic"],
["stagehand", "Saturday"],
["stagnate", "savagery"],
["stairway", "scavenger"],
["standard", "sensation"],
["stapler", "sociable"],
["steamship", "souvenir"],
["sterling", "specialist"],
["stockman", "speculate"],
["stopwatch", "stethoscope"],
["stormy", "stupendous"],
["sugar", "supportive"],
["surmount", "surrender"],
["suspense", "suspicious"],
["sweatband", "sympathy"],
["swelter", "tambourine"],
["tactics", "telephone"],
["talon", "therapist"],
["tapeworm", "tobacco"],
["tempest", "tolerance"],
["tiger", "tomorrow"],
["tissue", "torpedo"],
["tonic", "tradition"],
["topmost", "travesty"],
["tracker", "trombonist"],
["transit", "truncated"],
["trauma", "typewriter"],
["treadmill", "ultimate"],
["Trojan", "undaunted"],
["trouble", "underfoot"],
["tumor", "unicorn"],
["tunnel", "unify"],
["tycoon", "universe"],
["uncut", "unravel"],
["unearth", "upcoming"],
["unwind", "vacancy"],
["uproot", "vagabond"],
["upset", "vertigo"],
["upshot", "Virginia"],
["vapor", "visitor"],
["village", "vocalist"],
["virus", "voyager"],
["Vulcan", "warranty"],
["waffle", "Waterloo"],
["wallet", "whimsical"],
["watchword", "Wichita"],
["wayside", "Wilmington"],
["willow", "Wyoming"],
["woodlark", "yesteryear"],
["Zulu", "Yucatán"]]
hexre = re.compile("[a-fA-F0-9]+")
def wordify(seq):
seq = filter(lambda x: x not in (' ', '\n', '\t'), seq)
seq = "".join(seq) # Python3 compatibility
if not hexre.match(seq):
raise Exception("Input is not a valid hexadecimal value.")
if len(seq) % 2:
raise Exception("Input contains an odd number of bytes.")
ret = []
for i in range(0, len(seq), 2):
ret.append(_words[int(seq[i:i+2], 16)][(i//2)%2])
return ret
def usage():
print("Usage:")
print(" {0} [fingerprint...]".format(os.path.basename(sys.argv[0])))
print("")
print("If called with multiple arguments, they will be concatenated")
print("and treated as a single fingerprint.")
print("")
print("If called with no arguments, input is read from stdin,")
print("and each line is treated as a single fingerprint. In this")
print("mode, invalid values are silently ignored.")
exit(1)
if __name__ == '__main__':
if 1 == len(sys.argv):
fps = sys.stdin.readlines()
else:
fps = [" ".join(sys.argv[1:])]
for fp in fps:
try:
words = wordify(fp)
print("\n{0}: ".format(fp.strip()))
sys.stdout.write("\t")
for i in range(0, len(words)):
sys.stdout.write(words[i] + " ")
if (not (i+1) % 4) and not i == len(words)-1:
sys.stdout.write("\n\t")
print("")
except Exception as e:
if len(fps) == 1:
print (e)
usage()
print("")