def own_wallet_categories(self): all_cat_unique = [] idb = localdb.DB() all_cat = idb.select('address_category', ['category']) for rr in all_cat: if rr[0] not in all_cat_unique: all_cat_unique.append(rr[0]) if 'Excluded' not in all_cat_unique: all_cat_unique = ['Excluded'] + all_cat_unique if 'Not hidden' not in all_cat_unique: all_cat_unique = ['Not hidden'] + all_cat_unique if 'All' not in all_cat_unique: all_cat_unique = ['All'] + all_cat_unique if 'Hidden' not in all_cat_unique: all_cat_unique = all_cat_unique + ['Hidden'] if 'Edit' not in all_cat_unique: all_cat_unique = all_cat_unique + ['Edit'] return all_cat_unique
def close_all_notif(self,*eventargs): idb=localdb.DB() table={} table['notifications']=[{'closed':'True'}] idb.update(table,['closed'],{} ) self.update_notif_frame()
def set_que_waiting(self,command,jsonstr='', wait_seconds=0): idb=localdb.DB() tmparr=[0] latestid1=idb.select_max_val( 'queue_done','id' ) if len(latestid1)>0: if latestid1[0][0]!=None: tmparr.append(latestid1[0][0]) latestid2=idb.select_max_val( 'queue_waiting','id') if len(latestid2)>0: if latestid2[0][0]!=None: tmparr.append(latestid2[0][0]) nextid=max(tmparr)+1 return {"type":'manual' , "wait_seconds":wait_seconds # max time to wait , "created_time":app_fun.now_to_str(False) #datetime of creation , "command":command # send, new wallet, ... , "json":jsonstr # if needed , "id":nextid # uniwue id , "status":'waiting' }
def update_list(self): idb=localdb.DB() wwhere={} llast=self.filter_table.get_value('last') if llast=='24h': wwhere['datetime(created_time)']=['>=',"datetime('"+app_fun.date2str(datetime.datetime.now()-datetime.timedelta(hours=24) )+"')"] elif llast=='week': wwhere['datetime(created_time)']=['>=',"datetime('"+app_fun.date2str(datetime.datetime.now()-datetime.timedelta(days=7) )+"')"] elif llast=='month': wwhere['datetime(created_time)']=['>=',"datetime('"+app_fun.date2str(datetime.datetime.now()-datetime.timedelta(days=31) )+"')"] elif llast=='12 months': wwhere['datetime(created_time)']=['>=',"datetime('"+app_fun.date2str(datetime.datetime.now()-datetime.timedelta(days=365) )+"')"] task_done=idb.select('queue_done', ['type','command','json','created_time','end_time','result','wait_seconds','id'],where=wwhere,orderby=[{'end_time':'desc'},{'created_time':'desc'}]) ccat=self.filter_table.get_value('category') rres=self.filter_table.get_value('result') cmd=self.filter_table.get_value('command') for rr in task_done: tmpdict={} sstyle={'bgc':'green','fgc':'#fff'} short_result='Success/True' if 'error' in rr[5].lower() or 'failed' in rr[5].lower() or 'false' in rr[5].lower(): short_result='Failed/False' sstyle={'bgc':'red','fgc':'black'} elif 'cancelled' in rr[5].lower(): short_result='Cancelled' sstyle={'bgc':'blue','fgc':'white'} visible=True if ccat not in ['All',rr[0]]: continue # visible=False if cmd not in ['All',rr[1]]: continue # visible=False if rres!='All' and rres not in short_result: # print(133,short_result) # visible=False continue tmpdict[rr[7]]=[{'T':'LabelV', 'L':rr[0], 'uid':'cat'+str(rr[7]), 'visible':visible } , {'T':'LabelV', 'L':rr[1], 'uid':'cmd'+str(rr[7]) , 'visible':visible} , {'T':'InputL', 'L':rr[2], 'uid':'json'+str(rr[7]) , 'visible':visible, 'width':24} , {'T':'LabelV', 'L':rr[3], 'uid':'ctime'+str(rr[7]) , 'visible':visible} , {'T':'LabelV', 'L':rr[4], 'uid':'etime'+str(rr[7]), 'visible':visible} , {'T':'LabelV', 'L':short_result, 'uid':'res'+str(rr[7]) , 'visible':visible, 'style':sstyle} , {'T':'LabelV', 'L':str(rr[6]), 'uid':'wait'+str(rr[7]) , 'visible':visible} , {'T':'InputL', 'L':rr[5], 'uid':'details'+str(rr[7]), 'visible':visible, 'width':32 } #app_fun.json_to_str(rr[5] ) ] self.grid_settings.append(tmpdict)
def update_grid(*argsevnts): global grid_lol_select tmplen = len(grid_lol_select) if tmplen > 1: del grid_lol_select[1:tmplen] idb = localdb.DB() sel_addr_book = idb.select( 'addr_book', ['Category', 'Alias', 'Address', 'usage'], orderby=[{ 'usage': 'desc' }, { 'Category': 'asc' }, { 'Alias': 'asc' }]) if len(sel_addr_book) > 0: filterv = filtbox.get() for ii, rr in enumerate(sel_addr_book): tmpdict = {} visible = False if filterv in [rr[0], 'All']: visible = True tmpdict[ii] = [{ 'T': 'Button', 'L': 'Select', 'uid': 'select' + str(ii), 'visible': visible }, { 'T': 'LabelV', 'L': str(rr[3]), 'uid': 'Usage' + str(ii), 'visible': visible }, { 'T': 'LabelV', 'L': rr[0], 'uid': 'Category' + str(ii), 'visible': visible }, { 'T': 'LabelV', 'L': rr[1], 'uid': 'Alias' + str(ii), 'visible': visible }, { 'T': 'LabelV', 'L': rr[2], 'uid': 'Address' + str(ii), 'visible': visible }] grid_lol_select.append(tmpdict)
def ok_close(struid,*evargs): idb=localdb.DB() table={} table['notifications']=[{'closed':'True'}] try: idb.update(table,['closed'],where={'uid':['=',int(struid)]}) self.update_notif_frame() except: pass
def update_list(self): idb=localdb.DB() ff=self.filter_table.get_value('category') wwhere={} if ff=='New': wwhere ={'closed':['<>',"'True'"]} else: wwhere ={'closed':['=',"'True'"]} task_done=idb.select('notifications', ['uid','datetime' ,'opname' ,'details' ,'status' ,'closed','orig_json'],where=wwhere,orderby=[{'uid':'desc'}]) for ij,rr in enumerate(task_done): tmpdict={} visible=True okclosebutton={'T':'Button', 'L':'Ok, close', 'uid':'ok'+str(rr[0]) , 'visible':visible, 'tooltip':rr[0]} if rr[5]=='True': okclosebutton={} #{'T':'LabelE'} review={} #{'T':'LabelE'} tmpdetails=rr[6] # print('orig_json',rr[3]) if rr[2] =='payment request' and rr[5]!='True': tmp=rr[6].split('PaymentRequest;') tmpdetails=tmp[0] tmp=tmp[-1] review={'T':'Button', 'L':'Review', 'uid':'rev'+str(rr[0]) , 'visible':visible, 'tooltip':tmp} # tmpdetails=rr[6] #[15:] # else: # okclosebutton={'T':'LabelE' } # print(rr[0]) okclosebutton={'T':'LabelV','L':'','uid':'ok'+str(rr[0])} # print(okclosebutton,review) tmpdict[rr[0]]=[{'T':'LabelV', 'L':rr[1], 'uid':'date'+str(rr[0]), 'visible':visible } , {'T':'LabelV', 'L':rr[2], 'uid':'name'+str(rr[0]) , 'visible':visible} , {'T':'InputL', 'L':tmpdetails, 'uid':'det'+str(rr[0]) , 'visible':visible, 'width':48} , {'T':'LabelV', 'L': rr[4], 'uid':'stat'+str(rr[0]), 'visible':visible, 'width':11 } , okclosebutton, review ] self.grid_notif.append(tmpdict)
def __init__(self,parent_frame): self.grid_settings=[] self.update_in_progress=False idb=localdb.DB() frame0=ttk.LabelFrame(parent_frame,text='Filter') # frame0.grid(row=0,column=0, sticky="nsew") task_done=idb.select('queue_done', ['command'],distinct=True) tmpcommands=[cc[0] for cc in task_done] tmpdict={} tmpdict['filters']=[{'T':'LabelC', 'L':'Category: '} , {'T':'Combox', 'uid':'category', 'V':['All','manual','auto'] } , {'T':'LabelC', 'L':'Command: '} , {'T':'Combox', 'uid':'command', 'V':['All']+tmpcommands } , {'T':'LabelC', 'L':'Last: '} , {'T':'Combox', 'uid':'last', 'V':['24h','week','month','12 months','All'] } , {'T':'LabelC', 'L':'Result: '} , {'T':'Combox', 'uid':'result', 'V':['All','Failed','Success','Cancelled'] } ] grid_filter=[] grid_filter.append(tmpdict ) self.filter_table=flexitable.FlexiTable(frame0,grid_filter) # addr book view left: frame1=ttk.LabelFrame(parent_frame,text='Tasks list') frame1.grid(row=1,column=0, sticky="nsew") tmpdict={} tmpdict['head']=[{'T':'LabelC', 'L':'Category' } , {'T':'LabelC', 'L':'Command' } , {'T':'LabelC', 'L':'Command json' } , {'T':'LabelC', 'L':'Created at' } , {'T':'LabelC', 'L':'Finished at' } , {'T':'LabelC', 'L':'Result' } , {'T':'LabelC', 'L':'wait_seconds' } , {'T':'LabelC', 'L':'Result details' } ] self.grid_settings.append(tmpdict) self.update_list() self.main_table=flexitable.FlexiTable(frame1,self.grid_settings, min_canvas_width=1200,force_scroll=True) self.filter_table.bind_combox_cmd('category',[], self.update_history_frame ) self.filter_table.bind_combox_cmd('result',[], self.update_history_frame ) self.filter_table.bind_combox_cmd('command',[], self.update_history_frame ) self.filter_table.bind_combox_cmd('last',[], self.update_history_frame )
def categories_filter(self): all_cat_unique = [] idb = localdb.DB() sel_addr_book = idb.select('addr_book', ['Category']) for kk in sel_addr_book: if kk[0] not in all_cat_unique: all_cat_unique.append(kk[0]) if 'All' not in all_cat_unique: all_cat_unique = ['All'] + all_cat_unique return all_cat_unique
def encr_db(): global wallet_display_set, dmn, cc #app_password # add db lock for threads dict_set = {} dict_set['lock_db_threads'] = [{'lock': 'yes'}] idb = localdb.DB('init.db') if idb.check_table_exist('lock_db_threads'): idb.upsert(dict_set, ["lock"], {}) dmn.started = False # ??? ppath = os.getcwd() if localdb.is_busy(): time.sleep(1) tryii = 2 while localdb.is_busy(): time.sleep(1) tryii = tryii - 1 if tryii < 0: print('exit anyway ...') break localdb.del_busy_too_long() tryii = 3 while tryii > 0: tryii = tryii - 1 # try: if True: cc.aes_encrypt_file(os.path.join(ppath, 'local_storage.db'), os.path.join(ppath, 'local_storage.encr'), wallet_display_set.password) if os.path.exists(os.path.join(ppath, 'local_storage.encr')): app_fun.secure_delete(os.path.join(ppath, 'local_storage.db')) flexitable.messagebox_showinfo( "local_storage.db encrypted", "DB secure: local_storage.db -> local_storage.encr ") break # except: print('Exception in delete local_storage.db', tryii) time.sleep(1)
def close_request( decis,*evargs): # print('decis',decis) idb=localdb.DB() table={} table['notifications']=[ {'opname':'PaymentRequest '+decis,'closed':'True' }] # print(rev_id) try: id=int(rev_id ) # print('id',id) idb.update(table,['opname','closed'],{'uid':['=',id]} ) except: # print('bad id?? 141 notif') pass formframe.destroy()
def thread_loop(): global queue_start_stop, autostart, queue_com, wallet_display_set, dmn while len(additional_obj) != 4: time.sleep(1) dmn.set_wallet_widgets(stat_lab, bstartstop, wallet_summary_frame, wallet_details, wallet_display_set, additional_obj['queue_status'], additional_obj['tahi'], additional_obj['txhi'], additional_obj['notif'], messages) while not close_thread: grid_queue = wallet_display_set.prepare_queue_frame() if len(grid_queue) > 0: additional_obj['queue_status'].update_frame(grid_queue) wallet_display_set.queue_frame_buttons( grid_queue, additional_obj['queue_status']) if queue_com.qsize(): # start stop blockchain ON/OFF try: id, msgstr, ffunn = queue_com.get(0) idb = localdb.DB() done = idb.select('queue_done', ['result'], {'id': ['=', id]}) if len(done) > 0: ffunn(id, msgstr, done) except Queue.Empty: pass if queue_start_stop.qsize(): # start stop blockchain ON/OFF try: cmd = queue_start_stop.get(0) if cmd['cmd'] == 'stop_deamon': dmn.stop_deamon() elif cmd['cmd'] == 'start_deamon': dmn.start_deamon(cmd['addrescan']) except: #Queue.Empty: pass if dmn.started: dmn.update_status() elif autostart != 'no': autostart = 'no' dmn.start_deamon() time.sleep(1)
def on_closing(): global dmn, close_thread #, app_password close_thread = True idb = localdb.DB() idb.vacuum() is_deamon_working = app_fun.check_deamon_running() if is_deamon_working[0]: if messagebox.askokcancel( "Quit", "Are you sure you want to quit? Blockchain deamon is still running. If you plan to shut down your computer it is better to STOP blockchain and quit afterwards." ): encr_db() #True root.destroy() else: encr_db() root.destroy()
def update_filter_cmd(self): idb=localdb.DB() task_done=idb.select('queue_done', ['command'],distinct=True) tmpcommands=[cc[0] for cc in task_done] tmpdict={} tmpdict['filters']=[{'T':'LabelC', 'L':'Category: '} , {'T':'Combox', 'uid':'category', 'V':['All','manual','auto'] } , {'T':'LabelC', 'L':'Command: '} , {'T':'Combox', 'uid':'command', 'V':['All']+tmpcommands } , {'T':'LabelC', 'L':'Last: '} , {'T':'Combox', 'uid':'last', 'V':['24h','week','month','12 months','All'] } , {'T':'LabelC', 'L':'Result: '} , {'T':'Combox', 'uid':'result', 'V':['All','Failed','Success'] } ] grid_filter=[] grid_filter.append(tmpdict ) self.filter_table.update_frame(grid_filter,head_offset=-1)
def selecting_addr_from_book_set_and_destroy( self, addr, uid, frame_to_destroy, *evargs): # here also get signature! uid = uid.replace('_edit', '') if addr != '': idb = localdb.DB() if 'unknown' in uid: uid = uid.replace('edit_unknown_', '') msg_upd = {'msgs_inout': [{'addr_ext': addr}]} idb.update(msg_upd, ['addr_ext'], where={'uid': ['=', uid]}) elif 'uid_' in uid: # first assignments of addr uid = uid.replace('uid_', '') in_sign_upd = {'in_signatures': [{'addr_from_book': addr}]} idb.update(in_sign_upd, ['addr_from_book'], {'uid': ['=', uid]}) msg_upd = {'msgs_inout': [{'addr_ext': addr}]} idb.update(msg_upd, ['addr_ext'], where={'in_sign_uid': ['=', uid]}) elif addr != uid: in_sign_upd = {'in_signatures': [{'addr_from_book': addr}]} idb.update(in_sign_upd, ['addr_from_book'], {'addr_from_book': ['=', "'" + uid + "'"]}) msg_upd = {'msgs_inout': [{'addr_ext': addr}]} idb.update(msg_upd, ['addr_ext'], where={ 'addr_ext': ['=', "'" + uid + "'"], 'type': ['=', "'in'"] }) self.proc_inout() self.update_tread_frame() self.cur_uid = self.valid_uids[0] #self.thr_ord[0]+'_' self.update_msg_frame() frame_to_destroy.destroy()
def isvalid(pas): ppath = os.getcwd() if os.path.exists(os.path.join(ppath, 'local_storage.encr')): cc.aes_decrypt_file(os.path.join(ppath, 'local_storage.encr'), os.path.join(ppath, 'local_storage.db'), pas) idb = localdb.DB() at = idb.all_tables() if len(at) > 0: app_fun.secure_delete(os.path.join(ppath, 'local_storage.encr')) return True elif os.path.exists(os.path.join(ppath, 'local_storage.db')): return True return False
def drop_alias(uid, *evargs): uid = uid.replace('_drop_', '') if 'uid_' in uid: self.warning_info( 'No address to drop!', uid + ' is not an address. There is no address/alias assigned from address book to drop it.' ) return idb = localdb.DB() if len( idb.select('msgs_inout', ['uid', 'in_sign_uid', 'addr_ext'], { 'addr_ext': ['=', "'" + uid + "'"], 'type': ['=', "'in'"] })) == 0: self.warning_info( 'Nothing to drop!', 'There is no incoming messages to unassign from this thread.' ) return in_sign_upd = {'in_signatures': [{'addr_from_book': ''}]} idb.update(in_sign_upd, ['addr_from_book'], {'addr_from_book': ['=', "'" + uid + "'"]}) msg_upd = {'msgs_inout': [{'addr_ext': ''}]} idb.update(msg_upd, ['addr_ext'], where={ 'addr_ext': ['=', "'" + uid + "'"], 'type': ['=', "'in'"] }) self.proc_inout() self.update_tread_frame() self.cur_uid = self.valid_uids[0] #self.thr_ord[0]+'_' self.update_msg_frame()
def send(): global tmpaddr msg = msg_table.get_value('msg') if msg.strip() == '': return to = tmpaddr if tmpaddr == '': to = msg_table.get_value('addr') froma = msg_table.get_value('ownaddr') if froma == '': return got_bad_char, msg_arr = self.prep_msg(msg, to) if got_bad_char: return ddict = {'fromaddr': froma, 'to': []} # for mm in msg_arr: ddict['to'].append({'z': to, 'a': 0.0001, 'm': mm}) table = {} table['queue_waiting'] = [ localdb.set_que_waiting('send', jsonstr=json.dumps(ddict)) ] table['queue_waiting'][0]['type'] = 'message' idb = localdb.DB() idb.insert(table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ]) # self.set_last_addr_from( froma) localdb.set_last_addr_from(froma, "'last_msg_from_addr'") selframe.destroy()
def approve(*evargs): tmpdict=json.loads(strjson) # print('approved ',tmpdict) tmpsignature=localdb.get_addr_to_hash(tmpdict['toaddress']) tmpfromaddr=g1_table.get_value('seladdr') #localdb.get_last_addr_from( "'last_book_from_addr'") memotxt='Payment for '+tmpdict['title'] if len(tmpdict['docuri'].strip())>1: memotxt+=' docuri: '+tmpdict['docuri'] memotxt+=tmpsignature ddict={'fromaddr':tmpfromaddr, 'to':[{'z':tmpdict['toaddress'],'a':tmpdict['amount'],'m':memotxt }] } table={} table['queue_waiting']=[localdb.set_que_waiting('send',jsonstr=json.dumps(ddict) ) ] idb=localdb.DB() idb.insert(table,['type','wait_seconds','created_time','command' ,'json','id','status' ]) # 1. send tx # 2. update notifications closed and opname close_request('Approved') flexitable.showinfo('Payment Request approved','Payment Request to address of amount '+str(tmpdict['amount'])+'\n'+tmpdict['toaddress']+'\nAPPROVED')
def save_wallet_display(opt, *evnt): global wds idb = localdb.DB() table = {} vv = wallet_summary_frame.get_value(opt.replace( 'ing', '')) # name similar to uid hence hack table['wallet_display'] = [{'option': opt, 'value': vv}] idb.upsert(table, ['option', 'value'], {'option': ['=', "'" + opt + "'"]}) while wds.is_locked(): time.sleep(1) wds.lock_basic_frames() grid_lol_wallet_sum = wds.prepare_summary_frame() wallet_summary_frame.update_frame(grid_lol_wallet_sum) grid_lol3 = wds.prepare_byaddr_frame() wallet_details.update_frame(grid_lol3) wds.prepare_byaddr_button_cmd(grid_lol3, wallet_details) wds.unlock_basic_frames()
def __init__(self, parent_frame, wds): global idb self.grid_settings = [] ################ PASS CHANGE frame0 = ttk.LabelFrame(parent_frame, text='Password change') frame0.grid(row=0, column=0, sticky="nsew") tmpdict = {} tmpdict['pass_change'] = [{ 'T': 'LabelC', 'L': 'Current password: '******'T': 'InputL', 'L': '', 'uid': 'old', 'width': 16 }, { 'T': 'LabelC', 'L': 'New password: '******'T': 'InputL', 'L': '', 'uid': 'new', 'width': 16 }, { 'T': 'Button', 'L': 'Change', 'uid': 'enter', 'width': 8 }] grid_pass = [] grid_pass.append(tmpdict) self.pass_table = flexitable.FlexiTable( frame0, grid_pass) # +++ update command filter after each iteration def clear_change_info(*evargs): newpass = self.pass_table.get_value('new').strip() wds.password = newpass # clear self.pass_table.set_textvariable('new', '') self.pass_table.set_textvariable('old', '') # info messagebox.showinfo( "Password changed", "You have new password! Leading and trailing spaces where removed from the password to avoid mistakes." ) self.pass_table.set_cmd('enter', [], clear_change_info) ################ DB maintenance / clear old tasks {'total_chars':total_chars, 'total_rows':rowsii, 'older_chars':older_chars, 'old_rows':old_rows} idb = localdb.DB() frame1 = ttk.LabelFrame(parent_frame, text='DB maintenance') frame1.grid(row=0, column=1, sticky="nsew") def update_db_info(): global idb grid_db = [] tmpsize = idb.table_size('jsons') tmpdict = {} tmpdict['jsons'] = [{ 'uid': '4', 'T': 'LabelV', 'L': '[jsons] table size: ' + str(tmpsize['total_chars']) + ' chars ' + str(tmpsize['total_rows']) + ' rows ' }] grid_db.append(tmpdict) tmpsize = idb.table_size('tx_history') tmpdict = {} tmpdict['tx_history'] = [{ 'uid': '2', 'T': 'LabelV', 'L': '[tx_history] table size: ' + str(tmpsize['total_chars']) + ' chars ' + str(tmpsize['total_rows']) + ' rows ' }] grid_db.append(tmpdict) tmpsize = idb.table_size('notifications') tmpdict = {} tmpdict['db_clear_old_notif'] = [{ 'uid': '3', 'T': 'LabelV', 'L': '[notifications] table size: ' + str(tmpsize['total_chars']) + ' chars ' + str(tmpsize['total_rows']) + ' rows ' }] grid_db.append(tmpdict) tmpdict = {} tmpdict['db_clear_old_notif2'] = [{ 'T': 'Button', 'L': 'Delete all notifications', 'uid': 'del_notif' }] grid_db.append(tmpdict) tmpsize = idb.table_size('queue_done') tmpdict = {} tmpdict['db_clear_old_tasks'] = [{ 'uid': '0', 'T': 'LabelV', 'L': 'Tasks history table size: ' + str(tmpsize['total_chars']) + ' chars ' + str(tmpsize['total_rows']) + ' rows ' }] grid_db.append(tmpdict) tmpdict = {} tmpdict['db_clear_old_tasks1'] = [{ 'uid': '1', 'T': 'LabelV', 'L': 'Older then 1 month: ' + str(tmpsize['older_chars']) + ' chars ' + str(tmpsize['old_rows']) + ' rows ' }] grid_db.append(tmpdict) tmpdict = {} tmpdict['db_clear_old_tasks2'] = [{ 'T': 'Button', 'L': 'Delete old tasks', 'uid': 'del' }] grid_db.append(tmpdict) return grid_db grid_db = update_db_info() self.db_table = flexitable.FlexiTable(frame1, grid_db) def delete_old(tname, datetime_colname, ddays, *evargs): global idb idb.delete_old(tname, datetime_colname, ddays) self.db_table.update_frame(update_db_info()) self.db_table.set_cmd('del', ['queue_done', 'created_time', 31], delete_old) self.db_table.set_cmd('del_notif', ['notifications', 'datetime', 0], delete_old) self.db_table.set_cmd('del', ['queue_done', 'created_time', 31], delete_old) self.db_table.set_cmd('del_notif', ['notifications', 'datetime', 0], delete_old)
def update_list(self): idb = localdb.DB() msg_filter = self.filter_table.get_value('msg') llimit = 9999 if msg_filter == 'Last 10': llimit = 10 elif msg_filter == 'Last 100': llimit = 100 threads_aa = self.threads_aa for k in self.thr_ord: tmpuid = threads_aa[k][2] wwhere = {} if threads_aa[k][0] == 'unknown': wwhere = { 'proc_json': ['=', "'True'"], 'type': ['=', "'in'"], 'in_sign_uid': ['<', 0] } elif 'uid_' in threads_aa[k][1]: wwhere = { 'proc_json': ['=', "'True'"], 'in_sign_uid': ['=', threads_aa[k][0].replace('uid_', '')] } # ? int() else: #if threads_aa[k][1]!='unknown': wwhere = { 'proc_json': ['=', "'True'"], 'addr_ext': ['=', "'" + threads_aa[k][0] + "'"], 'in_sign_uid': ['>', -2] } tmp_msg = idb.select( 'msgs_inout', ['type', 'msg', 'date_time', 'uid', 'in_sign_uid'], where=wwhere, orderby=[{ 'date_time': 'desc' }], limit=llimit) tmpdict = { threads_aa[k][1]: [ { 'T': 'LabelV', 'L': 'Correspondence with [' + threads_aa[k][1] + ']', 'uid': tmpuid, 'width': 32 } #, 'width':64 , { 'T': 'Button', 'L': 'Edit alias', 'uid': tmpuid + '_edit', 'width': 8, 'style': { 'bgc': '#eee', 'fgc': 'black', 'fontsize': 8 } }, { 'T': 'Button', 'L': 'Reply', 'uid': tmpuid + '_reply', 'width': 8, 'style': { 'bgc': '#fff', 'fgc': 'green', 'fontsize': 8 } }, { 'T': 'Button', 'L': 'Drop alias', 'uid': tmpuid + '_drop', 'width': 8, 'style': { 'bgc': '#eee', 'fgc': 'red', 'fontsize': 8 } } ] } if threads_aa[k][0] == 'unknown': tmpdict[threads_aa[k][1]][1]['uid'] = 'edit_unknown_' + str( tmp_msg[0][3]) msg_flow = [] msg_flow.append(tmpdict) for tm in tmp_msg: sstyle2 = {'bgc': '#fff', 'fgc': '#333'} tmppadx = 0 if tm[0] == 'out': sstyle2 = {'bgc': '#ddd', 'fgc': 'black'} tmppadx = 10 tmpdict = { tm[2]: [{ 'T': 'LabelV', 'L': tm[2] + ' ' + tm[1], 'uid': str(tm[3]), 'width': 112, 'wraplength': 600, 'style': sstyle2, 'span': 4, 'pads': [tmppadx, 0] }] } #, 'pads':[tmppadx,0] msg_flow.append(tmpdict) self.grid_threads_msg[tmpuid + '_'] = msg_flow
def update_threads(self): idb = localdb.DB() thr_filter = self.filter_table.get_value('thr') wwhere = {} #'Last 7 days','Last 30 days','All' if thr_filter == 'Last 7 days': wwhere = { 'date_time': ['>=', "'" + app_fun.today_add_days(-7) + "'"], 'in_sign_uid': ['>', -2] } # elif thr_filter == 'Last 30 days': wwhere = { 'date_time': ['>=', "'" + app_fun.today_add_days(-30) + "'"], 'in_sign_uid': ['>', -2] } adr_date = idb.select_max_val('msgs_inout', ['in_sign_uid', 'date_time'], where=wwhere, groupby=['addr_ext']) if hasattr(self, "adr_date") and self.adr_date == adr_date: return 0 self.adr_date = adr_date tmplen = len(self.grid_threads) if tmplen > 1: del self.grid_threads[1:tmplen] threads_aa = {} same_date_count = {} unk_count = 1 for ad in adr_date: tmpalias = '' tmpaddr = ad[0] tmpuid = str(ad[0]) if ad[0] != None and ad[0] != '': # all out + some in alias_from_book = idb.select( 'addr_book', ['Alias'], {'Address': ['=', "'" + ad[0] + "'"]}) # if len(alias_from_book) > 0: if alias_from_book[0][0] != None and alias_from_book[0][ 0] != '': tmpalias = alias_from_book[0][0] else: # or maybe empty tmpalias = ad[0][3:9] else: if 'uid' == ad[0][:3]: # if addr may be not in a book tmpalias = ad[0] else: tmpalias = ad[0][3:9] else: if ad[1] > -1: #got signature tmpalias = 'uid_' + str( ad[1]) # ad[1] #'uid_'+in_sign_uid tmpaddr = 'uid_' + str(ad[1]) else: tmpalias = 'unknown_' + str(unk_count) tmpaddr = 'unknown' #+str(unk_count) unk_count += 1 tmpuid = tmpalias if ad[2] not in threads_aa: same_date_count[ad[2]] = 1 else: same_date_count[ad[2]] = same_date_count[ad[2]] + 1 threads_aa[ad[2] + '__' + str(same_date_count[ad[2]])] = [ tmpaddr, tmpalias, tmpuid ] self.threads_aa = threads_aa self.thr_ord = sorted(threads_aa.keys(), reverse=True) self.valid_uids = [] for k in self.thr_ord: tmpdict = { k: [{ 'T': 'Button', 'L': threads_aa[k][1], 'uid': threads_aa[k][2], 'tooltip': threads_aa[k][0] }] } self.grid_threads.append(tmpdict) self.valid_uids.append(threads_aa[k][2] + '_') return 1
def proc_inout( self): # goal - set addr_ext and in_sign_uid for incoming msg idb = localdb.DB() mio = idb.select('msgs_inout', [ 'type', 'addr_ext', 'date_time', 'msg', 'in_sign_uid', 'uid', 'tx_status', 'txid' ], {'proc_json': ['=', "'False'"]}, orderby=[{ 'date_time': 'asc' }]) # if len(mio) == 0: return for mm in mio: mm1 = mm[1] tmpmsg = mm[3] if mm[0] == 'out': table = {'msgs_inout': [{'proc_json': 'True'}]} idb.update(table, ['proc_json'], {'uid': ['=', mm[5]]}) elif mm[0] == 'in': fsign = json.loads(mm1) uid, addr_from_book = self.match_sign(fsign) addr_ext = '' if uid > -1: tmpalias = 'uid_' + str(uid) if addr_from_book != '': addr_ext = addr_from_book tmpalias = idb.select( 'addr_book', ['Alias'], {'Address': ['=', "'" + addr_from_book + "'"]}) tmpalias = tmpalias[0][0] else: addr_ext = tmpalias table_h = {} uidtmp = tmpalias + ';uid=' + str(uid) + ': ' table_h['tx_history'] = [{'from_str': uidtmp + mm[3]}] idb.update(table_h, ['from_str'], {'txid': ['=', "'" + mm[7] + "'"]}) table_n = {} orig_json = idb.select( 'notifications', ['orig_json'], {'details': ['=', "'" + mm[7] + "'"]}) uidtmp = 'From ' + tmpalias + ';uid=' + str( uid) + ': ' + orig_json[0][0] table_n['notifications'] = [{'orig_json': uidtmp}] idb.update(table_n, ['orig_json'], {'details': ['=', "'" + mm[7] + "'"]}) if tmpmsg == '': tmpmsg = 'Received ' + orig_json[0][0] # 'type', tmptype = mm[0] if 'PaymentRequest' in mm[3]: tmptype = 'PaymentRequest' tmpmsg = tmpmsg.split('PaymentRequest;') tmpmsg = tmpmsg[-1] tmpmsg = 'Payment request ' + app_fun.json_to_str( json.loads(tmpmsg), tt='') table = { 'msgs_inout': [{ 'type': tmptype, 'proc_json': 'True', 'in_sign_uid': uid, 'addr_ext': addr_ext, 'msg': tmpmsg }] } idb.update( table, ['type', 'proc_json', 'in_sign_uid', 'addr_ext', 'msg'], {'uid': ['=', mm[5]]})
return True elif os.path.exists(os.path.join(ppath, 'local_storage.db')): return True return False tt = None deamon_cfg = None ###################### ASK INIT SETUP is_deamon_working = app_fun.check_deamon_running() idb = localdb.DB('init.db') tt = idb.select('init_settings', columns=["komodo", "datadir", "start_chain"]) #"password_on", if is_deamon_working[0]: if len(tt) == 0: flexitable.messagebox_showinfo( "init.db file missing while running - exit", "init.db file missing while running - exit") exit() else: # is_deamon_working[0]==False: wallet_tab.ask_paths() # after change load tt from db tt = idb.select('init_settings', columns=["komodo", "datadir", "start_chain"]) if len(tt) == 0:
def update_historical_txs(self,freshutxo): # max count: 80*tps * 60 =4800 < 5000 idb=localdb.DB() iterat_arr=freshutxo full_check=False if self.history_update_counter%60==0: iterat_arr=self.addr_list # oncece a 60 times check full full_check=True self.history_update_counter+=1 table_history_notif={} for aa in iterat_arr: # try: if True: tt=aa if full_check: tmp1=app_fun.run_process(self.cli_cmd,['z_listreceivedbyaddress',aa,str(self.min_conf) ]) try: tt=json.loads(tmp1) except: print('Exception wal api 85 ',tmp1) break else: aa=tt['address'] tt=[tt] if aa not in self.historical_txs: self.historical_txs[aa]={} for tx in tt: if "txid" not in tx: continue if tx["txid"] not in self.historical_txs[aa]: # if this ever change - may be needed to update some records in case of reorg ? self.historical_txs[aa][tx["txid"]]={} if tx['change']: continue outindex=0 if 'outindex' in tx: outindex=tx['outindex'] elif 'jsoutindex' in tx: outindex=tx['jsoutindex'] if outindex not in self.historical_txs[aa][tx["txid"]]: # 'Category'= "'outindex_"+str(outindex)+"'" tmpmemo=tx["memo"] try: tmpmemo=bytes.fromhex(tmpmemo).decode('utf-8') #int(tx["memo"], 16) except: pass # print(226) tmpmemo=self.clear_memo(tmpmemo) self.historical_txs[aa][tx["txid"]][outindex] = { "amount":tx["amount"]} #,"conf":tx["confirmations"],"memo":tmpmemo } tmpwhere={'to_str':['=',"'"+aa+"'"],'Type':['=',"'in'"],'txid':['=',"'"+tx["txid"]+"'"],'Category':['=',"'outindex_"+str(outindex)+"'"] } checkexist=idb.select('tx_history', ["Type"],tmpwhere) # if len(checkexist)==0: table={} y=self.getinfo() dt,ts=app_fun.now_to_str(False,ret_timestamp=True) # insert incoming msgs: dt=localdb.blocks_to_datetime(y["blocks"]-tx["confirmations"]) ##### prepare for inserting msg if aa not in table_history_notif: # merged_msg[aa]={} table_history_notif[aa]={} if tx["txid"] not in table_history_notif[aa]: # merged_msg[aa][tx["txid"]]={} table_history_notif[aa][tx["txid"]]={} if outindex not in table_history_notif[aa][tx["txid"]]: # merged_msg[aa][tx["txid"]][outindex]={'dt':dt, 'tmpmemo':tmpmemo } #table q={'dt':dt , 'tmpmemo':tmpmemo ,'block':y["blocks"]-tx["confirmations"] ,'timestamp':ts-60*tx["confirmations"] , 'date_time':app_fun.date2str(datetime.datetime.now()-datetime.timedelta(seconds=60*tx["confirmations"]) ) , 'amount':tx["amount"] , 'outindex':'_'+str(outindex) } table_history_notif[aa][tx["txid"]][outindex]=q # except: # break if self.first_block==None: idbinit=localdb.DB('init.db') first_block=idbinit.select_min_val('block_time_logs','block') self.first_block=first_block[0][0] for aa,txids in table_history_notif.items(): for txid, iis in txids.items(): kk_ordered=sorted(iis.keys()) # print('320 wal api sorted ',kk_ordered) init_table=iis[kk_ordered[0]] # init_table=txid[iis[0]] if len(kk_ordered)>1: for ii in kk_ordered[1:]: init_table['tmpmemo']+=iis[ii]['tmpmemo'] init_table['outindex']+=iis[ii]['outindex'] if init_table["block"]>=self.first_block: table_msg={} table_msg=self.prep_msgs_inout(txid,[init_table['tmpmemo'],0,''],'in',init_table['dt'],tx_status='received', in_sign_uid=-2 ) # -2 to be detected idb.insert(table_msg,['proc_json','type','addr_ext','txid','tx_status','date_time', 'msg','uid','in_sign_uid']) table={} table['tx_history']=[{'Category':"outindex"+init_table['outindex'] # "outindex" not to miss some amounts! , 'Type':'in' , 'status':'received' ,'txid':txid ,'block':init_table["block"] , 'timestamp':init_table["timestamp"] , 'date_time':init_table["date_time"] ,'from_str':table_msg['msgs_inout'][0]['msg'] ,'to_str':aa ,'amount':init_table["amount"] , 'uid':'auto' }] idb.insert(table,['Category','Type','status','txid','block','timestamp','date_time','from_str','to_str','amount','uid']) if init_table["block"]>=self.first_block: table={} toalias=' to address '+aa if aa in self.alias_map: toalias=' to alias '+self.alias_map[aa] tmpjson='Amount: '+str(init_table["amount"])+toalias tmpopname='received' if table_msg['msgs_inout'][0]['msg'][:14] =='PaymentRequest': tmpjson+=';'+table_msg['msgs_inout'][0]['msg'] tmpopname='payment request' table['notifications']=[{'opname':tmpopname,'datetime':init_table['dt'],'status':'Confirmed','details':txid,'closed':'False','orig_json':tmpjson ,'uid':'auto'}] idb.insert(table,['opname','datetime','status','details', 'closed','orig_json' ,'uid']) return len(table_history_notif)
def send_request(): localdb.set_last_addr_from(g1_table.get_value('sendfromaddr'), "'last_book_from_addr'") localdb.set_last_addr_from(g1_table.get_value('toaddr'), "'last_payment_to_addr'") tmpam = round(float(g1_table.get_value('amount')), 8) if tmpam > 100000000 or tmpam < 0.0001: flexitable.showinfo( 'Amount not valid, please correct', 'Amount ' + str(tmpam) + ' is not practical, please correct.') return tmptoaddr = g1_table.get_value('toaddr') if tmptoaddr in ['', '...']: flexitable.showinfo( 'Address missing', 'Please enter valid [Payment to address]') return tmpfromaddr = g1_table.get_value('sendfromaddr') if tmpfromaddr in ['', '...']: flexitable.showinfo( 'Address missing', 'Please enter valid [Send using] address') return if len(g1_table.get_value('title')) > 64: flexitable.showinfo( 'Title too long', 'Please correct request title to be less then 64 characters long.' ) return tmpsignature = localdb.get_addr_to_hash(addr) memo_json = { 'amount': tmpam, 'toaddress': tmptoaddr, 'title': g1_table.get_value('title'), 'docuri': g1_table.get_value('docuri') } # add sign ddict = { 'fromaddr': tmpfromaddr, 'to': [{ 'z': addr, 'a': 0.0001, 'm': 'PaymentRequest;' + json.dumps(memo_json) + tmpsignature }] } table = {} table['queue_waiting'] = [ localdb.set_que_waiting('send', jsonstr=json.dumps(ddict)) ] idb = localdb.DB() idb.insert(table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ]) formframe.destroy()
def prepare_own_addr_frame(self, selecting_filter='All', selecting_to=False): grid_lol3 = [] tmpdict2 = {} tmpdict2['head'] = [{ 'T': 'LabelC', 'L': 'Category', 'tooltip': 'May be useful for filtering addresses in big wallets' }, { 'T': 'LabelC', 'L': 'Alias', 'tooltip': 'Short unique address referrence', 'width': 7 }, { 'T': 'LabelC', 'L': 'Total' }, { 'T': 'LabelC', 'L': 'Confirmed' }, { 'T': 'LabelC', 'L': 'Pending' }, { 'T': 'LabelC', 'L': 'Usage' }, { 'T': 'LabelC', 'L': 'Select' }] grid_lol3.append(tmpdict2) idb = localdb.DB() disp_dict = idb.select('jsons', ['json_content', 'last_update_date_time'], {'json_name': ['=', "'display_wallet'"]}) format_str = ",.8f" sorting = 'usage' filtering = selecting_filter if len(disp_dict) > 0: ddict = json.loads(disp_dict[0][0]) sorting_lol = ddict['lol'] sorting_lol = sorted(sorting_lol, key=operator.itemgetter(3, 1, 2), reverse=True) adr_cat = idb.select('address_category', ['address', 'category']) addr_cat = {} for ac in adr_cat: addr_cat[ac[0]] = ac[1] for i in sorting_lol: ii = i[0] tmpcurcat = 'Edit' if ddict['wl'][ii]['addr'] in addr_cat: tmpcurcat = addr_cat[ddict['wl'][ii]['addr']] visible = False if filtering in ['All', tmpcurcat]: visible = True if filtering == 'Not hidden' and tmpcurcat != 'Hidden': visible = True tmp_confirmed = ddict['wl'][ii]['confirmed'] tmp_unconfirmed = ddict['wl'][ii]['unconfirmed'] tmp_total = tmp_confirmed + tmp_unconfirmed if tmp_total <= 0.0001 and selecting_to == False: visible = False send_state = 'normal' if tmp_total <= 0: send_state = 'disabled' bills = int(ddict['wl'][ii]['#conf'] + ddict['wl'][ii]['#unconf']) billsc = int(ddict['wl'][ii]['#conf']) billsunc = int(ddict['wl'][ii]['#unconf']) tmpalias = ddict['aliasmap'][ddict['wl'][ii]['addr']] tmpaddr = ddict['wl'][ii]['addr'] tmpdict2 = {} tmpdict2[tmpalias] = [{ 'T': 'LabelV', 'L': tmpcurcat, 'visible': visible, 'uid': 'tmpcurcat' + tmpalias }, { 'T': 'LabelV', 'L': tmpalias, 'visible': visible, 'uid': 'tmpalias' + tmpalias }, { 'T': 'LabelV', 'L': format(tmp_total, format_str).replace(',', "'"), 'visible': visible, 'uid': 'Total' + tmpalias }, { 'T': 'LabelV', 'L': format(tmp_confirmed, format_str).replace(',', "'"), 'visible': visible, 'uid': 'tmp_confirmed' + tmpalias }, { 'T': 'LabelV', 'L': format(tmp_unconfirmed, format_str).replace(',', "'"), 'visible': visible, 'uid': 'tmp_unconfirmed' + tmpalias }, { 'T': 'LabelV', 'L': str(ddict['lol'][ii][3]), 'visible': visible, 'uid': 'usage' + tmpalias }, { 'T': 'Button', 'L': 'Select', 'uid': 'select' + tmpalias, 'visible': visible, 'tooltip': tmpaddr }] grid_lol3.append(tmpdict2) return grid_lol3
def setaddrbook(self, parent_frame): global idb, grid_settings, form_grid, cur_addr frame0 = ttk.LabelFrame(parent_frame, text='Filter') frame0.grid(row=0, column=0, sticky="nsew") tmpdict = {} tmpdict['summary'] = [{ 'T': 'Combox', 'uid': 'filter', 'V': self.categories_filter() }] grid_filter = [] grid_filter.append(tmpdict) filter_table = flexitable.FlexiTable(frame0, grid_filter) # addr book view left: frame1 = ttk.LabelFrame(parent_frame, text='Addresses list') frame1.grid(row=1, column=0, sticky="nsew") grid_settings = [] tmpdict = {} tmpdict['head'] = [{ 'T': 'LabelC', 'L': 'Usage' }, { 'T': 'LabelC', 'L': 'Category' }, { 'T': 'LabelC', 'L': 'Alias' }, { 'T': 'LabelC', 'L': 'Full address' }, { 'T': 'LabelC', 'L': 'Valid' }, { 'T': 'LabelC', 'L': 'View Key' }, { 'T': 'LabelC', 'L': 'Valid' }, { 'T': 'LabelC', 'L': ' ' }, { 'T': 'LabelC', 'L': ' ' }, { 'T': 'LabelC', 'L': ' ' }, { 'T': 'LabelC', 'L': ' ' }] grid_settings.append(tmpdict) idb = localdb.DB() cur_addr = [] def update_grid(*argsevnts): global idb, grid_settings tmplen = len(grid_settings) if tmplen > 1: del grid_settings[1:tmplen] del cur_addr[0:] sel_addr_book = idb.select('addr_book', [ 'Category', 'Alias', 'Address', 'ViewKey', 'usage', 'addr_verif', 'viewkey_verif' ], orderby=[{ 'usage': 'desc' }, { 'Category': 'asc' }, { 'Alias': 'asc' }]) if len(sel_addr_book) > 0: filterv = filter_table.get_value('filter') for ii, rr in enumerate(sel_addr_book): tmpdict = {} visible = False if filterv in [rr[0], 'All']: visible = True cur_addr.append(rr[2]) tmphasvk = False uid_tmp = rr[2] tmpnott = { 'T': 'LabelV', 'L': str(tmphasvk), 'uid': 'View' + str(uid_tmp), 'visible': visible } if rr[3].strip() != '': tmphasvk = True tmpnott = { 'T': 'LabelV', 'L': str(tmphasvk), 'uid': 'View' + str(uid_tmp), 'visible': visible, 'tooltip': rr[3].strip() } addrvalid = 'Waiting' if rr[5] == -1: addrvalid = 'No' elif rr[5] == 1: addrvalid = 'Yes' viewk_valid = 'None' if rr[6] == -1: viewk_valid == 'No' elif rr[6] == -1: viewk_valid = 'Yes' elif rr[6] == 0: viewk_valid = 'Waiting' tmpdict[uid_tmp] = [{ 'T': 'LabelV', 'L': str(rr[4]), 'uid': 'Usage' + str(uid_tmp), 'visible': visible }, { 'T': 'LabelV', 'L': rr[0], 'uid': 'Category' + str(uid_tmp), 'visible': visible }, { 'T': 'LabelV', 'L': rr[1], 'uid': 'Alias' + str(uid_tmp), 'visible': visible }, { 'T': 'InputL', 'L': rr[2], 'uid': 'Address' + str(uid_tmp), 'visible': visible, 'width': 24 }, { 'T': 'LabelV', 'L': addrvalid, 'uid': 'AddressValid' + str(uid_tmp), 'visible': visible }, tmpnott, { 'T': 'LabelV', 'L': viewk_valid, 'uid': 'ViewKeyValid' + str(uid_tmp), 'visible': visible }, { 'T': 'Button', 'L': 'Edit', 'uid': 'edit' + str(uid_tmp), 'visible': visible }, { 'T': 'Button', 'L': 'Del.', 'uid': 'delete' + str(uid_tmp), 'visible': visible, 'tooltip': 'Delete record' }, { 'T': 'Button', 'L': 'Copy', 'uid': 'copy' + str(uid_tmp), 'visible': visible }, { 'T': 'Button', 'L': 'Send to', 'uid': 'sendto' + str(uid_tmp), 'visible': visible }, { 'T': 'Button', 'L': 'RP', 'uid': 'rp' + str(uid_tmp), 'visible': visible, 'tooltip': 'Request payment from' }] grid_settings.append(tmpdict) update_grid() main_table = flexitable.FlexiTable(frame1, grid_settings) def update_filter(update_fun, *someargs): global grid_settings update_grid() main_table.update_frame(grid_settings, -1) update_fun() # form for edit and add: frame2 = ttk.LabelFrame( parent_frame, text='Add/edit form' ) #.grid(row=0,column=0,columnspan=3,sticky="nsew") #pack(fill='x') frame2.grid(row=1, column=1, sticky="nsew") form_grid = [] init_form = [{ 'T': 'Button', 'L': 'Import', 'uid': 'import' }, { 'T': 'LabelC', 'L': 'Category' }, { 'T': 'InputL', 'uid': 'cat', 'width': 32 }, { 'T': 'LabelC', 'L': 'Alias' }, { 'T': 'InputL', 'uid': 'alia' }, { 'T': 'LabelC', 'L': 'Full address' }, { 'T': 'InputL', 'uid': 'addr', 'width': 32 }, { 'T': 'LabelC', 'L': 'View key' }, { 'T': 'InputL', 'uid': 'viewkey', 'width': 32 }, { 'T': 'Button', 'L': 'Save', 'uid': 'enter' }] for ii, inf in enumerate(init_form): tmpdict = {} tmpdict[ii] = [inf] form_grid.append(tmpdict) form_table = flexitable.FlexiTable(frame2, form_grid) # button functions: def delete_addr(uid, addr, alias, update_fun): global idb, grid_settings tf = flexitable.msg_yes_no( 'Delete from address book?', 'Please confirm to delete address\n\n' + addr + '\n\nof alias\n\n' + alias + '\n') if tf: idb.delete_where('addr_book', {'Address': ['=', "'" + addr + "'"]}) update_grid() main_table.update_frame(grid_settings, -1) update_fun() def edit_addr(uid, addr, alias, category, viewkey): # load data to form global idb, form_grid form_table.set_textvariable('cat', category) form_table.set_textvariable('alia', alias) form_table.set_textvariable('addr', addr) form_table.set_textvariable('viewkey', viewkey) def increment_usage(addr, update_fun): # when copy or sendto global idb, grid_settings sel_addr_book = idb.select('addr_book', ['usage'], {'Address': ['=', "'" + addr + "'"]}) table = {} table['addr_book'] = [{'usage': int(sel_addr_book[0][0]) + 1}] idb.upsert(table, ['usage'], {'Address': ['=', "'" + addr + "'"]}) update_grid() main_table.update_frame(grid_settings, -1) update_fun() def subcopy(main_table, addr, update_fun): flexitable.copy(main_table, addr) increment_usage(addr, update_fun) def subsendto(addr, update_fun, sendto_fun): sendto_fun(addr) increment_usage(addr, update_fun) # json to string {'amount':, 'toaddr':,title:'','docuri':} # todo defaut send to addr # submit action # title max length 64 def request_payment(alias, addr, update_fun, sendto_fun): formframe = Toplevel() formframe.title('Request payment from ' + alias) obligatory = ttk.Frame(formframe) obligatory.grid(row=0, column=0, sticky='NW') grid1 = [] grid1.append({ 'line1': [{ 'T': 'LabelC', 'L': 'Obligatory:' }, { 'T': 'LabelE' }] }) grid1.append({ 'amount': [{ 'T': 'LabelC', 'L': 'Request amount' }, { 'T': 'InputFloat', 'L': '0', 'uid': 'amount', 'width': 32 }] }) select = localdb.get_last_addr_from("'last_payment_to_addr'") grid1.append({ 'toaddress': [{ 'T': 'LabelC', 'L': 'Payment to address' }, { 'T': 'Button', 'L': select, 'uid': 'toaddr', 'width': 32 }] }) grid1.append({ 'line1': [{ 'T': 'LabelC', 'L': 'Optional:' }, { 'T': 'LabelE' }] }) grid1.append({ 'title': [{ 'T': 'LabelC', 'L': 'Title' }, { 'T': 'InputL', 'L': 'Payment request for invoice nr ', 'uid': 'title', 'width': 32 }] }) grid1.append({ 'docuri': [{ 'T': 'LabelC', 'L': 'Document URI' }, { 'T': 'InputL', 'uid': 'docuri', 'width': 32 }] }) select = localdb.get_last_addr_from("'last_book_from_addr'") grid1.append({ 'sendfrommyaddr': [{ 'T': 'LabelC', 'L': 'Send using' }, { 'T': 'Button', 'L': select, 'uid': 'sendfromaddr', 'width': 32 }] }) grid1.append({ 'submit': [{ 'T': 'Button', 'L': 'Send request', 'span': 2, 'uid': 'submit' }, {}] }) g1_table = flexitable.FlexiTable(obligatory, grid1) # def selecting_addr_from_book_set_and_destroy_sending( addr,uid,frame_to_destroy,*evargs ): # here also get signature! # uid.set(addr) # frame_to_destroy.destroy() g1_table.set_cmd('toaddr', [g1_table, ['toaddr']], self.get_addr_from_wallet) g1_table.set_cmd('sendfromaddr', [g1_table, ['sendfromaddr']], self.get_addr_from_wallet) def send_request(): localdb.set_last_addr_from(g1_table.get_value('sendfromaddr'), "'last_book_from_addr'") localdb.set_last_addr_from(g1_table.get_value('toaddr'), "'last_payment_to_addr'") tmpam = round(float(g1_table.get_value('amount')), 8) if tmpam > 100000000 or tmpam < 0.0001: flexitable.showinfo( 'Amount not valid, please correct', 'Amount ' + str(tmpam) + ' is not practical, please correct.') return tmptoaddr = g1_table.get_value('toaddr') if tmptoaddr in ['', '...']: flexitable.showinfo( 'Address missing', 'Please enter valid [Payment to address]') return tmpfromaddr = g1_table.get_value('sendfromaddr') if tmpfromaddr in ['', '...']: flexitable.showinfo( 'Address missing', 'Please enter valid [Send using] address') return if len(g1_table.get_value('title')) > 64: flexitable.showinfo( 'Title too long', 'Please correct request title to be less then 64 characters long.' ) return tmpsignature = localdb.get_addr_to_hash(addr) memo_json = { 'amount': tmpam, 'toaddress': tmptoaddr, 'title': g1_table.get_value('title'), 'docuri': g1_table.get_value('docuri') } # add sign ddict = { 'fromaddr': tmpfromaddr, 'to': [{ 'z': addr, 'a': 0.0001, 'm': 'PaymentRequest;' + json.dumps(memo_json) + tmpsignature }] } table = {} table['queue_waiting'] = [ localdb.set_que_waiting('send', jsonstr=json.dumps(ddict)) ] idb = localdb.DB() idb.insert(table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ]) formframe.destroy() g1_table.set_cmd('submit', [], send_request) # submit button - create json and send it # table={} # if asap: # table['queue_waiting']=[localdb.set_que_waiting('send',jsonstr=json.dumps(ddict) ) ] # else: # table['queue_waiting']=[localdb.set_que_waiting('send',jsonstr=json.dumps(ddict) , wait_seconds=WAIT_S) ] # if table['queue_waiting'][0]['wait_seconds']==0: # self.queue_com.put([ table['queue_waiting'][0]['id'],'Sending\n',self.message_asap_tx_done]) # buttons commands for main grid: def update_buttons(): global idb, form_grid, grid_settings for x1 in grid_settings: for kk, vv in x1.items(): if kk == 'head': continue addr = main_table.get_value('Address' + str(kk)) alias = main_table.get_value('Alias' + str(kk)) categ = main_table.get_value('Category' + str(kk)) viewk = '' if 'tooltip' in vv[5]: viewk = vv[5][ 'tooltip'] #main_table.get_value('View'+str(kk) ) edit_uid = 'edit' + str(kk) main_table.set_cmd(edit_uid, [kk, addr, alias, categ, viewk], edit_addr) del_uid = 'delete' + str( kk) # remove from db and update view main_table.set_cmd(del_uid, [kk, addr, alias, update_buttons], delete_addr) copy_uid = 'copy' + str( kk) # remove from db and update view main_table.set_cmd(copy_uid, [main_table, addr, update_buttons], subcopy) send_uid = 'sendto' + str(kk) main_table.set_cmd( send_uid, [addr, update_buttons, self.wds.send_to_addr], subsendto) # request payment # print('request payment') rp_uid = 'rp' + str(kk) main_table.set_cmd( rp_uid, [alias, addr, update_buttons, self.wds.send_to_addr], request_payment) update_buttons() filter_table.bind_combox_cmd('filter', [update_buttons], update_filter) def update_filter_values(): # global wds tmpdict = {} tmpdict['summary'] = [{ 'T': 'Combox', 'uid': 'filter', 'V': self.categories_filter() }] grid_filter = [] grid_filter.append(tmpdict) filter_table.update_frame(grid_filter) def save_new(): global idb, form_grid, grid_settings table = {} tmpaddr = form_table.get_value('addr').strip() if tmpaddr == '': return tmpvk = form_table.get_value('viewkey').strip() tmpcat = form_table.get_value('cat').strip() tmpalia = form_table.get_value('alia').strip() sel_addr_book = idb.select( 'addr_book', ['ViewKey', 'addr_verif', 'viewkey_verif'], {'Address': ['=', "'" + tmpaddr + "'"]}) tmpaddr_valid = 0 tmpvk_valid = -2 if len(sel_addr_book) > 0: if sel_addr_book[0][0] != tmpvk and tmpvk != '': tmpvk_valid = 0 else: tmpaddr_valid = sel_addr_book[0][1] tmpvk_valid = sel_addr_book[0][2] if tmpaddr in cur_addr: table = {} table['addr_book'] = [{ 'Category': tmpcat, 'Alias': tmpalia, 'Address': tmpaddr, 'ViewKey': tmpvk, 'addr_verif': tmpaddr_valid, 'viewkey_verif': tmpvk_valid }] idb.upsert(table, [ 'Category', 'Alias', 'Address', 'ViewKey', 'addr_verif', 'viewkey_verif' ], {'Address': ['=', "'" + tmpaddr + "'"]}) if tmpvk_valid == 0: # upsert to prevent double action table = {} tmpjson = json.dumps({'addr': tmpaddr, 'viewkey': tmpvk}) table['queue_waiting'] = [ localdb.set_que_waiting(command='import_view_key', jsonstr=tmpjson, wait_seconds=0) ] idb.upsert( table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ], { 'command': ['=', "'" + import_view_key + "'"], 'json': ['=', "'" + tmpjson + "'"] }) else: table['addr_book'] = [{ 'Category': tmpcat, 'Alias': tmpalia, 'Address': tmpaddr, 'ViewKey': tmpvk, 'usage': 0, 'addr_verif': tmpaddr_valid, 'viewkey_verif': tmpvk_valid }] idb.insert(table, [ 'Category', 'Alias', 'Address', 'ViewKey', 'usage', 'addr_verif', 'viewkey_verif' ]) table = {} # valid addr table['queue_waiting'] = [ localdb.set_que_waiting(command='validate_addr', jsonstr=json.dumps( {'addr': tmpaddr}), wait_seconds=0) ] idb.insert(table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ]) if tmpvk != '': table = {} tmpjson = json.dumps({'addr': tmpaddr, 'viewkey': tmpvk}) table['queue_waiting'] = [ localdb.set_que_waiting(command='import_view_key', jsonstr=tmpjson, wait_seconds=0) ] idb.insert(table, [ 'type', 'wait_seconds', 'created_time', 'command', 'json', 'id', 'status' ]) # idb.upsert(table,[ 'Category','Alias','Address','ViewKey','usage'],{'Address':['=',"'"+tmpaddr+"'"]}) form_table.set_textvariable('cat', '') form_table.set_textvariable('alia', '') form_table.set_textvariable('addr', '') form_table.set_textvariable('viewkey', '') update_grid() main_table.update_frame(grid_settings, -1) # print('674\n',grid_settings) update_buttons() update_filter_values() form_table.set_cmd('enter', [], save_new) # open dialog to select file # 2 types : zaddr or viewkey def import_z(): global zpath zpath = flexitable.get_file_dialog( "Select file with z-address or view key") if zpath == None: return tmpval = [] # if len(tmpval)>0: def whilewaiting(tmpval2): global zpath if tmpval2[0] == ' ': return cc = aes.Crypto() decr_val = cc.aes_decrypt_file(path1=zpath, path2=None, password=tmpval2[0]) try: ddi = json.loads(decr_val) if 'viewkey' in ddi: form_table.set_textvariable('cat', 'ViewKey') form_table.set_textvariable('addr', ddi['addr']) form_table.set_textvariable('viewkey', ddi['viewkey']) else: form_table.set_textvariable('addr', ddi['addr']) except: flexitable.showinfo( 'Could not decrypt file', 'File ' + zpath + ' does not contain encrypted address or view key or you have wrong password!' ) flexitable.ask_password(tmpval, 'Decrypting file', '\n Decrypting file ' + zpath + '\n\nEnter password\n', whilewaiting) # set password if needed ? form_table.set_cmd('import', [], import_z)
def __init__(self,CLI_STR,last_load): self.first_block=None self.min_conf=1 self.cli_cmd=CLI_STR self.last_block=0 self.addr_amount_dict={} self.amounts=[] self.amounts_conf=[] self.amounts_unc=[] self.addr_list=[] self.alias_map={} self.total_balance=0 self.total_conf=0 self.total_unconf=0 self.wl=[] self.unconfirmed={} self.confirmed={} self.all_unspent={} self.utxids={} idb=localdb.DB() disp_dict=idb.select('jsons',['json_content','last_update_date_time'],{'json_name':['=',"'display_wallet'"]}) if len(disp_dict)>0: disp_dict=json.loads(disp_dict[0][0]) if "blocks" in disp_dict: self.last_block=disp_dict["blocks"] if "addr_amount_dict" in disp_dict: self.addr_amount_dict=disp_dict['addr_amount_dict'] if "amounts" in disp_dict: self.amounts=disp_dict['amounts'] if "amounts_conf" in disp_dict: self.amounts_conf=disp_dict['amounts_conf'] if "amounts_unc" in disp_dict: self.amounts_unc=disp_dict['amounts_unc'] if "unconfirmed" in disp_dict: self.unconfirmed=disp_dict['unconfirmed'] if "confirmed" in disp_dict: self.confirmed=disp_dict['confirmed'] if "all_unspent" in disp_dict: self.all_unspent=disp_dict['all_unspent'] for aa,rr in self.all_unspent.items(): for utxo,vv in rr.items(): if utxo not in self.utxids: self.utxids[utxo]=vv['amount'] if "addr_list" in disp_dict: self.addr_list=disp_dict['addr_list'] # if "historical" in disp_dict: self.historical_txs=disp_dict['historical'] if "aliasmap" in disp_dict: self.alias_map=disp_dict['aliasmap'] if "top" in disp_dict: self.total_balance=disp_dict['top']['Total'] self.total_conf=disp_dict['top']['Confirmed'] self.total_unconf=disp_dict['top']['Pending'] if "wl" in disp_dict: self.wl=disp_dict['wl'] tx_in_sql=idb.select('tx_history',['Category','Type','status','txid','block','timestamp','date_time','from_str','to_str','amount','uid'],{'Type':['=',"'in'"]}) self.historical_txs={} self.history_update_counter=0 for ti in tx_in_sql: aa=ti[8] txid=ti[3] outindex=int(ti[0].replace('outindex_','')) if aa not in self.historical_txs: self.historical_txs[aa]={} if txid not in self.historical_txs[aa]: self.historical_txs[aa][txid]={} if outindex not in self.historical_txs[aa][txid]: self.historical_txs[aa][txid][outindex] = { "amount":ti[9]} #,"conf": self.last_block-ti[4],"memo":ti[7] }