Пример #1
0
def test_post_transfer_transaction_endpoint(b, client):
    from_keypair = crypto.generate_key_pair()
    to_keypair = crypto.generate_key_pair()

    tx = util.create_and_sign_tx(from_keypair[0], from_keypair[1], from_keypair[1], None, 'CREATE')
    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    tx_id = res.json['id']

    transfer = util.create_and_sign_tx(from_keypair[0], from_keypair[1], to_keypair[1], tx_id)
    res = client.post(TX_ENDPOINT, data=json.dumps(transfer))

    assert res.json['transaction']['current_owner'] == from_keypair[1]
    assert res.json['transaction']['new_owner'] == to_keypair[1]
Пример #2
0
def test_post_transfer_transaction_endpoint(b, client):
    from_keypair = crypto.generate_key_pair()
    to_keypair = crypto.generate_key_pair()

    tx = util.create_and_sign_tx(from_keypair[0], from_keypair[1],
                                 from_keypair[1], None, 'CREATE')
    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    tx_id = res.json['id']

    transfer = util.create_and_sign_tx(from_keypair[0], from_keypair[1],
                                       to_keypair[1], tx_id)
    res = client.post(TX_ENDPOINT, data=json.dumps(transfer))

    assert res.json['transaction']['current_owners'] == [from_keypair[1]]
    assert res.json['transaction']['new_owners'] == [to_keypair[1]]
Пример #3
0
def createUser():
    """
    :arg username: Desired Username of the user to be created
    :arg password: Intended password
    :arg type: Type of the user: This can be one of the following strings: 1.CUSTOMER 2. DONOR 3. COMPANY
    :return: status of the operation and the keypairs when the user creation is success! If there is some error, it sends the errorMessage as well.

    """
    # Specifying Mandatory Arguments
    parser = reqparse.RequestParser()
    parser.add_argument(UserAttributes.USERNAME.value, required=True, type=str)
    parser.add_argument(UserAttributes.PASSWORD.value, required=True, type=str)
    parser.add_argument(UserAttributes.TYPE.value, required=True, type=str)

    username = request.get_json(force=False)[UserAttributes.USERNAME.value]
    password = request.get_json(force=False)[UserAttributes.PASSWORD.value]
    type = request.get_json(force=False)[UserAttributes.TYPE.value]

    if (not checkIfTheUserExists(username)):
        user_priv, user_pub = crypto.generate_key_pair()
        userTuple = constructUserTuple(username, password, type, user_pub,
                                       user_priv)
        insertData(DatabaseNames.CUSTOM_DB.value, TableNames.USER.value,
                   userTuple)
        return jsonify(status="success",
                       publicKey=user_pub,
                       privateKey=user_priv)
    else:
        return jsonify(status="error", errorMessage="Username Already Exists!")
Пример #4
0
def run_configure(args, skip_if_exists=False):
    """Run a script to configure the current node.

    Args:
        skip_if_exists (bool): skip the function if a conf file already exists
    """
    config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH
    config_file_exists = os.path.exists(config_path)

    if config_file_exists and skip_if_exists:
        return

    if config_file_exists and not args.yes:
        want = input('Config file `{}` exists, do you want to override it? '
                     '(cannot be undone) [y/n]: '.format(config_path))
        if not want:
            return

    # Patch the default configuration with the new values
    conf = copy.deepcopy(bigchaindb._config)

    print('Generating keypair')
    conf['keypair']['private'], conf['keypair'][
        'public'] = crypto.generate_key_pair()

    if not args.yes:
        for key in ('host', 'port', 'name'):
            val = conf['database'][key]
            conf['database'][key] = input(
                'Database {}? (default `{}`): '.format(key, val)) or val

    bigchaindb.config_utils.write_config(conf, config_path)
    print('Ready to go!')
    def test_transaction_signature(self, b):
        sk, vk = crypto.generate_key_pair()
        tx = b.create_transaction(vk, 'b', 'c', 'd')
        tx_signed = b.sign_transaction(tx, sk)

        assert 'signature' in tx_signed
        assert b.verify_signature(tx_signed)
Пример #6
0
def run_configure(args, skip_if_exists=False):
    """Run a script to configure the current node.

    Args:
        skip_if_exists (bool): skip the function if a conf file already exists
    """
    config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH
    proceed = args.yes
    config_file_exists = os.path.exists(config_path)

    if config_file_exists and skip_if_exists:
        return

    if config_file_exists and not proceed:
        want = input('Config file `{}` exists, do you want to override it? '
                     '(cannot be undone) [y/n]: '.format(config_path))
        if not want:
            return

    # Patch the default configuration with the new values
    conf = bigchaindb._config
    print('Generating keypair')
    conf['keypair']['private'], conf['keypair']['public'] = generate_key_pair()

    for key in ('host', 'port', 'name'):
        val = conf['database'][key]
        conf['database'][key] = input('Database {}? (default `{}`): '.format(key, val)) or val

    bigchaindb.config_utils.write_config(conf, config_path)
    print('Ready to go!')
Пример #7
0
 def test_generate_key_pair(self):
     private_value_base58, public_value_compressed_base58 = generate_key_pair(
     )
     assert PrivateKey.encode(
         PrivateKey.decode(private_value_base58)) == private_value_base58
     assert PublicKey.encode(*PublicKey.decode(
         public_value_compressed_base58)) == public_value_compressed_base58
Пример #8
0
def run_configure(args, skip_if_exists=False):
    """Run a script to configure the current node.

    Args:
        skip_if_exists (bool): skip the function if a config file already exists
    """
    config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH

    config_file_exists = False
    # if the config path is `-` then it's stdout
    if config_path != '-':
        config_file_exists = os.path.exists(config_path)

    if config_file_exists and skip_if_exists:
        return

    if config_file_exists and not args.yes:
        want = input('Config file `{}` exists, do you want to override it? '
                     '(cannot be undone) [y/N]: '.format(config_path))
        if want != 'y':
            return

    conf = copy.deepcopy(bigchaindb.config)

    # Patch the default configuration with the new values
    conf = bigchaindb.config_utils.update(
            conf,
            bigchaindb.config_utils.env_config(bigchaindb.config))


    print('Generating keypair', file=sys.stderr)
    conf['keypair']['private'], conf['keypair']['public'] = \
        crypto.generate_key_pair()

    if not args.yes:
        for key in ('bind', ):
            val = conf['server'][key]
            conf['server'][key] = \
                input('API Server {}? (default `{}`): '.format(key, val)) \
                or val

        for key in ('host', 'port', 'name'):
            val = conf['database'][key]
            conf['database'][key] = \
                input('Database {}? (default `{}`): '.format(key, val)) \
                or val

        for key in ('host', 'port', 'rate'):
            val = conf['statsd'][key]
            conf['statsd'][key] = \
                input('Statsd {}? (default `{}`): '.format(key, val)) \
                or val

    if config_path != '-':
        bigchaindb.config_utils.write_config(conf, config_path)
    else:
        print(json.dumps(conf, indent=4, sort_keys=True))
    print('Configuration written to {}'.format(config_path), file=sys.stderr)
    print('Ready to go!', file=sys.stderr)
Пример #9
0
 def test_if_federation_size_is_greater_than_one_ignore_past_blocks(self, b):
     for _ in range(5):
         b.federation_nodes.append(crypto.generate_key_pair()[1])
     new_blocks = mp.Queue()
     bs = BlockStream(new_blocks)
     block_1 = b.create_block([])
     new_blocks.put(block_1)
     assert block_1 == bs.get()
def get_key_pair(request, format=None):
    """
    获取秘钥
    输入:无
    输出:公钥和私钥
    """
    private_key, public_key = crypto.generate_key_pair()
    return Response({'private_key': private_key, 'public_key': public_key})
Пример #11
0
def test_post_create_transaction_endpoint(b, client):
    keypair = crypto.generate_key_pair()

    tx = util.create_and_sign_tx(keypair[0], keypair[1], keypair[1], None, 'CREATE')

    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    assert res.json['transaction']['fulfillments'][0]['current_owners'][0] == b.me
    assert res.json['transaction']['conditions'][0]['new_owners'][0] == keypair[1]
Пример #12
0
def addUser(userName):

    if False == users.__contains__(userName):
        user = type('user', (), {'name': userName, 'pub': '', 'priv': ''})

        user.priv, user.pub = crypto.generate_key_pair()

        users[userName] = user
Пример #13
0
 def test_if_federation_size_is_greater_than_one_ignore_past_blocks(self, b):
     for _ in range(5):
         b.federation_nodes.append(generate_key_pair()[1])
     new_blocks = mp.Queue()
     bs = BlockStream(new_blocks)
     block_1 = b.create_block([])
     new_blocks.put(block_1)
     assert block_1 == bs.get()
Пример #14
0
def temp_client():
    """Create a new temporary client.

    Return:
        A client initialized with a keypair generated on the fly.
    """

    private_key, public_key = crypto.generate_key_pair()
    return Client(private_key=private_key, public_key=public_key, api_endpoint=bigchaindb.config["api_endpoint"])
Пример #15
0
def test_post_transfer_transaction_endpoint(b, client, user_vk, user_sk):
    to_keypair = crypto.generate_key_pair()
    input_valid = b.get_owned_ids(user_vk).pop()

    transfer = util.create_and_sign_tx(user_sk, user_vk, to_keypair[1], input_valid)
    res = client.post(TX_ENDPOINT, data=json.dumps(transfer))

    assert res.json['transaction']['fulfillments'][0]['current_owners'][0] == user_vk
    assert res.json['transaction']['conditions'][0]['new_owners'][0] == to_keypair[1]
Пример #16
0
def run_configure(args, skip_if_exists=False):
    """Run a script to configure the current node.

    Args:
        skip_if_exists (bool): skip the function if a config file already exists
    """
    config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH

    config_file_exists = False
    # if the config path is `-` then it's stdout
    if config_path != '-':
        config_file_exists = os.path.exists(config_path)

    if config_file_exists and skip_if_exists:
        return

    if config_file_exists and not args.yes:
        want = input('Config file `{}` exists, do you want to override it? '
                     '(cannot be undone) [y/N]: '.format(config_path))
        if want != 'y':
            return

    conf = copy.deepcopy(bigchaindb.config)

    # Patch the default configuration with the new values
    conf = bigchaindb.config_utils.update(
        conf, bigchaindb.config_utils.env_config(bigchaindb.config))

    print('Generating keypair', file=sys.stderr)
    conf['keypair']['private'], conf['keypair']['public'] = \
        crypto.generate_key_pair()

    if not args.yes:
        for key in ('bind', ):
            val = conf['server'][key]
            conf['server'][key] = \
                input('API Server {}? (default `{}`): '.format(key, val)) \
                or val

        for key in ('host', 'port', 'name'):
            val = conf['database'][key]
            conf['database'][key] = \
                input('Database {}? (default `{}`): '.format(key, val)) \
                or val

        for key in ('host', 'port', 'rate'):
            val = conf['statsd'][key]
            conf['statsd'][key] = \
                input('Statsd {}? (default `{}`): '.format(key, val)) \
                or val

    if config_path != '-':
        bigchaindb.config_utils.write_config(conf, config_path)
    else:
        print(json.dumps(conf, indent=4, sort_keys=True))
    print('Configuration written to {}'.format(config_path), file=sys.stderr)
    print('Ready to go!', file=sys.stderr)
Пример #17
0
def test_post_create_transaction_endpoint(b, client):
    keypair = crypto.generate_key_pair()

    tx = util.create_and_sign_tx(keypair[0], keypair[1], keypair[1], None,
                                 'CREATE')

    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    assert res.json['transaction']['current_owners'] == [b.me]
    assert res.json['transaction']['new_owners'] == [keypair[1]]
Пример #18
0
def temp_client():
    """Create a new temporary client.

    Return:
        A client initialized with a keypair generated on the fly.
    """

    private_key, public_key = crypto.generate_key_pair()
    return Client(private_key=private_key, public_key=public_key, api_endpoint='http://localhost:5000/api/v1')
Пример #19
0
def temp_client():
    """Create a new temporary client.

    Return:
        A client initialized with a keypair generated on the fly.
    """

    private_key, public_key = crypto.generate_key_pair()
    return Client(private_key=private_key, public_key=public_key, api_endpoint=bigchaindb.config['api_endpoint'])
Пример #20
0
    def generate_keys():
        """Generates a key pair.

        Returns:
            tuple: `(private_key, public_key)`. ECDSA key pair using the secp256k1 curve encoded
            in base58.

        """
        # generates and returns the keys serialized in hex
        return generate_key_pair()
Пример #21
0
    def test_transaction_signature(self, b):
        sk, vk = generate_key_pair()
        tx = b.create_transaction(vk, 'b', 'c', 'd')

        with pytest.raises(KeyError) as excinfo:
            b.verify_signature(tx)
        tx_signed = b.sign_transaction(tx, sk)

        assert 'signatures' in tx_signed
        assert b.verify_signature(tx_signed)
Пример #22
0
def generate_key_pair():
    """API endpoint to generate key pair.
            Returns:
                a json data of key pair.
                json format:
                {
                    "public_key":public_key,
                    "private_key":private_key
                }
            """
    private_key, public_key = crypto.generate_key_pair()
    dict = {"public_key": public_key, "private_key": private_key}
    return flask.jsonify(**dict)
Пример #23
0
def generate_key_pair():
    """API endpoint to generate key pair.
            Returns:
                a json data of key pair.
                json format:
                {
                    "public_key":public_key,
                    "private_key":private_key
                }
            """
    private_key,public_key=crypto.generate_key_pair()
    dict={
        "public_key":public_key,
        "private_key":private_key
    }
    return flask.jsonify(**dict)
    def test_assign_transaction_multiple_nodes(self, b, user_public_key, user_private_key):
        # create 5 federation nodes
        for _ in range(5):
            b.federation_nodes.append(crypto.generate_key_pair()[1])

        # test assignee for several transactions
        for _ in range(20):
            input_tx = b.get_owned_ids(user_public_key).pop()
            tx = b.create_transaction(user_public_key, 'b', input_tx, 'd')
            tx_signed = b.sign_transaction(tx, user_private_key)
            b.write_transaction(tx_signed)

            # retrieve the transaction
            response = r.table('backlog').get(tx_signed['id']).run(b.conn)

            # check if the assignee is the federation_nodes
            assert response['assignee'] in b.federation_nodes
Пример #25
0
    def test_valid_block_voting_with_create_transaction(self, b):
        q_new_block = mp.Queue()

        genesis = b.create_genesis_block()

        # create a `CREATE` transaction
        test_user_priv, test_user_pub = generate_key_pair()
        tx = b.create_transaction(b.me, test_user_pub, None, 'CREATE')
        tx_signed = b.sign_transaction(tx, b.me_private)
        assert b.is_valid_transaction(tx_signed)

        # create valid block
        block = b.create_block([tx_signed])
        # assert block is valid
        assert b.is_valid_block(block)
        b.write_block(block, durability='hard')

        # create queue and voter
        voter = Voter(q_new_block)

        # vote
        voter.start()
        # wait for vote to be written
        time.sleep(1)
        voter.kill()

        # retrive block from bigchain
        blocks = list(r.table('bigchain')
                       .order_by(r.asc((r.row['block']['timestamp'])))
                       .run(b.conn))

        # validate vote
        assert len(blocks[1]['votes']) == 1
        vote = blocks[1]['votes'][0]

        assert vote['vote']['voting_for_block'] == block['id']
        assert vote['vote']['previous_block'] == genesis['id']
        assert vote['vote']['is_block_valid'] is True
        assert vote['vote']['invalid_reason'] is None
        assert vote['node_pubkey'] == b.me
        assert PublicKey(b.me).verify(util.serialize(vote['vote']), vote['signature']) is True
Пример #26
0
    def test_valid_block_voting_with_create_transaction(self, b):
        q_new_block = mp.Queue()

        genesis = b.create_genesis_block()

        # create a `CREATE` transaction
        test_user_priv, test_user_pub = crypto.generate_key_pair()
        tx = b.create_transaction(b.me, test_user_pub, None, 'CREATE')
        tx_signed = b.sign_transaction(tx, b.me_private)
        assert b.is_valid_transaction(tx_signed)

        # create valid block
        block = b.create_block([tx_signed])
        # assert block is valid
        assert b.is_valid_block(block)
        b.write_block(block, durability='hard')

        # create queue and voter
        voter = Voter(q_new_block)

        # vote
        voter.start()
        # wait for vote to be written
        time.sleep(1)
        voter.kill()

        # retrive block from bigchain
        blocks = list(r.table('bigchain')
                       .order_by(r.asc((r.row['block']['timestamp'])))
                       .run(b.conn))

        # validate vote
        assert len(blocks[1]['votes']) == 1
        vote = blocks[1]['votes'][0]

        assert vote['vote']['voting_for_block'] == block['id']
        assert vote['vote']['previous_block'] == genesis['id']
        assert vote['vote']['is_block_valid'] is True
        assert vote['vote']['invalid_reason'] is None
        assert vote['node_pubkey'] == b.me
        assert crypto.VerifyingKey(b.me).verify(util.serialize(vote['vote']), vote['signature']) is True
def create_common_transaction(request, format=None):
    """
    通用交易插入函数
    输入:数据,前一个交易id(previous_process_tx_id)
    输出:交易id
    """
    data = request.data
    previous_process_tx_id = data.pop('previous_process_tx_id', None)
    # 将content转为unicode string存储
    content = str(data['content']).encode('unicode-escape')
    private_key, public_key = crypto.generate_key_pair()
    tx = b.create_transaction(b.me,
                              public_key,
                              None,
                              'CREATE',
                              payload={
                                  'previous_process_tx_id':
                                  previous_process_tx_id,
                                  'content': content
                              })
    tx_signed = b.sign_transaction(tx, b.me_private)
    b.write_transaction(tx_signed)
    return Response({'id': tx_signed['id']})
Пример #28
0
    def test_transaction_signature_multiple_owners(self, b):
        num_current_owners = 42
        sk, vk = [], []
        for _ in range(num_current_owners):
            sk_, vk_ = generate_key_pair()
            sk.append(sk_)
            vk.append(vk_)
        tx = b.create_transaction(vk, 'b', 'c', 'd')
        tx_signed = tx

        with pytest.raises(KeyError) as excinfo:
            b.verify_signature(tx_signed)

        for i in range(num_current_owners):
            if i > 0:
                assert b.verify_signature(tx_signed) is False
            tx_signed = b.sign_transaction(tx_signed, sk[i], vk[i])

        assert 'signatures' in tx_signed
        assert 'public_key' in tx_signed['signatures'][0]
        assert 'signature' in tx_signed['signatures'][0]
        assert len(tx_signed['signatures']) == num_current_owners
        assert b.verify_signature(tx_signed)
Пример #29
0
import copy
import json

import cryptoconditions as cc
from bigchaindb import util, crypto

signature_treshold = 1
# signature_treshold = 2

# Create some new testusers
thresholduser1_priv, thresholduser1_pub = crypto.generate_key_pair()
thresholduser2_priv, thresholduser2_pub = crypto.generate_key_pair()

# Retrieve the last transaction of testuser2
tx_retrieved_id = b.get_owned_ids(testuser2_pub).pop()

# Create a base template for a 1-input/2-output transaction
threshold_tx = b.create_transaction(testuser2_pub, [thresholduser1_pub, thresholduser2_pub], tx_retrieved_id, 'TRANSFER')

# Create a Threshold Cryptocondition
threshold_condition = cc.ThresholdSha256Fulfillment(threshold=signature_treshold)
threshold_condition.add_subfulfillment(cc.Ed25519Fulfillment(public_key=thresholduser1_pub))
threshold_condition.add_subfulfillment(cc.Ed25519Fulfillment(public_key=thresholduser2_pub))

# Update the condition in the newly created transaction
threshold_tx['transaction']['conditions'][0]['condition'] = {
    'details': json.loads(threshold_condition.serialize_json()),
    'uri': threshold_condition.condition.serialize_uri()
}

# Conditions have been updated, so the transaction hash (ID) needs updating
Пример #30
0
import copy
import json

import cryptoconditions as cc
from bigchaindb import util, crypto

signature_treshold = 1
# signature_treshold = 2

# Create some new testusers
thresholduser1_priv, thresholduser1_pub = crypto.generate_key_pair()
thresholduser2_priv, thresholduser2_pub = crypto.generate_key_pair()

# Retrieve the last transaction of testuser2
tx_retrieved_id = b.get_owned_ids(testuser2_pub).pop()

# Create a base template for a 1-input/2-output transaction
threshold_tx = b.create_transaction(testuser2_pub,
                                    [thresholduser1_pub, thresholduser2_pub],
                                    tx_retrieved_id, 'TRANSFER')

# Create a Threshold Cryptocondition
threshold_condition = cc.ThresholdSha256Fulfillment(
    threshold=signature_treshold)
threshold_condition.add_subfulfillment(
    cc.Ed25519Fulfillment(public_key=thresholduser1_pub))
threshold_condition.add_subfulfillment(
    cc.Ed25519Fulfillment(public_key=thresholduser2_pub))

# Update the condition in the newly created transaction
threshold_tx['transaction']['conditions'][0]['condition'] = {
Пример #31
0
def keys_new():
  return crypto.generate_key_pair()
from bigchaindb import Bigchain
from bigchaindb import crypto
from tornado import websocket, ioloop, web
from tornado.gen import coroutine
from tornado import gen
from .stream_coin import pay_royalties
import time
import json
import multiprocessing as mp

clients = []
coins_seen = []
play_until = time.time()
label_sk, label_vk = crypto.generate_key_pair()
artist_sk, artist_vk = crypto.generate_key_pair()
artist_share = 0
label_share = 0
royalties_queue = mp.Queue()
me = Bigchain().me


class StreamHandler(websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True

    def open(self):
        if self not in clients:
            clients.append(self)
            print('Received connection from {}'.format(self))
Пример #33
0

# Parse the command-line arguments
desc = 'Write a set of keypairs to keypairs.py'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('num_pairs',
                    help='number of keypairs to write',
                    type=int)
args = parser.parse_args()
num_pairs = int(args.num_pairs)

# Generate and write the keypairs to keypairs.py
print('Writing {} keypairs to keypairs.py...'.format(num_pairs))
with open('keypairs.py', 'w') as f:
    f.write('# -*- coding: utf-8 -*-\n')
    f.write('"""A set of keypairs for use in deploying\n')
    f.write('BigchainDB servers with a predictable set of keys.\n')
    f.write('"""\n')
    f.write('\n')
    f.write('from __future__ import unicode_literals\n')
    f.write('\n')
    f.write('keypairs_list = [')
    for pair_num in range(num_pairs):
        keypair = crypto.generate_key_pair()
        spacer = '' if pair_num == 0 else '    '
        f.write("{}('{}',\n     '{}'),\n".format(
                spacer, keypair[0], keypair[1]))
    f.write('    ]\n')

print('Done.')
Пример #34
0
def get_keys():
        priv1,pub1 = crypto.generate_key_pair()
        return jsonify({'public key': pub1, 'private key': priv1})
Пример #35
0
from bigchaindb import Bigchain
from bigchaindb import crypto
from tornado import websocket, ioloop, web
from tornado.gen import coroutine
from tornado import gen
from .stream_coin import pay_royalties
import time
import json
import multiprocessing as mp

clients = []
coins_seen = []
play_until = time.time()
label_sk, label_vk = crypto.generate_key_pair()
artist_sk, artist_vk = crypto.generate_key_pair()
artist_share = 0
label_share = 0
royalties_queue = mp.Queue()
me = Bigchain().me


class StreamHandler(websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        if self not in clients:
            clients.append(self)
            print('Received connection from {}'.format(self))

    def on_close(self):
def transfer_transaction(request, format=None):
    """
    创建Transfer交易
    输入:前一个交易id(previous_process_tx_id)
         交易发起方公钥(tx_originator_public_key),
         交易接收方公钥(tx_recipient_public_key),
         交易发起方私钥(tx_originator_private_key),
         人员(who: {original: whoItem, goto: whoItem}),
         whoItem: user_id, user_type, user_name, company_name, company_id, u_company_id
         地点(where: {original: whereItem, goto: whereItem})
         whereItem: nation, region, place, region_id
         时间(when: make_date, send_date, receive_date, expire_date)
         物品(thing: thing_type_id, thing_type_name, thing_id, thing_name, origin_place, thing_order_quantity, thing_order_batch, price)
    输出:交易id和剩余物品的秘钥
    """
    # get total numbers
    data = request.data
    tx_originator_public_key = data.pop('tx_originator_public_key', None)
    tx_originator_private_key = data.pop('tx_originator_private_key', None)
    tx_recipient_public_key = data.pop('tx_recipient_public_key', None)
    input_list = b.get_owned_ids(tx_originator_public_key)
    if input_list == []:
        return Response(status=status.HTTP_204_NO_CONTENT)
    input = input_list.pop()
    tx = b.get_transaction(input['txid'])
    total = tx['transaction']['data']['payload']['thing'][
        'thing_order_quantity']
    # transfer
    tx = b.create_transaction(tx_originator_public_key,
                              tx_recipient_public_key,
                              input,
                              'TRANSFER',
                              payload=data)
    tx_signed = b.sign_transaction(tx, tx_originator_private_key)
    b.write_transaction(tx_signed)
    # deal with remains
    remain = int(total) - int(data['thing']['thing_order_quantity'])
    if remain > 0:
        time.sleep(5)
        data['thing']['thing_order_quantity'] = str(remain)
        data['who']['goto'] = copy.deepcopy(data['who']['original'])
        data['where']['goto'] = copy.deepcopy(data['where']['original'])
        for key, value in data['who']['original'].items():
            data['who']['original'][key] = None
        for key, value in data['where']['original'].items():
            data['where']['original'][key] = None
        data['when']['receive_date'] = data['when']['send_date']
        data['previous_process_tx_id'] = tx_signed['id']
        private_key, public_key = crypto.generate_key_pair()
        tx = b.create_transaction(b.me,
                                  public_key,
                                  None,
                                  'CREATE',
                                  payload=data)
        tx_signed_2 = b.sign_transaction(tx, b.me_private)
        b.write_transaction(tx_signed_2)
        return Response({
            'txs': {
                'transfer_id': tx_signed['id'],
                'create_id': tx_signed_2['id']
            },
            'key_pair': {
                'public_key': public_key,
                'private_key': private_key
            }
        })
    return Response({'transfer tx id': tx_signed['id']})
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
        })
Пример #38
0
__author__ = 'PC-LiNing'

from bigchaindb import Bigchain
from bigchaindb import crypto
import time

b = Bigchain()

# user A
testuser1_priv, testuser1_pub = crypto.generate_key_pair()
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)
Пример #39
0
__author__ = 'PC-LiNing'

from bigchaindb import Bigchain
from bigchaindb import  crypto
import time

b=Bigchain()

# user A
testuser1_priv, testuser1_pub = crypto.generate_key_pair()
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()
import json
from time import sleep

import cryptoconditions as cc

from bigchaindb import Bigchain, util, crypto, exceptions


b = Bigchain()

"""
Create a Digital Asset
"""

# 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)
Пример #41
0
def keys_new():
    return crypto.generate_key_pair()
Пример #42
0
from flask import Flask
from flask import jsonify
from flask import request

#libraries for bigchain functionality
from bigchaindb import Bigchain
from bigchaindb import crypto
from bigchaindb import util
import cryptoconditions as cc


app = Flask(__name__)


#generate a public and private key (internal user)
priv,pub = crypto.generate_key_pair()

#instantiate your chain
b = Bigchain()


#GET: public and private key of a new user to be generated
#User Input: None
@app.route('/getKeys', methods=['GET'])
def get_keys():
        priv1,pub1 = crypto.generate_key_pair()
        return jsonify({'public key': pub1, 'private key': priv1})


#POST: a transfer transaction
#User Input: A json object, an example is shown below:
Пример #43
0
def generate_key_pair():
    return crypto.generate_key_pair()
Пример #44
0
 def test_generate_key_pair(self):
     private_value_base58, public_value_compressed_base58 = generate_key_pair()
     assert PrivateKey.encode(
         PrivateKey.decode(private_value_base58)) == private_value_base58
     assert PublicKey.encode(
         *PublicKey.decode(public_value_compressed_base58)) == public_value_compressed_base58
Пример #45
0
 def generate_key_pair(self):
     return crypto.generate_key_pair()
# The following HEX string represents an ECC public key belonging to the secret key
# of a crypto tag inside a product
# '6ABCA66658E30D4808F6DDABD900723BFB3DE8BF77F86B3DC84584D7F2039B1FED0
# 4CFE79C39390D7A6240B7713FFF1891AB687E62ADAE8460FCF040D02105D2'

# Define the product public key derived from a Riddle&Code crypto tag
tag_pubkey = b'6ABCA66658E30D4808F6DDABD900723BFB3DE8BF77F86B3DC84584D7F2039B1FED04CFE79C39390D7A6240B7713FFF1891AB687E62ADAE8460FCF040D02105D2'
# Translate public key from tag into a bicgchaindb compliant address
# Results in '5GjT173hXbwm9R5x2Sk4y6NgeqCCA2JrwdyZdzKPvC6a'
prdct_pubkey = binascii.hexlify(tag_pubkey)
prdct_pubkey = hashlib.sha3_256(prdct_pubkey).digest()
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)