From c92c499b0232e1501aa37e03274a7b5b47f8c665 Mon Sep 17 00:00:00 2001 From: Inso <insomniak.fr@gmail.com> Date: Mon, 24 Mar 2014 20:24:11 +0100 Subject: [PATCH] Huge code update to follow pip8 conventions --- Makefile | 2 +- res/ui/accountConfigurationDialog.ui | 32 +-- res/ui/addContactDialog.ui | 8 +- res/ui/communityConfigurationDialog.ui | 22 +- res/ui/communityParametersWidget.ui | 91 -------- res/ui/communityTabWidget.ui | 12 +- res/ui/issuanceDialog.ui | 14 +- res/ui/mainwindow.ui | 88 ++++---- res/ui/transferDialog.ui | 60 ++--- src/cutecoin/__init__.py | 4 +- src/cutecoin/core/__init__.py | 31 ++- src/cutecoin/core/config.py | 29 +-- src/cutecoin/core/exceptions.py | 58 ++++- src/cutecoin/gui/addContactDialog.py | 22 +- src/cutecoin/gui/communityTabWidget.py | 22 +- src/cutecoin/gui/configureAccountDialog.py | 81 +++---- src/cutecoin/gui/configureCommunityDialog.py | 67 +++--- src/cutecoin/gui/issuanceDialog.py | 57 +++-- src/cutecoin/gui/mainWindow.py | 108 +++++---- src/cutecoin/gui/transferMoneyDialog.py | 117 +++++----- src/cutecoin/models/account/__init__.py | 205 +++++++++++------- .../models/account/communities/__init__.py | 31 +-- .../models/account/communities/itemModel.py | 16 +- .../models/account/communities/listModel.py | 16 +- .../models/account/wallets/__init__.py | 28 +-- .../models/account/wallets/listModel.py | 15 +- src/cutecoin/models/coin/__init__.py | 11 +- src/cutecoin/models/coin/listModel.py | 17 +- src/cutecoin/models/community/__init__.py | 179 +++++++++------ src/cutecoin/models/community/itemModel.py | 24 +- .../models/community/membersListModel.py | 13 +- src/cutecoin/models/community/treeModel.py | 68 +++--- src/cutecoin/models/node/__init__.py | 18 +- src/cutecoin/models/node/itemModel.py | 33 +-- src/cutecoin/models/person/__init__.py | 27 ++- src/cutecoin/models/transaction/__init__.py | 33 +-- src/cutecoin/models/transaction/factory.py | 25 ++- .../models/transaction/issuancesListModel.py | 13 +- .../models/transaction/receivedListModel.py | 13 +- .../models/transaction/sentListModel.py | 13 +- src/cutecoin/models/wallet/__init__.py | 36 ++- src/cutecoin/models/wallet/listModel.py | 11 +- 42 files changed, 953 insertions(+), 817 deletions(-) delete mode 100644 res/ui/communityParametersWidget.ui diff --git a/Makefile b/Makefile index 22ff3a68..057c2329 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ RESOURCE_DIR = res/ui COMPILED_DIR = src/cutecoin/gen_resources #UI files to compile -UI_FILES = mainwindow.ui accountConfigurationDialog.ui communityConfigurationDialog.ui communityTabWidget.ui issuanceDialog.ui transferDialog.ui addContactDialog.ui communityParametersWidget.ui +UI_FILES = mainwindow.ui accountConfigurationDialog.ui communityConfigurationDialog.ui communityTabWidget.ui issuanceDialog.ui transferDialog.ui addContactDialog.ui #Qt resource files to compile RESOURCES = diff --git a/res/ui/accountConfigurationDialog.ui b/res/ui/accountConfigurationDialog.ui index 0b1edafa..c7d28bc9 100644 --- a/res/ui/accountConfigurationDialog.ui +++ b/res/ui/accountConfigurationDialog.ui @@ -33,7 +33,7 @@ </widget> </item> <item> - <widget class="QLineEdit" name="edit_accountName"/> + <widget class="QLineEdit" name="edit_account_name"/> </item> </layout> </item> @@ -47,7 +47,7 @@ </widget> </item> <item> - <widget class="QComboBox" name="combo_keysList"/> + <widget class="QComboBox" name="combo_keys_list"/> </item> </layout> </item> @@ -70,14 +70,14 @@ <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> - <widget class="QPushButton" name="button_addCommunity"> + <widget class="QPushButton" name="button_add_community"> <property name="text"> <string>Add a community</string> </property> </widget> </item> <item> - <widget class="QPushButton" name="button_removeCommunity"> + <widget class="QPushButton" name="button_remove_community"> <property name="text"> <string>Remove selected community</string> </property> @@ -89,7 +89,7 @@ </widget> </item> <item> - <widget class="QDialogButtonBox" name="buttonBox"> + <widget class="QDialogButtonBox" name="button_box"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> @@ -103,7 +103,7 @@ <resources/> <connections> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>accepted()</signal> <receiver>AccountConfigurationDialog</receiver> <slot>accept()</slot> @@ -119,7 +119,7 @@ </hints> </connection> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>rejected()</signal> <receiver>AccountConfigurationDialog</receiver> <slot>reject()</slot> @@ -135,10 +135,10 @@ </hints> </connection> <connection> - <sender>button_addCommunity</sender> + <sender>button_add_community</sender> <signal>clicked()</signal> <receiver>AccountConfigurationDialog</receiver> - <slot>openAddCommunityDialog()</slot> + <slot>open_add_community_dialog()</slot> <hints> <hint type="sourcelabel"> <x>109</x> @@ -151,10 +151,10 @@ </hints> </connection> <connection> - <sender>button_removeCommunity</sender> + <sender>button_remove_community</sender> <signal>clicked()</signal> <receiver>AccountConfigurationDialog</receiver> - <slot>actionRemoveCommunity()</slot> + <slot>action_remove_community()</slot> <hints> <hint type="sourcelabel"> <x>290</x> @@ -170,7 +170,7 @@ <sender>list_communities</sender> <signal>doubleClicked(QModelIndex)</signal> <receiver>AccountConfigurationDialog</receiver> - <slot>openEditCommunityDialog(QModelIndex)</slot> + <slot>open_edit_community_dialog(QModelIndex)</slot> <hints> <hint type="sourcelabel"> <x>199</x> @@ -184,9 +184,9 @@ </connection> </connections> <slots> - <slot>openAddCommunityDialog()</slot> - <slot>keyChanged(int)</slot> - <slot>actionRemoveCommunity()</slot> - <slot>openEditCommunityDialog(QModelIndex)</slot> + <slot>open_add_community_dialog()</slot> + <slot>key_changed(int)</slot> + <slot>action_remove_community()</slot> + <slot>open_edit_community_dialog(QModelIndex)</slot> </slots> </ui> diff --git a/res/ui/addContactDialog.ui b/res/ui/addContactDialog.ui index 73524bfa..0a42df89 100644 --- a/res/ui/addContactDialog.ui +++ b/res/ui/addContactDialog.ui @@ -109,7 +109,7 @@ <sender>edit_fingerprint</sender> <signal>textChanged(QString)</signal> <receiver>AddContactDialog</receiver> - <slot>fingerprintEdited()</slot> + <slot>fingerprint_edited()</slot> <hints> <hint type="sourcelabel"> <x>145</x> @@ -125,7 +125,7 @@ <sender>edit_name</sender> <signal>textChanged(QString)</signal> <receiver>AddContactDialog</receiver> - <slot>nameEdited()</slot> + <slot>name_edited()</slot> <hints> <hint type="sourcelabel"> <x>129</x> @@ -139,7 +139,7 @@ </connection> </connections> <slots> - <slot>nameEdited()</slot> - <slot>fingerprintEdited()</slot> + <slot>name_edited()</slot> + <slot>fingerprint_edited()</slot> </slots> </ui> diff --git a/res/ui/communityConfigurationDialog.ui b/res/ui/communityConfigurationDialog.ui index 2d023375..28cdbae6 100644 --- a/res/ui/communityConfigurationDialog.ui +++ b/res/ui/communityConfigurationDialog.ui @@ -24,7 +24,7 @@ </property> <layout class="QVBoxLayout" name="verticalLayout_3"> <item> - <widget class="QTreeView" name="communityView"> + <widget class="QTreeView" name="tree_nodes"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> @@ -33,7 +33,7 @@ <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> - <widget class="QLineEdit" name="serverEdit"> + <widget class="QLineEdit" name="server_edit"> <property name="text"> <string/> </property> @@ -43,7 +43,7 @@ </widget> </item> <item> - <widget class="QSpinBox" name="portBox"> + <widget class="QSpinBox" name="port_box"> <property name="minimum"> <number>1025</number> </property> @@ -56,7 +56,7 @@ </widget> </item> <item> - <widget class="QPushButton" name="addButton"> + <widget class="QPushButton" name="add_button"> <property name="text"> <string>Add</string> </property> @@ -68,7 +68,7 @@ </widget> </item> <item> - <widget class="QDialogButtonBox" name="buttonBox"> + <widget class="QDialogButtonBox" name="button_box"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> @@ -82,7 +82,7 @@ <resources/> <connections> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>accepted()</signal> <receiver>CommunityConfigurationDialog</receiver> <slot>accept()</slot> @@ -98,7 +98,7 @@ </hints> </connection> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>rejected()</signal> <receiver>CommunityConfigurationDialog</receiver> <slot>reject()</slot> @@ -114,10 +114,10 @@ </hints> </connection> <connection> - <sender>addButton</sender> + <sender>add_button</sender> <signal>clicked()</signal> <receiver>CommunityConfigurationDialog</receiver> - <slot>addNode()</slot> + <slot>add_node()</slot> <hints> <hint type="sourcelabel"> <x>337</x> @@ -130,7 +130,7 @@ </hints> </connection> <connection> - <sender>communityView</sender> + <sender>tree_nodes</sender> <signal>customContextMenuRequested(QPoint)</signal> <receiver>CommunityConfigurationDialog</receiver> <slot>showContextMenu(QPoint)</slot> @@ -147,7 +147,7 @@ </connection> </connections> <slots> - <slot>addNode()</slot> + <slot>add_node()</slot> <slot>showContextMenu(QPoint)</slot> </slots> </ui> diff --git a/res/ui/communityParametersWidget.ui b/res/ui/communityParametersWidget.ui deleted file mode 100644 index b183684e..00000000 --- a/res/ui/communityParametersWidget.ui +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>CommunityParametersWidget</class> - <widget class="QWidget" name="CommunityParametersWidget"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>400</width> - <height>300</height> - </rect> - </property> - <property name="windowTitle"> - <string>Form</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout_3"> - <item> - <widget class="QLabel" name="label_2"> - <property name="text"> - <string>Trusted nodes :</string> - </property> - </widget> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <widget class="QListView" name="list_Trusted"/> - </item> - <item> - <layout class="QVBoxLayout" name="verticalLayout"> - <property name="leftMargin"> - <number>6</number> - </property> - <item> - <widget class="QPushButton" name="button_addTrusted"> - <property name="text"> - <string>Add</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="button_removeTrusted"> - <property name="text"> - <string>Remove</string> - </property> - </widget> - </item> - </layout> - </item> - </layout> - </item> - <item> - <widget class="QLabel" name="label"> - <property name="text"> - <string>Favorite transaction nodes :</string> - </property> - </widget> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_2"> - <item> - <widget class="QListView" name="list_Transactions"/> - </item> - <item> - <layout class="QVBoxLayout" name="verticalLayout_2"> - <property name="leftMargin"> - <number>6</number> - </property> - <item> - <widget class="QPushButton" name="button_addTransaction"> - <property name="text"> - <string>Add</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="button_removeTransaction"> - <property name="text"> - <string>Remove</string> - </property> - </widget> - </item> - </layout> - </item> - </layout> - </item> - </layout> - </widget> - <resources/> - <connections/> -</ui> diff --git a/res/ui/communityTabWidget.ui b/res/ui/communityTabWidget.ui index 2c499cdb..a5681fce 100644 --- a/res/ui/communityTabWidget.ui +++ b/res/ui/communityTabWidget.ui @@ -24,7 +24,7 @@ </widget> </item> <item> - <widget class="QListView" name="communityMembersList"/> + <widget class="QListView" name="list_community_members"/> </item> </layout> </item> @@ -38,14 +38,14 @@ </widget> </item> <item> - <widget class="QPushButton" name="issuanceButton"> + <widget class="QPushButton" name="button_issuance"> <property name="text"> <string>Issue money</string> </property> </widget> </item> <item> - <widget class="QListView" name="issuancesList"/> + <widget class="QListView" name="list_issuances"/> </item> </layout> </item> @@ -54,10 +54,10 @@ <resources/> <connections> <connection> - <sender>issuanceButton</sender> + <sender>button_issuance</sender> <signal>clicked()</signal> <receiver>CommunityTabWidget</receiver> - <slot>openIssuanceDialog()</slot> + <slot>open_issuance_dialog()</slot> <hints> <hint type="sourcelabel"> <x>296</x> @@ -71,6 +71,6 @@ </connection> </connections> <slots> - <slot>openIssuanceDialog()</slot> + <slot>open_issuance_dialog()</slot> </slots> </ui> diff --git a/res/ui/issuanceDialog.ui b/res/ui/issuanceDialog.ui index 527942fc..82728b12 100644 --- a/res/ui/issuanceDialog.ui +++ b/res/ui/issuanceDialog.ui @@ -28,7 +28,7 @@ </spacer> </item> <item> - <widget class="QLabel" name="totalLabel"> + <widget class="QLabel" name="label_total"> <property name="text"> <string>Total : </string> </property> @@ -38,7 +38,7 @@ </widget> </item> <item> - <widget class="QDialogButtonBox" name="buttonBox"> + <widget class="QDialogButtonBox" name="button_box"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> @@ -52,7 +52,7 @@ <resources/> <connections> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>accepted()</signal> <receiver>IssuanceDialog</receiver> <slot>accept()</slot> @@ -68,7 +68,7 @@ </hints> </connection> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>rejected()</signal> <receiver>IssuanceDialog</receiver> <slot>reject()</slot> @@ -84,10 +84,10 @@ </hints> </connection> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>accepted()</signal> <receiver>IssuanceDialog</receiver> - <slot>actionIssueCoins()</slot> + <slot>action_issue_coins()</slot> <hints> <hint type="sourcelabel"> <x>199</x> @@ -101,6 +101,6 @@ </connection> </connections> <slots> - <slot>actionIssueCoins()</slot> + <slot>action_issue_coins()</slot> </slots> </ui> diff --git a/res/ui/mainwindow.ui b/res/ui/mainwindow.ui index bec0edc3..dd455633 100644 --- a/res/ui/mainwindow.ui +++ b/res/ui/mainwindow.ui @@ -16,7 +16,7 @@ <widget class="QWidget" name="centralwidget"> <layout class="QVBoxLayout" name="verticalLayout_6"> <item> - <widget class="QLabel" name="accountNameLabel"> + <widget class="QLabel" name="label_account_name"> <property name="text"> <string>Please select an account</string> </property> @@ -32,27 +32,27 @@ </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> - <widget class="QTabWidget" name="accountTabs"> + <widget class="QTabWidget" name="tabs_account"> <property name="enabled"> <bool>false</bool> </property> <property name="currentIndex"> - <number>0</number> + <number>2</number> </property> - <widget class="QWidget" name="walletsTab"> + <widget class="QWidget" name="tab_wallets"> <attribute name="title"> <string>Wallets</string> </attribute> <layout class="QHBoxLayout" name="horizontalLayout"> <item> - <widget class="QListView" name="walletsList"/> + <widget class="QListView" name="list_wallets"/> </item> <item> - <widget class="QListView" name="walletContent"/> + <widget class="QListView" name="list_wallet_content"/> </item> </layout> </widget> - <widget class="QWidget" name="transactionsTab"> + <widget class="QWidget" name="tab_transactions"> <attribute name="title"> <string>Transactions</string> </attribute> @@ -67,7 +67,7 @@ </widget> </item> <item> - <widget class="QListView" name="transactionsSent"/> + <widget class="QListView" name="list_transactions_sent"/> </item> </layout> </item> @@ -81,19 +81,19 @@ </widget> </item> <item> - <widget class="QListView" name="transactionsReceived"/> + <widget class="QListView" name="list_transactions_received"/> </item> </layout> </item> </layout> </widget> - <widget class="QWidget" name="communitiesWidget"> + <widget class="QWidget" name="tab_communities"> <attribute name="title"> <string>Communities</string> </attribute> <layout class="QHBoxLayout" name="horizontalLayout_4"> <item> - <widget class="QTabWidget" name="communitiesTab"> + <widget class="QTabWidget" name="tabs_communities"> <property name="currentIndex"> <number>-1</number> </property> @@ -121,33 +121,33 @@ <property name="title"> <string>Account</string> </property> - <widget class="QMenu" name="menuChange_account"> + <widget class="QMenu" name="menu_change_account"> <property name="title"> <string>Change account</string> </property> </widget> - <addaction name="actionConfigure_parameters"/> - <addaction name="menuChange_account"/> - <addaction name="actionAdd_account"/> + <addaction name="action_configure_parameters"/> + <addaction name="menu_change_account"/> + <addaction name="action_add_account"/> <addaction name="separator"/> - <addaction name="actionSave"/> - <addaction name="actionQuit"/> + <addaction name="action_save"/> + <addaction name="action_quit"/> </widget> <widget class="QMenu" name="menu_contacts"> <property name="title"> <string>Contacts</string> </property> - <widget class="QMenu" name="menu_contactsList"> + <widget class="QMenu" name="menu_contacts_list"> <property name="title"> <string>Contacts</string> </property> <addaction name="separator"/> </widget> <addaction name="separator"/> - <addaction name="actionAdd_a_contact"/> - <addaction name="menu_contactsList"/> + <addaction name="action_add_a_contact"/> + <addaction name="menu_contacts_list"/> </widget> - <widget class="QMenu" name="menuActions"> + <widget class="QMenu" name="menu_actions"> <property name="title"> <string>Actions</string> </property> @@ -155,7 +155,7 @@ </widget> <addaction name="menu_account"/> <addaction name="menu_contacts"/> - <addaction name="menuActions"/> + <addaction name="menu_actions"/> </widget> <widget class="QStatusBar" name="statusbar"/> <action name="actionManage_accounts"> @@ -168,7 +168,7 @@ <string>Configure trustable nodes</string> </property> </action> - <action name="actionAdd_a_contact"> + <action name="action_add_a_contact"> <property name="text"> <string>Add a contact</string> </property> @@ -203,17 +203,17 @@ <string>Remove contact</string> </property> </action> - <action name="actionAdd_account"> + <action name="action_add_account"> <property name="text"> <string>Add account</string> </property> </action> - <action name="actionSave"> + <action name="action_save"> <property name="text"> <string>Save</string> </property> </action> - <action name="actionQuit"> + <action name="action_quit"> <property name="text"> <string>Quit</string> </property> @@ -228,7 +228,7 @@ <string>Transfer money</string> </property> </action> - <action name="actionConfigure_parameters"> + <action name="action_configure_parameters"> <property name="text"> <string>Configure</string> </property> @@ -237,10 +237,10 @@ <resources/> <connections> <connection> - <sender>actionAdd_account</sender> + <sender>action_add_account</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> - <slot>openAddAccountDialog()</slot> + <slot>open_add_account_dialog()</slot> <hints> <hint type="sourcelabel"> <x>-1</x> @@ -253,7 +253,7 @@ </hints> </connection> <connection> - <sender>actionSave</sender> + <sender>action_save</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> <slot>save()</slot> @@ -269,7 +269,7 @@ </hints> </connection> <connection> - <sender>actionQuit</sender> + <sender>action_quit</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> <slot>close()</slot> @@ -288,7 +288,7 @@ <sender>actionTransfer_money</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> - <slot>openTransferMoneyDialog()</slot> + <slot>open_transfer_money_dialog()</slot> <hints> <hint type="sourcelabel"> <x>-1</x> @@ -301,10 +301,10 @@ </hints> </connection> <connection> - <sender>actionAdd_a_contact</sender> + <sender>action_add_a_contact</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> - <slot>openAddContactDialog()</slot> + <slot>open_add_contact_dialog()</slot> <hints> <hint type="sourcelabel"> <x>-1</x> @@ -317,10 +317,10 @@ </hints> </connection> <connection> - <sender>actionConfigure_parameters</sender> + <sender>action_configure_parameters</sender> <signal>triggered()</signal> <receiver>MainWindow</receiver> - <slot>openConfigureAccountDialog()</slot> + <slot>open_configure_account_dialog()</slot> <hints> <hint type="sourcelabel"> <x>-1</x> @@ -333,10 +333,10 @@ </hints> </connection> <connection> - <sender>walletsList</sender> + <sender>list_wallets</sender> <signal>clicked(QModelIndex)</signal> <receiver>MainWindow</receiver> - <slot>refreshWalletContent(QModelIndex)</slot> + <slot>refresh_wallet_content(QModelIndex)</slot> <hints> <hint type="sourcelabel"> <x>137</x> @@ -350,12 +350,12 @@ </connection> </connections> <slots> - <slot>openAddAccountDialog()</slot> + <slot>open_add_account_dialog()</slot> <slot>save()</slot> - <slot>openTransferMoneyDialog()</slot> - <slot>openAddContactDialog()</slot> - <slot>openConfigureAccountDialog()</slot> - <slot>refreshMainWindow()</slot> - <slot>refreshWalletContent(QModelIndex)</slot> + <slot>open_transfer_money_dialog()</slot> + <slot>open_add_contact_dialog()</slot> + <slot>open_configure_account_dialog()</slot> + <slot>refresh_main_window()</slot> + <slot>refresh_wallet_content(QModelIndex)</slot> </slots> </ui> diff --git a/res/ui/transferDialog.ui b/res/ui/transferDialog.ui index 0921653d..a8035cf8 100644 --- a/res/ui/transferDialog.ui +++ b/res/ui/transferDialog.ui @@ -23,7 +23,7 @@ <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> - <widget class="QRadioButton" name="radio_keyFingerprint"> + <widget class="QRadioButton" name="radio_key_fingerprint"> <property name="text"> <string>Recipient fingerprint</string> </property> @@ -33,7 +33,7 @@ </widget> </item> <item> - <widget class="QLineEdit" name="edit_keyFingerprint"> + <widget class="QLineEdit" name="edit_key_fingerprint"> <property name="inputMask"> <string/> </property> @@ -57,7 +57,7 @@ </widget> </item> <item> - <widget class="QComboBox" name="comboBox_contact"> + <widget class="QComboBox" name="combo_contact"> <property name="enabled"> <bool>false</bool> </property> @@ -77,7 +77,7 @@ <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> - <widget class="QRadioButton" name="radio_nodeAddress"> + <widget class="QRadioButton" name="radio_node_address"> <property name="text"> <string>Node</string> </property> @@ -87,7 +87,7 @@ </widget> </item> <item> - <widget class="QLineEdit" name="edit_nodeAddress"> + <widget class="QLineEdit" name="edit_node_address"> <property name="inputMask"> <string/> </property> @@ -121,14 +121,14 @@ <item> <layout class="QHBoxLayout" name="horizontalLayout_4"> <item> - <widget class="QRadioButton" name="radio_trustedNode"> + <widget class="QRadioButton" name="radio_trusted_node"> <property name="text"> <string>Trusted node</string> </property> </widget> </item> <item> - <widget class="QComboBox" name="comboBox_trustedNode"> + <widget class="QComboBox" name="combo_trusted_node"> <property name="enabled"> <bool>false</bool> </property> @@ -156,10 +156,10 @@ <number>6</number> </property> <item> - <widget class="QComboBox" name="comboBox_wallets"/> + <widget class="QComboBox" name="combo_wallets"/> </item> <item> - <widget class="QListView" name="listView_wallet"/> + <widget class="QListView" name="list_wallet"/> </item> </layout> </item> @@ -169,7 +169,7 @@ <number>0</number> </property> <item> - <widget class="QPushButton" name="button_manageCoins"> + <widget class="QPushButton" name="button_manage_coins"> <property name="text"> <string>Manage wallet coins</string> </property> @@ -207,7 +207,7 @@ </widget> </item> <item> - <widget class="QListView" name="listView_coinsSent"> + <widget class="QListView" name="list_coins_sent"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Preferred"> <horstretch>0</horstretch> @@ -251,7 +251,7 @@ </widget> </item> <item> - <widget class="QDialogButtonBox" name="buttonBox"> + <widget class="QDialogButtonBox" name="button_box"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> @@ -265,7 +265,7 @@ <resources/> <connections> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>accepted()</signal> <receiver>TransferMoneyDialog</receiver> <slot>accept()</slot> @@ -281,7 +281,7 @@ </hints> </connection> <connection> - <sender>buttonBox</sender> + <sender>button_box</sender> <signal>rejected()</signal> <receiver>TransferMoneyDialog</receiver> <slot>reject()</slot> @@ -300,7 +300,7 @@ <sender>button_add</sender> <signal>clicked()</signal> <receiver>TransferMoneyDialog</receiver> - <slot>addCoinsToTransfer()</slot> + <slot>add_coins_to_transfer()</slot> <hints> <hint type="sourcelabel"> <x>201</x> @@ -316,7 +316,7 @@ <sender>button_remove</sender> <signal>clicked()</signal> <receiver>TransferMoneyDialog</receiver> - <slot>removeCoinsFromTransfer()</slot> + <slot>remove_coins_from_transfer()</slot> <hints> <hint type="sourcelabel"> <x>201</x> @@ -329,10 +329,10 @@ </hints> </connection> <connection> - <sender>button_manageCoins</sender> + <sender>button_manage_coins</sender> <signal>clicked()</signal> <receiver>TransferMoneyDialog</receiver> - <slot>openManageWalletCoins()</slot> + <slot>open_manage_wallet_coins()</slot> <hints> <hint type="sourcelabel"> <x>201</x> @@ -345,10 +345,10 @@ </hints> </connection> <connection> - <sender>comboBox_wallets</sender> + <sender>combo_wallets</sender> <signal>currentIndexChanged(int)</signal> <receiver>TransferMoneyDialog</receiver> - <slot>changeDisplayedWallet()</slot> + <slot>change_displayed_wallet(int)</slot> <hints> <hint type="sourcelabel"> <x>82</x> @@ -361,10 +361,10 @@ </hints> </connection> <connection> - <sender>radio_keyFingerprint</sender> + <sender>radio_key_fingerprint</sender> <signal>toggled(bool)</signal> <receiver>TransferMoneyDialog</receiver> - <slot>recipientModeChanged(bool)</slot> + <slot>recipient_mode_changed(bool)</slot> <hints> <hint type="sourcelabel"> <x>87</x> @@ -377,10 +377,10 @@ </hints> </connection> <connection> - <sender>radio_nodeAddress</sender> + <sender>radio_node_address</sender> <signal>toggled(bool)</signal> <receiver>TransferMoneyDialog</receiver> - <slot>transferModeChanged(bool)</slot> + <slot>transfer_mode_changed(bool)</slot> <hints> <hint type="sourcelabel"> <x>70</x> @@ -394,11 +394,11 @@ </connection> </connections> <slots> - <slot>addCoinsToTransfer()</slot> - <slot>removeCoinsFromTransfer()</slot> - <slot>openManageWalletCoins()</slot> - <slot>changeDisplayedWallet(int)</slot> - <slot>transferModeChanged(bool)</slot> - <slot>recipientModeChanged(bool)</slot> + <slot>add_coins_to_transfer()</slot> + <slot>remove_coins_from_transfer()</slot> + <slot>open_manage_wallet_coins()</slot> + <slot>change_displayed_wallet(int)</slot> + <slot>transfer_mode_changed(bool)</slot> + <slot>recipient_mode_changed(bool)</slot> </slots> </ui> diff --git a/src/cutecoin/__init__.py b/src/cutecoin/__init__.py index baa65356..51bcbecf 100644 --- a/src/cutecoin/__init__.py +++ b/src/cutecoin/__init__.py @@ -8,10 +8,12 @@ from PyQt5.QtWidgets import QApplication, QDialog from cutecoin.gui.mainWindow import MainWindow from cutecoin.core import Core +#TODO: Rename all functions to match python style + if __name__ == '__main__': app = QApplication(sys.argv) core = Core(sys.argv) window = MainWindow(core) window.show() sys.exit(app.exec_()) - pass \ No newline at end of file + pass diff --git a/src/cutecoin/core/__init__.py b/src/cutecoin/core/__init__.py index e4357813..15065a70 100644 --- a/src/cutecoin/core/__init__.py +++ b/src/cutecoin/core/__init__.py @@ -14,45 +14,46 @@ from cutecoin.models.account import Account class Core(object): + ''' Managing core application datas : Accounts list and general configuration ''' + def __init__(self, argv): ''' Constructor ''' self.accounts = [] - self.currentAccount = None - config.parseArguments(argv) + self.current_account = None + config.parse_arguments(argv) self.load() - def getAccount(self, name): + def get_account(self, name): for a in self.accounts: logging.debug('Name : ' + a.name + '/' + name) if name == a.name: return a - def addAccount(self, account): + def add_account(self, account): for a in self.accounts: if a.keyId == account.keyId: - raise KeyAlreadyUsed(account, account.keyId, a) + raise KeyAlreadyUsed(account, account.keyid, a) self.accounts.append(account) - self.currentAccount = account + self.current_account = account - def delAccount(self, account): + def del_account(self, account): self.accounts.remove(account) - def load(self): if not os.path.exists(config.parameters['home']): logging.info("Creating home directory") os.makedirs((config.parameters['home'])) - if (os.path.exists(config.parameters['data']) \ - and os.path.isfile(config.parameters['data'])): - json_data=open(config.parameters['data'], 'r') + if (os.path.exists(config.parameters['data']) + and os.path.isfile(config.parameters['data'])): + json_data = open(config.parameters['data'], 'r') data = json.load(json_data) json_data.close() @@ -61,16 +62,14 @@ class Core(object): def save(self): with open(config.parameters['data'], 'w') as outfile: - json.dump(self.jsonify(), outfile, indent = 4, sort_keys=True) + json.dump(self.jsonify(), outfile, indent=4, sort_keys=True) - - def jsonifyAccounts(self): + def jsonify_accounts(self): data = [] for account in self.accounts: data.append(account.jsonify()) return data def jsonify(self): - data = {'localAccounts' : self.jsonifyAccounts()} + data = {'localAccounts': self.jsonify_accounts()} return data - diff --git a/src/cutecoin/core/config.py b/src/cutecoin/core/config.py index c1e4595c..4055be75 100644 --- a/src/cutecoin/core/config.py +++ b/src/cutecoin/core/config.py @@ -13,10 +13,11 @@ import ucoinpy as ucoin home = os.path.expanduser("~") -parameters = { 'home' : home + '/.config/cutecoin/', - 'data' : home + '/.config/cutecoin/' 'data'} +parameters = {'home': home + '/.config/cutecoin/', + 'data': home + '/.config/cutecoin/' 'data'} -def parseArguments(argv): + +def parse_arguments(argv): parser = OptionParser() parser.add_option("-v", "--verbose", @@ -24,27 +25,29 @@ def parseArguments(argv): help="Print INFO messages to stdout") parser.add_option("-d", "--debug", - action="store_true", dest="debug", default=False, - help="Print DEBUG messages to stdout") - + action="store_true", dest="debug", default=False, + help="Print DEBUG messages to stdout") parser.add_option("--home", dest="home", default=parameters['home'], - help="Set another home for cutecoin.") + help="Set another home for cutecoin.") (options, args) = parser.parse_args(argv) - if options.debug == True: - logging.basicConfig(format='%(levelname)s:%(module)s:%(message)s', level=logging.DEBUG) - elif options.verbose == True: - logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) + if options.debug: + logging.basicConfig( + format='%(levelname)s:%(module)s:%(message)s', + level=logging.DEBUG) + elif options.verbose: + logging.basicConfig( + format='%(levelname)s:%(message)s', + level=logging.INFO) else: logging.getLogger().propagate = False - ucoin.settings['gpg'] = gnupg.GPG() logger = logging.getLogger("gnupg") logger.setLevel(logging.INFO) parameters['home'] = options.home - pass \ No newline at end of file + pass diff --git a/src/cutecoin/core/exceptions.py b/src/cutecoin/core/exceptions.py index de9ce941..5de93dba 100644 --- a/src/cutecoin/core/exceptions.py +++ b/src/cutecoin/core/exceptions.py @@ -4,7 +4,9 @@ Created on 9 févr. 2014 @author: inso ''' + class Error(Exception): + def __init__(self, message): ''' Constructor @@ -13,9 +15,11 @@ class Error(Exception): class NotMemberOfCommunityError(Error): + ''' Exception raised when adding a community the account is not a member of ''' + def __init__(self, account, community): ''' Constructor @@ -23,29 +27,61 @@ class NotMemberOfCommunityError(Error): super(NotMemberOfCommunityError, self) \ .__init__(account + " is not a member of " + community) + class PersonNotFoundError(Error): + ''' - Exception raised when looking for a person in a community who isnt present in key list + Exception raised when looking for a person in a community + who isnt present in key list ''' - def __init__(self, classType, value, community): + + def __init__(self, class_type, value, community): ''' Constructor ''' - super(PersonNotFoundError, self) \ - .__init("Person looked by " + classType \ - + " in " + type + " not present in community " + community.name) + super( + PersonNotFoundError, + self) .__init( + "Person looked by " + + class_type + + " in " + + type + + " not present in community " + + community.name) -class KeyAlreadyUsed(Error): +class CommunityNotFoundError(Error): + ''' - Exception raised trying to add an account using a key already used for another account. + Exception raised when looking for community in an account list ''' - def __init__(self, newAccount, keyId, foundAccount): + + def __init__(self, keyid, amendmentid): ''' Constructor ''' - super(KeyAlreadyUsed, self) \ - .__init__("Cannot add account " + newAccount.name + " : " \ - " the pgpKey " + keyId + " is already used by " + foundAccount.name) + super(CommunityNotFoundError, self) \ + .__init("Community with amendment " + amendmentid + + " not found in account " + keyid) + +class KeyAlreadyUsed(Error): + + ''' + Exception raised trying to add an account using a key already used for another account. + ''' + def __init__(self, new_account, keyid, found_account): + ''' + Constructor + ''' + super( + KeyAlreadyUsed, + self) .__init__( + "Cannot add account " + + new_account.name + + " : " + " the pgpKey " + + keyid + + " is already used by " + + found_account.name) diff --git a/src/cutecoin/gui/addContactDialog.py b/src/cutecoin/gui/addContactDialog.py index 351cd26d..4d08264d 100644 --- a/src/cutecoin/gui/addContactDialog.py +++ b/src/cutecoin/gui/addContactDialog.py @@ -11,10 +11,13 @@ from cutecoin.models.person import Person from cutecoin.gen_resources.addContactDialog_uic import Ui_AddContactDialog + class AddContactDialog(QDialog, Ui_AddContactDialog): + ''' classdocs ''' + def __init__(self, account, parent=None): ''' Constructor @@ -22,22 +25,23 @@ class AddContactDialog(QDialog, Ui_AddContactDialog): super(AddContactDialog, self).__init__() self.setupUi(self) self.account = account - self.mainWindow = parent - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) - + self.main_window = parent + self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) def accept(self): name = self.edit_name.text() fingerprint = self.edit_fingerprint.text() email = self.edit_email.text() self.account.addContact(Person(name, fingerprint, email)) - self.mainWindow.menu_contactsList.addAction(name) + self.main_window.menu_contactsList.addAction(name) self.close() - def nameEdited(self, newName): - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( len(newName) > 0 ) + def name_edited(self, new_name): + name_ok = len(new_name) > 0 + self.button_box.button(QDialogButtonBox.Ok).setEnabled(name_ok) - def fingerprintEdited(self, newFingerprint): + def fingerprint_edited(self, new_fingerprint): pattern = re.compile("([A-Z]|[0-9])+") - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( pattern.match(newFingerprint) is not None ) - + self.button_box.button( + QDialogButtonBox.Ok).setEnabled( + pattern.match(new_fingerprint) is not None) diff --git a/src/cutecoin/gui/communityTabWidget.py b/src/cutecoin/gui/communityTabWidget.py index 3925f9ea..1e26c34e 100644 --- a/src/cutecoin/gui/communityTabWidget.py +++ b/src/cutecoin/gui/communityTabWidget.py @@ -11,10 +11,13 @@ from cutecoin.models.transaction.issuancesListModel import IssuancesListModel from cutecoin.gui.issuanceDialog import IssuanceDialog from cutecoin.gen_resources.communityTabWidget_uic import Ui_CommunityTabWidget + class CommunityTabWidget(QWidget, Ui_CommunityTabWidget): + ''' classdocs ''' + def __init__(self, account, community): ''' Constructor @@ -23,16 +26,15 @@ class CommunityTabWidget(QWidget, Ui_CommunityTabWidget): self.setupUi(self) self.community = community self.account = account - self.communityMembersList.setModel(MembersListModel(community)) - self.issuancesList.setModel(IssuancesListModel(account, community)) - if self.account.issuedLastDividend(community): - self.issuanceButton.setEnabled(False) + #TODO: Rename to list: + self.list_community_members.setModel(MembersListModel(community)) + self.list_issuances.setModel(IssuancesListModel(account, community)) + if self.account.issued_last_dividend(community): + self.button_issuance.setEnabled(False) else: - self.issuanceButton.setEnabled(True) + self.button_issuance.setEnabled(True) - def openIssuanceDialog(self): + def open_issuance_dialog(self): logging.debug("Display dialog") - issuanceDialog = IssuanceDialog(self.account, self.community) - issuanceDialog.exec_() - - + dialog = IssuanceDialog(self.account, self.community) + dialog.exec_() diff --git a/src/cutecoin/gui/configureAccountDialog.py b/src/cutecoin/gui/configureAccountDialog.py index 93261706..7304b9e8 100644 --- a/src/cutecoin/gui/configureAccountDialog.py +++ b/src/cutecoin/gui/configureAccountDialog.py @@ -14,7 +14,6 @@ from cutecoin.models.node import Node from PyQt5.QtWidgets import QDialog, QErrorMessage, QInputDialog import gnupg -import re class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog): @@ -22,7 +21,6 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog): classdocs ''' - def __init__(self, core, account): ''' Constructor @@ -36,75 +34,80 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog): self.setWindowTitle("New account") else: self.setWindowTitle("Configure " + self.account.name) - self.combo_keysList.setEnabled(False) + self.combo_keys_list.setEnabled(False) - self.setData() + self.set_data() - def setData(self): + def set_data(self): gpg = gnupg.GPG() - self.combo_keysList.clear() - availableKeys = gpg.list_keys(True) + self.combo_keys_list.clear() + available_keys = gpg.list_keys(True) if self.account is None: - self.account = Account.create(availableKeys[0]['keyid'], "", Communities()) - self.combo_keysList.currentIndexChanged[int].connect(self.keyChanged) - - for index, key in enumerate(availableKeys): - self.combo_keysList.addItem(key['uids'][0]) - if (key['keyid']) == self.account.keyId: - self.combo_keysList.setCurrentIndex(index) - + self.account = Account.create( + available_keys[0]['keyid'], + "", + Communities()) + self.combo_keys_list.currentIndexChanged[ + int].connect(self.keyChanged) + + for index, key in enumerate(available_keys): + self.combo_keys_list.addItem(key['uids'][0]) + if (key['keyid']) == self.account.keyid: + self.combo_keys_list.setCurrentIndex(index) self.list_communities.setModel(CommunitiesListModel(self.account)) - self.edit_accountName.setText(self.account.name) + self.edit_account_name.setText(self.account.name) - def openAddCommunityDialog(self): + def open_add_community_dialog(self): - text, ok = QInputDialog.getText(self, 'Add a community', - 'Enter a main node address you trust :') + text, ok = QInputDialog.getText( + self, 'Add a community', 'Enter a main node address you trust :') if ok: server, port = text.split(':')[0], int(text.split(':')[1]) - dialog = ConfigureCommunityDialog(self.account, None, Node(server, port)) - dialog.buttonBox.accepted.connect(self.actionAddCommunity) + dialog = ConfigureCommunityDialog( + self.account, + None, + Node( + server, + port)) + dialog.button_box.accepted.connect(self.actionAddCommunity) dialog.exec_() - def actionAddCommunity(self): - self.combo_keysList.setEnabled(False) - self.combo_keysList.disconnect() + def action_add_community(self): + self.combo_keys_list.setEnabled(False) + self.combo_keys_list.disconnect() self.list_communities.setModel(CommunitiesListModel(self.account)) - def actionRemoveCommunity(self): + def action_remove_community(self): for index in self.list_communities.selectedIndexes(): - community = self.account.communities.communitiesList[ index.row() ] + community = self.account.communities.communitiesList[index.row()] self.account.wallets.removeAllWalletsOf(community) self.account.communities.communitiesList.pop(index.row()) - self.list_communities.setModel( CommunitiesListModel(self.account )) + self.list_communities.setModel(CommunitiesListModel(self.account)) - def actionEditCommunity(self): + def action_edit_community(self): self.list_communities.setModel(CommunitiesListModel(self.account)) - def openEditCommunityDialog(self, index): - community = self.account.communities.communitiesList[index.row()] + def open_edit_community_dialog(self, index): + community = self.account.communities.communities_list[index.row()] dialog = ConfigureCommunityDialog(self.account, community) - dialog.buttonBox.accepted.connect(self.actionEditCommunity) - dialog.setAccount(self.account) + dialog.button_box.accepted.connect(self.action_edit_community) dialog.exec_() - def keyChanged(self, keyIndex): + def key_changed(self, key_index): gpg = gnupg.GPG() - availableKeys = gpg.list_keys(True) - self.account.keyId = availableKeys[keyIndex]['keyid'] + available_keys = gpg.list_keys(True) + self.account.keyid = available_keys[key_index]['keyid'] def accept(self): if self.account not in self.core.accounts: - self.account.name = self.edit_accountName.text() + self.account.name = self.edit_account_name.text() try: - self.core.addAccount(self.account) + self.core.add_account(self.account) except KeyAlreadyUsed as e: QErrorMessage(self).showMessage(e.message) self.close() - - diff --git a/src/cutecoin/gui/configureCommunityDialog.py b/src/cutecoin/gui/configureCommunityDialog.py index 14f5a38e..7aaa6e1e 100644 --- a/src/cutecoin/gui/configureCommunityDialog.py +++ b/src/cutecoin/gui/configureCommunityDialog.py @@ -3,19 +3,21 @@ Created on 8 mars 2014 @author: inso ''' +import logging from cutecoin.gen_resources.communityConfigurationDialog_uic import Ui_CommunityConfigurationDialog -from PyQt5.QtWidgets import QDialog, QErrorMessage, QMenu +from PyQt5.QtWidgets import QDialog, QErrorMessage, QMenu, QMessageBox from cutecoin.models.community.treeModel import CommunityTreeModel from cutecoin.models.node import Node from cutecoin.core.exceptions import NotMemberOfCommunityError + class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog): + ''' classdocs ''' - - def __init__(self, account, community, defaultNode=None): + def __init__(self, account, community, default_node=None): ''' Constructor ''' @@ -26,28 +28,39 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog): if self.community is None: self.setWindowTitle("Add a community") try: - defaultNode.trust = True - defaultNode.hoster = True - self.community = self.account.communities.addCommunity(defaultNode, self.account.keyFingerprint()) - self.account.wallets.addWallet(self.community) - self.communityView.setModel( CommunityTreeModel(self.community) ) - #TODO: Ask for THT pull + default_node.trust = True + default_node.hoster = True + self.community = self.account.communities.add_community( + default_node, + self.account.key_fingerprint()) + self.account.wallets.add_wallet(self.community) + self.community_view.set_model(CommunityTreeModel(self.community)) + # TODO: Ask for THT pull + msg_box = QMessageBox() + msg_box.setText("Add a community") + msg_box.setInformativeText( + "Would you like to existing THT from this community ?") + msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) + msg_box.exec_() + if msg_box.clickedButton() == QMessageBox.Yes: + self.account.pull_tht(self.community) except NotMemberOfCommunityError as e: QErrorMessage(self).showMessage(e.message) else: - self.setWindowTitle("Configure community " + self.community.currency) - #TODO: Ask for THT push - self.communityView.setModel( CommunityTreeModel(self.community)) + self.setWindowTitle( + "Configure community " + + self.community.currency) + self.tree_nodes.setModel(CommunityTreeModel(self.community)) - def addNode(self): + def add_node(self): ''' Add node slot ''' - server = self.serverEdit.text() - port = self.portBox.value() + server = self.edit_server.text() + port = self.box_port.value() if self.community is not None: self.community.nodes.append(Node(server, port, trust=True)) - self.communityView.setModel( CommunityTreeModel(self.community )) + self.tree_nodes.setModel(CommunityTreeModel(self.community)) def showContextMenu(self, point): menu = QMenu() @@ -55,18 +68,22 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog): if self.community is not None: if len(self.community.nodes) == 1: action.setEnabled(False) - menu.exec_(self.communityView.mapToGlobal(point)) + menu.exec_(self.tree_nodes.mapToGlobal(point)) - def removeNode(self): - for index in self.communityView.selectedIndexes(): + def remove_node(self): + for index in self.community_view.selectedIndexes(): self.community.nodes.pop(index.row()) - self.communityView.setModel( CommunityTreeModel(self.community )) + self.tree_nodes.setModel(CommunityTreeModel(self.community)) def accept(self): - #TODO: Ask for THT push - self.close() - - - + reply = QMessageBox.question( + self, + "Trusts and hosters changed", + "Would you like to push THT to the community ?", + QMessageBox.Yes | QMessageBox.No) + if reply == QMessageBox.Yes: + logging.debug("Yes clicked") + self.account.push_tht(self.community) + self.close() diff --git a/src/cutecoin/gui/issuanceDialog.py b/src/cutecoin/gui/issuanceDialog.py index e3d05705..31d41f8e 100644 --- a/src/cutecoin/gui/issuanceDialog.py +++ b/src/cutecoin/gui/issuanceDialog.py @@ -13,12 +13,13 @@ from cutecoin.models.coin import Coin from cutecoin.gen_resources.issuanceDialog_uic import Ui_IssuanceDialog + class IssuanceDialog(QDialog, Ui_IssuanceDialog): + ''' classdocs ''' - def __init__(self, issuer, community): ''' Constructor @@ -28,23 +29,24 @@ class IssuanceDialog(QDialog, Ui_IssuanceDialog): self.issuer = issuer self.community = community self.dividend = self.community.dividend() - self.coinMinimalPower = self.community.coinMinimalPower() - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) + self.coin_minimal_power = self.community.coin_minimal_power() + self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) self.sliders = [] - self.slidersLabels = [] - maxCoinPower = 1 - nMax = 0 - # We look for the power of 10 which is directly higher than the dividend - while maxCoinPower < self.dividend: - maxCoinPower = pow(10, nMax) - nMax += 1 + self.sliders_labels = [] + max_coin_power = 1 + nmax = 0 + # We look for the power of 10 which is directly higher than the + # dividend + while max_coin_power < self.dividend: + max_coin_power = pow(10, nmax) + nmax += 1 # N max is the power just before the one we found - logging.debug("Pow max : " + str(nMax)) + logging.debug("Pow max : " + str(nmax)) - for i in range(self.coinMinimalPower, nMax): + for i in range(self.coinMinimalPower, nmax): self.generateSliderFrame(i) def generateSliderFrame(self, n): @@ -57,41 +59,36 @@ class IssuanceDialog(QDialog, Ui_IssuanceDialog): slider = QSlider(Qt.Horizontal, frame) slider.setMinimum(0) slider.setMaximum(9) - slider.valueChanged.connect(self.refreshTotal) + slider.valueChanged.connect(self.refresh_total) frame.layout().addWidget(slider) label.setText("0 coins of " + str(pow(10, n))) - - self.slidersLabels.append(label) + self.sliders_labels.append(label) self.sliders.append(slider) self.layout().insertWidget(n, frame) - def refreshTotal(self): + def refresh_total(self): n = 0 total = 0 for slider in self.sliders: - self.slidersLabels[n].setText(str(slider.value()) + " coins of " + str(pow(10, n))) - self.totalLabel.setText("Total : " + str(total)) - total += slider.value()*pow(10, n) + self.sliders_labels[n].setText( + str(slider.value()) + " coins of " + str(pow(10, n))) + self.total_label.setText("Total : " + str(total)) + total += slider.value() * pow(10, n) n += 1 - self.totalLabel.setText("Total : " + str(total)) + self.total_label.setText("Total : " + str(total)) if total != self.dividend: - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) + self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) else: - self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True) + self.button_box.button(QDialogButtonBox.Ok).setEnabled(True) - def actionIssueCoins(self): + def action_issue_coins(self): coins = [] n = 0 for slider in self.sliders: - coins.append(str(slider.value())+","+str(n)) + coins.append(str(slider.value()) + "," + str(n)) n += 1 - self.issuer.issueDividend(self.community, coins) - - - - - + self.issuer.issue_dividend(self.community, coins) diff --git a/src/cutecoin/gui/mainWindow.py b/src/cutecoin/gui/mainWindow.py index bfcb26e9..a8a68ad2 100644 --- a/src/cutecoin/gui/mainWindow.py +++ b/src/cutecoin/gui/mainWindow.py @@ -17,12 +17,13 @@ from cutecoin.models.transaction.receivedListModel import ReceivedListModel import logging + class MainWindow(QMainWindow, Ui_MainWindow): + ''' classdocs ''' - def __init__(self, core): ''' Constructor @@ -31,31 +32,34 @@ class MainWindow(QMainWindow, Ui_MainWindow): super(MainWindow, self).__init__() self.setupUi(self) self.core = core - self.refreshMainWindow() + self.refresh() - def openAddAccountDialog(self): + def open_add_account_dialog(self): dialog = ConfigureAccountDialog(self.core, None) - dialog.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.refreshMainWindow) + dialog.button_box.button( + QDialogButtonBox.Ok).clicked.connect( + self.refreshMainWindow) dialog.exec_() - def save(self): self.core.save() - def actionChangeAccount(self, accountName): - self.core.currentAccount = self.core.getAccount(accountName) - logging.info('Changing account to ' + self.core.currentAccount.name) - self.refreshMainWindow() + def action_change_account(self, account_name): + self.core.current_account = self.core.get_account(account_name) + logging.info('Changing account to ' + self.core.current_account.name) + self.refresh() - def openTransferMoneyDialog(self): - TransferMoneyDialog(self.core.currentAccount).exec_() + def open_transfer_money_dialog(self): + TransferMoneyDialog(self.core.current_account).exec_() - def openAddContactDialog(self): - AddContactDialog(self.core.currentAccount, self).exec_() + def open_add_contact_dialog(self): + AddContactDialog(self.core.current_account, self).exec_() - def openConfigureAccountDialog(self): - dialog = ConfigureAccountDialog(self.core, self.core.currentAccount) - dialog.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.refreshMainWindow) + def open_configure_account_dialog(self): + dialog = ConfigureAccountDialog(self.core, self.core.current_account) + dialog.button_box.button( + QDialogButtonBox.Ok).clicked.connect( + self.refresh) dialog.exec_() ''' @@ -63,41 +67,51 @@ class MainWindow(QMainWindow, Ui_MainWindow): When the selected account changes, all the widgets in the window have to be refreshed ''' - def refreshMainWindow(self): - self.menuChange_account.clear() - signalMapper = QSignalMapper(self) + + def refresh(self): + self.menu_change_account.clear() + signal_mapper = QSignalMapper(self) for account in self.core.accounts: action = QAction(account.name, self) - self.menuChange_account.addAction(action) - signalMapper.setMapping(action, account.name) - action.triggered.connect(signalMapper.map) - signalMapper.mapped[str].connect(self.actionChangeAccount) + self.menu_change_account.addAction(action) + signal_mapper.setMapping(action, account.name) + action.triggered.connect(signal_mapper.map) + signal_mapper.mapped[str].connect(self.action_change_account) - if self.core.currentAccount == None: - self.accountTabs.setEnabled(False) + if self.core.current_account is None: + self.tabs_account.setEnabled(False) else: - self.accountTabs.setEnabled(True) - self.accountNameLabel.setText("Current account : " + self.core.currentAccount.name) - self.walletsList.setModel(WalletsListModel(self.core.currentAccount)) - - self.communitiesTab.clear() - for community in self.core.currentAccount.communities.communitiesList: - communityTab = CommunityTabWidget(self.core.currentAccount, community) - self.communitiesTab.addTab(communityTab, community.name()) - - self.menu_contactsList.clear() - for contact in self.core.currentAccount.contacts: - self.menu_contactsList.addAction(contact.name) - - self.transactionsSent.setModel(SentListModel(self.core.currentAccount)) - self.transactionsReceived.setModel(ReceivedListModel(self.core.currentAccount)) - - - def refreshWalletContent(self, index): + self.tabs_account.setEnabled(True) + self.label_account_name.setText( + "Current account : " + + self.core.current_account.name) + self.list_wallets.setModel( + WalletsListModel( + self.core.current_account)) + + self.tabs_communities.clear() + for community in self.core.current_account.communities.communities_list: + tab_community = CommunityTabWidget( + self.core.current_account, + community) + self.tabs_communities.addTab(tab_community, community.name()) + + self.menu_contacts_list.clear() + for contact in self.core.current_account.contacts: + self.menu_contacts_list.addAction(contact.name) + + self.list_transactions_sent.setModel( + SentListModel( + self.core.current_account)) + self.list_transactions_received.setModel( + ReceivedListModel( + self.core.current_account)) + + def refresh_wallet_content(self, index): if index.isValid(): - currentWallet = self.core.currentAccount.wallets.walletsList[index.row()] - self.walletContent.setModel(WalletListModel(currentWallet)) + current_wallet = self.core.current_account.wallets.wallets_list[ + index.row()] + self.list_wallet_content.setModel(WalletListModel(current_wallet)) else: - self.walletContent.setModel(WalletListModel([])) - + self.list_wallet_content.setModel(WalletListModel([])) diff --git a/src/cutecoin/gui/transferMoneyDialog.py b/src/cutecoin/gui/transferMoneyDialog.py index 3ad80f97..4b033a2e 100644 --- a/src/cutecoin/gui/transferMoneyDialog.py +++ b/src/cutecoin/gui/transferMoneyDialog.py @@ -6,7 +6,7 @@ Created on 2 févr. 2014 import logging from math import pow -from PyQt5.QtWidgets import QDialog,QFrame, QSlider, QLabel, QDialogButtonBox, QErrorMessage +from PyQt5.QtWidgets import QDialog, QFrame, QSlider, QLabel, QDialogButtonBox, QErrorMessage from PyQt5.QtCore import Qt, QSignalMapper @@ -17,10 +17,13 @@ from cutecoin.models.coin.listModel import CoinsListModel from cutecoin.gen_resources.transferDialog_uic import Ui_TransferMoneyDialog + class TransferMoneyDialog(QDialog, Ui_TransferMoneyDialog): + ''' classdocs ''' + def __init__(self, sender): ''' Constructor @@ -28,84 +31,82 @@ class TransferMoneyDialog(QDialog, Ui_TransferMoneyDialog): super(TransferMoneyDialog, self).__init__() self.setupUi(self) self.sender = sender - for wallet in sender.wallets.walletsList: - self.comboBox_wallets.addItem(wallet.getText()) + for wallet in sender.wallets.wallets_list: + self.combo_wallets.addItem(wallet.getText()) for contact in sender.contacts: - self.comboBox_contact.addItem(contact.name) + self.combo_contact.addItem(contact.name) - self.refreshTransaction(sender.wallets.walletsList[0]) + self.refresh_transaction(sender.wallets.wallets_list[0]) - - def removeCoinsFromTransfer(self): - selection = self.listView_coinsSent.selectedIndexes() - walletCoins = self.listView_wallet.model().coins - sentCoins = self.listView_coinsSent.model().coins - newWallet = sentCoins + def remove_coins_from_transfer(self): + selection = self.list_coins_sent.selectedIndexes() + wallet_coins = self.list_wallet.model().coins + sent_coins = self.list_coins_sent.model().coins + new_wallet = sent_coins for selected in selection: - coin = sentCoins[selected.row()] - sentCoins.remove(coin) - walletCoins.append(coin) - self.listView_wallet.setModel(CoinsListModel(walletCoins)) - self.listView_coinsSent.setModel(CoinsListModel(newWallet)) - - def addCoinsToTransfer(self): - selection = self.listView_wallet.selectedIndexes() - walletCoins = self.listView_wallet.model().coins - sentCoins = self.listView_coinsSent.model().coins - newWallet = walletCoins + coin = sent_coins[selected.row()] + sent_coins.remove(coin) + wallet_coins.append(coin) + self.list_wallet.setModel(CoinsListModel(wallet_coins)) + self.list_coins_sent.setModel(CoinsListModel(new_wallet)) + + def add_coins_to_transfer(self): + selection = self.list_wallet.selectedIndexes() + wallet_coins = self.list_wallet.model().coins + sent_coins = self.list_coins_sent.model().coins + new_wallet = wallet_coins for selected in selection: - coin = walletCoins[selected.row()] - newWallet.remove(coin) - sentCoins.append(coin) - self.listView_wallet.setModel(CoinsListModel(newWallet)) - self.listView_coinsSent.setModel(CoinsListModel(sentCoins)) + coin = wallet_coins[selected.row()] + new_wallet.remove(coin) + sent_coins.append(coin) + self.list_wallet.setModel(CoinsListModel(new_wallet)) + self.list_coins_sent.setModel(CoinsListModel(sent_coins)) - def openManageWalletCoins(self): + def open_manage_wallet_coins(self): pass def accept(self): - sentCoins = self.listView_coinsSent.model().toList() + sent_coins = self.list_coins_sent.model().toList() recipient = None - if self.radio_keyFingerprint.isChecked(): - recipient = Person("", self.edit_keyFingerprint.text(), "") + if self.radio_key_fingerprint.isChecked(): + recipient = Person("", self.edit_key_fingerprint.text(), "") else: - recipient = self.sender.contacts[self.comboBox_contact.currentIndex()] + recipient = self.sender.contacts[ + self.combo_contact.currentIndex()] - if self.radio_nodeAddress.isChecked(): - node = Node(self.edit_nodeAddress.text(), int(self.edit_port.text())) + if self.radio_node_address.isChecked(): + node = Node( + self.edit_node_address.text(), int( + self.edit_port.text())) else: - #TODO: Manage trusted nodes - node = Node(self.edit_nodeAddress.text(), int(self.edit_port.text())) + # TODO: Manage trusted nodes + node = Node( + self.edit_node_address.text(), int( + self.edit_port.text())) message = self.edit_message.text() - #TODO: Transfer money, and validate the window if no error happened - if self.sender.transferCoins(node, recipient, sentCoins, message): + # TODO: Transfer money, and validate the window if no error happened + if self.sender.transfer_coins(node, recipient, sent_coins, message): self.close() else: QErrorMessage(self).showMessage("Cannot transfer coins.") - def changeDisplayedWallet(self, index): - wallet = self.sender.wallets.walletsList[index] - self.refreshTransaction(wallet) - - def refreshTransaction(self, wallet): - coinsSentModel = CoinsListModel([]) - self.listView_coinsSent.setModel(coinsSentModel) - walletCoinsModel = CoinsListModel(list(wallet.coins)) - self.listView_wallet.setModel(walletCoinsModel) - - def recipientModeChanged(self, fingerprintToggled): - self.edit_keyFingerprint.setEnabled(fingerprintToggled) - self.comboBox_contact.setEnabled(not fingerprintToggled) - - def transferModeChanged(self, nodeAddressToggled): - self.edit_nodeAddress.setEnabled(nodeAddressToggled) - self.comboBox_trustedNode.setEnabled(not nodeAddressToggled) - - - + def change_displayed_wallet(self, index): + wallet = self.sender.wallets.wallets_list[index] + self.refresh_transaction(wallet) + def refresh_transaction(self, wallet): + coins_sent_model = CoinsListModel([]) + self.list_coins_sent.setModel(coins_sent_model) + wallet_coins_model = CoinsListModel(list(wallet.coins)) + self.list_wallet.setModel(wallet_coins_model) + def recipient_mode_changed(self, fingerprint_toggled): + self.edit_key_fingerprint.setEnabled(fingerprint_toggled) + self.combo_contact.setEnabled(not fingerprint_toggled) + def transfer_mode_changed(self, node_address_toggled): + self.edit_node_address.setEnabled(node_address_toggled) + self.combo_trusted_node.setEnabled(not node_address_toggled) diff --git a/src/cutecoin/models/account/__init__.py b/src/cutecoin/models/account/__init__.py index fbd287a5..fc060cb8 100644 --- a/src/cutecoin/models/account/__init__.py +++ b/src/cutecoin/models/account/__init__.py @@ -13,170 +13,217 @@ from cutecoin.models.account.communities import Communities from cutecoin.models.community import Community from cutecoin.models.transaction import factory from cutecoin.models.person import Person +from cutecoin.core.exceptions import CommunityNotFoundError + class Account(object): + ''' An account is specific to a key. Each account has only one key, and a key can be locally referenced by only one account. ''' - def __init__(self, keyId, name, communities, wallets, contacts): + + def __init__(self, keyid, name, communities, wallets, contacts): ''' Constructor ''' - self.keyId = keyId + self.keyid = keyid self.name = name self.communities = communities self.wallets = wallets self.contacts = contacts @classmethod - def create(cls, keyId, name, communities): + def create(cls, keyid, name, communities): ''' Constructor ''' wallets = Wallets() - account = cls(keyId, name, communities, wallets, []) - for community in account.communities.communitiesList: - wallet = account.wallets.addWallet(community.currency) - wallet.refreshCoins(community, account.keyFingerprint()) + account = cls(keyid, name, communities, wallets, []) + for community in account.communities.communities_list: + wallet = account.wallets.add_wallet(community.currency) + wallet.refresh_coins(community, account.key_fingerprint()) return account @classmethod - def load(cls, jsonData): - keyId = jsonData['keyId'] - name = jsonData['name'] + def load(cls, json_data): + keyid = json_data['keyid'] + name = json_data['name'] communities = Communities() wallets = Wallets() contacts = [] - for contactData in jsonData['contacts']: - contacts.append(Person.fromJson(contactData)) + for contact_data in json_data['contacts']: + contacts.append(Person.from_json(contact_data)) - account = cls(keyId, name, communities, wallets, contacts) + account = cls(keyid, name, communities, wallets, contacts) - for communityData in jsonData['communities']: - account.communities.communitiesList.append(Community.load(communityData, account)) + for community_data in json_data['communities']: + account.communities.communities_list.append( + Community.load( + community_data, + account)) return account def __eq__(self, other): if other is not None: - return other.keyId == self.keyId + return other.keyid == self.keyid else: return False - def addWallet(self, name, currency): - self.wallets.addWallet(name, currency) + def add_wallet(self, name, currency): + self.wallets.add_wallet(name, currency) - def addContact(self, person): + def add_contact(self, person): self.contacts.append(person) - def keyFingerprint(self): + def key_fingerprint(self): gpg = gnupg.GPG() - availableKeys = gpg.list_keys() - logging.debug(self.keyId) - for k in availableKeys: + available_keys = gpg.list_keys() + logging.debug(self.keyid) + for k in available_keys: logging.debug(k) - if k['keyid'] == self.keyId: + if k['keyid'] == self.keyid: return k['fingerprint'] return "" - def transactionsReceived(self): + def transactions_received(self): received = [] - for community in self.communities.communitiesList: - transactionsData = community.ucoinRequest(ucoin.hdc.transactions.Recipient(self.keyFingerprint())) - for trxData in transactionsData: - received.append(factory.createTransaction(trxData['value']['transaction']['sender'], trxData['value']['transaction']['number'], community)) + for community in self.communities.communities_list: + transactions_data = community.ucoin_request( + ucoin.hdc.transactions.Recipient( + self.key_fingerprint())) + for trxData in transactions_data: + received.append( + factory.create_transaction( + trxData['value']['transaction']['sender'], + trxData['value']['transaction']['number'], + community)) return received - def transactionsSent(self): + def transactions_sent(self): sent = [] - for community in self.communities.communitiesList: - transactionsData = community.ucoinRequest(ucoin.hdc.transactions.sender.Last(self.keyFingerprint(), 20)) - for trxData in transactionsData: + for community in self.communities.communities_list: + transactions_data = community.ucoin_request( + ucoin.hdc.transactions.sender.Last( + self.key_fingerprint(), + 20)) + for trx_data in transactions_data: # Small bug in ucoinpy library - if not isinstance(trxData, str): - sent.append(factory.createTransaction(trxData['value']['transaction']['sender'], trxData['value']['transaction']['number'], community)) + if not isinstance(trx_data, str): + sent.append( + factory.create_transaction( + trxData['value']['transaction']['sender'], + trxData['value']['transaction']['number'], + community)) return sent - def lastIssuances(self, community): + def last_issuances(self, community): issuances = [] - if community in self.communities.communitiesList: - issuancesData = community.ucoinRequest(ucoin.hdc.transactions.sender.Issuance(self.keyFingerprint())) - for issuance in issuancesData: + if community in self.communities.communities_list: + issuances_data = community.ucoin_request( + ucoin.hdc.transactions.sender.Issuance( + self.key_fingerprint())) + for issuance in issuances_data: logging.debug(issuance) - issuances.append(factory.createTransaction(issuance['value']['transaction']['sender'], issuance['value']['transaction']['number'], community)) + issuances.append( + factory.create_transaction( + issuance['value']['transaction']['sender'], + issuance['value']['transaction']['number'], + community)) return issuances - def issuedLastDividend(self, community): - currentAmendmentNumber = community.amendmentNumber() - if community in self.communities.communitiesList: - dividendsData = community.ucoinRequest(ucoin.hdc.transactions.sender.issuance.Dividend(self.keyFingerprint(), currentAmendmentNumber)) - for dividend in dividendsData: + def issued_last_dividend(self, community): + current_amendment_number = community.amendment_number() + if community in self.communities.communities_list: + dividends_data = community.ucoin_request( + ucoin.hdc.transactions.sender.issuance.Dividend( + self.key_fingerprint(), + current_amendment_number)) + for dividend in dividends_data: # Small bug in ucoinpy library if not isinstance(dividend, str): return True return False - def issueDividend(self, community, coins): - if community in self.communities.communitiesList: + def issue_dividend(self, community, coins): + if community in self.communities.communities_list: logging.debug(coins) - issuance = ucoin.wrappers.transactions.Issue(self.keyFingerprint(), community.amendmentNumber(), coins, keyId=self.pgpKeyId) + issuance = ucoin.wrappers.transactions.Issue( + self.key_fingerprint(), + community.amendment_number(), + coins, + keyid=self.keyid) return issuance() def tht(self, community): - if community in self.communities.communitiesList: - tht = community.ucoinRequest(ucoin.ucg.tht(self.keyFingerprint())) + if community in self.communities.communities_list: + tht = community.ucoinRequest(ucoin.ucg.tht(self.key_fingerprint())) return tht['entries'] return None - def updateTrustsAndHosters(self, community): - if community in self.communities.communitiesList: - hostersFg = community.hosters() - trustsFg = community.trusts() + def push_tht(self, community): + if community in self.communities.communities_list: + hosters_fg = [] + trusts_fg = [] for trust in community.trusts(): peering = trust.peering() - trustsFg.append(peering['Fingerprint']) + logging.debug(peering) + trusts_fg.append(peering['fingerprint']) for hoster in community.hosters(): + logging.debug(peering) peering = hoster.peering() - hostersFg.append(peering['Fingerprint']) + hosters_fg.append(peering['fingerprint']) entry = { - 'version' : '1', - 'currency' : community.currency, - 'fingerprint' : self.fingerprint(), - 'hosters' : self.hostersFg, - 'trusts' : self.trustsFg + 'version': '1', + 'currency': community.currency, + 'fingerprint': self.key_fingerprint(), + 'hosters': hosters_fg, + 'trusts': trusts_fg } - jsonEntry = json.dump(entry, indent = 2) + logging.debug(entry) + json_entry = json.JSONEncoder(indent=2).encode(entry) gpg = gnupg.GPG() - signature = gpg.sign(jsonEntry, keyId=self.keyid, detach=True) + signature = gpg.sign(json_entry, keyid=self.keyid, clearsign=True) dataPost = { - 'entry' : entry, - 'signature' : signature + 'entry': entry, + 'signature': str(signature) } - community.ucoinPost(ucoin.ucg.tht(self.keyFingerprint()), json.dump(dataPost, indent=2)) - - - def transferCoins(self, node, recipient, coins, message): - transfer = ucoin.wrappers.transactions.RawTransfer(self.keyFingerprint(), recipient.fingerprint, coins, message, keyid=self.pgpKeyId, server=node.server, port=node.port) + community.ucoin_post( + ucoin.ucg.THT( + pgp_fingerprint=self.key_fingerprint()), + dataPost) + else: + raise CommunityNotFoundError(self.keyid, community.amendment_id()) + + def pull_tht(self, community): + if community in self.communities.communities_list: + community.pull_tht(self.key_fingerprint()) + + def transfer_coins(self, node, recipient, coins, message): + transfer = ucoin.wrappers.transactions.RawTransfer( + self.key_fingerprint(), + recipient.fingerprint, + coins, + message, + keyid=self.keyid, + server=node.server, + port=node.port) return transfer() - def jsonifyContacts(self): + def jsonify_contacts(self): data = [] for p in self.contacts: data.append(p.jsonify()) return data def jsonify(self): - data = {'name' : self.name, - 'keyId' : self.keyId, - 'communities' : self.communities.jsonify(self.wallets), - 'contacts' : self.jsonifyContacts()} + data = {'name': self.name, + 'keyId': self.keyid, + 'communities': self.communities.jsonify(self.wallets), + 'contacts': self.jsonify_contacts()} return data - - - - diff --git a/src/cutecoin/models/account/communities/__init__.py b/src/cutecoin/models/account/communities/__init__.py index 180d5604..7d3ecb77 100644 --- a/src/cutecoin/models/account/communities/__init__.py +++ b/src/cutecoin/models/account/communities/__init__.py @@ -3,39 +3,47 @@ Created on 5 févr. 2014 @author: inso ''' -import ucoinpy as ucoin from cutecoin.models.community import Community from cutecoin.core.exceptions import NotMemberOfCommunityError +import ucoinpy as ucoin import logging + class Communities(object): + ''' The list of the communities an account is member of. ''' + def __init__(self): ''' Constructor ''' - self.communitiesList = [] + self.communities_list = [] - def addCommunity(self, mainNode, keyFingerprint): + def add_community(self, main_node, key_fingerprint): ''' Add a community with a mainNode and the fingerprint of the account Check if the fingerprint is present in the community members list If its not, the account isnt added and an error is raised. ''' - community = Community.create(mainNode) - members = community.ucoinRequest(ucoin.hdc.amendments.view.Members(community.amendmentId())) + community = Community.create(main_node) + members = community.ucoin_request( + ucoin.hdc.amendments.view.Members( + community.amendment_id())) - logging.debug("Account fingerprint : " + keyFingerprint) + logging.debug("Account fingerprint : " + key_fingerprint) for member in members: logging.debug(member) - if member['value'] == keyFingerprint: - self.communitiesList.append(community) + if member['value'] == key_fingerprint: + self.communities_list.append(community) return community - raise NotMemberOfCommunityError(keyFingerprint, community.currency + "-" + community.amendmentId()) - + raise NotMemberOfCommunityError( + key_fingerprint, + community.currency + + "-" + + community.amendment_id()) def jsonify(self, wallets): ''' @@ -45,6 +53,3 @@ class Communities(object): for community in self.communitiesList: data.append(community.jsonify(wallets)) return data - - - diff --git a/src/cutecoin/models/account/communities/itemModel.py b/src/cutecoin/models/account/communities/itemModel.py index 65f39f0e..18dfc872 100644 --- a/src/cutecoin/models/account/communities/itemModel.py +++ b/src/cutecoin/models/account/communities/itemModel.py @@ -4,26 +4,28 @@ Created on 5 févr. 2014 @author: inso ''' + class CommunitiesItemModel(object): + def __init__(self, account): - self.communitiesText = account.pgpKey - self.communityItems = [] + self.communities_text = account.key + self.community_items = [] - def appendChild(self, communityItem): - self.communityItems.append(communityItem) + def appendChild(self, community_item): + self.community_items.append(community_item) def child(self, row): return self.communityItems[row] def childCount(self): - return len(self.communityItems) + return len(self.community_items) def columnCount(self): return 1 def data(self, column): try: - return self.communitiesText + return self.communities_text except IndexError: return None @@ -31,4 +33,4 @@ class CommunitiesItemModel(object): return None def row(self): - return 0 \ No newline at end of file + return 0 diff --git a/src/cutecoin/models/account/communities/listModel.py b/src/cutecoin/models/account/communities/listModel.py index 8bd7bea8..83e2b047 100644 --- a/src/cutecoin/models/account/communities/listModel.py +++ b/src/cutecoin/models/account/communities/listModel.py @@ -6,10 +6,13 @@ Created on 5 févr. 2014 from PyQt5.QtCore import QAbstractListModel, Qt + class CommunitiesListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, account, parent=None): ''' Constructor @@ -17,16 +20,15 @@ class CommunitiesListModel(QAbstractListModel): super(CommunitiesListModel, self).__init__(parent) self.communities = account.communities + def rowCount(self, parent): + return len(self.communities.communities_list) - def rowCount(self ,parent): - return len(self.communities.communitiesList) - - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() - value = self.communities.communitiesList[row].name() + row = index.row() + value = self.communities.communities_list[row].name() return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/account/wallets/__init__.py b/src/cutecoin/models/account/wallets/__init__.py index c6b5dfd1..6ef0808b 100644 --- a/src/cutecoin/models/account/wallets/__init__.py +++ b/src/cutecoin/models/account/wallets/__init__.py @@ -6,29 +6,32 @@ Created on 7 févr. 2014 from cutecoin.models.wallet import Wallet + class Wallets(object): + ''' The list of the wallets owned by an account. ''' + def __init__(self): ''' Constructor ''' - self.walletsList = [] + self.wallets_list = [] - def addWallet(self, currency): + def add_wallet(self, currency): ''' Create a new wallet of a specific currency. This wallet must not already be present in the account, it means the wallet must have a different name or a different currency. ''' wallet = Wallet.create(currency) - if wallet not in self.walletsList: - self.walletsList.append(wallet) + if wallet not in self.walletslist: + self.wallets_list.append(wallet) else: - return self.walletsList.get(wallet) + return self.wallets_list.get(wallet) - def getWallet(self, wallet): + def get_wallet(self, wallet): ''' Look for a wallet in the wallets list. ''' @@ -37,19 +40,18 @@ class Wallets(object): return w return None - def removeAllWalletsOf(self, community): - for wallet in self.walletsList: + def remove_all_wallets_of(self, community): + for wallet in self.wallets_list: if wallet.community == community: - self.walletsList.remove(wallet) - + self.wallets_list.remove(wallet) def jsonify(self, community): ''' Return the list of wallets in a key:value form. ''' - communityWallets = [w for w in self.walletsList if w.community == community] + community_wallets = [ + w for w in self.wallets_list if w.community == community] data = [] - for wallet in communityWallets: + for wallet in community_wallets: data.append(wallet.jsonify()) return data - diff --git a/src/cutecoin/models/account/wallets/listModel.py b/src/cutecoin/models/account/wallets/listModel.py index bdefb4cb..e7e779ae 100644 --- a/src/cutecoin/models/account/wallets/listModel.py +++ b/src/cutecoin/models/account/wallets/listModel.py @@ -6,10 +6,13 @@ Created on 8 févr. 2014 from PyQt5.QtCore import QAbstractListModel, Qt + class WalletsListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, account, parent=None): ''' Constructor @@ -17,14 +20,14 @@ class WalletsListModel(QAbstractListModel): super(WalletsListModel, self).__init__(parent) self.wallets = account.wallets - def rowCount(self ,parent): - return len(self.wallets.walletsList) + def rowCount(self, parent): + return len(self.wallets.wallets_list) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() - value = self.wallets.walletsList[row].getText() + row = index.row() + value = self.wallets.wallets_list[row].getText() return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/coin/__init__.py b/src/cutecoin/models/coin/__init__.py index cd6bf8f7..61c7a7eb 100644 --- a/src/cutecoin/models/coin/__init__.py +++ b/src/cutecoin/models/coin/__init__.py @@ -8,10 +8,13 @@ import re import math import logging + class Coin(object): + ''' A coin parsing a regex to read its value ''' + def __init__(self, issuer, number, base, power, origin): self.issuer = issuer self.number = number @@ -20,7 +23,7 @@ class Coin(object): self.origin = origin @classmethod - def fromId(cls, coin_id): + def from_id(cls, coin_id): # Regex to parse the coin id regex = "^([A-Z\d]{40})-(\d+)-(\d)-(\d+)-((A|F|D)-\d+)$" m = re.search(regex, coin_id) @@ -32,12 +35,12 @@ class Coin(object): return cls(issuer, number, base, power, origin) def __eq__(self, other): - return self.getId() == other.getId() + return self.get_id() == other.get_id() def value(self): - return self.base*math.pow(10, self.power) + return self.base * math.pow(10, self.power) - def getId(self): + def get_id(self): return self.issuer + "-" \ + str(self.number) + "-" \ + str(self.base) + "-" \ diff --git a/src/cutecoin/models/coin/listModel.py b/src/cutecoin/models/coin/listModel.py index f167e467..106a786b 100644 --- a/src/cutecoin/models/coin/listModel.py +++ b/src/cutecoin/models/coin/listModel.py @@ -6,10 +6,13 @@ Created on 8 févr. 2014 from PyQt5.QtCore import QAbstractListModel, Qt + class CoinsListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, coins, parent=None): ''' Constructor @@ -17,20 +20,20 @@ class CoinsListModel(QAbstractListModel): super(CoinsListModel, self).__init__(parent) self.coins = coins - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.coins) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = str(self.coins[row].value()) return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled def toList(self): - coinsList = [] + coins_list = [] for c in self.coins: - coinsList.append(c.getId()) - return coinsList \ No newline at end of file + coins_list.append(c.getId()) + return coins_list diff --git a/src/cutecoin/models/community/__init__.py b/src/cutecoin/models/community/__init__.py index 4d625543..eab08152 100644 --- a/src/cutecoin/models/community/__init__.py +++ b/src/cutecoin/models/community/__init__.py @@ -8,14 +8,16 @@ import ucoinpy as ucoin import hashlib import json import logging - from cutecoin.models.node import Node from cutecoin.models.wallet import Wallet + class Community(object): + ''' classdocs ''' + def __init__(self, nodes): ''' A community is a group of nodes using the same currency. @@ -23,51 +25,88 @@ class Community(object): An account is a member of a community if he is a member of the current amendment. ''' self.nodes = nodes - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - self.currency = currentAmendment['currency'] + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + self.currency = current_amendment['currency'] @classmethod - def create(cls, mainNode): + def create(cls, main_node): nodes = [] - nodes.append(mainNode) + nodes.append(main_node) return cls(nodes) - @classmethod - def load(cls, jsonData, account): - knownNodes = [] - for nodeData in jsonData['nodes']: - knownNodes.append(Node(nodeData['server'], nodeData['port'], nodeData['trust'], nodeData['hoster'])) - - community = cls(knownNodes) - - for walletsData in jsonData['wallets']: - wallet = Wallet.load(walletsData, community) - wallet.refreshCoins(account.keyFingerprint()) - account.wallets.walletsList.append(wallet) + def load(cls, json_data, account): + known_nodes = [] + for node_data in json_data['nodes']: + known_nodes.append( + Node( + node_data['server'], + node_data['port'], + node_data['trust'], + node_data['hoster'])) + + community = cls(known_nodes) + + for wallets_data in json_data['wallets']: + wallet = Wallet.load(wallets_data, community) + wallet.refreshCoins(account.key_fingerprint()) + account.wallets.wallets_list.append(wallet) return community - - #TODO: Check if its working - def _searchTrustAddresses(self, trustFg, nextNode, traversedNodes): - nextFg = nextNode.peering()['fingerprint'] - if nextFg not in traversedNodes: - traversedNodes.append(nextFg) - if trustFg == nextFg: - return trustFg + # TODO: Check if its working + def _search_node_by_fingerprint(self, node_fg, next_node, traversed_nodes=[]): + next_fg = next_node.peering()['fingerprint'] + if next_fg not in traversed_nodes: + traversed_nodes.append(next_fg) + if node_fg == next_fg: + return next_node else: - for peer in nextNode.peers(): + for peer in next_node.peers(): # Look for next node informations - found = self._searchTrustAddresses(trustFg, Node(peer['ipv4'], int(peer['port'])), traversedNodes) + found = self._searchTrustAddresses( + node_fg, Node( + peer['ipv4'], int( + peer['port'])), traversed_nodes) if found is not None: return found return None - def synchronizeTrusts(self, trustsFingerprints): - trusts = [] - for trustFg in trustsFingerprints: - trusts.append(self._searchTrustAddresses(trustFg, self.trusts()[0])) - return trusts + def get_nodes_in_peering(self, fingerprints): + nodes = [] + for node_fg in fingerprints: + nodes.append( + self._search_node_by_fingerprint( + node_fg, + self.trusts()[0])) + return nodes + + def pull_tht(self, fingerprint): + tht = self.ucoin_request(ucoin.ucg.THT(fingerprint)) + nodes = [] + nodes.append(self.trusts()[0]) + # We add trusts to the node list + for node_fg in tht['trusts']: + nodes.append( + self._search_node_by_fingerprint( + node_fg, + self.trusts()[0])) + # We look in hosters lists + for node_fg in tht['hosters']: + # If the node was already added as a trust + if node_fg in tht['trusts']: + found_nodes = [ + node for node in nodes if node.peering()['fingerprint'] == node_fg] + if len(found_nodes) == 1: + found_nodes[0].hoster = True + else: + # not supposed to happen + pass + # Else we add it + else: + nodes.append( + self._search_node_by_fingerprint( + node_fg, + self.trusts()[0])) def trusts(self): return [node for node in self.nodes if node.trust] @@ -75,74 +114,78 @@ class Community(object): def hosters(self): return [node for node in self.nodes if node.trust] - def membersFingerprints(self): + def members_fingerprints(self): ''' Listing members of a community ''' - fingerprints = self.ucoinRequest(ucoin.hdc.amendments.view.Members(self.amendmentId())) + fingerprints = self.ucoin_request( + ucoin.hdc.amendments.view.Members( + self.amendment_id())) members = [] for f in fingerprints: members.append(f['value']) return members - def ucoinRequest(self, request, get_args={}): + def ucoin_request(self, request, get_args={}): for node in self.trusts(): - logging.debug("Trying to connect to : " + node.getText()) - request = node.use(request) - return request.get(**get_args) + logging.debug("Trying to connect to : " + node.getText()) + request = node.use(request) + return request.get(**get_args) raise RuntimeError("Cannot connect to any node") - - def ucoinPost(self, request, get_args={}): + def ucoin_post(self, request, get_args={}): for node in self.hosters(): - logging.debug("Trying to connect to : " + node.getText()) - request = node.use(request) - return request.post(**get_args) + logging.debug("Trying to connect to : " + node.getText()) + request = node.use(request) + return request.post(**get_args) raise RuntimeError("Cannot connect to any node") - def amendmentId(self): - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - currentAmendmentHash = hashlib.sha1(currentAmendment['raw'].encode('utf-8')).hexdigest().upper() - amendmentId = str(currentAmendment["number"]) + "-" + currentAmendmentHash - logging.debug("Amendment : " + amendmentId) - return amendmentId + def amendment_id(self): + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + current_amendment_hash = hashlib.sha1( + current_amendment['raw'].encode('utf-8')).hexdigest().upper() + amendment_id = str( + current_amendment["number"]) + "-" + current_amendment_hash + logging.debug("Amendment : " + amendment_id) + return amendment_id def __eq__(self, other): - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - currentAmendmentHash = hashlib.sha1(currentAmendment['raw'].encode('utf-8')).hexdigest().upper() + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + current_amendment_hash = hashlib.sha1( + current_amendment['raw'].encode('utf-8')).hexdigest().upper() - otherAmendment = other.ucoinRequest(ucoin.hdc.amendments.Current()) - otherAmendmentHash = hashlib.sha1(otherAmendment['raw'].encode('utf-8')).hexdigest().upper() + other_amendment = other.ucoin_request(ucoin.hdc.amendments.Current()) + other_amendment_hash = hashlib.sha1( + other_amendment['raw'].encode('utf-8')).hexdigest().upper() - return (otherAmendmentHash == currentAmendmentHash) + return (other_amendment_hash == current_amendment_hash) def name(self): return self.currency def dividend(self): - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - return currentAmendment['dividend'] + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + return current_amendment['dividend'] - def coinMinimalPower(self): - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - if 'coinMinimalPower' in currentAmendment.keys(): - return currentAmendment['coinMinimalPower'] + def coin_minimal_power(self): + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + if 'coinMinimalPower' in current_amendment.keys(): + return current_amendment['coinMinimalPower'] else: return 0 - def amendmentNumber(self): - currentAmendment = self.ucoinRequest(ucoin.hdc.amendments.Current()) - return currentAmendment['number'] + def amendment_number(self): + current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) + return current_amendment['number'] - def jsonifyNodesList(self): + def jsonify_nodes_list(self): data = [] for node in self.nodes: data.append(node.jsonify()) return data def jsonify(self, wallets): - data = {'nodes' : self.jsonifyNodesList(), - 'currency' : self.currency, - 'wallets' : wallets.jsonify(self)} + data = {'nodes': self.jsonify_nodeslist(), + 'currency': self.currency, + 'wallets': wallets.jsonify(self)} return data - diff --git a/src/cutecoin/models/community/itemModel.py b/src/cutecoin/models/community/itemModel.py index 5777ed46..1987a5a4 100644 --- a/src/cutecoin/models/community/itemModel.py +++ b/src/cutecoin/models/community/itemModel.py @@ -4,35 +4,37 @@ Created on 5 févr. 2014 @author: inso ''' + class CommunityItemModel(object): - def __init__(self, community, communitiesItem=None): - self.communitiesItem = communitiesItem - self.communityText = community.name() - self.mainNodeItems = [] + + def __init__(self, community, communities_item=None): + self.communities_item = communities_item + self.community_text = community.name() + self.main_node_items = [] def appendChild(self, item): - self.mainNodeItems.append(item) + self.main_node_items.append(item) def child(self, row): - return self.mainNodeItems[row] + return self.main_node_items[row] def childCount(self): - return len(self.mainNodeItems) + return len(self.main_node_items) def columnCount(self): return 1 def data(self, column): try: - return self.communityText + return self.community_text except IndexError: return None def parent(self): - return self.communitiesItem + return self.communities_item def row(self): - if self.communitiesItem: - return self.communitiesItem.communityItems.index(self) + if self.communities_item: + return self.communities_item.index(self) return 0 diff --git a/src/cutecoin/models/community/membersListModel.py b/src/cutecoin/models/community/membersListModel.py index 1dcf0f13..71b87661 100644 --- a/src/cutecoin/models/community/membersListModel.py +++ b/src/cutecoin/models/community/membersListModel.py @@ -7,28 +7,31 @@ Created on 5 févr. 2014 from cutecoin.models.person import Person from PyQt5.QtCore import QAbstractListModel, Qt + class MembersListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, community, parent=None): ''' Constructor ''' super(MembersListModel, self).__init__(parent) - fingerprints = community.membersFingerprints() + fingerprints = community.members_fingerprints() self.members = [] for f in fingerprints: self.members.append(Person.lookup(f, community)) - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.members) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = self.members[row].name return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/community/treeModel.py b/src/cutecoin/models/community/treeModel.py index 0ec7bb22..1595cbcb 100644 --- a/src/cutecoin/models/community/treeModel.py +++ b/src/cutecoin/models/community/treeModel.py @@ -9,18 +9,21 @@ from cutecoin.models.node.itemModel import MainNodeItem, NodeItem from cutecoin.models.community.itemModel import CommunityItemModel import logging + class CommunityTreeModel(QAbstractItemModel): + ''' A Qt abstract item model to display nodes of a community ''' + def __init__(self, community): ''' Constructor ''' super(CommunityTreeModel, self).__init__(None) self.community = community - self.rootItem = CommunityItemModel(self.community) - self.refreshTreeNodes() + self.root_item = CommunityItemModel(self.community) + self.refresh_tree_nodes() def columnCount(self, parent): return 3 @@ -31,7 +34,6 @@ class CommunityTreeModel(QAbstractItemModel): item = index.internalPointer() - if role == Qt.DisplayRole and index.column() == 0: return item.data(0) elif role == Qt.CheckStateRole and index.column() == 1: @@ -39,7 +41,6 @@ class CommunityTreeModel(QAbstractItemModel): elif role == Qt.CheckStateRole and index.column() == 2: return Qt.Checked if item.hoster else Qt.Unchecked - return None def flags(self, index): @@ -49,11 +50,11 @@ class CommunityTreeModel(QAbstractItemModel): if index.column() == 0: return Qt.ItemIsEnabled | Qt.ItemIsSelectable else: - return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable + return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole and section == 0: - return self.rootItem.data(0) + " nodes" + return self.root_item.data(0) + " nodes" elif orientation == Qt.Horizontal and role == Qt.DisplayRole and section == 1: return "Trust" elif orientation == Qt.Horizontal and role == Qt.DisplayRole and section == 2: @@ -65,13 +66,13 @@ class CommunityTreeModel(QAbstractItemModel): return QModelIndex() if not parent.isValid(): - parentItem = self.rootItem + parent_item = self.root_item else: - parentItem = parent.internalPointer() + parent_item = parent.internalPointer() - childItem = parentItem.child(row) - if childItem: - return self.createIndex(row, column, childItem) + child_item = parent_item.child(row) + if child_item: + return self.createIndex(row, column, child_item) else: return QModelIndex() @@ -79,24 +80,24 @@ class CommunityTreeModel(QAbstractItemModel): if not index.isValid(): return QModelIndex() - childItem = index.internalPointer() - parentItem = childItem.parent() + child_item = index.internalPointer() + parent_item = child_item.parent() - if parentItem == self.rootItem: + if parent_item == self.root_item: return QModelIndex() - return self.createIndex(parentItem.row(), 0, parentItem) + return self.createIndex(parent_item.row(), 0, parent_item) def rowCount(self, parent): if parent.column() > 0: return 0 if not parent.isValid(): - parentItem = self.rootItem + parent_item = self.root_item else: - parentItem = parent.internalPointer() + parent_item = parent.internalPointer() - return parentItem.childCount() + return parent_item.childCount() def setData(self, index, value, role=Qt.EditRole): if index.column() == 0: @@ -110,17 +111,24 @@ class CommunityTreeModel(QAbstractItemModel): item.trust = value elif index.column() == 2: item.host = value - self.dataChanged.emit(index, index) + self.data_changed.emit(index, index) return True - def refreshTreeNodes(self): - logging.debug("root : " + self.rootItem.data(0)) - for mainNode in self.community.nodes: - mainNodeItem = MainNodeItem(mainNode, self.rootItem) - logging.debug("mainNode : " + mainNode.getText() + " / " + mainNodeItem.data(0)) - self.rootItem.appendChild(mainNodeItem) - for node in mainNode.downstreamPeers(): - nodeItem = NodeItem(node, mainNodeItem) - logging.debug("\t node : " + node.getText()+ " / " + nodeItem.data(0)) - mainNodeItem.appendChild(nodeItem) - + def refresh_tree_nodes(self): + logging.debug("root : " + self.root_item.data(0)) + for main_node in self.community.nodes: + main_node_item = MainNodeItem(main_node, self.root_item) + logging.debug( + "mainNode : " + + main_node.getText() + + " / " + + main_node_item.data(0)) + self.root_item.appendChild(main_node_item) + for node in main_node.downstream_peers(): + node_item = NodeItem(node, main_node_item) + logging.debug( + "\t node : " + + node.getText() + + " / " + + node_item.data(0)) + main_node_item.appendChild(node_item) diff --git a/src/cutecoin/models/node/__init__.py b/src/cutecoin/models/node/__init__.py index 3f126737..505d2f64 100644 --- a/src/cutecoin/models/node/__init__.py +++ b/src/cutecoin/models/node/__init__.py @@ -6,10 +6,13 @@ Created on 1 févr. 2014 import ucoinpy as ucoin + class Node(object): + ''' A ucoin node using BMA protocol ''' + def __init__(self, server, port, trust=False, hoster=False): ''' Constructor @@ -20,7 +23,7 @@ class Node(object): self.hoster = hoster def __eq__(self, other): - return ( self.server == other.server and self.port == other.port ) + return (self.server == other.server and self.port == other.port) def getText(self): return self.server + ":" + str(self.port) @@ -29,7 +32,8 @@ class Node(object): TrustedNode is a node the community is reading to get informations. The account sends data one of the community main nodes. ''' - def downstreamPeers(self): + + def downstream_peers(self): ucoin.settings['server'] = self.server ucoin.settings['port'] = self.port @@ -40,7 +44,6 @@ class Node(object): return peers - #TODO: Peering is not json format. Parse it differently def peering(self): request = ucoin.ucg.peering.Peer() self.use(request) @@ -57,8 +60,7 @@ class Node(object): return request def jsonify(self): - return {'server' : self.server, - 'port' : self.port, - 'trust':self.trust, - 'hoster':self.hoster} - + return {'server': self.server, + 'port': self.port, + 'trust': self.trust, + 'hoster': self.hoster} diff --git a/src/cutecoin/models/node/itemModel.py b/src/cutecoin/models/node/itemModel.py index fb1ad706..64f7ad2e 100644 --- a/src/cutecoin/models/node/itemModel.py +++ b/src/cutecoin/models/node/itemModel.py @@ -6,6 +6,7 @@ Created on 5 févr. 2014 class NodeItem(object): + def __init__(self, node, mainNodeItem=None): self.mainNodeItem = mainNodeItem self.nodeText = node.getText() @@ -38,39 +39,39 @@ class NodeItem(object): return self.mainNodeItem.nodeItems.index(self) return 0 + class MainNodeItem(object): - def __init__(self, mainNode, communityItem=None): - self.communityItem = communityItem - self.mainNodeText = mainNode.getText() - self.trust = mainNode.trust - self.hoster = mainNode.hoster - self.nodeItems = [] - def appendChild(self, nodeItem): - self.nodeItems.append(nodeItem) + def __init__(self, main_node, community_item=None): + self.community_item = community_item + self.main_node_text = main_node.getText() + self.trust = main_node.trust + self.hoster = main_node.hoster + self.node_items = [] + + def appendChild(self, node_item): + self.node_items.append(node_item) def child(self, row): - return self.nodeItems[row] + return self.node_items[row] def childCount(self): - return len(self.nodeItems) + return len(self.node_items) def columnCount(self): return 1 def data(self, column): try: - return self.mainNodeText + return self.main_node_text except IndexError: return None def parent(self): - return self.communityItem + return self.community_item def row(self): - if self.communityItem: - return self.communityItem.mainNodeItems.index(self) + if self.community_item: + return self.community_item.main_node_items.index(self) return 0 - - diff --git a/src/cutecoin/models/person/__init__.py b/src/cutecoin/models/person/__init__.py index 30e91312..7cbf0dd0 100644 --- a/src/cutecoin/models/person/__init__.py +++ b/src/cutecoin/models/person/__init__.py @@ -7,13 +7,14 @@ Created on 11 févr. 2014 import ucoinpy as ucoin from cutecoin.core.exceptions import PersonNotFoundError + class Person(object): + ''' A person with a name, a fingerprint and an email Created by the person.factory ''' - def __init__(self, name, fingerprint, email): ''' Constructor @@ -22,14 +23,17 @@ class Person(object): self.fingerprint = fingerprint self.email = email - @classmethod def lookup(cls, fingerprint, community): ''' Create a person from the fngerprint found in a community ''' - keys = community.ucoinRequest(ucoin.pks.Lookup(), - get_args={'search':"0x"+fingerprint, 'op':'index'})['keys'] + keys = community.ucoin_request( + ucoin.pks.Lookup(), + get_args={ + 'search': "0x" + + fingerprint, + 'op': 'index'})['keys'] if len(keys) > 0: json = keys[0]['key'] name = json['name'] @@ -41,18 +45,17 @@ class Person(object): return None @classmethod - def fromJson(cls, jsonPerson): + def from_json(cls, json_person): ''' Create a person from json data ''' - name = jsonPerson['name'] - fingerprint = jsonPerson['fingerprint'] - email = jsonPerson['email'] + name = json_person['name'] + fingerprint = json_person['fingerprint'] + email = json_person['email'] return cls(name, fingerprint, email) def jsonify(self): - data = {'name' : self.name, - 'fingerprint' : self.fingerprint, - 'email' : self.email} + data = {'name': self.name, + 'fingerprint': self.fingerprint, + 'email': self.email} return data - diff --git a/src/cutecoin/models/transaction/__init__.py b/src/cutecoin/models/transaction/__init__.py index 9f773c9a..26dabe68 100644 --- a/src/cutecoin/models/transaction/__init__.py +++ b/src/cutecoin/models/transaction/__init__.py @@ -7,11 +7,14 @@ Created on 1 févr. 2014 import ucoinpy as ucoin from cutecoin.models.coin import Coin + class Transaction(object): + ''' A transaction which can be a transfer or an issuance. At the moment the difference is not made ''' + def __init__(self): self.increment = 0 self.community = "" @@ -20,46 +23,48 @@ class Transaction(object): def value(self): value = 0 - trxData = self.community.ucoinRequest(ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) - for coin in trxData['transaction']['coins']: - value += Coin.fromId(coin['id']).value() + trx_data = self.community.ucoin_request( + ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) + for coin in trx_data['transaction']['coins']: + value += Coin.from_id(coin['id']).value() return value def currency(self): - trxData = self.community.ucoinRequest(ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) - currency = trxData['transaction']['currency'] + trx_data = self.community.ucoin_request( + ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) + currency = trx_data['transaction']['currency'] return currency def transactionID(self): - return self.senderFingerprint + "-" + self.increment - + return self.sender_fingerprint + "-" + self.increment class Transfer(Transaction): + ''' A received transaction ''' + def __init__(self): super(Transfer).__init__() def getText(self): - return str(self.value()) + " " + self.currency() + " from " + self.sender.name - + return str(self.value()) + " " + self.currency() + \ + " from " + self.sender.name class Issuance(Transaction): + ''' An issuance ''' + def __init__(self): super(Issuance).__init__() def amendmentNumber(self): - self.community.ucoinRequest(ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) + self.community.ucoin_request( + ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) def getText(self): return str(self.value()) + " " + self.currency() - - - - diff --git a/src/cutecoin/models/transaction/factory.py b/src/cutecoin/models/transaction/factory.py index dbf6c527..a9886ec1 100644 --- a/src/cutecoin/models/transaction/factory.py +++ b/src/cutecoin/models/transaction/factory.py @@ -8,21 +8,26 @@ import ucoinpy as ucoin from cutecoin.models.person import Person from cutecoin.models.transaction import Transfer, Issuance -#TODO: Passer par des factory + pythonic -def createTransaction(senderFingerprint, increment, community): - transactionId = senderFingerprint + "-" + str(increment) - ucoinTransactionView = community.ucoinRequest(ucoin.hdc.transactions.View(transactionId)) - ucoinTransaction = ucoinTransactionView['transaction'] +# TODO: Passer par des factory + pythonic + + +def create_transaction(sender_fingerprint, increment, community): + transaction_id = sender_fingerprint + "-" + str(increment) + ucoin_transaction_view = community.ucoin_request( + ucoin.hdc.transactions.View(transaction_id)) + ucoin_transaction = ucoin_transaction_view['transaction'] transaction = None - if ucoinTransaction['type'] == 'TRANSFER': + if ucoin_transaction['type'] == 'TRANSFER': transaction = Transfer() - elif ucoinTransaction['type'] == 'ISSUANCE': + elif ucoin_transaction['type'] == 'ISSUANCE': transaction = Issuance() - if transaction != None: + if transaction is not None: transaction.increment = increment transaction.community = community - transaction.sender = Person.lookup(senderFingerprint, community) - transaction.recipient = Person.lookup(ucoinTransaction['recipient'], community) + transaction.sender = Person.lookup(sender_fingerprint, community) + transaction.recipient = Person.lookup( + ucoin_transaction['recipient'], + community) return transaction diff --git a/src/cutecoin/models/transaction/issuancesListModel.py b/src/cutecoin/models/transaction/issuancesListModel.py index d10ae4f3..658c7faf 100644 --- a/src/cutecoin/models/transaction/issuancesListModel.py +++ b/src/cutecoin/models/transaction/issuancesListModel.py @@ -6,26 +6,29 @@ Created on 5 févr. 2014 from PyQt5.QtCore import QAbstractListModel, Qt + class IssuancesListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, account, community, parent=None): ''' Constructor ''' super(IssuancesListModel, self).__init__(parent) - self.issuances = account.lastIssuances(community) + self.issuances = account.last_issuances(community) - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.issuances) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = self.issuances[row].getText() return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/transaction/receivedListModel.py b/src/cutecoin/models/transaction/receivedListModel.py index 96628d00..c46930d2 100644 --- a/src/cutecoin/models/transaction/receivedListModel.py +++ b/src/cutecoin/models/transaction/receivedListModel.py @@ -8,26 +8,29 @@ import ucoinpy as ucoin import logging from PyQt5.QtCore import QAbstractListModel, Qt + class ReceivedListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, account, parent=None): ''' Constructor ''' super(ReceivedListModel, self).__init__(parent) - self.transactions = account.transactionsReceived() + self.transactions = account.transactions_received() - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.transactions) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = self.transactions[row].getText() return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/transaction/sentListModel.py b/src/cutecoin/models/transaction/sentListModel.py index 52218ee1..27a1c00d 100644 --- a/src/cutecoin/models/transaction/sentListModel.py +++ b/src/cutecoin/models/transaction/sentListModel.py @@ -8,26 +8,29 @@ import ucoinpy as ucoin import logging from PyQt5.QtCore import QAbstractListModel, Qt + class SentListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, account, parent=None): ''' Constructor ''' super(SentListModel, self).__init__(parent) - self.transactions = account.transactionsSent() + self.transactions = account.transactions_sent() - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.transactions) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = self.transactions[row].getText() return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled diff --git a/src/cutecoin/models/wallet/__init__.py b/src/cutecoin/models/wallet/__init__.py index 1858a919..45406d91 100644 --- a/src/cutecoin/models/wallet/__init__.py +++ b/src/cutecoin/models/wallet/__init__.py @@ -8,13 +8,14 @@ import ucoinpy as ucoin import gnupg from cutecoin.models.coin import Coin + class Wallet(object): + ''' A wallet is list of coins. It's only used to sort coins. ''' - def __init__(self, coins, community): ''' Constructor @@ -23,22 +24,19 @@ class Wallet(object): self.community = community self.name = "Main Wallet" - @classmethod def create(cls, community): return cls([], community) @classmethod - def load(cls, jsonData, community): + def load(cls, json_data, community): coins = [] - for coinData in jsonData['coins']: - coins.append(Coin.fromId(coinData['coin'])) + for coinData in json_data['coins']: + coins.append(Coin.from_id(coinData['coin'])) return cls(coins, community) - - def __eq__(self, other): - return ( self.community == other.community ) + return (self.community == other.community) def value(self): value = 0 @@ -46,27 +44,27 @@ class Wallet(object): value += coin.value() return value - #TODO: Refresh coins when changing current account + # TODO: Refresh coins when changing current account def refreshCoins(self, fingerprint): - dataList = self.community.ucoinRequest(ucoin.hdc.coins.List({'pgp_fingerprint':fingerprint})) - for issaunces in dataList['coins']: + data_list = self.community.ucoin_request( + ucoin.hdc.coins.List({'pgp_fingerprint': fingerprint})) + for issaunces in data_list['coins']: issuer = issaunces['issuer'] - for coinsIds in issaunces['ids']: - shortened_id = coinsIds - coin = Coin.fromId(issuer+"-"+shortened_id) + for coins_ids in issaunces['ids']: + shortened_id = coins_ids + coin = Coin.from_id(issuer + "-" + shortened_id) self.coins.append(coin) def getText(self): - return self.name + " : " + str(self.value()) + " " + self.community.currency + return self.name + " : " + \ + str(self.value()) + " " + self.community.currency def jsonifyCoinsList(self): data = [] for coin in self.coins: - data.append({'coin' : coin.getId()}) + data.append({'coin': coin.get_id()}) return data def jsonify(self): - return {'coins': self.jsonifyCoinsList(), + return {'coins': self.jsonify_coins_list(), 'name': self.name} - - diff --git a/src/cutecoin/models/wallet/listModel.py b/src/cutecoin/models/wallet/listModel.py index d55d24e9..6197bed6 100644 --- a/src/cutecoin/models/wallet/listModel.py +++ b/src/cutecoin/models/wallet/listModel.py @@ -6,10 +6,13 @@ Created on 8 févr. 2014 from PyQt5.QtCore import QAbstractListModel, Qt + class WalletListModel(QAbstractListModel): + ''' A Qt abstract item model to display communities in a tree ''' + def __init__(self, wallet, parent=None): ''' Constructor @@ -17,14 +20,14 @@ class WalletListModel(QAbstractListModel): super(WalletListModel, self).__init__(parent) self.coins = wallet.coins - def rowCount(self ,parent): + def rowCount(self, parent): return len(self.coins) - def data(self,index,role): + def data(self, index, role): if role == Qt.DisplayRole: - row=index.row() + row = index.row() value = str(self.coins[row].value()) return value - def flags(self,index): + def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled -- GitLab