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 all 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
47 changes: 32 additions & 15 deletions example/python/batch-example.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@
# SPDX-License-Identifier: Apache-2.0
#

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

print("""

PLEASE ENSURE THAT MST IS ENABLED IN IROHA CONFIG

""")

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

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


iroha = Iroha('admin@test')
net = IrohaGrpc()
Expand Down Expand Up @@ -74,10 +79,14 @@ def send_batch_and_print_status(*transactions):
def create_users():
global iroha
init_cmds = [
iroha.command('CreateAsset', asset_name='bitcoin', domain_id='test', precision=2),
iroha.command('CreateAsset', asset_name='dogecoin', domain_id='test', precision=2),
iroha.command('AddAssetQuantity', asset_id='bitcoin#test', amount='100000'),
iroha.command('AddAssetQuantity', asset_id='dogecoin#test', amount='20000'),
iroha.command('CreateAsset', asset_name='bitcoin',
domain_id='test', precision=2),
iroha.command('CreateAsset', asset_name='dogecoin',
domain_id='test', precision=2),
iroha.command('AddAssetQuantity',
asset_id='bitcoin#test', amount='100000'),
iroha.command('AddAssetQuantity',
asset_id='dogecoin#test', amount='20000'),
iroha.command('CreateAccount', account_name='alice', domain_id='test',
public_key=ic.hex_key_to_bytes(alice_public_keys[0])),
iroha.command('CreateAccount', account_name='bob', domain_id='test',
Expand All @@ -98,15 +107,17 @@ def add_keys_and_set_quorum():
alice_cmds = [
alice_iroha.command('AddSignatory', account_id='alice@test',
public_key=ic.hex_key_to_bytes(alice_public_keys[1])),
alice_iroha.command('SetAccountQuorum', account_id='alice@test', quorum=2)
alice_iroha.command('SetAccountQuorum',
account_id='alice@test', quorum=2)
]
alice_tx = alice_iroha.transaction(alice_cmds)
ic.sign_transaction(alice_tx, alice_private_keys[0])
send_transaction_and_print_status(alice_tx)

bob_iroha = Iroha('bob@test')
bob_cmds = [
bob_iroha.command('AddSignatory', account_id='bob@test', public_key=ic.hex_key_to_bytes(bob_public_keys[1])),
bob_iroha.command('AddSignatory', account_id='bob@test',
public_key=ic.hex_key_to_bytes(bob_public_keys[1])),
bob_iroha.command('SetAccountQuorum', account_id='bob@test', quorum=2)
]
bob_tx = bob_iroha.transaction(bob_cmds)
Expand Down Expand Up @@ -150,10 +161,12 @@ def bob_accepts_exchange_request():
pending_transactions = net.send_query(q)
for tx in pending_transactions.transactions_response.transactions:
if tx.payload.reduced_payload.creator_account_id == 'alice@test':
del tx.signatures[:] # we need do this temporarily, otherwise accept will not reach MST engine
# we need do this temporarily, otherwise accept will not reach MST engine
del tx.signatures[:]
else:
ic.sign_transaction(tx, *bob_private_keys)
send_batch_and_print_status(*pending_transactions.transactions_response.transactions)
send_batch_and_print_status(
*pending_transactions.transactions_response.transactions)


@trace
Expand All @@ -162,7 +175,8 @@ def check_no_pending_txs():
print(
net.send_query(
ic.sign_query(
iroha.query('GetPendingTransactions', creator_account='bob@test'),
iroha.query('GetPendingTransactions',
creator_account='bob@test'),
bob_private_keys[0]
)
)
Expand All @@ -185,11 +199,14 @@ def bob_declines_exchange_request():
pending_transactions = net.send_query(q)
for tx in pending_transactions.transactions_response.transactions:
if tx.payload.reduced_payload.creator_account_id == 'alice@test':
del tx.signatures[:] # we need do this temporarily, otherwise accept will not reach MST engine
# we need do this temporarily, otherwise accept will not reach MST engine
del tx.signatures[:]
else:
ic.sign_transaction(tx, *alice_private_keys) # intentionally alice keys were used to fail bob's txs
# intentionally alice keys were used to fail bob's txs
ic.sign_transaction(tx, *alice_private_keys)
# zeroes as private keys are also acceptable
send_batch_and_print_status(*pending_transactions.transactions_response.transactions)
send_batch_and_print_status(
*pending_transactions.transactions_response.transactions)


create_users()
Expand Down
65 changes: 33 additions & 32 deletions example/python/blocks-query.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,46 @@
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()

admin_priv = open("../[email protected]", "r").read()
admin_pub = open("../[email protected]", "r").read()
key_pair = crypto.convertFromExisting(admin_pub, admin_priv)
from irohalib import IrohaCrypto
from irohalib import Iroha, IrohaGrpc

creator = "admin@test"
current_time = int(round(time.time() * 1000)) - 10**5

def get_blocks():
query = blocks_query_builder.creatorAccountId(creator)\
.createdTime(current_time)\
.queryCounter(1) \
.build()
admin_private_key = open('../[email protected]').read()
iroha = Iroha('admin@test')
net = IrohaGrpc()

query_blob = iroha.ModelProtoBlocksQuery(query).signAndAddSignature(key_pair).finish().blob()
proto_query = queries_pb2.BlocksQuery()

if sys.version_info[0] == 2:
tmp = ''.join(map(chr, query_blob))
else:
tmp = bytes(query_blob)
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

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()
47 changes: 44 additions & 3 deletions 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 @@ -240,8 +268,10 @@ class IrohaGrpc(object):
def __init__(self, address=None):
self._address = address if address else '127.0.0.1:50051'
self._channel = grpc.insecure_channel(self._address)
self._command_service_stub = endpoint_pb2_grpc.CommandServiceStub(self._channel)
self._query_service_stub = endpoint_pb2_grpc.QueryServiceStub(self._channel)
self._command_service_stub = endpoint_pb2_grpc.CommandServiceStub(
self._channel)
self._query_service_stub = endpoint_pb2_grpc.QueryServiceStub(
self._channel)

def send_tx(self, transaction):
"""
Expand Down Expand Up @@ -284,6 +314,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