Ejemplo 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

        print(txobj)
        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
Ejemplo 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
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
    def remove(self, transaction_id, txobj=None, db_num=-1):
        """
        Delete all data regarding the specified transaction_id
        :param transaction_id:
        :param txobj:
        :param db_num:
        :return:
        """
        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)

        self.remove_asset_files(txobj)
Ejemplo n.º 5
0
Archivo: coin.py Proyecto: luomin/bbc1
def chown(new_owner, asid):
    asset = json.loads(get_coindata(asid).decode("UTF-8"))
    if asset["owner"] != binascii.b2a_hex(user_id).decode("UTF-8"):
        print("Owner of this coin 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()
    ret = bbc_app_client.search_asset(asset_group_id, binascii.unhexlify(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.transaction_data])
    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.....")
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
 def receive_transaction_data_from_others(self, dat):
     """
     Receive transaction data from other core_nodes and check its validity
     :param dat:
     :return:
     """
     #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 and len(invalid_assets) == 0:
         self.stats.update_stats_increment("transaction", "success_repair", 1)
         for idx in range(len(self.data_handler.db_adaptors)):
             self.data_handler.restore_data(db_num=idx, transaction_id=txobj.transaction_id,
                                            txobj=txobj, asset_files=valid_assets)
         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]]
Ejemplo n.º 8
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])

        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(asset_group_id, dat[KeyType.source_user_id], i, signature)
                return
Ejemplo n.º 9
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])
    transaction.dump()
    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(
                asset_group_id, recvdat[KeyType.source_user_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(
                    asset_group_id, recvdat[KeyType.source_user_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(asset_group_id,
                                      recvdat[KeyType.source_user_id], 0,
                                      signature)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
0
def get_txid_from_asid(asset_group, asid):
    bbc_app_client = setup_bbc_client(asset_group)
    ret = bbc_app_client.search_asset(asset_group, binascii.unhexlify(asid))
    assert ret
    response_data = bbc_app_client.callback.synchronize()
    get_transaction = bbclib.BBcTransaction()
    get_transaction.deserialize(response_data[KeyType.transaction_data])
    transaction_id = get_transaction.transaction_id
    return transaction_id
Ejemplo n.º 13
0
def store_proc(data, approver_id, txid=None):
    # make transaction object
    transaction = bbclib.make_transaction_for_base_asset(
        asset_group_id=asset_group_id, event_num=1)
    transaction.events[0].add(mandatory_approver=approver_id,
                              asset_group_id=asset_group_id)
    transaction.events[0].asset.add(user_id=user_id, asset_body=data)
    if txid:
        obj = {
            "jsonrpc": "2.0",
            "method": "bbc1_GetTransaction",
            "params": {
                "asset_group_id": bbclib.bin2str_base64(asset_group_id),
                "tx_id": txid,
                "user_id": bbclib.bin2str_base64(user_id),
            },
            "id": 114514
        }
        response = json_post(obj)
        prevtx = response["result"]
        prevtx = bbclib.BBcTransaction(jsonload=prevtx)
        bbclib.add_reference_to_transaction(asset_group_id, transaction,
                                            prevtx, 0)

    # get transaction digest
    jsontx = transaction.jsondump()
    obj = {
        "jsonrpc": "2.0",
        "method": "bbc1_GetTransactionDigest",
        "params": jsontx,
        "id": 114514
    }
    response = json_post(obj)

    # add sign to transaction json
    sig = bbclib.bin2str_base64(
        key_pair.sign(
            binascii.a2b_base64(response["result"]["digest"].encode("utf-8"))))
    jsontx = json.loads(response["result"]["tx"])
    sig = {
        "type": 1,
        "signature": sig,
        "pubkey": bbclib.bin2str_base64(key_pair.public_key)
    }
    jsontx["Signature"].append(sig)
    # Insert Transaction
    obj = {
        "jsonrpc": "2.0",
        "method": "bbc1_InsertTransaction",
        "params": json.dumps(jsontx),
        "id": 114514
    }
    response = json_post(obj)
    print("TXID: %s" % response["result"])
    print("ASID: %s" % jsontx["Event"][0]["Asset"]["asset_id"])
    return response["result"]
Ejemplo n.º 14
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)
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def get_data(asset_group, asid):
    bbc_app_client = setup_bbc_client(asset_group)
    asid = binascii.unhexlify(asid)
    ret = bbc_app_client.search_asset(asset_group, asid)
    assert ret
    response_data = bbc_app_client.callback.synchronize()

    get_transaction = bbclib.BBcTransaction()
    get_transaction.deserialize(response_data[KeyType.transaction_data])
    retdata = get_transaction.events[0].asset.asset_body
    refdata = get_transaction.references
    return retdata
Ejemplo n.º 17
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
Ejemplo n.º 18
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.events[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.events[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]
Ejemplo n.º 19
0
def get_coindata(asid):
    bbc_app_client = setup_bbc_client()
    asid = binascii.unhexlify(asid)
    ret = bbc_app_client.search_asset(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.transaction_data])

    retdata = get_transaction.events[0].asset.asset_body
    refdata = get_transaction.references
    print("get: %s" % retdata)
    print("ref: %s" % refdata)
    return retdata
Ejemplo n.º 20
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)
Ejemplo n.º 21
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(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                             private_key=keypair1.private_key,
                             public_key=keypair1.public_key)
            txobj.add_signature(user_id=user_id1, signature=sig)
            txobj.digest()
            transactions.append(txobj)
Ejemplo n.º 22
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(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                               private_key=keypair.private_key,
                               public_key=keypair.public_key)
        transaction.add_signature(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, transaction.serialize(),
                                          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)
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(key_type=bbclib.KeyType.ECDSA_SECP256k1,
                         private_key=keypair1.private_key,
                         public_key=keypair1.public_key)
        txobj.add_signature(user_id=user_id1, signature=sig)
        txobj.digest()
        transactions.append(txobj)
Ejemplo n.º 24
0
    def __update_local_database(self, user_id):
        ret = self.__app.search_transaction_with_condition(
            asset_group_id=self.namespace_id, user_id=user_id)
        res = self.__app.callback.sync_by_queryid(
            ret, 2)  # FIXME: slow when not found
        if res is None or res[KeyType.status] < ESUCCESS:
            raise ValueError('not found')
        tx = bbclib.BBcTransaction(deserialize=res[KeyType.transactions][0])
        tx_last = tx
        tx_directives = []
        while True:
            ret = self.__db.exec_sql_fetchone(
                self.domain_id, NAME_OF_DB,
                ('select * from id_pubkey_table where '
                 'tx_id_added=? or tx_id_removed=?'), tx.transaction_id,
                tx.transaction_id)
            if ret is not None:
                break
            directives = []
            event = self.__get_event(tx, user_id)
            ptr = 0
            while True:
                ptr, directive = Directive.from_serialized_data(
                    ptr, event.asset.asset_body)
                if directive is None:
                    break
                directives.append(directive)
            tx_directives.append((tx.transaction_id, directives))
            tx = self.__get_referred_transaction(tx)
            if tx is None:
                break

        for (tx_id, directives) in reversed(tx_directives):
            for directive in directives:
                self.__apply(tx_id, user_id, directive)

        return tx_last
Ejemplo n.º 25
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]
    asset_id = transaction.events[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.events[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]
Ejemplo n.º 26
0
    def transfer(self,
                 from_user_id,
                 to_user_id,
                 amount,
                 keypair_from=None,
                 keypair_mint=None):
        tx = bbclib.BBcTransaction()
        sorted_tuples = self.store.get_sorted_utxo_list(
            from_user_id, tx.timestamp)
        num_refs = 0
        value = 0
        for t in sorted_tuples:
            num_refs += 1
            value += t[0]
            if value >= amount:
                break
        if value < amount:
            raise ValueError("not enough fund")

        spec_tuples = []
        for i in range(num_refs):
            ref_tx = self.store.get_tx(sorted_tuples[i][2][IDX_TX_ID])
            ref = bbclib.BBcReference(
                asset_group_id=self.mint_id,
                transaction=tx,
                ref_transaction=ref_tx,
                event_index_in_ref=sorted_tuples[i][2][IDX_EVENT_IDX])
            tx.add(reference=ref)
            _, body = BaseAssetBody.from_serialized_data(
                0, ref_tx.events[ref.event_index_in_ref].asset.asset_body)
            found = False
            for t in spec_tuples:
                if body.is_same_spec(t[2], t[3]):
                    found = True
                    t[0] += sorted_tuples[i][0]
                    t[1] += body.value_specified
                    t[4].append(i)
                    break
            if found == False:
                spec_tuples.append([
                    sorted_tuples[i][0], body.value_specified,
                    body.time_of_origin, body.variation_specs, [i]
                ])

        for i, t in enumerate(spec_tuples):
            amount -= t[0]
            if amount >= 0:
                body = BaseAssetBody(BaseAssetBody.T_VALUE, t[1], t[2], t[3])
                tx.add(event=self.make_event(t[4], to_user_id, body))
            else:
                idx = i
                break

        if amount < 0:
            t = spec_tuples[idx]
            v = (t[1] * (t[0] + amount)) // t[0]

            body = BaseAssetBody(BaseAssetBody.T_VALUE, v, t[2], t[3])
            while body.get_effective_value(tx.timestamp,
                    self.store.get_condition()) < t[0] + amount and \
                    body.value_specified < t[1]:
                body.value_specified += 1
            v = body.value_specified
            tx.add(event=self.make_event(t[4], to_user_id, body))

            body = BaseAssetBody(BaseAssetBody.T_CHANGE, t[1] - v, t[2], t[3])
            tx.add(event=self.make_event(t[4], from_user_id, body))

            for i in range(idx + 1, len(spec_tuples)):
                t = spec_tuples[i]
                body = BaseAssetBody(BaseAssetBody.T_CHANGE, t[1], t[2], t[3])
                tx.add(event=self.make_event(t[4], from_user_id, body))

        if keypair_from is None:
            return tx

        if keypair_mint is None:
            self.app.gather_signatures(tx, destinations=[self.mint_id])
            res = self.app.callback.synchronize()
            if res[KeyType.status] < ESUCCESS:
                raise RuntimeError(res[KeyType.reason].decode())
            result = res[KeyType.result]
            tx.add_signature(self.mint_id, signature=result[2])
            return self.store.sign_and_insert(tx, from_user_id, keypair_from,
                                              self.idPublickeyMap)

        self.store.sign(tx, from_user_id, keypair_from)

        return self.store.sign_and_insert(tx, self.mint_id, keypair_mint,
                                          self.idPublickeyMap)
Ejemplo n.º 27
0
    def search_transaction(self,
                           transaction_id=None,
                           asset_group_id=None,
                           asset_id=None,
                           user_id=None,
                           count=1,
                           db_num=0):
        """
        Search transaction data
        :param transaction_id:
        :param asset_group_id:
        :param asset_id:
        :param user_id:
        :param count:
        :param idx:
        :return:
        """
        if transaction_id is not None:
            txinfo = self.exec_sql(
                db_num=db_num,
                sql="SELECT * FROM transaction_table WHERE transaction_id = %s"
                % self.db_adaptors[0].placeholder,
                args=(transaction_id, ))
            if len(txinfo) == 0:
                return None, None
        else:
            sql = "SELECT * from asset_info_table WHERE "
            conditions = list()
            if asset_group_id is not None:
                conditions.append("asset_group_id = %s " %
                                  self.db_adaptors[0].placeholder)
            if asset_id is not None:
                conditions.append("asset_id = %s " %
                                  self.db_adaptors[0].placeholder)
            if user_id is not None:
                conditions.append("user_id = %s " %
                                  self.db_adaptors[0].placeholder)
            sql += "AND ".join(conditions) + "ORDER BY id DESC"
            if count > 0:
                if count > 20:
                    count = 20
                sql += " limit %d" % count
            sql += ";"
            args = list(
                filter(lambda a: a is not None,
                       (asset_group_id, asset_id, user_id)))
            ret = self.exec_sql(db_num=db_num, sql=sql, args=args)
            txinfo = list()
            for record in ret:
                tx = self.exec_sql(
                    db_num=db_num,
                    sql=
                    "SELECT * FROM transaction_table WHERE transaction_id = %s"
                    % self.db_adaptors[0].placeholder,
                    args=(record[1], ))
                if tx is not None and len(tx) == 1:
                    txinfo.append(tx[0])

        result_txobj = dict()
        result_asset_files = dict()
        for txid, txdata in txinfo:
            txobj = bbclib.BBcTransaction(deserialize=txdata)
            result_txobj[txid] = txobj
            for asset_group_id, asset_id, user_id, fileflag, filedigest in self.get_asset_info(
                    txobj):
                if fileflag:
                    result_asset_files[asset_id] = self.get_in_storage(
                        asset_group_id, asset_id)
        return result_txobj, result_asset_files