operator-time
quadrismegistus 4 years ago
parent 7f27b2ed21
commit 11667b5aa9

@ -1,6 +1,6 @@
# mine imports
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade.backend.caller import Caller
from komrade.operators.caller import Caller
from komrade import KomradeException,Logger
# other imports

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Before

Width:  |  Height:  |  Size: 333 KiB

After

Width:  |  Height:  |  Size: 333 KiB

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 276 KiB

Before

Width:  |  Height:  |  Size: 568 KiB

After

Width:  |  Height:  |  Size: 568 KiB

Before

Width:  |  Height:  |  Size: 9.7 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before

Width:  |  Height:  |  Size: 9.7 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before

Width:  |  Height:  |  Size: 398 KiB

After

Width:  |  Height:  |  Size: 398 KiB

Before

Width:  |  Height:  |  Size: 384 KiB

After

Width:  |  Height:  |  Size: 384 KiB

Before

Width:  |  Height:  |  Size: 9.7 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before

Width:  |  Height:  |  Size: 9.7 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before

Width:  |  Height:  |  Size: 9.7 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before

Width:  |  Height:  |  Size: 491 KiB

After

Width:  |  Height:  |  Size: 491 KiB

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

Before

Width:  |  Height:  |  Size: 7.1 MiB

After

Width:  |  Height:  |  Size: 7.1 MiB

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Before

Width:  |  Height:  |  Size: 923 KiB

After

Width:  |  Height:  |  Size: 923 KiB

Before

Width:  |  Height:  |  Size: 491 KiB

After

Width:  |  Height:  |  Size: 491 KiB

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Before

Width:  |  Height:  |  Size: 224 KiB

After

Width:  |  Height:  |  Size: 224 KiB

Before

Width:  |  Height:  |  Size: 151 KiB

After

Width:  |  Height:  |  Size: 151 KiB

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 246 KiB

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Before

Width:  |  Height:  |  Size: 202 KiB

After

Width:  |  Height:  |  Size: 202 KiB

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

@ -1,39 +0,0 @@
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade.backend.crypt import Crypt
# from komrade.backend.the_operator import TheOperator
from komrade.backend.keymaker import Keymaker
from komrade import KomradeException,Logger
from pythemis.skeygen import KEY_PAIR_TYPE, GenerateKeyPair
from pythemis.smessage import SMessage, ssign, sverify
from pythemis.skeygen import GenerateSymmetricKey
from pythemis.scell import SCellSeal
from pythemis.exception import ThemisError
import getpass,os
# paths
PATH_KOMRADE = os.path.abspath(os.path.join(os.path.expanduser('~'),'.komrade'))
PATH_CALLER = os.path.join(PATH_KOMRADE,'.caller')
PATH_CALLER_PUBKEY = os.path.join(PATH_CALLER,'.ca.key.pub.encr')
PATH_CALLER_PRIVKEY = os.path.join(PATH_CALLER,'.ca.key.priv.encr')
PATH_CRYPT_KEYS = os.path.join(PATH_CALLER,'.ca.db.keys.crypt')
PATH_CRYPT_DATA = os.path.join(PATH_CALLER,'.ca.db.data.encr')
# class HelloOperator(object):
# def __init__(self,op=None):
# # for now
# self.op = TheOperator()
# def create_keys(self,name):
# return self.op.create_keys(name)
# def exists(self,*x,**y): return self.op.exists(*x,**y)
if __name__ == '__main__':
#caller = Caller('elon2')
Op = Caller()
# caller.register()

@ -1,85 +0,0 @@
"""
There is only one operator!
Running on node prime.
"""
import os
from flask import Flask
from flask import request
import asyncio
from pythemis.skeygen import KEY_PAIR_TYPE, GenerateKeyPair
from pythemis.smessage import SMessage, ssign, sverify
from pythemis.exception import ThemisError
from base64 import b64encode,b64decode
BSEP=b'||||||||||'
BSEP2=b'@@@@@@@@@@'
BSEP3=b'##########'
HOME_OPERATOR = os.path.abspath(__file__)
PATH_DB_KEYS = os.path.join(HOME_OPERATOR, '.keydb')
keyhome = os.path.join(os.path.expanduser('~'),'.komrade','.keyserver')
if not os.path.exists(keyhome): os.makedirs(keyhome)
keyserver = 'komrade.app'
keyserver_port = 5566
app = Flask(__name__)
async def init():
from api import Api
api = Api()
# keyserver = await api.personate('keyserver')
keypair = GenerateKeyPair(KEY_PAIR_TYPE.EC)
privkey = keypair.export_private_key()
pubkey = keypair.export_public_key()
print('pubkey:',pubkey)
with open('.keyserver.loc','wb') as of: of.write(b64encode(pubkey))
with open(os.path.join(keyhome,'.keyserver.key'),'wb') as of: of.write(b64encode(privkey))
## load pubkey
PATH_PUBKEY = os.path.join(os.path.dirname(__file__),'.keyserver.loc')
PATH_PRIVKEY = os.path.join(keyhome,'.keyserver.key')
if not os.path.exists(PATH_PRIVKEY) or not os.path.exists(PATH_PUBKEY):
asyncio.run(init())
with open(PATH_PUBKEY) as f:
PUBKEY_b64 = f.read()
PUBKEY = b64decode(PUBKEY_b64)
with open(PATH_PRIVKEY) as f:
PRIVKEY_b64 = f.read()
PRIVKEY = b64decode(PRIVKEY_b64)
@app.route('/pub')
def pubkey():
return PUBKEY_b64
@app.route('/add/<name>',methods=['POST'])
def add(name):
key_fn = os.path.join(keyhome,name+'.loc')
if not os.path.exists(key_fn):
with open(key_fn,'wb') as of:
pubkey,signed_pubkey=request.data.split(BSEP)
server_signed_pubkey = b64encode(ssign(PRIVKEY,pubkey))
package = pubkey + BSEP + signed_pubkey + BSEP + server_signed_pubkey
package_b64 = b64encode(package)
print('add package -->',package)
print('add package_b64 -->',package_b64)
of.write(package_b64)
return package_b64
return None
@app.route('/get/<name>')
def get(name):
key_fn = os.path.join(keyhome,name+'.loc')
if os.path.exists(key_fn):
with open(key_fn,'rb') as f:
signed_key=f.read()
return signed_key
return b''
if __name__ == '__main__':
app.run(host='0.0.0.0',port=keyserver_port)
# asyncio.run(init())

@ -1,26 +0,0 @@
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade.backend.operators import *
from flask import Flask
from flask_classful import FlaskView
## Main
OPERATOR = TheOperator()
class OperatorOnPhone(FlaskView):
def index(self):
return OPERATOR.keychain()['pubkey']
def something(self):
return 'something'
def run_forever():
app = Flask(__name__)
switchboard = Switchboard()
switchboard.register(app, route_base='/op/', route_prefix=None)
app.run(debug=True)
if __name__ == '__main__':
run_forever()

@ -1,225 +0,0 @@
"""
There is only one operator!
Running on node prime.
"""
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade.backend.crypt import Crypt
from komrade.backend.caller import Caller
from komrade.backend.keymaker import Keymaker
from flask import Flask
from flask_classful import FlaskView
from pythemis.skeygen import KEY_PAIR_TYPE, GenerateKeyPair
from pythemis.smessage import SMessage, ssign, sverify
from pythemis.skeygen import GenerateSymmetricKey
from pythemis.scell import SCellSeal
from pythemis.exception import ThemisError
from base64 import b64encode,b64decode
from komrade import KomradeException,Logger
import getpass
PATH_HERE = os.path.dirname(__file__)
sys.path.append(PATH_HERE)
from crypt import *
### Constants
BSEP=b'||||||||||'
BSEP2=b'@@@@@@@@@@'
BSEP3=b'##########'
# paths
PATH_KOMRADE = os.path.abspath(os.path.join(os.path.expanduser('~'),'.komrade'))
PATH_OPERATOR = os.path.join(PATH_KOMRADE,'.operator')
PATH_OPERATOR_PUBKEY = os.path.join(PATH_OPERATOR,'.op.key.pub.encr')
PATH_OPERATOR_PRIVKEY = os.path.join(PATH_OPERATOR,'.op.key.priv.encr')
PATH_CRYPT_KEYS = os.path.join(PATH_OPERATOR,'.op.db.keys.crypt')
PATH_CRYPT_DATA = os.path.join(PATH_OPERATOR,'.op.db.data.encr')
# init req paths
if not os.path.exists(PATH_OPERATOR): os.makedirs(PATH_OPERATOR)
class TheOperator(Caller):
"""
The operator.
"""
PATH_CRYPT_KEYS=PATH_CRYPT_KEYS
PATH_CRYPT_DATA=PATH_CRYPT_DATA
def __init__(self, name = 'Operator', passphrase = None):
"""
Boot up the operator. Requires knowing or setting a password of memory.
"""
self.name = name
# Do I have my keys?
have_keys = self.have_keys()
# If not, forge them -- only once!
# if not have_keys: self.forge_keys()
# load keys
# self.pubkey,self.privkey = self.get_op_keys()
# That's it!
def have_keys(self):
self.log('checking for keys...')
have_keys = self.crypt_keys.get(self.name,prefix='/pubkey_encr/')
self.log('have_keys =',have_keys)
return have_keys
# def forge_keys(self):
# self.log('forging keys...')
# # first time only!
# # this will save the three encrypted keys
# # all are returned, including the decryptor keys
# keychain = self.create_keys(self.name,return_all_keys=True)
####
# Key CRUD
####
def forge_new_keys(self,name,pubkey_is_public=False,return_all_keys=False):
self.log('forging new keys...')
# Create public and private keys
keypair = GenerateKeyPair(KEY_PAIR_TYPE.EC)
privkey = keypair.export_private_key()
pubkey = keypair.export_public_key()
adminkey = GenerateSymmetricKey()
# Create decryption/permission keys
pubkey_decr = GenerateSymmetricKey()
privkey_decr = GenerateSymmetricKey()
adminkey_decr = GenerateSymmetricKey() #SCellSeal(passphrase=passphrase)
# Encrypt original keys
pubkey_encr = SCellSeal(key=pubkey_decr).encrypt(pubkey)
privkey_encr = SCellSeal(key=privkey_decr).encrypt(privkey)
adminkey_encr = SCellSeal(key=adminkey_decr).encrypt(adminkey)
# store encrypted on my hardware
self.crypt_keys.set(name,pubkey_encr,prefix='/pubkey_encr/')
self.crypt_keys.set(pubkey,privkey_encr,prefix='/privkey_encr/')
self.crypt_keys.set(privkey,adminkey_encr,prefix='/adminkey_encr/')
# store permissions file?
secret_admin_val = pubkey_encr + BSEP + b'find,read,admin'
if pubkey_is_public: secret_admin_val += b'*'+BSEP+b'find'
secret_admin_val_encr = SCellSeal(key=adminkey).encrypt(secret_admin_val)
self.crypt_keys.set(adminkey,secret_admin_val_encr,prefix='/permkey_encr/')
# keep public key?
if pubkey_is_public: self.crypt_keys.set(name,pubkey_decr,prefix='/pubkey_decr/')
# send back decryption keys to client
if not return_all_keys: # default situation
keychain = {
'pubkey_decr':pubkey_decr,
'privkey_decr':privkey_decr,
'adminkey_decr':adminkey_decr
}
else: # only in special case!
keychain = {
'pubkey':pubkey,'pubkey_encr':pubkey_encr,'pubkey_decr':pubkey_decr,
'privkey':privkey,'privkey_encr':privkey_encr,'privkey_decr':privkey_decr,
'adminkey':adminkey,'adminkey_encr':adminkey_encr,'adminkey_decr':adminkey_decr
}
return keychain
# Magic key attributes
## DECRYPTED REAL FINAL KEYS
def pubkey(self, name, keychain_decr):
pubkey_decr = keychain_decr.get('pubkey_decr')
pubkey_encr = self.pubkey_encr(name)
if not pubkey_decr or not pubkey_encr: return None
pubkey = SCellSeal(key=pubkey_decr).decrypt(pubkey_encr)
return pubkey
def privkey(self, name, keychain_decr):
privkey_decr = keychain_decr.get('privkey_decr')
privkey_encr = self.privkey_encr(name, keychain_decr)
if not privkey_decr or not privkey_encr: return None
privkey = SCellSeal(key=privkey_decr).decrypt(privkey_encr)
return privkey
def adminkey(self, name, keychain_decr):
adminkey_decr = keychain_decr.get('adminkey_decr')
adminkey_encr = self.adminkey_encr(name, keychain_decr)
if not adminkey_decr or not adminkey_encr: return None
adminkey = SCellSeal(key=adminkey_decr).decrypt(adminkey_encr)
return adminkey
def exists(self,name):
return self.crypt_keys.get(name,prefix='/pubkey_encr/') is not None
def login(self, name, keychain_encr):
pass
class TheOperatorView(FlaskView):
route_prefix = '/'
def index(self):
print('hello')
return "<br>".join(quotes)
def something(self):
return 'something'
def get_random_id():
import uuid
return uuid.uuid4().hex
def get_random_binary_id():
import base64
idstr = get_random_id()
return base64.b64encode(idstr.encode())
## Main
def run_forever():
app = Flask(__name__)
TheOperator.register(app, route_base='/op/', route_prefix=None)
app.run(debug=True)
if __name__ == '__main__':
#run_forever()
op = TheOperator()
#print(op.crypt_keys.set('aaaa','1111'))
# print(op.crypt_keys.get('aaaa'))
# print(op.forge_keys())

@ -1,175 +0,0 @@
"""
Kivy asyncio example app.
Kivy needs to run on the main thread and its graphical instructions have to be
called from there. But it's still possible to run an asyncio EventLoop, it
just has to happen on its own, separate thread.
Requires Python 3.5+.
"""
import kivy
kivy.require('1.10.0')
import asyncio
import threading
from kivy.app import App
from kivy.clock import mainthread
from kivy.event import EventDispatcher
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
KV = '''\
<RootLayout>:
orientation: 'vertical'
Button:
id: btn
text: 'Start EventLoop thread.'
on_press: app.start_event_loop_thread()
TextInput:
multiline: False
size_hint_y: 0.25
on_text: app.submit_pulse_text(args[1])
BoxLayout:
Label:
id: pulse_listener
Label:
id: status
'''
class RootLayout(BoxLayout):
pass
class EventLoopWorker(EventDispatcher):
__events__ = ('on_pulse',) # defines this EventDispatcher's sole event
def __init__(self):
super().__init__()
self._thread = threading.Thread(target=self._run_loop) # note the Thread target here
self._thread.daemon = True
self.loop = None
# the following are for the pulse() coroutine, see below
self._default_pulse = ['tick!', 'tock!']
self._pulse = None
self._pulse_task = None
def _run_loop(self):
self.loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(self.loop)
self._restart_pulse()
# this example doesn't include any cleanup code, see the docs on how
# to properly set up and tear down an asyncio event loop
self.loop.run_forever()
def start(self):
self._thread.start()
async def pulse(self):
"""Core coroutine of this asyncio event loop.
Repeats a pulse message in a short interval on three channels:
- using `print()`
- by dispatching a Kivy event `on_pulse` with the help of `@mainthread`
- on the Kivy thread through `kivy_update_status()` with the help of
`@mainthread`
The decorator `@mainthread` is a convenience wrapper around
`Clock.schedule_once()` which ensures the callables run on the Kivy
thread.
"""
for msg in self._pulse_messages():
# show it through the console:
print(msg)
# `EventLoopWorker` is an `EventDispatcher` to which others can
# subscribe. See `display_on_pulse()` in `start_event_loop_thread()`
# on how it is bound to the `on_pulse` event. The indirection
# through the `notify()` function is necessary to apply the
# `@mainthread` decorator (left label):
@mainthread
def notify(text):
self.dispatch('on_pulse', text)
notify(msg) # dispatch the on_pulse event
# Same, but with a direct call instead of an event (right label):
@mainthread
def kivy_update_status(text):
status_label = App.get_running_app().root.ids.status
status_label.text = text
kivy_update_status(msg) # control a Label directly
await asyncio.sleep(1)
def set_pulse_text(self, text):
self._pulse = text
# it's not really necessary to restart this task; just included for the
# sake of this example. Comment this line out and see what happens.
self._restart_pulse()
def _restart_pulse(self):
"""Helper to start/reset the pulse task when the pulse changes."""
if self._pulse_task is not None:
self._pulse_task.cancel()
self._pulse_task = self.loop.create_task(self.pulse())
def on_pulse(self, *_):
"""An EventDispatcher event must have a corresponding method."""
pass
def _pulse_messages(self):
"""A generator providing an inexhaustible supply of pulse messages."""
while True:
if isinstance(self._pulse, str) and self._pulse != '':
pulse = self._pulse.split()
yield from pulse
else:
yield from self._default_pulse
class AsyncioExampleApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.event_loop_worker = None
def build(self):
return RootLayout()
def start_event_loop_thread(self):
"""Start the asyncio event loop thread. Bound to the top button."""
if self.event_loop_worker is not None:
return
self.root.ids.btn.text = ("Running the asyncio EventLoop now...\n\n\n\n"
"Now enter a few words below.")
self.event_loop_worker = worker = EventLoopWorker()
pulse_listener_label = self.root.ids.pulse_listener
def display_on_pulse(instance, text):
pulse_listener_label.text = text
# make the label react to the worker's `on_pulse` event:
worker.bind(on_pulse=display_on_pulse)
worker.start()
def submit_pulse_text(self, text):
"""Send the TextInput string over to the asyncio event loop worker."""
worker = self.event_loop_worker
if worker is not None:
loop = self.event_loop_worker.loop
# use the thread safe variant to run it on the asyncio event loop:
loop.call_soon_threadsafe(worker.set_pulse_text, text)
if __name__ == '__main__':
Builder.load_string(KV)
AsyncioExampleApp().run()

@ -1,91 +0,0 @@
# import logging
# import asyncio
# from kademlia.network import Server
# from kademlia.storage import *
# import shelve
# from collections import OrderedDict
# import pickle,os
# class HalfForgetfulStorage(ForgetfulStorage):
# def __init__(self, ttl=604800):
# """
# By default, max age is a week.
# """
# self.fn='sto.dat'
# if not os.path.exists(self.fn):
# self.data={}
# else:
# with open(self.fn,'rb') as f:
# self.data=pickle.load(f)
# print('loaded:',self.data)
# #self.data = pickle.open('sto.dat','rb') #,writeback=True)
# # self.data = self.store.get('OrderedDict',OrderedDict())
# self.ttl = ttl
# def __setitem__(self, key, value):
# self.data[key] = (time.monotonic(), value)
# self.write()
# def write(self):
# with open(self.fn,'wb') as f:
# pickle.dump(self.data, f, protocol=pickle.HIGHEST_PROTOCOL)
# def get(self, key, default=None):
# # self.cull()
# if key in self.data:
# print('????',self.data[key])
# return self[key]
# return default
# def __getitem__(self, key):
# return self.data[key][1]
# def __repr__(self):
# return repr(self.data)
# def iter_older_than(self, seconds_old):
# min_birthday = time.monotonic() - seconds_old
# zipped = self._triple_iter()
# matches = takewhile(lambda r: min_birthday >= r[1], zipped)
# return list(map(operator.itemgetter(0, 2), matches))
# def _triple_iter(self):
# ikeys = self.data.keys()
# ibirthday = map(operator.itemgetter(0), self.data.values())
# ivalues = map(operator.itemgetter(1), self.data.values())
# return zip(ikeys, ibirthday, ivalues)
# def __iter__(self):
# ikeys = self.data.keys()
# ivalues = map(operator.itemgetter(1), self.data.values())
# return zip(ikeys, ivalues)
# # handler = logging.StreamHandler()
# # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# # handler.setFormatter(formatter)
# # log = logging.getLogger('kademlia')
# # log.addHandler(handler)
# # log.setLevel(logging.DEBUG)
# loop = asyncio.get_event_loop()
# loop.set_debug(True)
# shelf = HalfForgetfulStorage()
# server = Server(storage=shelf)
# loop.run_until_complete(server.listen(8468))
# try:
# loop.run_forever()
# except KeyboardInterrupt:
# pass
# finally:
# server.stop()
# loop.close()

@ -1,96 +0,0 @@
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.screenmanager import Screen
from kivymd.icon_definitions import md_icons
from kivymd.app import MDApp
from kivymd.uix.list import OneLineIconListItem
Builder.load_string(
'''
#:import images_path kivymd.images_path
<CustomOneLineIconListItem>:
IconLeftWidget:
icon: root.icon
<PreviousMDIcons>:
BoxLayout:
orientation: 'vertical'
spacing: dp(10)
padding: dp(20)
BoxLayout:
size_hint_y: None
height: self.minimum_height
MDIconButton:
icon: 'magnify'
MDTextField:
id: search_field
hint_text: 'Search icon'
on_text: root.set_list_md_icons(self.text, True)
RecycleView:
id: rv
key_viewclass: 'viewclass'
key_size: 'height'
RecycleBoxLayout:
padding: dp(10)
default_size: None, dp(48)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
'''
)
class CustomOneLineIconListItem(OneLineIconListItem):
icon = StringProperty()
class PreviousMDIcons(Screen):
def set_list_md_icons(self, text="", search=False):
'''Builds a list of icons for the screen MDIcons.'''
def add_icon_item(name_icon):
self.ids.rv.data.append(
{
"viewclass": "CustomOneLineIconListItem",
"icon": name_icon,
"text": name_icon,
"callback": lambda x: x,
}
)
self.ids.rv.data = []
for name_icon in md_icons.keys():
if search:
if text in name_icon:
add_icon_item(name_icon)
else:
add_icon_item(name_icon)
class MainApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = PreviousMDIcons()
def build(self):
return self.screen
def on_start(self):
self.screen.set_list_md_icons()
MainApp().run()

@ -1,87 +0,0 @@
import asyncio
from kademlia.network import Server
from kademlia.storage import *
import shelve
from collections import OrderedDict
import pickle,os
class HalfForgetfulStorage(ForgetfulStorage):
def __init__(self, ttl=604800):
"""
By default, max age is a week.
"""
self.fn='sto2.dat'
if not os.path.exists(self.fn):
self.data={}
else:
with open(self.fn,'rb') as f:
self.data=pickle.load(f)
print('loaded:',self.data)
#self.data = pickle.open('sto.dat','rb') #,writeback=True)
# self.data = self.store.get('OrderedDict',OrderedDict())
self.ttl = ttl
def __setitem__(self, key, value):
self.data[key] = (time.monotonic(), value)
self.write()
def write(self):
with open(self.fn,'wb') as f:
pickle.dump(self.data, f, protocol=pickle.HIGHEST_PROTOCOL)
def get(self, key, default=None):
# self.cull()
if key in self.data:
print('????',self.data[key])
return self[key]
return default
def __getitem__(self, key):
return self.data[key][1]
def __repr__(self):
return repr(self.data)
def iter_older_than(self, seconds_old):
min_birthday = time.monotonic() - seconds_old
zipped = self._triple_iter()
matches = takewhile(lambda r: min_birthday >= r[1], zipped)
return list(map(operator.itemgetter(0, 2), matches))
def _triple_iter(self):
ikeys = self.data.keys()
ibirthday = map(operator.itemgetter(0), self.data.values())
ivalues = map(operator.itemgetter(1), self.data.values())
return zip(ikeys, ibirthday, ivalues)
def __iter__(self):
ikeys = self.data.keys()
ivalues = map(operator.itemgetter(1), self.data.values())
return zip(ikeys, ivalues)
host="68.66.241.111"
# host="0.0.0.0"
async def run():
# Create a node and start listening on port 5678
node = Server() #storage=HalfForgetfulStorage())
await node.listen(8469)
# Bootstrap the node by connecting to other known nodes, in this case
# replace 123.123.123.123 with the IP of another node and optionally
# give as many ip/port combos as you can for other nodes.
await node.bootstrap([(host, 8468)])
# set a value for the key "my-key" on the network
# await node.set("my-key2", "my awesome value")
# get the value associated with "my-key" from the network
result = await node.get("my-key2")
print(result)
asyncio.run(run())

@ -1,4 +1,4 @@
from komrade.backend.crypt import Crypt
from komrade.operators.crypt import Crypt
from komrade import KomradeException,Logger
from pythemis.skeygen import KEY_PAIR_TYPE, GenerateKeyPair
from pythemis.smessage import SMessage, ssign, sverify

@ -3,8 +3,8 @@ There is only one operator!
Running on node prime.
"""
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade.backend.crypt import Crypt
from komrade.backend.keymaker import Keymaker
from komrade.operators.crypt import Crypt
from komrade.operators.keymaker import Keymaker
from flask import Flask
from flask_classful import FlaskView
from pythemis.skeygen import KEY_PAIR_TYPE, GenerateKeyPair
@ -55,6 +55,15 @@ class Operator(Keymaker):
self._keychain = self.keychain(force = True)
class Caller(Operator):
def get_new_keys(self,pubkey_pass = None, privkey_pass = None, adminkey_pass = None):
# Get decryptor keys back from The Operator (one half of the Keymaker)
keychain = self.forge_new_keys(self.name)
self.log('create_keys() res from Operator? <-',keychain)
# Now lock the decryptor keys away, sealing it with a password of memory!
self.lock_new_keys(keychain)
class TheOperator(Operator):
"""
The remote operator! Only one!
@ -68,23 +77,23 @@ class TheOperator(Operator):
passphrase=getpass.getpass('Hello, this is the Operator speaking. What is the passphrase?\n> ')
super().__init__(name,passphrase)
#self.boot(create=True)
OPERATOR = None
class TheOperatorsSwitchboard(FlaskView):
def index(self):
return OPERATOR.keychain()['pubkey']
def something(self):
return 'something'
# # ca = RemoteOperator(name='elon')
# # # ca.get_new_keys()
# # op.boot()
# # ca.boot()
# #print(op.crypt_keys.set('aaaa','1111'))
# # print(op.crypt_keys.get('aaaa'))
# # print(op.forge_keys())
# # from pprint import pprint
# # keychain = op.keychain()
# # pprint(keychain)
# # print(len(keychain))
def run_forever():
global OPERATOR
OPERATOR = TheOperator()
app = Flask(__name__)
TheOperatorsSwitchboard.register(app, route_base='/op/', route_prefix=None)
app.run(debug=True)
# print('Op pubkey:',op.keychain()['pubkey'])
# print('Ca pubkey:',ca.keychain()['pubkey'])
if __name__ == '__main__':
run_forever()
Loading…
Cancel
Save