Skip to content

Commit

Permalink
Preparing compatibility with UCP2
Browse files Browse the repository at this point in the history
  • Loading branch information
Insoleet committed Feb 27, 2016
1 parent 43dbe83 commit 3b9d381
Show file tree
Hide file tree
Showing 37 changed files with 666 additions and 443 deletions.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ucoinpy>=0.13
ucoinpy>=0.20
git+https://github.com/harvimt/quamash.git@gh45
asynctest
git+https://github.com/networkx/networkx.git@v1.11
31 changes: 15 additions & 16 deletions src/sakia/core/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
@author: inso
"""

from ucoinpy.documents.certification import SelfCertification, Certification, Revocation
from ucoinpy.documents.membership import Membership
from ucoinpy.documents import Membership, SelfCertification, Certification, Revokation, BlockUID
from ucoinpy.key import SigningKey

import logging
Expand Down Expand Up @@ -345,13 +344,13 @@ def _parse_uid_certifiers(data):
return self.name == data['uid'], self.name, data['uid']

def _parse_uid_lookup(data):
timestamp = 0
timestamp = BlockUID.empty()
found_uid = ""
for result in data['results']:
if result["pubkey"] == self.pubkey:
uids = result['uids']
for uid_data in uids:
if uid_data["meta"]["timestamp"] > timestamp:
if BlockUID.from_str(uid_data["meta"]["timestamp"]) >= timestamp:
timestamp = uid_data["meta"]["timestamp"]
found_uid = uid_data["uid"]
return self.name == found_uid, self.name, found_uid
Expand All @@ -360,13 +359,13 @@ def _parse_pubkey_certifiers(data):
return self.pubkey == data['pubkey'], self.pubkey, data['pubkey']

def _parse_pubkey_lookup(data):
timestamp = 0
timestamp = BlockUID.empty()
found_uid = ""
found_result = ["", ""]
for result in data['results']:
uids = result['uids']
for uid_data in uids:
if uid_data["meta"]["timestamp"] > timestamp:
if BlockUID.from_str(uid_data["meta"]["timestamp"]) >= timestamp:
timestamp = uid_data["meta"]["timestamp"]
found_uid = uid_data["uid"]
if found_uid == self.name:
Expand Down Expand Up @@ -464,12 +463,12 @@ async def send_membership(self, password, community, mstype):
"""
logging.debug("Send membership")

blockid = await community.blockid()
blockUID = await community.blockUID()
self_identity = await self._identities_registry.future_find(self.pubkey, community)
selfcert = await self_identity.selfcert(community)

membership = Membership(PROTOCOL_VERSION, community.currency,
selfcert.pubkey, blockid, mstype, selfcert.uid,
selfcert.pubkey, blockUID, mstype, selfcert.uid,
selfcert.timestamp, None)
key = SigningKey(self.salt, password)
membership.sign([key])
Expand All @@ -495,12 +494,12 @@ async def certify(self, password, community, pubkey):
:param str pubkey: The certified identity pubkey
"""
logging.debug("Certdata")
blockid = await community.blockid()
blockUID = await community.blockUID()
identity = await self._identities_registry.future_find(pubkey, community)
selfcert = await identity.selfcert(community)
if selfcert:
certification = Certification(PROTOCOL_VERSION, community.currency,
self.pubkey, pubkey, blockid, None)
self.pubkey, pubkey, blockUID, None)

key = SigningKey(self.salt, password)
certification.sign(selfcert, [key])
Expand Down Expand Up @@ -531,23 +530,23 @@ async def revoke(self, password, community):
Revoke self-identity on server, not in blockchain
:param str password: The account SigningKey password
:param sakia.core.community.Community community: The community target of the revocation
:param sakia.core.community.Community community: The community target of the revokation
"""
revoked = await self._identities_registry.future_find(self.pubkey, community)

revocation = Revocation(PROTOCOL_VERSION, community.currency, None)
revokation = Revokation(PROTOCOL_VERSION, community.currency, None)
selfcert = await revoked.selfcert(community)

key = SigningKey(self.salt, password)
revocation.sign(selfcert, [key])
revokation.sign(selfcert, [key])

logging.debug("Self-Revocation Document : \n{0}".format(revocation.raw(selfcert)))
logging.debug("Signature : \n{0}".format(revocation.signatures[0]))
logging.debug("Self-Revokation Document : \n{0}".format(revokation.raw(selfcert)))
logging.debug("Signature : \n{0}".format(revokation.signatures[0]))

data = {
'pubkey': revoked.pubkey,
'self_': selfcert.signed_raw(),
'sig': revocation.signatures[0]
'sig': revokation.signatures[0]
}
logging.debug("Posted data : {0}".format(data))
responses = await community.bma_access.broadcast(bma.wot.Revoke, {}, data)
Expand Down
24 changes: 13 additions & 11 deletions src/sakia/core/community.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ..tools.exceptions import NoPeerAvailable
from .net.network import Network
from ucoinpy.api import bma
from ucoinpy.documents import Block, BlockId
from ucoinpy.documents import Block, BlockUID
from .net.api.bma.access import BmaAccess


Expand Down Expand Up @@ -187,7 +187,7 @@ async def monetary_mass(self):
:return: The monetary mass value
"""
# Get cached block by block number
block_number = self.network.current_blockid.number
block_number = self.network.current_blockUID.number
if block_number:
block = await self.bma_access.future_request(bma.blockchain.Block,
req_args={'number': block_number})
Expand All @@ -203,7 +203,7 @@ async def nb_members(self):
"""
try:
# Get cached block by block number
block_number = self.network.current_blockid.number
block_number = self.network.current_blockUID.number
block = await self.bma_access.future_request(bma.blockchain.Block,
req_args={'number': block_number})
return block['membersCount']
Expand All @@ -214,20 +214,22 @@ async def nb_members(self):
logging.debug(str(e))
return 0

async def time(self):
async def time(self, block_number=None):
"""
Get the blockchain time
:param block_number: The block number, None if current block
:return: The community blockchain time
:rtype: int
"""
try:
# Get cached block by block number
block_number = self.network.current_blockid.number
if block_number is None:
block_number = self.network.current_blockUID.number
block = await self.bma_access.future_request(bma.blockchain.Block,
req_args={'number': block_number})
return block['medianTime']
except ValueError as e:
if '404' in e:
if '404' in str(e):
return 0
except NoPeerAvailable as e:
logging.debug(str(e))
Expand Down Expand Up @@ -290,7 +292,7 @@ async def get_block(self, number=None):
:param int number: The block number. If none, returns current block.
"""
if number is None:
block_number = self.network.current_blockid.number
block_number = self.network.current_blockUID.number
data = await self.bma_access.future_request(bma.blockchain.Block,
req_args={'number': block_number})
else:
Expand All @@ -299,22 +301,22 @@ async def get_block(self, number=None):
req_args={'number': number})
return data

async def blockid(self):
async def blockUID(self):
"""
Get the block id.
:return: The current block ID as [NUMBER-HASH] format.
"""
try:
block_number = self.network.current_blockid.number
block_number = self.network.current_blockUID.number
block = await self.bma_access.future_request(bma.blockchain.Block,
req_args={'number': block_number})
signed_raw = "{0}{1}\n".format(block['raw'], block['signature'])
except ValueError as e:
if '404' in str(e):
return BlockId.empty()
return BlockUID.empty()

return Block.from_signed_raw(signed_raw).blockid
return Block.from_signed_raw(signed_raw).blockUID

async def members_pubkeys(self):
"""
Expand Down
24 changes: 12 additions & 12 deletions src/sakia/core/net/api/bma/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def _get_from_cache(self, request, req_args, get_args):
if request is bma.blockchain.Parameters and self._rollback_to == 0:
need_reload = True
elif str(request) in BmaAccess.__saved_requests \
or cached_data['metadata']['block_hash'] == self._network.current_blockid.sha_hash:
or cached_data['metadata']['block_hash'] == self._network.current_blockUID.sha_hash:
need_reload = False
ret_data = cached_data['value']
else:
Expand Down Expand Up @@ -168,8 +168,8 @@ def _update_cache(self, request, req_args, get_args, data):
self._data[cache_key] = {'metadata': {},
'value': {}}

self._data[cache_key]['metadata']['block_number'] = self._network.current_blockid.number
self._data[cache_key]['metadata']['block_hash'] = self._network.current_blockid.sha_hash
self._data[cache_key]['metadata']['block_number'] = self._network.current_blockUID.number
self._data[cache_key]['metadata']['block_hash'] = self._network.current_blockUID.sha_hash
self._data[cache_key]['metadata']['sakia_version'] = __version__
if not self._compare_json(self._data[cache_key]['value'], data):
self._data[cache_key]['value'] = data
Expand Down Expand Up @@ -236,7 +236,7 @@ async def future_request(self, request, req_args={}, get_args={}):
conn_handler = node.endpoint.conn_handler()
req = request(conn_handler, **req_args)
try:
json_data = await req.get(**get_args)
json_data = await req.get(**get_args, session=self._network.session)
self._update_cache(request, req_args, get_args, json_data)
return json_data
except ValueError as e:
Expand All @@ -245,9 +245,9 @@ async def future_request(self, request, req_args={}, get_args={}):
tries += 1
except (ClientError, ServerDisconnectedError, gaierror, asyncio.TimeoutError) as e:
tries += 1
except jsonschema.ValidationError as e:
logging.debug(str(e))
tries += 1
#except jsonschema.ValidationError as e:
# logging.debug(str(e))
# tries += 1
if len(nodes) == 0 or json_data is None:
raise NoPeerAvailable("", len(nodes))
return json_data
Expand All @@ -269,17 +269,17 @@ async def simple_request(self, request, req_args={}, get_args={}):
json_data = None
while tries < 3:
try:
json_data = await req.get(**get_args)
json_data = await req.get(**get_args, session=self._network.session)
return json_data
except ValueError as e:
if '404' in str(e) or '400' in str(e):
raise
tries += 1
except (ClientError, ServerDisconnectedError, gaierror, asyncio.TimeoutError) as e:
tries += 1
except jsonschema.ValidationError as e:
logging.debug(str(e))
tries += 1
#except jsonschema.ValidationError as e:
# logging.debug(str(e))
# tries += 1
if len(nodes) == 0 or not json_data:
raise NoPeerAvailable("", len(nodes))
return json_data
Expand Down Expand Up @@ -307,7 +307,7 @@ async def broadcast(self, request, req_args={}, post_args={}):
logging.debug("Trying to connect to : " + node.pubkey)
conn_handler = node.endpoint.conn_handler()
req = request(conn_handler, **req_args)
reply = asyncio.ensure_future(req.post(**post_args))
reply = asyncio.ensure_future(req.post(**post_args, session=self._network.session))
replies.append(reply)
self._invalidate_cache(request)
else:
Expand Down
Loading

0 comments on commit 3b9d381

Please sign in to comment.