Exemplo n.º 1
0
def _normalize_asset(asset, is_transfer=False):
    """
    Normalizes the given asset dictionary.

    For now, this means converting the given asset dictionary to a
    :class:`~.bigchaindb.common.transaction.Asset` class.

    Args:
        asset (dict): The asset to normalize.
        is_transfer (boal, optional): Flag used to indicate whether the
            asset is to be used as part of a `'TRANSFER'` operation or
            not. Defaults to ``False``.

    Returns:
        The :class:`~.bigchaindb.common.transaction.Asset` class,
        instantiated from the given asset dictionary.

        .. important:: If the instantiation step fails, ``None`` may be
            returned.

    .. danger:: For specific internal usage only. The behavior is tricky,
        and is subject to change.

    """
    if is_transfer:
        asset = Asset.from_dict(asset)
    else:
        try:
            asset = Asset(**asset)
        except (AttributeError, TypeError):
            if not asset:
                asset = None
    return asset
    def transfer(self, transaction, *owners_after, asset, signing_key=None):
        """Issue a transaction to transfer an asset.

        Args:
            transaction (dict): The transaction to transfer.
            owners_after (str): Zero or more public keys of the new owners.
            asset (dict): Asset to transfer.
            signing_key (str): Private key used to sign transactions.

        Returns:
            dict: The transaction pushed to the Federation.

        Raises:
            :class:`~bigchaindb_driver.exceptions.InvalidSigningKey`: If
                neither ``signing_key`` nor ``self.signing_key`` have been set.

        """
        signing_key = signing_key if signing_key else self.signing_key
        if not signing_key:
            raise InvalidSigningKey
        transaction_obj = Transaction.from_dict(transaction)
        signed_transfer_transaction = Transaction.transfer(
            transaction_obj.to_inputs(),
            list(owners_after),
            asset=Asset.from_dict(asset),
        ).sign([signing_key]).to_dict()
        return self._push(signed_transfer_transaction)
def create_transfer(p_num):
    print(p_num, ":create_transfer start")
    while True:
        alice, bob = generate_keypair(), generate_keypair()

        asset = Asset(data={'money': 'RMB'}, data_id='20170628150000', divisible=True)
        metadata = {'planet': 'earth'}
        tx_create = Transaction.create([alice.public_key], [([alice.public_key], 1)], metadata=metadata, asset=asset)
        tx_create = tx_create.sign([alice.private_key])
        try:
            create_queue.put(tx_create, False)
        except Full:
            print(p_num, ":create_queue full", create_queue.qsize())
            break

        cid = 0
        condition = tx_create.to_dict()['transaction']['conditions'][cid]
        inputs = Fulfillment.from_dict({
            'fulfillment': condition['condition']['details'],
            'input': {
                'cid': cid,
                'txid': tx_create.to_dict()['id'],
            },
            'owners_before': condition['owners_after'],
        })
        asset = Asset.from_dict(tx_create.to_dict()['transaction']['asset'])
        tx_transfer = Transaction.transfer([inputs], [([bob.public_key], 1)], asset)
        tx_transfer = tx_transfer.sign([alice.private_key])
        try:
            transfer_queue.put(tx_transfer, False)
        except Full:
            print(p_num, ":transfer_queue full")
            break
Exemplo n.º 4
0
    def get_asset_by_id(self, asset_id):
        """Returns the asset associated with an asset_id.

            Args:
                asset_id (str): The asset id.

            Returns:
                :class:`~bigchaindb.common.transaction.Asset` if the asset
                exists else None.
        """
        cursor = backend.query.get_asset_by_id(self.connection, asset_id)
        cursor = list(cursor)
        if cursor:
            return Asset.from_dict(cursor[0]['asset'])
Exemplo n.º 5
0
def create_transfer():
    ##################################################### 1.CREATE
    # Cryptographic Identities Generation
    alice, bob = generate_keypair(), generate_keypair()

    # Digital Asset Definition (e.g. bicycle)
    asset = Asset(data={"bicycle": {"manufacturer": "bkfab", "serial_number": "abcd1234"}})

    # Metadata Definition
    metadata = {'planet': 'earth'}

    # create trnsaction  TODO : owners_before might be node_pubkey in v0.8.0
    tx = Transaction.create([alice.public_key], [([alice.public_key], 1)], metadata=metadata, asset=asset)
    print(" ")
    print("1.tx_create asset id    :  alice-----bicycle(", tx.to_dict()['transaction']['asset']['id'], ")----->alice")
    print("1.tx_create tx id       : ", tx.to_dict()['id'])

    # sign with alice's private key
    tx = tx.sign([alice.private_key])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("1.tx_create db response : ", b.write_transaction(tx))

    # wait 2 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("1.tx_create query       : ", tx)
    # print("tx1_id:"+tx.to_dict()['id'])
    print(" ")
    ##################################################### 2.TRANSFER
    #  inputs and asset [fake]
    cid = 0
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment': condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before': [bob.public_key],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx = Transaction.transfer([inputs], [([bob.public_key], 1)], asset)
    print("2.tx_fake asset id    :  bob-----bicycle(", tx.to_dict()['transaction']['asset']['id'], ")----->bob")
    print("2.tx_fake tx id       : ", tx.to_dict()['id'])

    # sign with bob's private key [fake]
    tx = tx.sign([bob.private_key])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("2.tx_fake db response : ", b.write_transaction(tx))

    # wait 2 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("2.tx_fake query       : ", tx)
    # print("tx2_id:"+tx.to_dict()['id'])
    print(" ")
Exemplo n.º 6
0
def create_transfer():
    ##################################################### 1.CREATE
    # Cryptographic Identities Generation
    alice, bob, tom = generate_keypair(), generate_keypair(), generate_keypair(
    )
    asset = Asset(data={'money': 'RMB'},
                  data_id='20170628150000',
                  divisible=True)
    metadata = {'planet': 'earth'}

    tx = Transaction.create([alice.public_key], [([alice.public_key], 1000)],
                            metadata=metadata,
                            asset=asset)
    print(" ")
    print("1.tx_create asset id    :  alice-----money 1000(",
          tx.to_dict()['transaction']['asset']['id'], ")----->alice")
    print("1.tx_create tx id       : ", tx.to_dict()['id'])

    # sign with alice's private key
    tx = tx.sign([alice.private_key])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("1.tx_create db response : ", b.write_transaction(tx))

    # wait 4 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("1.tx_create query       : ", tx)
    # print("tx1_id:"+tx.to_dict()['id'])
    print(" ")
    ##################################################### 2.TRANSFER
    #  inputs and asset
    cid = 0
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment':
        condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before':
        condition['owners_after'],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx = Transaction.transfer([inputs], [([bob.public_key], 300),
                                         ([alice.public_key], 700)], asset)
    print("2.tx_transfer asset id    :  alice-----money 300(",
          tx.to_dict()['transaction']['asset']['id'], ")----->bob")
    print("2.tx_transfer tx id       : ", tx.to_dict()['id'])
    print("2.tx_transfer tx          : ", tx.to_dict())
    print(" ")
    # sign with alice's private key
    tx = tx.sign([alice.private_key])

    # man in the middle attack, then write to backlog
    tx.conditions[0].amount = 600
    tx.conditions[1].amount = 400
    print("3.tx_attack asset id    :  alice-----money 600(",
          tx.to_dict()['transaction']['asset']['id'], ")----->tom")
    print("3.tx_attack tx id       : ", tx.to_dict()['id'])
    print("3.tx_attack tx          : ", tx.to_dict())
    tx_id = tx.to_dict()['id']
    b = Bigchain()
    print("3.tx_attack db response : ", b.write_transaction(tx))

    # wait 4 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("3.tx_attack query       : ", tx)
    print(" ")
Exemplo n.º 7
0
def create_double():
    ##################################################### 1.CREATE
    # Cryptographic Identities Generation
    alice, bob = generate_keypair(), generate_keypair()

    # Digital Asset Definition (e.g. money)
    asset = Asset(data={'money': 'RMB'},
                  data_id='20170628150000',
                  divisible=True)

    # Metadata Definition
    metadata = {'planet': 'earth'}

    # create trnsaction  TODO : owners_before might be node_pubkey in v0.8.0
    tx = Transaction.create([alice.public_key], [([alice.public_key], 100),
                                                 ([alice.public_key], 100)],
                            metadata=metadata,
                            asset=asset)
    print(" ")
    print("1.tx_create asset id    :  alice-----money(",
          tx.to_dict()['transaction']['asset']['id'], ")----->alice")
    print("1.tx_create tx id       : ", tx.to_dict()['id'])

    # sign with alice's private key
    tx = tx.sign([alice.private_key])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("1.tx_create db response : ", b.write_transaction(tx))

    # wait 2 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    unspent = b.get_outputs_filtered_not_include_freeze(
        alice.public_key, False)
    print("1.tx_create query       : ", tx)
    print("1.tx_create unspent     : ", unspent)
    print(" ")

    ##################################################### 2.TRANSFER
    #  inputs and asset
    cid = 0
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment':
        condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before': [alice.public_key],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx1 = Transaction.transfer([inputs], [([bob.public_key], 100)], asset)
    print("2.tx_transfer asset id    :  alice-----money(",
          tx1.to_dict()['transaction']['asset']['id'], ")----->bob")
    print("2.tx_transfer tx id       : ", tx1.to_dict()['id'])

    # sign with alice's private key
    tx1 = tx1.sign([alice.private_key])
    tx1_id = tx1.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("2.tx_transfer db response : ", b.write_transaction(tx1))

    # wait 2 sec
    sleep(delay)

    # get tx by id
    tx1 = b.get_transaction(tx1_id)
    block = list(b.get_blocks_status_containing_tx(tx1_id).keys())[0]
    votes = list(b.backend.get_votes_by_block_id(block))
    votes_cast = [vote['vote']['is_block_valid'] for vote in votes]
    election = b.get_blocks_status_containing_tx(tx1_id)
    print("2.tx_transfer query       : ", tx1)
    print("2.tx_transfer block       : ", block)
    print("2.            votes       : ", votes)
    print("2.            votes_cast  : ", votes_cast)
    print("2.            election    : ", election)
    print(" ")
    ##################################################### 3.INTERVAL
    # Cryptographic Identities Generation
    alice, bob = generate_keypair(), generate_keypair()

    # Digital Asset Definition (e.g. money)
    asset = Asset(data={'money': 'RMB'},
                  data_id='20170628150000',
                  divisible=True)

    # Metadata Definition
    metadata = {'planet': 'earth'}

    # create trnsaction  TODO : owners_before might be node_pubkey in v0.8.0
    txi = Transaction.create([alice.public_key], [([alice.public_key], 100),
                                                  ([alice.public_key], 100)],
                             metadata=metadata,
                             asset=asset)
    print(" ")
    print("1.tx_create asset id    :  alice-----money(",
          tx.to_dict()['transaction']['asset']['id'], ")----->alice")
    print("1.tx_create tx id       : ", txi.to_dict()['id'])

    # sign with alice's private key
    txi = txi.sign([alice.private_key])
    tx_id = txi.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("1.tx_create db response : ", b.write_transaction(tx))

    # wait 2 sec
    sleep(delay)
    ##################################################### 3.TRANSFER
    #  inputs and asset [double spend]
    cid = 1
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment':
        condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before': [alice.public_key],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx1 = Transaction.transfer([inputs], [([bob.public_key], 100)], asset)
    print("3.tx_double asset id    :  alice-----money(",
          tx1.to_dict()['transaction']['asset']['id'], ")----->bob")
    print("3.tx_double tx id       : ", tx1.to_dict()['id'])

    # sign with alice's private key
    tx1 = tx1.sign([alice.private_key])
    tx1_id = tx1.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("3.tx_double db response : ", b.write_transaction(tx1))
    # wait 2 sec
    sleep(delay)

    # get tx by id
    tx1 = b.get_transaction(tx1_id)
    block = list(b.get_blocks_status_containing_tx(tx1_id).keys())[0]
    votes = list(b.backend.get_votes_by_block_id(block))
    votes_cast = [vote['vote']['is_block_valid'] for vote in votes]
    election = b.get_blocks_status_containing_tx(tx1_id)
    print("3.tx_transfer query       : ", tx1)
    print("3.tx_transfer block       : ", block)
    print("3.            votes       : ", votes)
    print("3.            votes_cast  : ", votes_cast)
    print("3.            election    : ", election)
    print(" ")
Exemplo n.º 8
0
def create_transfer(alicepub, alicepriv, include_spent):
    ##################################################### 1.CREATE
    # Cryptographic Identities Generation
    # alice, bob = generate_keypair(), generate_keypair()

    # Digital Asset Definition (e.g. bicycle)
    asset = Asset(data={
        "bicycle": {
            "manufacturer": "bkfab",
            "serial_number": "abcd1234"
        }
    },
                  data_id="334cd061-846b-4213-bd25-588e951def5f")

    # Metadata Definition
    metadata = {'planet': 'earth'}

    # create trnsaction  TODO : owners_before might be node_pubkey in v0.8.0
    tx = Transaction.create([alicepub], [([alicepub], 100)],
                            metadata=metadata,
                            asset=asset)

    # sign with alice's private key
    tx = tx.sign([alicepriv])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    b.write_transaction(tx)
    print("========create 100 asset for userA========")
    print("========wait for block and vote...========")
    # wait 2 sec
    sleep(5)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("create 100 asset tx1_id:" + tx.to_dict()['id'])

    ##################################################### 3.UTXO
    #  inputs and asset
    utxo = b.get_outputs_filtered_not_include_freeze(alicepub, include_spent)
    for u in utxo:
        # print(u)
        u.pop('details')
    print('userA unspent asset:')
    print(json.dumps(utxo, indent=4))
    # print(json.load(utxo))

    ##################################################### 2.Freeze
    #  inputs and asset
    cid = 0
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment':
        condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before':
        condition['owners_after'],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx = Transaction.freeze_asset([inputs], [([alicepub], 90, True),
                                             ([alicepub], 10, False)], asset)

    # sign with alice's private key
    tx = tx.sign([alicepriv])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    b.write_transaction(tx)
    print("========freeze 90 asset for userA ========")
    print("========wait for block and vote...========")
    # wait 2 sec
    sleep(5)

    # get tx by id
    tx = b.get_transaction(tx_id)

    print("freeze 90 asset tx2_id:" + tx.to_dict()['id'])

    ##################################################### 3.UTXO
    #  inputs and asset
    utxo = b.get_outputs_filtered_not_include_freeze(alicepub, include_spent)
    for u in utxo:
        # print(u)
        u.pop('details')
    print('userA unspent asset:')
    print(json.dumps(utxo, indent=4))
Exemplo n.º 9
0
def create_transfer():
    ##################################################### 1.CREATE
    # Cryptographic Identities Generation
    alice, bob, tom = generate_keypair(), generate_keypair(), generate_keypair()
    asset = Asset(data={"bicycle": {"manufacturer": "bkfab", "serial_number": "abcd1234"}})
    metadata = {'planet': 'earth'}

    tx = Transaction.create([alice.public_key], [([alice.public_key], 1)], metadata=metadata, asset=asset)
    print(" ")
    print("1.tx_create asset id    :  alice-----bicycle(", tx.to_dict()['transaction']['asset']['id'], ")----->alice")
    print("1.tx_create tx id       : ", tx.to_dict()['id'])

    # sign with alice's private key
    tx = tx.sign([alice.private_key])
    tx_id = tx.to_dict()['id']

    # write to backlog
    b = Bigchain()
    print("1.tx_create db response : ", b.write_transaction(tx))

    # wait 4 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("1.tx_create query       : ", tx)
    # print("tx1_id:"+tx.to_dict()['id'])
    print(" ")
    ##################################################### 2.TRANSFER
    #  inputs and asset
    cid = 0
    condition = tx.to_dict()['transaction']['conditions'][cid]
    inputs = Fulfillment.from_dict({
        'fulfillment': condition['condition']['details'],
        'input': {
            'cid': cid,
            'txid': tx.to_dict()['id'],
        },
        'owners_before': condition['owners_after'],
    })
    asset = Asset.from_dict(tx.to_dict()['transaction']['asset'])

    # transfer
    tx = Transaction.transfer([inputs], [([bob.public_key], 1)], asset)
    print("2.tx_transfer asset id    :  alice-----bicycle(", tx.to_dict()['transaction']['asset']['id'], ")----->bob")
    print("2.tx_transfer tx id       : ", tx.to_dict()['id'])
    print("2.tx_transfer tx          : ", tx.to_dict())
    print(" ")
    # sign with alice's private key
    tx = tx.sign([alice.private_key])

    # man in the middle attack, then write to backlog
    tx.conditions[0].owners_after = [tom.public_key]
    print("3.tx_attack asset id    :  alice-----bicycle(", tx.to_dict()['transaction']['asset']['id'], ")----->tom")
    print("3.tx_attack tx id       : ", tx.to_dict()['id'])
    print("3.tx_attack tx          : ", tx.to_dict())
    tx_id = tx.to_dict()['id']
    b = Bigchain()
    print("3.tx_attack db response : ", b.write_transaction(tx))

    # wait 4 sec
    sleep(delay)

    # get tx by id
    tx = b.get_transaction(tx_id)
    print("3.tx_attack query       : ", tx)
    print(" ")