Skip to content
Snippets Groups Projects
Commit a891b255 authored by inso's avatar inso
Browse files

Managing account quality in communities (voter/member/nothing)

Refactoring
Debugging
parent c92c499b
No related branches found
No related tags found
No related merge requests found
Showing
with 269 additions and 264 deletions
###### EDIT #####################
#Directory with ui and resource files
RESOURCE_DIR = res/ui
#Directory for compiled resources
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
#Qt resource files to compile
RESOURCES =
#pyuic5 and pyrcc5 binaries
PYUIC = pyuic5
PYRCC = pyrcc5
#################################
# DO NOT EDIT FOLLOWING
COMPILED_UI = $(UI_FILES:%.ui=$(COMPILED_DIR)/%_uic.py)
COMPILED_RESOURCES = $(RESOURCES:%.qrc=$(COMPILED_DIR)/%_rc.py)
all : resources ui
resources : $(COMPILED_RESOURCES)
ui : $(COMPILED_UI)
$(COMPILED_DIR)/%_uic.py : $(RESOURCE_DIR)/%.ui
$(PYUIC) $< -o $@
$(COMPILED_DIR)/%_rc.py : $(RESOURCE_DIR)/%.qrc
$(PYRCC) $< -o $@
clean :
$(RM) $(COMPILED_UI) $(COMPILED_RESOURCES) $(COMPILED_UI:.py=.pyc) $(COMPILED_RESOURCES:.py=.pyc)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os, multiprocessing, subprocess
resources = os.path.abspath(os.path.join(os.path.dirname(__file__), 'res'))
gen_resources = os.path.abspath(os.path.join(os.path.dirname(__file__), 'src', 'cutecoin', 'gen_resources'))
def convert_ui(args, **kwargs):
subprocess.call(args, **kwargs)
def build_resources():
try:
to_process = []
for root, dirs, files in os.walk(resources):
for f in files:
if f.endswith('.ui'):
source = os.path.join(root, f)
dest = os.path.join(gen_resources, os.path.splitext(os.path.basename(source))[0]+'_uic.py')
exe = 'pyuic5'
elif f.endswith('.qrc'):
source = os.path.join(root, f)
dest = os.path.join(gen_resources, os.path.splitext(os.path.basename(source))[0]+'_rc.py')
exe = 'pyrcc5'
else:
continue
print(source + " >> " + dest)
to_process.append([exe, '-o', dest, source])
if sys.platform.startswith('win'):
# doing this in parallel on windows will crash your computer
[convert_ui(args, shell=True) for args in to_process]
else:
pool = multiprocessing.Pool()
pool.map(convert_ui, to_process)
except EnvironmentError:
print("""\
Warning: PyQt5 development utilities (pyuic5 and pyrcc5) not found
Unable to install praxes' graphical user interface
""")
build_resources()
\ No newline at end of file
...@@ -37,7 +37,7 @@ class Core(object): ...@@ -37,7 +37,7 @@ class Core(object):
def add_account(self, account): def add_account(self, account):
for a in self.accounts: for a in self.accounts:
if a.keyId == account.keyId: if a.keyid == account.keyid:
raise KeyAlreadyUsed(account, account.keyid, a) raise KeyAlreadyUsed(account, account.keyid, a)
self.accounts.append(account) self.accounts.append(account)
......
...@@ -49,7 +49,7 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog): ...@@ -49,7 +49,7 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog):
"", "",
Communities()) Communities())
self.combo_keys_list.currentIndexChanged[ self.combo_keys_list.currentIndexChanged[
int].connect(self.keyChanged) int].connect(self.key_changed)
for index, key in enumerate(available_keys): for index, key in enumerate(available_keys):
self.combo_keys_list.addItem(key['uids'][0]) self.combo_keys_list.addItem(key['uids'][0])
...@@ -73,7 +73,7 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog): ...@@ -73,7 +73,7 @@ class ConfigureAccountDialog(QDialog, Ui_AccountConfigurationDialog):
Node( Node(
server, server,
port)) port))
dialog.button_box.accepted.connect(self.actionAddCommunity) dialog.button_box.accepted.connect(self.action_add_community)
dialog.exec_() dialog.exec_()
def action_add_community(self): def action_add_community(self):
......
...@@ -31,10 +31,9 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog): ...@@ -31,10 +31,9 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog):
default_node.trust = True default_node.trust = True
default_node.hoster = True default_node.hoster = True
self.community = self.account.communities.add_community( self.community = self.account.communities.add_community(
default_node, default_node)
self.account.key_fingerprint())
self.account.wallets.add_wallet(self.community) self.account.wallets.add_wallet(self.community)
self.community_view.set_model(CommunityTreeModel(self.community)) self.tree_nodes.setModel(CommunityTreeModel(self.community))
# TODO: Ask for THT pull # TODO: Ask for THT pull
msg_box = QMessageBox() msg_box = QMessageBox()
msg_box.setText("Add a community") msg_box.setText("Add a community")
...@@ -71,7 +70,7 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog): ...@@ -71,7 +70,7 @@ class ConfigureCommunityDialog(QDialog, Ui_CommunityConfigurationDialog):
menu.exec_(self.tree_nodes.mapToGlobal(point)) menu.exec_(self.tree_nodes.mapToGlobal(point))
def remove_node(self): def remove_node(self):
for index in self.community_view.selectedIndexes(): for index in self.tree_nodes.selectedIndexes():
self.community.nodes.pop(index.row()) self.community.nodes.pop(index.row())
self.tree_nodes.setModel(CommunityTreeModel(self.community)) self.tree_nodes.setModel(CommunityTreeModel(self.community))
......
...@@ -38,7 +38,7 @@ class MainWindow(QMainWindow, Ui_MainWindow): ...@@ -38,7 +38,7 @@ class MainWindow(QMainWindow, Ui_MainWindow):
dialog = ConfigureAccountDialog(self.core, None) dialog = ConfigureAccountDialog(self.core, None)
dialog.button_box.button( dialog.button_box.button(
QDialogButtonBox.Ok).clicked.connect( QDialogButtonBox.Ok).clicked.connect(
self.refreshMainWindow) self.refresh)
dialog.exec_() dialog.exec_()
def save(self): def save(self):
...@@ -95,7 +95,9 @@ class MainWindow(QMainWindow, Ui_MainWindow): ...@@ -95,7 +95,9 @@ class MainWindow(QMainWindow, Ui_MainWindow):
tab_community = CommunityTabWidget( tab_community = CommunityTabWidget(
self.core.current_account, self.core.current_account,
community) community)
self.tabs_communities.addTab(tab_community, community.name()) quality = self.core.current_account.quality(community)
self.tabs_communities.addTab(tab_community, quality +
" in " + community.name())
self.menu_contacts_list.clear() self.menu_contacts_list.clear()
for contact in self.core.current_account.contacts: for contact in self.core.current_account.contacts:
......
...@@ -43,7 +43,7 @@ class Account(object): ...@@ -43,7 +43,7 @@ class Account(object):
account = cls(keyid, name, communities, wallets, []) account = cls(keyid, name, communities, wallets, [])
for community in account.communities.communities_list: for community in account.communities.communities_list:
wallet = account.wallets.add_wallet(community.currency) wallet = account.wallets.add_wallet(community.currency)
wallet.refresh_coins(community, account.key_fingerprint()) wallet.refresh_coins(community, account.fingerprint())
return account return account
@classmethod @classmethod
...@@ -79,7 +79,7 @@ class Account(object): ...@@ -79,7 +79,7 @@ class Account(object):
def add_contact(self, person): def add_contact(self, person):
self.contacts.append(person) self.contacts.append(person)
def key_fingerprint(self): def fingerprint(self):
gpg = gnupg.GPG() gpg = gnupg.GPG()
available_keys = gpg.list_keys() available_keys = gpg.list_keys()
logging.debug(self.keyid) logging.debug(self.keyid)
...@@ -92,9 +92,9 @@ class Account(object): ...@@ -92,9 +92,9 @@ class Account(object):
def transactions_received(self): def transactions_received(self):
received = [] received = []
for community in self.communities.communities_list: for community in self.communities.communities_list:
transactions_data = community.ucoin_request( transactions_data = community.network.request(
ucoin.hdc.transactions.Recipient( ucoin.hdc.transactions.Recipient(
self.key_fingerprint())) self.fingerprint()))
for trxData in transactions_data: for trxData in transactions_data:
received.append( received.append(
factory.create_transaction( factory.create_transaction(
...@@ -106,9 +106,9 @@ class Account(object): ...@@ -106,9 +106,9 @@ class Account(object):
def transactions_sent(self): def transactions_sent(self):
sent = [] sent = []
for community in self.communities.communities_list: for community in self.communities.communities_list:
transactions_data = community.ucoin_request( transactions_data = community.network.request(
ucoin.hdc.transactions.sender.Last( ucoin.hdc.transactions.sender.Last(
self.key_fingerprint(), self.fingerprint(),
20)) 20))
for trx_data in transactions_data: for trx_data in transactions_data:
# Small bug in ucoinpy library # Small bug in ucoinpy library
...@@ -123,9 +123,9 @@ class Account(object): ...@@ -123,9 +123,9 @@ class Account(object):
def last_issuances(self, community): def last_issuances(self, community):
issuances = [] issuances = []
if community in self.communities.communities_list: if community in self.communities.communities_list:
issuances_data = community.ucoin_request( issuances_data = community.network.request(
ucoin.hdc.transactions.sender.Issuance( ucoin.hdc.transactions.sender.Issuance(
self.key_fingerprint())) self.fingerprint()))
for issuance in issuances_data: for issuance in issuances_data:
logging.debug(issuance) logging.debug(issuance)
issuances.append( issuances.append(
...@@ -138,9 +138,9 @@ class Account(object): ...@@ -138,9 +138,9 @@ class Account(object):
def issued_last_dividend(self, community): def issued_last_dividend(self, community):
current_amendment_number = community.amendment_number() current_amendment_number = community.amendment_number()
if community in self.communities.communities_list: if community in self.communities.communities_list:
dividends_data = community.ucoin_request( dividends_data = community.network.request(
ucoin.hdc.transactions.sender.issuance.Dividend( ucoin.hdc.transactions.sender.issuance.Dividend(
self.key_fingerprint(), self.fingerprint(),
current_amendment_number)) current_amendment_number))
for dividend in dividends_data: for dividend in dividends_data:
# Small bug in ucoinpy library # Small bug in ucoinpy library
...@@ -152,15 +152,26 @@ class Account(object): ...@@ -152,15 +152,26 @@ class Account(object):
if community in self.communities.communities_list: if community in self.communities.communities_list:
logging.debug(coins) logging.debug(coins)
issuance = ucoin.wrappers.transactions.Issue( issuance = ucoin.wrappers.transactions.Issue(
self.key_fingerprint(), self.fingerprint(),
community.amendment_number(), community.amendment_number(),
coins, coins,
keyid=self.keyid) keyid=self.keyid)
return issuance() return issuance()
def transfer_coins(self, node, recipient, coins, message):
transfer = ucoin.wrappers.transactions.RawTransfer(
self.fingerprint(),
recipient.fingerprint,
coins,
message,
keyid=self.keyid,
server=node.server,
port=node.port)
return transfer()
def tht(self, community): def tht(self, community):
if community in self.communities.communities_list: if community in self.communities.communities_list:
tht = community.ucoinRequest(ucoin.ucg.tht(self.key_fingerprint())) tht = community.ucoinRequest(ucoin.ucg.tht(self.fingerprint()))
return tht['entries'] return tht['entries']
return None return None
...@@ -168,18 +179,18 @@ class Account(object): ...@@ -168,18 +179,18 @@ class Account(object):
if community in self.communities.communities_list: if community in self.communities.communities_list:
hosters_fg = [] hosters_fg = []
trusts_fg = [] trusts_fg = []
for trust in community.trusts(): for trust in community.network.trusts():
peering = trust.peering() peering = trust.peering()
logging.debug(peering) logging.debug(peering)
trusts_fg.append(peering['fingerprint']) trusts_fg.append(peering['fingerprint'])
for hoster in community.hosters(): for hoster in community.network.hosters():
logging.debug(peering) logging.debug(peering)
peering = hoster.peering() peering = hoster.peering()
hosters_fg.append(peering['fingerprint']) hosters_fg.append(peering['fingerprint'])
entry = { entry = {
'version': '1', 'version': '1',
'currency': community.currency, 'currency': community.currency,
'fingerprint': self.key_fingerprint(), 'fingerprint': self.fingerprint(),
'hosters': hosters_fg, 'hosters': hosters_fg,
'trusts': trusts_fg 'trusts': trusts_fg
} }
...@@ -193,27 +204,24 @@ class Account(object): ...@@ -193,27 +204,24 @@ class Account(object):
'signature': str(signature) 'signature': str(signature)
} }
community.ucoin_post( community.network.post(
ucoin.ucg.THT( ucoin.ucg.THT(
pgp_fingerprint=self.key_fingerprint()), pgp_fingerprint=self.fingerprint()),
dataPost) dataPost)
else: else:
raise CommunityNotFoundError(self.keyid, community.amendment_id()) raise CommunityNotFoundError(self.keyid, community.amendment_id())
def pull_tht(self, community): def pull_tht(self, community):
if community in self.communities.communities_list: if community in self.communities.communities_list:
community.pull_tht(self.key_fingerprint()) community.pull_tht(self.fingerprint())
else:
raise CommunityNotFoundError(self.keyid, community.amendment_id())
def transfer_coins(self, node, recipient, coins, message): def quality(self, community):
transfer = ucoin.wrappers.transactions.RawTransfer( if community in self.communities.communities_list:
self.key_fingerprint(), return community.person_quality(self.fingerprint())
recipient.fingerprint, else:
coins, raise CommunityNotFoundError(self.keyid, community.amendment_id())
message,
keyid=self.keyid,
server=node.server,
port=node.port)
return transfer()
def jsonify_contacts(self): def jsonify_contacts(self):
data = [] data = []
...@@ -223,7 +231,7 @@ class Account(object): ...@@ -223,7 +231,7 @@ class Account(object):
def jsonify(self): def jsonify(self):
data = {'name': self.name, data = {'name': self.name,
'keyId': self.keyid, 'keyid': self.keyid,
'communities': self.communities.jsonify(self.wallets), 'communities': self.communities.jsonify(self.wallets),
'contacts': self.jsonify_contacts()} 'contacts': self.jsonify_contacts()}
return data return data
...@@ -21,35 +21,21 @@ class Communities(object): ...@@ -21,35 +21,21 @@ class Communities(object):
''' '''
self.communities_list = [] self.communities_list = []
def add_community(self, main_node, key_fingerprint): def add_community(self, main_node):
''' '''
Add a community with a mainNode and the fingerprint of the account Add a community with a mainNode
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(main_node) community = Community.create(main_node)
members = community.ucoin_request( if community not in self.communities_list:
ucoin.hdc.amendments.view.Members( self.communities_list.append(community)
community.amendment_id())) return community
return None
logging.debug("Account fingerprint : " + key_fingerprint)
for member in members:
logging.debug(member)
if member['value'] == key_fingerprint:
self.communities_list.append(community)
return community
raise NotMemberOfCommunityError(
key_fingerprint,
community.currency +
"-" +
community.amendment_id())
def jsonify(self, wallets): def jsonify(self, wallets):
''' '''
Return the list of communities in a key:value form. Return the list of communities in a key:value form.
''' '''
data = [] data = []
for community in self.communitiesList: for community in self.communities_list:
data.append(community.jsonify(wallets)) data.append(community.jsonify(wallets))
return data return data
...@@ -26,7 +26,7 @@ class Wallets(object): ...@@ -26,7 +26,7 @@ class Wallets(object):
it means the wallet must have a different name or a different currency. it means the wallet must have a different name or a different currency.
''' '''
wallet = Wallet.create(currency) wallet = Wallet.create(currency)
if wallet not in self.walletslist: if wallet not in self.wallets_list:
self.wallets_list.append(wallet) self.wallets_list.append(wallet)
else: else:
return self.wallets_list.get(wallet) return self.wallets_list.get(wallet)
......
...@@ -10,6 +10,7 @@ import json ...@@ -10,6 +10,7 @@ import json
import logging import logging
from cutecoin.models.node import Node from cutecoin.models.node import Node
from cutecoin.models.wallet import Wallet from cutecoin.models.wallet import Wallet
from cutecoin.models.community.network import CommunityNetwork
class Community(object): class Community(object):
...@@ -18,21 +19,21 @@ class Community(object): ...@@ -18,21 +19,21 @@ class Community(object):
classdocs classdocs
''' '''
def __init__(self, nodes): def __init__(self, network):
''' '''
A community is a group of nodes using the same currency. A community is a group of nodes using the same currency.
They are all using the same amendment and are syncing their datas. They are all using the same amendment and are syncing their datas.
An account is a member of a community if he is a member of the current amendment. An account is a member of a community if he is a member of the current amendment.
''' '''
self.nodes = nodes self.network = network
current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) current_amendment = self.network.request(ucoin.hdc.amendments.Current())
self.currency = current_amendment['currency'] self.currency = current_amendment['currency']
@classmethod @classmethod
def create(cls, main_node): def create(cls, main_node):
nodes = [] nodes = []
nodes.append(main_node) nodes.append(main_node)
return cls(nodes) return cls(CommunityNetwork(nodes))
@classmethod @classmethod
def load(cls, json_data, account): def load(cls, json_data, account):
...@@ -45,147 +46,92 @@ class Community(object): ...@@ -45,147 +46,92 @@ class Community(object):
node_data['trust'], node_data['trust'],
node_data['hoster'])) node_data['hoster']))
community = cls(known_nodes) community = cls(CommunityNetwork(known_nodes))
for wallets_data in json_data['wallets']: for wallets_data in json_data['wallets']:
wallet = Wallet.load(wallets_data, community) wallet = Wallet.load(wallets_data, community)
wallet.refreshCoins(account.key_fingerprint()) wallet.refreshCoins(account.fingerprint())
account.wallets.wallets_list.append(wallet) account.wallets.wallets_list.append(wallet)
return community return community
# TODO: Check if its working def name(self):
def _search_node_by_fingerprint(self, node_fg, next_node, traversed_nodes=[]): return self.currency
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 next_node.peers():
# Look for next node informations
found = self._searchTrustAddresses(
node_fg, Node(
peer['ipv4'], int(
peer['port'])), traversed_nodes)
if found is not None:
return found
return None
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]
def hosters(self):
return [node for node in self.nodes if node.trust]
def members_fingerprints(self):
'''
Listing members of a community
'''
fingerprints = self.ucoin_request(
ucoin.hdc.amendments.view.Members(
self.amendment_id()))
members = []
for f in fingerprints:
members.append(f['value'])
return members
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)
raise RuntimeError("Cannot connect to any node")
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)
raise RuntimeError("Cannot connect to any node")
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): def __eq__(self, other):
current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) current_amendment = self.network.request(ucoin.hdc.amendments.Current())
current_amendment_hash = hashlib.sha1( current_amendment_hash = hashlib.sha1(
current_amendment['raw'].encode('utf-8')).hexdigest().upper() current_amendment['raw'].encode('utf-8')).hexdigest().upper()
other_amendment = other.ucoin_request(ucoin.hdc.amendments.Current()) other_amendment = other.network.request(ucoin.hdc.amendments.Current())
other_amendment_hash = hashlib.sha1( other_amendment_hash = hashlib.sha1(
other_amendment['raw'].encode('utf-8')).hexdigest().upper() other_amendment['raw'].encode('utf-8')).hexdigest().upper()
return (other_amendment_hash == current_amendment_hash) return (other_amendment_hash == current_amendment_hash)
def name(self):
return self.currency
def dividend(self): def dividend(self):
current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) current_amendment = self.network.request(ucoin.hdc.amendments.Current())
return current_amendment['dividend'] return current_amendment['dividend']
def coin_minimal_power(self): def coin_minimal_power(self):
current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) current_amendment = self.network.request(ucoin.hdc.amendments.Current())
if 'coinMinimalPower' in current_amendment.keys(): if 'coinMinimalPower' in current_amendment.keys():
return current_amendment['coinMinimalPower'] return current_amendment['coinMinimalPower']
else: else:
return 0 return 0
def amendment_id(self):
current_amendment = self.network.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 amendment_number(self): def amendment_number(self):
current_amendment = self.ucoin_request(ucoin.hdc.amendments.Current()) current_amendment = self.network.request(ucoin.hdc.amendments.Current())
return current_amendment['number'] return current_amendment['number']
def person_quality(self, fingerprint):
if (fingerprint in self.voters_fingerprints()):
return "voter"
elif (fingerprint in self.members_fingerprints()):
return "member"
else:
return "nothing"
def members_fingerprints(self):
'''
Listing members of a community
'''
fingerprints = self.network.request(
ucoin.hdc.amendments.view.Members(
self.amendment_id()))
members = []
for f in fingerprints:
members.append(f['value'])
return members
def voters_fingerprints(self):
'''
Listing members of a community
'''
fingerprints = self.network.request(
ucoin.hdc.amendments.view.Voters(
self.amendment_id()))
voters = []
for f in fingerprints:
voters.append(f['value'])
return voters
def jsonify_nodes_list(self): def jsonify_nodes_list(self):
data = [] data = []
for node in self.nodes: for node in self.network.nodes:
data.append(node.jsonify()) data.append(node.jsonify())
return data return data
def jsonify(self, wallets): def jsonify(self, wallets):
data = {'nodes': self.jsonify_nodeslist(), data = {'nodes': self.jsonify_nodes_list(),
'currency': self.currency, 'currency': self.currency,
'wallets': wallets.jsonify(self)} 'wallets': wallets.jsonify(self)}
return data return data
'''
Created on 27 mars 2014
@author: inso
'''
from cutecoin.models.node import Node
import ucoinpy as ucoin
import logging
class CommunityNetwork(object):
'''
classdocs
'''
#TODO: Factory to load json
def __init__(self, nodes):
'''
Constructor
'''
self.nodes = nodes
def 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)
raise RuntimeError("Cannot connect to any node")
def 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)
raise RuntimeError("Cannot connect to any node")
# 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 next_node.peers():
# Look for next node informations
found = self._searchTrustAddresses(
node_fg, Node(
peer['ipv4'], int(
peer['port'])), traversed_nodes)
if found is not None:
return found
return None
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.network.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]
def hosters(self):
return [node for node in self.nodes if node.hoster]
...@@ -5,7 +5,7 @@ Created on 5 févr. 2014 ...@@ -5,7 +5,7 @@ Created on 5 févr. 2014
''' '''
from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt
from cutecoin.models.node.itemModel import MainNodeItem, NodeItem from cutecoin.models.node.itemModel import NodeItem
from cutecoin.models.community.itemModel import CommunityItemModel from cutecoin.models.community.itemModel import CommunityItemModel
import logging import logging
...@@ -111,24 +111,24 @@ class CommunityTreeModel(QAbstractItemModel): ...@@ -111,24 +111,24 @@ class CommunityTreeModel(QAbstractItemModel):
item.trust = value item.trust = value
elif index.column() == 2: elif index.column() == 2:
item.host = value item.host = value
self.data_changed.emit(index, index) self.dataChanged.emit(index, index)
return True return True
def refresh_tree_nodes(self): def refresh_tree_nodes(self):
logging.debug("root : " + self.root_item.data(0)) logging.debug("root : " + self.root_item.data(0))
for main_node in self.community.nodes: for node in self.community.network.nodes:
main_node_item = MainNodeItem(main_node, self.root_item) node_item = NodeItem(node, self.root_item)
logging.debug( logging.debug(
"mainNode : " + "mainNode : " +
main_node.getText() + node.getText() +
" / " + " / " +
main_node_item.data(0)) node_item.data(0))
self.root_item.appendChild(main_node_item) self.root_item.appendChild(node_item)
for node in main_node.downstream_peers(): for node in node.downstream_peers():
node_item = NodeItem(node, main_node_item) child_node_item = NodeItem(node, node_item)
logging.debug( logging.debug(
"\t node : " + "\t node : " +
node.getText() + node.getText() +
" / " + " / " +
node_item.data(0)) child_node_item.data(0))
main_node_item.appendChild(node_item) node_item.appendChild(child_node_item)
...@@ -7,41 +7,6 @@ Created on 5 févr. 2014 ...@@ -7,41 +7,6 @@ Created on 5 févr. 2014
class NodeItem(object): class NodeItem(object):
def __init__(self, node, mainNodeItem=None):
self.mainNodeItem = mainNodeItem
self.nodeText = node.getText()
self.trust = node.trust
self.hoster = node.hoster
def appendChild(self, item):
pass
def child(self, row):
return None
def childCount(self):
return 0
def columnCount(self):
return 1
def data(self, column):
try:
return self.nodeText
except IndexError:
return None
def parent(self):
return self.mainNodeItem
def row(self):
if self.mainNodeItem:
return self.mainNodeItem.nodeItems.index(self)
return 0
class MainNodeItem(object):
def __init__(self, main_node, community_item=None): def __init__(self, main_node, community_item=None):
self.community_item = community_item self.community_item = community_item
self.main_node_text = main_node.getText() self.main_node_text = main_node.getText()
......
...@@ -28,7 +28,7 @@ class Person(object): ...@@ -28,7 +28,7 @@ class Person(object):
''' '''
Create a person from the fngerprint found in a community Create a person from the fngerprint found in a community
''' '''
keys = community.ucoin_request( keys = community.network.request(
ucoin.pks.Lookup(), ucoin.pks.Lookup(),
get_args={ get_args={
'search': "0x" + 'search': "0x" +
......
...@@ -23,14 +23,14 @@ class Transaction(object): ...@@ -23,14 +23,14 @@ class Transaction(object):
def value(self): def value(self):
value = 0 value = 0
trx_data = self.community.ucoin_request( trx_data = self.community.network.request(
ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment)))
for coin in trx_data['transaction']['coins']: for coin in trx_data['transaction']['coins']:
value += Coin.from_id(coin['id']).value() value += Coin.from_id(coin['id']).value()
return value return value
def currency(self): def currency(self):
trx_data = self.community.ucoin_request( trx_data = self.community.network.request(
ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment)))
currency = trx_data['transaction']['currency'] currency = trx_data['transaction']['currency']
return currency return currency
...@@ -63,7 +63,7 @@ class Issuance(Transaction): ...@@ -63,7 +63,7 @@ class Issuance(Transaction):
super(Issuance).__init__() super(Issuance).__init__()
def amendmentNumber(self): def amendmentNumber(self):
self.community.ucoin_request( self.community.network.request(
ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment))) ucoin.hdc.transactions.View(self.sender.fingerprint + "-" + str(self.increment)))
def getText(self): def getText(self):
......
...@@ -13,13 +13,13 @@ from cutecoin.models.transaction import Transfer, Issuance ...@@ -13,13 +13,13 @@ from cutecoin.models.transaction import Transfer, Issuance
def create_transaction(sender_fingerprint, increment, community): def create_transaction(sender_fingerprint, increment, community):
transaction_id = sender_fingerprint + "-" + str(increment) transaction_id = sender_fingerprint + "-" + str(increment)
ucoin_transaction_view = community.ucoin_request( transaction_view = community.network.request(
ucoin.hdc.transactions.View(transaction_id)) ucoin.hdc.transactions.View(transaction_id))
ucoin_transaction = ucoin_transaction_view['transaction'] transaction_data = transaction_view['transaction']
transaction = None transaction = None
if ucoin_transaction['type'] == 'TRANSFER': if transaction_data['type'] == 'TRANSFER':
transaction = Transfer() transaction = Transfer()
elif ucoin_transaction['type'] == 'ISSUANCE': elif transaction_data['type'] == 'ISSUANCE':
transaction = Issuance() transaction = Issuance()
if transaction is not None: if transaction is not None:
...@@ -27,7 +27,7 @@ def create_transaction(sender_fingerprint, increment, community): ...@@ -27,7 +27,7 @@ def create_transaction(sender_fingerprint, increment, community):
transaction.community = community transaction.community = community
transaction.sender = Person.lookup(sender_fingerprint, community) transaction.sender = Person.lookup(sender_fingerprint, community)
transaction.recipient = Person.lookup( transaction.recipient = Person.lookup(
ucoin_transaction['recipient'], transaction_data['recipient'],
community) community)
return transaction return transaction
...@@ -46,7 +46,7 @@ class Wallet(object): ...@@ -46,7 +46,7 @@ class Wallet(object):
# TODO: Refresh coins when changing current account # TODO: Refresh coins when changing current account
def refreshCoins(self, fingerprint): def refreshCoins(self, fingerprint):
data_list = self.community.ucoin_request( data_list = self.community.network.request(
ucoin.hdc.coins.List({'pgp_fingerprint': fingerprint})) ucoin.hdc.coins.List({'pgp_fingerprint': fingerprint}))
for issaunces in data_list['coins']: for issaunces in data_list['coins']:
issuer = issaunces['issuer'] issuer = issaunces['issuer']
...@@ -59,7 +59,7 @@ class Wallet(object): ...@@ -59,7 +59,7 @@ class Wallet(object):
return self.name + " : " + \ return self.name + " : " + \
str(self.value()) + " " + self.community.currency str(self.value()) + " " + self.community.currency
def jsonifyCoinsList(self): def jsonify_coins_list(self):
data = [] data = []
for coin in self.coins: for coin in self.coins:
data.append({'coin': coin.get_id()}) data.append({'coin': coin.get_id()})
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment