Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_document_message(self):
# prepare message
document_message = DocumentMessage()
# prepare document
identity_document = Identity(
10,
"beta_brousouf",
"HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd",
"lolcat",
BlockUID(32, "DB30D958EE5CB75186972286ED3F4686B8A1C2CD"),
"J3G9oM5AKYZNLAB5Wx499w61NuUoS57JVccTShUbGpCMjCqj9yXXqNq7dyZpDWA6BxipsiaMZhujMeBfCznzyci",
)
# get json string message
json_document_message = document_message.get_json(
DocumentMessage.IDENTITY_TYPE_ID, identity_document.inline()
)
# convert to dict to verify
dict_document_message = json.loads(json_document_message)
# verify
self.assertIn("body", dict_document_message)
self.assertIn("name", dict_document_message["body"])
self.assertIn("identity", dict_document_message["body"])
self.assertEqual(4, dict_document_message["body"]["name"])
expected = """HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd\
:J3G9oM5AKYZNLAB5Wx499w61NuUoS57JVccTShUbGpCMjCqj9yXXqNq7dyZpDWA6BxipsiaMZhujMeBfCznzyci:32\
'connid' key, whose value in brackets is prepended to the log message.
"""
def process(self, msg, kwargs):
return '[%s] %s' % (self.extra['pubkey'][:5], msg), kwargs
class NodeConnector(QObject):
"""
A node is a peer send from the client point of view.
"""
changed = pyqtSignal()
success = pyqtSignal()
failure = pyqtSignal(int)
identity_changed = pyqtSignal()
neighbour_found = pyqtSignal(Peer)
block_found = pyqtSignal(BlockUID)
def __init__(self, node, user_parameters, session=None):
"""
Constructor
"""
super().__init__()
self.node = node
self.failure_count = 0
self._ws_tasks = {'block': None,
'peer': None}
self._connected = {'block': False,
'peer': False}
self._user_parameters = user_parameters
self.session = session
self._raw_logger = logging.getLogger('sakia')
self._logger = NodeConnectorLoggerAdapter(self._raw_logger, {'pubkey': self.node.pubkey})
password: str,
) -> Membership:
"""
Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current block data
:param identity: Identity document
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Membership
"""
# get current block BlockStamp
timestamp = BlockUID(current_block["number"], current_block["hash"])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
# create identity document
membership = Membership(
version=10,
currency=current_block["currency"],
issuer=key.pubkey,
membership_ts=timestamp,
membership_type=membership_type,
uid=identity.uid,
identity_ts=identity.timestamp,
)
# sign document
data = c.fetchone()
if data:
return block_uid(data[0])
else:
c = self._conn.execute("""SELECT `current_buid`,
COUNT(`current_buid`) AS `value_occurrence`
FROM `nodes`
WHERE currency == ?
GROUP BY `current_buid`
ORDER BY `value_occurrence` DESC
LIMIT 1;""", (currency,))
data = c.fetchone()
if data:
return block_uid(data[0])
return BlockUID.empty()
def build_stopline(currency, pubkey, block_number, mediantime):
"""
Used to insert a line of ignored tx in the history
"""
transaction = Transaction(currency=currency,
pubkey=pubkey,
sha_hash=STOPLINE_HASH,
written_block=block_number,
blockstamp=BlockUID(block_number, BlockUID.empty().sha_hash),
timestamp=mediantime,
signatures="",
issuers="",
receivers="",
amount=0,
amount_base=0,
comment="",
txid=0,
state=Transaction.VALIDATED,
raw="")
return transaction
Initialize memberships and other data for given identity
:param sakia.data.entities.Identity identity:
:param function log_stream: callback to log text
:param function progress: callback for progressbar
"""
log_stream("Requesting membership data")
progress(1/3)
try:
memberships_data = await self._bma_connector.get(identity.currency, bma.blockchain.memberships,
req_args={'search': identity.pubkey})
if block_uid(memberships_data['sigDate']) == identity.blockstamp \
and memberships_data['uid'] == identity.uid:
identity.written = True
for ms in memberships_data['memberships']:
if ms['written'] and ms['written'] > identity.membership_written_on:
identity.membership_buid = BlockUID(ms['blockNumber'], ms['blockHash'])
identity.membership_type = ms['membership']
identity.membership_written_on = ms['written']
progress(1 / 3)
if identity.membership_buid:
log_stream("Requesting membership timestamp")
ms_block_data = await self._bma_connector.get(identity.currency, bma.blockchain.block,
req_args={'number': identity.membership_buid.number})
if ms_block_data:
identity.membership_timestamp = ms_block_data['medianTime']
log_stream("Requesting identity requirements status")
progress(1 / 3)
requirements_data = await self._bma_connector.get(identity.currency, bma.wot.requirements,
req_args={'search': identity.pubkey})
"""
Create and return a Certification document
:param current_block: Current block data
:param self_cert_document: Identity document
:param from_pubkey: Pubkey of the certifier
:rtype: Certification
"""
# construct Certification Document
return Certification(
version=10,
currency=current_block["currency"],
pubkey_from=from_pubkey,
identity=self_cert_document,
timestamp=BlockUID(current_block["number"], current_block["hash"]),
signature="",
)
def current_blockUID(self):
"""
Get the latest block considered valid
It is the most frequent last block of every known nodes
"""
blocks = [n.block for n in self.synced_nodes if n.block]
if len(blocks) > 0:
return BlockUID(blocks[0]['number'], blocks[0]['hash'])
else:
return BlockUID.empty()
software = data['software']
if 'version' in data:
version = data['version']
if 'fork_window' in data:
fork_window = data['fork_window']
if parse_version("0.11") <= file_version < parse_version("0.12dev1") :
for endpoint_data in data['endpoints']:
endpoints.append(Endpoint.from_inline(endpoint_data))
if currency in data:
currency = data['currency']
peer = Peer(2, currency, pubkey, BlockUID(0, Block.Empty_Hash), endpoints, "SOMEFAKESIGNATURE")
else:
peer = Peer.from_signed_raw(data['peer'])
node = cls(peer, uid, pubkey, block,
state, last_change,
{'root': "", 'leaves': []},
software, version, fork_window, session)
logging.debug("Node from json : {:}".format(str(node)))
return node