Update plugins to use new Block API

This commit is contained in:
Arinerron 2018-05-15 20:08:42 -07:00
parent 3c8cbd2291
commit 30f617c83e
No known key found for this signature in database
GPG Key ID: 99383627861C62F0
5 changed files with 53 additions and 89 deletions

BIN
onionr/core Normal file

Binary file not shown.

View File

@ -56,6 +56,7 @@ class Block:
self.signed = False
self.signature = None
self.signedData = None
self.blockFile = None
self.bheader = {}
self.bmetadata = {}

View File

@ -40,9 +40,7 @@ class DaemonAPI:
return
def local_command(self, command):
self.pluginapi.get_utils().localCommand(self, command)
return
return self.pluginapi.get_utils().localCommand(self, command)
def queue_pop(self):
return self.get_core().daemonQueue()

View File

@ -16,48 +16,54 @@
'''
# Imports some useful libraries
import logger, config
import os, sqlite3, core
import logger, config, core
import os, sqlite3, threading
from onionrblockapi import Block
plugin_name = 'gui'
def send():
global message
block = Block()
block.setType('txt')
block.setContent(message)
logger.debug('Sent message in block %s.' % block.save(sign = True))
def sendMessage():
global sendEntry
messageToAdd = '-txt-' + sendEntry.get()
#addedHash = pluginapi.get_core().setData(messageToAdd)
#pluginapi.get_core().addToBlockDB(addedHash, selfInsert=True)
#pluginapi.get_core().setBlockType(addedHash, 'txt')
pluginapi.get_core().insertBlock(messageToAdd, header='txt', sign=True)
sendEntry.delete(0, END)
global message
message = sendEntry.get()
t = threading.Thread(target = send)
t.start()
sendEntry.delete(0, len(message))
def update():
global listedBlocks, listbox, runningCheckDelayCount, runningCheckDelay, root, daemonStatus
# TO DO: migrate to new header format
for i in pluginapi.get_core().getBlocksByType('txt'):
if i.strip() == '' or i in listedBlocks:
for i in Block.getBlocks(type = 'txt'):
if i.getContent().strip() == '' or i.getHash() in listedBlocks:
continue
blockFile = open('./data/blocks/' + i + '.dat')
listbox.insert(END, str(blockFile.read().replace('-txt-', '')))
blockFile.close()
listedBlocks.append(i)
listbox.see(END)
blocksList = os.listdir('./data/blocks/') # dir is your directory path
number_blocks = len(blocksList)
listbox.insert(99999, str(i.getContent()))
listedBlocks.append(i.getHash())
listbox.see(99999)
runningCheckDelayCount += 1
if runningCheckDelayCount == runningCheckDelay:
resp = pluginapi.get_core()._utils.localCommand('ping')
resp = pluginapi.daemon.local_command('ping')
if resp == 'pong':
daemonStatus.config(text="Onionr Daemon Status: Running")
daemonStatus.config(text = "Onionr Daemon Status: Running")
else:
daemonStatus.config(text="Onionr Daemon Status: Not Running")
daemonStatus.config(text = "Onionr Daemon Status: Not Running")
runningCheckDelayCount = 0
root.after(10000, update)
def openGUI():
def reallyOpenGUI():
import tkinter
global root, runningCheckDelay, runningCheckDelayCount, scrollbar, listedBlocks, nodeInfo, keyInfo, idText, idEntry, pubKeyEntry, listbox, daemonStatus, sendEntry
@ -77,11 +83,11 @@ def openGUI():
keyInfo = tkinter.Frame(root)
hostname = pluginapi.get_onionr().get_hostname()
logger.debug('hostname: %s' % hostname)
logger.debug('Onionr Hostname: %s' % hostname)
idText = hostname
idEntry = tkinter.Entry(nodeInfo)
tkinter.Label(nodeInfo, text="Node Address: ").pack(side=tkinter.LEFT)
tkinter.Label(nodeInfo, text = "Node Address: ").pack(side=tkinter.LEFT)
idEntry.pack()
idEntry.insert(0, idText.strip())
idEntry.configure(state="readonly")
@ -114,6 +120,11 @@ def openGUI():
root.after(2000, update)
root.mainloop()
def openGUI():
t = threading.Thread(target = reallyOpenGUI)
t.daemon = False
t.start()
def on_init(api, data = None):
global pluginapi
pluginapi = api

View File

@ -21,6 +21,7 @@
# useful libraries
import logger, config
import os, sys, json, time, random, shutil, base64, getpass, datetime, re
from onionrblockapi import Block
plugin_name = 'pluginmanager'
@ -143,9 +144,8 @@ def sanitize(name):
def blockToPlugin(block):
try:
blockContent = pluginapi.get_core().getData(block)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
block = Block(block)
blockContent = json.loads(block.getContent())
name = sanitize(blockContent['name'])
author = blockContent['author']
@ -224,46 +224,10 @@ def pluginToBlock(plugin, import_block = True):
return False
def parseBlock(hash, key):# deal with block metadata
blockContent = pluginapi.get_core().getData(hash)
try:
blockMetadata = json.loads(blockContent[:blockContent.decode().find('\n')].decode())
try:
blockMeta2 = json.loads(blockMetadata['meta'])
except KeyError:
blockMeta2 = {'type': ''}
pass
blockContent = blockContent[blockContent.rfind(b'\n') + 1:]
try:
blockContent = blockContent.decode()
except AttributeError:
pass
if not pluginapi.get_crypto().verifyPow(blockContent, blockMeta2):
logger.debug("(pluginmanager): %s has invalid or insufficient proof of work" % str(hash))
return False
if not (('sig' in blockMetadata)): # and ('id' in blockMeta2)
logger.debug('(pluginmanager): %s is missing required parameters' % hash)
return False
else:
if pluginapi.get_crypto().edVerify(blockMetadata['meta'] + '\n' + blockContent, key, blockMetadata['sig'], encodedData=True):
# logger.debug('(pluginmanager): %s was signed' % str(hash))
return True
else:
# logger.debug('(pluginmanager): %s has an invalid signature' % str(hash))
return False
except json.decoder.JSONDecodeError as e:
logger.error('(pluginmanager): Could not decode block metadata.', error = e, timestamp = False)
return False
def installBlock(block):
try:
blockContent = pluginapi.get_core().getData(block)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
block = Block(block)
blockContent = json.loads(block.getContent())
name = sanitize(blockContent['name'])
author = blockContent['author']
@ -284,7 +248,7 @@ def installBlock(block):
install = logger.confirm(message = 'Continue with installation %s?')
if install:
blockToPlugin(block)
blockToPlugin(block.getHash())
addPlugin(name)
else:
logger.info('Installation cancelled.')
@ -415,7 +379,7 @@ def commandInstallPlugin():
real_key = False
if valid_hash:
real_block = pluginapi.get_utils().hasBlock(pkobh)
real_block = Block.exists(pkobh)
elif valid_key:
real_key = pluginapi.get_utils().hasKey(pkobh)
@ -440,39 +404,31 @@ def commandInstallPlugin():
saveKey(pluginname, pkobh)
blocks = pluginapi.get_core().getBlocksByType('plugin')
signedBlocks = list()
for hash in blocks:
if parseBlock(hash, publickey):
signedBlocks.append(hash)
signedBlocks = Block.getBlocks(type = 'plugin', signed = True, signer = publickey)
mostRecentTimestamp = None
mostRecentVersionBlock = None
for hash in signedBlocks:
for block in signedBlocks:
try:
blockContent = pluginapi.get_core().getData(hash)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
blockContent = json.loads(block.getContent())
if not (('author' in blockContent) and ('info' in blockContent) and ('date' in blockContent) and ('name' in blockContent)):
raise ValueError('Missing required parameter `date` in block %s.' % hash)
raise ValueError('Missing required parameter `date` in block %s.' % block.getHash())
blockDatetime = datetime.datetime.strptime(blockContent['date'], '%Y-%m-%d %H:%M:%S')
if blockContent['name'] == pluginname:
if ('version' in blockContent['info']) and (blockContent['info']['version'] == version) and (not version is None):
mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash
mostRecentVersionBlock = block.getHash()
break
elif mostRecentTimestamp is None:
mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash
mostRecentVersionBlock = block.getHash()
elif blockDatetime > mostRecentTimestamp:
mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash
mostRecentVersionBlock = block.getHash()
except Exception as e:
pass
@ -505,11 +461,9 @@ def commandAddRepository():
blockhash = sys.argv[2]
if pluginapi.get_utils().validateHash(blockhash):
if pluginapi.get_utils().hasBlock(blockhash):
if Block.exists(blockhash):
try:
blockContent = pluginapi.get_core().getData(blockhash)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
blockContent = json.loads(Block(blockhash).getContent())
pluginslist = dict()