示例#1
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))
示例#2
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()
示例#3
0
def get():
    # Cryptographic Identities Generation
    alice, bob = generate_keypair(), generate_keypair()
    print(" ")
    # 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],
                            metadata=metadata,
                            asset=asset)

    # sign with private key
    tx = tx.sign([alice.private_key])
    # get tx by id
    b = Bigchain()

    block = b.create_block([tx])
    block_voters = block.to_dict()['block']['voters']
    print(block_voters)
    tx_id = '2cb004cad29c0b79872646558f8c867a4c0aecbc4997f0917'
    tx = b.get_transaction(tx_id)
    print(
        "block status         : ",
        b.block_election_status(
            '2257384a0cee8cf98bd82c3142dd38eee5c268c124b5b357b773b8c6c1fa1221',
            block_voters))
示例#4
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))
示例#5
0
class Block:
    """This class encapsulates the logic to create blocks.

    Note:
        Methods of this class will be executed in different processes.
    """

    def __init__(self):
        """Initialize the Block creator"""
        self.bigchain = Bigchain()
        self.txs = []

    def filter_tx(self, tx):
        """Filter a transaction.

        Args:
            tx (dict): the transaction to process.

        Returns:
            The transaction if assigned to the current node,
            ``None`` otherwise.
        """

        if tx['assignee'] == self.bigchain.me:
            tx.pop('assignee')
            tx.pop('assignment_timestamp')
            return tx

    def validate_tx(self, tx):
        """Validate a transaction.
        Also checks if the transaction already exists in the blockchain. If it
        does, or it's invalid, it's deleted from the backlog immediately.
        Args:
            tx (dict): the transaction to validate.
        Returns:
            The transaction if valid, ``None`` otherwise.
        """
        if self.bigchain.transaction_exists(tx['id']):
            # if the transaction already exists, we must check whether
            # it's in a valid or undecided block
            tx, status = self.bigchain.get_transaction(tx['id'],
                                                       include_status=True)
            if status == self.bigchain.TX_VALID \
               or status == self.bigchain.TX_UNDECIDED:
                # if the tx is already in a valid or undecided block,
                # then it no longer should be in the backlog, or added
                # to a new block. We can delete and drop it.
                r.table('backlog').get(tx['id']) \
                        .delete(durability='hard') \
                        .run(self.bigchain.conn)
                return None

        tx_validated = self.bigchain.is_valid_transaction(tx)
        if tx_validated:
            return tx
        else:
            # if the transaction is not valid, remove it from the
            # backlog
            r.table('backlog').get(tx['id']) \
                    .delete(durability='hard') \
                    .run(self.bigchain.conn)
            return None

    def create(self, tx, timeout=False):
        """Create a block.

        This method accumulates transactions to put in a block and outputs
        a block when one of the following conditions is true:
        - the size limit of the block has been reached, or
        - a timeout happened.

        Args:
            tx (dict): the transaction to validate, might be None if
                a timeout happens.
            timeout (bool): ``True`` if a timeout happened
                (Default: ``False``).

        Returns:
            The block, if a block is ready, or ``None``.
        """
        if tx:
            self.txs.append(tx)
        if len(self.txs) == 1000 or (timeout and self.txs):
            block = self.bigchain.create_block(self.txs)
            self.txs = []
            return block

    def write(self, block):
        """Write the block to the Database.

        Args:
            block (dict): the block of transactions to write to the database.

        Returns:
            The block.
        """
        logger.info('Write new block %s with %s transactions',
                    block['id'],
                    len(block['block']['transactions']))
        self.bigchain.write_block(block)
        return block

    def delete_tx(self, block):
        """Delete transactions.
        Args:
            block (dict): the block containg the transactions to delete.
        Returns:
            The block.
        """
        r.table('backlog')\
         .get_all(*[tx['id'] for tx in block['block']['transactions']])\
         .delete(durability='hard')\
         .run(self.bigchain.conn)

        return block
示例#6
0
from bigchaindb import Bigchain
import writeout

b = Bigchain()


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

示例#7
0
import hashlib
# monkey patch hashlib with sha3 functions
import sha3
import json

from bigchaindb import Bigchain
import writeout

b = Bigchain()

user1priv, user1pub = writeout.importData("user1")
user2priv, user2pub = writeout.importData("user2")
user3priv, user3pub = writeout.importData("user3")
govt_priv, govt_pub = writeout.importData("govt")

gids = b.get_owned_ids(govt_pub)

for id in gids:
    t = b.get_transaction(id)
    print(t)

#data = {'vote': 30}
#tx_serialized = bytes(json.dumps(data, skipkeys=False, ensure_ascii=False, separators=(',', ':')).encode("utf-8"))
#tx_hash = hashlib.sha3_256(tx_serialized).hexdigest()
#txs = b.get_tx_by_payload_hash(tx_hash)
#for tx in txs:
#    print(tx)
示例#8
0
from bigchaindb import Bigchain
import writeout

b = Bigchain()

for x in range(1, 8):
    tx_signed = writeout.importData("user" + str(x) + "vote")
    tx_retrieved = b.get_transaction(tx_signed['id'])
    print(b.transaction_exists(tx_retrieved['id']))
示例#9
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(" ")
示例#10
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(" ")
示例#11
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))
示例#12
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))
# 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'])

"""
Transfer the Digital Asset
"""

# create a second testuser
testuser2_priv, testuser2_pub = crypto.generate_key_pair()
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
        })
示例#15
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(" ")
示例#16
0
class Block:
    """This class encapsulates the logic to create blocks.

    Note:
        Methods of this class will be executed in different processes.
    """

    def __init__(self):
        """Initialize the Block creator"""
        self.bigchain = Bigchain()
        self.txs = []

    def filter_tx(self, tx):
        """Filter a transaction.

        Args:
            tx (dict): the transaction to process.

        Returns:
            The transaction if assigned to the current node,
            ``None`` otherwise.
        """

        if tx['assignee'] == self.bigchain.me:
            tx.pop('assignee')
            tx.pop('assignment_timestamp')
            return tx

    def validate_tx(self, tx):
        """Validate a transaction.

        Also checks if the transaction already exists in the blockchain. If it
        does, or it's invalid, it's deleted from the backlog immediately.

        Args:
            tx (dict): the transaction to validate.

        Returns:
            The transaction if valid, ``None`` otherwise.
        """
        if self.bigchain.transaction_exists(tx['id']):
            # if the transaction already exists, we must check whether
            # it's in a valid or undecided block
            tx, status = self.bigchain.get_transaction(tx['id'],
                                                       include_status=True)
            if status == self.bigchain.TX_VALID \
               or status == self.bigchain.TX_UNDECIDED:
                # if the tx is already in a valid or undecided block,
                # then it no longer should be in the backlog, or added
                # to a new block. We can delete and drop it.
                r.table('backlog').get(tx['id']) \
                        .delete(durability='hard') \
                        .run(self.bigchain.conn)
                return None

        tx_validated = self.bigchain.is_valid_transaction(tx)
        if tx_validated:
            return tx
        else:
            # if the transaction is not valid, remove it from the
            # backlog
            r.table('backlog').get(tx['id']) \
                    .delete(durability='hard') \
                    .run(self.bigchain.conn)
            return None 

    def create(self, tx, timeout=False):
        """Create a block.

        This method accumulates transactions to put in a block and outputs
        a block when one of the following conditions is true:
        - the size limit of the block has been reached, or
        - a timeout happened.

        Args:
            tx (dict): the transaction to validate, might be None if
                a timeout happens.
            timeout (bool): ``True`` if a timeout happened
                (Default: ``False``).

        Returns:
            The block, if a block is ready, or ``None``.
        """
        if tx:
            self.txs.append(tx)
        if len(self.txs) == 1000 or (timeout and self.txs):
            block = self.bigchain.create_block(self.txs)
            self.txs = []
            return block

    def write(self, block):
        """Write the block to the Database.

        Args:
            block (dict): the block of transactions to write to the database.

        Returns:
            The block.
        """
        logger.info('Write new block %s with %s transactions',
                    block['id'],
                    len(block['block']['transactions']))
        self.bigchain.write_block(block)
        return block

    def delete_tx(self, block):
        """Delete transactions.

        Args:
            block (dict): the block containg the transactions to delete.

        Returns:
            The block.
        """
        r.table('backlog')\
         .get_all(*[tx['id'] for tx in block['block']['transactions']])\
         .delete(durability='hard')\
         .run(self.bigchain.conn)

        return block
示例#17
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(" ")