Exemplo n.º 1
0
 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)
Exemplo n.º 2
0
def signin():

    if request.method == 'GET':
        return render_template('fileproof/sign-in.html')

    elif request.method == 'POST':

        password = request.form.get('password')
        if password is None or len(password) <= 0:
            return render_template('fileproof/message.html',
                                   message="ERROR: Password is missing.")
        password_digest = bbclib.get_new_id(password, include_timestamp=False)
        password_digest_str = bbclib.convert_id_to_string(password_digest)

        username = request.form.get('username')
        if username is None or len(username) <= 0:
            return render_template('fileproof/message.html',
                                   message='ERROR: User name is missing.')

        r = requests.get(PREFIX_API + '/api/user/keypair',
                         params={
                             'password_digest_str': password_digest_str,
                             'username': username
                         })
        res = r.json()

        if r.status_code != 200:
            return render_template('fileproof/message.html',
                                   message=res['message'])

        session['username'] = username
        session['user_id_str'] = res['user_id_str']

        return render_template('fileproof/message.html',
                               message="Getting keypair was success.")
Exemplo n.º 3
0
def make_client(index,
                core_port_increment,
                callback=None,
                connect_to_core=True,
                domain_id=None):
    keypair = bbclib.KeyPair()
    keypair.generate()
    clients[index]['user_id'] = bbclib.get_new_id("user_%i" % index)
    clients[index]['keypair'] = keypair
    clients[index]['app'] = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT +
                                                 core_port_increment,
                                                 multiq=False,
                                                 loglevel=loglv)
    if connect_to_core:
        if domain_id is None:
            global common_domain_id
            domain_id = common_domain_id
        clients[index]['app'].set_user_id(clients[index]['user_id'])
        clients[index]['app'].set_domain_id(domain_id)
    if callback is not None:
        clients[index]['app'].set_callback(callback)
    working_dir = ".bbc1-%i/" % (DEFAULT_CORE_PORT + core_port_increment)
    if os.path.exists(os.path.join(working_dir, "node_key.pem")):
        clients[index]['app'].set_node_key(
            os.path.join(working_dir, "node_key.pem"))
    time.sleep(1)
    print("[%i] user_id = %s" %
          (index, binascii.b2a_hex(clients[index]['user_id'])))
Exemplo n.º 4
0
 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)
Exemplo n.º 5
0
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 name 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
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
    def _register_demo(self, count):
        print("transaction_id's:")

        for i in range(count):
            txid = bbclib.get_new_id("dummy %d" % (i))
            self.client.register_in_ledger_subsystem(None, txid)
            dat = wait_check_result_msg_type(self.client.callback,
                    bbclib.MsgType.RESPONSE_REGISTER_HASH_IN_SUBSYS)
            print(bbclib.convert_id_to_string(txid))
Exemplo n.º 8
0
def default_domain_id():
    domain_id = bbclib.get_new_id("test_id_lib", include_timestamp=False)

    tmpclient = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT,
                                     multiq=False,
                                     loglevel="all")
    tmpclient.domain_setup(domain_id)
    tmpclient.callback.synchronize()
    tmpclient.unregister_from_core()
    return domain_id
Exemplo n.º 9
0
def run_client():
    client = bbc_app.BBcAppClient(port=bbc_config.DEFAULT_CORE_PORT,
                                  multiq=False,
                                  loglevel='all')
    client.set_user_id(
        bbclib.get_new_id('examples.certify_web', include_timestamp=False))
    client.set_domain_id(domain_id)
    client.set_callback(bbc_app.Callback())
    ret = client.register_to_core()
    assert ret
    return client
Exemplo n.º 10
0
    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())
Exemplo n.º 11
0
 def run_client(self):
     self.check_domain_id()
     self.client = bbc_app.BBcAppClient(port=bbc_config.DEFAULT_CORE_PORT,
                                        multiq=False,
                                        loglevel='all')
     self.client.set_user_id(
         bbclib.get_new_id('examples.certificates',
                           include_timestamp=False))
     self.client.set_domain_id(self.domain_id)
     self.client.set_callback(bbc_app.Callback())
     ret = self.client.register_to_core()
     assert ret
 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])
Exemplo n.º 13
0
 def _run_client(self, args):
     self._check_domain_id()
     if self.client is None:
         if args.ip4address:
             addr = args.ip4address
         if args.ip6address:
             addr = args.ip6address
         self.client = bbc_app.BBcAppClient(host=addr, port=args.coreport,
                 multiq=False, loglevel='all')
         self.client.set_user_id(bbclib.get_new_id('.subsystem_tool',
                 include_timestamp=False))
         self.client.set_domain_id(self.domain_id)
         self.client.set_callback(bbc_app.Callback())
         ret = self.client.register_to_core()
         assert ret
Exemplo n.º 14
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)
Exemplo n.º 15
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
Exemplo n.º 16
0
def signup():
    if request.method == 'GET':
        return render_template('fileproof/sign-up.html')

    elif request.method == 'POST':

        r = requests.get(PREFIX_API + '/api/domain')
        res = r.json()

        if r.status_code != 200:
            return render_template(
                'fileproof/message.html',
                message="ERROR: Failed to connect core node to domain(%s)." %
                res['domain_id'])

        password = request.form.get('password')
        if password is None or len(password) <= 0:
            return render_template('fileproof/message.html',
                                   message="ERROR: Password is missing.")
        password_digest = bbclib.get_new_id(password, include_timestamp=False)
        password_digest_str = bbclib.convert_id_to_string(password_digest)

        username = request.form.get('username')
        if username is None or len(username) <= 0:
            return render_template('fileproof/message.html',
                                   message='ERROR: User name is missing.')

        r = requests.post(PREFIX_API + '/api/user',
                          json={
                              'password_digest_str': password_digest_str,
                              'username': username
                          })
        res = r.json()

        if r.status_code != 200:
            return render_template('fileproof/message.html',
                                   message=res['message'])

        public_key = bbclib.convert_idstring_to_bytes(res['public_key_str'])
        private_key = bbclib.convert_idstring_to_bytes(res['private_key_str'])

        with open(PRIVATE_KEY, "wb") as fout:
            fout.write(private_key)

        with open(PUBLIC_KEY, "wb") as fout:
            fout.write(public_key)

        return redirect('/fileproof/sign-in')
Exemplo n.º 17
0
def get_document(request):
    if request.headers['Content-Type'] != 'application/json':
        abort_by_bad_content_type(request.headers['Content-Type'])

    try:
        root = dict2xml(request.get_json())

    except Exception as e:
        s = str(e).split(':')
        if s[1].endswith('understand.'):
            abort_by_bad_json_format()
        else:
            s0 = s[0].split()
            abort(int(s0[0]), description=s[1].strip())

    id = root.findtext('id', default='N/A')
    return registry_lib.Document(document_id=bbclib.get_new_id(
        id, include_timestamp=False),
                                 root=root)
Exemplo n.º 18
0
def create_new_domain():

    domain_id = bbclib.get_new_id("certificate domain")
    tmpclient = bbc_app.BBcAppClient(port=bbc_config.DEFAULT_CORE_PORT,
                                     multiq=False,
                                     loglevel="all")
    tmpclient.domain_setup(domain_id)
    tmpclient.callback.synchronize()
    tmpclient.unregister_from_core()

    print("domain_id:")
    print(bbclib.convert_id_to_string(domain_id))

    idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id)
    dic = {}

    id, keypairs = idPubkeyMap.create_user_id(num_pubkeys=1)
    dic[KEY_REGISTRY] = User(id, keypairs[0])

    id, keypairs = idPubkeyMap.create_user_id(num_pubkeys=1)
    dic[KEY_USER] = User(id, keypairs[0])

    write_dic(domain_id, dic)
Exemplo n.º 19
0
# -*- coding: utf-8 -*-
import pytest

import binascii
import sys

sys.path.extend(["../"])
from bbc1.core.bbclib import BBcTransaction, BBcEvent, BBcReference, BBcWitness, BBcRelation, BBcAsset, \
    BBcCrossRef, KeyPair, KeyType
from bbc1.core 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")
Exemplo n.º 20
0
from werkzeug.utils import secure_filename

from bbc1.core import bbclib
from bbc1.core.bbc_config import DEFAULT_CORE_PORT

MAPPING_FILE = ".bbc_id_mappings"
PUBLIC_KEY = ".public_key"
PRIVATE_KEY = ".private_key"
PREFIX_API = 'http://127.0.0.1:5000'  #FIXME to be flexible

fileproof = Blueprint('fileproof',
                      __name__,
                      static_folder='./static',
                      template_folder='./templates')

asset_group_id = bbclib.get_new_id("file_proof_asset_group",
                                   include_timestamp=False)
asset_group_id_str = bbclib.convert_id_to_string(asset_group_id)


def allowed_file(filename, allowed_ext={'txt'}):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in allowed_ext


def get_id_from_mappings(name, asset_group_id):
    if not os.path.exists(MAPPING_FILE):
        return None
    asset_group_id_str = binascii.b2a_hex(asset_group_id).decode()
    with open(MAPPING_FILE, "r") as f:
        mapping = json.load(f)
    if mapping is None:
Exemplo n.º 21
0
from examples.file_proof import file_proof
import testutils
from testutils import prepare, start_core_thread


LOGLEVEL = 'debug'
#LOGLEVEL = 'info'


core_num = 2
client_num = 2
cores = [None for i in range(core_num)]
clients = [None for i in range(client_num)]
keypairs = [None for i in range(client_num)]

domain_id = bbclib.get_new_id("file_proof_test_domain", include_timestamp=False)
asset_group_id = bbclib.get_new_id("file_proof_asset_group", include_timestamp=False)
user_ids = [bbclib.get_new_id("user_%d" % i) for i in range(client_num)]

transaction_id = None
asset_id = None
large_data = b"aaaaaaaaaa" * 200


def setup_bbc_client(port_increase=0, user_id=None):
    bbc_app_client = bbc_app.BBcAppClient(port=DEFAULT_CORE_PORT + port_increase, multiq=False, loglevel="all")
    bbc_app_client.set_user_id(user_id)
    bbc_app_client.set_domain_id(domain_id)
    bbc_app_client.set_callback(bbc_app.Callback())
    if os.path.exists(os.path.join(".bbc1-900%d" % port_increase, "node_key.pem")):
        bbc_app_client.set_node_key(os.path.join(".bbc1-900%d" % port_increase, "node_key.pem"))
Exemplo n.º 22
0
from bbc1.core import bbclib
from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility
from bbc1.core import domain0_manager
from bbc1.core.message_key_types import KeyType

LOGLEVEL = 'info'
#LOGLEVEL = 'debug'

domain_num = 3
core_per_domain = 5
core_num = domain_num * core_per_domain
client_per_core = 2
client_num = core_num * client_per_core
cores = None
clients = None
domain_ids = [bbclib.get_new_id("testdomain%d" % i) for i in range(domain_num)]
asset_group_ids = [
    bbclib.get_new_id("asset_group_%d" % i) for i in range(domain_num)
]

core_domains = [None for i in range(core_num)]
msg_processor = [None for i in range(client_num)]


def show_domain_list(domain_list):
    for dm in domain_list.keys():
        print(" Domain:", dm.hex())
        for nd in domain_list[dm]:
            print("   node_id:", nd.hex())

Exemplo n.º 23
0
    ["user_id", "BLOB"],
    ["name", "TEXT"],
    ["public_key", "BLOB"],
    ["private_key", "BLOB"],
]

IDX_USER_ID = 0
IDX_NAME = 1
IDX_PUBKEY = 2
IDX_PRIVKEY = 3

# As a matter of convenience, we need two users: the registry and its user.
NAME_REGISTRY = 'registry'
NAME_USER = '******'

domain_id = bbclib.get_new_id("certify_web_domain", include_timestamp=False)


class User:
    def __init__(self, user_id, name, keypair):
        self.user_id = user_id
        self.name = name
        self.keypair = keypair

    @staticmethod
    def from_row(row):
        return User(
            row[IDX_USER_ID], row[IDX_NAME],
            bbclib.KeyPair(privkey=row[IDX_PRIVKEY], pubkey=row[IDX_PUBKEY]))

Exemplo n.º 24
0
sys.path.extend(["../"])

from bbc1.core import bbclib
from bbc1.core import bbc_network, bbc_config, query_management, bbc_stats
from bbc1.core.topology_manager import TopologyManagerBase

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)])


class DummyCore:
Exemplo n.º 25
0
import sys
sys.path.extend(["../"])
from bbc1.core import bbclib
from bbc1.core.message_key_types import KeyType
from bbc1.core 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 = core_num * 2
cores = None
clients = None
domain_id = bbclib.get_new_id("testdomain")
asset_group_id1 = bbclib.get_new_id("asset_group_1")
asset_group_id2 = bbclib.get_new_id("asset_group_2")
asset_group_id3 = bbclib.get_new_id("asset_group_3")
user_id1 = bbclib.get_new_id("destination_id_test1")
user_id2 = bbclib.get_new_id("destination_id_test2")
transactions = list()
txid1 = bbclib.get_new_id("dummy_txid_1")
txid2 = bbclib.get_new_id("dummy_txid_2")
cross_ref_list = [[] for i in range(client_num)]
keypair1 = bbclib.KeyPair()
keypair1.generate()

msg_processor = [None for i in range(client_num)]

Exemplo n.º 26
0
"""
import argparse
import binascii
import json
import sys

from bbc1.lib import app_support_lib, id_lib, token_lib
from bbc1.core import bbc_app
from bbc1.core.bbc_config import DEFAULT_CORE_PORT
from bbc1.core import bbclib
from bbc1.core.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,
Exemplo n.º 27
0
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
Exemplo n.º 28
0
import time

import sys

sys.path.extend(["../"])
import bbc1
from bbc1.core import bbclib
from bbc1.core import ledger_subsystem, bbc_stats, bbc_network, bbc_config
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")


class DummyCore:
    class UserMessageRouting:
        def add_domain(self, domain_id):
            pass

        def remove_domain(self, domain_id):
            pass

    def __init__(self):
        self.user_message_routing = DummyCore.UserMessageRouting()
        self.stats = bbc_stats.BBcStats()
Exemplo n.º 29
0
import sys
sys.path.extend(["../"])
from bbc1.core import bbclib
from bbc1.core.message_key_types import KeyType
from bbc1.core 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 = list()
msg_processor = [None for i in range(client_num)]

asset_file_content = b"AAAAAAAAAAAAAAAAAAAAAAAAA"

asset_id_0 = None


def make_transaction(user_id, keypair):
    txobj = bbclib.make_transaction(relation_num=1, witness=True)
    bbclib.add_relation_asset(txobj,
                              relation_idx=0,
                              asset_group_id=asset_group_id,
                              user_id=user_id,
Exemplo n.º 30
0
import time

import sys
sys.path.extend(["../"])
from bbc1.core import bbclib
from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility

LOGLEVEL = 'debug'
LOGLEVEL = 'info'


core_num = 1
client_num = 1
cores = None
clients = None
domain_id = bbclib.get_new_id("testdomain")


class TestBBcAppClient(object):

    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")

        prepare(core_num=core_num, client_num=client_num)
        for i in range(core_num):
            start_core_thread(index=i)
            make_client(index=i, core_port_increment=0)
        time.sleep(1)

        global cores, clients
        cores, clients = get_core_client()