Exemplo n.º 1
0
    def proc_cmd_sign_request(self, dat):
        self.logger.info(
            "[%d] Recv SIGN_REQUEST from %s" %
            (self.idx, binascii.b2a_hex(dat[KeyType.source_user_id])))
        if KeyType.transactions not in dat:
            self.logger.warn("message needs to include referred transactions")
            return
        txobj = bbclib.BBcTransaction()
        txobj.deserialize(dat[KeyType.transaction_data])

        objs = dict()
        for txid, txdata in dat[KeyType.transactions].items():
            txo = bbclib.BBcTransaction()
            txo.deserialize(txdata)
            objs[txid] = txo

        for i, reference in enumerate(txobj.references):
            event = objs[reference.transaction_id].events[
                reference.event_index_in_ref]
            if clients[self.idx]['user_id'] in event.mandatory_approvers:
                signature = txobj.sign(keypair=clients[self.idx]['keypair'])
                clients[self.idx]['app'].sendback_signature(
                    dat[KeyType.source_user_id], txobj.transaction_id, i,
                    signature)
                return
Exemplo n.º 2
0
 def test_10_search_transaction(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     transactions[0] = bbclib.BBcTransaction()
     transactions[0].deserialize(transaction_dat)
     print("find txid=", binascii.b2a_hex(transactions[0].transaction_id))
     clients[1]['app'].search_transaction(transactions[0].transaction_id)
     dat = msg_processor[1].synchronize()
     assert dat[KeyType.status] == 0
     assert KeyType.transaction_data in dat
     txobj = bbclib.BBcTransaction(
         deserialize=dat[KeyType.transaction_data])
     assert txobj.transaction_id == transactions[0].transaction_id
Exemplo n.º 3
0
def chown(new_owner, asid):
    asset = json.loads(get_landdata(asid).decode("UTF-8"))
    if asset["owner"] != binascii.b2a_hex(user_id).decode("UTF-8"):
        print("Owner of this asset is not you")
        return 0
    asset["owner"] = new_owner
    asset["date"] = datetime.now().strftime('%s')
    data = json.dumps(asset)

    bbc_app_client = setup_bbc_client()
    asid = binascii.unhexlify(asid)
    ret = bbc_app_client.search_transaction_with_condition(
        asset_group_id, asid)
    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)
    get_transaction = bbclib.BBcTransaction()
    get_transaction.deserialize(response_data[KeyType.transactions][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,
                                binascii.unhexlify(new_owner))
    print("Transfer is done.....")
Exemplo n.º 4
0
 def test_01_setup(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     global data_handler
     dummycore = DummyCore()
     conf = config["domains"][bbclib.convert_id_to_string(domain_id)]
     data_handler = DataHandler(networking=dummycore.networking, config=conf, workingdir="testdir", domain_id=domain_id)
     global transactions
     for i in range(10):
         txobj = bbclib.BBcTransaction()
         evt = bbclib.BBcEvent()
         evt.asset_group_id = asset_group_id1
         evt.asset = bbclib.BBcAsset()
         evt.asset.add(user_id=user_id1, asset_body=b'aaaaaa')
         rtn = bbclib.BBcRelation()
         rtn.asset_group_id = asset_group_id2
         rtn.asset = bbclib.BBcAsset()
         rtn.asset.add(user_id=user_id2, asset_body=b'bbbbbb', asset_file=b'cccccccccc%d' % i)
         ptr = bbclib.BBcPointer()
         ptr.add(transaction_id=txid1)
         rtn.add(pointer=ptr)
         if i > 0:
             ptr = bbclib.BBcPointer()
             ptr.add(transaction_id=transactions[-1].transaction_id)
             rtn.add(pointer=ptr)
         wit = bbclib.BBcWitness()
         txobj.add(event=evt, relation=rtn, witness=wit)
         wit.add_witness(user_id1)
         sig = txobj.sign(private_key=keypair1.private_key, public_key=keypair1.public_key)
         txobj.add_signature(user_id=user_id1, signature=sig)
         txobj.digest()
         transactions.append(txobj)
Exemplo n.º 5
0
    def _receive_transaction_data_from_others(self, dat):
        """Receive transaction data from other core_nodes and check its validity

        Args:
            dat (dict): received message
        """
        #print("_receive_transaction_data_from_others:")
        if KeyType.transaction_data not in dat or KeyType.transaction_id not in dat or KeyType.nonce not in dat:
            return
        if dat[KeyType.nonce] not in self.requesting_list:
            return
        asset_files = dict()
        if KeyType.all_asset_files in dat:
            asset_files = dat[KeyType.all_asset_files]
        txobj = bbclib.BBcTransaction(deserialize=dat[KeyType.transaction_data])
        if txobj.transaction_data is None:
            return

        txobj_is_valid, valid_assets, invalid_assets = bbclib.validate_transaction_object(txobj, asset_files)
        if txobj_is_valid:
            self.stats.update_stats_increment("transaction", "success_repair", 1)
            for idx in range(len(self.data_handler.db_adaptors)):
                self.data_handler.restore_transaction_data(db_num=idx, transaction_id=txobj.transaction_id, txobj=txobj)
            add_info = {
                "repaired_by": dat[KeyType.source_node_id].hex(),
                "repaired_at": int(time.time())
            }
            self.requesting_list[dat[KeyType.nonce]].update(add_info)
            self._output_log(self.requesting_list[dat[KeyType.nonce]])
            del self.requesting_list[dat[KeyType.nonce]]
def prepare_transaction(asset_group,
                        client,
                        datnum,
                        txid_pointer=None,
                        no_cross_ref=False):
    user_id = client['user_id']
    kp = client['keypair']
    txobj = bbclib.BBcTransaction()
    rtn = bbclib.BBcRelation()
    asset = bbclib.BBcAsset()
    asset.add(user_id=user_id, asset_body=b'data=%d' % datnum)
    rtn.add(asset_group_id=asset_group, asset=asset)
    if txid_pointer is not None:
        ptr = bbclib.BBcPointer()
        ptr.add(transaction_id=txid_pointer)
        rtn.add(pointer=ptr)
    wit = bbclib.BBcWitness()
    txobj.add(relation=rtn, witness=wit)
    wit.add_witness(user_id)
    if not no_cross_ref:
        client['app'].include_cross_ref(txobj)
    sig = txobj.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1, keypair=kp)
    txobj.add_signature(user_id=user_id, signature=sig)
    txobj.digest()
    return txobj
Exemplo n.º 7
0
    def remove(self, transaction_id, txobj=None, db_num=-1):
        """Delete all data regarding the specified transaction_id

        This method requires either transaction_id or txobj.

        Args:
            transaction_id (bytes): target transaction_id
            txobj (BBcTransaction): transaction object to remove
            db_num (int): index of DB if multiple DBs are used
        """
        if transaction_id is None:
            return
        if txobj is None:
            txdata = self.exec_sql(
                sql="SELECT * FROM transaction_table WHERE transaction_id = %s"
                % self.db_adaptors[0].placeholder,
                args=(transaction_id, ))
            txobj = bbclib.BBcTransaction(deserialize=txdata[0][1])
        elif txobj.transaction_id != transaction_id:
            return

        if db_num == -1 or db_num >= len(self.db_adaptors):
            for i in range(len(self.db_adaptors)):
                self._remove_transaction(txobj, i)
        else:
            self._remove_transaction(txobj, db_num)
Exemplo n.º 8
0
    def test_07_1_insert_transaction(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        global transaction
        transaction = bbclib.BBcTransaction()
        rtn = bbclib.BBcRelation()
        rtn.asset_group_id = asset_group_id
        rtn.asset = bbclib.BBcAsset()
        rtn.asset.add(user_id=user_id1, asset_body=b'bbbbbb', asset_file=b'cccccccccc')
        ptr = bbclib.BBcPointer()
        ptr.add(transaction_id=txid1)
        rtn.add(pointer=ptr)
        wit = bbclib.BBcWitness()
        transaction.add(relation=rtn, witness=wit)
        wit.add_witness(user_id1)
        sig = transaction.sign(private_key=keypair.private_key, public_key=keypair.public_key)
        transaction.add_signature_object(user_id=user_id1, signature=sig)
        transaction.digest()
        asset_files = {
            transaction.relations[0].asset.asset_id: transaction.relations[0].asset.asset_file,
        }
        ret = cores[0].insert_transaction(domain_id, bbclib.serialize(transaction), asset_files)
        assert ret[KeyType.transaction_id] == transaction.transaction_id

        ret = cores[0]._search_transaction_by_txid(domain_id, transaction.transaction_id)
        assert ret is not None
        assert len(ret[KeyType.all_asset_files]) == 1
        print(ret)

        print("-- wait 2 seconds --")
        time.sleep(2)
Exemplo n.º 9
0
def verify_file(file):
    fileinfo = get_id_from_mappings(os.path.basename(file), asset_group_id)
    if fileinfo is None:
        print("Not exists in local mapping cache. So, asset_id is not known...")
        sys.exit(1)

    bbc_app_client = setup_bbc_client()
    ret = bbc_app_client.search_transaction_with_condition(asset_group_id=asset_group_id, asset_id=fileinfo["asset_id"])
    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)

    transaction = bbclib.BBcTransaction(deserialize=response_data[KeyType.transactions][0])
    digest = transaction.digest()
    ret = transaction.signatures[0].verify(digest)
    if not ret:
        print("Transaction data is invalid.")
        sys.exit(1)
    with open(file, "rb") as fin:
        data = fin.read()

    file_digest = hashlib.sha256(data).digest()
    if file_digest == transaction.relations[0].asset.asset_file_digest:
        print("%s is valid" % file)
    else:
        print("%s is invalid" % file)
    print("done verify %s" % os.path.basename(file))
    print("Content of the transaction:::")
    print(transaction)
Exemplo n.º 10
0
def get_file(file):
    fileinfo = get_id_from_mappings(os.path.basename(file), asset_group_id)
    if fileinfo is None:
        print("Not exists in local mapping cache. So, asset_id is not known...")
        sys.exit(1)

    bbc_app_client = setup_bbc_client()
    ret = bbc_app_client.search_transaction_with_condition(asset_group_id=asset_group_id, asset_id=fileinfo["asset_id"])
    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)

    get_transaction = bbclib.BBcTransaction(deserialize=response_data[KeyType.transactions][0])
    if KeyType.all_asset_files in response_data:
        asset_file_dict = response_data[KeyType.all_asset_files]
        asset_id = get_transaction.relations[0].asset.asset_id
        data = asset_file_dict[asset_id]
    else:
        data = get_transaction.relations[0].asset.asset_body
    out_file_name = file
    if os.path.exists(out_file_name):
        current_datetime = datetime.datetime.now()
        time_str = current_datetime.strftime('_%Y%m%d%H%M%S')
        out_file_name += time_str
    with open(out_file_name, "wb") as outfile:
        outfile.write(data)
    print("done get %s" % out_file_name)
Exemplo n.º 11
0
    def set_mint_data(self,
                      index,
                      asset_body,
                      update=False,
                      keypair=None,
                      idPublickeyMap=None):
        store_id = self.store_ids[index]

        if update:
            self.app.search_transaction_with_condition(
                asset_group_id=self.mint_id, user_id=store_id)
            res = self.app.callback.synchronize()
            if res[KeyType.status] >= ESUCCESS:
                reftx = bbclib.BBcTransaction(
                    deserialize=res[KeyType.transactions][0])
        else:
            reftx = None

        tx = bbclib.make_transaction_for_base_asset(
            asset_group_id=self.mint_id, event_num=1)
        tx.events[0].asset.add(user_id=store_id, asset_body=asset_body)
        tx.events[0].add(mandatory_approver=self.mint_id)
        if reftx is None:
            tx.add(witness=bbclib.BBcWitness())
            tx.witness.add_witness(self.mint_id)
        else:
            bbclib.add_reference_to_transaction(self.mint_id, tx, reftx, 0)

        if keypair is None:
            return tx

        return self.sign_and_insert(tx, self.mint_id, keypair, idPublickeyMap)
Exemplo n.º 12
0
def prepare_transactions():
    global transactions
    for i in range(client_num*2):
        txobj = bbclib.BBcTransaction()
        evt = bbclib.BBcEvent()
        evt.asset_group_id = asset_group_id1
        evt.asset = bbclib.BBcAsset()
        evt.asset.add(user_id=user_id1, asset_body=b'aaaaaa')
        rtn = bbclib.BBcRelation()
        rtn.asset_group_id = asset_group_id2
        rtn.asset = bbclib.BBcAsset()
        rtn.asset.add(user_id=user_id2, asset_body=b'bbbbbb', asset_file=b'cccccccccc%d' % i)
        ptr = bbclib.BBcPointer()
        ptr.add(transaction_id=txid1)
        rtn.add(pointer=ptr)
        rtn2 = bbclib.BBcRelation()
        rtn2.asset_group_id = asset_group_id3
        rtn2.asset = bbclib.BBcAsset()
        rtn2.asset.add(user_id=user_id2, asset_body=b'cccccc')
        if i > 0:
            ptr = bbclib.BBcPointer()
            ptr.add(transaction_id=transactions[-1].transaction_id)
            rtn.add(pointer=ptr)
        wit = bbclib.BBcWitness()
        if i % 2 == 0:
            txobj.add(event=evt, relation=[rtn, rtn2], witness=wit)
        else:
            txobj.add(event=evt, relation=rtn, witness=wit)
        wit.add_witness(user_id1)
        sig = txobj.sign(private_key=keypair1.private_key, public_key=keypair1.public_key)
        txobj.add_signature(user_id=user_id1, signature=sig)
        txobj.digest()
        transactions.append(txobj)
Exemplo n.º 13
0
 def test_19_search_asset(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     clients[0]['app'].search_transaction_with_condition(
         asset_group_id=asset_group_id,
         asset_id=transactions[0].events[1].asset.asset_id)
     dat = msg_processor[0].synchronize()
     assert KeyType.transactions in dat
     txobj = bbclib.BBcTransaction(deserialize=dat[KeyType.transactions][0])
     assert txobj.transaction_id == transactions[0].transaction_id
Exemplo n.º 14
0
def recive():
    bbc_app_client = setup_bbc_client()
    print("Waiting for the message of chown land...")
    recvdat = bbc_app_client.callback.synchronize()
    transaction = bbclib.BBcTransaction()
    transaction.deserialize(recvdat[KeyType.transaction_data])
    print(transaction)
    data = json.loads(transaction.events[0].asset.asset_body)
    if transaction.references:
        print("TX has reference...")
        sql = "select * from land where reftx like (?)"
        cur.execute(
            sql,
            (binascii.hexlify(transaction.references[0].transaction_id), ))
        list = cur.fetchall()
        if len(list) != 0:
            print("Ref tx has alredy been referenced")
            bbc_app_client.sendback_denial_of_sign(
                recvdat[KeyType.source_user_id], transaction.transaction_id,
                "Ref tx has alredy been referenced")
            return 0
        else:
            print("Ref tx has not been referenced.")
            sql = "select * from land where txid like (?)"
            cur.execute(
                sql,
                (binascii.hexlify(transaction.references[0].transaction_id), ))
            list = cur.fetchall()
            if len(list) == 0:
                print("ref tx is not found")
                bbc_app_client.sendback_denial_of_sign(
                    recvdat[KeyType.source_user_id],
                    transaction.transaction_id, "Ref Tx is not found")
                return 0
            else:
                print("Ref is correct, insert tx to our DB.")
                sql = u"insert into land(asid,txid,place,owner,reftx) values (?, ?, ?, ?, ?)"
                con.execute(
                    sql,
                    (binascii.hexlify(transaction.events[0].asset.asset_id),
                     binascii.hexlify(transaction.transaction_id),
                     data["place"], data["owner"],
                     binascii.hexlify(
                         transaction.references[0].transaction_id)))
                con.commit()
    else:
        print("This tx is land registration tx.")
        sql = u"insert into land(asid,txid,place,owner,reftx) values (?, ?, ?, ?, ?)"
        con.execute(sql,
                    (binascii.hexlify(transaction.events[0].asset.asset_id),
                     binascii.hexlify(transaction.transaction_id),
                     data["place"], data["owner"], None))
        con.commit()

    signature = transaction.sign(keypair=key_pair)
    bbc_app_client.sendback_signature(recvdat[KeyType.source_user_id],
                                      transaction.transaction_id, 0, signature)
Exemplo n.º 15
0
 def proc_cmd_sign_request(self, dat):
     self.logger.debug(
         "[%i] Recv SIGN_REQUEST from %s" %
         (self.idx, binascii.b2a_hex(dat[KeyType.source_user_id])))
     txobj = bbclib.BBcTransaction()
     txobj.deserialize(dat[KeyType.transaction_data])
     signature = txobj.sign(keypair=clients[self.idx]['keypair'])
     clients[self.idx]['app'].sendback_signature(
         dat[KeyType.source_user_id], txobj.transaction_id, signature)
Exemplo n.º 16
0
    def get_mint_data(self, index):
        store_id = self.store_ids[index]

        self.app.search_transaction_with_condition(asset_group_id=self.mint_id,
                                                   user_id=store_id)
        res = self.app.callback.synchronize()
        if res[KeyType.status] < ESUCCESS:
            raise ValueError('not found')
        tx = bbclib.BBcTransaction(deserialize=res[KeyType.transactions][0])
        return tx.events[0].asset.asset_body
Exemplo n.º 17
0
 def test_21_search_transaction_by_userid(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     clients[0]['app'].search_transaction_with_condition(
         asset_group_id=asset_group_id, user_id=clients[0]['user_id'])
     dat = wait_check_result_msg_type(
         msg_processor[0], bbclib.MsgType.RESPONSE_SEARCH_WITH_CONDITIONS)
     assert dat[KeyType.status] == ESUCCESS
     assert KeyType.transactions in dat
     transaction_data = dat[KeyType.transactions][0]
     txobj = bbclib.BBcTransaction(deserialize=transaction_data)
     print(txobj)
Exemplo n.º 18
0
 def proc_resp_search_asset(self, dat):
     if KeyType.transaction_data in dat:
         self.logger.info("OK: Asset [%s] is found." % binascii.b2a_hex(dat[KeyType.asset_id]))
         tx_obj = bbclib.BBcTransaction(deserialize=dat[KeyType.transaction_data])
         for evt in tx_obj.events:
             if evt.asset.asset_body_size > 0:
                 self.logger.info(" [%s] asset_body --> %s" % (binascii.b2a_hex(evt.asset.asset_id[:4]),
                                                               evt.asset.asset_body))
     else:
         self.logger.info("NG.....")
     self.queue.put(dat)
Exemplo n.º 19
0
 def take_tx(self, tx_id):
     if self.db_online is False:
         return None
     rows = self.db.exec_sql(
         self.domain_id, NAME_OF_DB,
         'select tx from token_tx_id_table where tx_id=?', tx_id)
     if len(rows) <= 0:
         return None
     tx = bbclib.BBcTransaction()
     tx.deserialize(rows[0][0])
     self.db.exec_sql(self.domain_id, NAME_OF_DB,
                      'delete from token_tx_id_table where tx_id=?', tx_id)
     return tx
 def test_04_search_transaction_direction_backward(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     clients[0]['app'].traverse_transactions(transactions1[1].transaction_id, direction=1, hop_count=3)
     dat = clients[0]['app'].callback.synchronize()
     assert dat[KeyType.status] == 0
     assert KeyType.transaction_tree in dat
     assert len(dat[KeyType.transaction_tree]) == 2
     asset_bodies = list()
     for i, txtree in enumerate(dat[KeyType.transaction_tree]):
         for txdat in txtree:
             txobj = bbclib.BBcTransaction(deserialize=txdat)
             asset_body = txobj.relations[0].asset.asset_body
             print("[%d] asset=%s" % (i, asset_body))
             asset_bodies.append(asset_body)
     assert b'transaction1_1' in asset_bodies
     assert b'transaction1_0' in asset_bodies
 def test_07_search_transaction_direction_forward(self):
     print("\n-----", sys._getframe().f_code.co_name, "-----")
     clients[0]['app'].traverse_transactions(transactions2[4].transaction_id, direction=0, hop_count=10)
     dat = clients[0]['app'].callback.synchronize()
     assert dat[KeyType.status] == 0
     assert KeyType.transaction_tree in dat
     assert KeyType.all_included in dat and not dat[KeyType.all_included]
     print("*Expected sequences: 4-5-6-7-8, 4-5-9-10-11-12-13-14 (total txobj count=11)")
     assert len(dat[KeyType.transaction_tree]) == 8   # "4-5-9-10-11-12-13-14"
     asset_bodies = list()
     for i, txtree in enumerate(dat[KeyType.transaction_tree]):
         for txdat in txtree:
             txobj = bbclib.BBcTransaction(deserialize=txdat)
             asset_body = txobj.events[0].asset.asset_body
             print("[%d] asset=%s" % (i, asset_body))
             asset_bodies.append(asset_body)
Exemplo n.º 22
0
def get_txid_from_asid(asset_group, asid):
    if asset_group == land_asset_group:
        bbc_app_client = setup_bbc_client(land_domain_id)
    elif asset_group == coin_asset_group:
        bbc_app_client = setup_bbc_client(coin_domain_id)
    asid = binascii.unhexlify(asid)
    ret = bbc_app_client.search_transaction_with_condition(asset_group, asid)
    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)
    get_transaction = bbclib.BBcTransaction()
    get_transaction.deserialize(response_data[KeyType.transactions][0])
    transaction_id = get_transaction.transaction_id
    return transaction_id
Exemplo n.º 23
0
def pick_valid_transaction_info(received_data=None, bbc_app_client=None):
    transaction = bbclib.BBcTransaction()
    transaction.deserialize(received_data[KeyType.transaction_data])
    asset_files = received_data[KeyType.all_asset_files]
    asid = transaction.relations[0].asset.asset_id
    assert asid in asset_files
    file_to_obtain = asset_files[asid]
    file_digest = hashlib.sha256(file_to_obtain).digest()
    print("----------------[Receiver]----------------")
    print(
        "File digest written in the transaction data:  ",
        binascii.b2a_hex(
            transaction.relations[0].asset.asset_file_digest).decode())
    print("File digest calculated from the received file:",
          binascii.b2a_hex(file_digest).decode())
    print("------------------------------------------")
    return transaction, received_data[KeyType.source_user_id]
Exemplo n.º 24
0
def get_landdata(asid):
    bbc_app_client = setup_bbc_client()
    asid = binascii.unhexlify(asid)
    ret = bbc_app_client.search_transaction_with_condition(
        asset_group_id, asid)
    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)
    get_transaction = bbclib.BBcTransaction()
    get_transaction.deserialize(response_data[KeyType.transactions][0])

    retdata = get_transaction.events[0].asset.asset_body
    refdata = get_transaction.references
    print("get: %s" % retdata)
    print("ref: %s" % refdata)
    return retdata
Exemplo n.º 25
0
    def proc_cmd_sign_request(self, dat):
        source_user_id = dat[KeyType.source_user_id]

        if self.keypair is None:
            self.mint.app.sendback_denial_of_sign(source_user_id,
                                                  'keypair is unset')

        tx = bbclib.BBcTransaction()
        tx.deserialize(dat[KeyType.transaction_data])

        # FIXME: check validity

        sig = self.mint.store.sign(tx, self.mint.user_id, self.keypair)
        tx.digest()

        self.mint.store.reserve_referred_utxos(tx)
        self.mint.store.push_tx(tx.transaction_id, tx)
        self.mint.app.sendback_signature(source_user_id, tx.transaction_id, -1,
                                         sig)
Exemplo n.º 26
0
def store_proc(data, approver_id, txid=None):
    bbc_app_client = setup_bbc_client()
    transaction = bbclib.make_transaction(event_num=1)
    transaction.events[0].add(mandatory_approver=approver_id)
    bbclib.add_event_asset(transaction,
                           event_idx=0,
                           asset_group_id=asset_group_id,
                           user_id=user_id,
                           asset_body=data)
    if txid:
        bbc_app_client.search_transaction(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.BBcTransaction(
            deserialize=response_data[KeyType.transaction_data])
        reference = bbclib.add_reference_to_transaction(
            transaction, asset_group_id, prev_tx, 0)
        sig = transaction.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                               private_key=key_pair.private_key,
                               public_key=key_pair.public_key)
        transaction.references[0].add_signature(user_id=user_id, signature=sig)
    else:
        sig = transaction.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                               private_key=key_pair.private_key,
                               public_key=key_pair.public_key)
        transaction.add_signature(signature=sig)
    transaction.digest()
    print(transaction)

    ret = bbc_app_client.insert_transaction(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(transaction.events[0].asset.asset_id))

    txinfo = [transaction.transaction_id, transaction.events[0].asset.asset_id]
    return txinfo
Exemplo n.º 27
0
    def test_11_verify_file(self):
        print("\n-----", sys._getframe().f_code.co_name, "-----")
        # -- verify by user_1
        clients[1].search_transaction_with_condition(
            asset_group_id=asset_group_id, asset_id=asset_id)
        response_data = clients[1].callback.synchronize()
        assert response_data[KeyType.status] == ESUCCESS

        txobj = bbclib.BBcTransaction(
            deserialize=response_data[KeyType.transactions][0])
        digest = txobj.digest()
        ret = txobj.signatures[0].verify(digest)
        assert ret

        file_digest = hashlib.sha256(large_data).digest()
        if file_digest == txobj.relations[0].asset.asset_file_digest:
            print("oooo valid")
        else:
            print("xxxx invalid")
        print(txobj)
Exemplo n.º 28
0
def pick_valid_transaction_info(received_data=None, bbc_app_client=None):
    transaction = bbclib.BBcTransaction(deserialize=received_data[KeyType.transaction_data])
    asset_files = received_data[KeyType.all_asset_files]
    asset_id = transaction.relations[0].asset.asset_id
    if asset_id not in asset_files:
        print("**** No valid file is received...")
        print(received_data)
        bbc_app_client.sendback_denial_of_sign(received_data[KeyType.source_user_id],
                                               transaction.transaction_id,
                                               "No valid file is received.")
        sys.exit(1)

    file_to_obtain = asset_files[asset_id]
    file_digest = hashlib.sha256(file_to_obtain).digest()
    print("--------------------------")
    print("File digest written in the transaction data:  ",
          binascii.b2a_hex(transaction.relations[0].asset.asset_file_digest).decode())
    print("File digest calculated from the received file:", binascii.b2a_hex(file_digest).decode())
    print("--------------------------")
    return transaction, received_data[KeyType.source_user_id]
Exemplo n.º 29
0
def add_ref_tx(asset_group,transaction,ref_tx,ref_index):
    if asset_group == land_asset_group:
        bbc_app_client = setup_bbc_client(land_domain_id)
    elif asset_group == coin_asset_group:
        bbc_app_client = setup_bbc_client(coin_domain_id)
    bbc_app_client.search_transaction(ref_tx)
    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.BBcTransaction(deserialize=response_data[KeyType.transaction_data])
    reference = bbclib.add_reference_to_transaction(transaction, asset_group, prev_tx,0)
    sig = transaction.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                                 private_key=key_pair.private_key,
                                 public_key=key_pair.public_key)
    transaction.references[ref_index].add_signature(user_id=user_id, signature=sig)
    if asset_group == land_asset_group:
        print("ref to land asset")

    return transaction
Exemplo n.º 30
0
def create_transaction_object_and_send_sign_req(idx,
                                                receiver_user_id,
                                                ref_txids=None,
                                                file_data=None):
    if ref_txids is None or ref_txids[0] is None:
        ref_txids = []

    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=receiver_user_id,
                              asset_body="transferred",
                              asset_file=file_data)
    txobj.witness.add_witness(user_ids[idx])
    txobj.witness.add_witness(receiver_user_id)

    for i, ref_txid in enumerate(ref_txids):
        clients[idx].search_transaction(ref_txid)
        response_data = clients[idx].callback.synchronize()
        if response_data[KeyType.status] < ESUCCESS:
            print("ERROR: ", response_data[KeyType.reason].decode())
            sys.exit(0)
        prev_tx = bbclib.BBcTransaction(
            deserialize=response_data[KeyType.transaction_data])
        bbclib.add_relation_pointer(txobj,
                                    0,
                                    ref_transaction_id=prev_tx.digest())

    sig_mine = txobj.sign(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                          private_key=keypairs[idx].private_key,
                          public_key=keypairs[idx].public_key)
    txobj.witness.add_signature(user_id=user_ids[idx], signature=sig_mine)

    asset_id = txobj.relations[0].asset.asset_id
    asset_files = {asset_id: file_data}
    ret = clients[idx].gather_signatures(txobj,
                                         destinations=[receiver_user_id],
                                         asset_files=asset_files)
    assert ret
    return txobj