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.signed = False
self.signature = None self.signature = None
self.signedData = None self.signedData = None
self.blockFile = None
self.bheader = {} self.bheader = {}
self.bmetadata = {} self.bmetadata = {}

View File

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

View File

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

View File

@ -21,6 +21,7 @@
# useful libraries # useful libraries
import logger, config import logger, config
import os, sys, json, time, random, shutil, base64, getpass, datetime, re import os, sys, json, time, random, shutil, base64, getpass, datetime, re
from onionrblockapi import Block
plugin_name = 'pluginmanager' plugin_name = 'pluginmanager'
@ -143,9 +144,8 @@ def sanitize(name):
def blockToPlugin(block): def blockToPlugin(block):
try: try:
blockContent = pluginapi.get_core().getData(block) block = Block(block)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode() blockContent = json.loads(block.getContent())
blockContent = json.loads(blockContent)
name = sanitize(blockContent['name']) name = sanitize(blockContent['name'])
author = blockContent['author'] author = blockContent['author']
@ -224,46 +224,10 @@ def pluginToBlock(plugin, import_block = True):
return False 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): def installBlock(block):
try: try:
blockContent = pluginapi.get_core().getData(block) block = Block(block)
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode() blockContent = json.loads(block.getContent())
blockContent = json.loads(blockContent)
name = sanitize(blockContent['name']) name = sanitize(blockContent['name'])
author = blockContent['author'] author = blockContent['author']
@ -284,7 +248,7 @@ def installBlock(block):
install = logger.confirm(message = 'Continue with installation %s?') install = logger.confirm(message = 'Continue with installation %s?')
if install: if install:
blockToPlugin(block) blockToPlugin(block.getHash())
addPlugin(name) addPlugin(name)
else: else:
logger.info('Installation cancelled.') logger.info('Installation cancelled.')
@ -415,7 +379,7 @@ def commandInstallPlugin():
real_key = False real_key = False
if valid_hash: if valid_hash:
real_block = pluginapi.get_utils().hasBlock(pkobh) real_block = Block.exists(pkobh)
elif valid_key: elif valid_key:
real_key = pluginapi.get_utils().hasKey(pkobh) real_key = pluginapi.get_utils().hasKey(pkobh)
@ -440,39 +404,31 @@ def commandInstallPlugin():
saveKey(pluginname, pkobh) saveKey(pluginname, pkobh)
blocks = pluginapi.get_core().getBlocksByType('plugin') signedBlocks = Block.getBlocks(type = 'plugin', signed = True, signer = publickey)
signedBlocks = list()
for hash in blocks:
if parseBlock(hash, publickey):
signedBlocks.append(hash)
mostRecentTimestamp = None mostRecentTimestamp = None
mostRecentVersionBlock = None mostRecentVersionBlock = None
for hash in signedBlocks: for block in signedBlocks:
try: try:
blockContent = pluginapi.get_core().getData(hash) blockContent = json.loads(block.getContent())
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
if not (('author' in blockContent) and ('info' in blockContent) and ('date' in blockContent) and ('name' in blockContent)): 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') blockDatetime = datetime.datetime.strptime(blockContent['date'], '%Y-%m-%d %H:%M:%S')
if blockContent['name'] == pluginname: if blockContent['name'] == pluginname:
if ('version' in blockContent['info']) and (blockContent['info']['version'] == version) and (not version is None): if ('version' in blockContent['info']) and (blockContent['info']['version'] == version) and (not version is None):
mostRecentTimestamp = blockDatetime mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash mostRecentVersionBlock = block.getHash()
break break
elif mostRecentTimestamp is None: elif mostRecentTimestamp is None:
mostRecentTimestamp = blockDatetime mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash mostRecentVersionBlock = block.getHash()
elif blockDatetime > mostRecentTimestamp: elif blockDatetime > mostRecentTimestamp:
mostRecentTimestamp = blockDatetime mostRecentTimestamp = blockDatetime
mostRecentVersionBlock = hash mostRecentVersionBlock = block.getHash()
except Exception as e: except Exception as e:
pass pass
@ -505,11 +461,9 @@ def commandAddRepository():
blockhash = sys.argv[2] blockhash = sys.argv[2]
if pluginapi.get_utils().validateHash(blockhash): if pluginapi.get_utils().validateHash(blockhash):
if pluginapi.get_utils().hasBlock(blockhash): if Block.exists(blockhash):
try: try:
blockContent = pluginapi.get_core().getData(blockhash) blockContent = json.loads(Block(blockhash).getContent())
blockContent = blockContent[blockContent.rfind(b'\n') + 1:].decode()
blockContent = json.loads(blockContent)
pluginslist = dict() pluginslist = dict()