work on pow for public keys

This commit is contained in:
Kevin Froman 2018-05-07 01:55:03 -05:00
parent 54a3557fd0
commit bc88e8107c
No known key found for this signature in database
GPG Key ID: 0D414D0FE405B63B
7 changed files with 72 additions and 29 deletions

View File

@ -30,4 +30,4 @@ soft-reset:
reset: reset:
@echo "Hard-resetting Onionr..." @echo "Hard-resetting Onionr..."
rm -rf onionr/data/ | true > /dev/null 2>&1 rm -rf onionr/data/ | true > /dev/null 2>&1
@./RUN-LINUX.sh version | grep -v "Failed" --color=always #@./RUN-LINUX.sh version | grep -v "Failed" --color=always

View File

@ -227,8 +227,8 @@ class API:
response = 'none' response = 'none'
resp = Response(response) resp = Response(response)
elif action == 'kex': elif action == 'kex':
peers = self._core.listPeers() peers = self._core.listPeers(getPow=True)
response = ','.join(self._core.listPeers()) response = ','.join(peers)
resp = Response(response) resp = Response(response)
else: else:
resp = Response("") resp = Response("")

View File

@ -679,7 +679,7 @@ class OnionrCommunicate:
except KeyError: except KeyError:
return False return False
dataLen = len(blockContent) dataLen = len(blockContent)
print(blockContent)
expectedHash = self._crypto.blake2bHash(base64.b64decode(metadata['powToken']) + self._crypto.blake2bHash(blockContent.encode())) expectedHash = self._crypto.blake2bHash(base64.b64decode(metadata['powToken']) + self._crypto.blake2bHash(blockContent.encode()))
difficulty = 0 difficulty = 0
try: try:

View File

@ -76,7 +76,7 @@ class Core:
exit(1) exit(1)
return return
def addPeer(self, peerID, name=''): def addPeer(self, peerID, powID, name=''):
''' '''
Adds a public key to the key database (misleading function name) Adds a public key to the key database (misleading function name)
@ -85,10 +85,11 @@ class Core:
# This function simply adds a peer to the DB # This function simply adds a peer to the DB
if not self._utils.validatePubKey(peerID): if not self._utils.validatePubKey(peerID):
return False return False
conn = sqlite3.connect(self.peerDB) conn = sqlite3.connect(self.peerDB)
hashID = self._crypto.pubKeyHashID(peerID) hashID = self._crypto.pubKeyHashID(peerID)
c = conn.cursor() c = conn.cursor()
t = (peerID, name, 'unknown', hashID) t = (peerID, name, 'unknown', hashID, powID)
for i in c.execute("SELECT * FROM PEERS where id = '" + peerID + "';"): for i in c.execute("SELECT * FROM PEERS where id = '" + peerID + "';"):
try: try:
@ -99,7 +100,7 @@ class Core:
pass pass
except IndexError: except IndexError:
pass pass
c.execute('INSERT INTO peers (id, name, dateSeen, hashID) VALUES(?, ?, ?, ?);', t) c.execute('INSERT INTO peers (id, name, dateSeen, pow, hashID) VALUES(?, ?, ?, ?, ?);', t)
conn.commit() conn.commit()
conn.close() conn.close()
@ -212,7 +213,8 @@ class Core:
bytesStored int, bytesStored int,
trust int, trust int,
pubkeyExchanged int, pubkeyExchanged int,
hashID); hashID text,
pow text not null);
''') ''')
conn.commit() conn.commit()
conn.close() conn.close()
@ -431,7 +433,7 @@ class Core:
conn.close() conn.close()
return addressList return addressList
def listPeers(self, randomOrder=True): def listPeers(self, randomOrder=True, getPow=False):
''' '''
Return a list of public keys (misleading function name) Return a list of public keys (misleading function name)
@ -448,10 +450,16 @@ class Core:
for i in c.execute(payload): for i in c.execute(payload):
try: try:
if len(i[0]) != 0: if len(i[0]) != 0:
peerList.append(i[0]) if getPow:
peerList.append(i[0] + '-' + i[11])
else:
peerList.append(i[0])
except TypeError: except TypeError:
pass pass
peerList.append(self._crypto.pubKey) if getPow:
peerList.append(self._crypto.pubKey + '-' + self._crypto.pubKeyPowToken)
else:
peerList.append(self._crypto.pubKey)
conn.close() conn.close()
return peerList return peerList
@ -633,19 +641,24 @@ class Core:
powProof = onionrproofs.POW(data) powProof = onionrproofs.POW(data)
powToken = '' powToken = ''
# wait for proof to complete # wait for proof to complete
while True: try:
powToken = powProof.getResult() while True:
if powToken == False: powToken = powProof.getResult()
time.sleep(0.3) if powToken == False:
continue time.sleep(0.3)
powHash = powToken[0] continue
powToken = base64.b64encode(powToken[1]) powHash = powToken[0]
try: powToken = base64.b64encode(powToken[1])
powToken = powToken.decode() try:
except AttributeError: powToken = powToken.decode()
pass except AttributeError:
finally: pass
break finally:
break
except KeyboardInterrupt:
logger.warn("Got keyboard interrupt while working on inserting block, stopping.")
powProof.shutdown()
return ''
try: try:
data.decode() data.decode()

View File

@ -389,7 +389,8 @@ class Onionr:
addedHash = self.onionrCore.insertBlock(messageToAdd, header='txt') addedHash = self.onionrCore.insertBlock(messageToAdd, header='txt')
#self.onionrCore.addToBlockDB(addedHash, selfInsert=True) #self.onionrCore.addToBlockDB(addedHash, selfInsert=True)
#self.onionrCore.setBlockType(addedHash, 'txt') #self.onionrCore.setBlockType(addedHash, 'txt')
logger.info("Message inserted as as block %s" % addedHash) if addedHash != '':
logger.info("Message inserted as as block %s" % addedHash)
return return
def getPMs(self): def getPMs(self):

View File

@ -17,15 +17,19 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
''' '''
import nacl.signing, nacl.encoding, nacl.public, nacl.hash, nacl.secret, os, binascii, base64, hashlib, logger import nacl.signing, nacl.encoding, nacl.public, nacl.hash, nacl.secret, os, binascii, base64, hashlib, logger, onionrproofs, time
class OnionrCrypto: class OnionrCrypto:
def __init__(self, coreInstance): def __init__(self, coreInstance):
self._core = coreInstance self._core = coreInstance
self._keyFile = 'data/keys.txt' self._keyFile = 'data/keys.txt'
self.keyPowFile = 'data/keyPow.txt'
self.pubKey = None self.pubKey = None
self.privKey = None self.privKey = None
self.pubKeyPowToken = None
self.pubKeyPowHash = None
self.HASH_ID_ROUNDS = 2000 self.HASH_ID_ROUNDS = 2000
# Load our own pub/priv Ed25519 keys, gen & save them if they don't exist # Load our own pub/priv Ed25519 keys, gen & save them if they don't exist
@ -34,12 +38,30 @@ class OnionrCrypto:
keys = keys.read().split(',') keys = keys.read().split(',')
self.pubKey = keys[0] self.pubKey = keys[0]
self.privKey = keys[1] self.privKey = keys[1]
try:
with open(self.keyPowFile, 'r') as powFile:
data = powFile.read()
self.pubKeyPowHash = data.split('-')[0]
self.pubKeyPowToken = data.split('-')[1]
except (FileNotFoundError, IndexError):
pass
else: else:
keys = self.generatePubKey() keys = self.generatePubKey()
self.pubKey = keys[0] self.pubKey = keys[0]
self.privKey = keys[1] self.privKey = keys[1]
with open(self._keyFile, 'w') as keyfile: with open(self._keyFile, 'w') as keyfile:
keyfile.write(self.pubKey + ',' + self.privKey) keyfile.write(self.pubKey + ',' + self.privKey)
with open(self.keyPowFile, 'w') as keyPowFile:
proof = onionrproofs.POW(self.pubKey)
logger.info('Doing necessary work to insert our public key')
while True:
time.sleep(0.2)
powToken = proof.getResult()
if powToken != False:
break
keyPowFile.write(base64.b64encode(powToken[1]).decode())
self.pubKeyPowToken = powToken[1]
self.pubKeyPowHash = powToken[0]
return return
def edVerify(self, data, key, sig, encodedData=True): def edVerify(self, data, key, sig, encodedData=True):

View File

@ -101,9 +101,16 @@ class OnionrUtils:
retVal = False retVal = False
if newKeyList != False: if newKeyList != False:
for key in newKeyList.split(','): for key in newKeyList.split(','):
if not key in self._core.listPeers(randomOrder=False) and type(key) != None and key != self._core._crypto.pubKey: key = key.split('-')
if self._core.addPeer(key): if len(key[0]) > 60 or len(key[1]) > 1000:
retVal = True logger.warn(key[0] + ' or its pow value is too large.')
continue
if self._core._crypto.blake2bHash(base64.b64decode(key[1]) + key[0]).startswith('0000'):
if not key[0] in self._core.listPeers(randomOrder=False) and type(key) != None and key[0] != self._core._crypto.pubKey:
if self._core.addPeer(key[0], key[1]):
retVal = True
else:
logger.warn(key[0] + 'pow failed')
return retVal return retVal
except Exception as error: except Exception as error:
logger.error('Failed to merge keys.', error=error) logger.error('Failed to merge keys.', error=error)