예제 #1
0
class Election:
    """Election class."""
    def __init__(self, events_queue=None):
        self.bigchain = Bigchain()
        self.events_queue = events_queue

    def check_for_quorum(self, next_vote):
        """
        Checks if block has enough invalid votes to make a decision

        Args:
            next_vote: The next vote.

        """
        try:
            block_id = next_vote['vote']['voting_for_block']
            node = next_vote['node_pubkey']
        except KeyError:
            return

        next_block = self.bigchain.get_block(block_id)

        result = self.bigchain.block_election(next_block)
        self.handle_block_events(result, block_id)
        if result['status'] == self.bigchain.BLOCK_INVALID:
            return Block.from_dict(next_block)

        # Log the result
        if result['status'] != self.bigchain.BLOCK_UNDECIDED:
            msg = 'node:%s block:%s status:%s' % \
                (node, block_id, result['status'])
            # Extra data can be accessed via the log formatter.
            # See logging.dictConfig.
            logger_results.debug(msg,
                                 extra={
                                     'current_vote': next_vote,
                                     'election_result': result,
                                 })

    def requeue_transactions(self, invalid_block):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block.transactions), invalid_block.id)
        for tx in invalid_block.transactions:
            self.bigchain.write_transaction(tx)
        return invalid_block

    def handle_block_events(self, result, block_id):
        if self.events_queue:
            if result['status'] == self.bigchain.BLOCK_UNDECIDED:
                return
            elif result['status'] == self.bigchain.BLOCK_INVALID:
                event_type = EventTypes.BLOCK_INVALID
            elif result['status'] == self.bigchain.BLOCK_VALID:
                event_type = EventTypes.BLOCK_VALID

            event = Event(event_type, self.bigchain.get_block(block_id))
            self.events_queue.put(event)
예제 #2
0
class Election:

    def __init__(self):
        self.bigchain = Bigchain()

    def check_for_quorum(self, next_vote):
        """
        Checks if block has enough invalid votes to make a decision
        """
        next_block = r.table('bigchain')\
            .get(next_vote['vote']['voting_for_block'])\
            .run(self.bigchain.conn)
        if self.bigchain.block_election_status(next_block) == self.bigchain.BLOCK_INVALID:
            return next_block

    def requeue_transactions(self, invalid_block):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block['block']['transactions']),
                    invalid_block['id'])
        for tx in invalid_block['block']['transactions']:
            self.bigchain.write_transaction(tx)
        return invalid_block
예제 #3
0
def create_duplicate_tx():
    ##################################################### 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': 'earth1'}

    # 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(" ")

    #####################################################
    print("2.write dulpicate tx: ", b.write_transaction(tx))
예제 #4
0
class Election:
    def __init__(self):
        self.bigchain = Bigchain()

    def check_for_quorum(self, next_vote):
        """
        Checks if block has enough invalid votes to make a decision
        """
        next_block = r.table('bigchain')\
            .get(next_vote['vote']['voting_for_block'])\
            .run(self.bigchain.conn)
        if self.bigchain.block_election_status(
                next_block) == self.bigchain.BLOCK_INVALID:
            return next_block

    def requeue_transactions(self, invalid_block):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block['block']['transactions']),
                    invalid_block['id'])
        for tx in invalid_block['block']['transactions']:
            self.bigchain.write_transaction(tx)
        return invalid_block
예제 #5
0
class Election:
    """Election class."""

    def __init__(self):
        self.bigchain = Bigchain()

    def check_for_quorum(self, next_vote):
        """
        Checks if block has enough invalid votes to make a decision

        Args:
            next_vote: The next vote.

        """
        next_block = self.bigchain.get_block(
            next_vote['vote']['voting_for_block'])

        block_status = self.bigchain.block_election_status(next_block['id'],
                                                           next_block['block']['voters'])
        if block_status == self.bigchain.BLOCK_INVALID:
            return Block.from_dict(next_block)

    def requeue_transactions(self, invalid_block):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block.transactions),
                    invalid_block.id)
        for tx in invalid_block.transactions:
            self.bigchain.write_transaction(tx)
        return invalid_block
예제 #6
0
class Election:
    """Election class."""
    def __init__(self):
        self.bigchain = Bigchain()

    def check_for_quorum(self, next_vote):
        """
        Checks if block has enough invalid votes to make a decision

        Args:
            next_vote: The next vote.

        """
        next_block = self.bigchain.get_block(
            next_vote['vote']['voting_for_block'])

        block_status = self.bigchain.block_election_status(
            next_block['id'], next_block['block']['voters'])
        if block_status == self.bigchain.BLOCK_INVALID:
            return Block.from_dict(next_block)

    def requeue_transactions(self, invalid_block):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block.transactions), invalid_block.id)
        for tx in invalid_block.transactions:
            self.bigchain.write_transaction(tx)
        return invalid_block
예제 #7
0
def 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)

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

    # write to backlog
    b = Bigchain()
    b.write_transaction(tx)

    # wait 2 sec
    sleep(2)

    # get tx by id
    tx = b.get_transaction(tx_id)
    return tx.to_dict()
예제 #8
0
class Election:
    """Election class."""

    def __init__(self, events_queue=None):
        self.bigchain = Bigchain()
        self.events_queue = events_queue

    def check_for_quorum(self, next_vote):
        """Checks if block has enough invalid votes to make a decision

        Args:
            next_vote: The next vote.

        """
        try:
            block_id = next_vote['vote']['voting_for_block']
            node = next_vote['node_pubkey']
        except KeyError:
            return

        next_block = self.bigchain.get_block(block_id)

        result = self.bigchain.block_election(next_block)
        self.handle_block_events(result, block_id)
        if result['status'] == self.bigchain.BLOCK_INVALID:
            return Block.from_dict(next_block)

        # Log the result
        if result['status'] != self.bigchain.BLOCK_UNDECIDED:
            msg = 'node:%s block:%s status:%s' % \
                (node, block_id, result['status'])
            # Extra data can be accessed via the log formatter.
            # See logging.dictConfig.
            logger_results.debug(msg, extra={
                'current_vote': next_vote,
                'election_result': result,
            })

    def requeue_transactions(self, invalid_block):
        """Liquidates transactions from invalid blocks so they can be processed again
        """
        logger.info('Rewriting %s transactions from invalid block %s',
                    len(invalid_block.transactions),
                    invalid_block.id)
        for tx in invalid_block.transactions:
            self.bigchain.write_transaction(tx)
        return invalid_block

    def handle_block_events(self, result, block_id):
        if self.events_queue:
            if result['status'] == self.bigchain.BLOCK_UNDECIDED:
                return
            elif result['status'] == self.bigchain.BLOCK_INVALID:
                event_type = EventTypes.BLOCK_INVALID
            elif result['status'] == self.bigchain.BLOCK_VALID:
                event_type = EventTypes.BLOCK_VALID

            event = Event(event_type, self.bigchain.get_block(block_id))
            self.events_queue.put(event)
예제 #9
0
def merge_utxo(alicepub, alicepriv, include_spent):
    asset = Asset(data={
        "bicycle": {
            "manufacturer": "bkfab",
            "serial_number": "abcd1234"
        }
    },
                  data_id="334cd061-846b-4213-bd25-588e951def5f")
    metadata = {'planet': 'earth'}
    b = Bigchain()
    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))
    inputs = []
    balance = 0
    utxo = b.get_outputs_filtered_not_include_freeze(alicepub, include_spent)
    for i in utxo:
        f = Fulfillment.from_dict({
            'fulfillment': i['details'],
            'input': {
                'cid': i['cid'],
                'txid': i['txid'],
            },
            'owners_before': [alicepub],
        })
        inputs.append(f)
        balance += i['amount']

    length = len(utxo)
    if balance <= 0:
        print('No need to merge, because of lack of balance')
    elif length <= 1:
        print('No need to merge, because utxo len = 1')
    else:
        tx = Transaction.transfer(inputs, [([alicepub], balance)],
                                  metadata=metadata,
                                  asset=asset)
        tx = tx.sign([alicepriv])
        tx_id = tx.to_dict()['id']
        # write to backlog
        b.write_transaction(tx)
        # wait 2 sec
        print("========userA merge multi-asset========")
        print("========wait for block and vote...========")
        sleep(5)
        # get tx by id
        tx = b.get_transaction(tx_id)
        print("merge txid:" + tx.to_dict()['id'])

    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))
예제 #10
0
def create_write_transaction(tx_left):
    b = Bigchain()
    while tx_left > 0:
        # use uuid to prevent duplicate transactions (transactions with the same hash)
        tx = b.create_transaction(b.me, b.me, None, 'CREATE',
                                  payload={'msg': str(uuid.uuid4())})
        tx_signed = b.sign_transaction(tx, b.me_private)
        b.write_transaction(tx_signed)
        tx_left -= 1
예제 #11
0
def test_full_pipeline(monkeypatch, user_pk):
    from bigchaindb.backend import query
    from bigchaindb.models import Transaction
    CONFIG = {
        'keyring': ['aaa', 'bbb'],
        'backlog_reassign_delay': 0.01
    }
    config_utils.update_config(CONFIG)
    b = Bigchain()

    original_txs = {}
    original_txc = []

    monkeypatch.setattr('time.time', lambda: 1)

    for i in range(100):
        tx = Transaction.create([b.me], [([user_pk], 1)],
                                metadata={'msg': random.random()})
        tx = tx.sign([b.me_private])
        original_txc.append(tx.to_dict())

        b.write_transaction(tx)
    original_txs = list(query.get_stale_transactions(b.connection, 0))
    original_txs = {tx['id']: tx for tx in original_txs}

    assert len(original_txs) == 100

    monkeypatch.undo()

    inpipe = Pipe()
    # Each time the StaleTransactionMonitor pipeline runs, it reassigns
    # all eligible transactions. Passing this inpipe prevents that from
    # taking place more than once.
    inpipe.put(())
    outpipe = Pipe()
    pipeline = stale.create_pipeline(backlog_reassign_delay=1,
                                     timeout=1)
    pipeline.setup(indata=inpipe, outdata=outpipe)
    pipeline.start()

    # to terminate
    for _ in range(100):
        outpipe.get()

    pipeline.terminate()

    assert len(list(query.get_stale_transactions(b.connection, 0))) == 100
    reassigned_txs = list(query.get_stale_transactions(b.connection, 0))

    # check that every assignment timestamp has increased, and every tx has a new assignee
    for reassigned_tx in reassigned_txs:
        assert reassigned_tx['assignment_timestamp'] > original_txs[reassigned_tx['id']]['assignment_timestamp']
        assert reassigned_tx['assignee'] != original_txs[reassigned_tx['id']]['assignee']
예제 #12
0
def mint_coin(user_pk):
    b = Bigchain()
    coin_id = uuid.uuid4()

    for i in range(10):
        payload = {
            'coin_id': str(coin_id),
            'coin_share': str(i)
        }
        tx = b.create_transaction(b.me, user_pk, None, 'CREATE', payload=payload)
        tx_signed = b.sign_transaction(tx, b.me_private)
        b.write_transaction(tx_signed)
        print('MINT {} {} {}'.format(tx['id'], coin_id, i))
예제 #13
0
def transfer_coin(user_vk, user_sk, coin_id):
    b = Bigchain()
    coins = get_owned_coins(user_vk)

    if coin_id in coins.keys():
        for tx in coins[coin_id]:
            tx_input = {'txid': tx['id'], 'cid': 0}
            tx_transfer = b.create_transaction(user_vk, b.me, tx_input, 'TRANSFER',
                                               payload=tx['transaction']['data']['payload'])
            tx_transfer_signed = b.sign_transaction(tx_transfer, user_sk)
            b.write_transaction(tx_transfer_signed)
            print('TRANSFER {} {} {}'.format(tx_transfer_signed['id'],
                                             coin_id, tx['transaction']['data']['payload']['coin_share']))
예제 #14
0
def mint_coin(user_pk):
    b = Bigchain()
    coin_id = uuid.uuid4()

    for i in range(10):
        payload = {'coin_id': str(coin_id), 'coin_share': str(i)}
        tx = b.create_transaction(b.me,
                                  user_pk,
                                  None,
                                  'CREATE',
                                  payload=payload)
        tx_signed = b.sign_transaction(tx, b.me_private)
        b.write_transaction(tx_signed)
        print('MINT {} {} {}'.format(tx['id'], coin_id, i))
예제 #15
0
    def requeue_transactions(self):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        while True:
            invalid_block = self.q_invalid_blocks.get()

            # poison pill
            if invalid_block == 'stop':
                logger.info('clean exit')
                return

            b = Bigchain()
            for tx in invalid_block['block']['transactions']:
                b.write_transaction(tx)
예제 #16
0
    def requeue_transactions(self):
        """
        Liquidates transactions from invalid blocks so they can be processed again
        """
        while True:
            invalid_block = self.q_invalid_blocks.get()

            # poison pill
            if invalid_block == 'stop':
                logger.info('clean exit')
                return

            b = Bigchain()
            for tx in invalid_block['block']['transactions']:
                b.write_transaction(tx)
예제 #17
0
def pay_royalties(label_vk, artist_vk, tx, label_share=7, artist_share=3):
    b = Bigchain()

    payload = tx['transaction']['data']['payload']
    tx_input = {'txid': tx['id'], 'cid': 0}
    if int(payload['coin_share']) < artist_share:
        new_owner = artist_vk
    else:
        new_owner = label_vk

    tx_royalties = b.create_transaction(b.me, new_owner, tx_input, 'TRANSFER', payload=payload)
    tx_royalties_signed = b.sign_transaction(tx_royalties, b.me_private)
    b.write_transaction(tx_royalties_signed)
    print('ROYALTIES {} {} {} {}'.format(tx_royalties['id'], payload['coin_id'],
                                        payload['coin_share'], new_owner))
예제 #18
0
def transfer_coin(user_vk, user_sk, coin_id):
    b = Bigchain()
    coins = get_owned_coins(user_vk)

    if coin_id in coins.keys():
        for tx in coins[coin_id]:
            tx_input = {'txid': tx['id'], 'cid': 0}
            tx_transfer = b.create_transaction(
                user_vk,
                b.me,
                tx_input,
                'TRANSFER',
                payload=tx['transaction']['data']['payload'])
            tx_transfer_signed = b.sign_transaction(tx_transfer, user_sk)
            b.write_transaction(tx_transfer_signed)
            print('TRANSFER {} {} {}'.format(
                tx_transfer_signed['id'], coin_id,
                tx['transaction']['data']['payload']['coin_share']))
예제 #19
0
def pay_royalties(label_vk, artist_vk, tx, label_share=7, artist_share=3):
    b = Bigchain()

    payload = tx['transaction']['data']['payload']
    tx_input = {'txid': tx['id'], 'cid': 0}
    if int(payload['coin_share']) < artist_share:
        new_owner = artist_vk
    else:
        new_owner = label_vk

    tx_royalties = b.create_transaction(b.me,
                                        new_owner,
                                        tx_input,
                                        'TRANSFER',
                                        payload=payload)
    tx_royalties_signed = b.sign_transaction(tx_royalties, b.me_private)
    b.write_transaction(tx_royalties_signed)
    print('ROYALTIES {} {} {} {}'.format(tx_royalties['id'],
                                         payload['coin_id'],
                                         payload['coin_share'], new_owner))
prdct_pubkey = base58.b58encode(prdct_pubkey)


# Define a private and public key representing the producer
prdusr_privkey, prdusr_pubkey = crypto.generate_key_pair()

# Define a private and public key representing a future product owner
ownr_privkey, ownr_pubkey = crypto.generate_key_pair()

# Create a multisig transaction including the three pre-produced public keys signed with
# master key of the BigchainDB instance holder
tx_msig = b.create_transaction(b.me, [prdct_pubkey, prdusr_pubkey, ownr_pubkey], None, 'CREATE')

# Sign the multisig
tx_msig_signed = b.sign_transaction(tx_msig, b.me_private)

# Write the signed multig transaction to the federated BigchainDB
# Results in {'deleted': 0, 'unchanged': 0, 'errors': 0, 'skipped': 0, 'inserted': 1, 'replaced': 0}
b.write_transaction(tx_msig_signed)

# Check the uploaded multisig transaction
tx_msig_retrieved = b.get_transaction(tx_msig_signed['id'])

"""

Has to result in JSON string like :

{'transaction': {'timestamp': '1481491650', 'operation': 'CREATE', 'data': {'uuid': 'f75d216a-1966-4cef-8de4-71ce57563aae', 'payload': None}, 'conditions': [{'cid': 0, 'condition': {'details': {'type_id': 2, 'subfulfillments': [{'signature': None, 'weight': 1, 'public_key': '5GjT173hXbwm9R5x2Sk4y6NgeqCCA2JrwdyZdzKPvC6a', 'type_id': 4, 'type': 'fulfillment', 'bitmask': 32}, {'signature': None, 'weight': 1, 'public_key': '3NdRQzR9x1vuPJmHcKFJzFZnErjs3NS9LVCzU5UWDrQt', 'type_id': 4, 'type': 'fulfillment', 'bitmask': 32}, {'signature': None, 'weight': 1, 'public_key': 'BSoNeHng8wc1CJXF4gwTKZYQDuL6AXKuNuisQ57VZDuo', 'type_id': 4, 'type': 'fulfillment', 'bitmask': 32}], 'type': 'fulfillment', 'threshold': 3, 'bitmask': 41}, 'uri': 'cc:2:29:Qy_H1gssES5-IxGKOJv-pNtUDEz17TmGAlJn6rDkriE:306'}, 'new_owners': ['5GjT173hXbwm9R5x2Sk4y6NgeqCCA2JrwdyZdzKPvC6a', '3NdRQzR9x1vuPJmHcKFJzFZnErjs3NS9LVCzU5UWDrQt', 'BSoNeHng8wc1CJXF4gwTKZYQDuL6AXKuNuisQ57VZDuo']}], 'fulfillments': [{'current_owners': ['5sShezEyMTWsSM7D4mHVLBMksEr3AxNdP7RB9XjgEm59'], 'input': None, 'fid': 0, 'fulfillment': 'cf:4:SFrZKwost0FPXd7KN210xFM47KHIweSunvI5Ue6LkljQADZJ9AidR9JdR_B8rN-PX_qbz5meeGTJdf8oJPxa4rR3K-_eTh6yLNYnTeBjA_i4N9cE3rukkAzZGpGV1FwK'}]}, 'id': 'bd36ee938e6b5b1cf1b54eed2537c38445eaad672d3c882288cfc01f22b56a14', 'version': 1}

"""
# create a test user
testuser1_priv, testuser1_pub = crypto.generate_key_pair()

# define a digital asset data payload
digital_asset_payload = {'msg': 'Hello BigchainDB!'}

# a create transaction uses the operation `CREATE` and has no inputs
tx = b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=digital_asset_payload)

# all transactions need to be signed by the user creating the transaction
tx_signed = b.sign_transaction(tx, b.me_private)

# write the transaction to the bigchain
# the transaction will be stored in a backlog where it will be validated,
# included in a block, and written to the bigchain
b.write_transaction(tx_signed)

sleep(8)

"""
Read the Creation Transaction from the DB
"""

tx_retrieved = b.get_transaction(tx_signed['id'])

print(json.dumps(tx_retrieved, sort_keys=True, indent=4, separators=(',', ':')))

print(testuser1_pub)
print(b.me)

print(tx_retrieved['id'])
예제 #22
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(" ")
예제 #23
0
payload_A = {
            "msg" : "node send -50 to A,is -50",
            "issue" : "cost",
            "category" : "currency",
            "amount" : 50,
            "asset":"",
            # final owner 's account
            "account":300,
            "previous":testuser1_last['txid'],
            "trader":testuser2_pub
          }

tx_create= b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=payload_A)
tx_create_signed = b.sign_transaction(tx_create, b.me_private)
if b.is_valid_transaction(tx_create_signed):
    b.write_transaction(tx_create_signed)

# node create transaction for b,
testuser2_last=b.get_owned_ids(testuser2_pub).pop()
payload_B = {
            "msg" : "node send +50 to B,is +50",
            "issue" : "earn",
            "category" : "currency",
            "amount" : 50,
            "asset":"",
            # final owner 's account
            "account":400,
            "previous":testuser2_last['txid'],
            "trader":testuser1_pub
          }
예제 #24
0
# "PRICE":  "50" ,
# "QUANTITY":  "50000" ,
# "SIDE":  "S" ,
# "TYPE":  "EQ"
# },
# ...]
data = []
with open('data.csv', 'r') as fid:
    reader = csv.DictReader(fid)
    for row in reader:
        data.append(row)

# generate distinct users from the CPTY1 column and assign keys
users = []
for user_name in set([d['CPTY1'] for d in data]):
    sk, vk = b.generate_keys()
    user = users.append(
        {
            'name': user_name,
            'signing_key': sk,
            'verifying_key': vk
        }
    )

# create assets on the blockchain with the payload and assign to the user
for asset in data:
    user = [u for u in users if u['name'] == asset['CPTY1']][0]
    tx = b.create_transaction(b.me, user['verifying_key'], None, 'CREATE', payload=asset)
    tx_signed = b.sign_transaction(tx, b.me_private)
    b.write_transaction(tx_signed)
예제 #25
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(" ")
예제 #26
0
class ChainQuery(object):

    def __init__(self, host=None, port=None, dbname=None,pub_key=None,priv_key=None,keyring=[],
                 consensus_plugin=None):
         self.host = host
         self.port = port
         self.dbname = dbname
         self.conn =r.connect(host=host,port=port,db=dbname)
         self.bigchain=Bigchain(host=host,port=port,dbname=dbname,public_key=pub_key,private_key=priv_key,keyring=keyring,consensus_plugin=consensus_plugin)

    #test
    def test(self):
        tables=r.db('bigchain').table_list().run(self.conn)
        #print(tables)
        return tables

    # create key_pair for user
    def generate_key_pair(self):
        return crypto.generate_key_pair()

    # create asset
    def create_asset(self,public_key, digital_asset_payload):
        tx = self.bigchain.create_transaction(self.bigchain.me, public_key, None, 'CREATE', payload=digital_asset_payload)
        tx_signed = self.bigchain.sign_transaction(tx, self.bigchain.me_private)
        return self.bigchain.write_transaction(tx_signed)

    # get transaction by payload_uuid
    def getTxid_by_payload_uuid(self,payload_uuid):
        cursor = r.table('bigchain') \
            .get_all(payload_uuid, index='payload_uuid') \
            .pluck({'block':{'transactions':'id'}}) \
            .run(self.conn)

        transactions = list(cursor)
        return transactions

    # get transaction by payload
    def getTxid_by_payload(self,payload):
        pass


    # get currentowner of a payload(assert)
    def getOwnerofAssert(self,payload):
        return


    # get one's assert
    def get_owned_asserts(self,pub_key):
        return

    # if tx contains someone
    def tx_contains_one(self,tx,one_pub):
        for condition in tx['conditions']:
            if one_pub in condition['new_owners']:
                return True
        for fullfillment in tx['fulfillments']:
            if one_pub in fullfillment['current_owners']:
                return True


    # transfer assert to another, old_owner create this transaction,so need old_owner's pub/priv key.
    def transfer_assert(self,old_owner_pub,old_owner_priv,new_owner_pub,tx_id):
        tx_transfer=self.bigchain.create_transaction(old_owner_pub,new_owner_pub,tx_id,'TRANSFER')
        tx_transfer_signed=self.bigchain.sign_transaction(tx_transfer,old_owner_priv)
        #check if the transaction is valid
        check=self.bigchain.is_valid_transaction(tx_transfer_signed)
        if check:
            self.bigchain.write_transaction(tx_transfer_signed)
        else:
            logger.info('this transaction is invalid.')
예제 #27
0
from bigchaindb import Bigchain
import writeout
import random

b = Bigchain()

random.seed(3)

for x in range(1,8):
    # define a digital asset data payload
    digital_asset_payload = {'choice': random.randint(0,100)}

    # a create transaction uses the operation `CREATE` and has no inputs
    priv, pub = writeout.importData("user"+str(x))
    tx = b.create_transaction(b.me, pub, None, 'CREATE', payload=digital_asset_payload)
    #tx = b.create_transaction(b.me, pub, None, 'CREATE')


    # all transactions need to be signed by the user creating the transaction
    tx_signed = b.sign_transaction(tx, b.me_private)
    writeout.exportData(tx_signed, "user"+str(x)+"vote")

    # write the transaction to the bigchain
    # the transaction will be stored in a backlog where it will be validated,
    # included in a block, and written to the bigchain
    print(b.write_transaction(tx_signed))


예제 #28
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(" ")
예제 #29
0
b = Bigchain()

govt_priv, govt_pub = writeout.importData("govt")

for x in range(1,8):
    priv, pub = writeout.importData("user"+str(x))
    tx_signed = writeout.importData("user"+str(x)+"vote")
    tx_retrieved = b.get_transaction(tx_signed['id'])
    print(tx_retrieved)


    # create a transfer transaction
    tx_transfer = b.create_transaction(pub, govt_pub, tx_retrieved['id'], 'TRANSFER')
    print(tx_transfer)

    # sign the transaction
    tx_transfer_signed = b.sign_transaction(tx_transfer, priv)
    print(tx_transfer_signed)

    # write the transaction
    b.write_transaction(tx_transfer_signed)

    # check if the transaction is already in the bigchain
    tx_transfer_retrieved = b.get_transaction(tx_transfer_signed['id'])

    print(tx_transfer_retrieved)

    data = b.validate_transaction(tx_transfer_signed)
    print(data)
def transactions(request, format=None):
    '''
    URL:
      transactions/
    Use for:
      get or create bill transaction
    Para:
      GET:
        field - filter every json dict
        operation - CREATE or TRANSFER
        limit - limit list length, less than 100
        sortby - sort by specified field, for timestamp
        order - the order for sort, asc or des, default asc
        receive_pubk - public key to get all transactions`id by receive,
          do not support some paras like limit
        origin_pubk - public key to get all transactions`id by origin
      POST:
        origin_pubk - transaction origin public key, if no this value, will
          create one CREATE transaction
        origin_prik - transaction origin private key, if no this value, will
          create one CREATE transaction
        pre_txid - previous transaction id
        receive_pubk - transaction receive public key
        data - data json string
    '''
    if request.method == 'GET':
        # get paras
        fields = request.GET.getlist('field')
        limit = request.GET.get('limit', None)
        sortby = request.GET.get('sortby', None)
        order = request.GET.get('order', None)
        receive_pubk = request.GET.get('receive_pubk', None)
        origin_pubk = request.GET.get('origin_pubk', None)
        operation = request.GET.get('operation', None)
        # make sort function for rethinkdb driver
        sort_func = None
        if sortby != None:
            sort_func = lambda ts: ts['transaction'][sortby]
        # make filter
        filtes_funcs = []
        if receive_pubk != None:
            filtes_funcs.append(lambda x: x['transaction'].contains(lambda x: \
                       x['conditions'].contains(lambda x: x['new_owners'].\
                       contains(receive_pubk))))
        elif origin_pubk != None:
            filtes_funcs.append(lambda x: x['transaction'].contains(lambda x: \
                       x['fulfillments'].contains(lambda x: x['current_owners'].\
                       contains(origin_pubk))))
        if operation != None:
            filtes_funcs.append(lambda t: t.contains(\
                lambda x: x['transaction']['operation'] == operation))
        # get datas
        datas = rdb_select(sortby=sort_func,
                           order=order,
                           filtes=filtes_funcs,
                           keys=['block', 'transactions'],
                           limit=limit)
        # can`t pluck, limit this data by rethinkdb driver, handle with hand
        # limit
        try:
            limit = int(limit)
        except TypeError:
            limit = 100
        limit = min(100, limit)  # limit less than 100
        # return datas by max operation
        if limit == 1 and sortby != None:
            return Response(field_filter(datas[0], fields))
        # return normal datas, it`s format willbe [[d1, ...], [d2, ..], ...]
        #  change format to [d1, d2, d3...]
        ans = []
        for alist in datas:
            for data in alist:
                if len(ans) >= limit:
                    return Response(ans)
                ans.append(field_filter(data, fields))  # filter data

        return Response(ans)
    elif request.method == 'POST':
        # get paras
        origin_pubk = request.POST.get('origin_pubk', None)
        origin_prik = request.POST.get('origin_prik', None)
        pre_txid = request.POST.get('pre_txid', None)
        receive_pubk = request.POST.get('receive_pubk', None)
        data = request.POST.get('data', '{}')
        # make sure paras
        receive_prik = ''
        bdb_input = None
        bdb_type = 'CREATE'
        bdb = Bigchain()
        try:
            data = json.loads(data)  # json string to json data
        except JSONDecodeError:
            return error(400, 'Wrong json string format')
        # bill data format checker
        left_money = 0
        pre_data = None
        billm = 'Bill_amount_money'
        bill = 'bill'
        if billm not in data.keys():
            return error(400, 'Wrong data format')
        # make sure paras
        if receive_pubk == None:  # create a pair
            receive_prik, receive_pubk = crypto.generate_key_pair()
        if origin_pubk == None:  # create transaction
            origin_pubk = bdb.me
            origin_prik = bdb.me_private
        else:  # transfer transaction
            bdb_type = 'TRANSFER'
            if origin_prik == None:
                return error(400, 'need private key')
            if pre_txid == None:
                return error(400, 'need pre_txid when transfer')
            # get previous bill, and check it
            pre_tx = bdb.get_transaction(pre_txid)
            if pre_tx == None:
                return error(400, 'This pre_txid does not exist')
            # make input, in our case, the key 'cid' will always be 0
            bdb_input = {'cid': 0, 'txid': pre_txid}
            # check bdb_input belong origin
            if bdb_input not in bdb.get_owned_ids(origin_pubk):
                return error(400, 'This pre_txid does not belong the origin')
            # money check
            pre_data = pre_tx['transaction']['data']['payload']
            pre_money = pre_data[bill][billm]
            now_money = data[billm]
            if now_money > pre_money:
                return error(400, 'money to less')
            left_money = pre_money - now_money
        # start transaction
        tx = bdb.create_transaction(origin_pubk,
                                    receive_pubk,
                                    bdb_input,
                                    bdb_type,
                                    payload={
                                        'pre_txid': pre_txid,
                                        'bill': data
                                    })
        bdb.write_transaction(bdb.sign_transaction(tx, origin_prik))
        # create new bill with left money
        if pre_data != None:
            # change data
            pre_data[bill][billm] = left_money
            pre_data['pre_txid'] = pre_txid
            ltx = bdb.create_transaction(bdb.me,
                                         origin_pubk,
                                         None,
                                         'CREATE',
                                         payload=pre_data)
            bdb.write_transaction(bdb.sign_transaction(ltx, bdb.me_private))
        return Response({
            'txid': tx['id'],
            'receive_pubk': receive_pubk,
            'receive_prik': receive_prik
        })
예제 #31
0
print("testuser1_priv:" + testuser1_priv)
print("testuser1_pub:" + testuser1_pub)
payload = {
    "msg": "first charge for user A",
    "issue": "charge",
    "category": "currency",
    "amount": 300,
    "asset": "",
    "account": 0,
    "previous": "genesis",
    "trader": ""
}
tx = b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=payload)
tx_signed = b.sign_transaction(tx, b.me_private)
if b.is_valid_transaction(tx_signed):
    b.write_transaction(tx_signed)
    print(tx_signed)

# user B
testuser2_priv, testuser2_pub = crypto.generate_key_pair()
print("testuser2_priv:" + testuser2_priv)
print("testuser2_pub:" + testuser2_pub)
payload2 = {
    "msg": "first charge for user B",
    "issue": "charge",
    "category": "currency",
    "amount": 400,
    "asset": "",
    "account": 0,
    "previous": "genesis",
    "trader": ""
예제 #32
0
from bigchaindb import Bigchain
import writeout
import random

b = Bigchain()

random.seed(3)

for x in range(1, 8):
    # define a digital asset data payload
    digital_asset_payload = {'choice': random.randint(0, 100)}

    # a create transaction uses the operation `CREATE` and has no inputs
    priv, pub = writeout.importData("user" + str(x))
    tx = b.create_transaction(b.me,
                              pub,
                              None,
                              'CREATE',
                              payload=digital_asset_payload)
    #tx = b.create_transaction(b.me, pub, None, 'CREATE')

    # all transactions need to be signed by the user creating the transaction
    tx_signed = b.sign_transaction(tx, b.me_private)
    writeout.exportData(tx_signed, "user" + str(x) + "vote")

    # write the transaction to the bigchain
    # the transaction will be stored in a backlog where it will be validated,
    # included in a block, and written to the bigchain
    print(b.write_transaction(tx_signed))
예제 #33
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))
예제 #34
0
def create_transfer(public_key, private_key, include_spent):
    asset = Asset(data={
        "bicycle": {
            "manufacturer": "bkfab",
            "serial_number": "abcd1234"
        }
    },
                  data_id="334cd061-846b-4213-bd25-588e951def5f")

    ##################################################### 1.getfreeze
    b = Bigchain()

    utxo_freeze = b.get_freeze_outputs_only(public_key)

    # for u in utxo_freeze:
    #     # print(u)
    #     u.pop('details')
    print('userA frozen asset:')
    print(json.dumps(utxo_freeze, indent=4))
    # print(json.load(utxo))

    #
    # ##################################################### 2.Unfreeze
    inputs = []
    balance = 0
    for i in utxo_freeze:
        f = Fulfillment.from_dict({
            'fulfillment': i['details'],
            'input': {
                'cid': i['cid'],
                'txid': i['txid'],
            },
            'owners_before': [public_key],
        })
        inputs.append(f)
        balance += i['amount']

    # create trnsaction
    tx = Transaction.freeze_asset(inputs, [([public_key], balance, False)],
                                  asset)
    # #  inputs and asset

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

    # write to backlog
    b = Bigchain()
    b.write_transaction(tx)
    print("unfreeze 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("unfreeze asset tx1_id:" + tx.to_dict()['id'])

    ##################################################### 3.UTXO
    #  inputs and asset
    utxo = b.get_outputs_filtered_not_include_freeze(public_key, include_spent)
    for u in utxo:
        # print(u)
        u.pop('details')
    print('userA unspent asset:')
    print(json.dumps(utxo, indent=4))
예제 #35
0
class ChainQuery(object):
    def __init__(
        self, host=None, port=None, dbname=None, pub_key=None, priv_key=None, keyring=[], consensus_plugin=None
    ):
        self.host = host
        self.port = port
        self.dbname = dbname
        self.conn = r.connect(host=host, port=port, db=dbname)
        self.bigchain = Bigchain(
            host=host,
            port=port,
            dbname=dbname,
            public_key=pub_key,
            private_key=priv_key,
            keyring=keyring,
            consensus_plugin=consensus_plugin,
        )

    # test
    def test(self):
        tables = r.db("bigchain").table_list().run(self.conn)
        # print(tables)
        return tables

    # create key_pair for user
    def generate_key_pair(self):
        return crypto.generate_key_pair()

    # create asset
    def create_asset(self, public_key, digital_asset_payload):
        tx = self.bigchain.create_transaction(
            self.bigchain.me, public_key, None, "CREATE", payload=digital_asset_payload
        )
        tx_signed = self.bigchain.sign_transaction(tx, self.bigchain.me_private)
        return self.bigchain.write_transaction(tx_signed)

    # get transaction by payload_uuid
    def getTxid_by_payload_uuid(self, payload_uuid):
        cursor = (
            r.table("bigchain")
            .get_all(payload_uuid, index="payload_uuid")
            .pluck({"block": {"transactions": "id"}})
            .run(self.conn)
        )

        transactions = list(cursor)
        return transactions

    # get transaction by payload
    def getTxid_by_payload(self, payload):
        pass

    # get currentowner of a payload(assert)
    def getOwnerofAssert(self, payload):
        return

    # get one's assert
    def get_owned_asserts(self, pub_key):
        return

    # if tx contains someone
    def tx_contains_one(self, tx, one_pub):
        for condition in tx["conditions"]:
            if one_pub in condition["new_owners"]:
                return True
        for fullfillment in tx["fulfillments"]:
            if one_pub in fullfillment["current_owners"]:
                return True

    # transfer assert to another, old_owner create this transaction,so need old_owner's pub/priv key.
    def transfer_assert(self, old_owner_pub, old_owner_priv, new_owner_pub, tx_id):
        tx_transfer = self.bigchain.create_transaction(old_owner_pub, new_owner_pub, tx_id, "TRANSFER")
        tx_transfer_signed = self.bigchain.sign_transaction(tx_transfer, old_owner_priv)
        # check if the transaction is valid
        check = self.bigchain.is_valid_transaction(tx_transfer_signed)
        if check:
            self.bigchain.write_transaction(tx_transfer_signed)
        else:
            logger.info("this transaction is invalid.")
예제 #36
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(" ")