def test_invoke(self): self.shutdown_test_env() self.start_test_env() time.sleep(5) client = Client() chain = client.new_channel(CHAIN_ID) client.set_state_store(file_key_value_store(self.kv_store_path)) chain.add_peer(Peer()) submitter = get_submitter() signing_identity = submitter.signing_identity # cc_invoke_req = create_invocation_proposal_req( # CHAINCODE_NAME, CHAINCODE_VERSION, signing_identity, # args=['move', 'a', 'b', '100']) queue = Queue(1) # # chain.invoke_chaincode(cc_invoke_req) \ # .subscribe(lambda x: queue.put(x)) prop = queue.get(timeout=10) proposal_bytes = prop.proposal_bytes sig = prop.signature # verify the signature against the hash of proposal_bytes digest = signing_identity.msp.crypto_suite.hash(proposal_bytes) self.assertEqual( signing_identity.verify(str.encode(digest.hexdigest()), sig), True) self.shutdown_test_env()
def test_string_to_signature(self): with open(self.channel_tx, 'rb') as f: channel_tx = f.read() channel_config = utils.extract_channel_config(channel_tx) client = Client() client.state_store = FileKeyValueStore(self.kv_store_path) orderer_org_admin = get_orderer_org_admin(client) orderer_org_admin_tx_context = \ TXContext(orderer_org_admin, Ecies(), {}) client.tx_context = orderer_org_admin_tx_context orderer_org_admin_signature = client.sign_channel_config( channel_config) orderer_org_admin_signature_bytes = \ orderer_org_admin_signature.SerializeToString() proto_signature = utils.string_to_signature( [orderer_org_admin_signature_bytes]) self.assertIsInstance(proto_signature, list) self.assertTrue( 'OrdererMSP' in proto_signature[0].signature_header.__str__())
def test_build_header(self): timestamp = utils.current_timestamp() client = Client() client.state_store = FileKeyValueStore(self.kv_store_path) orderer_org_admin = get_orderer_org_admin(client) orderer_org_admin_tx_context = \ TXContext(orderer_org_admin, Ecies(), {}) client.tx_context = orderer_org_admin_tx_context orderer_org_admin_serialized = utils.create_serialized_identity( orderer_org_admin) serialized_identity = identities_pb2.SerializedIdentity() serialized_identity.ParseFromString(orderer_org_admin_serialized) proto_channel_header = utils.build_channel_header( common_pb2.HeaderType.Value('CONFIG_UPDATE'), orderer_org_admin_tx_context.tx_id, self.channel_id, timestamp ) channel_header = utils.build_header( orderer_org_admin_tx_context.identity, proto_channel_header, orderer_org_admin_tx_context.nonce ) self.assertIsInstance(channel_header, common_pb2.Header)
def test_create_new_chain(self): client = Client() test_chain = client.new_channel('test') self.assertEqual(test_chain, client.get_channel('test')) no_chain = client.get_channel('test1') self.assertIsNone(no_chain)
def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_mutual_tls'] self.config_yaml = \ E2E_CONFIG['test-network']['channel-artifacts']['config_yaml'] self.channel_profile = \ E2E_CONFIG['test-network']['channel-artifacts']['channel_profile'] self.client = Client('test/fixtures/network-mutual-tls.json') with open('test/fixtures/network-mutual-tls.json') as f: self.network_info = json.load(f) self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') # Boot up the testing network self.shutdown_test_env() self.start_test_env() time.sleep(1)
def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.configtx_path = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.peer0Org1_req_endpoint = E2E_CONFIG['test-network'][ 'org1.example.com']['peers']['peer0']['grpc_request_endpoint'] self.peer0Org1_tls_certs = E2E_CONFIG['test-network'][ 'org1.example.com']['peers']['peer0']['tls_cacerts'] self.peer0Org1_tls_hostname = E2E_CONFIG['test-network'][ 'org1.example.com']['peers']['peer0']['server_hostname'] self.peer0Org2_req_endpoint = E2E_CONFIG['test-network'][ 'org2.example.com']['peers']['peer0']['grpc_request_endpoint'] self.peer0Org2_tls_certs = E2E_CONFIG['test-network'][ 'org2.example.com']['peers']['peer0']['tls_cacerts'] self.peer0Org2_tls_hostname = E2E_CONFIG['test-network'][ 'org2.example.com']['peers']['peer0']['server_hostname'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.base_path = "/tmp/fabric-sdk-py" self.kv_store_path = os.path.join(self.base_path, "key-value-store") self.client = Client() self.start_test_env()
def setUp(self, wipe_all): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../test/fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) if "LOCAL_DEPLOY" in os.environ: LOCAL_DEPLOY = os.environ["LOCAL_DEPLOY"] == "True" GCP_DEPLOY = not LOCAL_DEPLOY self.channel_tx = \ E2E_CONFIG[NETWORK_NAME]['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG[NETWORK_NAME]['docker']['compose_file_trustas_gcp'] if GCP_DEPLOY else \ E2E_CONFIG[NETWORK_NAME]['docker']['compose_file_trustas_localhost'] self.config_yaml = \ E2E_CONFIG[NETWORK_NAME]['channel-artifacts']['config_yaml'] self.channel_profile = \ E2E_CONFIG[NETWORK_NAME]['channel-artifacts']['channel_profile'] self.client = Client('test/fixtures/trustas_net_gcp.json') if GCP_DEPLOY else \ Client('test/fixtures/network.json') # Client('test/fixtures/local-10peers.json') self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') global ALIVE ALIVE = True # Boot up the testing network self.start_test_env(wipe_all) return HOST, NAME
def setUp(self): super(ChannelEventHubTest, self).setUp() self.client = Client('test/fixtures/network.json') self.channel_name = "businesschannel" # default application channel self.channel = self.client.new_channel(self.channel_name) self.blocks = [] self.org = 'org1.example.com' self.peer = self.client.get_peer('peer0.' + self.org) self.org_admin = self.client.get_user(self.org, 'Admin') self.loop = asyncio.get_event_loop()
def test_create_serialized_identity(self): client = Client() client.state_store = FileKeyValueStore(self.kv_store_path) orderer_org_admin = get_orderer_org_admin(client) orderer_org_admin_serialized = utils.create_serialized_identity( orderer_org_admin) serialized_identity = identities_pb2.SerializedIdentity() serialized_identity.ParseFromString(orderer_org_admin_serialized) self.assertEqual(serialized_identity.mspid, self.orderer_org_mspid)
def setUp(self): self.configtx_path = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.orderer_tls_certs = \ E2E_CONFIG['test-network']['orderer']['tls_cacerts'] self.orderer_tls_hostname = \ E2E_CONFIG['test-network']['orderer']['server_hostname'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.base_path = "/tmp/fabric-sdk-py" self.kv_store_path = os.path.join(self.base_path, "key-value-store") self.client = Client() self.start_test_env()
def setUp(self): self.base_path = "/tmp/fabric-sdk-py" self.kv_store_path = os.path.join(self.base_path, "key-value-store") self.client = Client() self.client.state_store = FileKeyValueStore(self.kv_store_path) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.channel_name = \ E2E_CONFIG['test-network']['channel-artifacts']['channel_id'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.start_test_env()
def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.client = Client('test/fixtures/network.json') self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') self.start_test_env()
class BaseTestCase(unittest.TestCase): """ Base class for test cases. All test cases can feel free to implement this. """ def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.client = Client('test/fixtures/network.json') self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') self.start_test_env() def tearDown(self): self.shutdown_test_env() def check_logs(self): cli_call([ "docker-compose", "-f", self.compose_file_path, "logs", "--tail=200" ]) def start_test_env(self): cli_call(["docker-compose", "-f", self.compose_file_path, "up", "-d"]) def shutdown_test_env(self): cli_call(["docker-compose", "-f", self.compose_file_path, "down"])
class ClientBase: """Base class for a Hyperledger Fabric client.""" def __init__(self, profile, channel_name, org_name, peer_name, user_name): self.client = Client(profile) self._channel_name = channel_name self._org_name = org_name self._peer_name = peer_name self._user_name = user_name self._user = self.client.get_user(self._org_name, self._user_name) endpoint = self.client.get_net_info('peers', self._peer_name, 'url') tlscert = self.client.get_net_info('peers', self._peer_name, 'tlsCACerts', 'path') loop = asyncio.get_event_loop() peer = create_peer(endpoint=endpoint, tls_cacerts=tlscert) loop.run_until_complete( self.client.init_with_discovery(self._user, peer, self._channel_name)) self._channel = self.client.new_channel(self._channel_name) @property def channel_name(self): return self._channel_name @property def channel(self): return self._channel @property def org_name(self): return self._org_name @property def peer_name(self): return self._peer_name @property def user_name(self): return self._user_name @property def user(self): return self._user
def test_create_new_chain(self): client = Client() client.set_state_store(file_key_value_store(self.kv_store_path)) test_chain = client.new_chain('test') self.assertEqual(test_chain, client.get_chain('test')) no_chain = client.get_chain('test1') self.assertIsNone(no_chain)
def test_create_serialized_identity(self): client = Client('test/fixtures/network.json') orderer_org_admin = get_orderer_org_user( state_store=client.state_store) orderer_org_admin_serialized = utils.create_serialized_identity( orderer_org_admin) serialized_identity = identities_pb2.SerializedIdentity() serialized_identity.ParseFromString(orderer_org_admin_serialized) self.assertEqual(serialized_identity.mspid, self.orderer_org_mspid)
def setUp(self): self.channel_tx = \ test_network['channel-artifacts']['channel.tx'] self.channel_name = \ test_network['channel-artifacts']['channel_id'] self.compose_file_path = \ test_network['docker']['compose_file_tls'] self.client = Client('test/fixtures/network.json') self.start_test_env()
def __init__(self, profile, channel_name, org_name, peer_name, user_name): self.client = Client(profile) self._channel_name = channel_name self._org_name = org_name self._peer_name = peer_name self._user_name = user_name self._user = self.client.get_user(self._org_name, self._user_name) endpoint = self.client.get_net_info('peers', self._peer_name, 'url') tlscert = self.client.get_net_info('peers', self._peer_name, 'tlsCACerts', 'path') loop = asyncio.get_event_loop() peer = create_peer(endpoint=endpoint, tls_cacerts=tlscert) loop.run_until_complete( self.client.init_with_discovery(self._user, peer, self._channel_name)) self._channel = self.client.new_channel(self._channel_name)
def create_channel(self): client = Client('test/fixtures/network.json') logger.info("start to create channel") request = build_channel_request( client, self.channel_tx, self.channel_name) q = Queue(1) response = client._create_channel(request) response.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x)) status, _ = q.get(timeout=5) self.assertEqual(status.status, 200) logger.info("successfully create the channel: %s", self.channel_name) client.state_store = None
def create_channel(self): client = Client() client.state_store = FileKeyValueStore(self.kv_store_path + 'build-channel') logger.info("start to create channel") request = build_channel_request(client, self.channel_tx, self.channel_name) q = Queue(1) response = client.create_channel(request) response.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x)) status, _ = q.get(timeout=5) self.assertEqual(status.status, 200) logger.info("successfully create the channel: %s", self.channel_name) client.state_store = None
def join_channel(self): # sleep 5 seconds for channel created time.sleep(5) client = Client() client.state_store = FileKeyValueStore(self.kv_store_path + 'join-channel') channel = client.new_channel(self.channel_name) logger.info("start to join channel") orgs = ["org1.example.com", "org2.example.com"] for org in orgs: request = build_join_channel_req(org, channel, client) assert (request) # result = True and channel.join_channel(request) logger.info("peers in org: %s join channel: %", org, self.channel_name) logger.info("joining channel tested succefully") client.state_store = None
def join_channel(self): # wait for channel created time.sleep(5) client = Client('test/fixtures/network.json') channel = client.new_channel(self.channel_name) logger.info("start to join channel") orgs = ["org1.example.com", "org2.example.com"] done = True for org in orgs: client.state_store = FileKeyValueStore( self.client.kv_store_path + org) request = build_join_channel_req(org, channel, client) done = done and channel.join_channel(request) if done: logger.info("peers in org: %s join channel: %s.", org, self.channel_name) if done: logger.info("joining channel tested successfully.") client.state_store = None assert(done)
def test_install(self): time.sleep(5) client = Client() chain = client.new_chain(CHAIN_ID) client.set_state_store(file_key_value_store(self.kv_store_path)) chain.add_peer(Peer()) chain.add_orderer(Orderer()) submitter = get_submitter() signing_identity = submitter.signing_identity cc_install_req = create_installment_proposal_req( CHAINCODE_NAME, CHAINCODE_PATH, CHAINCODE_VERSION) queue = Queue(1) chain.install_chaincode(cc_install_req, signing_identity) \ .subscribe(on_next=lambda x: queue.put(x), on_error=lambda x: queue.put(x)) response, _ = queue.get(timeout=5) # TODO: create channel not implement yet print(response.status) self.assertEqual(404, response.status)
def test_string_to_signature(self): with open(self.channel_tx, 'rb') as f: channel_tx = f.read() channel_config = utils.extract_channel_config(channel_tx) client = Client('test/fixtures/network.json') orderer_org_admin = get_orderer_org_user( state_store=client.state_store) orderer_org_admin_tx_context = \ TXContext(orderer_org_admin, Ecies(), {}) client.tx_context = orderer_org_admin_tx_context orderer_org_admin_signature = client.sign_channel_config( channel_config) proto_signature = utils.string_to_signature( [orderer_org_admin_signature]) self.assertIsInstance(proto_signature, list) self.assertTrue( 'OrdererMSP' in proto_signature[0].signature_header.__str__())
def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ NET_CONFIG['channel-artifacts']['channel.tx'] self.compose_file_path = \ NET_CONFIG['docker']['compose_file_tls'] self.config_yaml = \ NET_CONFIG['channel-artifacts']['config_yaml'] self.channel_profile = \ NET_CONFIG['channel-artifacts']['channel_profile'] self.client = Client('test/fixtures/trustas-net.json') self.channel_name = "businesschannel" # application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') global ALIVE ALIVE = True # Boot up the testing network self.start_test_env()
def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.configtx_path = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.base_path = "/tmp/fabric-sdk-py" self.kv_store_path = os.path.join(self.base_path, "key-value-store") self.client = Client() self.client.state_store = FileKeyValueStore(self.kv_store_path) self.start_test_env()
def setUp(self): self.client = Client('test/fixtures/network.json')
class E2eTest(BaseTestCase): def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_mutual_tls'] self.config_yaml = \ E2E_CONFIG['test-network']['channel-artifacts']['config_yaml'] self.channel_profile = \ E2E_CONFIG['test-network']['channel-artifacts']['channel_profile'] self.client = Client('test/fixtures/network-mutual-tls.json') self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') # Boot up the testing network self.shutdown_test_env() self.start_test_env() time.sleep(1) def tearDown(self): super(E2eTest, self).tearDown() def channel_create(self): """ Create an channel for further testing. :return: """ logger.info("E2E: Channel creation start: name={}".format( self.channel_name)) # By default, self.user is the admin of org1 response = self.client.channel_create( 'orderer.example.com', self.channel_name, self.user, config_yaml=self.config_yaml, channel_profile=self.channel_profile) self.assertTrue(response) logger.info("E2E: Channel creation done: name={}".format( self.channel_name)) def channel_join(self): """ Join peers of two orgs into an existing channels :return: """ logger.info("E2E: Channel join start: name={}".format( self.channel_name)) # channel must already exist when to join channel = self.client.get_channel(self.channel_name) self.assertIsNotNone(channel) orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, 'Admin') response = self.client.channel_join( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], orderer='orderer.example.com') self.assertTrue(response) # Verify the ledger exists now in the peer node dc = docker.from_env() for peer in ['peer0', 'peer1']: peer0_container = dc.containers.get(peer + '.' + org) code, output = peer0_container.exec_run( 'test -f ' '/var/hyperledger/production/ledgersData/chains/chains/{}' '/blockfile_000000'.format(self.channel_name)) self.assertEqual(code, 0, "Local ledger not exists") logger.info("E2E: Channel join done: name={}".format( self.channel_name)) def chaincode_install(self): """ Test installing an example chaincode to peer :return: """ logger.info("E2E: Chaincode install start") orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.chaincode_install( requestor=org_admin, peers=['peer0.' + org, 'peer1.' + org], cc_path=CC_PATH, cc_name=CC_NAME, cc_version=CC_VERSION) self.assertTrue(response) # Verify the cc pack exists now in the peer node dc = docker.from_env() for peer in ['peer0', 'peer1']: peer0_container = dc.containers.get(peer + '.' + org) code, output = peer0_container.exec_run( 'test -f ' '/var/hyperledger/production/chaincodes/example_cc.1.0') self.assertEqual(code, 0, "chaincodes pack not exists") logger.info("E2E: chaincode install done") def chaincode_install_fail(self): pass def chaincode_instantiate(self): """ Test instantiating an example chaincode to peer :return: """ logger.info("E2E: Chaincode instantiation start") orgs = ["org1.example.com"] args = ['a', '200', 'b', '300'] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.chaincode_instantiate( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], args=args, cc_name=CC_NAME, cc_version=CC_VERSION) logger.info( "E2E: Chaincode instantiation response {}".format(response)) self.assertTrue(response) logger.info("E2E: chaincode instantiation done") def chaincode_invoke(self): """ Test invoking an example chaincode to peer :return: """ logger.info("E2E: Chaincode invoke start") orgs = ["org1.example.com"] args = ['a', 'b', '100'] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.chaincode_invoke( requestor=org_admin, channel_name=self.channel_name, peers=['peer1.' + org], args=args, cc_name=CC_NAME, cc_version=CC_VERSION, wait_for_event=True) self.assertEqual(response, '') logger.info("E2E: chaincode invoke done") def chaincode_query(self): """ Test invoking an example chaincode to peer :return: """ logger.info("E2E: Chaincode query start") orgs = ["org1.example.com"] args = ['b'] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.chaincode_query( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], args=args, cc_name=CC_NAME, cc_version=CC_VERSION) self.assertEqual(response, '400') # 300 + 100 logger.info("E2E: chaincode query done") def query_installed_chaincodes(self): """ Test query installed chaincodes on peer :return: """ logger.info("E2E: Query installed chaincode start") orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_installed_chaincodes( requestor=org_admin, peers=['peer0.' + org, 'peer1.' + org], ) self.assertEqual(response.chaincodes[0].name, CC_NAME, "Query failed") self.assertEqual(response.chaincodes[0].version, CC_VERSION, "Query failed") self.assertEqual(response.chaincodes[0].path, CC_PATH, "Query failed") logger.info("E2E: Query installed chaincode done") def query_channels(self): """ Test querying channel :return: """ logger.info("E2E: Query channel start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_channels( requestor=org_admin, peers=['peer0.' + org, 'peer1.' + org], ) self.assertEqual(response.channels[0].channel_id, 'businesschannel', "Query failed") logger.info("E2E: Query channel done") def query_info(self): """ Test querying information on the state of the Channel :return: """ logger.info("E2E: Query info start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_info( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], ) self.assertEqual(response.height, 3, "Query failed") logger.info("E2E: Query info done") def query_block_by_txid(self): """ Test querying block by tx id :return: """ logger.info("E2E: Query block by tx id start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_info( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], ) response = self.client.query_block_by_hash( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], block_hash=response.currentBlockHash) tx_id = response.get('data').get('data')[0].get('payload').get( 'header').get('channel_header').get('tx_id') response = self.client.query_block_by_txid( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], tx_id=tx_id) self.assertEqual( response.get('data').get('data')[0].get('payload').get( 'header').get('channel_header').get('tx_id'), tx_id, "Query failed") logger.info("E2E: Query block by tx id done") def query_block_by_hash(self): """ Test querying block by block hash :return: """ logger.info("E2E: Query block by block hash start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_info( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], ) previous_block_hash = response.previousBlockHash current_block_hash = response.currentBlockHash response = self.client.query_block_by_hash( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], block_hash=current_block_hash) self.assertEqual( response['header']['previous_hash'].decode('utf-8'), previous_block_hash.hex(), "Query failed") logger.info("E2E: Query block by block hash done") def query_block(self): """ Test querying block by block number :return: """ logger.info("E2E: Query block by block number start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_block( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], block_number='0') self.assertEqual(response['header']['number'], 0, "Query failed") self.blockheader = response['header'] logger.info("E2E: Query block by block number done") def query_transaction(self): """ Test querying transaction by tx id :return: """ logger.info("E2E: Query transaction by tx id start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_info( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], ) response = self.client.query_block_by_hash( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], block_hash=response.currentBlockHash) tx_id = response.get('data').get('data')[0].get('payload').get( 'header').get('channel_header').get('tx_id') response = self.client.query_transaction( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], tx_id=tx_id) self.assertEqual( response.get('transaction_envelope').get('payload').get( 'header').get('channel_header').get('channel_id'), self.channel_name, "Query failed") logger.info("E2E: Query transaction by tx id done") def query_instantiated_chaincodes(self): """ Test query instantiated chaincodes on peer :return: """ logger.info("E2E: Query installed chaincode start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.query_instantiated_chaincodes( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org]) self.assertEqual(response.chaincodes[0].name, CC_NAME, "Query failed") self.assertEqual(response.chaincodes[0].version, CC_VERSION, "Query failed") self.assertEqual(response.chaincodes[0].path, CC_PATH, "Query failed") logger.info("E2E: Query installed chaincode done") def get_channel_config(self): """ Test get channel config on peer :return: """ logger.info("E2E: Get channel config start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = self.client.get_channel_config( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org]) self.assertEqual(response.config.sequence, 1, "Get Config Failed") logger.info("E2E: Query installed chaincode done") def get_events(self): org = 'org1.example.com' peer = self.client.get_peer('peer0.' + org) org_admin = self.client.get_user(org, 'Admin') events = self.client.get_events(org_admin, peer, self.channel_name, filtered=True, behavior='FAIL_IF_NOT_READY') self.assertEqual(len(events), 4) self.assertEqual(events[0]['number'], 0) self.assertEqual(events[0]['channel_id'], self.channel_name) filtered_transaction = events[0]['filtered_transactions'][0] self.assertEqual(filtered_transaction['tx_validation_code'], 'VALID') self.assertEqual(filtered_transaction['txid'], '') self.assertEqual(filtered_transaction['type'], 'CONFIG') self.assertEqual(events[2]['number'], 2) filtered_transaction = events[2]['filtered_transactions'][0] self.assertEqual(filtered_transaction['tx_validation_code'], 'VALID') self.assertEqual(filtered_transaction['type'], 'ENDORSER_TRANSACTION') # test missing block is present data = {'channel_id': '', 'filtered_transactions': [], 'number': 0} self.assertEqual(events[len(events) - 1], data) def test_in_sequence(self): logger.info("\n\nE2E testing started...") self.channel_create() self.channel_join() self.chaincode_install() self.chaincode_install_fail() self.chaincode_instantiate() self.chaincode_invoke() self.chaincode_query() self.query_instantiated_chaincodes() self.query_installed_chaincodes() self.query_channels() self.query_info() self.query_block_by_txid() self.query_block_by_hash() self.query_block() self.query_transaction() self.get_channel_config() self.get_events() logger.info("E2E all test cases done\n\n")
class ClientTest(unittest.TestCase): def setUp(self): self.client = Client('test/fixtures/network.json') def test_create_client(self): self.client.crypto_suite = 'my_crypto_suite' self.assertEqual(self.client.crypto_suite, 'my_crypto_suite') self.client.tx_context = 'my_tx_context' self.assertEqual(self.client.tx_context, 'my_tx_context') self.client.user_context = 'my_user_context' self.assertEqual(self.client.user_context, 'my_user_context') self.client.state_store = 'my_state_store' self.assertEqual(self.client.state_store, 'my_state_store') def test_new_channel(self): test_channel = self.client.new_channel('test') self.assertEqual(test_channel, self.client.get_channel('test')) def test_get_channel(self): test_channel = self.client.new_channel('test') self.assertEqual(test_channel, self.client.get_channel('test')) no_chain = self.client.get_channel('test1') self.assertIsNone(no_chain) def test_create_channel_missing_signatures(self): request = {} request['config'] = 'config' request['channel_name'] = 'channel_name' request['orderer'] = 'orderer' request['tx_id'] = 'tx_id' request['nonce'] = 'nonce' with self.assertRaises(ValueError): loop.run_until_complete(self.client._create_or_update_channel( request)) def test_create_channel_not_list_of_signatures(self): request = {} request['config'] = 'config' request['signatures'] = 'signatures' request['channel_name'] = 'channel_name' request['orderer'] = 'orderer' request['tx_id'] = 'tx_id' request['nonce'] = 'nonce' with self.assertRaises(ValueError): loop.run_until_complete(self.client._create_or_update_channel( request)) def test_create_channel_missing_tx_id(self): request = {} request['config'] = 'config' request['channel_name'] = 'channel_name' request['orderer'] = 'orderer' request['nonce'] = 'nonce' with self.assertRaises(ValueError): loop.run_until_complete(self.client._create_or_update_channel( request)) def test_create_channel_missing_orderer(self): request = {} request['config'] = 'config' request['channel_name'] = 'channel_name' request['tx_id'] = 'tx_id' request['nonce'] = 'nonce' with self.assertRaises(ValueError): loop.run_until_complete(self.client._create_or_update_channel( request)) def test_create_channel_missing_channel_name(self): request = { 'config': 'config', 'orderer': 'orderer', 'tx_id': 'tx_id', 'nonce': 'nonce', } with self.assertRaises(ValueError): loop.run_until_complete(self.client._create_or_update_channel( request)) def test_export_network_profile(self): network_info = { "organizations": { }, "orderers": { }, "peers": { }, "certificateAuthorities": { }, 'a': { 'b': 'a.b' } } self.client.network_info = network_info self.client.export_net_profile('test-export.json') self.client.network_info = dict() self.client.init_with_net_profile('test-export.json') self.assertEqual(network_info, self.client.network_info) self.assertEqual('a.b', self.client.get_net_info('a', 'b')) def test_init_with_net_profile(self): self.client.init_with_net_profile('test/fixtures/network.json') self.assertEqual(self.client.get_net_info('organizations', 'orderer.example.com', 'mspid'), 'OrdererMSP', "profile not match")
class E2ePrivateDataTest(BaseTestCase): def setUp(self): self.gopath_bak = os.environ.get('GOPATH', '') gopath = os.path.normpath( os.path.join(os.path.dirname(__file__), "../fixtures/chaincode")) os.environ['GOPATH'] = os.path.abspath(gopath) self.channel_tx = \ E2E_CONFIG['test-network']['channel-artifacts']['channel.tx'] self.compose_file_path = \ E2E_CONFIG['test-network']['docker']['compose_file_tls'] self.config_yaml = \ E2E_CONFIG['test-network']['channel-artifacts']['config_yaml'] self.channel_profile = \ E2E_CONFIG['test-network']['channel-artifacts']['channel_profile'] self.client = Client('test/fixtures/network.json') self.channel_name = "businesschannel" # default application channel self.user = self.client.get_user('org1.example.com', 'Admin') self.assertIsNotNone(self.user, 'org1 admin should not be None') # Boot up the testing network self.shutdown_test_env() self.start_test_env() time.sleep(1) def tearDown(self): super(E2ePrivateDataTest, self).tearDown() async def channel_create(self): """ Create an channel for further testing. :return: """ logger.info(f"E2E: Channel creation start: name={self.channel_name}") # By default, self.user is the admin of org1 response = await self.client.channel_create( 'orderer.example.com', self.channel_name, self.user, config_yaml=self.config_yaml, channel_profile=self.channel_profile) self.assertTrue(response) logger.info(f"E2E: Channel creation done: name={self.channel_name}") async def channel_join(self): """ Join peers of two orgs into an existing channels :return: """ logger.info(f"E2E: Channel join start: name={self.channel_name}") # channel must already exist when to join channel = self.client.get_channel(self.channel_name) self.assertIsNotNone(channel) orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, 'Admin') response = await self.client.channel_join( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], orderer='orderer.example.com') self.assertTrue(response) # Verify the ledger exists now in the peer node dc = docker.from_env() for peer in ['peer0', 'peer1']: peer0_container = dc.containers.get(peer + '.' + org) code, output = peer0_container.exec_run( 'test -f ' '/var/hyperledger/production/ledgersData/chains/' f'chains/{self.channel_name}' '/blockfile_000000') self.assertEqual(code, 0, "Local ledger not exists") logger.info(f"E2E: Channel join done: name={self.channel_name}") async def channel_update_anchors(self): orgs = ["org1.example.com", "org2.example.com"] anchors = [ 'test/fixtures/e2e_cli/channel-artifacts/' + msporg + 'anchors.tx' for msporg in ['Org1MSP', 'Org2MSP'] ] for org, anchortx in zip(orgs, anchors): org_admin = self.client.get_user(org, "Admin") response = await self.client.channel_update("orderer.example.com", self.channel_name, org_admin, config_tx=anchortx) self.assertTrue(response) async def chaincode_install(self): """ Test installing an example chaincode to peer """ logger.info("E2E: Chaincode install start") cc = f'/var/hyperledger/production/chaincodes/{CC_NAME}.{CC_VERSION}' # uncomment for testing with packaged_cc # create packaged chaincode before for having same id # code_package = package_chaincode(CC_PATH, CC_TYPE_GOLANG) orgs = ["org1.example.com", "org2.example.com"] for org in orgs: # simulate possible different chaincode archive based on timestamp time.sleep(2) org_admin = self.client.get_user(org, "Admin") responses = await self.client.chaincode_install( requestor=org_admin, peers=['peer0.' + org, 'peer1.' + org], cc_path=CC_PATH, cc_name=CC_NAME, cc_version=CC_VERSION, # packaged_cc=code_package ) self.assertTrue(responses) # Verify the cc pack exists now in the peer node dc = docker.from_env() for peer in ['peer0', 'peer1']: peer_container = dc.containers.get(peer + '.' + org) code, output = peer_container.exec_run(f'test -f {cc}') self.assertEqual(code, 0, "chaincodes pack not exists") logger.info("E2E: chaincode install done") async def chaincode_instantiate(self): """ Test instantiating an example chaincode to peer """ logger.info("E2E: Chaincode instantiation start") org = "org1.example.com" policy = s2d().parse("OR('Org1MSP.member', 'Org2MSP.member')") collections_config = [{ "name": "collectionMarbles", "policy": s2d().parse("OR('Org1MSP.member','Org2MSP.member')"), "requiredPeerCount": 0, "maxPeerCount": 1, "blockToLive": 1000000, "memberOnlyRead": True }, { "name": "collectionMarblePrivateDetails", "policy": s2d().parse("OR('Org1MSP.member')"), "requiredPeerCount": 0, "maxPeerCount": 1, "blockToLive": 5, "memberOnlyRead": True }] org_admin = self.client.get_user(org, "Admin") response = await self.client.chaincode_instantiate( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], args=None, cc_name=CC_NAME, cc_version=CC_VERSION, cc_endorsement_policy=policy, collections_config=collections_config, wait_for_event=True) logger.info( "E2E: Chaincode instantiation response {}".format(response)) policy = { 'version': 0, 'rule': { 'n_out_of': { 'n': 1, 'rules': [{ 'signed_by': 0 }, { 'signed_by': 1 }] } }, 'identities': [ { 'principal_classification': 'ROLE', 'principal': { 'msp_identifier': 'Org1MSP', 'role': 'MEMBER' } }, { 'principal_classification': 'ROLE', 'principal': { 'msp_identifier': 'Org2MSP', 'role': 'MEMBER' } }, ] } self.assertEqual(response['name'], CC_NAME) self.assertEqual(response['version'], CC_VERSION) self.assertEqual(response['policy'], policy) logger.info("E2E: chaincode instantiation done") async def chaincode_invoke(self): """ Test invoking an example chaincode to peer :return: """ logger.info("E2E: Chaincode invoke start") orgs = ["org1.example.com"] marble = json.dumps({ "name": "marble1", "color": "blue", "size": 35, "owner": "tom", "price": 99 }).encode() for org in orgs: org_admin = self.client.get_user(org, "Admin") response = await self.client.chaincode_invoke( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], fcn='initMarble', args=None, cc_name=CC_NAME, wait_for_event=True, wait_for_event_timeout=120, transient_map={"marble": marble}) self.assertFalse(response) # Wait for gossip private data time.sleep(5) logger.info("E2E: chaincode invoke done") async def chaincode_query(self): """ Test invoking an example chaincode to peer :return: """ logger.info("E2E: Chaincode query start") orgs = ["org1.example.com"] args = ["marble1"] res = { "color": "blue", "docType": "marble", "name": "marble1", "owner": "tom", "size": 35 } resp = { "docType": "marblePrivateDetails", "name": "marble1", "price": 99 } for org in ["org1.example.com", "org2.example.com"]: org_admin = self.client.get_user(org, "Admin") response = await self.client.chaincode_query( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], fcn="readMarble", args=args, cc_name=CC_NAME) self.assertEqual(json.loads(response), res) orgs = ["org1.example.com"] args = ["marble1"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = await self.client.chaincode_query( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], fcn="readMarblePrivateDetails", args=args, cc_name=CC_NAME) self.assertEqual(json.loads(response), resp) orgs = ["org2.example.com"] args = ["marble1"] error = "does not have read access permission" for org in orgs: org_admin = self.client.get_user(org, "Admin") with self.assertRaises(Exception) as context: response = await self.client.chaincode_query( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org], fcn="readMarblePrivateDetails", args=args, cc_name=CC_NAME) self.assertTrue(error in str(context.exception)) logger.info("E2E: chaincode query done") async def query_installed_chaincodes(self): """ Test query installed chaincodes on peer :return: """ logger.info("E2E: Query installed chaincode start") orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") responses = await self.client.query_installed_chaincodes( requestor=org_admin, peers=['peer0.' + org, 'peer1.' + org], ) self.assertEqual(responses[0].chaincodes[0].name, CC_NAME, "Query failed") self.assertEqual(responses[0].chaincodes[0].version, CC_VERSION, "Query failed") self.assertEqual(responses[0].chaincodes[0].path, CC_PATH, "Query failed") logger.info("E2E: Query installed chaincode done") async def query_instantiated_chaincodes(self): """ Test query instantiated chaincodes on peer :return: """ logger.info("E2E: Query instantiated chaincode start") orgs = ["org1.example.com", "org2.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") responses = await self.client.query_instantiated_chaincodes( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org], ) self.assertTrue(len(responses) >= 1) self.assertEqual(responses[0].chaincodes[0].name, CC_NAME, "Query failed") self.assertEqual(responses[0].chaincodes[0].version, CC_VERSION, "Query failed") self.assertEqual(responses[0].chaincodes[0].path, CC_PATH, "Query failed") logger.info("E2E: Query installed chaincode done") async def get_channel_config(self): """ Test get channel config on peer :return: """ logger.info(f"E2E: Get channel {self.channel_name} config start") orgs = ["org1.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") responses = await self.client.get_channel_config( requestor=org_admin, channel_name=self.channel_name, peers=['peer0.' + org, 'peer1.' + org]) self.assertEqual(responses[0].config.sequence, 1, "Get Config Failed") logger.info("E2E: Query installed chaincode done") async def get_channel_config_with_orderer(self, chname=SYSTEM_CHANNEL_NAME): """ Test get channel config on orderer :return: """ logger.info(f"E2E: Get channel {chname} config start") orgs = ["orderer.example.com"] for org in orgs: org_admin = self.client.get_user(org, "Admin") response = await self.client.get_channel_config_with_orderer( orderer='orderer.example.com', requestor=org_admin, channel_name=chname, ) self.assertEqual(response['config']['sequence'], '0', "Get Config Failed") logger.info(f"E2E: Get channel {chname} config done") def test_in_sequence(self): loop = asyncio.get_event_loop() logger.info("\n\nE2E testing started...") self.client.new_channel(SYSTEM_CHANNEL_NAME) loop.run_until_complete(self.get_channel_config_with_orderer()) loop.run_until_complete(self.channel_create()) loop.run_until_complete(self.channel_join()) loop.run_until_complete(self.channel_update_anchors()) loop.run_until_complete(self.get_channel_config()) loop.run_until_complete(self.chaincode_install()) loop.run_until_complete(self.query_installed_chaincodes()) loop.run_until_complete(self.chaincode_instantiate()) loop.run_until_complete(self.query_instantiated_chaincodes()) loop.run_until_complete(self.chaincode_invoke()) loop.run_until_complete(self.chaincode_query()) logger.info("E2E private data all test cases done\n\n")