Beispiel #1
0
    def create_user_id(self, num_pubkeys=1, public_keys=None):

        keypair = bbclib.KeyPair()
        user_id = hashlib.sha256(bytes(keypair.public_key)).digest()
        # FIXME: detect collision

        initial_keypairs = []
        if public_keys is None:
            public_keys = []
            for i in range(num_pubkeys):
                new_keypair = bbclib.KeyPair()
                initial_keypairs.append(new_keypair)
                public_keys.append(new_keypair.public_key)

        directive = Directive(Directive.CMD_REPLACE, public_keys)

        tx = bbclib.make_transaction_for_base_asset(
            asset_group_id=self.namespace_id, event_num=1)

        tx.events[0].asset.add(user_id=user_id,
                               asset_body=directive.serialize())
        tx.events[0].add(mandatory_approver=user_id)
        tx.add(witness=bbclib.BBcWitness())
        tx.witness.add_witness(user_id)
        self.sign_and_insert(tx, user_id, keypair)
        return (user_id, initial_keypairs)
    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        print("domain_id =", binascii.b2a_hex(domain_id))

        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        try:
            os.mkdir(".bbc1")
        except:
            pass
        with open(os.path.join(".bbc1", keyname), "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        global msg_processor
        prepare(core_num=core_num, client_num=client_num, loglevel=LOGLEVEL)
        for i in range(core_num):
            start_core_thread(index=i,
                              core_port_increment=i,
                              p2p_port_increment=i)
            time.sleep(0.1)
            domain_setup_utility(i, domain_id)  # system administrator
        time.sleep(1)
        for i in range(client_num):
            msg_processor[i] = MessageProcessor(index=i)
            make_client(index=i,
                        core_port_increment=i,
                        callback=msg_processor[i])
        time.sleep(1)

        global cores, clients
        cores, clients = get_core_client()
Beispiel #3
0
def test_keypair_generate():
    """
    """
    keypair = bbclib.KeyPair()
    keypair.generate()
    assert (keypair.private_key_len.value == 32)
    assert (keypair.public_key_len.value == 65)
Beispiel #4
0
 def test_00_key_setup(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     keypair = bbclib.KeyPair()
     keypair.generate()
     keyname = domain_id.hex() + ".pem"
     with open(keyname, "wb") as f:
         f.write(keypair.get_private_key_in_pem())
Beispiel #5
0
def create_keypair():
    keypair = bbclib.KeyPair()
    keypair.generate()
    with open(PRIVATE_KEY, "wb") as fout:
        fout.write(keypair.private_key)
    with open(PUBLIC_KEY, "wb") as fout:
        fout.write(keypair.public_key)
    print("created private_key and public_key : %s, %s" % (PRIVATE_KEY, PUBLIC_KEY))
Beispiel #6
0
    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,
                    bbclib.KeyPair(privkey=private_key, pubkey=public_key),
                    dic['is_selected'])
Beispiel #7
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)
Beispiel #8
0
def test_keypair_pubkey():
    """
    """
    keypair = bbclib.KeyPair(type=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey)
    keypair.mk_keyobj_from_private_key()
    assert (keypair.public_key_len.value == 65)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Beispiel #9
0
    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        print("domain_id =", binascii.b2a_hex(domain_id))

        global keyname
        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = os.path.join(".bbc1", domain_id.hex() + ".pem")
        try:
            os.mkdir(".bbc1")
        except:
            pass
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        keypair_dummy = bbclib.KeyPair()
        keypair_dummy.generate()
        with open(os.path.join(".bbc1", "dummy.pem"), "wb") as f:
            f.write(keypair_dummy.get_private_key_in_pem())

        with open(os.path.join(".bbc1", "testconf.json"), "wb") as f:
            f.write(json.dumps(config_file_content).encode())

        global msg_processor
        prepare(core_num=core_num,
                client_num=client_num,
                conf_file=os.path.join(".bbc1", "testconf.json"),
                loglevel=LOGLEVEL)
        for i in range(core_num):
            start_core_thread(index=i,
                              core_port_increment=i,
                              p2p_port_increment=i,
                              use_nodekey=True)
            time.sleep(0.1)
        time.sleep(1)
        for i in range(client_num):
            msg_processor[i] = MessageProcessor(index=i)
            make_client(index=i,
                        core_port_increment=i,
                        callback=msg_processor[i])
        time.sleep(1)

        global cores, clients
        cores, clients = get_core_client()
Beispiel #10
0
    def test_06_domain_key_change(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        for i, nw in enumerate(networkings):
            nw.get_domain_keypair(domain_id)

        keypair = bbclib.KeyPair()
        keypair.generate()
        keyname = domain_id.hex() + ".pem"
        with open(keyname, "wb") as f:
            f.write(keypair.get_private_key_in_pem())

        for i, nw in enumerate(networkings):
            nw.get_domain_keypair(domain_id)
Beispiel #11
0
 def set_domain_key(self, pem_file=None):
     """
     Set domain_auth_key to this client
     :param pem_file:
     :return:
     """
     if pem_file is None:
         self.domain_keypair = None
     try:
         self.domain_keypair = bbclib.KeyPair()
         with open(pem_file, "r") as f:
             self.domain_keypair.mk_keyobj_from_private_key_pem(f.read())
     except:
         return
Beispiel #12
0
def test_keypair_pem():
    """
    """
    keypair = bbclib.KeyPair(type=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)

    pem = keypair.get_private_key_in_pem()
    assert (bytes(pem) == in_pem[:(len(in_pem) - 1)])  # ヌル終端を取り除いて比較する。

    keypair.mk_keyobj_from_private_key_pem(str(pem))  # 文字列化する。
    assert (bytes(
        keypair.private_key)[:keypair.private_key_len.value] == in_privkey)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Beispiel #13
0
def test_keypair_der():
    """
    """
    keypair = bbclib.KeyPair(type=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)

    der = keypair.get_private_key_in_der()
    assert (der == in_der)

    keypair.mk_keyobj_from_private_key_der(der)
    assert (bytes(
        keypair.private_key)[:keypair.private_key_len.value] == in_privkey)
    assert (bytes(
        keypair.public_key)[:keypair.public_key_len.value] == in_pubkey)
Beispiel #14
0
def test_map_creation_with_pubkeys(default_domain_id):

    NUM_KEYPAIRS = 3

    public_keys = []
    for i in range(NUM_KEYPAIRS):
        keypair = bbclib.KeyPair()
        public_keys.append(keypair.public_key)

    idPubkeyMap = id_lib.BBcIdPublickeyMap(default_domain_id)
    (user_id, keypairs) = idPubkeyMap.create_user_id(public_keys=public_keys)

    assert len(keypairs) == 0

    for i in range(NUM_KEYPAIRS):
        assert idPubkeyMap.is_mapped(user_id, public_keys[i]) == True
Beispiel #15
0
def replace_keypair(name, dic, file_name):
    for name0, user in dic.items():
        if name0 == name:
            keypair_old = user.keypair
            keypair = bbclib.KeyPair()
            idPubkeyMap = id_lib.BBcIdPublickeyMap(domain_id)
            idPubkeyMap.update(user.user_id,
                               public_keys_to_replace=[keypair.public_key],
                               keypair=keypair_old)
            user.keypair = keypair
            break

    write_dic(file_name, dic)
    print("public key for %s is renewed:" % (name))
    print("old:", binascii.b2a_hex(keypair_old.public_key).decode())
    print("new:", binascii.b2a_hex(keypair.public_key).decode())
Beispiel #16
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'])))
Beispiel #17
0
def sys_check(args):
    if args.command_type in ("store", "update", "verify") and \
            not os.path.exists(args.target_file):
        raise Exception("file not found : %s" % args.target_file)
    # TODO consider whether to check core accessibility
    if args.command_type != "keypair":
        if not os.path.exists(PRIVATE_KEY):
            message = "not exist private key\n"
            message += "create a key pair with keypair option"
            raise Exception(message)
        if not os.path.exists(PUBLIC_KEY):
            message = "not exist public key\n"
            message += "create a key pair with keypair option"
            raise Exception(message)
        with open(PRIVATE_KEY, "rb") as fin:
            private_key = fin.read()
        with open(PUBLIC_KEY, "rb") as fin:
            public_key = fin.read()
        global key_pair
        key_pair = bbclib.KeyPair(privkey=private_key, pubkey=public_key)
Beispiel #18
0
def test_map_update(default_domain_id):

    idPubkeyMap = id_lib.BBcIdPublickeyMap(default_domain_id)
    (user_id, keypairs) = idPubkeyMap.create_user_id(num_pubkeys=1)

    assert len(keypairs) == 1

    assert idPubkeyMap.is_mapped(user_id, keypairs[0].public_key) == True

    public_keys = []
    for i in range(3):
        keypair = bbclib.KeyPair()
        public_keys.append(keypair.public_key)

    tx = idPubkeyMap.update(user_id,
                            public_keys_to_replace=public_keys,
                            keypair=keypairs[0])

    assert idPubkeyMap.is_mapped(user_id, keypairs[0].public_key) == False
    for i in range(3):
        assert idPubkeyMap.is_mapped(user_id, public_keys[i]) == True
    def test_00_setup(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        print("domain_id =", binascii.b2a_hex(domain_id))

        prepare(core_num=core_num, client_num=client_num, loglevel=LOGLEVEL)
        for i in range(core_num):
            start_core_thread(index=i,
                              core_port_increment=i,
                              p2p_port_increment=i)
        time.sleep(1)

        global cores
        cores = testutils.cores

        for i in range(client_num):
            clients[i] = setup_bbc_client(i, user_ids[i])
            ret = clients[i].register_to_core()
            assert ret
            keypairs[i] = bbclib.KeyPair()
            keypairs[i].generate()
        time.sleep(1)
Beispiel #20
0
def test_keypair_sign_and_verify():
    """
    """
    digest = binascii.a2b_hex(
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

    keypair = bbclib.KeyPair(type=bbclib.KeyType.ECDSA_SECP256k1,
                             privkey=in_privkey,
                             pubkey=in_pubkey)
    signature = keypair.sign(digest)
    print("signature = {}".format(signature))

    ret = keypair.verify(digest, signature)
    # print("ret = {}".format(ret))
    assert (ret == 1)

    not_digest = binascii.a2b_hex("bbbbbb")

    ret = keypair.verify(not_digest, signature)
    # print("ret = {}".format(ret))
    assert (ret == 0)
Beispiel #21
0
 def get_domain_keypair(self, domain_id):
     """
     (internal use) Get domain_keys (private key and public key)
     :param domain_id:
     :return:
     """
     keyconfig = self.config.get_config().get('domain_auth_key', None)
     if keyconfig is None:
         self.domains[domain_id]['keypair'] = None
         return
     if 'use' not in keyconfig or not keyconfig['use']:
         return
     if 'directory' not in keyconfig or not os.path.exists(
             keyconfig['directory']):
         self.domains[domain_id]['keypair'] = None
         return
     domain_id_str = domain_id.hex()
     keypair = bbclib.KeyPair()
     try:
         with open(
                 os.path.join(keyconfig['directory'],
                              domain_id_str + ".pem"), "r") as f:
             keypair.mk_keyobj_from_private_key_pem(f.read())
     except:
         self.domains[domain_id]['keypair'] = None
         return
     self.domains[domain_id].setdefault('keypair', dict())
     self.domains[domain_id]['keypair'].setdefault('keys', list())
     self.domains[domain_id]['keypair']['keys'].insert(0, keypair)
     timer = self.domains[domain_id]['keypair'].setdefault('timer', None)
     if timer is None or not timer.active:
         self.domains[domain_id]['keypair'][
             'timer'] = query_management.QueryEntry(
                 expire_after=keyconfig['obsolete_timeout'],
                 data={KeyType.domain_id: domain_id},
                 callback_expire=self.delete_obsoleted_domain_keys)
     else:
         timer.update_expiration_time(keyconfig['obsolete_timeout'])
     self.domains[domain_id]['keypair']['keys'].insert(0, keypair)
Beispiel #22
0
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()
    user_info = {
        'user_id': bbclib.get_new_id("user_%i" % index),
        'keypair': keypair,
    }
    users.append(user_info)

Beispiel #23
0
def test_map_eval(default_domain_id):

    idPubkeyMap = id_lib.BBcIdPublickeyMap(default_domain_id)
    (user_id, keypairs0) = idPubkeyMap.create_user_id()

    time0 = int(time.time())
    print("\n2-second interval.")
    time.sleep(2)

    keypairs1 = []
    public_keys = []
    for i in range(3):
        keypairs1.append(bbclib.KeyPair())
        public_keys.append(keypairs1[i].public_key)

    tx = idPubkeyMap.update(user_id,
                            public_keys_to_add=public_keys,
                            keypair=keypairs0[0])

    time1 = int(time.time())
    print("2-second interval.")
    time.sleep(2)

    tx = idPubkeyMap.update(user_id,
                            public_keys_to_remove=public_keys,
                            keypair=keypairs0[0])

    time2 = int(time.time())
    print("2-second interval.")
    time.sleep(2)

    tx = idPubkeyMap.update(user_id,
                            public_keys_to_replace=public_keys,
                            keypair=keypairs0[0])

    time3 = int(time.time())

    public_keys = idPubkeyMap.get_mapped_public_keys(user_id, time3)

    assert len(public_keys) == 3

    for keypair in keypairs1:
        assert bytes(keypair.public_key) in public_keys

    assert idPubkeyMap.is_mapped(user_id, keypairs0[0].public_key,
                                 time3) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[0].public_key,
                                 time3) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[1].public_key,
                                 time3) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[2].public_key,
                                 time3) == True

    public_keys = idPubkeyMap.get_mapped_public_keys(user_id, time2)

    assert len(public_keys) == 1

    for keypair in keypairs0:
        assert bytes(keypair.public_key) in public_keys

    assert idPubkeyMap.is_mapped(user_id, keypairs0[0].public_key,
                                 time2) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[0].public_key,
                                 time2) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[1].public_key,
                                 time2) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[2].public_key,
                                 time2) == False

    public_keys = idPubkeyMap.get_mapped_public_keys(user_id, time1)

    assert len(public_keys) == 4

    for keypair in keypairs0:
        assert bytes(keypair.public_key) in public_keys
    for keypair in keypairs1:
        assert bytes(keypair.public_key) in public_keys

    assert idPubkeyMap.is_mapped(user_id, keypairs0[0].public_key,
                                 time1) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[0].public_key,
                                 time1) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[1].public_key,
                                 time1) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[2].public_key,
                                 time1) == True

    public_keys = idPubkeyMap.get_mapped_public_keys(user_id, time0)

    assert len(public_keys) == 1

    for keypair in keypairs0:
        assert bytes(keypair.public_key) in public_keys

    assert idPubkeyMap.is_mapped(user_id, keypairs0[0].public_key,
                                 time0) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[0].public_key,
                                 time0) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[1].public_key,
                                 time0) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[2].public_key,
                                 time0) == False

    idPubkeyMap._BBcIdPublickeyMap__clear_local_database(user_id)
    print("cleared local database entries for the user for reconstruction.")

    public_keys = idPubkeyMap.get_mapped_public_keys(user_id)

    assert len(public_keys) == 3

    for keypair in keypairs1:
        assert bytes(keypair.public_key) in public_keys

    assert idPubkeyMap.is_mapped(user_id, keypairs0[0].public_key) == False
    assert idPubkeyMap.is_mapped(user_id, keypairs1[0].public_key) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[1].public_key) == True
    assert idPubkeyMap.is_mapped(user_id, keypairs1[2].public_key) == True
Beispiel #24
0
    transaction_id = get_transaction.transaction_id
    transaction_info = store_proc(data, approver_id=binascii.unhexlify(new_owner),txid=transaction_id)
    bbc_app_client.send_message(transaction_info, asset_group_id, binascii.unhexlify(new_owner))
    print("Transfer is done.....")

if __name__ == '__main__':
    if(not os.path.exists(PRIVATE_KEY) and not os.path.exists(PUBLIC_KEY)):
        create_keypair()
    with open(PRIVATE_KEY, "rb") as fin:
        private_key = fin.read()
    with open(PUBLIC_KEY, "rb") as fin:
        public_key = fin.read()

    asset_group_setup()

    key_pair = bbclib.KeyPair(privkey=private_key, pubkey=public_key)
    user_id = bbclib.get_new_id(str(binascii.b2a_hex(key_pair.public_key)), include_timestamp=False)
    print("welcome to sample coin manage!")
    print("Your id: %s" % binascii.b2a_hex(user_id))
    print("Type command(help to see command list)")
    while(True):
        command = input('>> ')
        if command == "help":
            print("generate - generate coin")
            print("get - get coin info")
            print("send - send coin")
            print("recieve - wait for recieve coin")
            print("exit - exit coin manage")
        elif command == "generate":
            print("Type price generate coin")
            address = input('>> ')
Beispiel #25
0
import pprint
import sys
sys.path.extend(["../"])
from bbc1.common import bbclib
from bbc1.core import bbc_stats
from bbc1.core.data_handler import DataHandler

user_id1 = bbclib.get_new_id("destination_id_test1")
user_id2 = bbclib.get_new_id("destination_id_test2")
domain_id = bbclib.get_new_id("test_domain")
asset_group_id1 = bbclib.get_new_id("asset_group_1")
asset_group_id2 = bbclib.get_new_id("asset_group_2")
txid1 = bbclib.get_new_id("dummy_txid_1")
txid2 = bbclib.get_new_id("dummy_txid_2")
keypair1 = bbclib.KeyPair()
keypair1.generate()

transactions = list()

data_handler = None
config = {
    "domains": {
        bbclib.convert_id_to_string(domain_id): {
            "storage": {
                "type": "internal",
            },
            "db": {
                "db_type":
                "mysql",
                "db_name":