Skip to content
This repository was archived by the owner on Jan 27, 2022. It is now read-only.

Commit 4eb3ec7

Browse files
committed
fixup bridge moudle bugs
1 parent d318135 commit 4eb3ec7

File tree

9 files changed

+176
-106
lines changed

9 files changed

+176
-106
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ examples/common/python/connectors/direct/tcs_listener/__pycache__/
1212
examples/common/python/crypto/crypto.py
1313
examples/common/python/crypto/crypto_wrap.cpp
1414
examples/common/python/dist/
15+
examples/common/python/kv_storage
16+
examples/common/python/kv_storage-lock
1517
examples/common/python/tcf_examples_common.egg-info/
1618
examples/enclave_manager/build/
1719
examples/enclave_manager/dist/
@@ -28,3 +30,6 @@ tools/build/_dev/
2830

2931
# Byte-compiled / optimized / DLL files
3032
__pycache__/
33+
34+
kv_storage
35+
kv_storage-lock

config/tcs_config.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
[KvStorage]
1616
StoragePath = "config/Kv_Shared_tmp"
17-
StorageSize = "1 TB"
17+
StorageSize = "1 GB"
1818
# the remote version is of higher priority if enabled
1919
#remote_url = "http://localhost:9090"
2020

examples/common/python/connectors/ethereum/direct_registry_bridge.py

Lines changed: 67 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -14,58 +14,67 @@
1414

1515
''' this Component acts as bridge between smart contract deployed in blockchain and KV storage'''
1616

17-
import os
18-
import sys
19-
from os import urandom
20-
import argparse
21-
import time
22-
import json
23-
import logging
24-
from os.path import dirname, join, abspath
2517

2618
from shared_kv.shared_kv_interface import KvStorage
19+
from connectors.ethereum.ethereum_worker_registry_list_impl import \
20+
EthereumWorkerRegistryListImpl as registry
21+
from utility.tcf_types import RegistryStatus
22+
23+
import toml
24+
from os.path import dirname, join, abspath
25+
import logging
26+
import json
27+
import time
28+
import argparse
29+
from os import urandom, environ
30+
import sys
31+
import os
2732

2833
sys.path.insert(0, abspath(join(dirname(__file__), '..')) + '/tcf_connector/')
2934

30-
import EthereumDirectRegistry as registry
3135

3236
logger = logging.getLogger(__name__)
37+
logger.setLevel(logging.DEBUG)
3338

3439

3540
def str_list_to_bytes_list(str_list):
3641
bytes_list = []
3742
for str in str_list:
38-
bytes_list.append(str.encode())
43+
bytes_list.append(bytes.fromhex(str))
3944
return bytes_list
4045

4146

4247
def bytes_list_to_str_list(bytes_list):
4348
str_list = []
4449
for byte in bytes_list:
45-
str_list.append(byte.decode().rstrip(' \t\r\n\0'))
50+
str_list.append(byte.hex())
4651
return str_list
4752

4853

49-
def create_json_object(registry_id, registry, status):
54+
def create_json_object(org_id, registry, status):
55+
logger.debug("create_json_object id: %s, registry: %s",
56+
org_id.hex(), registry)
5057
registry_info = dict()
5158
# registry[0] contains registryType which symbolizes if registry present ( value equals to 1).
52-
registry_info["orgId"] = (registry_id.decode()).rstrip(' \t\r\n\0') # Strip off null bytes added by decode
53-
registry_info["uri"] = registry[1]
54-
registry_info["scAddress"] = (registry[2].decode()).rstrip(' \t\r\n\0')
55-
app_ids_bytes = registry[3] # list of application ids
59+
registry_info["orgId"] = org_id.hex()
60+
registry_info["uri"] = registry[0]
61+
registry_info["scAddress"] = registry[1].hex()
62+
app_ids_bytes = registry[2] # list of application ids
63+
logger.debug("app_ids_bytes %s", app_ids_bytes)
5664
app_ids_list = bytes_list_to_str_list(app_ids_bytes)
5765
registry_info["appTypeIds"] = app_ids_list
58-
registry_info["status"] = status
66+
registry_info["status"] = status.value
67+
logger.debug("registry_info %s", registry_info)
5968

6069
json_registry = json.dumps(registry_info)
61-
logger.debug("JSON serialized registry is %s", json_registry)
70+
logger.debug("JSON serialized registry %s is %s", org_id.hex(), json_registry)
6271
return json_registry
6372

6473

6574
def deserialize_json_object(json_reg_info):
6675
reg_info = json.loads(json_reg_info)
6776
uri = reg_info["uri"]
68-
sc_address = reg_info["scAddress"].encode()
77+
sc_address = bytes.fromhex(reg_info["scAddress"])
6978
app_ids_str = reg_info["appTypeIds"]
7079

7180
# Convert list of appTypeIds of type string to bytes
@@ -76,32 +85,37 @@ def deserialize_json_object(json_reg_info):
7685

7786
def sync_contract_and_lmdb(eth_direct_registry, kv_storage):
7887
# Check if all registries in smart contract are available in KvStorage, if not add them
79-
eth_lookup_result = eth_direct_registry.RegistryLookUp()
80-
eth_registry_list = eth_lookup_result[-1] # last value of lookup will be list of registry id's/org id's
88+
eth_lookup_result = eth_direct_registry.registry_lookup()
89+
# last value of lookup will be list of registry id's/org id's
90+
org_id_list = eth_lookup_result[-1]
8191

8292
logger.info("Syncing registries from Contract to KvStorage")
83-
if not eth_registry_list:
93+
if not org_id_list:
8494
logger.info("No registries available in Direct registry contract")
8595

8696
else:
87-
for eth_registry_id in eth_registry_list:
88-
eth_reg_info = eth_direct_registry.RegistryRetrieve(eth_registry_id)
89-
97+
for org_id in org_id_list:
98+
eth_reg_info = eth_direct_registry.registry_retrieve(org_id)
99+
logger.debug("eth_reg_info: %s", eth_reg_info)
90100
# Check if registry entry present in KvStorage
91-
logger.info("Check if registry with id %s present in KvStorage", eth_registry_id.decode())
92-
kv_reg_info = kv_storage.get("registries", eth_registry_id.decode().rstrip(' \t\r\n\0'))
101+
logger.info(
102+
"Check if registry with id %s present in KvStorage", org_id.hex())
103+
kv_reg_info = kv_storage.get("registries", org_id)
93104
if not kv_reg_info:
94-
logger.info("No matching registry found in KvStorage, ADDING it to KvStorage")
105+
logger.info(
106+
"No matching registry found in KvStorage, ADDING it to KvStorage")
95107
# Create JSON registry object with status 0 equivalent to SUSPENDED
96-
json_registry = create_json_object(eth_registry_id, eth_reg_info, 0)
97-
kv_storage.set("registries", eth_registry_id.decode().rstrip(' \t\r\n\0'), json_registry)
108+
json_registry = create_json_object(org_id, eth_reg_info, RegistryStatus.SUSPENDED)
109+
kv_storage.set("registries", org_id.hex(), json_registry)
98110

99111
else:
100-
logger.info("Matching registry found in KvStorage, hence ADDING")
112+
logger.info(
113+
"Matching registry found in KvStorage, hence ADDING")
101114
# Set the status of registry to ACTIVE
102115
kv_registry = json.loads(kv_reg_info)
103116
kv_registry["status"] = 1 # status = 1 implies ACTIVE
104-
kv_storage.set("registries", eth_registry_id.decode().rstrip(' \t\r\n\0'), json.dumps(kv_registry))
117+
kv_storage.set("registries", org_id.hex(),
118+
json.dumps(kv_registry))
105119

106120
logger.info("Syncing registries from KvStorage to Contract")
107121
# Check if all registries present in KvStorage are available in Smart contract, if not add them
@@ -114,21 +128,30 @@ def sync_contract_and_lmdb(eth_direct_registry, kv_storage):
114128
for kv_registry_id in kv_registry_list:
115129
kv_reg_info = kv_storage.get("registries", kv_registry_id)
116130
# Check if registry entry present in smart contract
117-
retrieve_result = eth_direct_registry.RegistryRetrieve(kv_registry_id.encode())
131+
logger.debug(
132+
"found registry_retrieve: %s from kv store", kv_registry_id)
133+
retrieve_result = eth_direct_registry.registry_retrieve(
134+
bytes.fromhex(kv_registry_id))
118135

119136
if retrieve_result[0] == 0:
120-
logger.info("Matching registry with id %s not found in Smart contract, hence ADDING", kv_registry_id)
137+
logger.info(
138+
"Matching registry with id %s not found in Smart contract, hence ADDING", kv_registry_id)
121139
reg_info = deserialize_json_object(kv_reg_info)
122140
# Add registry to smart contract and set status to ACTIVE
123-
eth_direct_registry.RegistryAdd(kv_registry_id.encode(), reg_info[0], reg_info[1], reg_info[2])
124-
eth_direct_registry.RegistrySetStatus(kv_registry_id.encode(), json.loads(kv_reg_info)["status"])
141+
eth_direct_registry.registry_add(
142+
bytes.fromhex(kv_registry_id), reg_info[0], reg_info[1], reg_info[2])
143+
eth_direct_registry.registry_set_status(
144+
bytes.fromhex(kv_registry_id), RegistryStatus.ACTIVE)
125145

126146
else:
127147
# Set status of registry to registry status in KvStorage
128-
logger.info("Matching registry %s found in Smart contract, CHANGING status", kv_registry_id)
129-
eth_direct_registry.RegistrySetStatus(kv_registry_id.encode(), json.loads(kv_reg_info)["status"])
148+
logger.info(
149+
"Matching registry %s found in Smart contract, CHANGING status", kv_registry_id)
150+
eth_direct_registry.registry_set_status(
151+
bytes.fromhex(kv_registry_id), RegistryStatus.ACTIVE) # TODO
130152

131-
logger.info("-------------- Direct Registry bridge flow complete ------------------- ")
153+
logger.info(
154+
"-------------- Direct Registry bridge flow complete ------------------- ")
132155
return
133156

134157

@@ -137,9 +160,11 @@ def main(args=None):
137160

138161
# Smart contract address is the address where smart contract is deployed.
139162
# TODO: Add mechanism to read the address from config file.
140-
141-
eth_direct_registry = registry.EthereumDirectRegistry("0x8c99670a15047248403a3E5A38eb8FBE7a12533e", \
142-
'../connectors/contracts/WorkerRegistryList.sol')
163+
tcf_home = environ.get("TCF_HOME", "../../")
164+
config_file = tcf_home + "/examples/common/python/connectors/" + "tcf_connector.toml"
165+
with open(config_file) as fd:
166+
config = toml.load(fd)
167+
eth_direct_registry = registry(config)
143168
kv_storage = KvStorage()
144169
kv_storage.open("kv_storage")
145170

examples/common/python/connectors/ethereum/ethereum_worker_registry_list_impl.py

Lines changed: 48 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,27 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import logging
1615

1716
from eth_utils.hexadecimal import is_hex
1817
import binascii
1918
from os import environ
19+
import logging
2020

2121
from connectors.interfaces.worker_registry_list_interface import WorkerRegistryListInterface
2222
from connectors.ethereum.ethereum_wrapper import EthereumWrapper
2323
from utility.tcf_types import RegistryStatus
24+
from connectors.utils import construct_message
25+
26+
logging.basicConfig(
27+
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
28+
logging.level = logging.DEBUG
2429

25-
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
2630

2731
class EthereumWorkerRegistryListImpl(WorkerRegistryListInterface):
2832
"""
2933
Implements WorkerRegistryListInterface interface
3034
"""
35+
3136
def __init__(self, config):
3237
if self.__validate(config):
3338
self.__initialize(config)
@@ -50,8 +55,8 @@ def registry_add(self, org_id, uri, sc_addr, app_type_ids):
5055
logging.info("Invalid application id {}".format(aid))
5156
return construct_message("failed", "Invalid application id")
5257

53-
txn_hash = self.__contract_instance.functions.registryAdd(org_id, uri, org_id,
54-
app_type_ids).buildTransaction(
58+
txn_hash = self.__contract_instance.functions.registryAdd(org_id, uri, sc_addr,
59+
app_type_ids).buildTransaction(
5560
{
5661
"chainId": self.__eth_client.get_channel_id(),
5762
"gas": self.__eth_client.get_gas_limit(),
@@ -61,18 +66,19 @@ def registry_add(self, org_id, uri, sc_addr, app_type_ids):
6166
tx = self.__eth_client.execute_transaction(txn_hash)
6267
return tx
6368
else:
64-
logging.error("direct registry contract instance is not initialized")
69+
logging.error(
70+
"direct registry contract instance is not initialized")
6571
return construct_message("failed", "direct registry contract instance is \
6672
not initialized")
6773

68-
6974
def registry_update(self, org_id, uri, sc_addr, app_type_ids):
7075
if (self.__contract_instance != None):
7176
if (is_hex(binascii.hexlify(org_id).decode("utf8")) == False):
7277
logging.error("Invalid Org id {}".format(org_id))
7378
return construct_message("failed", "Invalid Org id")
7479
if (sc_addr is not None and is_hex(binascii.hexlify(sc_addr).decode("utf8")) == False):
75-
logging.error("Invalid smart contract address {}".format(sc_addr))
80+
logging.error(
81+
"Invalid smart contract address {}".format(sc_addr))
7682
return construct_message("failed", "Invalid smart contract address")
7783
if (not uri):
7884
logging.error("Empty uri {}".format(uri))
@@ -83,17 +89,18 @@ def registry_update(self, org_id, uri, sc_addr, app_type_ids):
8389
return construct_message("failed", "Invalid application id")
8490

8591
txn_hash = self.__contract_instance.functions.registryUpdate(org_id, uri, sc_addr,
86-
app_type_ids).buildTransaction(
92+
app_type_ids).buildTransaction(
8793
{
8894
"chainId": self.__eth_client.get_channel_id(),
8995
"gas": self.__eth_client.get_gas_limit(),
9096
"gasPrice": self.__eth_client.get_gas_price(),
91-
"nonce": self.__eth_client.get_txn_nonce()
97+
"nonce": self.__eth_client.get_txn_nonce()
9298
})
9399
tx = self.__eth_client.execute_transaction(txn_hash)
94100
return tx
95101
else:
96-
logging.error("direct registry contract instance is not initialized")
102+
logging.error(
103+
"direct registry contract instance is not initialized")
97104
return construct_message("failed", "direct registry contract instance is \
98105
not initialized")
99106

@@ -106,59 +113,72 @@ def registry_set_status(self, org_id, status):
106113
logging.info("Invalid registry status {}".format(status))
107114
return construct_message("failed", "Invalid worker status {}".format(status))
108115
txn_hash = self.__contract_instance.functions.registrySetStatus(org_id,
109-
status.value).buildTransaction(
110-
{
111-
"chainId": self.__eth_client.get_channel_id(),
112-
"gas": self.__eth_client.get_gas_limit(),
113-
"gasPrice": self.__eth_client.get_gas_price(),
114-
"nonce": self.__eth_client.get_txn_nonce()
115-
})
116+
status.value).buildTransaction(
117+
{
118+
"chainId": self.__eth_client.get_channel_id(),
119+
"gas": self.__eth_client.get_gas_limit(),
120+
"gasPrice": self.__eth_client.get_gas_price(),
121+
"nonce": self.__eth_client.get_txn_nonce()
122+
})
116123
tx = self.__eth_client.execute_transaction(txn_hash)
117124
return tx
118125
else:
119-
logging.error("direct registry contract instance is not initialized")
126+
logging.error(
127+
"direct registry contract instance is not initialized")
120128
return construct_message("failed", "direct registry contract instance is \
121129
not initialized")
122-
130+
123131
def registry_lookup(self, app_type_id=None):
124132
if (self.__contract_instance != None):
125133
if app_type_id != None:
126134
if is_hex(binascii.hexlify(app_type_id).decode("utf8")):
127135
lookupResult = self.__contract_instance.functions.registryLookUp(
128136
app_type_id).call()
129137
else:
130-
logging.info("Invalid application type id {}".format(app_type_id))
138+
logging.info(
139+
"Invalid application type id {}".format(app_type_id))
131140
return construct_message("failed", "Invalid application type id")
132141
else:
133-
lookupResult = self.__contract_instance.functions.registryLookUp(b"").call()
142+
lookupResult = self.__contract_instance.functions.registryLookUp(
143+
b"").call()
134144
return lookupResult
135145
else:
136-
logging.error("direct registry contract instance is not initialized")
146+
logging.error(
147+
"direct registry contract instance is not initialized")
137148
return construct_message("failed", "direct registry contract instance is not initialized")
138-
149+
139150
def registry_retrieve(self, org_id):
151+
logging.info("registryRetrieve %s->%s from contract, len %s",
152+
org_id.hex(), org_id, len(org_id))
140153
if (self.__contract_instance != None):
141154
if (is_hex(binascii.hexlify(org_id).decode("utf8")) == False):
142155
logging.info("Invalid Org id {}".format(org_id))
143156
return construct_message("failed", "Invalid Org id")
144157
else:
145-
registryDetails = self.__contract_instance.functions.registryRetrieve(org_id).call()
158+
# TODO may cause panic: OverflowError: Python int too large to convert to C ssize_t
159+
registryDetails = self.__contract_instance.functions.registryRetrieve(
160+
org_id).call()
161+
logging.info("registryRetrieve %s done", org_id.hex())
146162
return registryDetails
147163
else:
148-
logging.error("direct registry contract instance is not initialized")
164+
logging.error(
165+
"direct registry contract instance is not initialized")
149166
return construct_message("failed", "direct registry contract instance is \
150167
not initialized")
151168

152169
def registry_lookup_next(self, app_type_id, lookup_tag):
153170
if (self.__contract_instance != None):
154171
if is_hex(binascii.hexlify(app_type_id).decode("utf8")):
155-
lookupResult = self.__contract_instance.functions.registryLookUpNext(app_type_id, lookup_tag).call()
172+
lookupResult = self.__contract_instance.functions.registryLookUpNext(
173+
app_type_id, lookup_tag).call()
156174
return lookupResult
157175
else:
158-
logging.info("Invalid application type id {}".format(app_type_id))
176+
logging.info(
177+
"Invalid application type id {}".format(app_type_id))
159178
return construct_message("failed", "Invalid application type id")
160179
else:
161-
logging.error("direct registry contract instance is not initialized")
180+
logging.error(
181+
"direct registry contract instance is not initialized")
162182
return construct_message("failed", "direct registry contract instance \
163183
is not initialized")
164184

0 commit comments

Comments
 (0)