def test_01_serialize(self): print("\n-----", sys._getframe().f_code.co_name, "-----") msg = { KeyType.source_node_id: bbclib.get_new_id("aaa"), KeyType.destination_node_id: bbclib.get_new_id("bbb"), KeyType.status: True, KeyType.random: int(8000).to_bytes(4, "little") } pprint.pprint(msg) global msg_data msg_data = message_key_types.make_TLV_formatted_message(msg)
def default_domain_id(): domain_id = bbclib.get_new_id("test_id_lib", include_timestamp=False) tmpclient = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT, loglevel="all") tmpclient.domain_setup(domain_id, "simple_cluster") tmpclient.callback.synchronize() tmpclient.unregister_from_core() return domain_id
def require_receiver_info_for(filename): print("Your name is [", user_name, "] and user_id is [", binascii.b2a_hex(user_id).decode(), "]") print("Please enter the receiver user_id for file %s." % filename) receiver_name = input('>> ') receiver_user_id = bbclib.get_new_id(receiver_name, include_timestamp=False) return receiver_name, receiver_user_id
def test_33_messaging(self): print("\n-----", sys._getframe().f_code.co_name, "-----") msg = "message to X" clients[0]['app'].send_message(msg, bbclib.get_new_id("xxxxx")) dat = msg_processor[0].synchronize() assert KeyType.message in dat assert dat[KeyType.reason] == b'Cannot find such user' print("recv=", dat)
def make_user(index): global users keypair = bbclib.KeyPair() keypair.generate() user_info = { 'user_id': bbclib.get_new_id("user_%i" % index), 'keypair': keypair, } users.append(user_info)
def test_02_add_node(self): print("-----", sys._getframe().f_code.co_name, "-----") domain_id = binascii.a2b_hex("0000000000000000000000000000000000000000000000000000000000000000") dconf = config.get_domain_config(domain_id) assert dconf is not None node_id_str = bbclib.convert_id_to_string(bbclib.get_new_id("testnode1")) dconf['static_nodes'][node_id_str] = [1, 2, 3] config.update_config() with open(".bbc1/config.json", "r") as f: print(f.read())
def test_11_put(self): print("-----", sys._getframe().f_code.co_name, "-----") resource = b'aaaaaa' resource_id = bbclib.get_new_id("dummy_resource_id") networkings[1].put(domain_id=domain_id, asset_group_id=asset_group_id, resource_id=resource_id, resource=resource) print("wait queue: 9") total = wait_results(9) assert total == 9
def store_proc(data, approver_id,txid=None): bbc_app_client = setup_bbc_client() store_transaction = bbclib.make_transaction_for_base_asset(asset_group_id=asset_group_id, event_num=1) store_transaction.events[0].add(mandatory_approver=approver_id, asset_group_id=asset_group_id) store_transaction.events[0].asset.add(user_id=user_id, asset_body=data) LAB_id = bbclib.get_new_id("LegalAffairsBureau", include_timestamp=False) store_transaction.events[0].add(option_approver=LAB_id) if txid: bbc_app_client.search_transaction(asset_group_id, txid) response_data = bbc_app_client.callback.synchronize() if response_data[KeyType.status] < ESUCCESS: print("ERROR: ", response_data[KeyType.reason].decode()) sys.exit(0) prev_tx = bbclib.recover_transaction_object_from_rawdata(response_data[KeyType.transaction_data]) reference = bbclib.add_reference_to_transaction(asset_group_id, store_transaction, prev_tx, 0) sig = store_transaction.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1_XY, private_key=key_pair.private_key, public_key=key_pair.public_key) store_transaction.references[0].add_signature(user_id=user_id, signature=sig) else: sig = store_transaction.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1_XY, private_key=key_pair.private_key, public_key=key_pair.public_key) store_transaction.add_signature(signature=sig) store_transaction.add_signature(user_id=user_id, signature=sig) # Get signature from LegalAffairsBureau bbc_app_client.gather_signatures(asset_group_id, store_transaction,destinations=[LAB_id]) response_data = bbc_app_client.callback.synchronize() if response_data[KeyType.status] < ESUCCESS: print("Rejected because ", response_data[KeyType.reason].decode(), "") sys.exit(0) result = response_data[KeyType.result] store_transaction.get_sig_index(result[1]) store_transaction.add_signature(user_id=result[1], signature=result[2]) store_transaction.digest() store_transaction.dump() ret = bbc_app_client.insert_transaction(asset_group_id, store_transaction) assert ret response_data = bbc_app_client.callback.synchronize() if response_data[KeyType.status] < ESUCCESS: print("ERROR: ", response_data[KeyType.reason].decode()) sys.exit(0) print("TxID: %s", binascii.b2a_hex(response_data[KeyType.transaction_id])) print("AsID: %s", binascii.b2a_hex(store_transaction.events[0].asset.asset_id)) txinfo = [store_transaction.transaction_id, store_transaction.events[0].asset.asset_id] return txinfo
def test_01_setup(self): print("\n-----", sys._getframe().f_code.co_name, "-----") key_exchange_manager.KeyExchangeManager.KEY_EXCHANGE_INVOKE_MAX_BACKOFF = 1 key_exchange_manager.KeyExchangeManager.KEY_EXCHANGE_RETRY_INTERVAL = 2 key_exchange_manager.KeyExchangeManager.KEY_REFRESH_INTERVAL = 20 global key_managers, node_ids for i in range(2): node_ids[i] = bbclib.get_new_id("node%d" % i) key_managers[0] = key_exchange_manager.KeyExchangeManager( DummyNetwork(), domain_id, node_ids[1]) key_managers[1] = key_exchange_manager.KeyExchangeManager( DummyNetwork(), domain_id, node_ids[0])
def test_13_send_message_to_invalid_user(self): print("\n-----", sys._getframe().f_code.co_name, "-----") msg = { KeyType.domain_id: domain_id, KeyType.source_user_id: users[7], KeyType.destination_user_id: bbclib.get_new_id("test_user_invalid"), KeyType.message: 200, } user_routings[3].send_message_to_user(msg) time.sleep(1) recvmsg = result_queue.get() print(recvmsg) assert KeyType.reason in recvmsg assert recvmsg[KeyType.message] == 200
def test_08_route_message_inavlid_user(self): print("-----", sys._getframe().f_code.co_name, "-----") dummy_user_id = bbclib.get_new_id("dummy_user_id") msg = { KeyType.command: 3, KeyType.query_id: 4, b'aaaaa': 1, b'bbbb': "CCCCCC from 1" } networkings[1].route_message(domain_id=domain_id, asset_group_id=asset_group_id, dst_user_id=dummy_user_id, msg_to_send=msg) total = wait_results(1) assert total == 0
def setup(): global domain_id global mint_id global idPubkeyMap global keypairs domain_id = bbclib.get_new_id("test_token_lib", include_timestamp=False) tmpclient = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT, loglevel="all") tmpclient.domain_setup(domain_id, "simple_cluster") tmpclient.callback.synchronize() tmpclient.unregister_from_core() idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id) (mint_id, keypairs) = idPubkeyMap.create_user_id(num_pubkeys=1)
def test_12_get_failure(self): print("-----", sys._getframe().f_code.co_name, "-----") resource_id = bbclib.get_new_id("dummy_resource_id") query_entry = query_management.QueryEntry( expire_after=10, callback_expire=get_test_func_failure, data={ KeyType.domain_id: domain_id, KeyType.asset_group_id: asset_group_id, KeyType.resource_id: resource_id, KeyType.resource_type: ResourceType.Transaction_data }, retry_count=3) query_entry.update(2, callback=get_test_func_success) networkings[2].get(query_entry) print("wait queue: 1") total = wait_results(1) assert total == 0
def make_client(index, core_port_increment, callback=None, connect_to_core=True, asset_group_id=None): keypair = bbclib.KeyPair() keypair.generate() clients[index]['user_id'] = bbclib.get_new_id("user_%i" % index) clients[index]['keypair'] = keypair if connect_to_core: clients[index]['app'] = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT + core_port_increment, loglevel=loglv) clients[index]['app'].set_user_id(clients[index]['user_id']) clients[index]['app'].set_asset_group_id(asset_group_id) if callback is not None: clients[index]['app'].set_callback(callback) print("[%i] user_id = %s" % (index, binascii.b2a_hex(clients[index]['user_id'])))
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import argparse import sys sys.path.append("../") from bbc1.app import bbc_app from bbc1.core.bbc_config import DEFAULT_CORE_PORT from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType domain_id = bbclib.get_new_id("test_domain", include_timestamp=False) user_id = bbclib.get_new_id("dummy_user_name") def wait_check_result_msg_type(callback, msg_type): dat = callback.synchronize() if dat[KeyType.command] != msg_type: sys.stderr.write("XXXXXX not expected result: %d <=> %d(received)\n" % (msg_type, dat[KeyType.command])) return dat def argument_parser(): argparser = argparse.ArgumentParser( description='Register/Verify transaction in the ledger subsystem.') argparser.add_argument('-4',
import sqlite3 sys.path.extend(["../../"]) from bbc1.common import bbclib from bbc1.app import bbc_app from bbc1.core.bbc_config import DEFAULT_CORE_PORT from bbc1.common.message_key_types import KeyType from bbc1.common.bbc_error import * PRIVATE_KEY = ".private_key" PUBLIC_KEY = ".public_key" dbpath = "land.sqlite" con = sqlite3.connect(dbpath) domain_id = bbclib.get_new_id("landdomain", include_timestamp=False) asset_group_id = bbclib.get_new_id("land_asset_group", include_timestamp=False) user_id = bbclib.get_new_id("LegalAffairsBureau", include_timestamp=False) key_pair = None bbc_app_client = None def asset_group_setup(): tmpclient = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT, loglevel="all") tmpclient.domain_setup(domain_id, "simple_cluster") tmpclient.callback.synchronize() tmpclient.register_asset_group(domain_id=domain_id, asset_group_id=asset_group_id) tmpclient.callback.synchronize()
# -*- coding: utf-8 -*- import pytest import sys sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.core import bbc_ledger, bbc_config from bbc1.core.bbc_ledger import ResourceType config = bbc_config.BBcConfig() ledger_manager =bbc_ledger.BBcLedger(config=config) user_id = bbclib.get_new_id("destination_id_test1") domain_id = bbclib.get_new_id("test_domain") asset_group_id = bbclib.get_new_id("asset_group_1") keypair1 = bbclib.KeyPair() keypair1.generate() transaction1 = bbclib.make_transaction_for_base_asset(asset_group_id=asset_group_id) transaction1.digest() print("**** transaction_id:", transaction1.transaction_id) class TestBBcLedger(object): def test_01_open(self): print("-----", sys._getframe().f_code.co_name, "-----") ledger_manager.add_domain(domain_id) ledger_manager.open_db(domain_id, 'transaction_db') ledger_manager.close_db(domain_id, 'transaction_db')
sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from bbc1.common.bbc_error import * from bbc1.app import bbc_app from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility LOGLEVEL = 'debug' #LOGLEVEL = 'info' core_num = 5 client_num = 5 cores = None clients = None keyname = None domain_id = bbclib.get_new_id("testdomain", include_timestamp=False) asset_group_id = bbclib.get_new_id("asset_group_1") transactions = [None for i in range(client_num)] transaction_dat = None msg_processor = [None for i in range(client_num)] large_data = "aaaaaaaaaa" * 200 config_file_content = { 'domain_auth_key': { 'use': True, 'obsolete_timeout': 300, }, }
sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from bbc1.core import bbc_network, bbc_config, query_management from bbc1.core.bbc_ledger import ResourceType LOGLEVEL = 'debug' LOGLEVEL = 'info' ticker = query_management.get_ticker() core_nodes = 10 networkings = [None for i in range(core_nodes)] nodes = [None for i in range(core_nodes)] domain_id = bbclib.get_new_id("test_domain") asset_group_id = bbclib.get_new_id("asset_group_1") users = [bbclib.get_new_id("test_user_%i" % i) for i in range(core_nodes)] result_queue = queue.Queue() sample_resource_id = bbclib.get_new_id("sample_resource_id") def get_random_data(length=16): import random source_str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' return "".join([random.choice(source_str) for x in range(length)]) def wait_results(count):
import datetime import binascii import json from datetime import datetime sys.path.extend(["../../../"]) from bbc1.common import bbclib from bbc1.app import bbc_app from bbc1.core.bbc_config import DEFAULT_CORE_PORT from bbc1.common.message_key_types import KeyType from bbc1.common.bbc_error import * PRIVATE_KEY = ".private_key" PUBLIC_KEY = ".public_key" domain_id = bbclib.get_new_id("coindomain", include_timestamp=False) asset_group_id = bbclib.get_new_id("coin_asset_group", include_timestamp=False) user_id = None key_pair = None bbc_app_client = None def asset_group_setup(): tmpclient = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT, loglevel="all") tmpclient.domain_setup(domain_id, "simple_cluster") tmpclient.callback.synchronize() tmpclient.register_asset_group(domain_id=domain_id, asset_group_id=asset_group_id) tmpclient.callback.synchronize() tmpclient.unregister_from_core() print("Domain %s and asset_group %s are created." % (binascii.b2a_hex(domain_id[:4]).decode(), binascii.b2a_hex(asset_group_id[:4]).decode()))
# -*- coding: utf-8 -*- import pytest import sys sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.core import bbc_storage, bbc_config config = bbc_config.BBcConfig() storage_manager = bbc_storage.BBcStorage(config=config) domain_ids = [bbclib.get_new_id("test_domain_%d" % i) for i in range(3)] asset_group_ids = [bbclib.get_new_id("asset_group_%d" % i) for i in range(3)] class TestBBcStorage(object): def test_0_setup(self): print("-----", sys._getframe().f_code.co_name, "-----") storage_manager.set_storage_path(domain_ids[0], asset_group_ids[0]) def test_1_put(self): print("-----", sys._getframe().f_code.co_name, "-----") ret = storage_manager.store_locally(domain_ids[0], asset_group_ids[0], b"abcdefg", b'fuawhfuawefba') assert ret def test_2_get(self): print("-----", sys._getframe().f_code.co_name, "-----") ret = storage_manager.get_locally(domain_ids[0], asset_group_ids[0], b"abcdefg") print(ret)
NAME_OF_DB = 'id_db' id_pubkey_table_definition = [ ["user_id", "BLOB"], ["public_key", "BLOB"], ["tx_id_added", "BLOB"], ["tx_id_removed", "BLOB"], ] IDX_USER_ID = 0 IDX_PUBLIC_KEY = 1 IDX_TX_ID_ADDED = 2 IDX_TX_ID_REMOVED = 3 default_namespace_id = bbclib.get_new_id(".default_namespace", include_timestamp=False) id_publickey_map_user_id = bbclib.get_new_id(".id_publickey_map", include_timestamp=False) class Directive: CMD_NONE = 0 CMD_ADD = 1 CMD_REMOVE = 2 CMD_REPLACE = 3 def __init__(self, command, public_keys): self.command = command self.public_keys = public_keys
import sys sys.path.append('.') sys.path.append('..') from bbc1.common import bbclib from bbc1.core import ledger_subsystem, bbc_stats, bbc_network, bbc_config from bbc1.core.ethereum import setup from bbc1.core.ethereum import bbc_ethereum from tests import test_bbc_ethereum DEFAULT_ETHEREUM_LOG_FILE = 'geth.log' DEFAULT_ETHEREUM_CHAIN_ID = 15 DEFAULT_ETHEREUM_GETH_PORT = 30303 domain_id1 = bbclib.get_new_id("test_domain1") domain_id2 = bbclib.get_new_id("test_domain2") default_config = { 'domains': { domain_id1.hex(): { 'use_ledger_subsystem': True, # if this items does not exist or False, ledger_subsystem will not be used 'ledger_subsystem': { 'subsystem': 'ethereum', 'max_transactions': 4096, 'max_seconds': 60 * 60, }, }, domain_id2.hex(): { 'use_ledger_subsystem':
import sys sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from bbc1.common.bbc_error import * from bbc1.app import bbc_app from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility LOGLEVEL = 'debug' #LOGLEVEL = 'info' core_num = 5 client_num = 5 cores = None clients = None domain_id = bbclib.get_new_id("testdomain") anycast_id = bbclib.get_new_id() msg_processor = [None for i in range(client_num)] class MessageProcessor(bbc_app.Callback): def __init__(self, index=0): super(MessageProcessor, self).__init__(self) self.idx = index def proc_user_message(self, dat): print("User[%d] receives message:%s" % (self.idx, dat[KeyType.message]))
import json import os import sys sys.path.extend(["../../"]) from bbc1.app import bbc_app, app_support_lib, id_lib, token_lib from bbc1.core.bbc_config import DEFAULT_CORE_PORT from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from bbc1.common.bbc_error import * F_JSON_CURRENCIES = 'payment_currencies.json' F_JSON_USERS = 'payment_users.json' domain_id = bbclib.get_new_id("payment_test_domain", include_timestamp=False) class User: def __init__(self, user_id, keypair, is_selected=False): self.user_id = user_id self.keypair = keypair self.is_selected = is_selected @staticmethod def from_dict(dic): user_id = bytes(binascii.a2b_hex(dic['user_id'])) public_key = bytes(binascii.a2b_hex(dic['public_key'])) private_key = bytes(binascii.a2b_hex(dic['private_key'])) return User(user_id,
import sys sys.path.extend(["../"]) from bbc1.core.bbc_types import ResourceType from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from testutils import prepare, start_core_thread, get_core_client, make_client LOGLEVEL = 'debug' LOGLEVEL = 'info' core_num = 3 client_num = 3 cores = None clients = None domain_id = bbclib.get_new_id("testdomain") asset_group_id = bbclib.get_new_id("asset_group_1") transaction = None txid = None user_id1 = bbclib.get_new_id("destination_id_test1") txid1 = bbclib.get_new_id("dummy_txid_1") keypair = bbclib.KeyPair() keypair.generate() result_queue = queue.Queue() def make_user(index): global users keypair = bbclib.KeyPair() keypair.generate()
if isinstance(dst_ip, ipaddress.IPv4Address): ipv4 = str(dst_ip) else: ipv6 = str(dst_ip) print("Request domain_ping to %s, %s, %d" % (ipv4, ipv6, dst_port)) bbcclient.send_domain_ping(domain_id, ipv4, ipv6, dst_port) if __name__ == '__main__': port = None parsed_args = argument_parser() if parsed_args.domain_id is None: print("### -d option is mandatory!") sys.exit(1) if parsed_args.id: value = bbclib.get_new_id(parsed_args.id, include_timestamp=False) print(bbclib.convert_id_to_string(value)) sys.exit(0) if parsed_args.timebaseid: value = bbclib.get_new_id(parsed_args.id, include_timestamp=True) print(bbclib.convert_id_to_string(value)) sys.exit(0) if parsed_args.ip4address: addr = parsed_args.ip4address if parsed_args.ip6address: addr = parsed_args.ip6address port = parsed_args.port bbcclient = bbc_app.BBcAppClient(host=addr, port=port, loglevel="all") domain_id = bbclib.convert_idstring_to_bytes(parsed_args.domain_id)
import time import queue import sys sys.path.extend(["../"]) from bbc1.core import query_management from bbc1.core import key_exchange_manager from bbc1.common import message_key_types from bbc1.common import bbclib ticker = query_management.get_ticker() msg_queue = queue.Queue() node_num = 4 domain_id = bbclib.get_new_id("test_domain") node_ids = [None for i in range(node_num)] key_managers = [None for i in range(node_num)] class DummyNetwork: def send_key_exchange_message(self, domain_id, node_id, command, pubkey, nonce, random_val, key_name): print("send KEY_EXCHANGE message") msg_queue.put( [domain_id, node_id, pubkey, nonce, random_val, key_name]) return True class TestKeyExchangeManager(object): def test_01_setup(self):
import sys sys.path.extend(["../"]) from bbc1.common import bbclib from bbc1.common.message_key_types import KeyType from bbc1.app import bbc_app from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility LOGLEVEL = 'debug' #LOGLEVEL = 'none' core_num = 5 client_num = 5 cores = None clients = None domain_id = bbclib.get_new_id("testdomain") asset_group_id = bbclib.get_new_id("asset_group_1") transactions = [None for i in range(client_num)] msg_processor = [None for i in range(client_num)] def check_insert_response(clnum, transaction_id): msg = msg_processor[clnum].synchronize() if msg[KeyType.command] == bbclib.MsgType.RESPONSE_INSERT: assert msg[KeyType.transaction_id] == transaction_id print("[%d] inserted" % clnum) elif msg[KeyType.command] == bbclib.MsgType.NOTIFY_INSERTED: assert KeyType.asset_group_ids in msg print("[%d] notification txid=%s, asset_group=%s" % (clnum, binascii.b2a_hex(msg[KeyType.transaction_id]),
# -*- coding: utf-8 -*- import pytest import binascii import sys sys.path.extend(["../"]) from bbc1.common.bbclib import BBcTransaction, BBcEvent, BBcReference, BBcWitness, BBcRelation, BBcAsset, \ BBcCrossRef, KeyPair, KeyType from bbc1.common import bbclib user_id = bbclib.get_new_id("user_id_test1") user_id2 = bbclib.get_new_id("user_id_test2") domain_id = bbclib.get_new_id("testdomain") asset_group_id = bbclib.get_new_id("asset_group_1") transaction1_id = bbclib.get_new_id("transaction_1") transaction2_id = bbclib.get_new_id("transaction_2") keypair1 = KeyPair() keypair1.generate() keypair2 = KeyPair() keypair2.generate() transaction1 = None asset1 = None asset2 = None event1 = None event2 = None transaction2 = None asset_content = b'abcdefg' print("\n") print("private_key:", binascii.b2a_hex(keypair1.private_key))