Skip to content
This repository has been archived by the owner on Apr 17, 2019. It is now read-only.

Update tx-example.py and blocks-query.py #1844

Merged
merged 8 commits into from
Nov 15, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions example/python/batch-example.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@

""")

import sys

if sys.version_info[0] < 3:
raise Exception('Python 3 or a more recent version is required.')

from irohalib import Iroha, IrohaGrpc
from irohalib import IrohaCrypto as ic

Expand Down
66 changes: 33 additions & 33 deletions example/python/blocks-query.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,45 @@
import sys
sys.path.insert(0, 'build/shared_model/bindings')
import iroha
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#

import endpoint_pb2_grpc
import queries_pb2
import grpc
import time
import sys

if sys.version_info[0] < 3:
raise Exception('Python 3 or a more recent version is required.')

blocks_query_builder = iroha.ModelBlocksQueryBuilder()
crypto = iroha.ModelCrypto()
from irohalib import IrohaCrypto
from irohalib import Iroha, IrohaGrpc

admin_priv = open("../[email protected]", "r").read()
admin_pub = open("../[email protected]", "r").read()
key_pair = crypto.convertFromExisting(admin_pub, admin_priv)

creator = "admin@test"
current_time = int(round(time.time() * 1000)) - 10**5
admin_private_key = open('../[email protected]').read()
iroha = Iroha('admin@test')
net = IrohaGrpc()

def get_blocks():
query = blocks_query_builder.creatorAccountId(creator)\
.createdTime(current_time)\
.queryCounter(1) \
.build()

query_blob = iroha.ModelProtoBlocksQuery(query).signAndAddSignature(key_pair).finish().blob()
proto_query = queries_pb2.BlocksQuery()
def trace(func):
"""
A decorator for tracing methods' begin/end execution points
"""
def tracer(*args, **kwargs):
name = func.__name__
print('\tEntering "{}"'.format(name))
result = func(*args, **kwargs)
print('\tLeaving "{}"'.format(name))
return result
return tracer

if sys.version_info[0] == 2:
tmp = ''.join(map(chr, query_blob))
else:
tmp = bytes(query_blob)

proto_query.ParseFromString(tmp)

channel = grpc.insecure_channel('127.0.0.1:50051')
query_stub = endpoint_pb2_grpc.QueryServiceStub(channel)
query_response = query_stub.FetchCommits(proto_query)
@trace
def get_blocks():
"""
Subscribe to blocks stream from the network
:return:
"""
query = iroha.blocks_query()
IrohaCrypto.sign_query(query, admin_private_key)
for block in net.send_blocks_stream_query(query):
print('The next block arrived:', block)

for block in query_response:
print("block:")
print(block)

get_blocks()
41 changes: 40 additions & 1 deletion example/python/irohalib.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,13 @@ def hash(proto_with_payload):
:proto_with_payload: proto transaction or query
:return: bytes representation of hash
"""
bytes = proto_with_payload.payload.SerializeToString()
obj = None
if hasattr(proto_with_payload, 'payload'):
obj = getattr(proto_with_payload, 'payload')
elif hasattr(proto_with_payload, 'meta'):
obj = getattr(proto_with_payload, 'meta')

bytes = obj.SerializeToString()
hash = hashlib.sha3_256(bytes).digest()
return hash

Expand Down Expand Up @@ -211,6 +217,28 @@ def query(self, name, counter=1, creator_account=None, created_time=None, **kwar
internal_query.CopyFrom(message)
return query_wrapper

def blocks_query(self, counter=1, creator_account=None, created_time=None):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be just creator_account=self.creator_account, created_time=self.now()? Lines 228-231 could be removed after that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, that won't work, since self is not defined at the moment of evaluation.

>>> class A(object):
...     def __init__(self):
...             self.a = 'abc'
...     def x(self, param=self.a):
...             print(param)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in A
NameError: name 'self' is not defined

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python was definitely overrated by me.

"""
Creates a protobuf query for a blocks stream
:param counter: query counter, should be incremented for each new query
:param creator_account: account id of query creator
:param created_time: query creation timestamp in milliseconds
:return: a proto blocks query
"""
if not created_time:
created_time = self.now()
if not creator_account:
creator_account = self.creator_account

meta = queries_pb2.QueryPayloadMeta()
meta.created_time = created_time
meta.creator_account_id = creator_account
meta.query_counter = counter

query_wrapper = queries_pb2.BlocksQuery()
query_wrapper.meta.CopyFrom(meta)
return query_wrapper

@staticmethod
def batch(*transactions, atomic=True):
"""
Expand Down Expand Up @@ -284,6 +312,17 @@ def send_query(self, query):
response = self._query_service_stub.Find(query)
return response

def send_blocks_stream_query(self, query):
"""
Send a query for blocks stream to Iroha
:param query: protobuf BlocksQuery
:return: an iterable over a stream of blocks
:raise: grpc.RpcError with .code() available in case of any error
"""
response = self._query_service_stub.FetchCommits(query)
for block in response:
yield block

def tx_status(self, transaction):
"""
Request a status of a transaction
Expand Down
Loading