fix merged conflicts

This commit is contained in:
jai.s 2019-10-18 19:41:42 +05:30
commit b18ed5e80f
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
57 changed files with 459 additions and 438 deletions

View File

@ -158,7 +158,7 @@ def encodeAddress(version, stream, ripe):
raise Exception( raise Exception(
'Programming error in encodeAddress: The length of' 'Programming error in encodeAddress: The length of'
' a given ripe hash was not 20.') ' a given ripe hash was not 20.')
ripe = ripe.lstrip('\x00') ripe = ripe.lstrip('\x00'.encode('utf-8'))
storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe
@ -180,7 +180,6 @@ def decodeAddress(address):
data (almost certainly a ripe hash)) data (almost certainly a ripe hash))
""" """
# pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches # pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches
address = str(address).strip() address = str(address).strip()
if address[:3] == 'BM-': if address[:3] == 'BM-':
@ -192,7 +191,7 @@ def decodeAddress(address):
return status, 0, 0, '' return status, 0, 0, ''
# after converting to hex, the string will be prepended # after converting to hex, the string will be prepended
# with a 0x and appended with a L # with a 0x and appended with a L
hexdata = hex(integer)[2:-1] hexdata = hex(integer)[2:]
if len(hexdata) % 2 != 0: if len(hexdata) % 2 != 0:
hexdata = '0' + hexdata hexdata = '0' + hexdata
@ -248,7 +247,7 @@ def decodeAddress(address):
embeddedRipeData embeddedRipeData
elif len(embeddedRipeData) == 18: elif len(embeddedRipeData) == 18:
return status, addressVersionNumber, streamNumber, \ return status, addressVersionNumber, streamNumber, \
'\x00\x00' + embeddedRipeData '\x00\x00'.encode('utf-8') + embeddedRipeData
elif len(embeddedRipeData) < 18: elif len(embeddedRipeData) < 18:
return 'ripetooshort', 0, 0, '' return 'ripetooshort', 0, 0, ''
elif len(embeddedRipeData) > 20: elif len(embeddedRipeData) > 20:
@ -265,7 +264,8 @@ def decodeAddress(address):
return 'ripetoolong', 0, 0, '' return 'ripetoolong', 0, 0, ''
elif len(embeddedRipeData) < 4: elif len(embeddedRipeData) < 4:
return 'ripetooshort', 0, 0, '' return 'ripetooshort', 0, 0, ''
x00string = '\x00' * (20 - len(embeddedRipeData)) x00string = '\x00'.encode('utf-8') * (20 - len(embeddedRipeData))
return status, addressVersionNumber, streamNumber, \ return status, addressVersionNumber, streamNumber, \
x00string + embeddedRipeData x00string + embeddedRipeData

View File

@ -46,13 +46,13 @@ def generate_hash(string):
# make input case insensitive # make input case insensitive
string = str.lower(string) string = str.lower(string)
hash_object = hashlib.md5(str.encode(string)) hash_object = hashlib.md5(str.encode(string))
print hash_object.hexdigest() print(hash_object.hexdigest())
# returned object is a hex string # returned object is a hex string
return hash_object.hexdigest() return hash_object.hexdigest()
except IndexError: except IndexError:
print "Error: Please enter a string as an argument." print("Error: Please enter a string as an argument.")
def random_color(hash_string): def random_color(hash_string):

View File

@ -1,19 +1,41 @@
#:import Toolbar kivymd.toolbar.Toolbar #:import MDToolbar kivymd.uix.toolbar.MDToolbar
#:import NavigationLayout kivymd.navigationdrawer.NavigationLayout #:import ThemeManager kivymd.theming.ThemeManager
#:import NavigationDrawerDivider kivymd.navigationdrawer.NavigationDrawerDivider #:import MDNavigationDrawer kivymd.uix.navigationdrawer.MDNavigationDrawer
#:import NavigationDrawerSubheader kivymd.navigationdrawer.NavigationDrawerSubheader #:import NavigationLayout kivymd.uix.navigationdrawer.NavigationLayout
#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox #:import NavigationDrawerDivider kivymd.uix.navigationdrawer.NavigationDrawerDivider
#:import MDList kivymd.list.MDList #:import NavigationDrawerToolbar kivymd.uix.navigationdrawer.NavigationDrawerToolbar
#:import OneLineListItem kivymd.list.OneLineListItem #:import NavigationDrawerSubheader kivymd.uix.navigationdrawer.NavigationDrawerSubheader
#:import MDTextField kivymd.textfields.MDTextField #:import MDCheckbox kivymd.uix.selectioncontrol.MDCheckbox
#:import MDSwitch kivymd.uix.selectioncontrol.MDSwitch
#:import MDList kivymd.uix.list.MDList
#:import OneLineListItem kivymd.uix.list.OneLineListItem
#:import TwoLineListItem kivymd.uix.list.TwoLineListItem
#:import ThreeLineListItem kivymd.uix.list.ThreeLineListItem
#:import OneLineAvatarListItem kivymd.uix.list.OneLineAvatarListItem
#:import OneLineIconListItem kivymd.uix.list.OneLineIconListItem
#:import OneLineAvatarIconListItem kivymd.uix.list.OneLineAvatarIconListItem
#:import MDTextField kivymd.uix.textfield.MDTextField
#:import MDSpinner kivymd.uix.spinner.MDSpinner
#:import MDCard kivymd.uix.card.MDCard
#:import MDSeparator kivymd.uix.card.MDSeparator
#:import MDDropdownMenu kivymd.uix.menu.MDDropdownMenu
#:import get_color_from_hex kivy.utils.get_color_from_hex #:import get_color_from_hex kivy.utils.get_color_from_hex
#:import colors kivymd.color_definitions.colors #:import colors kivymd.color_definitions.colors
#:import MDTabbedPanel kivymd.tabs.MDTabbedPanel #:import MDSlider kivymd.uix.slider.MDSlider
#:import MDTab kivymd.tabs.MDTab #:import MDTabs kivymd.uix.tab.MDTabs
#:import MDFloatingActionButton kivymd.button.MDFloatingActionButton #:import MDProgressBar kivymd.uix.progressbar.MDProgressBar
#:import MDAccordion kivymd.uix.accordion.MDAccordion
#:import MDAccordionItem kivymd.uix.accordion.MDAccordionItem
#:import MDAccordionSubItem kivymd.uix.accordion.MDAccordionSubItem
#:import MDFloatingActionButton kivymd.uix.button.MDFloatingActionButton
#:import Factory kivy.factory.Factory #:import Factory kivy.factory.Factory
#:import MDScrollViewRefreshLayout kivymd.refreshlayout.MDScrollViewRefreshLayout #:import MDTextButton kivymd.uix.button.MDTextButton
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout
#:import MDTabsBase kivymd.uix.tab.MDTabsBase
<Tab@BoxLayout+MDTabsBase>
#:set color_button (0.784, 0.443, 0.216, 1) # brown #:set color_button (0.784, 0.443, 0.216, 1) # brown
#:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown #:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown
@ -151,7 +173,7 @@ NavigationLayout:
BoxLayout: BoxLayout:
id: box_layout id: box_layout
orientation: 'vertical' orientation: 'vertical'
Toolbar: MDToolbar:
id: toolbar id: toolbar
title: app.current_address_label() title: app.current_address_label()
opacity: 1 if app.addressexist() else 0 opacity: 1 if app.addressexist() else 0
@ -314,10 +336,9 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .6, .35
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H4'
text: root.available_credits text: root.available_credits
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -363,7 +384,6 @@ NavigationLayout:
txt_input: txt_input txt_input: txt_input
rv: rv rv: rv
size : (890, 60) size : (890, 60)
size_hint: 1,1
MyTextInput: MyTextInput:
id: txt_input id: txt_input
size_hint_y: None size_hint_y: None
@ -437,19 +457,17 @@ NavigationLayout:
padding: dp(10) padding: dp(10)
BoxLayout: BoxLayout:
MDLabel: MDLabel:
font_style: 'Body1' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "You may generate addresses by using either random numbers or by using a passphrase If you use a passphrase, the address is called a deterministic; address The Random Number option is selected by default but deterministic addresses have several \n pros and cons:\n" text: "You may generate addresses by using either random numbers or by using a passphrase If you use a passphrase, the address is called a deterministic; address The Random Number option is selected by default but deterministic addresses have several \n pros and cons:\n"
halign: 'center' halign: 'center'
bold: True
color:app.theme_cls.primary_dark color:app.theme_cls.primary_dark
BoxLayout: BoxLayout:
MDLabel: MDLabel:
font_style: 'Caption' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "If talk about pros You can recreate your addresses on any computer from memory, You need-not worry about backing up your keys.dat file as long as you can remember your passphrase and aside talk about cons You must remember (or write down) your You must remember the address version number and the stream number along with your passphrase If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you" text: "If talk about pros You can recreate your addresses on any computer from memory, You need-not worry about backing up your keys.dat file as long as you can remember your passphrase and aside talk about cons You must remember (or write down) your You must remember the address version number and the stream number along with your passphrase If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you"
halign: 'center' halign: 'center'
bold: True
color:app.theme_cls.primary_dark color:app.theme_cls.primary_dark
MDCheckbox: MDCheckbox:
id: grp_chkbox_1 id: grp_chkbox_1
@ -457,12 +475,11 @@ NavigationLayout:
active: True active: True
allow_no_selection: False allow_no_selection: False
MDLabel: MDLabel:
font_style: 'Caption' font_style: 'Body2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "use a random number generator to make an address" text: "use a random number generator to make an address"
halign: 'center' halign: 'center'
size_hint_y: None size_hint_y: None
bold: True
height: self.texture_size[1] + dp(4) height: self.texture_size[1] + dp(4)
color: [0.941, 0, 0,1] color: [0.941, 0, 0,1]
MDCheckbox: MDCheckbox:
@ -470,22 +487,20 @@ NavigationLayout:
group: 'test' group: 'test'
allow_no_selection: False allow_no_selection: False
MDLabel: MDLabel:
font_style: 'Caption' font_style: 'Body2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "use a pseudo number generator to make an address" text: "use a pseudo number generator to make an address"
halign: 'center' halign: 'center'
size_hint_y: None size_hint_y: None
bold: True
color: [0.941, 0, 0,1] color: [0.941, 0, 0,1]
height: self.texture_size[1] + dp(4) height: self.texture_size[1] + dp(4)
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .5, .35
height: dp(40) height: dp(40)
on_press: app.root.ids.scr_mngr.current = 'random' on_press: app.root.ids.scr_mngr.current = 'random'
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'proceed' text: 'proceed'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -501,19 +516,17 @@ NavigationLayout:
padding: dp(20) padding: dp(20)
spacing: 100 spacing: 100
MDLabel: MDLabel:
font_style: 'Body1' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Random Addresses" text: "Random Addresses"
halign: 'center' halign: 'center'
bold: True
color:app.theme_cls.primary_dark color:app.theme_cls.primary_dark
MDLabel: MDLabel:
font_style: 'Body1' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged" text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged"
halign: 'center' halign: 'center'
bold: True
color:app.theme_cls.primary_dark color:app.theme_cls.primary_dark
MDTextField: MDTextField:
@ -525,12 +538,11 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .5, None
height: dp(40) height: dp(40)
on_release: root.generateaddress(app) on_release: root.generateaddress(app)
opposite_colors: True opposite_colors: True
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'next' text: 'next'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -558,7 +570,7 @@ NavigationLayout:
size_hint: .6, .55 size_hint: .6, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Server' text: 'Server'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -571,7 +583,7 @@ NavigationLayout:
size_hint: .6, .55 size_hint: .6, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Import or export data' text: 'Import or export data'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -584,7 +596,7 @@ NavigationLayout:
size_hint: .6, .55 size_hint: .6, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Restart background service' text: 'Restart background service'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -596,7 +608,6 @@ NavigationLayout:
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "bitmessage is 11 seconds behind the network" text: "bitmessage is 11 seconds behind the network"
halign: 'center' halign: 'center'
bold: True
color: [0.941, 0, 0,1] color: [0.941, 0, 0,1]
BoxLayout: BoxLayout:
@ -610,7 +621,6 @@ NavigationLayout:
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "show settings (for advanced users only)" text: "show settings (for advanced users only)"
halign: 'left' halign: 'left'
bold: True
color: app.theme_cls.primary_dark color: app.theme_cls.primary_dark
<MyAddress>: <MyAddress>:
@ -662,20 +672,20 @@ NavigationLayout:
size: self.size size: self.size
MDLabel: MDLabel:
size_hint_y: None size_hint_y: None
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'Platinum' text: 'Platinum'
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Subtitle1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'We provide subscriptions for proof of work calculation for first month. ' text: 'We provide subscriptions for proof of work calculation for first month. '
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
id: free_pak id: free_pak
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: '€ 50.0' text: '€ 50.0'
halign: 'center' halign: 'center'
@ -687,11 +697,11 @@ NavigationLayout:
Rectangle: Rectangle:
pos: self.pos pos: self.pos
size: self.size size: self.size
size_hint: 1, None size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1
height: dp(40) height: dp(40)
on_press: root.get_available_credits(self) on_press: root.get_available_credits(self)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Get Free Credits' text: 'Get Free Credits'
font_size: '13sp' font_size: '13sp'
color: (0,0,0,1) color: (0,0,0,1)
@ -708,19 +718,19 @@ NavigationLayout:
size: self.size size: self.size
MDLabel: MDLabel:
size_hint_y: None size_hint_y: None
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'Silver' text: 'Silver'
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Subtitle1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'We provide for proof of work calculation for six month. ' text: 'We provide for proof of work calculation for six month. '
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: '€ 100.0' text: '€ 100.0'
halign: 'center' halign: 'center'
@ -732,10 +742,10 @@ NavigationLayout:
Rectangle: Rectangle:
pos: self.pos pos: self.pos
size: self.size size: self.size
size_hint: 1, None size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Get Monthly Credits' text: 'Get Monthly Credits'
font_size: '13sp' font_size: '13sp'
color: (0,0,0,1) color: (0,0,0,1)
@ -752,19 +762,19 @@ NavigationLayout:
size: self.size size: self.size
MDLabel: MDLabel:
size_hint_y: None size_hint_y: None
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'Gold' text: 'Gold'
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Subtitle1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: 'We provide for proof of work calculation for 1years. ' text: 'We provide for proof of work calculation for 1years. '
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
font_style: 'Headline' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: '€ 500.0' text: '€ 500.0'
halign: 'center' halign: 'center'
@ -776,10 +786,10 @@ NavigationLayout:
Rectangle: Rectangle:
pos: self.pos pos: self.pos
size: self.size size: self.size
size_hint: 1, None size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Get Yearly Credits' text: 'Get Yearly Credits'
font_size: '13sp' font_size: '13sp'
color: (0,0,0,1) color: (0,0,0,1)
@ -826,7 +836,7 @@ NavigationLayout:
on_release: on_release:
root.savecontact() root.savecontact()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Save' text: 'Save'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -837,7 +847,7 @@ NavigationLayout:
on_press: root.dismiss() on_press: root.dismiss()
on_press: root.close_pop() on_press: root.close_pop()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Cancel' text: 'Cancel'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -846,7 +856,7 @@ NavigationLayout:
size_hint: 2, None size_hint: 2, None
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Scan QR code' text: 'Scan QR code'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -855,12 +865,11 @@ NavigationLayout:
<NetworkStat>: <NetworkStat>:
name: 'networkstat' name: 'networkstat'
MDTabbedPanel: MDTabs:
id: tab_panel id: tab_panel
tab_display_mode:'text' tab_display_mode:'text'
MDTab: Tab:
name: 'connections'
text: "Total connections" text: "Total connections"
ScrollView: ScrollView:
do_scroll_x: False do_scroll_x: False
@ -873,16 +882,15 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .6, .35 size_hint: .6, .3
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: root.text_variable_1 text: root.text_variable_1
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
halign: 'center' halign: 'center'
MDTab: Tab:
name: 'processes'
text: 'Processes' text: 'Processes'
ScrollView: ScrollView:
do_scroll_x: False do_scroll_x: False
@ -895,10 +903,10 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .7, .6 size_hint: .7, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: root.text_variable_2 text: root.text_variable_2
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -908,10 +916,10 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .7, .6 size_hint: .7, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: root.text_variable_3 text: root.text_variable_3
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -921,10 +929,10 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .7, .6 size_hint: .7, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: root.text_variable_4 text: root.text_variable_4
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -934,10 +942,10 @@ NavigationLayout:
BoxLayout: BoxLayout:
AnchorLayout: AnchorLayout:
MDRaisedButton: MDRaisedButton:
size_hint: .7, .6 size_hint: .7, .55
height: dp(40) height: dp(40)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: root.text_variable_5 text: root.text_variable_5
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -953,31 +961,31 @@ NavigationLayout:
height: dp(500) + self.minimum_height height: dp(500) + self.minimum_height
padding: dp(32) padding: dp(32)
MDLabel: MDLabel:
font_style: 'Headline' font_style: 'Subtitle1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.subject text: root.subject
halign: 'left' halign: 'left'
font_size: '20sp' font_size: '20sp'
CopyTextBtn: CopyTextBtn:
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'H4'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "From: " + root.from_addr text: "From: " + root.from_addr
halign: 'left' halign: 'left'
CopyTextBtn: CopyTextBtn:
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'H4'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "To: " + root.to_addr text: "To: " + root.to_addr
halign: 'left' halign: 'left'
CopyTextBtn: CopyTextBtn:
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'H4'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.status text: root.status
halign: 'left' halign: 'left'
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'H4'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.message text: root.message
halign: 'left' halign: 'left'
@ -1036,25 +1044,25 @@ NavigationLayout:
spacing:dp(25) spacing:dp(25)
MDLabel: MDLabel:
id: myaddr_label id: myaddr_label
font_style: 'Title' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Label" text: "Label"
font_size: '17sp' font_size: '17sp'
halign: 'left' halign: 'left'
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Body1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.address_label text: root.address_label
font_size: '15sp' font_size: '15sp'
halign: 'left' halign: 'left'
MDLabel: MDLabel:
font_style: 'Title' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Address" text: "Address"
font_size: '17sp' font_size: '17sp'
halign: 'left' halign: 'left'
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Body1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.address text: root.address
font_size: '15sp' font_size: '15sp'
@ -1068,7 +1076,7 @@ NavigationLayout:
height: dp(40) height: dp(40)
on_press: root.send_message_from() on_press: root.send_message_from()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Send message from' text: 'Send message from'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -1080,7 +1088,7 @@ NavigationLayout:
on_press: app.root.ids.scr_mngr.current = 'showqrcode' on_press: app.root.ids.scr_mngr.current = 'showqrcode'
on_press: app.root.ids.sc15.qrdisplay() on_press: app.root.ids.sc15.qrdisplay()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Show QR code' text: 'Show QR code'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -1091,7 +1099,7 @@ NavigationLayout:
on_press: root.dismiss() on_press: root.dismiss()
on_press: root.close_pop() on_press: root.close_pop()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Cancel' text: 'Cancel'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -1115,14 +1123,14 @@ NavigationLayout:
orientation: 'vertical' orientation: 'vertical'
spacing:dp(20) spacing:dp(20)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Label" text: "Label"
font_size: '17sp' font_size: '17sp'
halign: 'left' halign: 'left'
MDTextField: MDTextField:
id: add_label id: add_label
font_style: 'Subhead' font_style: 'Body1'
font_size: '15sp' font_size: '15sp'
halign: 'left' halign: 'left'
text: root.address_label text: root.address_label
@ -1130,13 +1138,13 @@ NavigationLayout:
required: True required: True
helper_text_mode: "on_error" helper_text_mode: "on_error"
MDLabel: MDLabel:
font_style: 'Title' font_style: 'Subtitle2'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Address" text: "Address"
font_size: '17sp' font_size: '17sp'
halign: 'left' halign: 'left'
MDLabel: MDLabel:
font_style: 'Subhead' font_style: 'Body1'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: root.address text: root.address
font_size: '15sp' font_size: '15sp'
@ -1150,7 +1158,7 @@ NavigationLayout:
height: dp(40) height: dp(40)
on_press: root.send_message_to() on_press: root.send_message_to()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Send message to' text: 'Send message to'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -1161,7 +1169,7 @@ NavigationLayout:
font_size: '10sp' font_size: '10sp'
on_press: root.update_addbook_label(root.address) on_press: root.update_addbook_label(root.address)
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Save' text: 'Save'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)
@ -1172,7 +1180,7 @@ NavigationLayout:
on_press: root.dismiss() on_press: root.dismiss()
on_press: root.close_pop() on_press: root.close_pop()
MDLabel: MDLabel:
font_style: 'Title' font_style: 'H6'
text: 'Cancel' text: 'Cancel'
font_size: '13sp' font_size: '13sp'
color: (1,1,1,1) color: (1,1,1,1)

View File

@ -19,8 +19,7 @@ from kivy.properties import (
ListProperty, ListProperty,
NumericProperty, NumericProperty,
ObjectProperty, ObjectProperty,
StringProperty StringProperty)
)
from kivy.uix.behaviors import FocusBehavior from kivy.uix.behaviors import FocusBehavior
from kivy.uix.boxlayout import BoxLayout from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button from kivy.uix.button import Button
@ -36,36 +35,37 @@ from kivy.uix.screenmanager import Screen
from kivy.uix.spinner import Spinner from kivy.uix.spinner import Spinner
from kivy.uix.textinput import TextInput from kivy.uix.textinput import TextInput
from kivy.utils import platform from kivy.utils import platform
import kivy_helper_search from bitmessagekivy import kivy_helper_search
from kivymd.button import MDIconButton from kivymd.uix.dialog import MDDialog
from kivymd.dialog import MDDialog from kivymd.uix.button import MDIconButton
from kivymd.label import MDLabel from kivymd.uix.label import MDLabel
from kivymd.list import ( from kivymd.uix.list import (
ILeftBody, ILeftBody,
ILeftBodyTouch, ILeftBodyTouch,
IRightBodyTouch, IRightBodyTouch,
TwoLineAvatarIconListItem, TwoLineAvatarIconListItem,
TwoLineListItem TwoLineListItem)
) from kivymd.uix.navigationdrawer import (
from kivymd.navigationdrawer import (
MDNavigationDrawer, MDNavigationDrawer,
NavigationDrawerHeaderBase NavigationDrawerHeaderBase)
) from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.selectioncontrols import MDCheckbox
from kivymd.theming import ThemeManager from kivymd.theming import ThemeManager
import queues import queues
from semaphores import kivyuisignaler from semaphores import kivyuisignaler
import state import state
from uikivysignaler import UIkivySignaler
import identiconGeneration from bitmessagekivy.uikivysignaler import UIkivySignaler
# pylint: disable=unused-argument, too-few-public-methods, import-error
from bitmessagekivy import identiconGeneration
import os
from kivy.core.clipboard import Clipboard
# pylint: disable=unused-argument, too-few-public-methods # pylint: disable=unused-argument, too-few-public-methods
def toast(text): def toast(text):
"""Method will display the toast message.""" """Method will display the toast message."""
# pylint: disable=redefined-outer-name from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name
from kivymd.toast.kivytoast import toast
toast(text) toast(text)
return return
@ -92,7 +92,7 @@ class Inbox(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method inbox accounts.""" """Clock Schdule for method inbox accounts."""
self.inboxaccounts() self.inboxaccounts()
print dt print(dt)
def inboxaccounts(self): def inboxaccounts(self):
"""Load inbox accounts.""" """Load inbox accounts."""
@ -156,12 +156,11 @@ class Inbox(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="No message found!" if state.searcing_text text="No message found!" if state.searcing_text
else "yet no message for this account!!!!!!!!!!!!!", else "yet no message for this account!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -184,9 +183,11 @@ class Inbox(Screen):
"UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str(
data_index)) data_index))
try: try:
msg_count_objs = self.parent.parent.parent.parent.children[2].children[0].ids msg_count_objs = \
except Exception: self.parent.parent.parent.parent.children[2].children[0].ids
msg_count_objs = self.parent.parent.parent.parent.parent.children[2].children[0].ids except Exception as e:
msg_count_objs = \
self.parent.parent.parent.parent.parent.children[2].children[0].ids
if int(state.inbox_count) > 0: if int(state.inbox_count) > 0:
msg_count_objs.inbox_cnt.badge_text = str( msg_count_objs.inbox_cnt.badge_text = str(
int(state.inbox_count) - 1) int(state.inbox_count) - 1)
@ -273,12 +274,11 @@ class MyAddress(Screen):
self.ids.ml.add_widget(meny) self.ids.ml.add_widget(meny)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="No address found!" if state.searcing_text text="No address found!" if state.searcing_text
else "yet no address is created by user!!!!!!!!!!!!!", else "yet no address is created by user!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -306,6 +306,7 @@ class MyAddress(Screen):
self.init_ui() self.init_ui()
self.ids.refresh_layout.refresh_done() self.ids.refresh_layout.refresh_done()
self.tick = 0 self.tick = 0
Clock.schedule_once(refresh_callback, 1) Clock.schedule_once(refresh_callback, 1)
@staticmethod @staticmethod
@ -330,7 +331,7 @@ class AddressBook(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method AddressBook.""" """Clock Schdule for method AddressBook."""
self.loadAddresslist(None, 'All', '') self.loadAddresslist(None, 'All', '')
print dt print (dt)
def loadAddresslist(self, account, where="", what=""): def loadAddresslist(self, account, where="", what=""):
"""Clock Schdule for method AddressBook.""" """Clock Schdule for method AddressBook."""
@ -367,12 +368,11 @@ class AddressBook(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="No contact found!" if state.searcing_text text="No contact found!" if state.searcing_text
else "No contact found yet...... ", else "No contact found yet...... ",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -430,7 +430,7 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
"""Respond to the selection of items in the view.""" """Respond to the selection of items in the view."""
self.selected = is_selected self.selected = is_selected
if is_selected: if is_selected:
print "selection changed to {0}".format(rv.data[index]) print("selection changed to {0}".format(rv.data[index]))
rv.parent.txt_input.text = rv.parent.txt_input.text.replace( rv.parent.txt_input.text = rv.parent.txt_input.text.replace(
rv.parent.txt_input.text, rv.data[index]['text']) rv.parent.txt_input.text, rv.data[index]['text'])
@ -438,39 +438,39 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
class RV(RecycleView): class RV(RecycleView):
"""Recycling View.""" """Recycling View."""
def __init__(self, **kwargs): def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Recycling Method.""" """Recycling Method."""
# pylint: disable=useless-super-delegation
super(RV, self).__init__(**kwargs) super(RV, self).__init__(**kwargs)
class DropDownWidget(BoxLayout): class DropDownWidget(BoxLayout):
"""Adding Dropdown Widget.""" """Adding Dropdown Widget."""
# pylint: disable=too-many-statements, inconsistent-return-statements, too-many-locals
txt_input = ObjectProperty() txt_input = ObjectProperty()
rv = ObjectProperty() rv = ObjectProperty()
def send(self, navApp): def send(self, navApp): # pylint: disable=too-many-statements, inconsistent-return-statements
"""Send message from one address to another.""" """Send message from one address to another."""
# pylint: disable=too-many-locals
fromAddress = str(self.ids.ti.text) fromAddress = str(self.ids.ti.text)
toAddress = str(self.ids.txt_input.text) toAddress = str(self.ids.txt_input.text)
subject = self.ids.subject.text.encode('utf-8').strip() subject = self.ids.subject.text.encode('utf-8').strip()
message = self.ids.body.text.encode('utf-8').strip() message = self.ids.body.text.encode('utf-8').strip()
encoding = 3 encoding = 3
print "message: ", self.ids.body.text print ("message: ", self.ids.body.text)
sendMessageToPeople = True sendMessageToPeople = True
if sendMessageToPeople: if sendMessageToPeople:
if toAddress != '' and subject and message: if toAddress != '' and subject and message:
from addresses import decodeAddress from addresses import decodeAddress
status, addressVersionNumber, streamNumber, ripe = decodeAddress(toAddress) status, addressVersionNumber, streamNumber, ripe = \
decodeAddress(toAddress)
if status == 'success': if status == 'success':
if state.detailPageType == 'draft' and state.send_draft_mail: if state.detailPageType == 'draft' and state.send_draft_mail:
sqlExecute( sqlExecute(
"UPDATE sent SET toaddress = ?" "UPDATE sent SET toaddress = ? \
", fromaddress = ? , subject = ?" , fromaddress = ? , subject = ?\
", message = ?, folder = 'sent'" , message = ?, folder = 'sent'\
" WHERE ackdata = ?;", WHERE ackdata = ?;",
toAddress, toAddress,
fromAddress, fromAddress,
subject, subject,
@ -485,12 +485,12 @@ class DropDownWidget(BoxLayout):
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
statusIconColor = 'red' statusIconColor = 'red'
if addressVersionNumber > 4 or addressVersionNumber <= 1: if addressVersionNumber > 4 or addressVersionNumber <= 1:
print "addressVersionNumber > 4 \ print("addressVersionNumber > 4 \
or addressVersionNumber <= 1" or addressVersionNumber <= 1")
if streamNumber > 1 or streamNumber == 0: if streamNumber > 1 or streamNumber == 0:
print "streamNumber > 1 or streamNumber == 0" print("streamNumber > 1 or streamNumber == 0")
if statusIconColor == 'red': if statusIconColor == 'red':
print "shared.statusIconColor == 'red'" print("shared.statusIconColor == 'red'")
stealthLevel = BMConfigParser().safeGetInt( stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel') 'bitmessagesettings', 'ackstealthlevel')
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
@ -525,7 +525,7 @@ class DropDownWidget(BoxLayout):
toLabel = '' toLabel = ''
queues.workerQueue.put(('sendmessage', toAddress)) queues.workerQueue.put(('sendmessage', toAddress))
print "sqlExecute successfully #######################" print ("sqlExecute successfully #######################")
self.parent.parent.current = 'inbox' self.parent.parent.current = 'inbox'
state.in_composer = True state.in_composer = True
navApp.back_press() navApp.back_press()
@ -577,9 +577,8 @@ class MyTextInput(TextInput):
starting_no = NumericProperty(3) starting_no = NumericProperty(3)
suggestion_text = '' suggestion_text = ''
def __init__(self, **kwargs): def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Getting Text Input.""" """Getting Text Input."""
# pylint: disable=useless-super-delegation
super(MyTextInput, self).__init__(**kwargs) super(MyTextInput, self).__init__(**kwargs)
def on_text(self, instance, value): def on_text(self, instance, value):
@ -609,9 +608,8 @@ class MyTextInput(TextInput):
class Payment(Screen): class Payment(Screen):
"""Payment Method.""" """Payment Method."""
def get_available_credits(self, instance): def get_available_credits(self, instance): # pylint: disable=no-self-use
"""Method helps to get the available credits""" """Method helps to get the available credits"""
# pylint: disable=no-self-use
state.availabe_credit = instance.parent.children[1].text state.availabe_credit = instance.parent.children[1].text
existing_credits = state.kivyapp.root.ids.sc18.ids.ml.children[0].children[0].children[0].children[0].text existing_credits = state.kivyapp.root.ids.sc18.ids.ml.children[0].children[0].children[0].children[0].text
if len(existing_credits.split(' ')) > 1: if len(existing_credits.split(' ')) > 1:
@ -724,7 +722,7 @@ class Sent(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method sent accounts.""" """Clock Schdule for method sent accounts."""
self.sentaccounts() self.sentaccounts()
print dt print(dt)
def sentaccounts(self): def sentaccounts(self):
"""Load sent accounts.""" """Load sent accounts."""
@ -740,7 +738,8 @@ class Sent(Screen):
data = [] data = []
queryreturn = kivy_helper_search.search_sql( queryreturn = kivy_helper_search.search_sql(
xAddress, account, "sent", where, what, False) xAddress, account, "sent", where, what, False)
if state.msg_counter_objs and state.association == state.check_sent_acc: if state.msg_counter_objs and state.association == \
state.check_sent_acc:
state.msg_counter_objs.send_cnt.badge_text = str(len(queryreturn)) state.msg_counter_objs.send_cnt.badge_text = str(len(queryreturn))
state.sent_count = str(int(state.sent_count) + 1) state.sent_count = str(int(state.sent_count) + 1)
state.all_count = str(int(state.all_count) + 1) state.all_count = str(int(state.all_count) + 1)
@ -791,12 +790,11 @@ class Sent(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="No message found!" if state.searcing_text text="No message found!" if state.searcing_text
else "yet no message for this account!!!!!!!!!!!!!", else "yet no message for this account!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -832,8 +830,8 @@ class Sent(Screen):
state.trash_count = str(int(state.trash_count) + 1) state.trash_count = str(int(state.trash_count) + 1)
state.all_count = str(int(state.all_count) - 1) state.all_count = str(int(state.all_count) - 1)
sqlExecute( sqlExecute(
"UPDATE sent SET folder = 'trash'" "UPDATE sent SET folder = 'trash' \
" WHERE ackdata = ?;", str(data_index)) WHERE ackdata = ?;", str(data_index))
self.ids.ml.remove_widget(instance.parent.parent) self.ids.ml.remove_widget(instance.parent.parent)
toast('Deleted') toast('Deleted')
self.update_trash() self.update_trash()
@ -841,8 +839,8 @@ class Sent(Screen):
def archive(self, data_index, instance, *args): def archive(self, data_index, instance, *args):
"""Archive sent mail from sent mail listing.""" """Archive sent mail from sent mail listing."""
sqlExecute( sqlExecute(
"UPDATE sent SET folder = 'trash'" "UPDATE sent SET folder = 'trash' \
" WHERE ackdata = ?;", str(data_index)) WHERE ackdata = ?;", str(data_index))
self.ids.ml.remove_widget(instance.parent.parent) self.ids.ml.remove_widget(instance.parent.parent)
self.update_trash() self.update_trash()
@ -873,13 +871,14 @@ class Trash(Screen):
if state.association == '': if state.association == '':
if BMConfigParser().addresses(): if BMConfigParser().addresses():
state.association = BMConfigParser().addresses()[0] state.association = BMConfigParser().addresses()[0]
inbox = sqlQuery( inbox = sqlQuery(
"SELECT toaddress, fromaddress, subject, message, folder, received from" "SELECT toaddress, fromaddress, subject, message, folder, received from \
" inbox WHERE folder = 'trash' and toaddress = '{}';".format( inbox WHERE folder = 'trash' and toaddress = '{}';".format(
state.association)) state.association))
sent = sqlQuery( sent = sqlQuery(
"SELECT toaddress, fromaddress, subject, message, folder, lastactiontime from" "SELECT toaddress, fromaddress, subject, message, folder, lastactiontime from \
" sent WHERE folder = 'trash' and fromaddress = '{}';".format( sent WHERE folder = 'trash' and fromaddress = '{}';".format(
state.association)) state.association))
trash_data = inbox + sent trash_data = inbox + sent
@ -916,11 +915,10 @@ class Trash(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="yet no trashed message for this account!!!!!!!!!!!!!", text="yet no trashed message for this account!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -956,9 +954,8 @@ class Setting(Screen):
pass pass
class NavigateApp(App): class NavigateApp(App): # pylint: disable=too-many-public-methods
"""Navigation Layout of class.""" """Navigation Layout of class."""
# pylint: disable=too-many-public-methods
theme_cls = ThemeManager() theme_cls = ThemeManager()
previous_date = ObjectProperty() previous_date = ObjectProperty()
@ -989,6 +986,7 @@ class NavigateApp(App):
def build(self): def build(self):
"""Method builds the widget.""" """Method builds the widget."""
import os
main_widget = Builder.load_file( main_widget = Builder.load_file(
os.path.join(os.path.dirname(__file__), 'main.kv')) os.path.join(os.path.dirname(__file__), 'main.kv'))
self.nav_drawer = Navigatorss() self.nav_drawer = Navigatorss()
@ -1029,24 +1027,25 @@ class NavigateApp(App):
self.root.ids.sc1.ids.ml.clear_widgets() self.root.ids.sc1.ids.ml.clear_widgets()
self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc1.loadMessagelist(state.association)
self.root.ids.scr_mngr.current = 'inbox' self.root.ids.scr_mngr.current = 'inbox'
msg_counter_objs = self.root_window.children[1].children[2].children[0].ids
msg_counter_objs = \
self.root_window.children[1].children[2].children[0].ids
state.sent_count = str( state.sent_count = str(
sqlQuery( sqlQuery(
"SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and" "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and \
" folder = 'sent' ;".format(state.association))[0][0]) folder = 'sent' ;".format(state.association))[0][0])
state.inbox_count = str( state.inbox_count = str(
sqlQuery( sqlQuery(
"SELECT COUNT(*) FROM inbox WHERE toaddress = '{}' and" "SELECT COUNT(*) FROM inbox WHERE toaddress = '{}' and \
" folder = 'inbox' ;".format(state.association))[0][0]) folder = 'inbox' ;".format(state.association))[0][0])
state.trash_count = str(sqlQuery( state.trash_count = str(sqlQuery("SELECT (SELECT count(*) FROM sent \
"SELECT (SELECT count(*) FROM sent" where fromaddress = '{0}' and folder = 'trash' ) \
" where fromaddress = '{0}' and folder = 'trash' )" +(SELECT count(*) FROM inbox where toaddress = '{0}' and \
"+(SELECT count(*) FROM inbox where toaddress = '{0}' and" folder = 'trash') AS SumCount".format(state.association))[0][0])
" folder = 'trash') AS SumCount".format(state.association))[0][0])
state.draft_count = str( state.draft_count = str(
sqlQuery( sqlQuery(
"SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and" "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and \
" folder = 'draft' ;".format(state.association))[0][0]) folder = 'draft' ;".format(state.association))[0][0])
state.all_count = str(int(state.sent_count) + int(state.inbox_count)) state.all_count = str(int(state.sent_count) + int(state.inbox_count))
if msg_counter_objs: if msg_counter_objs:
@ -1091,7 +1090,7 @@ class NavigateApp(App):
if not os.path.exists(directory): if not os.path.exists(directory):
os.makedirs(directory) os.makedirs(directory)
except OSError: except OSError:
print 'Error: Creating directory. ' + directory print('Error: Creating directory. ' + directory)
@staticmethod @staticmethod
def get_default_image(): def get_default_image():
@ -1167,8 +1166,10 @@ class NavigateApp(App):
def back_press(self): def back_press(self):
"""Method used for going back from composer to previous page.""" """Method used for going back from composer to previous page."""
self.root.ids.toolbar.right_action_items = [['account-plus', lambda x: self.addingtoaddressbook()]] self.root.ids.toolbar.right_action_items = \
self.root.ids.toolbar.left_action_items = [['menu', lambda x: self.root.toggle_nav_drawer()]] [['account-plus', lambda x: self.addingtoaddressbook()]]
self.root.ids.toolbar.left_action_items = \
[['menu', lambda x: self.root.toggle_nav_drawer()]]
self.root.ids.scr_mngr.current = 'inbox' \ self.root.ids.scr_mngr.current = 'inbox' \
if state.in_composer else 'allmails'\ if state.in_composer else 'allmails'\
if state.is_allmail else state.detailPageType\ if state.is_allmail else state.detailPageType\
@ -1183,7 +1184,7 @@ class NavigateApp(App):
@staticmethod @staticmethod
def on_stop(): def on_stop():
"""On stop methos is used for stoping the runing script.""" """On stop methos is used for stoping the runing script."""
print "*******************EXITING FROM APPLICATION*******************" print("*******************EXITING FROM APPLICATION*******************")
import shutdown import shutdown
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
@ -1232,7 +1233,7 @@ class NavigateApp(App):
self.root.ids.sc1.ids.ml.clear_widgets() self.root.ids.sc1.ids.ml.clear_widgets()
try: try:
self.root.ids.sc1.children[2].children[1].ids.search_field.text = '' self.root.ids.sc1.children[2].children[1].ids.search_field.text = ''
except Exception: except Exception as e:
self.root.ids.sc1.children[1].children[1].ids.search_field.text = '' self.root.ids.sc1.children[1].children[1].ids.search_field.text = ''
self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc1.loadMessagelist(state.association)
elif instance.text == 'Draft': elif instance.text == 'Draft':
@ -1252,7 +1253,7 @@ class NavigateApp(App):
self.root.ids.sc10.ids.ml.clear_widgets() self.root.ids.sc10.ids.ml.clear_widgets()
try: try:
self.root.ids.sc10.children[1].children[1].ids.search_field.text = '' self.root.ids.sc10.children[1].children[1].ids.search_field.text = ''
except Exception: except Exception as e:
self.root.ids.sc10.children[2].children[1].ids.search_field.text = '' self.root.ids.sc10.children[2].children[1].ids.search_field.text = ''
self.root.ids.sc10.init_ui() self.root.ids.sc10.init_ui()
return return
@ -1285,9 +1286,8 @@ class NavigateApp(App):
class GrashofPopup(Popup): class GrashofPopup(Popup):
"""Methods for saving contacts, error messages.""" """Methods for saving contacts, error messages."""
def __init__(self, **kwargs): def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Grash of pop screen settings.""" """Grash of pop screen settings."""
# pylint: disable=useless-super-delegation
super(GrashofPopup, self).__init__(**kwargs) super(GrashofPopup, self).__init__(**kwargs)
def savecontact(self): def savecontact(self):
@ -1429,16 +1429,16 @@ class MailDetail(Screen):
self.page_type = state.detailPageType if state.detailPageType else '' self.page_type = state.detailPageType if state.detailPageType else ''
if state.detailPageType == 'sent' or state.detailPageType == 'draft': if state.detailPageType == 'sent' or state.detailPageType == 'draft':
data = sqlQuery( data = sqlQuery(
"select toaddress, fromaddress, subject, message, status," "select toaddress, fromaddress, subject, message, status, \
" ackdata from sent where ackdata = ?;", state.mail_id) ackdata from sent where ackdata = ?;", state.mail_id)
state.status = self state.status = self
state.ackdata = data[0][5] state.ackdata = data[0][5]
self.assign_mail_details(data) self.assign_mail_details(data)
state.kivyapp.set_mail_detail_header() state.kivyapp.set_mail_detail_header()
elif state.detailPageType == 'inbox': elif state.detailPageType == 'inbox':
data = sqlQuery( data = sqlQuery(
"select toaddress, fromaddress, subject, message from inbox" "select toaddress, fromaddress, subject, message from inbox \
" where msgid = ?;", str(state.mail_id)) where msgid = ?;", str(state.mail_id))
self.assign_mail_details(data) self.assign_mail_details(data)
state.kivyapp.set_mail_detail_header() state.kivyapp.set_mail_detail_header()
@ -1461,16 +1461,16 @@ class MailDetail(Screen):
msg_count_objs = state.kivyapp.root.children[2].children[0].ids msg_count_objs = state.kivyapp.root.children[2].children[0].ids
if state.detailPageType == 'sent': if state.detailPageType == 'sent':
sqlExecute( sqlExecute(
"UPDATE sent SET folder = 'trash' WHERE" "UPDATE sent SET folder = 'trash' WHERE \
" ackdata = ?;", str(state.mail_id)) ackdata = ?;", str(state.mail_id))
msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1)
state.sent_count = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1)
self.parent.screens[3].ids.ml.clear_widgets() self.parent.screens[3].ids.ml.clear_widgets()
self.parent.screens[3].loadSent(state.association) self.parent.screens[3].loadSent(state.association)
elif state.detailPageType == 'inbox': elif state.detailPageType == 'inbox':
sqlExecute( sqlExecute(
"UPDATE inbox SET folder = 'trash' WHERE" "UPDATE inbox SET folder = 'trash' WHERE \
" msgid = ?;", str(state.mail_id)) msgid = ?;", str(state.mail_id))
msg_count_objs.inbox_cnt.badge_text = str(int(state.inbox_count) - 1) msg_count_objs.inbox_cnt.badge_text = str(int(state.inbox_count) - 1)
state.inbox_count = str(int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1)
self.parent.screens[0].ids.ml.clear_widgets() self.parent.screens[0].ids.ml.clear_widgets()
@ -1499,8 +1499,8 @@ class MailDetail(Screen):
def inbox_reply(self): def inbox_reply(self):
"""Method used for replying inbox messages.""" """Method used for replying inbox messages."""
data = sqlQuery( data = sqlQuery(
"select toaddress, fromaddress, subject, message from inbox where" "select toaddress, fromaddress, subject, message from inbox where \
" msgid = ?;", str(state.mail_id)) msgid = ?;", str(state.mail_id))
composer_obj = self.parent.screens[2].children[0].ids composer_obj = self.parent.screens[2].children[0].ids
composer_obj.ti.text = data[0][0] composer_obj.ti.text = data[0][0]
composer_obj.btn.text = data[0][0] composer_obj.btn.text = data[0][0]
@ -1518,7 +1518,8 @@ class MailDetail(Screen):
def write_msg(self, navApp): def write_msg(self, navApp):
"""Method used to write on draft mail.""" """Method used to write on draft mail."""
state.send_draft_mail = state.mail_id state.send_draft_mail = state.mail_id
composer_ids = self.parent.parent.parent.parent.ids.sc3.children[0].ids composer_ids = \
self.parent.parent.parent.parent.ids.sc3.children[0].ids
composer_ids.ti.text = state.write_msg['from_addr'] composer_ids.ti.text = state.write_msg['from_addr']
composer_ids.btn.text = state.write_msg['from_addr'] composer_ids.btn.text = state.write_msg['from_addr']
composer_ids.txt_input.text = state.write_msg['to_addr'] composer_ids.txt_input.text = state.write_msg['to_addr']
@ -1544,9 +1545,8 @@ class MyaddDetailPopup(Popup):
address_label = StringProperty() address_label = StringProperty()
address = StringProperty() address = StringProperty()
def __init__(self, **kwargs): def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""My Address Details screen setting.""" """My Address Details screen setting."""
# pylint: disable=useless-super-delegation
super(MyaddDetailPopup, self).__init__(**kwargs) super(MyaddDetailPopup, self).__init__(**kwargs)
def set_address(self, address, label): def set_address(self, address, label):
@ -1577,9 +1577,8 @@ class AddbookDetailPopup(Popup):
address_label = StringProperty() address_label = StringProperty()
address = StringProperty() address = StringProperty()
def __init__(self, **kwargs): def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Method used set screen of address detail page.""" """Method used set screen of address detail page."""
# pylint: disable=useless-super-delegation
super(AddbookDetailPopup, self).__init__(**kwargs) super(AddbookDetailPopup, self).__init__(**kwargs)
def set_addbook_data(self, address, label): def set_addbook_data(self, address, label):
@ -1590,9 +1589,8 @@ class AddbookDetailPopup(Popup):
def update_addbook_label(self, address): def update_addbook_label(self, address):
"""Updating the label of address book address.""" """Updating the label of address book address."""
if str(self.ids.add_label.text): if str(self.ids.add_label.text):
sqlExecute( sqlExecute("UPDATE addressbook SET label = '{}' WHERE \
"UPDATE addressbook SET label = '{}' WHERE" address = '{}';".format(str(self.ids.add_label.text), address))
" address = '{}';".format(str(self.ids.add_label.text), address))
self.parent.children[1].ids.sc11.ids.ml.clear_widgets() self.parent.children[1].ids.sc11.ids.ml.clear_widgets()
self.parent.children[1].ids.sc11.loadAddresslist(None, 'All', '') self.parent.children[1].ids.sc11.loadAddresslist(None, 'All', '')
self.dismiss() self.dismiss()
@ -1644,7 +1642,7 @@ class Draft(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method draft accounts.""" """Clock Schdule for method draft accounts."""
self.sentaccounts() self.sentaccounts()
print dt print (dt)
def sentaccounts(self): def sentaccounts(self):
"""Load draft accounts.""" """Load draft accounts."""
@ -1698,11 +1696,10 @@ class Draft(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="yet no message for this account!!!!!!!!!!!!!", text="yet no message for this account!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)
@ -1724,7 +1721,8 @@ class Draft(Screen):
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str(
data_index)) data_index))
try: try:
msg_count_objs = self.parent.parent.parent.parent.children[2].children[0].ids msg_count_objs = \
self.parent.parent.parent.parent.children[2].children[0].ids
except Exception: except Exception:
msg_count_objs = self.parent.parent.parent.parent.parent.children[ msg_count_objs = self.parent.parent.parent.parent.parent.children[
2].children[0].ids 2].children[0].ids
@ -1749,7 +1747,8 @@ class Draft(Screen):
sendMessageToPeople = True sendMessageToPeople = True
if sendMessageToPeople: if sendMessageToPeople:
from addresses import decodeAddress from addresses import decodeAddress
status, addressVersionNumber, streamNumber, ripe = decodeAddress(toAddress) status, addressVersionNumber, streamNumber, ripe = \
decodeAddress(toAddress)
from addresses import addBMIfNotPresent from addresses import addBMIfNotPresent
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
statusIconColor = 'red' statusIconColor = 'red'
@ -1810,7 +1809,7 @@ class Allmails(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method all mails.""" """Clock Schdule for method all mails."""
self.mailaccounts() self.mailaccounts()
print dt print (dt)
def mailaccounts(self): def mailaccounts(self):
"""Load all mails for account.""" """Load all mails for account."""
@ -1857,11 +1856,10 @@ class Allmails(Screen):
self.ids.ml.add_widget(carousel) self.ids.ml.add_widget(carousel)
else: else:
content = MDLabel( content = MDLabel(
font_style='Body1', font_style='Caption',
theme_text_color='Primary', theme_text_color='Primary',
text="yet no message for this account!!!!!!!!!!!!!", text="yet no message for this account!!!!!!!!!!!!!",
halign='center', halign='center',
bold=True,
size_hint_y=None, size_hint_y=None,
valign='top') valign='top')
self.ids.ml.add_widget(content) self.ids.ml.add_widget(content)

View File

@ -179,13 +179,13 @@ def signal_handler(signum, frame):
if shared.thisapp.daemon or not state.enableGUI: if shared.thisapp.daemon or not state.enableGUI:
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
else: else:
print '# Thread: %s(%d)' % (thread.name, thread.ident) print ('# Thread: {}({})'.format(thread.name, thread.ident))
for filename, lineno, name, line in traceback.extract_stack(frame): for filename, lineno, name, line in traceback.extract_stack(frame):
print 'File: "%s", line %d, in %s' % (filename, lineno, name) print ("File: '{}', line {}, in {}" .format(filename, lineno, name))
if line: if line:
print ' %s' % line.strip() print (' {}'.format(line.strip()))
print 'Unfortunately you cannot use Ctrl+C when running the UI \ print('Unfortunately you cannot use Ctrl+C when running the UI \
because the UI captures the signal.' because the UI captures the signal.')
class Main: # pylint: disable=no-init, old-style-class class Main: # pylint: disable=no-init, old-style-class
@ -282,7 +282,7 @@ class Main: # pylint: disable=no-init, old-style-class
if daemon: if daemon:
with shared.printLock: with shared.printLock:
print 'Running as a daemon. Send TERM signal to end.' print('Running as a daemon. Send TERM signal to end.')
self.daemonize() self.daemonize()
self.setSignalHandler() self.setSignalHandler()
@ -358,7 +358,7 @@ class Main: # pylint: disable=no-init, old-style-class
# Not needed if objproc disabled # Not needed if objproc disabled
if state.enableObjProc: if state.enableObjProc:
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
shared.reloadBroadcastSendersForWhichImWatching() # shared.reloadBroadcastSendersForWhichImWatching()
# API is also objproc dependent # API is also objproc dependent
if config.safeGetBoolean('bitmessagesettings', 'apienabled'): if config.safeGetBoolean('bitmessagesettings', 'apienabled'):
import api # pylint: disable=relative-import import api # pylint: disable=relative-import
@ -373,7 +373,7 @@ class Main: # pylint: disable=no-init, old-style-class
asyncoreThread = BMNetworkThread() asyncoreThread = BMNetworkThread()
asyncoreThread.daemon = True asyncoreThread.daemon = True
asyncoreThread.start() asyncoreThread.start()
for i in range(config.getint('threads', 'receive')): for i in range(config.safeGet('threads', 'receive')):
receiveQueueThread = ReceiveQueueThread(i) receiveQueueThread = ReceiveQueueThread(i)
receiveQueueThread.daemon = True receiveQueueThread.daemon = True
receiveQueueThread.start() receiveQueueThread.start()
@ -405,7 +405,7 @@ class Main: # pylint: disable=no-init, old-style-class
if state.curses: if state.curses:
if not depends.check_curses(): if not depends.check_curses():
sys.exit() sys.exit()
print 'Running with curses' print('Running with curses')
import bitmessagecurses import bitmessagecurses
bitmessagecurses.runwrapper() bitmessagecurses.runwrapper()
@ -498,10 +498,9 @@ class Main: # pylint: disable=no-init, old-style-class
# signal.signal(signal.SIGINT, signal.SIG_DFL) # signal.signal(signal.SIGINT, signal.SIG_DFL)
@staticmethod @staticmethod
def usage(): def usage(self):
"""After passing argument, method displays the usages""" print('Usage: ' + sys.argv[0] + ' [OPTIONS]')
print 'Usage: ' + sys.argv[0] + ' [OPTIONS]' print ('''
print '''
Options: Options:
-h, --help show this help message and exit -h, --help show this help message and exit
-c, --curses use curses (text mode) interface -c, --curses use curses (text mode) interface
@ -509,12 +508,12 @@ Options:
-t, --test dryrun, make testing -t, --test dryrun, make testing
All parameters are optional. All parameters are optional.
''' ''')
def stop(self): # pylint: disable=no-self-use def stop(self): # pylint: disable=no-self-use
"""Method helps to stop the Bitmessage Deamon""" """Method helps to stop the Bitmessage Deamon"""
with shared.printLock: with shared.printLock:
print 'Stopping Bitmessage Deamon.' print('Stopping Bitmessage Deamon.')
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
# ..todo: nice function but no one is using this # ..todo: nice function but no one is using this

View File

@ -1,5 +1,5 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from Queue import Queue from queue.Queue import Queue
from time import time from time import time
class BMStatusBar(QtGui.QStatusBar): class BMStatusBar(QtGui.QStatusBar):

View File

@ -2,7 +2,7 @@
BMConfigParser class definition and default configuration settings BMConfigParser class definition and default configuration settings
""" """
import ConfigParser import configparser
import shutil import shutil
import os import os
from datetime import datetime from datetime import datetime
@ -42,35 +42,35 @@ BMConfigDefaults = {
@Singleton @Singleton
class BMConfigParser(ConfigParser.SafeConfigParser): class BMConfigParser(configparser.ConfigParser):
"""Singleton class inherited from ConfigParser.SafeConfigParser """Singleton class inherited from ConfigParsedadfeConfigParser
with additional methods specific to bitmessage config.""" with additional methods specific to bitmessage config."""
_temp = {} _temp = {}
def set(self, section, option, value=None): def set(self, section, option, value=None):
if self._optcre is self.OPTCRE or value: if self._optcre is self.OPTCRE or value:
if not isinstance(value, basestring): if not isinstance(value, str):
raise TypeError("option values must be strings") raise TypeError("option values must be strings")
if not self.validate(section, option, value): if not self.validate(section, option, value):
raise ValueError("Invalid value %s" % value) raise ValueError("Invalid value %s" % value)
return ConfigParser.ConfigParser.set(self, section, option, value) return configparser.ConfigParser.set(self, section, option, value)
def get(self, section, option, raw=False, variables=None): def get(self, section, option, raw=False, variables=None):
try: try:
if section == "bitmessagesettings" and option == "timeformat": if section == "bitmessagesettings" and option == "timeformat":
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, raw, variables) self, section, option, raw=True, vars=variables)
try: try:
return self._temp[section][option] return self._temp[section][option]
except KeyError: except KeyError:
pass pass
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, True, variables) self, section, option, raw=True, vars=variables)
except ConfigParser.InterpolationError: except configparser.InterpolationError:
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, True, variables) self, section, option, raw=True, vars=variables)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e: except (configparser.NoSectionError, configparser.NoOptionError) as e:
try: try:
return BMConfigDefaults[section][option] return BMConfigDefaults[section][option]
except (KeyError, ValueError, AttributeError): except (KeyError, ValueError, AttributeError):
@ -84,49 +84,58 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
self._temp[section] = {option: value} self._temp[section] = {option: value}
def safeGetBoolean(self, section, field): def safeGetBoolean(self, section, field):
config = configparser.ConfigParser()
try: try:
return self.getboolean(section, field) #Used in the python2.7
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, # return self.getboolean(section, field)
#Used in the python3.5.2
return config.getboolean(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return False return False
def safeGetInt(self, section, field, default=0): def safeGetInt(self, section, field, default=0):
config = configparser.ConfigParser()
try: try:
return self.getint(section, field) #Used in the python2.7
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, # return self.getint(section, field)
#Used in the python3.5.2
return config.getint(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return default return default
def safeGet(self, section, option, default=None): def safeGet(self, section, option, default=None):
try: try:
return self.get(section, option) return self.get(section, option)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return default return default
def items(self, section, raw=False, variables=None): def items(self, section, raw=False, variables=None):
return ConfigParser.ConfigParser.items(self, section, True, variables) return configparser.ConfigParser.items(self, section, True, variables)
def addresses(self): def addresses(self):
return filter( return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
lambda x: x.startswith('BM-'), BMConfigParser().sections())
def read(self, filenames): def read(self, filenames):
ConfigParser.ConfigParser.read(self, filenames) configparser.ConfigParser.read(self, filenames)
for section in self.sections(): for section in self.sections():
for option in self.options(section): for option in self.options(section):
try: try:
if not self.validate( if not self.validate(
section, option, section, option,
ConfigParser.ConfigParser.get(self, section, option) self[section][option]
): ):
try: try:
newVal = BMConfigDefaults[section][option] newVal = BMConfigDefaults[section][option]
except configparser.NoSectionError:
continue
except KeyError: except KeyError:
continue continue
ConfigParser.ConfigParser.set( configparser.ConfigParser.set(
self, section, option, newVal) self, section, option, newVal)
except ConfigParser.InterpolationError: except configparser.InterpolationError:
continue continue
def save(self): def save(self):
@ -144,7 +153,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
# didn't exist before. # didn't exist before.
fileNameExisted = False fileNameExisted = False
# write the file # write the file
with open(fileName, 'wb') as configfile: with open(fileName, 'w') as configfile:
self.write(configfile) self.write(configfile)
# delete the backup # delete the backup
if fileNameExisted: if fileNameExisted:
@ -152,7 +161,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
def validate(self, section, option, value): def validate(self, section, option, value):
try: try:
return getattr(self, 'validate_%s_%s' % (section, option))(value) return getattr(self, 'validate_{}_{}'.format(section, option))(value)
except AttributeError: except AttributeError:
return True return True

View File

@ -29,7 +29,6 @@ class addressGenerator(StoppableThread):
super(addressGenerator, self).stopThread() super(addressGenerator, self).stopThread()
def run(self): def run(self):
while state.shutdown == 0: while state.shutdown == 0:
queueValue = queues.addressGeneratorQueue.get() queueValue = queues.addressGeneratorQueue.get()
nonceTrialsPerByte = 0 nonceTrialsPerByte = 0
@ -134,7 +133,7 @@ class addressGenerator(StoppableThread):
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
if ( if (
ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] ==
'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash
): ):
break break
logger.info( logger.info(
@ -151,19 +150,20 @@ class addressGenerator(StoppableThread):
# The user must have a pretty fast computer. # The user must have a pretty fast computer.
# time.time() - startTime equaled zero. # time.time() - startTime equaled zero.
pass pass
address = encodeAddress( address = encodeAddress(
addressVersionNumber, streamNumber, ripe) addressVersionNumber, streamNumber, ripe)
# An excellent way for us to store our keys # An excellent way for us to store our keys
# is in Wallet Import Format. Let us convert now. # is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey privSigningKey = '\x80'.encode('utf-8') + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4] privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase( privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58) privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80' + potentialPrivEncryptionKey privEncryptionKey = '\x80'.encode('utf-8') + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4] privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKeyWIF = arithmetic.changebase(

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
import threading import threading
import time import time

View File

@ -143,8 +143,8 @@ class singleCleaner(StoppableThread):
# inv/object tracking # inv/object tracking
for connection in \ for connection in \
BMConnectionPool().inboundConnections.values() + \ list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
connection.clean() connection.clean()
# discovery tracking # discovery tracking

View File

@ -70,9 +70,11 @@ class sqlThread(threading.Thread):
# If the settings version is equal to 2 or 3 then the # If the settings version is equal to 2 or 3 then the
# sqlThread will modify the pubkeys table and change # sqlThread will modify the pubkeys table and change
# the settings version to 4. # the settings version to 4.
settingsversion = BMConfigParser().getint( # settingsversion = BMConfigParser().getint('bitmessagesettings', 'settingsversion')
'bitmessagesettings', 'settingsversion') # In the Python3 I am below condition converting into int
# settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \
# if BMConfigParser().get('bitmessagesettings', 'settingsversion') else 0)
settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion')
# People running earlier versions of PyBitmessage do not have the # People running earlier versions of PyBitmessage do not have the
# usedpersonally field in their pubkeys table. Let's add it. # usedpersonally field in their pubkeys table. Let's add it.
if settingsversion == 2: if settingsversion == 2:

View File

@ -23,7 +23,7 @@ Use: `from debug import logger` to import this facility into whatever module you
""" """
import ConfigParser import configparser
import logging import logging
import logging.config import logging.config
import os import os
@ -47,12 +47,13 @@ def configureLogging():
fail_msg = '' fail_msg = ''
try: try:
logging_config = os.path.join(state.appdata, 'logging.dat') logging_config = os.path.join(state.appdata, 'logging.dat')
logging.config.fileConfig(logging_config) # right now I am commenting the logger
# logging.config.fileConfig(logging_config, disable_existing_loggers=False)
return ( return (
False, False,
'Loaded logger configuration from %s' % logging_config 'Loaded logger configuration from %s' % logging_config
) )
except (OSError, ConfigParser.NoSectionError): except (OSError, configparser.NoSectionError):
if os.path.isfile(logging_config): if os.path.isfile(logging_config):
fail_msg = \ fail_msg = \
'Failed to load logger configuration from %s, using default' \ 'Failed to load logger configuration from %s, using default' \

View File

@ -419,11 +419,11 @@ def check_dependencies(verbose=False, optional=False):
'PyBitmessage requires Python 2.7.4 or greater' 'PyBitmessage requires Python 2.7.4 or greater'
' (but not Python 3+)') ' (but not Python 3+)')
has_all_dependencies = False has_all_dependencies = False
if sys.hexversion >= 0x3000000: # if sys.hexversion >= 0x3000000:
logger.error( # logger.error(
'PyBitmessage does not support Python 3+. Python 2.7.4' # 'PyBitmessage does not support Python 3+. Python 2.7.4'
' or greater is required.') # ' or greater is required.')
has_all_dependencies = False # has_all_dependencies = False
check_functions = [check_ripemd160, check_sqlite, check_openssl] check_functions = [check_ripemd160, check_sqlite, check_openssl]
if optional: if optional:

View File

@ -4,7 +4,8 @@ from pyelliptic import arithmetic
# This function expects that pubkey begin with \x04 # This function expects that pubkey begin with \x04
def calculateBitcoinAddressFromPubkey(pubkey): def calculateBitcoinAddressFromPubkey(pubkey):
if len(pubkey) != 65: if len(pubkey) != 65:
print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was'\
'{}, bytes long rather than 65.'.format(len(pubkey)))
return "error" return "error"
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha256') sha = hashlib.new('sha256')
@ -25,7 +26,8 @@ def calculateBitcoinAddressFromPubkey(pubkey):
def calculateTestnetAddressFromPubkey(pubkey): def calculateTestnetAddressFromPubkey(pubkey):
if len(pubkey) != 65: if len(pubkey) != 65:
print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was',\
'{}, bytes long rather than 65.'.format(pubkey))
return "error" return "error"
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha256') sha = hashlib.new('sha256')

View File

@ -1,7 +1,7 @@
"""Helper Sql performs sql operations.""" """Helper Sql performs sql operations."""
import threading import threading
import Queue import queue as Queue
sqlSubmitQueue = Queue.Queue() sqlSubmitQueue = Queue.Queue()
# SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks. # SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks.

View File

@ -7,7 +7,7 @@ Helper Start performs all the startup operations.
# pylint: disable=too-many-branches,too-many-statements # pylint: disable=too-many-branches,too-many-statements
from __future__ import print_function from __future__ import print_function
import ConfigParser import configparser
import os import os
import platform import platform
import sys import sys
@ -25,20 +25,23 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False
def _loadTrustedPeer(): def _loadTrustedPeer():
trustedPeer = ''
try: try:
trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer')
except ConfigParser.Error: except configparser.Error:
# This probably means the trusted peer wasn't specified so we # This probably means the trusted peer wasn't specified so we
# can just leave it as None # can just leave it as None
return return
try: try:
if trustedPeer != None:
host, port = trustedPeer.split(':') host, port = trustedPeer.split(':')
state.trustedPeer = state.Peer(host, int(port))
except ValueError: except ValueError:
sys.exit( sys.exit(
'Bad trustedpeer config setting! It should be set as' 'Bad trustedpeer config setting! It should be set as'
' trustedpeer=<hostname>:<portnumber>' ' trustedpeer=<hostname>:<portnumber>'
) )
state.trustedPeer = state.Peer(host, int(port))
def loadConfig(): def loadConfig():
@ -137,11 +140,12 @@ def loadConfig():
_loadTrustedPeer() _loadTrustedPeer()
def updateConfig(): def updateConfig():
"""Save the config""" """Save the config"""
config = BMConfigParser() config = BMConfigParser()
settingsversion = config.getint('bitmessagesettings', 'settingsversion') # Used python2.7
# settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \
settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion')
if settingsversion == 1: if settingsversion == 1:
config.set('bitmessagesettings', 'socksproxytype', 'none') config.set('bitmessagesettings', 'socksproxytype', 'none')
config.set('bitmessagesettings', 'sockshostname', 'localhost') config.set('bitmessagesettings', 'sockshostname', 'localhost')

View File

@ -15,8 +15,8 @@ def makeCryptor(privkey):
"""Return a private pyelliptic.ECC() instance""" """Return a private pyelliptic.ECC() instance"""
private_key = a.changebase(privkey, 16, 256, minlen=32) private_key = a.changebase(privkey, 16, 256, minlen=32)
public_key = pointMult(private_key) public_key = pointMult(private_key)
privkey_bin = '\x02\xca\x00\x20' + private_key privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key
pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-32:] pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:]
cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin)
return cryptor return cryptor

View File

@ -40,8 +40,8 @@ def json_serialize_knownnodes(output):
Reorganize knownnodes dict and write it as JSON to output Reorganize knownnodes dict and write it as JSON to output
""" """
_serialized = [] _serialized = []
for stream, peers in knownNodes.iteritems(): for stream, peers in iter(knownNodes.items()):
for peer, info in peers.iteritems(): for peer, info in iter(peers.items()):
info.update(rating=round(info.get('rating', 0), 2)) info.update(rating=round(info.get('rating', 0), 2))
_serialized.append({ _serialized.append({
'stream': stream, 'peer': peer._asdict(), 'info': info 'stream': stream, 'peer': peer._asdict(), 'info': info
@ -85,7 +85,7 @@ def saveKnownNodes(dirName=None):
if dirName is None: if dirName is None:
dirName = state.appdata dirName = state.appdata
with knownNodesLock: with knownNodesLock:
with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output: with open(os.path.join(dirName, 'knownnodes.dat'), 'w') as output:
json_serialize_knownnodes(output) json_serialize_knownnodes(output)
@ -106,7 +106,7 @@ def createDefaultKnownNodes():
def readKnownNodes(): def readKnownNodes():
try: try:
with open(state.appdata + 'knownnodes.dat', 'rb') as source: with open(state.appdata + 'knownnodes.dat', 'r') as source:
with knownNodesLock: with knownNodesLock:
try: try:
json_deserialize_knownnodes(source) json_deserialize_knownnodes(source)

View File

@ -64,20 +64,30 @@ else:
if time_format != DEFAULT_TIME_FORMAT: if time_format != DEFAULT_TIME_FORMAT:
try: try:
#Check day names #Check day names
for i in xrange(7): new_time_format = time_format
unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) import sys
if sys.version_info >= (3, 0, 0) and time_format == '%%c':
time_format = '%c'
for i in range(7):
#this work for python2.7
# unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding)
#this code for the python3
(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode()
#Check month names #Check month names
for i in xrange(1, 13): for i in range(1, 13):
unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) # unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding)
(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode()
#Check AM/PM #Check AM/PM
unicode(time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode()
unicode(time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode()
#Check DST #Check DST
unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1)), encoding) (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode()
except: except:
logger.exception('Could not decode locale formatted timestamp') logger.exception('Could not decode locale formatted timestamp')
time_format = DEFAULT_TIME_FORMAT time_format = DEFAULT_TIME_FORMAT
encoding = DEFAULT_ENCODING encoding = DEFAULT_ENCODING
time_format = new_time_format
def setlocale(category, newlocale): def setlocale(category, newlocale):
locale.setlocale(category, newlocale) locale.setlocale(category, newlocale)

View File

@ -4,7 +4,7 @@ src/messagetypes/__init__.py
""" """
from importlib import import_module from importlib import import_module
from os import path, listdir from os import path, listdir
from string import lower
try: try:
from kivy.utils import platform from kivy.utils import platform
except: except:

View File

@ -3,7 +3,7 @@ src/multiqueue.py
================= =================
""" """
import Queue import queue as Queue
from collections import deque from collections import deque
import helper_random import helper_random

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
from helper_threading import StoppableThread from helper_threading import StoppableThread
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool

View File

@ -30,7 +30,10 @@ class AdvancedDispatcher(asyncore.dispatcher):
_buf_len = 131072 # 128kB _buf_len = 131072 # 128kB
def __init__(self, sock=None): def __init__(self, sock=None):
if not hasattr(self, '_map'): # python 2 below condition is used
# if not hasattr(self, '_map'):
# python 3 below condition is used
if not '_map' in dir(self):
asyncore.dispatcher.__init__(self, sock) asyncore.dispatcher.__init__(self, sock)
self.read_buf = bytearray() self.read_buf = bytearray()
self.write_buf = bytearray() self.write_buf = bytearray()

View File

@ -769,8 +769,8 @@ class dispatcher:
try: try:
retattr = getattr(self.socket, attr) retattr = getattr(self.socket, attr)
except AttributeError: except AttributeError:
raise AttributeError("%s instance has no attribute '%s'" raise AttributeError("{} instance has no attribute {}"
% (self.__class__.__name__, attr)) .format(self.__class__.__name__, attr))
else: else:
msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \
"instead" % {'me': self.__class__.__name__, 'attr': attr} "instead" % {'me': self.__class__.__name__, 'attr': attr}
@ -788,7 +788,7 @@ class dispatcher:
def log_info(self, message, log_type='info'): def log_info(self, message, log_type='info'):
"""Conditionally print a message""" """Conditionally print a message"""
if log_type not in self.ignore_log_types: if log_type not in self.ignore_log_types:
print '%s: %s' % (log_type, message) print ('{}: {}'.format((log_type, message)))
def handle_read_event(self): def handle_read_event(self):
"""Handle a read event""" """Handle a read event"""

View File

@ -11,7 +11,7 @@ import time
from binascii import hexlify from binascii import hexlify
import addresses import addresses
import connectionpool import network.connectionpool
import knownnodes import knownnodes
import protocol import protocol
import state import state
@ -26,9 +26,9 @@ from network.bmobject import (
BMObjectInvalidError, BMObjectAlreadyHaveError) BMObjectInvalidError, BMObjectAlreadyHaveError)
from network.node import Node from network.node import Node
from network.proxy import ProxyError from network.proxy import ProxyError
from objectracker import missingObjects, ObjectTracker from network.objectracker import missingObjects, ObjectTracker
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
class BMProtoError(ProxyError): class BMProtoError(ProxyError):
@ -86,7 +86,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"""Process incoming header""" """Process incoming header"""
self.magic, self.command, self.payloadLength, self.checksum = \ self.magic, self.command, self.payloadLength, self.checksum = \
protocol.Header.unpack(self.read_buf[:protocol.Header.size]) protocol.Header.unpack(self.read_buf[:protocol.Header.size])
self.command = self.command.rstrip('\x00') self.command = self.command.rstrip('\x00'.encode('utf-8'))
if self.magic != 0xE9BEB4D9: if self.magic != 0xE9BEB4D9:
# skip 1 byte in order to sync # skip 1 byte in order to sync
self.set_state("bm_header", length=1) self.set_state("bm_header", length=1)

View File

@ -7,20 +7,19 @@ import re
import socket import socket
import time import time
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import helper_random import helper_random
import knownnodes import knownnodes
import protocol import protocol
import state import state
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from connectionchooser import chooseConnection from network.connectionchooser import chooseConnection
from debug import logger from debug import logger
from proxy import Proxy from network.proxy import Proxy
from singleton import Singleton from singleton import Singleton
from tcp import ( from network.tcp import (
bootstrap, Socks4aBMConnection, Socks5BMConnection, TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection)
TCPConnection, TCPServer) from network.udp import UDPSocket
from udp import UDPSocket
@Singleton @Singleton
@ -237,7 +236,7 @@ class BMConnectionPool(object):
except ValueError: except ValueError:
Proxy.onion_proxy = None Proxy.onion_proxy = None
established = sum( established = sum(
1 for c in self.outboundConnections.values() 1 for c in list(self.outboundConnections.values())
if (c.connected and c.fullyEstablished)) if (c.connected and c.fullyEstablished))
pending = len(self.outboundConnections) - established pending = len(self.outboundConnections) - established
if established < BMConfigParser().safeGetInt( if established < BMConfigParser().safeGetInt(
@ -275,10 +274,15 @@ class BMConnectionPool(object):
continue continue
self.lastSpawned = time.time() self.lastSpawned = time.time()
print('++++++++++++++++++++++++++++++++++++++++++')
print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values()))
print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values()))
print('+++++++++++++++++++++++++++++++++++++++++++')
else: else:
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() list(self.outboundConnections.values())
): ):
# FIXME: rating will be increased after next connection # FIXME: rating will be increased after next connection
i.handle_close() i.handle_close()
@ -324,8 +328,8 @@ class BMConnectionPool(object):
reaper = [] reaper = []
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() list(self.outboundConnections.values())
): ):
minTx = time.time() - 20 minTx = time.time() - 20
if i.fullyEstablished: if i.fullyEstablished:
@ -338,10 +342,10 @@ class BMConnectionPool(object):
time.time() - i.lastTx) time.time() - i.lastTx)
i.set_state("close") i.set_state("close")
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() + list(self.outboundConnections.values()) +
self.listeningSockets.values() + list(self.listeningSockets.values()) +
self.udpSockets.values() list(self.udpSockets.values())
): ):
if not (i.accepting or i.connecting or i.connected): if not (i.accepting or i.connecting or i.connected):
reaper.append(i) reaper.append(i)

View File

@ -7,7 +7,7 @@ from random import choice, sample, expovariate
from threading import RLock from threading import RLock
from time import time from time import time
import connectionpool from network import connectionpool
import state import state
from debug import logging from debug import logging
from queues import invQueue from queues import invQueue
@ -99,12 +99,12 @@ class Dandelion(): # pylint: disable=old-style-class
with self.lock: with self.lock:
if len(self.stem) < MAX_STEMS: if len(self.stem) < MAX_STEMS:
self.stem.append(connection) self.stem.append(connection)
for k in (k for k, v in self.nodeMap.iteritems() if v is None): for k in (k for k, v in iter(self.nodeMap.items()) if v is None):
self.nodeMap[k] = connection self.nodeMap[k] = connection
for k, v in { for k, v in iter({
k: v for k, v in self.hashMap.iteritems() k: v for k, v in iter(self.hashMap.items())
if v.child is None if v.child is None
}.iteritems(): }).items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
connection, v.stream, self.poissonTimeout()) connection, v.stream, self.poissonTimeout())
invQueue.put((v.stream, k, v.child)) invQueue.put((v.stream, k, v.child))
@ -120,13 +120,13 @@ class Dandelion(): # pylint: disable=old-style-class
self.stem.remove(connection) self.stem.remove(connection)
# active mappings to pointing to the removed node # active mappings to pointing to the removed node
for k in ( for k in (
k for k, v in self.nodeMap.iteritems() if v == connection k for k, v in iter(self.nodeMap.items()) if v == connection
): ):
self.nodeMap[k] = None self.nodeMap[k] = None
for k, v in { for k, v in iter({
k: v for k, v in self.hashMap.iteritems() k: v for k, v in iter(self.hashMap.items())
if v.child == connection if v.child == connection
}.iteritems(): }).items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
None, v.stream, self.poissonTimeout()) None, v.stream, self.poissonTimeout())
@ -167,7 +167,7 @@ class Dandelion(): # pylint: disable=old-style-class
with self.lock: with self.lock:
deadline = time() deadline = time()
toDelete = [ toDelete = [
[v.stream, k, v.child] for k, v in self.hashMap.iteritems() [v.stream, k, v.child] for k, v in iter(self.hashMap.items())
if v.timeout < deadline if v.timeout < deadline
] ]
@ -182,8 +182,8 @@ class Dandelion(): # pylint: disable=old-style-class
try: try:
# random two connections # random two connections
self.stem = sample( self.stem = sample(
connectionpool.BMConnectionPool( list(connectionpool.BMConnectionPool(
).outboundConnections.values(), MAX_STEMS) ).outboundConnections.values()), MAX_STEMS)
# not enough stems available # not enough stems available
except ValueError: except ValueError:
self.stem = connectionpool.BMConnectionPool( self.stem = connectionpool.BMConnectionPool(

View File

@ -7,12 +7,12 @@ import time
import addresses import addresses
import helper_random import helper_random
import protocol import protocol
from dandelion import Dandelion from network.dandelion import Dandelion
from debug import logger from debug import logger
from helper_threading import StoppableThread from helper_threading import StoppableThread
from inventory import Inventory from inventory import Inventory
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from objectracker import missingObjects from network.objectracker import missingObjects
class DownloadThread(StoppableThread): class DownloadThread(StoppableThread):
@ -32,7 +32,7 @@ class DownloadThread(StoppableThread):
"""Expire pending downloads eventually""" """Expire pending downloads eventually"""
deadline = time.time() - DownloadThread.requestExpires deadline = time.time() - DownloadThread.requestExpires
try: try:
toDelete = [k for k, v in missingObjects.iteritems() if v < deadline] toDelete = [k for k, v in iter(missingObjects.items()) if v < deadline]
except RuntimeError: except RuntimeError:
pass pass
else: else:
@ -46,7 +46,7 @@ class DownloadThread(StoppableThread):
# Choose downloading peers randomly # Choose downloading peers randomly
connections = [ connections = [
x for x in x for x in
BMConnectionPool().inboundConnections.values() + BMConnectionPool().outboundConnections.values() list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values())
if x.fullyEstablished] if x.fullyEstablished]
helper_random.randomshuffle(connections) helper_random.randomshuffle(connections)
try: try:

View File

@ -2,7 +2,7 @@ import socket
from advanceddispatcher import AdvancedDispatcher from advanceddispatcher import AdvancedDispatcher
import asyncore_pollchoose as asyncore import asyncore_pollchoose as asyncore
from proxy import ProxyError from network.proxy import ProxyError
from socks5 import Socks5Connection, Socks5Resolver from socks5 import Socks5Connection, Socks5Resolver
from socks4a import Socks4aConnection, Socks4aResolver from socks4a import Socks4aConnection, Socks4aResolver

View File

@ -2,7 +2,7 @@
src/network/invthread.py src/network/invthread.py
======================== ========================
""" """
import Queue import queue as Queue
import random import random
from time import time from time import time

View File

@ -7,7 +7,7 @@ from threading import RLock
import network.connectionpool import network.connectionpool
from network.dandelion import Dandelion from network.dandelion import Dandelion
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
haveBloom = False haveBloom = False

View File

@ -6,9 +6,9 @@ src/network/proxy.py
import socket import socket
import time import time
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import state import state
from advanceddispatcher import AdvancedDispatcher from network.advanceddispatcher import AdvancedDispatcher
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger

View File

@ -140,20 +140,20 @@ if __name__ == '__main__':
k = RandomTrackingDict() k = RandomTrackingDict()
d = {} d = {}
print "populating random tracking dict" print ("populating random tracking dict")
a.append(time()) a.append(time())
for i in range(50000): for i in range(50000):
k[randString()] = True k[randString()] = True
a.append(time()) a.append(time())
print "done" print ("done")
while k: while k:
retval = k.randomKeys(1000) retval = k.randomKeys(1000)
if not retval: if not retval:
print "error getting random keys" print ("error getting random keys")
try: try:
k.randomKeys(100) k.randomKeys(100)
print "bad" print( "bad")
except KeyError: except KeyError:
pass pass
for i in retval: for i in retval:
@ -161,4 +161,4 @@ if __name__ == '__main__':
a.append(time()) a.append(time())
for x in range(len(a) - 1): for x in range(len(a) - 1):
print "%i: %.3f" % (x, a[x + 1] - a[x]) print("{}i: {}.3f".format(x, a[x + 1] - a[x]))

View File

@ -1,5 +1,5 @@
import errno import errno
import Queue import queue as Queue
import socket import socket
from debug import logger from debug import logger

View File

@ -6,7 +6,7 @@ src/network/socks4a.py
import socket import socket
import struct import struct
from proxy import Proxy, ProxyError, GeneralProxyError from network.proxy import Proxy, ProxyError, GeneralProxyError
class Socks4aError(ProxyError): class Socks4aError(ProxyError):
@ -141,4 +141,4 @@ class Socks4aResolver(Socks4a):
PyBitmessage, a callback needs to be implemented which hasn't PyBitmessage, a callback needs to be implemented which hasn't
been done yet. been done yet.
""" """
print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) print("Resolved {} as {}".format(self.host, self.proxy_sock_name()))

View File

@ -9,7 +9,7 @@ import socket
import struct import struct
import state import state
from proxy import GeneralProxyError, Proxy, ProxyError from network.proxy import GeneralProxyError, Proxy, ProxyError
class Socks5AuthError(ProxyError): class Socks5AuthError(ProxyError):
@ -218,4 +218,4 @@ class Socks5Resolver(Socks5):
To use this within PyBitmessage, a callback needs to be To use this within PyBitmessage, a callback needs to be
implemented which hasn't been done yet. implemented which hasn't been done yet.
""" """
print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) print("Resolved {} as {}".format(self.host, self.proxy_sock_name()))

View File

@ -4,9 +4,9 @@ src/network/stats.py
""" """
import time import time
import asyncore_pollchoose as asyncore from network import asyncore_pollchoose as asyncore
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from objectracker import missingObjects from network.objectracker import missingObjects
lastReceivedTimestamp = time.time() lastReceivedTimestamp = time.time()
@ -20,8 +20,8 @@ currentSentSpeed = 0
def connectedHostsList(): def connectedHostsList():
"""List of all the connected hosts""" """List of all the connected hosts"""
retval = [] retval = []
for i in BMConnectionPool().inboundConnections.values() + \ for i in list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
if not i.fullyEstablished: if not i.fullyEstablished:
continue continue
try: try:

View File

@ -10,8 +10,8 @@ import socket
import time import time
import addresses import addresses
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import connectionpool import network.connectionpool
import helper_random import helper_random
import knownnodes import knownnodes
import protocol import protocol
@ -362,7 +362,7 @@ class TCPServer(AdvancedDispatcher):
"""TCP connection server for Bitmessage protocol""" """TCP connection server for Bitmessage protocol"""
def __init__(self, host='127.0.0.1', port=8444): def __init__(self, host='127.0.0.1', port=8444):
if not hasattr(self, '_map'): if not '_map' in dir(self):
AdvancedDispatcher.__init__(self) AdvancedDispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr() self.set_reuse_addr()

View File

@ -21,7 +21,12 @@ if sys.version_info >= (2, 7, 13):
# this means TLSv1 or higher # this means TLSv1 or higher
# in the future change to # in the future change to
# ssl.PROTOCOL_TLS1.2 # ssl.PROTOCOL_TLS1.2
# Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I
# have used try and catch
try:
sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member
except AttributeError:
sslProtocolVersion = ssl.PROTOCOL_SSLv23
elif sys.version_info >= (2, 7, 9): elif sys.version_info >= (2, 7, 9):
# this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created # this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created
sslProtocolVersion = ssl.PROTOCOL_SSLv23 sslProtocolVersion = ssl.PROTOCOL_SSLv23

View File

@ -7,9 +7,9 @@ import socket
import state import state
import protocol import protocol
from bmproto import BMProto from network.bmproto import BMProto
from debug import logger from debug import logger
from objectracker import ObjectTracker from network.objectracker import ObjectTracker
from queues import receiveDataQueue from queues import receiveDataQueue

View File

@ -11,7 +11,7 @@ from helper_threading import StoppableThread
from inventory import Inventory from inventory import Inventory
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.dandelion import Dandelion from network.dandelion import Dandelion
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
class UploadThread(StoppableThread): class UploadThread(StoppableThread):
@ -26,8 +26,8 @@ class UploadThread(StoppableThread):
while not self._stopped: while not self._stopped:
uploaded = 0 uploaded = 0
# Choose downloading peers randomly # Choose downloading peers randomly
connections = [x for x in BMConnectionPool().inboundConnections.values() + connections = [x for x in list(BMConnectionPool().inboundConnections.values()) +
BMConnectionPool().outboundConnections.values() if x.fullyEstablished] list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished]
helper_random.randomshuffle(connections) helper_random.randomshuffle(connections)
for i in connections: for i in connections:
now = time.time() now = time.time()

View File

@ -107,9 +107,10 @@ def do_opencl_pow(hash, target):
#initCL() #initCL()
if __name__ == "__main__": if __name__ == "__main__":
target = 54227212183L #in python3 I have change this 54227212183L to 54227212183
target = 54227212183
initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex") initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex")
nonce = do_opencl_pow(initialHash.encode("hex"), target) nonce = do_opencl_pow(initialHash.encode("hex"), target)
trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8])
print "{} - value {} < {}".format(nonce, trialValue, target) print ("{} - value {} < {}".format(nonce, trialValue, target))

View File

@ -94,9 +94,9 @@ def isBitSetWithinBitfield(fourByteString, n):
def encodeHost(host): def encodeHost(host):
"""Encode a given host to be used in low-level socket operations""" """Encode a given host to be used in low-level socket operations"""
if host.find('.onion') > -1: if host.find('.onion') > -1:
return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True) return '\xfd\x87\xd8\x7e\xeb\x43'.encode('utf-8') + base64.b32decode(host.split(".")[0], True)
elif host.find(':') == -1: elif host.find(':') == -1:
return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('utf-8') + \
socket.inet_aton(host) socket.inet_aton(host)
return socket.inet_pton(socket.AF_INET6, host) return socket.inet_pton(socket.AF_INET6, host)

View File

@ -30,17 +30,24 @@ def get_code_string(base):
elif base == 58: elif base == 58:
return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
elif base == 256: elif base == 256:
return ''.join([chr(x) for x in range(256)]) '''raw_unicode_escape is used because in the python3 after range(161) its genreate the'
the speical character so avoiding that function we have used the raw_unicode method '''
return ''.join([chr(x) for x in range(256)]).encode('raw_unicode_escape')
else: else:
raise ValueError("Invalid base!") raise ValueError("Invalid base!")
def encode(val, base, minlen=0): def encode(val, base, minlen=0):
code_string = get_code_string(base) code_string = get_code_string(base)
result = "" result = ''
# result = str.encode(result)
count = 0
while val > 0: while val > 0:
result = code_string[val % base] + result count += 1
val /= base print(f'code_string[int(val) % base:int(val) % base + 1] -{code_string[int(val) % base:int(val) % base + 1]}')
print(f'result-{result}')
result = code_string[int(val) % base:int(val) % base + 1] + result
val = int(val / base)
if len(result) < minlen: if len(result) < minlen:
result = code_string[0] * (minlen - len(result)) + result result = code_string[0] * (minlen - len(result)) + result
return result return result

View File

@ -8,7 +8,7 @@ src/pyelliptic/cipher.py
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from openssl import OpenSSL from .openssl import OpenSSL
# pylint: disable=redefined-builtin # pylint: disable=redefined-builtin

View File

@ -12,9 +12,9 @@ src/pyelliptic/ecc.py
from hashlib import sha512 from hashlib import sha512
from struct import pack, unpack from struct import pack, unpack
from cipher import Cipher from pyelliptic.cipher import Cipher
from hash import equals, hmac_sha256 from pyelliptic.hash import equals, hmac_sha256
from openssl import OpenSSL from pyelliptic.openssl import OpenSSL
class ECC(object): class ECC(object):
@ -137,18 +137,19 @@ class ECC(object):
i += 2 i += 2
pubkey_x = pubkey[i:i + tmplen] pubkey_x = pubkey[i:i + tmplen]
i += tmplen i += tmplen
i += int(tmplen / 3)
tmplen = unpack('!H', pubkey[i:i + 2])[0] tmplen = unpack('!H', pubkey[i:i + 2])[0]
i += 2 i += 2
pubkey_y = pubkey[i:i + tmplen] pubkey_y = pubkey[i:i + tmplen]
i += tmplen i += tmplen
return curve, pubkey_x, pubkey_y, i return curve, pubkey_x, pubkey_y, int(i)
@staticmethod @staticmethod
def _decode_privkey(privkey): def _decode_privkey(privkey):
i = 0 i = 0
curve = unpack('!H', privkey[i:i + 2])[0] curve = unpack('!H', privkey[i:i + 2])[0]
i += 2 i += 2
tmplen = unpack('!H', privkey[i:i + 2])[0] tmplen = pack('!s', privkey[i:i + 1])[0]
i += 2 i += 2
privkey = privkey[i:i + tmplen] privkey = privkey[i:i + tmplen]
i += tmplen i += tmplen

View File

@ -7,7 +7,7 @@ src/pyelliptic/hash.py
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from openssl import OpenSSL from .openssl import OpenSSL
# For python3 # For python3

View File

@ -90,7 +90,7 @@ class _OpenSSL:
"""Build the wrapper""" """Build the wrapper"""
self._lib = ctypes.CDLL(library) self._lib = ctypes.CDLL(library)
self._version, self._hexversion, self._cflags = get_version(self._lib) self._version, self._hexversion, self._cflags = get_version(self._lib)
self._libreSSL = self._version.startswith("LibreSSL") self._libreSSL = (self._version).decode("utf-8").startswith("OpenSSL")
self.pointer = ctypes.pointer self.pointer = ctypes.pointer
self.c_int = ctypes.c_int self.c_int = ctypes.c_int
@ -674,6 +674,7 @@ def loadOpenSSL():
elif 'win32' in sys.platform or 'win64' in sys.platform: elif 'win32' in sys.platform or 'win64' in sys.platform:
libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) libdir.append(path.join(sys._MEIPASS, 'libeay32.dll'))
else: else:
libdir.extend([ libdir.extend([
path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libcrypto.so'),
path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libssl.so'),

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
from class_objectProcessorQueue import ObjectProcessorQueue from class_objectProcessorQueue import ObjectProcessorQueue
from multiqueue import MultiQueue from multiqueue import MultiQueue

View File

@ -125,7 +125,7 @@ def reloadMyAddressHashes():
keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat') keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat')
hasEnabledKeys = False hasEnabledKeys = False
for addressInKeysFile in BMConfigParser().addresses(): for addressInKeysFile in BMConfigParser().addresses():
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled') isEnabled = BMConfigParser().safeGet(addressInKeysFile, 'enabled')
if isEnabled: if isEnabled:
hasEnabledKeys = True hasEnabledKeys = True
# status # status
@ -174,12 +174,9 @@ def reloadBroadcastSendersForWhichImWatching():
# Now, for all addresses, even version 2 addresses, # Now, for all addresses, even version 2 addresses,
# we should create Cryptor objects in a dictionary which we will # we should create Cryptor objects in a dictionary which we will
# use to attempt to decrypt encrypted broadcast messages. # use to attempt to decrypt encrypted broadcast messages.
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
privEncryptionKey = hashlib.sha512( privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \
encodeVarint(addressVersionNumber) + + encodeVarint(streamNumber) + hash)).digest()[:32]
encodeVarint(streamNumber) + hash
).digest()[:32]
MyECSubscriptionCryptorObjects[hash] = \ MyECSubscriptionCryptorObjects[hash] = \
highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
else: else:

View File

@ -1,5 +1,5 @@
import os import os
import Queue import queue as Queue
import threading import threading
import time import time

View File

@ -75,7 +75,7 @@ class singleinstance:
fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
self.lockPid = os.getpid() self.lockPid = os.getpid()
except IOError: except IOError:
print 'Another instance of this application is already running' print ('Another instance of this application is already running')
sys.exit(-1) sys.exit(-1)
else: else:
pidLine = "%i\n" % self.lockPid pidLine = "%i\n" % self.lockPid
@ -94,11 +94,11 @@ class singleinstance:
os.close(self.fd) os.close(self.fd)
else: else:
fcntl.lockf(self.fp, fcntl.LOCK_UN) fcntl.lockf(self.fp, fcntl.LOCK_UN)
except Exception, e: except Exception as e:
pass pass
return return
print "Cleaning up lockfile" print ("Cleaning up lockfile")
try: try:
if sys.platform == 'win32': if sys.platform == 'win32':
if hasattr(self, 'fd'): if hasattr(self, 'fd'):

View File

@ -9,7 +9,7 @@ from threading import RLock
import time import time
from paths import lookupAppdataFolder from paths import lookupAppdataFolder
from storage import InventoryStorage, InventoryItem from storage.storage import InventoryStorage, InventoryItem
class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ancestors, abstract-method class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ancestors, abstract-method
@ -144,7 +144,7 @@ class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ances
newInventory[streamNumber][hashId] = InventoryItem( newInventory[streamNumber][hashId] = InventoryItem(
objectType, streamNumber, None, expiresTime, tag) objectType, streamNumber, None, expiresTime, tag)
except KeyError: except KeyError:
print "error loading %s" % (hexlify(hashId)) print ("error loading {}".format((hexlify(hashId))))
self._inventory = newInventory self._inventory = newInventory
# for i, v in self._inventory.items(): # for i, v in self._inventory.items():
# print "loaded stream: %s, %i items" % (i, len(v)) # print "loaded stream: %s, %i items" % (i, len(v))

View File

@ -6,8 +6,9 @@ import sqlite3
import time import time
from threading import RLock from threading import RLock
from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
from storage import InventoryStorage, InventoryItem from storage.storage import InventoryStorage, InventoryItem
class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors

View File

@ -1,32 +0,0 @@
#!/usr/bin/env python
# Import the libraries.
import pdb;pdb.set_trace()
import pydenticon100000000000000000000000
import hashlib
# Set-up some test data.
users = ["alice", "bob", "eve", "dave"]
# Set-up a list of foreground colours (taken from Sigil).
foreground = ["rgb(45,79,255)",
"rgb(254,180,44)",
"rgb(226,121,234)",
"rgb(30,179,253)",
"rgb(232,77,65)",
"rgb(49,203,115)",
"rgb(141,69,170)"]
# Set-up a background colour (taken from Sigil).
background = "rgb(224,224,224)"
# Set-up the padding (top, bottom, left, right) in pixels.
padding = (20, 20, 20, 20)
# Instantiate a generator that will create 5x5 block identicons using SHA1
# digest.
generator = pydenticon.Generator(5, 5, digest=hashlib.sha1, foreground=foreground, background=background)
# identicon_ascii = generator.generate("john.doe@example.com", 200, 200,
# output_format="ascii")
# print identicon_ascii
for user in users:
identicon = generator.generate(user, 200, 200, padding=padding, output_format="png")
filename = user + ".png"
with open(filename, "wb") as f:
f.write(identicon)

View File

@ -5,7 +5,7 @@ Tests for core and those that do not work outside
import os import os
import pickle # nosec import pickle # nosec
import Queue import queue as Queue
import random # nosec import random # nosec
import string import string
import time import time

View File

@ -46,11 +46,11 @@ def translateText(context, text, n=None):
try: try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
except Exception as err: except Exception as err:
print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ print ('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\
.You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\ .You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\
or by searching Google for \'PyQt Download\'.\ or by searching Google for \'PyQt Download\'.\
If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon' If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon')
print 'Error message:', err print ('Error message:', err)
os._exit(0) # pylint: disable=protected-access os._exit(0) # pylint: disable=protected-access
if n is None: if n is None:
return QtGui.QApplication.translate(context, text) return QtGui.QApplication.translate(context, text)