From d899d4c8b6e9f2cd9ed14476012fe17c1633e800 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 17 Jan 2017 15:56:34 +0100 Subject: [PATCH 001/155] query string parameters test --- bigchaindb/web/views/parameters.py | 30 +++++++++++ bigchaindb/web/views/transactions.py | 15 +++++- tests/web/test_parameters.py | 79 ++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 bigchaindb/web/views/parameters.py create mode 100644 tests/web/test_parameters.py diff --git a/bigchaindb/web/views/parameters.py b/bigchaindb/web/views/parameters.py new file mode 100644 index 00000000..9968a659 --- /dev/null +++ b/bigchaindb/web/views/parameters.py @@ -0,0 +1,30 @@ +import re + + +def valid_txid(txid): + if re.match('^[a-fA-F0-9]{64}$', txid): + return txid.lower() + raise ValueError("Invalid hash") + + +def valid_bool(val): + if val == 'true': + return True + if val == 'false': + return False + raise ValueError('Boolean value must be "true" or "false" (lowercase)') + + +def valid_ed25519(key): + if (re.match('^[1-9a-zA-Z]{43,44}$', key) and not + re.match('.*[Il0O]', key)): + return key + raise ValueError("Invalid base58 ed25519 key") + + +def valid_operation(op): + if op == 'CREATE': + return 'CREATE' + if op == 'TRANSFER': + return 'TRANSFER' + raise ValueError('Operation must be "CREATE" or "TRANSFER') diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index fa544f65..e61a791f 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -5,9 +5,11 @@ For more information please refer to the documentation on ReadTheDocs: http-client-server-api.html """ import logging +import re from flask import current_app, request -from flask_restful import Resource +from flask_restful import Resource, reqparse + from bigchaindb.common.exceptions import ( AmountError, @@ -25,6 +27,7 @@ from bigchaindb.common.exceptions import ( import bigchaindb from bigchaindb.models import Transaction from bigchaindb.web.views.base import make_error +from bigchaindb.web.views import parameters logger = logging.getLogger(__name__) @@ -51,6 +54,16 @@ class TransactionApi(Resource): class TransactionListApi(Resource): + def get(self): + parser = reqparse.RequestParser() + parser.add_argument('operation', type=parameters.valid_operation) + parser.add_argument('unspent', type=parameters.valid_bool) + parser.add_argument('public_key', type=parameters.valid_ed25519, + action="append") + parser.add_argument('asset_id', type=parameters.valid_txid) + args = parser.parse_args() + return args + def post(self): """API endpoint to push transactions to the Federation. diff --git a/tests/web/test_parameters.py b/tests/web/test_parameters.py new file mode 100644 index 00000000..4044a273 --- /dev/null +++ b/tests/web/test_parameters.py @@ -0,0 +1,79 @@ +import pytest + + +def test_valid_txid(): + from bigchaindb.web.views.parameters import valid_txid + + valid = ['18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4', + '18AC3E7343F016890C510E93F935261169D9E3F565436429830FAF0934F4F8E4'] + for h in valid: + assert valid_txid(h) == h.lower() + + non = ['18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e', + '18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e45', + '18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8eg', + '18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e ', + ''] + for h in non: + with pytest.raises(ValueError): + valid_txid(h) + + +def test_valid_bool(): + from bigchaindb.web.views.parameters import valid_bool + + assert valid_bool('true') == True + valid_bool('false') == False + + with pytest.raises(ValueError): + valid_bool('TRUE') + with pytest.raises(ValueError): + valid_bool('FALSE') + with pytest.raises(ValueError): + valid_bool('0') + with pytest.raises(ValueError): + valid_bool('1') + with pytest.raises(ValueError): + valid_bool('yes') + with pytest.raises(ValueError): + valid_bool('no') + + +def test_valid_ed25519(): + from bigchaindb.web.views.parameters import valid_ed25519 + + valid = ['123456789abcdefghijkmnopqrstuvwxyz1111111111', + '123456789ABCDEFGHJKLMNPQRSTUVWXYZ1111111111'] + for h in valid: + assert valid_ed25519(h) == h + + with pytest.raises(ValueError): + valid_ed25519('1234556789abcdefghijkmnopqrstuvwxyz1111111') + with pytest.raises(ValueError): + valid_ed25519('1234556789abcdefghijkmnopqrstuvwxyz1111111111') + with pytest.raises(ValueError): + valid_ed25519('123456789abcdefghijkmnopqrstuvwxyz111111111l') + with pytest.raises(ValueError): + valid_ed25519('123456789abcdefghijkmnopqrstuvwxyz111111111I') + with pytest.raises(ValueError): + valid_ed25519('1234556789abcdefghijkmnopqrstuvwxyz11111111O') + with pytest.raises(ValueError): + valid_ed25519('1234556789abcdefghijkmnopqrstuvwxyz111111110') + + +def test_valid_operation(): + from bigchaindb.web.views.parameters import valid_operation + + assert valid_operation('CREATE') == 'CREATE' + assert valid_operation('TRANSFER') == 'TRANSFER' + + with pytest.raises(ValueError): + valid_operation('create') + with pytest.raises(ValueError): + valid_operation('transfer') + with pytest.raises(ValueError): + valid_operation('GENESIS') + with pytest.raises(ValueError): + valid_operation('blah') + with pytest.raises(ValueError): + valid_operation('') From dbb3414fd0f73bcde71efb983fdb2a411dfbe47f Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 17 Jan 2017 18:02:09 +0100 Subject: [PATCH 002/155] generalise get_txids_by_asset_id into get_txids_filtered and remove get_transactions_by_asset_id --- bigchaindb/backend/mongodb/query.py | 31 +++++----- bigchaindb/backend/query.py | 13 ++++ bigchaindb/backend/rethinkdb/query.py | 33 +++++----- bigchaindb/core.py | 24 -------- tests/assets/test_digital_assets.py | 89 --------------------------- tests/backend/mongodb/test_queries.py | 45 ++++++++------ tests/backend/test_generics.py | 2 +- 7 files changed, 74 insertions(+), 163 deletions(-) diff --git a/bigchaindb/backend/mongodb/query.py b/bigchaindb/backend/mongodb/query.py index a9e52c82..c4e3cdc8 100644 --- a/bigchaindb/backend/mongodb/query.py +++ b/bigchaindb/backend/mongodb/query.py @@ -82,21 +82,6 @@ def get_blocks_status_from_transaction(conn, transaction_id): projection=['id', 'block.voters']) -@register_query(MongoDBConnection) -def get_txids_by_asset_id(conn, asset_id): - cursor = conn.db['bigchain'].aggregate([ - {'$match': { - 'block.transactions.asset.id': asset_id - }}, - {'$unwind': '$block.transactions'}, - {'$match': { - 'block.transactions.asset.id': asset_id - }}, - {'$project': {'block.transactions.id': True}} - ]) - return (elem['block']['transactions']['id'] for elem in cursor) - - @register_query(MongoDBConnection) def get_asset_by_id(conn, asset_id): cursor = conn.db['bigchain'].aggregate([ @@ -249,3 +234,19 @@ def get_unvoted_blocks(conn, node_pubkey): 'votes': False, '_id': False }} ]) + + +@register_query(MongoDBConnection) +def get_txids_filtered(conn, asset_id, operation=None): + match = {'block.transactions.asset.id': asset_id} + + if operation: + match['block.transactions.operation'] = operation + + cursor = conn.db['bigchain'].aggregate([ + {'$match': match}, + {'$unwind': '$block.transactions'}, + {'$match': match}, + {'$project': {'block.transactions.id': True}} + ]) + return (r['block']['transactions']['id'] for r in cursor) diff --git a/bigchaindb/backend/query.py b/bigchaindb/backend/query.py index e71f6be3..cbd17d25 100644 --- a/bigchaindb/backend/query.py +++ b/bigchaindb/backend/query.py @@ -318,3 +318,16 @@ def get_unvoted_blocks(connection, node_pubkey): """ raise NotImplementedError + + +@singledispatch +def get_txids_filtered(connection, asset_id, operation=None): + """ + Return all transactions for a particular asset id and optional operation. + + Args: + asset_id (str): ID of transaction that defined the asset + operation (str) (optional): Operation to filter on + """ + + raise NotImplementedError diff --git a/bigchaindb/backend/rethinkdb/query.py b/bigchaindb/backend/rethinkdb/query.py index f7a7c45a..fd0bdcb3 100644 --- a/bigchaindb/backend/rethinkdb/query.py +++ b/bigchaindb/backend/rethinkdb/query.py @@ -71,22 +71,6 @@ def get_blocks_status_from_transaction(connection, transaction_id): .pluck('votes', 'id', {'block': ['voters']})) -@register_query(RethinkDBConnection) -def get_txids_by_asset_id(connection, asset_id): - # here we only want to return the transaction ids since later on when - # we are going to retrieve the transaction with status validation - - # Then find any TRANSFER transactions related to the asset - tx_cursor = connection.run( - r.table('bigchain') - .get_all(asset_id, index='asset_id') - .concat_map(lambda block: block['block']['transactions']) - .filter(lambda transaction: transaction['asset']['id'] == asset_id) - .get_field('id')) - - return tx_cursor - - @register_query(RethinkDBConnection) def get_asset_by_id(connection, asset_id): return connection.run(_get_asset_create_tx_query(asset_id).pluck('asset')) @@ -249,3 +233,20 @@ def get_unvoted_blocks(connection, node_pubkey): # database level. Solving issue #444 can help untangling the situation unvoted_blocks = filter(lambda block: not utils.is_genesis_block(block), unvoted) return unvoted_blocks + + +@register_query(RethinkDBConnection) +def get_txids_filtered(connection, asset_id, operation=None): + # here we only want to return the transaction ids since later on when + # we are going to retrieve the transaction with status validation + + tx_filter = r.row['asset']['id'] == asset_id + if operation: + tx_filter &= r.row['operation'] == operation + + return connection.run( + r.table('bigchain') + .get_all(asset_id, index='asset_id') + .concat_map(lambda block: block['block']['transactions']) + .filter(tx_filter) + .get_field('id')) diff --git a/bigchaindb/core.py b/bigchaindb/core.py index 3c62e65d..a520bba4 100644 --- a/bigchaindb/core.py +++ b/bigchaindb/core.py @@ -317,30 +317,6 @@ class Bigchain(object): else: return None - def get_transactions_by_asset_id(self, asset_id): - """Retrieves valid or undecided transactions related to a particular - asset. - - A digital asset in bigchaindb is identified by an uuid. This allows us - to query all the transactions related to a particular digital asset, - knowing the id. - - Args: - asset_id (str): the id for this particular asset. - - Returns: - A list of valid or undecided transactions related to the asset. - If no transaction exists for that asset it returns an empty list - `[]` - """ - txids = backend.query.get_txids_by_asset_id(self.connection, asset_id) - transactions = [] - for txid in txids: - tx = self.get_transaction(txid) - if tx: - transactions.append(tx) - return transactions - def get_asset_by_id(self, asset_id): """Returns the asset associated with an asset_id. diff --git a/tests/assets/test_digital_assets.py b/tests/assets/test_digital_assets.py index 9d2adbd5..1dc4764f 100644 --- a/tests/assets/test_digital_assets.py +++ b/tests/assets/test_digital_assets.py @@ -90,95 +90,6 @@ def test_asset_id_mismatch(b, user_pk): Transaction.get_asset_id([tx1, tx2]) -@pytest.mark.bdb -@pytest.mark.usefixtures('inputs') -def test_get_transactions_by_asset_id(b, user_pk, user_sk): - from bigchaindb.models import Transaction - - tx_create = b.get_owned_ids(user_pk).pop() - tx_create = b.get_transaction(tx_create.txid) - asset_id = tx_create.id - txs = b.get_transactions_by_asset_id(asset_id) - - assert len(txs) == 1 - assert txs[0].id == tx_create.id - assert txs[0].id == asset_id - - # create a transfer transaction - tx_transfer = Transaction.transfer(tx_create.to_inputs(), [([user_pk], 1)], - tx_create.id) - tx_transfer_signed = tx_transfer.sign([user_sk]) - # create the block - block = b.create_block([tx_transfer_signed]) - b.write_block(block) - # vote the block valid - vote = b.vote(block.id, b.get_last_voted_block().id, True) - b.write_vote(vote) - - txs = b.get_transactions_by_asset_id(asset_id) - - assert len(txs) == 2 - assert {tx_create.id, tx_transfer.id} == set(tx.id for tx in txs) - assert asset_id == Transaction.get_asset_id(txs) - - -@pytest.mark.bdb -@pytest.mark.usefixtures('inputs') -def test_get_transactions_by_asset_id_with_invalid_block(b, user_pk, user_sk): - from bigchaindb.models import Transaction - - tx_create = b.get_owned_ids(user_pk).pop() - tx_create = b.get_transaction(tx_create.txid) - asset_id = tx_create.id - txs = b.get_transactions_by_asset_id(asset_id) - - assert len(txs) == 1 - assert txs[0].id == tx_create.id - assert txs[0].id == asset_id - - # create a transfer transaction - tx_transfer = Transaction.transfer(tx_create.to_inputs(), [([user_pk], 1)], - tx_create.id) - tx_transfer_signed = tx_transfer.sign([user_sk]) - # create the block - block = b.create_block([tx_transfer_signed]) - b.write_block(block) - # vote the block invalid - vote = b.vote(block.id, b.get_last_voted_block().id, False) - b.write_vote(vote) - - txs = b.get_transactions_by_asset_id(asset_id) - - assert len(txs) == 1 - - -@pytest.mark.bdb -@pytest.mark.usefixtures('inputs') -def test_get_asset_by_id(b, user_pk, user_sk): - from bigchaindb.models import Transaction - - tx_create = b.get_owned_ids(user_pk).pop() - tx_create = b.get_transaction(tx_create.txid) - - # create a transfer transaction - tx_transfer = Transaction.transfer(tx_create.to_inputs(), [([user_pk], 1)], - tx_create.id) - tx_transfer_signed = tx_transfer.sign([user_sk]) - # create the block - block = b.create_block([tx_transfer_signed]) - b.write_block(block) - # vote the block valid - vote = b.vote(block.id, b.get_last_voted_block().id, True) - b.write_vote(vote) - - asset_id = Transaction.get_asset_id([tx_create, tx_transfer]) - txs = b.get_transactions_by_asset_id(asset_id) - assert len(txs) == 2 - - asset = b.get_asset_by_id(asset_id) - assert asset == tx_create.asset - - def test_create_invalid_divisible_asset(b, user_pk, user_sk): from bigchaindb.models import Transaction from bigchaindb.common.exceptions import AmountError diff --git a/tests/backend/mongodb/test_queries.py b/tests/backend/mongodb/test_queries.py index 9f20cc9f..48089805 100644 --- a/tests/backend/mongodb/test_queries.py +++ b/tests/backend/mongodb/test_queries.py @@ -125,24 +125,6 @@ def test_get_block_status_from_transaction(create_tx): assert block_db['block']['voters'] == block.voters -def test_get_txids_by_asset_id(signed_create_tx, signed_transfer_tx): - from bigchaindb.backend import connect, query - from bigchaindb.models import Block - conn = connect() - - # create and insert two blocks, one for the create and one for the - # transfer transaction - block = Block(transactions=[signed_create_tx]) - conn.db.bigchain.insert_one(block.to_dict()) - block = Block(transactions=[signed_transfer_tx]) - conn.db.bigchain.insert_one(block.to_dict()) - - txids = list(query.get_txids_by_asset_id(conn, signed_create_tx.id)) - - assert len(txids) == 2 - assert txids == [signed_create_tx.id, signed_transfer_tx.id] - - def test_get_asset_by_id(create_tx): from bigchaindb.backend import connect, query from bigchaindb.models import Block @@ -366,3 +348,30 @@ def test_get_unvoted_blocks(signed_create_tx): assert len(unvoted_blocks) == 1 assert unvoted_blocks[0] == block.to_dict() + + +def test_get_txids_filtered(signed_create_tx, signed_transfer_tx): + from bigchaindb.backend import connect, query + from bigchaindb.models import Block, Transaction + conn = connect() + + # create and insert two blocks, one for the create and one for the + # transfer transaction + block = Block(transactions=[signed_create_tx]) + conn.db.bigchain.insert_one(block.to_dict()) + block = Block(transactions=[signed_transfer_tx]) + conn.db.bigchain.insert_one(block.to_dict()) + + asset_id = Transaction.get_asset_id([signed_create_tx, signed_transfer_tx]) + + # Test get by just asset id + txids = set(query.get_txids_filtered(conn, asset_id)) + assert txids == {signed_create_tx.id, signed_transfer_tx.id} + + # Test get by asset and CREATE + txids = set(query.get_txids_filtered(conn, asset_id, Transaction.CREATE)) + assert txids == {signed_create_tx.id} + + # Test get by asset and TRANSFER + txids = set(query.get_txids_filtered(conn, asset_id, Transaction.TRANSFER)) + assert txids == {signed_transfer_tx.id} diff --git a/tests/backend/test_generics.py b/tests/backend/test_generics.py index 2ab33a7c..8db08999 100644 --- a/tests/backend/test_generics.py +++ b/tests/backend/test_generics.py @@ -26,7 +26,7 @@ def test_schema(schema_func_name, args_qty): ('get_stale_transactions', 1), ('get_blocks_status_from_transaction', 1), ('get_transaction_from_backlog', 1), - ('get_txids_by_asset_id', 1), + ('get_txids_filtered', 1), ('get_asset_by_id', 1), ('get_owned_ids', 1), ('get_votes_by_block_id', 1), From 1c918caf4c59d0660678045e567183927c9d89fa Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 18 Jan 2017 11:23:17 +0100 Subject: [PATCH 003/155] txlist / get_transactions_filtered --- bigchaindb/core.py | 13 +++++++++ tests/test_txlist.py | 66 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 tests/test_txlist.py diff --git a/bigchaindb/core.py b/bigchaindb/core.py index a520bba4..e18ec46d 100644 --- a/bigchaindb/core.py +++ b/bigchaindb/core.py @@ -417,6 +417,19 @@ class Bigchain(object): return owned + def get_transactions_filtered(self, asset_id=None, operation=None): + """ + Get a list of transactions filtered on some criteria + """ + if not asset_id: + raise ValueError("Need asset_id") + txids = backend.query.get_txids_filtered(self.connection, asset_id, + operation) + for txid in txids: + tx, status = self.get_transaction(txid, True) + if status == self.TX_VALID: + yield tx + def create_block(self, validated_transactions): """Creates a block given a list of `validated_transactions`. diff --git a/tests/test_txlist.py b/tests/test_txlist.py new file mode 100644 index 00000000..6f9f203a --- /dev/null +++ b/tests/test_txlist.py @@ -0,0 +1,66 @@ +""" +Test getting a list of transactions from the backend. + +This test module defines it's own fixture which is used by all the tests. +""" +import pytest + + +@pytest.fixture +def txlist(b, user_pk, user2_pk, user_sk, user2_sk, genesis_block): + from bigchaindb.models import Transaction + prev_block_id = genesis_block.id + + # Create first block with CREATE transactions + create1 = Transaction.create([user_pk], [([user2_pk], 6)]) \ + .sign([user_sk]) + create2 = Transaction.create([user2_pk], + [([user2_pk], 5), ([user_pk], 5)]) \ + .sign([user2_sk]) + block1 = b.create_block([create1, create2]) + b.write_block(block1) + + # Create second block with TRANSFER transactions + transfer1 = Transaction.transfer(create1.to_inputs(), + [([user_pk], 8)], + create1.id).sign([user2_sk]) + block2 = b.create_block([transfer1]) + b.write_block(block2) + + # Create block with double spend + tx_doublespend = Transaction.transfer(create1.to_inputs(), + [([user_pk], 9)], + create1.id).sign([user2_sk]) + block_doublespend = b.create_block([tx_doublespend]) + b.write_block(block_doublespend) + + # Vote on all the blocks + prev_block_id = genesis_block.id + for bid in [block1.id, block2.id]: + vote = b.vote(bid, prev_block_id, True) + prev_block_id = bid + b.write_vote(vote) + + # Create undecided block + untx = Transaction.create([user_pk], [([user2_pk], 7)]) \ + .sign([user_sk]) + block_undecided = b.create_block([untx]) + b.write_block(block_undecided) + + return type('', (), { + 'create1': create1, + 'transfer1': transfer1, + }) + + +@pytest.mark.bdb +def test_get_txlist_by_asset(b, txlist): + res = b.get_transactions_filtered(txlist.create1.id) + assert set(tx.id for tx in res) == set([txlist.transfer1.id, + txlist.create1.id]) + + +@pytest.mark.bdb +def test_get_txlist_by_operation(b, txlist): + res = b.get_transactions_filtered(txlist.create1.id, operation='CREATE') + assert set(tx.id for tx in res) == {txlist.create1.id} From ae14d0e5c4ffff38a839acfb57c38f15d17c7abf Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 18 Jan 2017 15:36:46 +0100 Subject: [PATCH 004/155] api method to get transactions by asset_id --- bigchaindb/web/views/transactions.py | 12 ++++++---- tests/web/test_transactions.py | 36 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index e61a791f..bc828df7 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -57,12 +57,14 @@ class TransactionListApi(Resource): def get(self): parser = reqparse.RequestParser() parser.add_argument('operation', type=parameters.valid_operation) - parser.add_argument('unspent', type=parameters.valid_bool) - parser.add_argument('public_key', type=parameters.valid_ed25519, - action="append") - parser.add_argument('asset_id', type=parameters.valid_txid) + parser.add_argument('asset_id', type=parameters.valid_txid, + required=True) args = parser.parse_args() - return args + + with current_app.config['bigchain_pool']() as bigchain: + txes = bigchain.get_transactions_filtered(**args) + + return [tx.to_dict() for tx in txes] def post(self): """API endpoint to push transactions to the Federation. diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index 9b7fac3f..f40bc924 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -1,5 +1,6 @@ import builtins import json +from unittest.mock import Mock, patch import pytest from bigchaindb.common import crypto @@ -180,3 +181,38 @@ def test_post_invalid_transfer_transaction_returns_400(b, client, user_pk): InvalidSignature.__name__, 'Transaction signature is invalid.') assert res.status_code == expected_status_code assert res.json['message'] == expected_error_message + + +def test_transactions_get_list_good(client): + from functools import partial + def gtf(conn, **args): + return [type('', (), {'to_dict': partial(lambda a: a, arg)}) + for arg in sorted(args.items())] + + asset_id = '1' * 64 + + with patch('bigchaindb.core.Bigchain.get_transactions_filtered', gtf): + url = TX_ENDPOINT + "?asset_id=" + asset_id + assert client.get(url).json == [ + ['asset_id', asset_id], + ['operation', None] + ] + url = TX_ENDPOINT + "?asset_id=" + asset_id + "&operation=CREATE" + assert client.get(url).json == [ + ['asset_id', asset_id], + ['operation', 'CREATE'] + ] + + +def test_transactions_get_list_bad(client): + with patch('bigchaindb.core.Bigchain.get_transactions_filtered', + lambda *_, **__: should_not_be_called()): + # Test asset id validated + url = TX_ENDPOINT + "?asset_id=" + '1' * 63 + assert client.get(url).status_code == 400 + # Test operation validated + url = TX_ENDPOINT + "?asset_id=" + '1' * 64 + "&operation=CEATE" + assert client.get(url).status_code == 400 + # Test asset ID required + url = TX_ENDPOINT + "?operation=CREATE" + assert client.get(url).status_code == 400 From 2ec23be05d5104b0a8c3aee14e9c3698228bdd8a Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 18 Jan 2017 17:13:38 +0100 Subject: [PATCH 005/155] fix flake8 --- bigchaindb/web/views/parameters.py | 2 +- bigchaindb/web/views/transactions.py | 1 - tests/test_txlist.py | 7 +++---- tests/web/test_parameters.py | 4 ++-- tests/web/test_transactions.py | 5 ++++- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/bigchaindb/web/views/parameters.py b/bigchaindb/web/views/parameters.py index 9968a659..222adb97 100644 --- a/bigchaindb/web/views/parameters.py +++ b/bigchaindb/web/views/parameters.py @@ -17,7 +17,7 @@ def valid_bool(val): def valid_ed25519(key): if (re.match('^[1-9a-zA-Z]{43,44}$', key) and not - re.match('.*[Il0O]', key)): + re.match('.*[Il0O]', key)): return key raise ValueError("Invalid base58 ed25519 key") diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index bc828df7..a2b6cd30 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -5,7 +5,6 @@ For more information please refer to the documentation on ReadTheDocs: http-client-server-api.html """ import logging -import re from flask import current_app, request from flask_restful import Resource, reqparse diff --git a/tests/test_txlist.py b/tests/test_txlist.py index 6f9f203a..e7de8c98 100644 --- a/tests/test_txlist.py +++ b/tests/test_txlist.py @@ -28,9 +28,8 @@ def txlist(b, user_pk, user2_pk, user_sk, user2_sk, genesis_block): b.write_block(block2) # Create block with double spend - tx_doublespend = Transaction.transfer(create1.to_inputs(), - [([user_pk], 9)], - create1.id).sign([user2_sk]) + tx_doublespend = Transaction.transfer(create1.to_inputs(), [([user_pk], 9)], + create1.id).sign([user2_sk]) block_doublespend = b.create_block([tx_doublespend]) b.write_block(block_doublespend) @@ -43,7 +42,7 @@ def txlist(b, user_pk, user2_pk, user_sk, user2_sk, genesis_block): # Create undecided block untx = Transaction.create([user_pk], [([user2_pk], 7)]) \ - .sign([user_sk]) + .sign([user_sk]) block_undecided = b.create_block([untx]) b.write_block(block_undecided) diff --git a/tests/web/test_parameters.py b/tests/web/test_parameters.py index 4044a273..d39c6f38 100644 --- a/tests/web/test_parameters.py +++ b/tests/web/test_parameters.py @@ -22,8 +22,8 @@ def test_valid_txid(): def test_valid_bool(): from bigchaindb.web.views.parameters import valid_bool - assert valid_bool('true') == True - valid_bool('false') == False + assert valid_bool('true') is True + assert valid_bool('false') is False with pytest.raises(ValueError): valid_bool('TRUE') diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index f40bc924..fb0f8cb2 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -1,6 +1,6 @@ import builtins import json -from unittest.mock import Mock, patch +from unittest.mock import patch import pytest from bigchaindb.common import crypto @@ -185,6 +185,7 @@ def test_post_invalid_transfer_transaction_returns_400(b, client, user_pk): def test_transactions_get_list_good(client): from functools import partial + def gtf(conn, **args): return [type('', (), {'to_dict': partial(lambda a: a, arg)}) for arg in sorted(args.items())] @@ -205,6 +206,8 @@ def test_transactions_get_list_good(client): def test_transactions_get_list_bad(client): + def should_not_be_called(): + assert False with patch('bigchaindb.core.Bigchain.get_transactions_filtered', lambda *_, **__: should_not_be_called()): # Test asset id validated From f2034cddde399973c73015a7c149d727af6c84ca Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 20 Jan 2017 10:08:30 +0100 Subject: [PATCH 006/155] make asset_id not optional in get_transactions_filtered --- bigchaindb/core.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bigchaindb/core.py b/bigchaindb/core.py index e18ec46d..f9c96bed 100644 --- a/bigchaindb/core.py +++ b/bigchaindb/core.py @@ -417,12 +417,10 @@ class Bigchain(object): return owned - def get_transactions_filtered(self, asset_id=None, operation=None): + def get_transactions_filtered(self, asset_id, operation=None): """ Get a list of transactions filtered on some criteria """ - if not asset_id: - raise ValueError("Need asset_id") txids = backend.query.get_txids_filtered(self.connection, asset_id, operation) for txid in txids: From c5253825b3bcc527fa21b71e099a7962a3dc22a4 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 20 Jan 2017 10:31:28 +0100 Subject: [PATCH 007/155] remove unused backend query stub get_txids_by_asset_id --- bigchaindb/backend/query.py | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/bigchaindb/backend/query.py b/bigchaindb/backend/query.py index cbd17d25..bdfb9e28 100644 --- a/bigchaindb/backend/query.py +++ b/bigchaindb/backend/query.py @@ -107,25 +107,6 @@ def get_blocks_status_from_transaction(connection, transaction_id): raise NotImplementedError -@singledispatch -def get_txids_by_asset_id(connection, asset_id): - """Retrieves transactions ids related to a particular asset. - - A digital asset in bigchaindb is identified by its ``CREATE`` - transaction's ID. Knowing this ID allows us to query all the - transactions related to a particular digital asset. - - Args: - asset_id (str): the ID of the asset. - - Returns: - A list of transactions ids related to the asset. If no transaction - exists for that asset it returns an empty list ``[]`` - """ - - raise NotImplementedError - - @singledispatch def get_asset_by_id(conneciton, asset_id): """Returns the asset associated with an asset_id. From 15d28e3f91eda73a8eea9ed47b3e598c6dd73db0 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Sun, 22 Jan 2017 14:47:45 +0100 Subject: [PATCH 008/155] Quickstart now assumes you're using Ubuntu 16.04 or similar --- docs/server/source/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/server/source/quickstart.md b/docs/server/source/quickstart.md index 89a20ceb..dfe485c5 100644 --- a/docs/server/source/quickstart.md +++ b/docs/server/source/quickstart.md @@ -1,6 +1,6 @@ # Quickstart -This page has instructions to set up a single stand-alone BigchainDB node for learning or experimenting. Instructions for other cases are [elsewhere](introduction.html). We will assume you're using Ubuntu 14.04 or similar. If you're not using Linux, then you might try [running BigchainDB with Docker](appendices/run-with-docker.html). +This page has instructions to set up a single stand-alone BigchainDB node for learning or experimenting. Instructions for other cases are [elsewhere](introduction.html). We will assume you're using Ubuntu 16.04 or similar. If you're not using Linux, then you might try [running BigchainDB with Docker](appendices/run-with-docker.html). A. [Install RethinkDB Server](https://rethinkdb.com/docs/install/ubuntu/) @@ -9,7 +9,7 @@ B. Open a Terminal and run RethinkDB Server with the command: rethinkdb ``` -C. Ubuntu 14.04 already has Python 3.4, so you don't need to install it, but you do need to install a couple other things: +C. Ubuntu 16.04 already has Python 3.5, so you don't need to install it, but you do need to install some other things: ```text sudo apt-get update sudo apt-get install g++ python3-dev libffi-dev From 98fb15c1249541c20549e81ac0990640055d7e39 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Sun, 22 Jan 2017 15:07:14 +0100 Subject: [PATCH 009/155] Added instructions to install fabric's OS-level dependencies --- docs/server/source/clusters-feds/aws-testing-cluster.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/server/source/clusters-feds/aws-testing-cluster.md b/docs/server/source/clusters-feds/aws-testing-cluster.md index 16a9791f..2df15917 100644 --- a/docs/server/source/clusters-feds/aws-testing-cluster.md +++ b/docs/server/source/clusters-feds/aws-testing-cluster.md @@ -18,6 +18,13 @@ The instructions that follow have been tested on Ubuntu 14.04, but may also work **Note: Our Python scripts for deploying to AWS use Python 2 because Fabric doesn't work with Python 3.** +You must install the Python package named `fabric`, but it depends on the `cryptography` package, and that depends on some OS-level packages. On Ubuntu 14.04, you can install those OS-level packages using: +```text +sudo apt-get install build-essential libssl-dev libffi-dev python-dev +``` + +For other operating systems, see [the installation instructions for the `cryptography` package](https://cryptography.io/en/latest/installation/). + Maybe create a Python 2 virtual environment and activate it. Then install the following Python packages (in that virtual environment): ```text pip install fabric fabtools requests boto3 awscli From 36eccb3f83bf94ecd43896a878a6bfb9ab777bcb Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Sun, 22 Jan 2017 16:20:13 +0100 Subject: [PATCH 010/155] Better error handling in awsdeploy.sh --- deploy-cluster-aws/awsdeploy.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/deploy-cluster-aws/awsdeploy.sh b/deploy-cluster-aws/awsdeploy.sh index ca504f16..00d1f431 100755 --- a/deploy-cluster-aws/awsdeploy.sh +++ b/deploy-cluster-aws/awsdeploy.sh @@ -1,8 +1,10 @@ -#! /bin/bash +#!/bin/bash -# The set -e option instructs bash to immediately exit -# if any command has a non-zero exit status -set -e +set -euo pipefail +# -e Abort at the first failed line (i.e. if exit status is not 0) +# -u Abort when undefined variable is used +# -o pipefail (Bash-only) Piped commands return the status +# of the last failed command, rather than the status of the last command # Check for the first command-line argument # (the name of the AWS deployment config file) From a5acd0c7b9ce03f2e8e9be1208ae95560cd877e4 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 23 Jan 2017 14:07:22 +0100 Subject: [PATCH 011/155] document patching technique in get_transactions_filtered web view test --- tests/web/test_transactions.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index fb0f8cb2..948ef171 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -186,13 +186,17 @@ def test_post_invalid_transfer_transaction_returns_400(b, client, user_pk): def test_transactions_get_list_good(client): from functools import partial - def gtf(conn, **args): + def get_txs_patched(conn, **args): + """ Patch `get_transactions_filtered` so that rather than return an array + of transactions it returns an array of shims with a to_dict() method + that reports one of the arguments passed to `get_transactions_filtered`. + """ return [type('', (), {'to_dict': partial(lambda a: a, arg)}) for arg in sorted(args.items())] asset_id = '1' * 64 - with patch('bigchaindb.core.Bigchain.get_transactions_filtered', gtf): + with patch('bigchaindb.core.Bigchain.get_transactions_filtered', get_txs_patched): url = TX_ENDPOINT + "?asset_id=" + asset_id assert client.get(url).json == [ ['asset_id', asset_id], From 23ba642d2cb571859bdce11543876ade0ee9eeff Mon Sep 17 00:00:00 2001 From: libscott Date: Mon, 23 Jan 2017 14:38:30 +0100 Subject: [PATCH 012/155] s/txes/txs/g --- bigchaindb/web/views/transactions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index a2b6cd30..3059b34f 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -61,9 +61,9 @@ class TransactionListApi(Resource): args = parser.parse_args() with current_app.config['bigchain_pool']() as bigchain: - txes = bigchain.get_transactions_filtered(**args) + txs = bigchain.get_transactions_filtered(**args) - return [tx.to_dict() for tx in txes] + return [tx.to_dict() for tx in txs] def post(self): """API endpoint to push transactions to the Federation. From ccdbb91c1ca58e78d07958d2776f2e43a1ab42c2 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 23 Jan 2017 15:16:15 +0100 Subject: [PATCH 013/155] short form 0.9, 0.10 etc tx version with no '.dev' suffix --- bigchaindb/common/transaction.py | 2 +- tests/common/test_transaction.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index bda62663..1bc0b1a5 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -410,7 +410,7 @@ class Transaction(object): TRANSFER = 'TRANSFER' GENESIS = 'GENESIS' ALLOWED_OPERATIONS = (CREATE, TRANSFER, GENESIS) - VERSION = bigchaindb.version.__version__ + VERSION = bigchaindb.version.__short_version__[:-4] # 0.9, 0.10 etc def __init__(self, operation, asset, inputs=None, outputs=None, metadata=None, version=None): diff --git a/tests/common/test_transaction.py b/tests/common/test_transaction.py index b4ef427c..da0fba17 100644 --- a/tests/common/test_transaction.py +++ b/tests/common/test_transaction.py @@ -966,11 +966,13 @@ def test_cant_add_empty_input(): def test_validate_version(utx): + import re import bigchaindb.version from .utils import validate_transaction_model from bigchaindb.common.exceptions import SchemaValidationError - assert utx.version == bigchaindb.version.__version__ + short_ver = bigchaindb.version.__short_version__ + assert utx.version == re.match(r'^(.*\d)', short_ver).group(1) validate_transaction_model(utx) From 4bb64fa0b83d337e44ba2b961ac9d8966c2fd8c6 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Thu, 19 Jan 2017 13:02:58 +0100 Subject: [PATCH 014/155] generalise get_owned_ids to get_outputs and get_owned_ids --- bigchaindb/common/transaction.py | 2 +- bigchaindb/core.py | 27 ++++++++++++++++++++------- tests/common/test_transaction.py | 9 +++++++++ tests/db/test_bigchain_api.py | 13 +++++++++++++ 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index bda62663..563638ce 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -159,7 +159,7 @@ class TransactionLink(object): def __eq__(self, other): # TODO: If `other !== TransactionLink` return `False` - return self.to_dict() == self.to_dict() + return self.to_dict() == other.to_dict() @classmethod def from_dict(cls, link): diff --git a/bigchaindb/core.py b/bigchaindb/core.py index f9c96bed..459c4908 100644 --- a/bigchaindb/core.py +++ b/bigchaindb/core.py @@ -373,8 +373,9 @@ class Bigchain(object): else: return None - def get_owned_ids(self, owner): - """Retrieve a list of ``txid`` s that can be used as inputs. + def get_outputs(self, owner): + """Retrieve a list of links to transaction outputs for a given public + key. Args: owner (str): base58 encoded public key. @@ -383,10 +384,9 @@ class Bigchain(object): :obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s pointing to another transaction's condition """ - # get all transactions in which owner is in the `owners_after` list response = backend.query.get_owned_ids(self.connection, owner) - owned = [] + links = [] for tx in response: # disregard transactions from invalid blocks @@ -411,10 +411,23 @@ class Bigchain(object): # subfulfillment for `owner` if utils.condition_details_has_owner(output['condition']['details'], owner): tx_link = TransactionLink(tx['id'], index) - # check if input was already spent - if not self.get_spent(tx_link.txid, tx_link.output): - owned.append(tx_link) + links.append(tx_link) + return links + def get_owned_ids(self, owner): + """Retrieve a list of ``txid`` s that can be used as inputs. + + Args: + owner (str): base58 encoded public key. + + Returns: + :obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s + pointing to another transaction's condition + """ + owned = [] + for tx_link in self.get_outputs(owner): + if not self.get_spent(tx_link.txid, tx_link.output): + owned.append(tx_link) return owned def get_transactions_filtered(self, asset_id, operation=None): diff --git a/tests/common/test_transaction.py b/tests/common/test_transaction.py index b4ef427c..56f81262 100644 --- a/tests/common/test_transaction.py +++ b/tests/common/test_transaction.py @@ -436,6 +436,15 @@ def test_cast_transaction_link_to_boolean(): assert bool(TransactionLink(False, False)) is True +def test_transaction_link_eq(): + from bigchaindb.common.transaction import TransactionLink + + assert TransactionLink(1, 2) == TransactionLink(1, 2) + assert TransactionLink(2, 2) != TransactionLink(1, 2) + assert TransactionLink(1, 1) != TransactionLink(1, 2) + assert TransactionLink(2, 1) != TransactionLink(1, 2) + + def test_add_input_to_tx(user_input, asset_definition): from bigchaindb.common.transaction import Transaction diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index 1bf028b0..cfc2e93f 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1,6 +1,7 @@ from time import sleep import pytest +from unittest.mock import patch pytestmark = pytest.mark.bdb @@ -1156,3 +1157,15 @@ class TestMultipleInputs(object): # check that the other remain marked as unspent for unspent in transactions[1:]: assert b.get_spent(unspent.id, 0) is None + + +def test_get_owned_ids_calls(): + from bigchaindb.common.transaction import TransactionLink as TL + from bigchaindb.core import Bigchain + with patch('bigchaindb.core.Bigchain.get_outputs') as get_outputs: + get_outputs.return_value = [TL('a', 1), TL('b', 2)] + with patch('bigchaindb.core.Bigchain.get_spent') as get_spent: + get_spent.side_effect = [True, False] + out = Bigchain().get_owned_ids('abc') + assert get_outputs.called_once_with('abc') + assert out == [TL('b', 2)] From 897ffe81bca5dc5c4856e4f81a67d69e3a2ea091 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Thu, 19 Jan 2017 15:49:30 +0100 Subject: [PATCH 015/155] outputs endpoint with unspent filter parameter --- bigchaindb/core.py | 16 +++++++---- bigchaindb/web/routes.py | 4 +-- bigchaindb/web/views/outputs.py | 28 ++++++++++++++++++ bigchaindb/web/views/unspents.py | 23 --------------- tests/db/test_bigchain_api.py | 27 ++++++++++++++++-- tests/web/test_outputs.py | 49 ++++++++++++++++++++++++++++++++ tests/web/test_unspents.py | 24 ---------------- 7 files changed, 114 insertions(+), 57 deletions(-) create mode 100644 bigchaindb/web/views/outputs.py delete mode 100644 bigchaindb/web/views/unspents.py create mode 100644 tests/web/test_outputs.py delete mode 100644 tests/web/test_unspents.py diff --git a/bigchaindb/core.py b/bigchaindb/core.py index 459c4908..871c3707 100644 --- a/bigchaindb/core.py +++ b/bigchaindb/core.py @@ -424,11 +424,17 @@ class Bigchain(object): :obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s pointing to another transaction's condition """ - owned = [] - for tx_link in self.get_outputs(owner): - if not self.get_spent(tx_link.txid, tx_link.output): - owned.append(tx_link) - return owned + return self.get_outputs_filtered(owner, include_spent=False) + + def get_outputs_filtered(self, owner, include_spent=True): + """ + Get a list of output links filtered on some criteria + """ + outputs = self.get_outputs(owner) + if not include_spent: + outputs = [o for o in outputs + if not self.get_spent(o.txid, o.output)] + return outputs def get_transactions_filtered(self, asset_id, operation=None): """ diff --git a/bigchaindb/web/routes.py b/bigchaindb/web/routes.py index 18133b3e..b20f8d40 100644 --- a/bigchaindb/web/routes.py +++ b/bigchaindb/web/routes.py @@ -5,7 +5,7 @@ from bigchaindb.web.views import ( info, statuses, transactions as tx, - unspents, + outputs, votes, ) @@ -30,7 +30,7 @@ ROUTES_API_V1 = [ r('statuses/', statuses.StatusApi), r('transactions/', tx.TransactionApi), r('transactions', tx.TransactionListApi), - r('unspents/', unspents.UnspentListApi), + r('outputs/', outputs.OutputListApi), r('votes/', votes.VotesApi), ] diff --git a/bigchaindb/web/views/outputs.py b/bigchaindb/web/views/outputs.py new file mode 100644 index 00000000..735a428f --- /dev/null +++ b/bigchaindb/web/views/outputs.py @@ -0,0 +1,28 @@ +from flask import current_app +from flask_restful import reqparse, Resource + +from bigchaindb.web.views import parameters + + +class OutputListApi(Resource): + def get(self): + """API endpoint to retrieve a list of links to transaction + outputs. + + Returns: + A :obj:`list` of :cls:`str` of links to outputs. + """ + parser = reqparse.RequestParser() + parser.add_argument('public_key', type=parameters.valid_ed25519, + required=True) + parser.add_argument('unspent', type=parameters.valid_bool) + args = parser.parse_args() + + pool = current_app.config['bigchain_pool'] + include_spent = not args['unspent'] + + with pool() as bigchain: + outputs = bigchain.get_outputs_filtered(args['public_key'], + include_spent) + # NOTE: We pass '..' as a path to create a valid relative URI + return [u.to_uri('..') for u in outputs] diff --git a/bigchaindb/web/views/unspents.py b/bigchaindb/web/views/unspents.py deleted file mode 100644 index 8cca995f..00000000 --- a/bigchaindb/web/views/unspents.py +++ /dev/null @@ -1,23 +0,0 @@ -from flask import current_app -from flask_restful import reqparse, Resource - - -class UnspentListApi(Resource): - def get(self): - """API endpoint to retrieve a list of links to transactions's - conditions that have not been used in any previous transaction. - - Returns: - A :obj:`list` of :cls:`str` of links to unfulfilled conditions. - """ - parser = reqparse.RequestParser() - parser.add_argument('public_key', type=str, location='args', - required=True) - args = parser.parse_args() - - pool = current_app.config['bigchain_pool'] - - with pool() as bigchain: - unspents = bigchain.get_owned_ids(args['public_key']) - # NOTE: We pass '..' as a path to create a valid relative URI - return [u.to_uri('..') for u in unspents] diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index cfc2e93f..78c14a28 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1159,13 +1159,34 @@ class TestMultipleInputs(object): assert b.get_spent(unspent.id, 0) is None -def test_get_owned_ids_calls(): +def test_get_owned_ids_calls_get_outputs_filtered(): + from bigchaindb.core import Bigchain + with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: + b = Bigchain() + res = b.get_owned_ids("abc") + gof.assert_called_once_with("abc", include_spent=False) + assert res == gof() + + +def test_get_outputs_filtered_only_unspent(): from bigchaindb.common.transaction import TransactionLink as TL from bigchaindb.core import Bigchain with patch('bigchaindb.core.Bigchain.get_outputs') as get_outputs: get_outputs.return_value = [TL('a', 1), TL('b', 2)] with patch('bigchaindb.core.Bigchain.get_spent') as get_spent: get_spent.side_effect = [True, False] - out = Bigchain().get_owned_ids('abc') - assert get_outputs.called_once_with('abc') + out = Bigchain().get_outputs_filtered('abc', include_spent=False) + get_outputs.assert_called_once_with('abc') assert out == [TL('b', 2)] + + +def test_get_outputs_filtered(): + from bigchaindb.common.transaction import TransactionLink as TL + from bigchaindb.core import Bigchain + with patch('bigchaindb.core.Bigchain.get_outputs') as get_outputs: + get_outputs.return_value = [TL('a', 1), TL('b', 2)] + with patch('bigchaindb.core.Bigchain.get_spent') as get_spent: + out = Bigchain().get_outputs_filtered('abc') + get_outputs.assert_called_once_with('abc') + get_spent.assert_not_called() + assert out == get_outputs.return_value diff --git a/tests/web/test_outputs.py b/tests/web/test_outputs.py new file mode 100644 index 00000000..8fb418ea --- /dev/null +++ b/tests/web/test_outputs.py @@ -0,0 +1,49 @@ +import pytest +from unittest.mock import MagicMock, patch + +pytestmark = [pytest.mark.bdb, pytest.mark.usefixtures('inputs')] + +UNSPENTS_ENDPOINT = '/api/v1/outputs/' + + +def test_get_outputs_endpoint(client, user_pk): + m = MagicMock() + m.to_uri.side_effect = lambda s: s + with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: + gof.return_value = [m, m] + res = client.get(UNSPENTS_ENDPOINT + '?public_key={}'.format(user_pk)) + assert res.json == ["..", ".."] + assert res.status_code == 200 + gof.assert_called_once_with(user_pk, True) + + +def test_get_outputs_endpoint_unspent(client, user_pk): + m = MagicMock() + m.to_uri.side_effect = lambda s: s + with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: + gof.return_value = [m] + params = '?unspent=true&public_key={}'.format(user_pk) + res = client.get(UNSPENTS_ENDPOINT + params) + assert res.json == [".."] + assert res.status_code == 200 + gof.assert_called_once_with(user_pk, False) + + +def test_get_outputs_endpoint_without_public_key(client): + res = client.get(UNSPENTS_ENDPOINT) + assert res.status_code == 400 + + +def test_get_outputs_endpoint_with_invalid_public_key(client): + expected = {'message': {'public_key': 'Invalid base58 ed25519 key'}} + res = client.get(UNSPENTS_ENDPOINT + '?public_key=abc') + assert expected == res.json + assert res.status_code == 400 + + +def test_get_outputs_endpoint_with_invalid_unspent(client, user_pk): + expected = {'message': {'unspent': 'Boolean value must be "true" or "false" (lowercase)'}} + params = '?unspent=tru&public_key={}'.format(user_pk) + res = client.get(UNSPENTS_ENDPOINT + params) + assert expected == res.json + assert res.status_code == 400 diff --git a/tests/web/test_unspents.py b/tests/web/test_unspents.py deleted file mode 100644 index 9539c664..00000000 --- a/tests/web/test_unspents.py +++ /dev/null @@ -1,24 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.bdb, pytest.mark.usefixtures('inputs')] - -UNSPENTS_ENDPOINT = '/api/v1/unspents/' - - -def test_get_unspents_endpoint(b, client, user_pk): - expected = [u.to_uri('..') for u in b.get_owned_ids(user_pk)] - res = client.get(UNSPENTS_ENDPOINT + '?public_key={}'.format(user_pk)) - assert expected == res.json - assert res.status_code == 200 - - -def test_get_unspents_endpoint_without_public_key(client): - res = client.get(UNSPENTS_ENDPOINT) - assert res.status_code == 400 - - -def test_get_unspents_endpoint_with_unused_public_key(client): - expected = [] - res = client.get(UNSPENTS_ENDPOINT + '?public_key=abc') - assert expected == res.json - assert res.status_code == 200 From f12264773c33df20ec55e3f61c6f54f329fa2d96 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Mon, 23 Jan 2017 16:49:59 +0100 Subject: [PATCH 016/155] bigchaindb configure now requires a positional backend argument. Created and fixed tests. Updated `b` fixture --- bigchaindb/__init__.py | 22 +++++++++++++------ bigchaindb/commands/bigchain.py | 20 ++++++++++++++--- tests/backend/test_generics.py | 29 +++++++++++++----------- tests/commands/test_commands.py | 39 +++++++++++++++++++++++++++++---- tests/conftest.py | 14 +++++------- tests/test_config_utils.py | 17 ++++++++++++-- 6 files changed, 104 insertions(+), 37 deletions(-) diff --git a/bigchaindb/__init__.py b/bigchaindb/__init__.py index c50f4810..315774e5 100644 --- a/bigchaindb/__init__.py +++ b/bigchaindb/__init__.py @@ -5,6 +5,20 @@ import os # PORT_NUMBER = reduce(lambda x, y: x * y, map(ord, 'BigchainDB')) % 2**16 # basically, the port number is 9984 +_database_rethinkdb = { + 'backend': os.environ.get('BIGCHAINDB_DATABASE_BACKEND', 'rethinkdb'), + 'host': os.environ.get('BIGCHAINDB_DATABASE_HOST', 'localhost'), + 'port': int(os.environ.get('BIGCHAINDB_DATABASE_PORT', 28015)), + 'name': os.environ.get('BIGCHAINDB_DATABASE_NAME', 'bigchain'), +} + +_database_mongodb = { + 'backend': os.environ.get('BIGCHAINDB_DATABASE_BACKEND', 'mongodb'), + 'host': os.environ.get('BIGCHAINDB_DATABASE_HOST', 'localhost'), + 'port': int(os.environ.get('BIGCHAINDB_DATABASE_PORT', 27017)), + 'name': os.environ.get('BIGCHAINDB_DATABASE_NAME', 'bigchain'), + 'replicaset': os.environ.get('BIGCHAINDB_DATABASE_REPLICASET', 'bigchain-rs'), +} config = { 'server': { @@ -14,13 +28,7 @@ config = { 'workers': None, # if none, the value will be cpu_count * 2 + 1 'threads': None, # if none, the value will be cpu_count * 2 + 1 }, - 'database': { - 'backend': os.environ.get('BIGCHAINDB_DATABASE_BACKEND', 'rethinkdb'), - 'host': os.environ.get('BIGCHAINDB_DATABASE_HOST', 'localhost'), - 'port': int(os.environ.get('BIGCHAINDB_DATABASE_PORT', 28015)), - 'name': os.environ.get('BIGCHAINDB_DATABASE_NAME', 'bigchain'), - 'replicaset': os.environ.get('BIGCHAINDB_DATABASE_REPLICASET', 'bigchain-rs'), - }, + 'database': _database_rethinkdb, 'keypair': { 'public': None, 'private': None, diff --git a/bigchaindb/commands/bigchain.py b/bigchaindb/commands/bigchain.py index 6661e902..2fc8df70 100644 --- a/bigchaindb/commands/bigchain.py +++ b/bigchaindb/commands/bigchain.py @@ -86,6 +86,16 @@ def run_configure(args, skip_if_exists=False): conf['keypair']['private'], conf['keypair']['public'] = \ crypto.generate_key_pair() + # select the correct config defaults based on the backend + print('Generating default configuration for backend {}' + .format(args.backend)) + database = {} + if args.backend == 'rethinkdb': + database = bigchaindb._database_rethinkdb + elif args.backend == 'mongodb': + database = bigchaindb._database_mongodb + conf['database'] = database + if not args.yes: for key in ('bind', ): val = conf['server'][key] @@ -282,9 +292,13 @@ def create_parser(): dest='command') # parser for writing a config file - subparsers.add_parser('configure', - help='Prepare the config file ' - 'and create the node keypair') + config_parser = subparsers.add_parser('configure', + help='Prepare the config file ' + 'and create the node keypair') + config_parser.add_argument('backend', + choices=['rethinkdb', 'mongodb'], + help='The backend to use. It can be either ' + 'rethinkdb or mongodb.') # parsers for showing/exporting config values subparsers.add_parser('show-config', diff --git a/tests/backend/test_generics.py b/tests/backend/test_generics.py index 2ab33a7c..2049d72b 100644 --- a/tests/backend/test_generics.py +++ b/tests/backend/test_generics.py @@ -1,4 +1,3 @@ -from importlib import import_module from unittest.mock import patch from pytest import mark, raises @@ -69,10 +68,6 @@ def test_changefeed_class(changefeed_class_func_name, args_qty): changefeed_class_func(None, *range(args_qty)) -@mark.parametrize('db,conn_cls', ( - ('mongodb', 'MongoDBConnection'), - ('rethinkdb', 'RethinkDBConnection'), -)) @patch('bigchaindb.backend.schema.create_indexes', autospec=True, return_value=None) @patch('bigchaindb.backend.schema.create_tables', @@ -80,16 +75,24 @@ def test_changefeed_class(changefeed_class_func_name, args_qty): @patch('bigchaindb.backend.schema.create_database', autospec=True, return_value=None) def test_init_database(mock_create_database, mock_create_tables, - mock_create_indexes, db, conn_cls): + mock_create_indexes): from bigchaindb.backend.schema import init_database - conn = getattr( - import_module('bigchaindb.backend.{}.connection'.format(db)), - conn_cls, - )('host', 'port', 'dbname') + from bigchaindb.backend.rethinkdb.connection import RethinkDBConnection + from bigchaindb.backend.mongodb.connection import MongoDBConnection + + # rethinkdb + conn = RethinkDBConnection('host', 'port', 'dbname') init_database(connection=conn, dbname='mickeymouse') - mock_create_database.assert_called_once_with(conn, 'mickeymouse') - mock_create_tables.assert_called_once_with(conn, 'mickeymouse') - mock_create_indexes.assert_called_once_with(conn, 'mickeymouse') + mock_create_database.assert_called_with(conn, 'mickeymouse') + mock_create_tables.assert_called_with(conn, 'mickeymouse') + mock_create_indexes.assert_called_with(conn, 'mickeymouse') + + # mongodb + conn = MongoDBConnection('host', 'port', 'dbname', replicaset='rs') + init_database(connection=conn, dbname='mickeymouse') + mock_create_database.assert_called_with(conn, 'mickeymouse') + mock_create_tables.assert_called_with(conn, 'mickeymouse') + mock_create_indexes.assert_called_with(conn, 'mickeymouse') @mark.parametrize('admin_func_name,kwargs', ( diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index a2e485da..1a1291e3 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -12,7 +12,8 @@ def test_make_sure_we_dont_remove_any_command(): parser = create_parser() - assert parser.parse_args(['configure']).command + assert parser.parse_args(['configure', 'rethinkdb']).command + assert parser.parse_args(['configure', 'mongodb']).command assert parser.parse_args(['show-config']).command assert parser.parse_args(['export-my-pubkey']).command assert parser.parse_args(['init']).command @@ -31,8 +32,8 @@ def test_start_raises_if_command_not_implemented(): with pytest.raises(NotImplementedError): # Will raise because `scope`, the third parameter, - # doesn't contain the function `run_configure` - utils.start(parser, ['configure'], {}) + # doesn't contain the function `run_start` + utils.start(parser, ['start'], {}) def test_start_raises_if_no_arguments_given(): @@ -204,7 +205,7 @@ def test_run_configure_when_config_does_not_exist(monkeypatch, from bigchaindb.commands.bigchain import run_configure monkeypatch.setattr('os.path.exists', lambda path: False) monkeypatch.setattr('builtins.input', lambda: '\n') - args = Namespace(config='foo', yes=True) + args = Namespace(config='foo', backend='rethinkdb', yes=True) return_value = run_configure(args) assert return_value is None @@ -228,6 +229,36 @@ def test_run_configure_when_config_does_exist(monkeypatch, assert value == {} +@pytest.mark.parametrize('backend', ( + 'rethinkdb', + 'mongodb', +)) +def test_run_configure_with_backend(backend, monkeypatch, mock_write_config): + import bigchaindb + from bigchaindb.commands.bigchain import run_configure + + value = {} + + def mock_write_config(new_config, filename=None): + value['return'] = new_config + + monkeypatch.setattr('os.path.exists', lambda path: False) + monkeypatch.setattr('builtins.input', lambda: '\n') + monkeypatch.setattr('bigchaindb.config_utils.write_config', + mock_write_config) + + args = Namespace(config='foo', backend=backend, yes=True) + expected_config = bigchaindb.config + run_configure(args) + + # update the expected config with the correct backend and keypair + backend_conf = getattr(bigchaindb, '_database_' + backend) + expected_config.update({'database': backend_conf, + 'keypair': value['return']['keypair']}) + + assert value['return'] == expected_config + + @patch('bigchaindb.common.crypto.generate_key_pair', return_value=('private_key', 'public_key')) @pytest.mark.usefixtures('ignore_local_config_file') diff --git a/tests/conftest.py b/tests/conftest.py index a69564bc..c3177c14 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -109,26 +109,24 @@ def _restore_dbs(request): @pytest.fixture(scope='session') def _configure_bigchaindb(request): + import bigchaindb from bigchaindb import config_utils test_db_name = TEST_DB_NAME # Put a suffix like _gw0, _gw1 etc on xdist processes xdist_suffix = getattr(request.config, 'slaveinput', {}).get('slaveid') if xdist_suffix: test_db_name = '{}_{}'.format(TEST_DB_NAME, xdist_suffix) + + backend = request.config.getoption('--database-backend') + backend_conf = getattr(bigchaindb, '_database_' + backend) config = { - 'database': { - 'name': test_db_name, - 'backend': request.config.getoption('--database-backend'), - }, + 'database': backend_conf, 'keypair': { 'private': '31Lb1ZGKTyHnmVK3LUMrAUrPNfd4sE2YyBt3UA4A25aA', 'public': '4XYfCbabAWVUCbjTmRTFEu2sc3dFEdkse4r6X498B1s8', } } - # FIXME - if config['database']['backend'] == 'mongodb': - # not a great way to do this - config['database']['port'] = 27017 + config['database']['name'] = test_db_name config_utils.set_config(config) diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index 6328d28c..4cb8bd45 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -130,7 +130,6 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): 'host': 'test-host', 'port': 4242, 'name': 'test-dbname', - 'replicaset': 'bigchain-rs' }, 'keypair': { 'public': None, @@ -215,7 +214,6 @@ def test_write_config(): ('BIGCHAINDB_DATABASE_HOST', 'test-host', 'host'), ('BIGCHAINDB_DATABASE_PORT', 4242, 'port'), ('BIGCHAINDB_DATABASE_NAME', 'test-db', 'name'), - ('BIGCHAINDB_DATABASE_REPLICASET', 'test-replicaset', 'replicaset') )) def test_database_envs(env_name, env_value, config_key, monkeypatch): import bigchaindb @@ -227,3 +225,18 @@ def test_database_envs(env_name, env_value, config_key, monkeypatch): expected_config['database'][config_key] = env_value assert bigchaindb.config == expected_config + + +def test_database_envs_replicaset(monkeypatch): + # the replica set env is only used if the backend is mongodb + import bigchaindb + + monkeypatch.setattr('os.environ', {'BIGCHAINDB_DATABASE_REPLICASET': + 'test-replicaset'}) + bigchaindb.config['database'] = bigchaindb._database_mongodb + bigchaindb.config_utils.autoconfigure() + + expected_config = copy.deepcopy(bigchaindb.config) + expected_config['database']['replicaset'] = 'test-replicaset' + + assert bigchaindb.config == expected_config From 927e57beba0a51d78c07313cca50f3b6926ffefa Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Mon, 23 Jan 2017 17:29:42 +0100 Subject: [PATCH 017/155] Changed `backend.connect` to handle backend specific kwargs. Fixed tests --- bigchaindb/backend/connection.py | 8 +++++++- bigchaindb/backend/mongodb/connection.py | 2 +- bigchaindb/backend/rethinkdb/connection.py | 2 +- tests/test_config_utils.py | 17 +++++++++++++++-- 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/bigchaindb/backend/connection.py b/bigchaindb/backend/connection.py index 0fda4078..629b6d8b 100644 --- a/bigchaindb/backend/connection.py +++ b/bigchaindb/backend/connection.py @@ -40,6 +40,12 @@ def connect(backend=None, host=None, port=None, name=None, replicaset=None): host = host or bigchaindb.config['database']['host'] port = port or bigchaindb.config['database']['port'] dbname = name or bigchaindb.config['database']['name'] + # Not sure how to handle this here. This setting is only relevant for + # mongodb. + # I added **kwargs for both RethinkDBConnection and MongoDBConnection + # to handle these these additional args. In case of RethinkDBConnection + # it just does not do anything with it. + replicaset = replicaset or bigchaindb.config['database'].get('replicaset') try: module_name, _, class_name = BACKENDS[backend].rpartition('.') @@ -51,7 +57,7 @@ def connect(backend=None, host=None, port=None, name=None, replicaset=None): raise ConfigurationError('Error loading backend `{}`'.format(backend)) from exc logger.debug('Connection: {}'.format(Class)) - return Class(host, port, dbname) + return Class(host, port, dbname, replicaset=replicaset) class Connection: diff --git a/bigchaindb/backend/mongodb/connection.py b/bigchaindb/backend/mongodb/connection.py index 19731161..43e92dd0 100644 --- a/bigchaindb/backend/mongodb/connection.py +++ b/bigchaindb/backend/mongodb/connection.py @@ -14,7 +14,7 @@ logger = logging.getLogger(__name__) class MongoDBConnection(Connection): def __init__(self, host=None, port=None, dbname=None, max_tries=3, - replicaset=None): + replicaset=None, **kwargs): """Create a new Connection instance. Args: diff --git a/bigchaindb/backend/rethinkdb/connection.py b/bigchaindb/backend/rethinkdb/connection.py index 173cdc7b..c0506f1f 100644 --- a/bigchaindb/backend/rethinkdb/connection.py +++ b/bigchaindb/backend/rethinkdb/connection.py @@ -17,7 +17,7 @@ class RethinkDBConnection(Connection): more times to run the query or open a connection. """ - def __init__(self, host, port, dbname, max_tries=3): + def __init__(self, host, port, dbname, max_tries=3, **kwargs): """Create a new :class:`~.RethinkDBConnection` instance. See :meth:`.Connection.__init__` for diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index 4cb8bd45..c1f63742 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -14,20 +14,28 @@ def clean_config(monkeypatch): monkeypatch.setattr('bigchaindb.config', copy.deepcopy(ORIGINAL_CONFIG)) -def test_bigchain_instance_is_initialized_when_conf_provided(): +def test_bigchain_instance_is_initialized_when_conf_provided(request): + import bigchaindb from bigchaindb import config_utils assert 'CONFIGURED' not in bigchaindb.config config_utils.set_config({'keypair': {'public': 'a', 'private': 'b'}}) assert bigchaindb.config['CONFIGURED'] is True + + # set the current backend so that Bigchain can create a connection + backend = request.config.getoption('--database-backend') + backend_conf = getattr(bigchaindb, '_database_' + backend) + bigchaindb.config['database'] = backend_conf + b = bigchaindb.Bigchain() assert b.me assert b.me_private -def test_bigchain_instance_raises_when_not_configured(monkeypatch): +def test_bigchain_instance_raises_when_not_configured(request, monkeypatch): + import bigchaindb from bigchaindb import config_utils from bigchaindb.common import exceptions assert 'CONFIGURED' not in bigchaindb.config @@ -36,6 +44,11 @@ def test_bigchain_instance_raises_when_not_configured(monkeypatch): # from existing configurations monkeypatch.setattr(config_utils, 'autoconfigure', lambda: 0) + # set the current backend so that Bigchain can create a connection + backend = request.config.getoption('--database-backend') + backend_conf = getattr(bigchaindb, '_database_' + backend) + bigchaindb.config['database'] = backend_conf + with pytest.raises(exceptions.KeypairNotFoundException): bigchaindb.Bigchain() From bd048a311590fdb9c7e0b86e7048cde955dd585b Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 23 Jan 2017 17:30:37 +0100 Subject: [PATCH 018/155] add flake8-quotes checker and cleanup double quotes --- bigchaindb/backend/utils.py | 6 ++-- bigchaindb/common/transaction.py | 2 +- bigchaindb/consensus.py | 4 +-- bigchaindb/web/views/info.py | 10 +++---- bigchaindb/web/views/statuses.py | 6 ++-- docs/server/generate_schema_documentation.py | 6 ++-- setup.py | 1 + tests/backend/rethinkdb/test_admin.py | 12 ++++---- tests/common/schema/test_schema.py | 4 +-- tests/web/test_blocks.py | 30 ++++++++++---------- tests/web/test_statuses.py | 18 ++++++------ tests/web/test_transactions.py | 10 +++---- tests/web/test_votes.py | 12 ++++---- 13 files changed, 61 insertions(+), 60 deletions(-) diff --git a/bigchaindb/backend/utils.py b/bigchaindb/backend/utils.py index 23b3e2d9..4a0c4095 100644 --- a/bigchaindb/backend/utils.py +++ b/bigchaindb/backend/utils.py @@ -12,9 +12,9 @@ def module_dispatch_registrar(module): return dispatch_registrar.register(obj_type)(func) except AttributeError as ex: raise ModuleDispatchRegistrationError( - ("`{module}` does not contain a single-dispatchable " - "function named `{func}`. The module being registered " - "was not implemented correctly!").format( + ('`{module}` does not contain a single-dispatchable ' + 'function named `{func}`. The module being registered ' + 'was not implemented correctly!').format( func=func_name, module=module.__name__)) from ex return wrapper return dispatch_wrapper diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index bda62663..e88ecabe 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -118,7 +118,7 @@ class Input(object): fulfillment = Fulfillment.from_uri(data['fulfillment']) except ValueError: # TODO FOR CC: Throw an `InvalidSignature` error in this case. - raise InvalidSignature("Fulfillment URI couldn't been parsed") + raise InvalidSignature('Fulfillment URI couldn\'t been parsed') except TypeError: # NOTE: See comment about this special case in # `Input.to_dict` diff --git a/bigchaindb/consensus.py b/bigchaindb/consensus.py index 9e7a11a1..1cc6e9ec 100644 --- a/bigchaindb/consensus.py +++ b/bigchaindb/consensus.py @@ -39,6 +39,6 @@ class BaseConsensusRules(): except SchemaValidationError as exc: logger.warning(exc) else: - logger.warning("Vote failed signature verification: " - "%s with voters: %s", signed_vote, voters) + logger.warning('Vote failed signature verification: ' + '%s with voters: %s', signed_vote, voters) return False diff --git a/bigchaindb/web/views/info.py b/bigchaindb/web/views/info.py index 98e061b6..cbe32acb 100644 --- a/bigchaindb/web/views/info.py +++ b/bigchaindb/web/views/info.py @@ -36,10 +36,10 @@ class ApiV1Index(Resource): '/drivers-clients/http-client-server-api.html', ] return { - "_links": { - "docs": ''.join(docs_url), - "self": api_root, - "statuses": api_root + "statuses/", - "transactions": api_root + "transactions/", + '_links': { + 'docs': ''.join(docs_url), + 'self': api_root, + 'statuses': api_root + 'statuses/', + 'transactions': api_root + 'transactions/', }, } diff --git a/bigchaindb/web/views/statuses.py b/bigchaindb/web/views/statuses.py index 06b768e6..39f880b1 100644 --- a/bigchaindb/web/views/statuses.py +++ b/bigchaindb/web/views/statuses.py @@ -28,7 +28,7 @@ class StatusApi(Resource): # logical xor - exactly one query argument required if bool(tx_id) == bool(block_id): - return make_error(400, "Provide exactly one query parameter. Choices are: block_id, tx_id") + return make_error(400, 'Provide exactly one query parameter. Choices are: block_id, tx_id') pool = current_app.config['bigchain_pool'] status, links = None, None @@ -37,7 +37,7 @@ class StatusApi(Resource): if tx_id: status = bigchain.get_status(tx_id) links = { - "tx": "/transactions/{}".format(tx_id) + 'tx': '/transactions/{}'.format(tx_id) } elif block_id: @@ -56,7 +56,7 @@ class StatusApi(Resource): if links: response.update({ - "_links": links + '_links': links }) return response diff --git a/docs/server/generate_schema_documentation.py b/docs/server/generate_schema_documentation.py index 9b6c1407..c94fe3a9 100644 --- a/docs/server/generate_schema_documentation.py +++ b/docs/server/generate_schema_documentation.py @@ -189,7 +189,7 @@ def render_section(section_name, obj): 'type': property_type(prop), }] except Exception as exc: - raise ValueError("Error rendering property: %s" % name, exc) + raise ValueError('Error rendering property: %s' % name, exc) return '\n\n'.join(out + ['']) @@ -201,7 +201,7 @@ def property_description(prop): return property_description(resolve_ref(prop['$ref'])) if 'anyOf' in prop: return property_description(prop['anyOf'][0]) - raise KeyError("description") + raise KeyError('description') def property_type(prop): @@ -214,7 +214,7 @@ def property_type(prop): return ' or '.join(property_type(p) for p in prop['anyOf']) if '$ref' in prop: return property_type(resolve_ref(prop['$ref'])) - raise ValueError("Could not resolve property type") + raise ValueError('Could not resolve property type') DEFINITION_BASE_PATH = '#/definitions/' diff --git a/setup.py b/setup.py index 9dd050bc..f7085218 100644 --- a/setup.py +++ b/setup.py @@ -45,6 +45,7 @@ tests_require = [ 'coverage', 'pep8', 'flake8', + 'flake8-quotes==0.8.1', 'pylint', 'pytest>=3.0.0', 'pytest-catchlog>=1.2.2', diff --git a/tests/backend/rethinkdb/test_admin.py b/tests/backend/rethinkdb/test_admin.py index f489f5f5..8c4f0528 100644 --- a/tests/backend/rethinkdb/test_admin.py +++ b/tests/backend/rethinkdb/test_admin.py @@ -57,8 +57,8 @@ def test_set_shards_dry_run(rdb_conn, db_name, db_conn): @pytest.mark.bdb @pytest.mark.skipif( _count_rethinkdb_servers() < 2, - reason=("Requires at least two servers. It's impossible to have" - "more replicas of the data than there are servers.") + reason=('Requires at least two servers. It\'s impossible to have' + 'more replicas of the data than there are servers.') ) def test_set_replicas(rdb_conn, db_name, db_conn): from bigchaindb.backend.schema import TABLES @@ -85,8 +85,8 @@ def test_set_replicas(rdb_conn, db_name, db_conn): @pytest.mark.bdb @pytest.mark.skipif( _count_rethinkdb_servers() < 2, - reason=("Requires at least two servers. It's impossible to have" - "more replicas of the data than there are servers.") + reason=('Requires at least two servers. It\'s impossible to have' + 'more replicas of the data than there are servers.') ) def test_set_replicas_dry_run(rdb_conn, db_name, db_conn): from bigchaindb.backend.schema import TABLES @@ -109,8 +109,8 @@ def test_set_replicas_dry_run(rdb_conn, db_name, db_conn): @pytest.mark.bdb @pytest.mark.skipif( _count_rethinkdb_servers() < 2, - reason=("Requires at least two servers. It's impossible to have" - "more replicas of the data than there are servers.") + reason=('Requires at least two servers. It\'s impossible to have' + 'more replicas of the data than there are servers.') ) def test_reconfigure(rdb_conn, db_name, db_conn): from bigchaindb.backend.rethinkdb.admin import reconfigure diff --git a/tests/common/schema/test_schema.py b/tests/common/schema/test_schema.py index a7cc6891..02a00ee2 100644 --- a/tests/common/schema/test_schema.py +++ b/tests/common/schema/test_schema.py @@ -13,7 +13,7 @@ def _test_additionalproperties(node, path=''): if isinstance(node, dict): if node.get('type') == 'object': assert 'additionalProperties' in node, \ - ("additionalProperties not set at path:" + path) + ('additionalProperties not set at path:' + path) for name, val in node.items(): _test_additionalproperties(val, path + name + '.') @@ -47,7 +47,7 @@ def test_drop_descriptions(): }, 'definitions': { 'wat': { - 'description': "go" + 'description': 'go' } } } diff --git a/tests/web/test_blocks.py b/tests/web/test_blocks.py index b0581061..01c17d71 100644 --- a/tests/web/test_blocks.py +++ b/tests/web/test_blocks.py @@ -41,7 +41,7 @@ def test_get_blocks_by_txid_endpoint(b, client): block_invalid = b.create_block([tx]) b.write_block(block_invalid) - res = client.get(BLOCKS_ENDPOINT + "?tx_id=" + tx.id) + res = client.get(BLOCKS_ENDPOINT + '?tx_id=' + tx.id) # test if block is retrieved as undecided assert res.status_code == 200 assert block_invalid.id in res.json @@ -51,7 +51,7 @@ def test_get_blocks_by_txid_endpoint(b, client): vote = b.vote(block_invalid.id, b.get_last_voted_block().id, False) b.write_vote(vote) - res = client.get(BLOCKS_ENDPOINT + "?tx_id=" + tx.id) + res = client.get(BLOCKS_ENDPOINT + '?tx_id=' + tx.id) # test if block is retrieved as invalid assert res.status_code == 200 assert block_invalid.id in res.json @@ -61,7 +61,7 @@ def test_get_blocks_by_txid_endpoint(b, client): block_valid = b.create_block([tx, tx2]) b.write_block(block_valid) - res = client.get(BLOCKS_ENDPOINT + "?tx_id=" + tx.id) + res = client.get(BLOCKS_ENDPOINT + '?tx_id=' + tx.id) # test if block is retrieved as undecided assert res.status_code == 200 assert block_valid.id in res.json @@ -71,7 +71,7 @@ def test_get_blocks_by_txid_endpoint(b, client): vote = b.vote(block_valid.id, block_invalid.id, True) b.write_vote(vote) - res = client.get(BLOCKS_ENDPOINT + "?tx_id=" + tx.id) + res = client.get(BLOCKS_ENDPOINT + '?tx_id=' + tx.id) # test if block is retrieved as valid assert res.status_code == 200 assert block_valid.id in res.json @@ -96,19 +96,19 @@ def test_get_blocks_by_txid_and_status_endpoint(b, client): block_valid = b.create_block([tx, tx2]) b.write_block(block_valid) - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_INVALID)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_INVALID)) # test if no blocks are retrieved as invalid assert res.status_code == 200 assert len(res.json) == 0 - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_UNDECIDED)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_UNDECIDED)) # test if both blocks are retrieved as undecided assert res.status_code == 200 assert block_valid.id in res.json assert block_invalid.id in res.json assert len(res.json) == 2 - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_VALID)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_VALID)) # test if no blocks are retrieved as valid assert res.status_code == 200 assert len(res.json) == 0 @@ -121,18 +121,18 @@ def test_get_blocks_by_txid_and_status_endpoint(b, client): vote = b.vote(block_valid.id, block_invalid.id, True) b.write_vote(vote) - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_INVALID)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_INVALID)) # test if the invalid block is retrieved as invalid assert res.status_code == 200 assert block_invalid.id in res.json assert len(res.json) == 1 - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_UNDECIDED)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_UNDECIDED)) # test if no blocks are retrieved as undecided assert res.status_code == 200 assert len(res.json) == 0 - res = client.get("{}?tx_id={}&status={}".format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_VALID)) + res = client.get('{}?tx_id={}&status={}'.format(BLOCKS_ENDPOINT, tx.id, Bigchain.BLOCK_VALID)) # test if the valid block is retrieved as valid assert res.status_code == 200 assert block_valid.id in res.json @@ -141,11 +141,11 @@ def test_get_blocks_by_txid_and_status_endpoint(b, client): @pytest.mark.bdb def test_get_blocks_by_txid_endpoint_returns_empty_list_not_found(client): - res = client.get(BLOCKS_ENDPOINT + "?tx_id=") + res = client.get(BLOCKS_ENDPOINT + '?tx_id=') assert res.status_code == 200 assert len(res.json) == 0 - res = client.get(BLOCKS_ENDPOINT + "?tx_id=123") + res = client.get(BLOCKS_ENDPOINT + '?tx_id=123') assert res.status_code == 200 assert len(res.json) == 0 @@ -155,7 +155,7 @@ def test_get_blocks_by_txid_endpoint_returns_400_bad_query_params(client): res = client.get(BLOCKS_ENDPOINT) assert res.status_code == 400 - res = client.get(BLOCKS_ENDPOINT + "?ts_id=123") + res = client.get(BLOCKS_ENDPOINT + '?ts_id=123') assert res.status_code == 400 assert res.json == { 'message': { @@ -163,13 +163,13 @@ def test_get_blocks_by_txid_endpoint_returns_400_bad_query_params(client): } } - res = client.get(BLOCKS_ENDPOINT + "?tx_id=123&foo=123") + res = client.get(BLOCKS_ENDPOINT + '?tx_id=123&foo=123') assert res.status_code == 400 assert res.json == { 'message': 'Unknown arguments: foo' } - res = client.get(BLOCKS_ENDPOINT + "?tx_id=123&status=123") + res = client.get(BLOCKS_ENDPOINT + '?tx_id=123&status=123') assert res.status_code == 400 assert res.json == { 'message': { diff --git a/tests/web/test_statuses.py b/tests/web/test_statuses.py index 4c65bec4..af9d09d3 100644 --- a/tests/web/test_statuses.py +++ b/tests/web/test_statuses.py @@ -10,15 +10,15 @@ STATUSES_ENDPOINT = '/api/v1/statuses' def test_get_transaction_status_endpoint(b, client, user_pk): input_tx = b.get_owned_ids(user_pk).pop() tx, status = b.get_transaction(input_tx.txid, include_status=True) - res = client.get(STATUSES_ENDPOINT + "?tx_id=" + input_tx.txid) + res = client.get(STATUSES_ENDPOINT + '?tx_id=' + input_tx.txid) assert status == res.json['status'] - assert res.json['_links']['tx'] == "/transactions/{}".format(input_tx.txid) + assert res.json['_links']['tx'] == '/transactions/{}'.format(input_tx.txid) assert res.status_code == 200 @pytest.mark.bdb def test_get_transaction_status_endpoint_returns_404_if_not_found(client): - res = client.get(STATUSES_ENDPOINT + "?tx_id=123") + res = client.get(STATUSES_ENDPOINT + '?tx_id=123') assert res.status_code == 404 @@ -32,7 +32,7 @@ def test_get_block_status_endpoint_undecided(b, client): status = b.block_election_status(block.id, block.voters) - res = client.get(STATUSES_ENDPOINT + "?block_id=" + block.id) + res = client.get(STATUSES_ENDPOINT + '?block_id=' + block.id) assert status == res.json['status'] assert '_links' not in res.json assert res.status_code == 200 @@ -53,7 +53,7 @@ def test_get_block_status_endpoint_valid(b, client): status = b.block_election_status(block.id, block.voters) - res = client.get(STATUSES_ENDPOINT + "?block_id=" + block.id) + res = client.get(STATUSES_ENDPOINT + '?block_id=' + block.id) assert status == res.json['status'] assert '_links' not in res.json assert res.status_code == 200 @@ -74,7 +74,7 @@ def test_get_block_status_endpoint_invalid(b, client): status = b.block_election_status(block.id, block.voters) - res = client.get(STATUSES_ENDPOINT + "?block_id=" + block.id) + res = client.get(STATUSES_ENDPOINT + '?block_id=' + block.id) assert status == res.json['status'] assert '_links' not in res.json assert res.status_code == 200 @@ -82,7 +82,7 @@ def test_get_block_status_endpoint_invalid(b, client): @pytest.mark.bdb def test_get_block_status_endpoint_returns_404_if_not_found(client): - res = client.get(STATUSES_ENDPOINT + "?block_id=123") + res = client.get(STATUSES_ENDPOINT + '?block_id=123') assert res.status_code == 404 @@ -91,8 +91,8 @@ def test_get_status_endpoint_returns_400_bad_query_params(client): res = client.get(STATUSES_ENDPOINT) assert res.status_code == 400 - res = client.get(STATUSES_ENDPOINT + "?ts_id=123") + res = client.get(STATUSES_ENDPOINT + '?ts_id=123') assert res.status_code == 400 - res = client.get(STATUSES_ENDPOINT + "?tx_id=123&block_id=123") + res = client.get(STATUSES_ENDPOINT + '?tx_id=123&block_id=123') assert res.status_code == 400 diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index 9b7fac3f..bc951739 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -53,8 +53,8 @@ def test_post_create_transaction_with_invalid_id(b, client, caplog): res = client.post(TX_ENDPOINT, data=json.dumps(tx)) expected_status_code = 400 expected_error_message = ( - "Invalid transaction ({}): The transaction's id '{}' isn't equal to " - "the hash of its body, i.e. it's not valid." + 'Invalid transaction ({}): The transaction\'s id \'{}\' isn\'t equal to ' + 'the hash of its body, i.e. it\'s not valid.' ).format(InvalidHash.__name__, tx['id']) assert res.status_code == expected_status_code assert res.json['message'] == expected_error_message @@ -74,8 +74,8 @@ def test_post_create_transaction_with_invalid_signature(b, client, caplog): res = client.post(TX_ENDPOINT, data=json.dumps(tx)) expected_status_code = 400 expected_error_message = ( - "Invalid transaction ({}): Fulfillment URI " - "couldn't been parsed" + 'Invalid transaction ({}): Fulfillment URI ' + 'couldn\'t been parsed' ).format(InvalidSignature.__name__) assert res.status_code == expected_status_code assert res.json['message'] == expected_error_message @@ -97,7 +97,7 @@ def test_post_create_transaction_with_invalid_schema(client, caplog): res = client.post(TX_ENDPOINT, data=json.dumps(tx)) expected_status_code = 400 expected_error_message = ( - "Invalid transaction schema: 'version' is a required property") + 'Invalid transaction schema: \'version\' is a required property') assert res.status_code == expected_status_code assert res.json['message'] == expected_error_message assert caplog.records[0].args['status'] == expected_status_code diff --git a/tests/web/test_votes.py b/tests/web/test_votes.py index 0f788fc4..bae31b9a 100644 --- a/tests/web/test_votes.py +++ b/tests/web/test_votes.py @@ -18,7 +18,7 @@ def test_get_votes_endpoint(b, client): vote = b.vote(block.id, b.get_last_voted_block().id, True) b.write_vote(vote) - res = client.get(VOTES_ENDPOINT + "?block_id=" + block.id) + res = client.get(VOTES_ENDPOINT + '?block_id=' + block.id) assert vote == res.json[0] assert len(res.json) == 1 assert res.status_code == 200 @@ -41,18 +41,18 @@ def test_get_votes_endpoint_multiple_votes(b, client): vote_invalid = b.vote(block.id, last_block, False) b.write_vote(vote_invalid) - res = client.get(VOTES_ENDPOINT + "?block_id=" + block.id) + res = client.get(VOTES_ENDPOINT + '?block_id=' + block.id) assert len(res.json) == 2 assert res.status_code == 200 @pytest.mark.bdb def test_get_votes_endpoint_returns_empty_list_not_found(client): - res = client.get(VOTES_ENDPOINT + "?block_id=") + res = client.get(VOTES_ENDPOINT + '?block_id=') assert [] == res.json assert res.status_code == 200 - res = client.get(VOTES_ENDPOINT + "?block_id=123") + res = client.get(VOTES_ENDPOINT + '?block_id=123') assert [] == res.json assert res.status_code == 200 @@ -62,8 +62,8 @@ def test_get_votes_endpoint_returns_400_bad_query_params(client): res = client.get(VOTES_ENDPOINT) assert res.status_code == 400 - res = client.get(VOTES_ENDPOINT + "?ts_id=123") + res = client.get(VOTES_ENDPOINT + '?ts_id=123') assert res.status_code == 400 - res = client.get(VOTES_ENDPOINT + "?tx_id=123&block_id=123") + res = client.get(VOTES_ENDPOINT + '?tx_id=123&block_id=123') assert res.status_code == 400 From fe5d966dcad8d983875edb1c5734fde9ba5c7f5d Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Tue, 24 Jan 2017 10:22:32 +0100 Subject: [PATCH 019/155] Put back some strings with wrapped single quotes just to double check that flake8-quotes does indeed tolerate it --- bigchaindb/common/transaction.py | 2 +- tests/web/test_transactions.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index e88ecabe..bda62663 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -118,7 +118,7 @@ class Input(object): fulfillment = Fulfillment.from_uri(data['fulfillment']) except ValueError: # TODO FOR CC: Throw an `InvalidSignature` error in this case. - raise InvalidSignature('Fulfillment URI couldn\'t been parsed') + raise InvalidSignature("Fulfillment URI couldn't been parsed") except TypeError: # NOTE: See comment about this special case in # `Input.to_dict` diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index bc951739..17f976e6 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -97,7 +97,7 @@ def test_post_create_transaction_with_invalid_schema(client, caplog): res = client.post(TX_ENDPOINT, data=json.dumps(tx)) expected_status_code = 400 expected_error_message = ( - 'Invalid transaction schema: \'version\' is a required property') + "Invalid transaction schema: 'version' is a required property") assert res.status_code == expected_status_code assert res.json['message'] == expected_error_message assert caplog.records[0].args['status'] == expected_status_code From 7207f578793134d0703433af5970290eaa26d2a0 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Tue, 24 Jan 2017 10:24:16 +0100 Subject: [PATCH 020/155] Change to single quotes --- bigchaindb/common/transaction.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index bda62663..5e9216da 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -1039,7 +1039,7 @@ class Transaction(object): if tx_body.get('operation') == Transaction.CREATE: if proposed_tx_id != tx_body['asset'].get('id'): - raise InvalidHash("CREATE tx has wrong asset_id") + raise InvalidHash('CREATE tx has wrong asset_id') @classmethod def from_dict(cls, tx): From af23ff5b65a008752a832f824d65dcf7baeb18e2 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 24 Jan 2017 12:08:55 +0100 Subject: [PATCH 021/155] clean up use of double quotes, rename UNSPENTS_ENDPOINT, clarify test --- tests/db/test_bigchain_api.py | 4 ++-- tests/web/test_outputs.py | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index 78c14a28..bd0508de 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1163,8 +1163,8 @@ def test_get_owned_ids_calls_get_outputs_filtered(): from bigchaindb.core import Bigchain with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: b = Bigchain() - res = b.get_owned_ids("abc") - gof.assert_called_once_with("abc", include_spent=False) + res = b.get_owned_ids('abc') + gof.assert_called_once_with('abc', include_spent=False) assert res == gof() diff --git a/tests/web/test_outputs.py b/tests/web/test_outputs.py index 8fb418ea..fd17d46d 100644 --- a/tests/web/test_outputs.py +++ b/tests/web/test_outputs.py @@ -3,40 +3,40 @@ from unittest.mock import MagicMock, patch pytestmark = [pytest.mark.bdb, pytest.mark.usefixtures('inputs')] -UNSPENTS_ENDPOINT = '/api/v1/outputs/' +OUTPUTS_ENDPOINT = '/api/v1/outputs/' def test_get_outputs_endpoint(client, user_pk): m = MagicMock() - m.to_uri.side_effect = lambda s: s + m.to_uri.side_effect = lambda s: 'a%sb' % s with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: gof.return_value = [m, m] - res = client.get(UNSPENTS_ENDPOINT + '?public_key={}'.format(user_pk)) - assert res.json == ["..", ".."] + res = client.get(OUTPUTS_ENDPOINT + '?public_key={}'.format(user_pk)) + assert res.json == ['a..b', 'a..b'] assert res.status_code == 200 gof.assert_called_once_with(user_pk, True) def test_get_outputs_endpoint_unspent(client, user_pk): m = MagicMock() - m.to_uri.side_effect = lambda s: s + m.to_uri.side_effect = lambda s: 'a%sb' % s with patch('bigchaindb.core.Bigchain.get_outputs_filtered') as gof: gof.return_value = [m] params = '?unspent=true&public_key={}'.format(user_pk) - res = client.get(UNSPENTS_ENDPOINT + params) - assert res.json == [".."] + res = client.get(OUTPUTS_ENDPOINT + params) + assert res.json == ['a..b'] assert res.status_code == 200 gof.assert_called_once_with(user_pk, False) def test_get_outputs_endpoint_without_public_key(client): - res = client.get(UNSPENTS_ENDPOINT) + res = client.get(OUTPUTS_ENDPOINT) assert res.status_code == 400 def test_get_outputs_endpoint_with_invalid_public_key(client): expected = {'message': {'public_key': 'Invalid base58 ed25519 key'}} - res = client.get(UNSPENTS_ENDPOINT + '?public_key=abc') + res = client.get(OUTPUTS_ENDPOINT + '?public_key=abc') assert expected == res.json assert res.status_code == 400 @@ -44,6 +44,6 @@ def test_get_outputs_endpoint_with_invalid_public_key(client): def test_get_outputs_endpoint_with_invalid_unspent(client, user_pk): expected = {'message': {'unspent': 'Boolean value must be "true" or "false" (lowercase)'}} params = '?unspent=tru&public_key={}'.format(user_pk) - res = client.get(UNSPENTS_ENDPOINT + params) + res = client.get(OUTPUTS_ENDPOINT + params) assert expected == res.json assert res.status_code == 400 From e3317b370bbeecb9177ce142703dccdd9717b95b Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 24 Jan 2017 12:11:21 +0100 Subject: [PATCH 022/155] don't rename TransactionLink to TL --- tests/db/test_bigchain_api.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index bd0508de..8a2040e8 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1169,22 +1169,24 @@ def test_get_owned_ids_calls_get_outputs_filtered(): def test_get_outputs_filtered_only_unspent(): - from bigchaindb.common.transaction import TransactionLink as TL + from bigchaindb.common.transaction import TransactionLink from bigchaindb.core import Bigchain with patch('bigchaindb.core.Bigchain.get_outputs') as get_outputs: - get_outputs.return_value = [TL('a', 1), TL('b', 2)] + get_outputs.return_value = [TransactionLink('a', 1), + TransactionLink('b', 2)] with patch('bigchaindb.core.Bigchain.get_spent') as get_spent: get_spent.side_effect = [True, False] out = Bigchain().get_outputs_filtered('abc', include_spent=False) get_outputs.assert_called_once_with('abc') - assert out == [TL('b', 2)] + assert out == [TransactionLink('b', 2)] def test_get_outputs_filtered(): - from bigchaindb.common.transaction import TransactionLink as TL + from bigchaindb.common.transaction import TransactionLink from bigchaindb.core import Bigchain with patch('bigchaindb.core.Bigchain.get_outputs') as get_outputs: - get_outputs.return_value = [TL('a', 1), TL('b', 2)] + get_outputs.return_value = [TransactionLink('a', 1), + TransactionLink('b', 2)] with patch('bigchaindb.core.Bigchain.get_spent') as get_spent: out = Bigchain().get_outputs_filtered('abc') get_outputs.assert_called_once_with('abc') From 5683ed5163367cd4bc49fbf7069566f77f762eb4 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 24 Jan 2017 15:59:02 +0100 Subject: [PATCH 023/155] Added mongodb admin commands to add and remove members from the replicaset --- bigchaindb/backend/admin.py | 10 +++++ bigchaindb/backend/mongodb/admin.py | 59 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 bigchaindb/backend/mongodb/admin.py diff --git a/bigchaindb/backend/admin.py b/bigchaindb/backend/admin.py index 057b5995..1a57c8a4 100644 --- a/bigchaindb/backend/admin.py +++ b/bigchaindb/backend/admin.py @@ -20,3 +20,13 @@ def set_shards(connection, *, shards): @singledispatch def set_replicas(connection, *, replicas): raise NotImplementedError + + +@singledispatch +def add_replicas(connection, *, replicas): + raise NotImplementedError + + +@singledispatch +def remove_replicas(connection, *, replicas): + raise NotImplementedError diff --git a/bigchaindb/backend/mongodb/admin.py b/bigchaindb/backend/mongodb/admin.py new file mode 100644 index 00000000..b41021e9 --- /dev/null +++ b/bigchaindb/backend/mongodb/admin.py @@ -0,0 +1,59 @@ +"""Database configuration functions.""" +import logging + +from bigchaindb.backend import admin +from bigchaindb.backend.utils import module_dispatch_registrar +from bigchaindb.backend.mongodb.connection import MongoDBConnection + +logger = logging.getLogger(__name__) + +register_admin = module_dispatch_registrar(admin) + + +@register_admin(MongoDBConnection) +def add_replicas(connection, replicas): + """Add a set of replicas to the replicaset + + Args: + replicas list of strings: of the form "hostname:port". + """ + # get current configuration + conf = connection.conn.admin.command('replSetGetConfig') + + # MongoDB does not automatically add and id for the members so we need + # to chose one that does not exists yet. The safest way is to use + # incrementing ids, so we first check what is the highest id already in + # the set and continue from there. + cur_id = max([member['_id'] for member in conf['config']['members']]) + + # add the nodes to the members list of the replica set + for replica in replicas: + cur_id += 1 + conf['config']['members'].append({'_id': cur_id, 'host': replica}) + + # increase the configuration version number + conf['config']['version'] += 1 + + # apply new configuration + return connection.conn.admin.command('replSetReconfig', conf['config']) + + +@register_admin(MongoDBConnection) +def remove_replicas(connection, replicas): + """Remove a set of replicas from the replicaset + + """ + # get the current configuration + conf = connection.conn.admin.command('replSetGetConfig') + + # remove the nodes from the members list in the replica set + conf['config']['members'] = list( + filter(lambda member: member['host'] not in replicas, + conf['config']['members']) + ) + + # increase the configuration version number + conf['config']['version'] += 1 + + # apply new configuration + return connection.conn.admin.command('replSetReconfig', conf['config']) From 69505a366baf76db045ac9e61f9723b1a95ae714 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 24 Jan 2017 17:55:06 +0100 Subject: [PATCH 024/155] Added bigchaindb commands to add and remove nodes from replicaset --- bigchaindb/backend/admin.py | 4 +- bigchaindb/backend/mongodb/__init__.py | 2 +- bigchaindb/backend/mongodb/admin.py | 13 +++++- bigchaindb/commands/bigchain.py | 55 +++++++++++++++++++++++++- bigchaindb/commands/utils.py | 31 ++++++++++++++- 5 files changed, 98 insertions(+), 7 deletions(-) diff --git a/bigchaindb/backend/admin.py b/bigchaindb/backend/admin.py index 1a57c8a4..da54397b 100644 --- a/bigchaindb/backend/admin.py +++ b/bigchaindb/backend/admin.py @@ -23,10 +23,10 @@ def set_replicas(connection, *, replicas): @singledispatch -def add_replicas(connection, *, replicas): +def add_replicas(connection, replicas): raise NotImplementedError @singledispatch -def remove_replicas(connection, *, replicas): +def remove_replicas(connection, replicas): raise NotImplementedError diff --git a/bigchaindb/backend/mongodb/__init__.py b/bigchaindb/backend/mongodb/__init__.py index af5293ac..e3746fa3 100644 --- a/bigchaindb/backend/mongodb/__init__.py +++ b/bigchaindb/backend/mongodb/__init__.py @@ -16,7 +16,7 @@ generic backend interfaces to the implementations in this module. """ # Register the single dispatched modules on import. -from bigchaindb.backend.mongodb import schema, query, changefeed # noqa +from bigchaindb.backend.mongodb import admin, schema, query, changefeed # noqa # MongoDBConnection should always be accessed via # ``bigchaindb.backend.connect()``. diff --git a/bigchaindb/backend/mongodb/admin.py b/bigchaindb/backend/mongodb/admin.py index b41021e9..3c2001d5 100644 --- a/bigchaindb/backend/mongodb/admin.py +++ b/bigchaindb/backend/mongodb/admin.py @@ -1,8 +1,11 @@ """Database configuration functions.""" import logging +from pymongo.errors import OperationFailure + from bigchaindb.backend import admin from bigchaindb.backend.utils import module_dispatch_registrar +from bigchaindb.backend.exceptions import DatabaseOpFailedError from bigchaindb.backend.mongodb.connection import MongoDBConnection logger = logging.getLogger(__name__) @@ -35,7 +38,10 @@ def add_replicas(connection, replicas): conf['config']['version'] += 1 # apply new configuration - return connection.conn.admin.command('replSetReconfig', conf['config']) + try: + return connection.conn.admin.command('replSetReconfig', conf['config']) + except OperationFailure as exc: + raise DatabaseOpFailedError(exc.details['errmsg']) @register_admin(MongoDBConnection) @@ -56,4 +62,7 @@ def remove_replicas(connection, replicas): conf['config']['version'] += 1 # apply new configuration - return connection.conn.admin.command('replSetReconfig', conf['config']) + try: + return connection.conn.admin.command('replSetReconfig', conf['config']) + except OperationFailure as exc: + raise DatabaseOpFailedError(exc.details['errmsg']) diff --git a/bigchaindb/commands/bigchain.py b/bigchaindb/commands/bigchain.py index 2fc8df70..78b3b745 100644 --- a/bigchaindb/commands/bigchain.py +++ b/bigchaindb/commands/bigchain.py @@ -22,7 +22,8 @@ from bigchaindb.models import Transaction from bigchaindb.utils import ProcessGroup from bigchaindb import backend from bigchaindb.backend import schema -from bigchaindb.backend.admin import set_replicas, set_shards +from bigchaindb.backend.admin import (set_replicas, set_shards, add_replicas, + remove_replicas) from bigchaindb.backend.exceptions import DatabaseOpFailedError from bigchaindb.commands import utils from bigchaindb import processes @@ -269,6 +270,32 @@ def run_set_replicas(args): logger.warn(e) +def run_add_replicas(args): + # Note: This command is specific to MongoDB + bigchaindb.config_utils.autoconfigure(filename=args.config, force=True) + conn = backend.connect() + + try: + add_replicas(conn, args.replicas) + except DatabaseOpFailedError as e: + logger.warn(e) + else: + logger.info('Added {} to the replicaset.'.format(args.replicas)) + + +def run_remove_replicas(args): + # Note: This command is specific to MongoDB + bigchaindb.config_utils.autoconfigure(filename=args.config, force=True) + conn = backend.connect() + + try: + remove_replicas(conn, args.replicas) + except DatabaseOpFailedError as e: + logger.warn(e) + else: + logger.info('Removed {} from the replicaset.'.format(args.replicas)) + + def create_parser(): parser = argparse.ArgumentParser( description='Control your BigchainDB node.', @@ -334,6 +361,32 @@ def create_parser(): type=int, default=1, help='Number of replicas (i.e. the replication factor)') + # parser for adding nodes to the replica set + add_replicas_parser = subparsers.add_parser('add-replicas', + help='Add a set of nodes to the ' + 'replica set. This command ' + 'is specific to the MongoDB' + ' backend.') + + add_replicas_parser.add_argument('replicas', nargs='+', + type=utils.mongodb_host, + help='A list of space separated hosts to ' + 'add to the replicaset. Each host ' + 'should be in the form `host:port`.') + + # parser for removing nodes from the replica set + rm_replicas_parser = subparsers.add_parser('remove-replicas', + help='Remove a set of nodes from the ' + 'replica set. This command ' + 'is specific to the MongoDB' + ' backend.') + + rm_replicas_parser.add_argument('replicas', nargs='+', + type=utils.mongodb_host, + help='A list of space separated hosts to ' + 'remove from the replicaset. Each host ' + 'should be in the form `host:port`.') + load_parser = subparsers.add_parser('load', help='Write transactions to the backlog') diff --git a/bigchaindb/commands/utils.py b/bigchaindb/commands/utils.py index 510eb2f6..7b662308 100644 --- a/bigchaindb/commands/utils.py +++ b/bigchaindb/commands/utils.py @@ -3,14 +3,15 @@ for ``argparse.ArgumentParser``. """ import argparse -from bigchaindb.common.exceptions import StartupError import multiprocessing as mp import subprocess import rethinkdb as r +from pymongo import uri_parser import bigchaindb from bigchaindb import backend +from bigchaindb.common.exceptions import StartupError from bigchaindb.version import __version__ @@ -95,6 +96,34 @@ def start(parser, argv, scope): return func(args) +def mongodb_host(host): + """Utility function that works as a type for mongodb ``host`` args. + + This function validates the ``host`` args provided by to the + ``add-replicas`` and ``remove-replicas`` commands and checks if each arg + is in the form "host:port" + + Args: + host (str): A string containing hostname and port (e.g. "host:port") + + Raises: + ArgumentTypeError: if it fails to parse the argument + """ + # check if mongodb can parse the host + try: + hostname, port = uri_parser.parse_host(host, default_port=None) + except ValueError as exc: + raise argparse.ArgumentTypeError(exc.args[0]) + + # we do require the port to be provided. + if port is None: + raise argparse.ArgumentTypeError('expected host in the form ' + '`host:port`. Got `{}` instead.' + .format(host)) + + return host + + base_parser = argparse.ArgumentParser(add_help=False, prog='bigchaindb') base_parser.add_argument('-c', '--config', From f15a7f7e8b593c39c40922e9d90b4fa265da90dc Mon Sep 17 00:00:00 2001 From: tim Date: Tue, 15 Nov 2016 14:43:30 +0100 Subject: [PATCH 025/155] Document conditions endpoint --- .../http-client-server-api.rst | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 969d912b..2d8fe0fd 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -123,6 +123,55 @@ GET /transactions/{tx_id} :statuscode 404: A transaction with that ID was not found. +GET /transactions/{tx_id}/conditions/{cid} +------------------------- + +.. http:get:: /transactions/{tx_id}/conditions/{cid} + + Returns the condition with index ``cid`` from a transaction with ID + ``txid``. + + If either a transaction with ID ``txid`` isn't found or the condition + requested at the index ``cid`` is not found, this endpoint will return a + ``400 Bad Request``. + + :param tx_id: transaction ID + :type tx_id: hex string + + :param cid: A condition's index in the transaction + :type cid: integer + + **Example request**: + + .. sourcecode:: http + + GET /transactions/2d431...0b4b0e/conditions/0 HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + } + } + } + + :statuscode 200: A condition with ``cid`` was found in a transaction with ID ``tx_id``. + :statuscode 400: Either a transaction with ``tx_id`` or a condition with ``cid`` wasn't found. + + GET /unspents/ ------------------------- From 1086c3a5c4b46e8576b45849900fc373cbdf406a Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 12:01:57 +0100 Subject: [PATCH 026/155] POST /transactions status code to 202 According to https://www.ietf.org/rfc/rfc2616.txt a 201 Created status code MUST only be returned when: "The origin server MUST create the resource before returning the 201 status code." hence, a 202 Accepted's definition is more appropriate: "The request has been accepted for processing, but the processing has not been completed. The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled." --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 2d8fe0fd..590d788d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -64,7 +64,7 @@ POST /transactions/ .. literalinclude:: samples/post-tx-response.http :language: http - :statuscode 201: A new transaction was created. + :statuscode 202: The pushed transaction was accepted, but the processing has not been completed. :statuscode 400: The transaction was invalid and not created. From 71d3c70fdae1a471a9ea43ecefb351b54146dff7 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 12:08:06 +0100 Subject: [PATCH 027/155] Status --> Statuses Usage of singular resource names is discouraged in REST: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api The plural of status is statuses: http://english.stackexchange.com/questions/877/what-is-the-plural-form-of-status --- .../source/drivers-clients/http-client-server-api.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 590d788d..5affaa44 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -68,12 +68,12 @@ POST /transactions/ :statuscode 400: The transaction was invalid and not created. -GET /transactions/{tx_id}/status +GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e -------------------------------- -.. http:get:: /transactions/{tx_id}/status +.. http:get:: /statuses/{tx_id}/ - Get the status of the transaction with the ID ``tx_id``, if a transaction + Get the status of a transaction with the ID ``tx_id``, if a transaction with that ``tx_id`` exists. The possible status values are ``backlog``, ``undecided``, ``valid`` or From 5789a37664746bd634fb8e5cc1fa3f716fdc7527 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 12:16:27 +0100 Subject: [PATCH 028/155] Allow /statuses to return a 303 See Other response. According to: https://www.ietf.org/rfc/rfc2616.txt a 303 See Other can be returned to indicate that the resource the user is looking for can be found under a new path. In the case of a transaction including the `status == 'valid'`, we return 303 See Other, as well as a Location header to the /transactions endpoint. "The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource." --- .../source/drivers-clients/http-client-server-api.rst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 5affaa44..d39eedfa 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -71,7 +71,7 @@ POST /transactions/ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e -------------------------------- -.. http:get:: /statuses/{tx_id}/ +.. http:get:: /statuses/{tx_id} Get the status of a transaction with the ID ``tx_id``, if a transaction with that ``tx_id`` exists. @@ -79,6 +79,10 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. + If a transaction is persisted to the chain and it's status is set to + ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as + well as a URL to the resource in the location header. + :param tx_id: transaction ID :type tx_id: hex string @@ -92,7 +96,8 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e .. literalinclude:: samples/get-tx-status-response.http :language: http - :statuscode 200: A transaction with that ID was found and the status is returned. + :statuscode 200: A transaction with that ID was found. The status is either ``backlog``, ``invalid``. + :statuscode 303: A transaction with that ID was found and persisted to the chain. A location header to the resource is provided. :statuscode 404: A transaction with that ID was not found. From b4889973535c10584e766fcd0f860ba4174f8554 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 12:23:54 +0100 Subject: [PATCH 029/155] tx_id --> txid --- .../http-client-server-api.rst | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index d39eedfa..3f100463 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -71,10 +71,10 @@ POST /transactions/ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e -------------------------------- -.. http:get:: /statuses/{tx_id} +.. http:get:: /statuses/{txid} - Get the status of a transaction with the ID ``tx_id``, if a transaction - with that ``tx_id`` exists. + Get the status of a transaction with the ID ``txid``, if a transaction + with that ``txid`` exists. The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. @@ -83,8 +83,8 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as well as a URL to the resource in the location header. - :param tx_id: transaction ID - :type tx_id: hex string + :param txid: transaction ID + :type txid: hex string **Example request**: @@ -101,18 +101,18 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e :statuscode 404: A transaction with that ID was not found. -GET /transactions/{tx_id} +GET /transactions/{txid} ------------------------- -.. http:get:: /transactions/{tx_id} +.. http:get:: /transactions/{txid} - Get the transaction with the ID ``tx_id``. + Get the transaction with the ID ``txid``. This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. - :param tx_id: transaction ID - :type tx_id: hex string + :param txid: transaction ID + :type txid: hex string **Example request**: @@ -128,10 +128,10 @@ GET /transactions/{tx_id} :statuscode 404: A transaction with that ID was not found. -GET /transactions/{tx_id}/conditions/{cid} +GET /transactions/{txid}/conditions/{cid} ------------------------- -.. http:get:: /transactions/{tx_id}/conditions/{cid} +.. http:get:: /transactions/{txid}/conditions/{cid} Returns the condition with index ``cid`` from a transaction with ID ``txid``. @@ -140,8 +140,8 @@ GET /transactions/{tx_id}/conditions/{cid} requested at the index ``cid`` is not found, this endpoint will return a ``400 Bad Request``. - :param tx_id: transaction ID - :type tx_id: hex string + :param txid: transaction ID + :type txid: hex string :param cid: A condition's index in the transaction :type cid: integer @@ -173,8 +173,8 @@ GET /transactions/{tx_id}/conditions/{cid} } } - :statuscode 200: A condition with ``cid`` was found in a transaction with ID ``tx_id``. - :statuscode 400: Either a transaction with ``tx_id`` or a condition with ``cid`` wasn't found. + :statuscode 200: A condition with ``cid`` was found in a transaction with ID ``txid``. + :statuscode 400: Either a transaction with ``txid`` or a condition with ``cid`` wasn't found. GET /unspents/ From 0dc9b46ea735fd1e56b05a3e215e9940a6069f56 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 13:20:54 +0100 Subject: [PATCH 030/155] Structural changes to the document - Remove /unspents/ and replace with endpoint under /transactions - Remove /transactions/txid/conditions/cid endpoint --- .../http-client-server-api.rst | 202 ++++++------------ 1 file changed, 69 insertions(+), 133 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 3f100463..d5a7a61f 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -101,6 +101,75 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e :statuscode 404: A transaction with that ID was not found. +GET /transactions +------------------------- + +.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_after={owner_after} + + Get a list of transactions with unfulfilled conditions (conditions that have + not been used yet in a persisted transaction. + + If the querystring ``fulfilled`` is set to ``false`` and all conditions for + ``owner_after`` happen to be fulfilled already, this endpoint will return + an empty list. + + + .. note:: + + This endpoint will return a ``HTTP 400 Bad Request`` if the querystring + ``owner_after`` happens to not be defined in the request. + + :param fields: The fields to be included in a transaction. + :type fields: string + + :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :type fields: boolean + + :param owner_after: A public key, able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :type owner_after: base58 encoded string + + **Example request**: + + .. sourcecode:: http + + GET /transactions?fields=id,conditions&fulfilled=false&owner_after=1AAAbbb...ccc HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [{ + "transaction": { + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "1AAAbbb...ccc" + } + }, + "amount": 1, + "owners_after": [ + "1AAAbbb...ccc" + ] + } + ], + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + }, ...] + + + :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. the ``owner_after`` querystring was not included in the request. + GET /transactions/{txid} ------------------------- @@ -126,136 +195,3 @@ GET /transactions/{txid} :statuscode 200: A transaction with that ID was found. :statuscode 404: A transaction with that ID was not found. - - -GET /transactions/{txid}/conditions/{cid} -------------------------- - -.. http:get:: /transactions/{txid}/conditions/{cid} - - Returns the condition with index ``cid`` from a transaction with ID - ``txid``. - - If either a transaction with ID ``txid`` isn't found or the condition - requested at the index ``cid`` is not found, this endpoint will return a - ``400 Bad Request``. - - :param txid: transaction ID - :type txid: hex string - - :param cid: A condition's index in the transaction - :type cid: integer - - **Example request**: - - .. sourcecode:: http - - GET /transactions/2d431...0b4b0e/conditions/0 HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - } - } - } - - :statuscode 200: A condition with ``cid`` was found in a transaction with ID ``txid``. - :statuscode 400: Either a transaction with ``txid`` or a condition with ``cid`` wasn't found. - - -GET /unspents/ -------------------------- - -.. note:: - - This endpoint (unspents) is not yet implemented. We published it here for preview and comment. - - -.. http:get:: /unspents?owner_after={owner_after} - - Get a list of links to transactions' outputs that have not been used in - a previous transaction and could hence be called unspent outputs - (or simply: unspents). - - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``owner_after`` happens to not be defined in the request. - - Note that if unspents for a certain ``public_key`` have not been found by - the server, this will result in the server returning a 200 OK HTTP status - code and an empty list in the response's body. - - :param owner_after: A public key, able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :type owner_after: base58 encoded string - - **Example request**: - - .. sourcecode:: http - - GET /unspents?owner_after=1AAAbbb...ccc HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [ - "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/0", - "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/1" - ] - - :statuscode 200: A list of outputs were found and returned in the body of the response. - :statuscode 400: The request wasn't understood by the server, e.g. the ``owner_after`` querystring was not included in the request. - - -Determining the API Root URL ----------------------------- - -When you start BigchainDB Server using ``bigchaindb start``, -an HTTP API is exposed at some address. The default is: - -`http://localhost:9984/api/v1/ `_ - -It's bound to ``localhost``, -so you can access it from the same machine, -but it won't be directly accessible from the outside world. -(The outside world could connect via a SOCKS proxy or whatnot.) - -The documentation about BigchainDB Server :any:`Configuration Settings` -has a section about how to set ``server.bind`` so as to make -the HTTP API publicly accessible. - -If the API endpoint is publicly accessible, -then the public API Root URL is determined as follows: - -- The public IP address (like 12.34.56.78) - is the public IP address of the machine exposing - the HTTP API to the public internet (e.g. either the machine hosting - Gunicorn or the machine running the reverse proxy such as Nginx). - It's determined by AWS, Azure, Rackspace, or whoever is hosting the machine. - -- The DNS hostname (like apihosting4u.net) is determined by DNS records, - such as an "A Record" associating apihosting4u.net with 12.34.56.78 - -- The port (like 9984) is determined by the ``server.bind`` setting - if Gunicorn is exposed directly to the public Internet. - If a reverse proxy (like Nginx) is exposed directly to the public Internet - instead, then it could expose the HTTP API on whatever port it wants to. - (It should expose the HTTP API on port 9984, but it's not bound to do - that by anything other than convention.) From e243a1be9b556eda9d8cec69f956b23c40d430ce Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 13:47:51 +0100 Subject: [PATCH 031/155] Use sphinx note for note in document --- .../drivers-clients/http-client-server-api.rst | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index d5a7a61f..b82e0169 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -47,12 +47,13 @@ POST /transactions/ Push a new transaction. - Note: The posted transaction should be a valid and signed :doc:`transaction <../data-models/transaction-model>`. - The steps to build a valid transaction are beyond the scope of this page. - One would normally use a driver such as the `BigchainDB Python Driver - `_ to - build a valid transaction. The exact contents of a valid transaction depend - on the associated public/private keypairs. + .. note:: + The posted transaction should be valid `transaction + `_. + The steps to build a valid transaction are beyond the scope of this page. + One would normally use a driver such as the `BigchainDB Python Driver + `_ + to build a valid transaction. **Example request**: From 85d9553a1e6f0ee6c9cdbe59e15a5e16236e0e43 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 13:48:14 +0100 Subject: [PATCH 032/155] owner_after --> owners_after Querystring keywords should be in line with data model. --- .../http-client-server-api.rst | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index b82e0169..9fd4fdca 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -69,7 +69,7 @@ POST /transactions/ :statuscode 400: The transaction was invalid and not created. -GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e +GET /statuses -------------------------------- .. http:get:: /statuses/{txid} @@ -105,35 +105,32 @@ GET /statuses/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e GET /transactions ------------------------- -.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_after={owner_after} +.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} Get a list of transactions with unfulfilled conditions (conditions that have not been used yet in a persisted transaction. If the querystring ``fulfilled`` is set to ``false`` and all conditions for - ``owner_after`` happen to be fulfilled already, this endpoint will return + ``owners_after`` happen to be fulfilled already, this endpoint will return an empty list. - - .. note:: - - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``owner_after`` happens to not be defined in the request. + This endpoint will return a ``HTTP 400 Bad Request`` if the querystring + ``owners_after`` happens to not be defined in the request. :param fields: The fields to be included in a transaction. :type fields: string :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :type fields: boolean + :type fulfilled: boolean - :param owner_after: A public key, able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :type owner_after: base58 encoded string + :param owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :type owners_after: base58 encoded string **Example request**: .. sourcecode:: http - GET /transactions?fields=id,conditions&fulfilled=false&owner_after=1AAAbbb...ccc HTTP/1.1 + GET /transactions?fields=id,conditions&fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: @@ -165,11 +162,10 @@ GET /transactions } ], "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - }, ...] - + }] :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``owner_after`` querystring was not included in the request. + :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. GET /transactions/{txid} ------------------------- From 9766332b8bb58eacab89b789c58ff10cca9b043c Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 14:05:54 +0100 Subject: [PATCH 033/155] Restructure doc: Endpoints as roots --- .../http-client-server-api.rst | 118 +++++++++++++----- 1 file changed, 84 insertions(+), 34 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 9fd4fdca..a5d4ab30 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -39,10 +39,86 @@ with something like the following in the body: "version": "0.6.0" } - -POST /transactions/ +Transactions ------------------- +.. http:get:: /transactions/{txid} + + Get the transaction with the ID ``txid``. + + This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` + block on ``bigchain``, if exists. + + :param txid: transaction ID + :type txid: hex string + + **Example request**: + + .. sourcecode:: http + + GET /transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "transaction": { + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + } + }, + "amount": 1, + "owners_after": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ], + "operation": "CREATE", + "asset": { + "divisible": false, + "updatable": false, + "data": null, + "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", + "refillable": false + }, + "metadata": null, + "timestamp": "1477578978", + "fulfillments": [ + { + "fid": 0, + "input": null, + "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", + "owners_before": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ] + }, + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + "version": 1 + } + + :statuscode 200: A transaction with that ID was found. + :statuscode 404: A transaction with that ID was not found. + +.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} + + is an `alias for retrieving unfulfilled conditions for a set of public keys. <#get--conditions?fulfilled=false&owner_afters=owners_after>`_ + .. http:post:: /transactions/ Push a new transaction. @@ -69,7 +145,7 @@ POST /transactions/ :statuscode 400: The transaction was invalid and not created. -GET /statuses +Statuses -------------------------------- .. http:get:: /statuses/{txid} @@ -102,10 +178,10 @@ GET /statuses :statuscode 404: A transaction with that ID was not found. -GET /transactions +Conditions ------------------------- -.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} +.. http:get:: /conditions?fulfilled=false&owner_afters={owners_after} Get a list of transactions with unfulfilled conditions (conditions that have not been used yet in a persisted transaction. @@ -117,8 +193,8 @@ GET /transactions This endpoint will return a ``HTTP 400 Bad Request`` if the querystring ``owners_after`` happens to not be defined in the request. - :param fields: The fields to be included in a transaction. - :type fields: string + This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` + block on ``bigchain``, if exists. :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. :type fulfilled: boolean @@ -130,7 +206,7 @@ GET /transactions .. sourcecode:: http - GET /transactions?fields=id,conditions&fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 + GET /conditions?fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: @@ -166,29 +242,3 @@ GET /transactions :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. - -GET /transactions/{txid} -------------------------- - -.. http:get:: /transactions/{txid} - - Get the transaction with the ID ``txid``. - - This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` - block on ``bigchain``, if exists. - - :param txid: transaction ID - :type txid: hex string - - **Example request**: - - .. literalinclude:: samples/get-tx-request.http - :language: http - - **Example response**: - - .. literalinclude:: samples/get-tx-response.http - :language: http - - :statuscode 200: A transaction with that ID was found. - :statuscode 404: A transaction with that ID was not found. From 156bf4fb2144e81956d60709aa5653f460630444 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 14:26:30 +0100 Subject: [PATCH 034/155] txid --> id KISS: A transaction is a resource as every other. Let's not give it a special id (like 'txid'), but simply a regular id. --- .../drivers-clients/http-client-server-api.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index a5d4ab30..323a0889 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -42,15 +42,15 @@ with something like the following in the body: Transactions ------------------- -.. http:get:: /transactions/{txid} +.. http:get:: /transactions/{id} - Get the transaction with the ID ``txid``. + Get the transaction with the ID ``id``. This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. - :param txid: transaction ID - :type txid: hex string + :param id: transaction ID + :type id: hex string **Example request**: @@ -148,10 +148,10 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses/{txid} +.. http:get:: /statuses/{id} - Get the status of a transaction with the ID ``txid``, if a transaction - with that ``txid`` exists. + Get the status of a transaction with the ID ``id``, if a transaction + with that ``id`` exists. The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. @@ -160,8 +160,8 @@ Statuses ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as well as a URL to the resource in the location header. - :param txid: transaction ID - :type txid: hex string + :param id: transaction ID + :type id: hex string **Example request**: From 90aff0e202f6c609a8ab4cdc8ba2f0d12ffa802c Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 14:45:29 +0100 Subject: [PATCH 035/155] Give up /conditions endpoint A transaction contains: - conditions - fulfillments - assets - meta data While: - assets; and - meta data could be viewed as their own "tables" or resources, conditions and fulfillments cannot. Why? Because in comparison they do not contain a primary key, allowing them to be queried by it. --- .../http-client-server-api.rst | 129 +++++++++--------- 1 file changed, 62 insertions(+), 67 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 323a0889..3bfddb4a 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -117,7 +117,68 @@ Transactions .. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} - is an `alias for retrieving unfulfilled conditions for a set of public keys. <#get--conditions?fulfilled=false&owner_afters=owners_after>`_ + Get a list of transactions with unfulfilled conditions. + + If the querystring ``fulfilled`` is set to ``false`` and all conditions for + ``owners_after`` happen to be fulfilled already, this endpoint will return + an empty list. + + This endpoint will return a ``HTTP 400 Bad Request`` if the querystring + ``owners_after`` happens to not be defined in the request. + + This endpoint returns conditions only if the transaction they're in are + included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + + :param fields: A comma separated string to expand properties on the transaction object to be returned. + :type fields: string + + :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :type fulfilled: boolean + + :param owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :type owners_after: base58 encoded string + + **Example request**: + + .. sourcecode:: http + + GET /transactions?fields=id,conditions&fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [{ + "transaction": { + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "1AAAbbb...ccc" + } + }, + "amount": 1, + "owners_after": [ + "1AAAbbb...ccc" + ] + } + ], + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + }] + + :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. + .. http:post:: /transactions/ @@ -176,69 +237,3 @@ Statuses :statuscode 200: A transaction with that ID was found. The status is either ``backlog``, ``invalid``. :statuscode 303: A transaction with that ID was found and persisted to the chain. A location header to the resource is provided. :statuscode 404: A transaction with that ID was not found. - - -Conditions -------------------------- - -.. http:get:: /conditions?fulfilled=false&owner_afters={owners_after} - - Get a list of transactions with unfulfilled conditions (conditions that have - not been used yet in a persisted transaction. - - If the querystring ``fulfilled`` is set to ``false`` and all conditions for - ``owners_after`` happen to be fulfilled already, this endpoint will return - an empty list. - - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``owners_after`` happens to not be defined in the request. - - This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` - block on ``bigchain``, if exists. - - :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :type fulfilled: boolean - - :param owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :type owners_after: base58 encoded string - - **Example request**: - - .. sourcecode:: http - - GET /conditions?fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [{ - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "1AAAbbb...ccc" - } - }, - "amount": 1, - "owners_after": [ - "1AAAbbb...ccc" - ] - } - ], - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - }] - - :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. From 58d0b771cb66663e21ee6d1c0ac094a6bfcb5b92 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 14:58:44 +0100 Subject: [PATCH 036/155] id --> resource_id Inevitably, some resources will not allow to filter by the exact keyword that is included in a resources body. Take for example asset and metadata. They both have a property called 'id', hence requests of a form: /transactions&fields=x,y&property_name=z might now be allowed to be resolved as the keyword 'id' in this case could reference both 'metadata.id' and 'asset.id'. This problem cannot be structurally resolved with URL paths. Hence it was decided to emphasize on a few resources that implement 'id' as a sort-of primary key. --- .../drivers-clients/http-client-server-api.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 3bfddb4a..c403d1ec 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -42,15 +42,15 @@ with something like the following in the body: Transactions ------------------- -.. http:get:: /transactions/{id} +.. http:get:: /transactions/{tx_id} - Get the transaction with the ID ``id``. + Get the transaction with the ID ``tx_id``. This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. - :param id: transaction ID - :type id: hex string + :param tx_id: transaction ID + :type tx_id: hex string **Example request**: @@ -209,10 +209,10 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses/{id} +.. http:get:: /statuses/{tx_id} - Get the status of a transaction with the ID ``id``, if a transaction - with that ``id`` exists. + Get the status of a transaction with the ID ``tx_id``, if a transaction + with that ``tx_id`` exists. The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. @@ -221,8 +221,8 @@ Statuses ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as well as a URL to the resource in the location header. - :param id: transaction ID - :type id: hex string + :param tx_id: transaction ID + :type tx_id: hex string **Example request**: From 748e15537856df93179a6555a1d31f24674d3cef Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 15:41:26 +0100 Subject: [PATCH 037/155] Get block status using /statuses --- .../http-client-server-api.rst | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index c403d1ec..69b8b7a3 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -209,21 +209,25 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses/{tx_id} +.. http:get:: /statuses/{tx_id | block_id} - Get the status of a transaction with the ID ``tx_id``, if a transaction - with that ``tx_id`` exists. + Get the status of an asynchronously written resource by their id. + Supports the retrieval of a status for a transaction using ``tx_id`` or the + retrieval of a status for a block using ``block_id``. The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. - If a transaction is persisted to the chain and it's status is set to + If a transaction or block is persisted to the chain and it's status is set to ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as - well as a URL to the resource in the location header. + well as an URL to the resource in the location header. :param tx_id: transaction ID :type tx_id: hex string + :param block_id: block ID + :type block_id: hex string + **Example request**: .. literalinclude:: samples/get-tx-status-request.http @@ -234,6 +238,6 @@ Statuses .. literalinclude:: samples/get-tx-status-response.http :language: http - :statuscode 200: A transaction with that ID was found. The status is either ``backlog``, ``invalid``. - :statuscode 303: A transaction with that ID was found and persisted to the chain. A location header to the resource is provided. - :statuscode 404: A transaction with that ID was not found. + :statuscode 200: A transaction or block with that ID was found. The status is either ``backlog``, ``invalid``. + :statuscode 303: A transaction or block with that ID was found and persisted to the chain. A location header to the resource is provided. + :statuscode 404: A transaction or block with that ID was not found. From ee904d78f4df97e46c3aba5bc9fe87be2ade57c5 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:01:16 +0100 Subject: [PATCH 038/155] Add transactions by asset id endpoint --- .../http-client-server-api.rst | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 69b8b7a3..abdff476 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -179,8 +179,58 @@ Transactions :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. +.. http:get:: /transactions?fields=id,asset,operation&operation={CREATE|TRANSFER}&asset_id={asset_id} -.. http:post:: /transactions/ + Get a list of transactions that use an asset with the ID ``asset_id``. + + This endpoint will return a ``HTTP 400 Bad Request`` if the querystring + ``asset_id`` happens to not be defined in the request. + + ``operation`` can either be ``GENESIS``, ``CREATE`` or ``TRANSFER``. + + This endpoint returns assets only if the transaction they're in are + included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + + :param fields: A comma separated string to expand properties on the transaction object to be returned. + :type fields: string + + :param operation: One of the three supported operations of a transaction. + :type operation: string + + :param asset_id: asset ID. + :type asset_id: uuidv4 + + **Example request**: + + .. sourcecode:: http + + GET /transactions?fields=id,asset,operation&operation=CREATE&asset_id=1AAAbbb...ccc HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [{ + "transaction": { + "asset": { + "divisible": false, + "updatable": false, + "data": null, + "id": "1AAAbbb...ccc", + "refillable": false + }, + "operation": "CREATE", + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + }] + + :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. + +.. http:post:: /transactions Push a new transaction. From 0a06547c1b34a6e50dd7162656f0eab2c2879367 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:19:53 +0100 Subject: [PATCH 039/155] Add transactions by metadata id endpoint --- .../http-client-server-api.rst | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index abdff476..eb906f27 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -230,6 +230,49 @@ Transactions :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. +.. http:get:: /transactions?fields=id,metadata&metadata_id={metadata_id} + + Get a list of transactions that use metadata with the ID ``metadata_id``. + + This endpoint will return a ``HTTP 400 Bad Request`` if the querystring + ``metadata_id`` happens to not be defined in the request. + + This endpoint returns assets only if the transaction they're in are + included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + + :param fields: A comma separated string to expand properties on the transaction object to be returned. + :type fields: string + + :param metadata_id: metadata ID. + :type metadata_id: uuidv4 + + **Example request**: + + .. sourcecode:: http + + GET /transactions?fields=id,metadata&metadata_id=1AAAbbb...ccc HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [{ + "transaction": { + "metadata": { + "id": "1AAAbbb...ccc", + "data": { + "hello": "world" + }, + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + }] + + :statuscode 200: A list of transaction's containing metadata with ID ``metadata_id`` was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. the ``metadata_id`` querystring was not included in the request. + .. http:post:: /transactions Push a new transaction. From f18f3cb8d20541fd16f07371cf2e805e8e3b38ac Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:26:40 +0100 Subject: [PATCH 040/155] Add sections to be done --- .../http-client-server-api.rst | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index eb906f27..1a300b55 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -334,3 +334,33 @@ Statuses :statuscode 200: A transaction or block with that ID was found. The status is either ``backlog``, ``invalid``. :statuscode 303: A transaction or block with that ID was found and persisted to the chain. A location header to the resource is provided. :statuscode 404: A transaction or block with that ID was not found. + + +Assets +-------------------------------- + +.. http:get:: /assets/{asset_id} + + Descriptions: TODO + + +Metadata +-------------------------------- + +.. http:get:: /metadata/{metadata_id} + + +Blocks +-------------------------------- + +.. http:get:: /blocks/{block_id} + + Descriptions: TODO + + +Votes +-------------------------------- + +.. http:get:: /votes?block_id={block_id} + + Descriptions: TODO From eda8cdbba192d261d45968750400c2df76bbe452 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:40:08 +0100 Subject: [PATCH 041/155] Add docs about /transactions endpoint --- .../http-client-server-api.rst | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 1a300b55..c8970926 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -115,6 +115,46 @@ Transactions :statuscode 200: A transaction with that ID was found. :statuscode 404: A transaction with that ID was not found. +.. http:get:: /transactions + + The current ``/transactions`` endpoint returns a ``404 Not Found`` HTTP + status code. Eventually, this functionality will get implemented. + We believe a PUSH rather than a PULL pattern is more appropriate, as the + items returned in the collection would change by the second. + + There are however requests that might come of use, given the endpoint is + queried correctly. Some of them include retrieving a list of transactions + that include: + + * `Unfulfilled conditions <#get--transactions?fields=id,conditions&fulfilled=false&owner_afters=owners_after>`_ + * `A specific asset <#get--transactions?fields=id,asset,operation&operation=CREATE|TRANSFER&asset_id=asset_id>`_ + * `Specific metadata <#get--transactions?fields=id,metadata&metadata_id=metadata_id>`_ + + In this section, we've listed those particular requests, as they will likely + to be very handy when implementing your application on top of BigchainDB. + A generalization of those parameters can follows: + + :query fields: A comma separated string to expand properties on the transaction object to be returned. + :type fields: string + + :query fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :type fulfilled: boolean + + :query owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :type owners_after: base58 encoded string + + :query operation: One of the three supported operations of a transaction. + :type operation: string + + :query asset_id: asset ID. + :type asset_id: uuidv4 + + :query metadata_id: metadata ID. + :type metadata_id: uuidv4 + + :statuscode 404: BigchainDB does not expose this endpoint. + + .. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} Get a list of transactions with unfulfilled conditions. From 152f151f23f79723aff35b0670e9a68fab006954 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:42:09 +0100 Subject: [PATCH 042/155] :param _: --> :query _: --- .../drivers-clients/http-client-server-api.rst | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index c8970926..9a7a5c74 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -169,13 +169,13 @@ Transactions This endpoint returns conditions only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :param fields: A comma separated string to expand properties on the transaction object to be returned. + :query fields: A comma separated string to expand properties on the transaction object to be returned. :type fields: string - :param fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :query fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. :type fulfilled: boolean - :param owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :query owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. :type owners_after: base58 encoded string **Example request**: @@ -231,13 +231,13 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :param fields: A comma separated string to expand properties on the transaction object to be returned. + :query fields: A comma separated string to expand properties on the transaction object to be returned. :type fields: string - :param operation: One of the three supported operations of a transaction. + :query operation: One of the three supported operations of a transaction. :type operation: string - :param asset_id: asset ID. + :query asset_id: asset ID. :type asset_id: uuidv4 **Example request**: @@ -280,10 +280,10 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :param fields: A comma separated string to expand properties on the transaction object to be returned. + :query fields: A comma separated string to expand properties on the transaction object to be returned. :type fields: string - :param metadata_id: metadata ID. + :query metadata_id: metadata ID. :type metadata_id: uuidv4 **Example request**: From 9a1b1364eab84dd323a123db380701b9561a1413 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:47:22 +0100 Subject: [PATCH 043/155] Add response headers --- .../source/drivers-clients/http-client-server-api.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 9a7a5c74..df8c093c 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -112,6 +112,8 @@ Transactions "version": 1 } + :resheader Content-Type: ``application/json`` + :statuscode 200: A transaction with that ID was found. :statuscode 404: A transaction with that ID was not found. @@ -216,6 +218,8 @@ Transactions "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", }] + :resheader Content-Type: ``application/json`` + :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. @@ -267,6 +271,8 @@ Transactions "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", }] + :resheader Content-Type: ``application/json`` + :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. @@ -310,6 +316,8 @@ Transactions "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", }] + :resheader Content-Type: ``application/json`` + :statuscode 200: A list of transaction's containing metadata with ID ``metadata_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``metadata_id`` querystring was not included in the request. @@ -371,6 +379,9 @@ Statuses .. literalinclude:: samples/get-tx-status-response.http :language: http + :resheader Content-Type: ``application/json`` + :resheader Location: Once the transaction has been persisted, this header will link to the actual resource. + :statuscode 200: A transaction or block with that ID was found. The status is either ``backlog``, ``invalid``. :statuscode 303: A transaction or block with that ID was found and persisted to the chain. A location header to the resource is provided. :statuscode 404: A transaction or block with that ID was not found. From d748a1dc18eeca81932811bb5ca5f29dd1416081 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 16:53:31 +0100 Subject: [PATCH 044/155] Minor corrections of redundant infos --- .../drivers-clients/http-client-server-api.rst | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index df8c093c..e55f65c5 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -223,22 +223,17 @@ Transactions :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. -.. http:get:: /transactions?fields=id,asset,operation&operation={CREATE|TRANSFER}&asset_id={asset_id} +.. http:get:: /transactions?fields=id,asset,operation&operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} Get a list of transactions that use an asset with the ID ``asset_id``. - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``asset_id`` happens to not be defined in the request. - - ``operation`` can either be ``GENESIS``, ``CREATE`` or ``TRANSFER``. - This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. :query fields: A comma separated string to expand properties on the transaction object to be returned. :type fields: string - :query operation: One of the three supported operations of a transaction. + :query operation: One of the three supported operations of a transaction (``GENESIS``, ``CREATE``, ``TRANSFER``). :type operation: string :query asset_id: asset ID. @@ -280,9 +275,6 @@ Transactions Get a list of transactions that use metadata with the ID ``metadata_id``. - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``metadata_id`` happens to not be defined in the request. - This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. @@ -353,6 +345,7 @@ Statuses .. http:get:: /statuses/{tx_id | block_id} Get the status of an asynchronously written resource by their id. + Supports the retrieval of a status for a transaction using ``tx_id`` or the retrieval of a status for a block using ``block_id``. From 2997a5e994e93c8846d2b9ec7848f32eb6509a71 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 16 Nov 2016 18:09:06 +0100 Subject: [PATCH 045/155] Minor corrections to endpoints --- .../drivers-clients/http-client-server-api.rst | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index e55f65c5..32b9d6bc 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -165,9 +165,6 @@ Transactions ``owners_after`` happen to be fulfilled already, this endpoint will return an empty list. - This endpoint will return a ``HTTP 400 Bad Request`` if the querystring - ``owners_after`` happens to not be defined in the request. - This endpoint returns conditions only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. @@ -401,10 +398,22 @@ Blocks Descriptions: TODO +.. http:get:: /blocks?tx_id={tx_id} + + Descriptions: TODO + Votes -------------------------------- +.. http:get:: /votes/{vote_id} + + Descriptions: TODO + .. http:get:: /votes?block_id={block_id} Descriptions: TODO + +.. http:get:: /votes?block_id={block_id}&voter={voter} + + Descriptions: TODO From af6b799c4fa5a9fcaa63a102c090a57f6fe275f1 Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 17 Nov 2016 14:11:27 +0100 Subject: [PATCH 046/155] Adjustments according to feedback - owner_afters --> owners_after - List choices for operation query string - List choices for fields query string - Use proper sphinx-way to define type of query string --- .../http-client-server-api.rst | 46 +++++++------------ 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 32b9d6bc..d7a2902c 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -128,7 +128,7 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Unfulfilled conditions <#get--transactions?fields=id,conditions&fulfilled=false&owner_afters=owners_after>`_ + * `Unfulfilled conditions <#get--transactions?fields=id,conditions&fulfilled=false&owners_after=owners_after>`_ * `A specific asset <#get--transactions?fields=id,asset,operation&operation=CREATE|TRANSFER&asset_id=asset_id>`_ * `Specific metadata <#get--transactions?fields=id,metadata&metadata_id=metadata_id>`_ @@ -136,28 +136,22 @@ Transactions to be very handy when implementing your application on top of BigchainDB. A generalization of those parameters can follows: - :query fields: A comma separated string to expand properties on the transaction object to be returned. - :type fields: string + :query string fields: Comma separated list, allowed values are: ``asset``, ``conditions``, ``fulfillments``, ``id``, ``metadata``, ``operation``, ``owners_after``, ``version``. - :query fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :type fulfilled: boolean + :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :query owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :type owners_after: base58 encoded string + :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :query operation: One of the three supported operations of a transaction. - :type operation: string + :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. - :query asset_id: asset ID. - :type asset_id: uuidv4 + :query string asset_id: asset ID. - :query metadata_id: metadata ID. - :type metadata_id: uuidv4 + :query string metadata_id: metadata ID. :statuscode 404: BigchainDB does not expose this endpoint. -.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owner_afters={owners_after} +.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owners_after={owners_after} Get a list of transactions with unfulfilled conditions. @@ -168,14 +162,11 @@ Transactions This endpoint returns conditions only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query fields: A comma separated string to expand properties on the transaction object to be returned. - :type fields: string + :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :type fulfilled: boolean + :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :query owners_after: Public keys able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :type owners_after: base58 encoded string + :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. **Example request**: @@ -227,14 +218,11 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query fields: A comma separated string to expand properties on the transaction object to be returned. - :type fields: string + :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query operation: One of the three supported operations of a transaction (``GENESIS``, ``CREATE``, ``TRANSFER``). - :type operation: string + :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. - :query asset_id: asset ID. - :type asset_id: uuidv4 + :query string asset_id: asset ID. **Example request**: @@ -275,11 +263,9 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query fields: A comma separated string to expand properties on the transaction object to be returned. - :type fields: string + :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query metadata_id: metadata ID. - :type metadata_id: uuidv4 + :query string metadata_id: metadata ID. **Example request**: From 26cb00ab9c64c9878616fd5ac6bb98618619ca38 Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 17 Nov 2016 17:38:49 +0100 Subject: [PATCH 047/155] Document /block/block_id endpoint --- .../http-client-server-api.rst | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index d7a2902c..f6fc498d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -382,7 +382,48 @@ Blocks .. http:get:: /blocks/{block_id} - Descriptions: TODO + Get the block with the ID ``block_id``. + + A block is only returned if it was labeled ``VALID`` or ``UNDECIDED`` and + exists in the table ``bigchain``. + + :param block_id: block ID + :type block_id: hex string + + **Example request**: + + .. sourcecode:: http + + GET /blocks/6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202 HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "block":{ + "node_pubkey":"ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt", + "timestamp":"1479389911", + "transactions":[ + '', + '' + ], + "voters":[ + "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" + ] + }, + "id":"6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202", + "signature":"53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" + } + + :resheader Content-Type: ``application/json`` + + :statuscode 200: A block with that ID was found. Its status is either ``VALID`` or ``UNDECIDED``. + :statuscode 404: A block with that ID was not found. .. http:get:: /blocks?tx_id={tx_id} From ea16a8731e0d8c778233261b2bcf821ae541bf6b Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 17 Nov 2016 17:48:24 +0100 Subject: [PATCH 048/155] Remove ?fields query string --- .../http-client-server-api.rst | 132 +++++++++++++++--- 1 file changed, 110 insertions(+), 22 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index f6fc498d..e08d1ab0 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -128,16 +128,14 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Unfulfilled conditions <#get--transactions?fields=id,conditions&fulfilled=false&owners_after=owners_after>`_ - * `A specific asset <#get--transactions?fields=id,asset,operation&operation=CREATE|TRANSFER&asset_id=asset_id>`_ - * `Specific metadata <#get--transactions?fields=id,metadata&metadata_id=metadata_id>`_ + * `Unfulfilled conditions <#get--transactions?fulfilled=false&owners_after=owners_after>`_ + * `A specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ + * `Specific metadata <#get--transactions?&metadata_id=metadata_id>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. A generalization of those parameters can follows: - :query string fields: Comma separated list, allowed values are: ``asset``, ``conditions``, ``fulfillments``, ``id``, ``metadata``, ``operation``, ``owners_after``, ``version``. - :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. @@ -151,7 +149,7 @@ Transactions :statuscode 404: BigchainDB does not expose this endpoint. -.. http:get:: /transactions?fields=id,conditions&fulfilled=false&owners_after={owners_after} +.. http:get:: /transactions?fulfilled=false&owners_after={owners_after} Get a list of transactions with unfulfilled conditions. @@ -162,8 +160,6 @@ Transactions This endpoint returns conditions only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. @@ -172,7 +168,7 @@ Transactions .. sourcecode:: http - GET /transactions?fields=id,conditions&fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 + GET /transactions?fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: @@ -203,7 +199,29 @@ Transactions ] } ], + "operation": "CREATE", + "asset": { + "divisible": false, + "updatable": false, + "data": null, + "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", + "refillable": false + }, + "metadata": null, + "timestamp": "1477578978", + "fulfillments": [ + { + "fid": 0, + "input": null, + "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", + "owners_before": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ] + }, "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + "version": 1 }] :resheader Content-Type: ``application/json`` @@ -211,15 +229,13 @@ Transactions :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. -.. http:get:: /transactions?fields=id,asset,operation&operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} +.. http:get:: /transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} Get a list of transactions that use an asset with the ID ``asset_id``. This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. @@ -228,7 +244,7 @@ Transactions .. sourcecode:: http - GET /transactions?fields=id,asset,operation&operation=CREATE&asset_id=1AAAbbb...ccc HTTP/1.1 + GET /transactions?operation=CREATE&asset_id=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: @@ -240,6 +256,26 @@ Transactions [{ "transaction": { + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + } + }, + "amount": 1, + "owners_after": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ], + "operation": "CREATE", "asset": { "divisible": false, "updatable": false, @@ -247,8 +283,21 @@ Transactions "id": "1AAAbbb...ccc", "refillable": false }, - "operation": "CREATE", + "metadata": null, + "timestamp": "1477578978", + "fulfillments": [ + { + "fid": 0, + "input": null, + "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", + "owners_before": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ] + }, "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + "version": 1 }] :resheader Content-Type: ``application/json`` @@ -256,22 +305,20 @@ Transactions :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. -.. http:get:: /transactions?fields=id,metadata&metadata_id={metadata_id} +.. http:get:: /transactions?metadata_id={metadata_id} Get a list of transactions that use metadata with the ID ``metadata_id``. This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query string fields: A comma separated string to expand properties on the transaction object to be returned. - :query string metadata_id: metadata ID. **Example request**: .. sourcecode:: http - GET /transactions?fields=id,metadata&metadata_id=1AAAbbb...ccc HTTP/1.1 + GET /transactions?metadata_id=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: @@ -283,12 +330,53 @@ Transactions [{ "transaction": { - "metadata": { - "id": "1AAAbbb...ccc", - "data": { - "hello": "world" + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + } + }, + "amount": 1, + "owners_after": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ], + "operation": "CREATE", + "asset": { + "divisible": false, + "updatable": false, + "data": null, + "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", + "refillable": false }, + "metadata": { + "id": "1AAAbbb...ccc", + "data": { + "hello": "world" + }, + }, + "timestamp": "1477578978", + "fulfillments": [ + { + "fid": 0, + "input": null, + "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", + "owners_before": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ] + }, "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + "version": 1 }] :resheader Content-Type: ``application/json`` From 9cd4c18fb474d9559fc094f7ed327ce6cd23f4b6 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 23 Nov 2016 10:25:07 +0100 Subject: [PATCH 049/155] Remove uuid based endpoints --- .../drivers-clients/http-client-server-api.rst | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index e08d1ab0..9f189511 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -450,21 +450,6 @@ Statuses :statuscode 303: A transaction or block with that ID was found and persisted to the chain. A location header to the resource is provided. :statuscode 404: A transaction or block with that ID was not found. - -Assets --------------------------------- - -.. http:get:: /assets/{asset_id} - - Descriptions: TODO - - -Metadata --------------------------------- - -.. http:get:: /metadata/{metadata_id} - - Blocks -------------------------------- From 5ac7eb9b5a121940842d58618c8d3fa979865d13 Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 23 Nov 2016 11:04:28 +0100 Subject: [PATCH 050/155] Add notes about endpoint specialities For details, see the following comment: https://github.com/bigchaindb/bigchaindb/pull/830#issuecomment-262468005 --- .../http-client-server-api.rst | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 9f189511..545aaf3e 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -236,6 +236,17 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + .. note:: + The BigchainDB API currently doesn't expose an + ``/assets/{asset_id}`` endpoint, as there wouldn't be any way for a + client to verify that what was received is consistent with what was + persisted in the database. + However, BigchainDB's consensus ensures that any ``asset_id`` is + a unique key identifying an asset, meaning that when calling + ``/transactions?operation=CREATE&asset_id={asset_id}``, there will in + any case only be one transaction returned (in a list though, since + ``/transactions`` is a list-returning endpoint). + :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. @@ -312,6 +323,17 @@ Transactions This endpoint returns assets only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + .. note:: + The BigchainDB API currently doesn't expose an + ``/metadata/{metadata_id}`` endpoint, as there wouldn't be any way for a + client to verify that what was received is consistent with what was + persisted in the database. + However, BigchainDB's consensus ensures that any ``metadata_id`` is + a unique key identifying metadata, meaning that when calling + ``/transactions?metadata_id={metadata_id}``, there will in any case only + be one transaction returned (in a list though, since ``/transactions`` + is a list-returning endpoint). + :query string metadata_id: metadata ID. **Example request**: From 5048846b0f941ef318a1b53b27de7305c9bf85eb Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 23 Nov 2016 13:27:01 +0100 Subject: [PATCH 051/155] Minor corrections on /statuses --- .../source/drivers-clients/http-client-server-api.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 545aaf3e..51456f53 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -435,7 +435,7 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses/{tx_id | block_id} +.. http:get:: /statuses/{tx_id|block_id} Get the status of an asynchronously written resource by their id. @@ -445,9 +445,9 @@ Statuses The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. - If a transaction or block is persisted to the chain and it's status is set to - ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, as - well as an URL to the resource in the location header. + If a transaction or block is persisted to the chain and it's status is set + to ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, + as well as an URL to the resource in the location header. :param tx_id: transaction ID :type tx_id: hex string From 91a115125544cda8b4856f4483d5e693118427f4 Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 24 Nov 2016 10:17:00 +0100 Subject: [PATCH 052/155] Add endpoint to get blocks by transaction --- .../http-client-server-api.rst | 102 +++++++++++++++++- 1 file changed, 100 insertions(+), 2 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 51456f53..8206a5fa 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -520,9 +520,107 @@ Blocks :statuscode 200: A block with that ID was found. Its status is either ``VALID`` or ``UNDECIDED``. :statuscode 404: A block with that ID was not found. -.. http:get:: /blocks?tx_id={tx_id} +.. http:get:: /blocks - Descriptions: TODO + The current ``/blocks`` endpoint returns a ``404 Not Found`` HTTP status + code. Eventually, this functionality will get implemented. + We believe a PUSH rather than a PULL pattern is more appropriate, as the + items returned in the collection would change by the second. + + :statuscode 404: BigchainDB does not expose this endpoint. + + +.. http:get:: /blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID} + + Retrieve a list of blocks that contain a transaction with the ID ``tx_id``. + + Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be + returned. To filter blocks by their status, use the optional ``status`` + querystring. + + .. note:: + In case no block was found, an empty list and an HTTP status code + ``200 OK`` is returned, as the request was still successful. + + :query string tx_id: transaction ID + :query string status: Filter blocks by their status. One of ``VALID``, ``UNDECIDED`` or ``INVALID``. + + **Example request**: + + .. sourcecode:: http + + GET /blocks?tx_id=2d431...0b4b0e HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "block":{ + "node_pubkey":"ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt", + "timestamp":"1479389911", + "transactions":[ + { + "transaction": { + "conditions": [ + { + "cid": 0, + "condition": { + "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", + "details": { + "signature": null, + "type": "fulfillment", + "type_id": 4, + "bitmask": 32, + "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + } + }, + "amount": 1, + "owners_after": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ], + "operation": "CREATE", + "asset": { + "divisible": false, + "updatable": false, + "data": null, + "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", + "refillable": false + }, + "metadata": null, + "timestamp": "1477578978", + "fulfillments": [ + { + "fid": 0, + "input": null, + "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", + "owners_before": [ + "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" + ] + } + ] + }, + "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", + "version": 1 + }], + "voters":[ + "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" + ] + }, + "id":"6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202", + "signature":"53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" + } + + :resheader Content-Type: ``application/json`` + + :statuscode 200: A list of blocks containing a transaction with ID ``tx_id`` was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks``, without defining ``tx_id``. Votes From 8f7816d32501f16d06d51cc6efdad590ba06e790 Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 24 Nov 2016 11:14:41 +0100 Subject: [PATCH 053/155] Bigchaindb --> BigchainDB --- .../server/source/drivers-clients/http-client-server-api.rst | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 8206a5fa..cebe9566 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -7,11 +7,6 @@ The HTTP Client-Server API there is no ability to do complex queries using the HTTP API. We plan to add more querying capabilities in the future. -This page assumes you already know an API Root URL -for a BigchainDB node or reverse proxy. -It should be something like ``http://apihosting4u.net:9984`` -or ``http://12.34.56.78:9984``. - If you set up a BigchainDB node or reverse proxy yourself, and you're not sure what the API Root URL is, then see the last section of this page for help. From 8e91e14e86b68bbe68e9afaeec05b55c97678fb7 Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 24 Nov 2016 11:37:58 +0100 Subject: [PATCH 054/155] Add /blocks/{block_id} safety querystring It didn't feel good letting users retrieve also invalid or undecided blocks in the /blocks/{block_id} endpoint. Hence, now a block can be evaluated by it's status. If block_id and status do not match, a 404 Not Found HTTP status code is returned. Per default, status is set to valid only. --- .../drivers-clients/http-client-server-api.rst | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index cebe9566..c57bb9c1 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -470,16 +470,23 @@ Statuses Blocks -------------------------------- -.. http:get:: /blocks/{block_id} +.. http:get:: /blocks/{block_id}?status={VALID|UNDECIDED|INVALID} Get the block with the ID ``block_id``. - A block is only returned if it was labeled ``VALID`` or ``UNDECIDED`` and - exists in the table ``bigchain``. + .. note:: + As ``status``'s default value is set to ``VALID``, only ``VALID`` blocks + will be returned by this endpoint. In case ``status=VALID``, but a block + that was labeled ``UNDECIDED`` or ``INVALID`` is requested by + ``block_id``, this endpoint will return a ``404 Not Found`` status code + to warn the user. To check a block's status independently, use the + `Statuses endpoint <#get--statuses-tx_id|block_id>`_. :param block_id: block ID :type block_id: hex string + :query string status: Per default set to ``VALID``. One of ``VALID``, ``UNDECIDED`` or ``INVALID``. + **Example request**: .. sourcecode:: http @@ -512,8 +519,9 @@ Blocks :resheader Content-Type: ``application/json`` - :statuscode 200: A block with that ID was found. Its status is either ``VALID`` or ``UNDECIDED``. - :statuscode 404: A block with that ID was not found. + :statuscode 200: A block with that ID was found. + :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. + :statuscode 404: A block with that ID and a certain ``status`` was not found. .. http:get:: /blocks From 0c651f6b112fb6c1de3aecff15ce958086597f1d Mon Sep 17 00:00:00 2001 From: tim Date: Thu, 24 Nov 2016 18:03:46 +0100 Subject: [PATCH 055/155] Timestamp of block as header: /transactions/tx_id For reasoning, see: https://github.com/bigchaindb/bigchaindb/pull/830#issuecomment-262774345 --- .../source/drivers-clients/http-client-server-api.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index c57bb9c1..d84c0991 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -44,6 +44,11 @@ Transactions This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. + A transaction itself doesn't include a ``timestamp`` property. Only the + block a transaction was included in has a unix ``timestamp`` property. It is + returned by this endpoint in a HTTP custom entity header called + ``X-BigchainDB-Timestamp``. + :param tx_id: transaction ID :type tx_id: hex string @@ -60,6 +65,7 @@ Transactions HTTP/1.1 200 OK Content-Type: application/json + X-BigchainDB-Timestamp: 1234567890 { "transaction": { @@ -107,6 +113,7 @@ Transactions "version": 1 } + :resheader X-BigchainDB-Timestamp: A unix timestamp describing when a transaction was included into a valid block. The timestamp provided is taken from the block the transaction was included in. :resheader Content-Type: ``application/json`` :statuscode 200: A transaction with that ID was found. From df3ded315cd2e7fced36671b503ea5f4f2c76530 Mon Sep 17 00:00:00 2001 From: tim Date: Fri, 25 Nov 2016 14:13:46 +0100 Subject: [PATCH 056/155] Remove retrieve vote by vote_id After talking to @r-marques and @libscott: - A vote's id is currently generated by RethinkDB - To verify a vote, the signature and the pubkey should be used - Vote's id will be removed from the "external" vote model in the future - Nobody would want to retrieve a vote, but rather a vote by block In case of the HTTP API, this means that a /votes/vote_id endpoint is not feasible to implement. --- .../source/drivers-clients/http-client-server-api.rst | 6 ------ 1 file changed, 6 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index d84c0991..98df59ed 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -636,14 +636,8 @@ Blocks Votes -------------------------------- -.. http:get:: /votes/{vote_id} - - Descriptions: TODO - .. http:get:: /votes?block_id={block_id} Descriptions: TODO .. http:get:: /votes?block_id={block_id}&voter={voter} - - Descriptions: TODO From 6e25ef45989f8190ef1a529f363960b9f598d533 Mon Sep 17 00:00:00 2001 From: tim Date: Fri, 25 Nov 2016 15:51:17 +0100 Subject: [PATCH 057/155] Add retrieve votes by block --- .../http-client-server-api.rst | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 98df59ed..fa3178b4 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -638,6 +638,48 @@ Votes .. http:get:: /votes?block_id={block_id} - Descriptions: TODO + Retrieve a list of votes for a certain block with ID ``block_id``. + To check for the validity of a vote, a user of this endpoint needs to + perform the `following steps: `_ + + 1. Check if the vote's ``node_pubkey`` is allowed to vote. + 2. Verify the vote's signature against the vote's body (``vote.vote``) and + ``node_pubkey``. + + :query string block_id: The block ID to filter the votes. + + **Example request**: + + .. sourcecode:: http + + GET /votes?block_id=6152f...e7202 HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [{ + "node_pubkey": "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" , + "signature": "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA", + "vote": { + "invalid_reason": null , + "is_block_valid": true , + "previous_block": "6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202" , + "timestamp": "1480082692" , + "voting_for_block": "6152f...e7202" + } + }] + + :resheader Content-Type: ``application/json`` + + :statuscode 200: A list of votes voting for a block with ID ``block_id`` was found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/votes``, without defining ``block_id``. + .. http:get:: /votes?block_id={block_id}&voter={voter} + + Description: TODO From 56b4da02c9d2032b2186b6bf322ae334a0f152ce Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 26 Dec 2016 16:18:09 +0100 Subject: [PATCH 058/155] (fix) : minor fixes to server docs for building --- .../source/drivers-clients/http-client-server-api.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index fa3178b4..6fe56a6e 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -513,8 +513,8 @@ Blocks "node_pubkey":"ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt", "timestamp":"1479389911", "transactions":[ - '', - '' + "", + "" ], "voters":[ "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" @@ -643,8 +643,8 @@ Votes perform the `following steps: `_ 1. Check if the vote's ``node_pubkey`` is allowed to vote. - 2. Verify the vote's signature against the vote's body (``vote.vote``) and - ``node_pubkey``. + 2. Verify the vote's signature against the vote's body (``vote.vote``) and ``node_pubkey``. + :query string block_id: The block ID to filter the votes. From a8f8c7f4a98cd39bd2fe8f48e2c99ed5180d5273 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 26 Dec 2016 16:36:21 +0100 Subject: [PATCH 059/155] GET transactions/id examples --> samples --- .../generate_http_server_api_documentation.py | 1 + .../http-client-server-api.rst | 59 ++----------------- 2 files changed, 5 insertions(+), 55 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 7c7c4b97..df685315 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -53,6 +53,7 @@ Host: example.com TPLS['get-tx-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json +X-BigchainDB-Timestamp: 1482766245 %(tx)s """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 6fe56a6e..c51dec65 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -54,64 +54,13 @@ Transactions **Example request**: - .. sourcecode:: http - - GET /transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-tx-request.http + :language: http **Example response**: - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - X-BigchainDB-Timestamp: 1234567890 - - { - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - } - }, - "amount": 1, - "owners_after": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ], - "operation": "CREATE", - "asset": { - "divisible": false, - "updatable": false, - "data": null, - "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", - "refillable": false - }, - "metadata": null, - "timestamp": "1477578978", - "fulfillments": [ - { - "fid": 0, - "input": null, - "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", - "owners_before": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ] - }, - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - "version": 1 - } + .. literalinclude:: samples/get-tx-response.http + :language: http :resheader X-BigchainDB-Timestamp: A unix timestamp describing when a transaction was included into a valid block. The timestamp provided is taken from the block the transaction was included in. :resheader Content-Type: ``application/json`` From d09a93f1a7d95e17652de9dc050626e1589929fc Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 26 Dec 2016 17:23:22 +0100 Subject: [PATCH 060/155] update GET transactions?unfulfilled - owners_after -> public_keys - examples -> samples --- .../generate_http_server_api_documentation.py | 51 ++++++++----- .../http-client-server-api.rst | 72 ++++--------------- 2 files changed, 47 insertions(+), 76 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index df685315..b960d078 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -9,6 +9,38 @@ from bigchaindb.common.transaction import Transaction TPLS = {} + +TPLS['get-tx-id-request'] = """\ +GET /transactions/%(txid)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-tx-id-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json +X-BigchainDB-Timestamp: 1482766245 + +%(tx)s +""" + + +TPLS['get-tx-unfulfilled-request'] = """\ +GET /transactions?fulfilled=false&public_keys=%(public_keys)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-tx-unfulfilled-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +[%(tx)s] +""" + + TPLS['post-tx-request'] = """\ POST /transactions/ HTTP/1.1 Host: example.com @@ -32,7 +64,6 @@ Host: example.com """ - TPLS['get-tx-status-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json @@ -43,20 +74,6 @@ Content-Type: application/json """ -TPLS['get-tx-request'] = """\ -GET /transactions/%(txid)s HTTP/1.1 -Host: example.com - -""" - - -TPLS['get-tx-response'] = """\ -HTTP/1.1 200 OK -Content-Type: application/json -X-BigchainDB-Timestamp: 1482766245 - -%(tx)s -""" def main(): @@ -75,7 +92,9 @@ def main(): for name, tpl in TPLS.items(): path = os.path.join(base_path, name + '.http') - code = tpl % {'tx': tx_json, 'txid': tx.id} + code = tpl % {'tx': tx_json, + 'txid': tx.id, + 'public_keys': tx.outputs[0].public_keys[0]} with open(path, 'w') as handle: handle.write(code) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index c51dec65..284625f9 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -54,12 +54,12 @@ Transactions **Example request**: - .. literalinclude:: samples/get-tx-request.http + .. literalinclude:: samples/get-tx-id-request.http :language: http **Example response**: - .. literalinclude:: samples/get-tx-response.http + .. literalinclude:: samples/get-tx-id-response.http :language: http :resheader X-BigchainDB-Timestamp: A unix timestamp describing when a transaction was included into a valid block. The timestamp provided is taken from the block the transaction was included in. @@ -79,7 +79,7 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Unfulfilled conditions <#get--transactions?fulfilled=false&owners_after=owners_after>`_ + * `Unfulfilled conditions <#get--transactions?fulfilled=false&public_keys=public_keys>`_ * `A specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ * `Specific metadata <#get--transactions?&metadata_id=metadata_id>`_ @@ -89,7 +89,7 @@ Transactions :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. @@ -100,12 +100,12 @@ Transactions :statuscode 404: BigchainDB does not expose this endpoint. -.. http:get:: /transactions?fulfilled=false&owners_after={owners_after} +.. http:get:: /transactions?fulfilled=false&public_keys={public_keys} Get a list of transactions with unfulfilled conditions. If the querystring ``fulfilled`` is set to ``false`` and all conditions for - ``owners_after`` happen to be fulfilled already, this endpoint will return + ``public_keys`` happen to be fulfilled already, this endpoint will return an empty list. This endpoint returns conditions only if the transaction they're in are @@ -113,67 +113,19 @@ Transactions :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. - :query string owners_after: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. **Example request**: - .. sourcecode:: http - GET /transactions?fulfilled=false&owners_after=1AAAbbb...ccc HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-tx-unfulfilled-request.http + :language: http + **Example response**: - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [{ - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "1AAAbbb...ccc" - } - }, - "amount": 1, - "owners_after": [ - "1AAAbbb...ccc" - ] - } - ], - "operation": "CREATE", - "asset": { - "divisible": false, - "updatable": false, - "data": null, - "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", - "refillable": false - }, - "metadata": null, - "timestamp": "1477578978", - "fulfillments": [ - { - "fid": 0, - "input": null, - "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", - "owners_before": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ] - }, - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - "version": 1 - }] + .. literalinclude:: samples/get-tx-unfulfilled-response.http + :language: http :resheader Content-Type: ``application/json`` From a37b505c8779ddb5d9f821dff8661540321cc2a3 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 26 Dec 2016 17:28:06 +0100 Subject: [PATCH 061/155] (fix): forgot one owners_after -> public_keys --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 284625f9..b6c4f3ef 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -130,7 +130,7 @@ Transactions :resheader Content-Type: ``application/json`` :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``owners_after`` querystring was not included in the request. + :statuscode 400: The request wasn't understood by the server, e.g. the ``public_keys`` querystring was not included in the request. .. http:get:: /transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} From b947cf7c729447ef4766ecd13dc196acac73dbdd Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 28 Dec 2016 15:43:54 +0100 Subject: [PATCH 062/155] GET transactions?operation&asset_id examples --> samples Updated example to include more than one TRANSFER --- .../generate_http_server_api_documentation.py | 56 ++++++++++++++++-- .../http-client-server-api.rst | 58 ++----------------- 2 files changed, 54 insertions(+), 60 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index b960d078..2d4d0fba 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -4,8 +4,7 @@ import json import os import os.path -from bigchaindb.common.transaction import Transaction - +from bigchaindb.common.transaction import Transaction, Input, TransactionLink TPLS = {} @@ -27,7 +26,7 @@ X-BigchainDB-Timestamp: 1482766245 TPLS['get-tx-unfulfilled-request'] = """\ -GET /transactions?fulfilled=false&public_keys=%(public_keys)s HTTP/1.1 +GET /transactions?fulfilled=false&public_keys=%(public_keys_transfer_last)s HTTP/1.1 Host: example.com """ @@ -37,7 +36,23 @@ TPLS['get-tx-unfulfilled-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json -[%(tx)s] +[%(tx_transfer_last)s] +""" + + +TPLS['get-tx-by-asset-request'] = """\ +GET /transactions?operation=transfer&asset_id=%(txid)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-tx-by-asset-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +[%(tx_transfer)s, +%(tx_transfer_last)s] """ @@ -80,10 +95,33 @@ def main(): """ Main function """ privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' pubkey = '4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD' - tx = Transaction.create([pubkey], [([pubkey], 1)]) + asset = {'msg': 'Hello BigchainDB!'} + tx = Transaction.create([pubkey], [([pubkey], 1)], asset=asset) tx = tx.sign([privkey]) tx_json = json.dumps(tx.to_dict(), indent=2, sort_keys=True) + privkey_transfer = '3AeWpPdhEZzWLYfkfYHBfMFC2r1f8HEaGS9NtbbKssya' + pubkey_transfer = '3yfQPHeWAa1MxTX9Zf9176QqcpcnWcanVZZbaHb8B3h9' + + cid = 0 + input_ = Input(fulfillment=tx.outputs[cid].fulfillment, + fulfills=TransactionLink(txid=tx.id, output=cid), + owners_before=tx.outputs[cid].public_keys) + tx_transfer = Transaction.transfer([input_], [([pubkey_transfer], 1)], asset_id=tx.id) + tx_transfer = tx_transfer.sign([privkey]) + tx_transfer_json = json.dumps(tx_transfer.to_dict(), indent=2, sort_keys=True) + + privkey_transfer_last = 'sG3jWDtdTXUidBJK53ucSTrosktG616U3tQHBk81eQe' + pubkey_transfer_last = '3Af3fhhjU6d9WecEM9Uw5hfom9kNEwE7YuDWdqAUssqm' + + cid = 0 + input_ = Input(fulfillment=tx_transfer.outputs[cid].fulfillment, + fulfills=TransactionLink(txid=tx_transfer.id, output=cid), + owners_before=tx_transfer.outputs[cid].public_keys) + tx_transfer_last = Transaction.transfer([input_], [([pubkey_transfer_last], 1)], asset_id=tx.id) + tx_transfer_last = tx_transfer_last.sign([privkey_transfer]) + tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) + base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') @@ -94,7 +132,13 @@ def main(): path = os.path.join(base_path, name + '.http') code = tpl % {'tx': tx_json, 'txid': tx.id, - 'public_keys': tx.outputs[0].public_keys[0]} + 'tx_transfer': tx_transfer_json, + 'tx_transfer_id': tx_transfer.id, + 'tx_transfer_last': tx_transfer_last_json, + 'tx_transfer_last_id': tx_transfer_last.id, + 'public_keys': tx.outputs[0].public_keys[0], + 'public_keys_transfer': tx_transfer.outputs[0].public_keys[0], + 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0]} with open(path, 'w') as handle: handle.write(code) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index b6c4f3ef..e774528d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -156,63 +156,13 @@ Transactions **Example request**: - .. sourcecode:: http - - GET /transactions?operation=CREATE&asset_id=1AAAbbb...ccc HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-tx-by-asset-request.http + :language: http **Example response**: - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [{ - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - } - }, - "amount": 1, - "owners_after": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ], - "operation": "CREATE", - "asset": { - "divisible": false, - "updatable": false, - "data": null, - "id": "1AAAbbb...ccc", - "refillable": false - }, - "metadata": null, - "timestamp": "1477578978", - "fulfillments": [ - { - "fid": 0, - "input": null, - "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", - "owners_before": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ] - }, - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - "version": 1 - }] + .. literalinclude:: samples/get-tx-by-asset-response.http + :language: http :resheader Content-Type: ``application/json`` From 35a7d11fb324b80b36bb03fc041483ae54110d48 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 28 Dec 2016 16:24:37 +0100 Subject: [PATCH 063/155] remove metadata query from endpoint -> see #856 --- .../http-client-server-api.rst | 104 ++---------------- 1 file changed, 9 insertions(+), 95 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index e774528d..08e0d5e3 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -79,13 +79,18 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Unfulfilled conditions <#get--transactions?fulfilled=false&public_keys=public_keys>`_ - * `A specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ - * `Specific metadata <#get--transactions?&metadata_id=metadata_id>`_ + * `Unfulfilled outputs <#get--transactions?fulfilled=false&public_keys=public_keys>`_ + * `Transactions related to a specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. - A generalization of those parameters can follows: + + .. note:: + Looking up transactions with a specific ``metadata`` field is currently not supported. + This functionality requires something like custom indexing per client or read-only followers, + which is not yet on the roadmap. + + A generalization of those parameters follows: :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. @@ -95,8 +100,6 @@ Transactions :query string asset_id: asset ID. - :query string metadata_id: metadata ID. - :statuscode 404: BigchainDB does not expose this endpoint. @@ -169,95 +172,6 @@ Transactions :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. -.. http:get:: /transactions?metadata_id={metadata_id} - - Get a list of transactions that use metadata with the ID ``metadata_id``. - - This endpoint returns assets only if the transaction they're in are - included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - - .. note:: - The BigchainDB API currently doesn't expose an - ``/metadata/{metadata_id}`` endpoint, as there wouldn't be any way for a - client to verify that what was received is consistent with what was - persisted in the database. - However, BigchainDB's consensus ensures that any ``metadata_id`` is - a unique key identifying metadata, meaning that when calling - ``/transactions?metadata_id={metadata_id}``, there will in any case only - be one transaction returned (in a list though, since ``/transactions`` - is a list-returning endpoint). - - :query string metadata_id: metadata ID. - - **Example request**: - - .. sourcecode:: http - - GET /transactions?metadata_id=1AAAbbb...ccc HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [{ - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - } - }, - "amount": 1, - "owners_after": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ], - "operation": "CREATE", - "asset": { - "divisible": false, - "updatable": false, - "data": null, - "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", - "refillable": false - }, - "metadata": { - "id": "1AAAbbb...ccc", - "data": { - "hello": "world" - }, - }, - "timestamp": "1477578978", - "fulfillments": [ - { - "fid": 0, - "input": null, - "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", - "owners_before": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ] - }, - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - "version": 1 - }] - - :resheader Content-Type: ``application/json`` - - :statuscode 200: A list of transaction's containing metadata with ID ``metadata_id`` was found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``metadata_id`` querystring was not included in the request. .. http:post:: /transactions From 5c106027548bd66cd95c5bedd17c67b7d2965158 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 28 Dec 2016 17:55:26 +0100 Subject: [PATCH 064/155] examples -> samples POST /transaction and /statuses --- .../generate_http_server_api_documentation.py | 24 ++++++++++++------- .../http-client-server-api.rst | 9 +++++-- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 2d4d0fba..6cd35d90 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -66,31 +66,39 @@ Content-Type: application/json TPLS['post-tx-response'] = """\ -HTTP/1.1 201 Created +HTTP/1.1 202 Accepted Content-Type: application/json - -%(tx)s +Location: ../statuses/%(txid)s """ -TPLS['get-tx-status-request'] = """\ -GET /transactions/%(txid)s/status HTTP/1.1 +TPLS['get-statuses-tx-request'] = """\ +GET /statuses/%(txid)s HTTP/1.1 Host: example.com """ -TPLS['get-tx-status-response'] = """\ +TPLS['get-statuses-tx-invalid-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json +{ + "status": "invalid" +} +""" + + +TPLS['get-statuses-tx-valid-response'] = """\ +HTTP/1.1 303 See Other +Content-Type: application/json +Location: ../transactions/%(txid)s + { "status": "valid" } """ - - def main(): """ Main function """ privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 08e0d5e3..fca6069a 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -224,12 +224,17 @@ Statuses **Example request**: - .. literalinclude:: samples/get-tx-status-request.http + .. literalinclude:: samples/get-statuses-tx-request.http :language: http **Example response**: - .. literalinclude:: samples/get-tx-status-response.http + .. literalinclude:: samples/get-statuses-tx-invalid-response.http + :language: http + + **Example response**: + + .. literalinclude:: samples/get-statuses-tx-valid-response.http :language: http :resheader Content-Type: ``application/json`` From 204c8cce9c7d7b33648ea3fe178e439811e5d627 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 29 Dec 2016 16:23:58 +0100 Subject: [PATCH 065/155] GET blocks/id examples -> samples --- .../generate_http_server_api_documentation.py | 27 ++++++++++++++++++- .../http-client-server-api.rst | 27 +++---------------- 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 6cd35d90..350a286a 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -5,6 +5,8 @@ import os import os.path from bigchaindb.common.transaction import Transaction, Input, TransactionLink +from bigchaindb.models import Block + TPLS = {} @@ -99,6 +101,20 @@ Location: ../transactions/%(txid)s """ +TPLS['get-block-request'] = """\ +GET /blocks/%(blockid)s HTTP/1.1 +Host: example.com + +""" + +TPLS['get-block-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +%(block)s +""" + + def main(): """ Main function """ privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' @@ -130,6 +146,11 @@ def main(): tx_transfer_last = tx_transfer_last.sign([privkey_transfer]) tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) + node = "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" + signature = "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" + block = Block(transactions=[tx], node_pubkey=node, voters=[node], signature=signature) + block_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) + base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') @@ -146,7 +167,9 @@ def main(): 'tx_transfer_last_id': tx_transfer_last.id, 'public_keys': tx.outputs[0].public_keys[0], 'public_keys_transfer': tx_transfer.outputs[0].public_keys[0], - 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0]} + 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0], + 'block': block_json, + 'blockid': block.id} with open(path, 'w') as handle: handle.write(code) @@ -158,3 +181,5 @@ def setup(*_): if __name__ == '__main__': main() + + diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index fca6069a..56ebfc86 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -266,33 +266,14 @@ Blocks **Example request**: - .. sourcecode:: http - - GET /blocks/6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202 HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-block-request.http + :language: http **Example response**: - .. sourcecode:: http + .. literalinclude:: samples/get-block-response.http + :language: http - HTTP/1.1 200 OK - Content-Type: application/json - - { - "block":{ - "node_pubkey":"ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt", - "timestamp":"1479389911", - "transactions":[ - "", - "" - ], - "voters":[ - "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" - ] - }, - "id":"6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202", - "signature":"53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" - } :resheader Content-Type: ``application/json`` From 21ffe225166034367eec92d3292eb6c229d18269 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 2 Jan 2017 15:24:14 +0100 Subject: [PATCH 066/155] API root URL vs BigchainDB root URL --- .../http-client-server-api.rst | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 56ebfc86..126a7903 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -12,8 +12,8 @@ and you're not sure what the API Root URL is, then see the last section of this page for help. -API Root URL ------------- +BigchainDB Root URL +------------------- If you send an HTTP GET request to the API Root URL e.g. ``http://localhost:9984`` @@ -31,7 +31,28 @@ with something like the following in the body: ], "public_key": "AiygKSRhZWTxxYT4AfgKoTG4TZAoPsWoEt6C6bLq4jJR", "software": "BigchainDB", - "version": "0.6.0" + "version": "0.9.0" + } + + +API Root URL +------------------- + +If you send an HTTP GET request to the API Root URL +e.g. ``http://localhost:9984/api/v1/`` +or ``http://apihosting4u.net:9984/api/v1/``, +then you should get an HTTP response +that allows you to discover the BigchainDB endpoints: + +.. code-block:: json + + { + "_links": { + "self": { "href": "/" }, + "transactions": { "href": "/transactions" }, + "statuses": { "href": "/statuses" }, + "blocks": { "href": "/blocks" }, + "votes": { "href": "/votes" } } Transactions From e54d50a58f57aa0985013130debae049343f80d6 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 2 Jan 2017 15:43:45 +0100 Subject: [PATCH 067/155] Add docs links to root endpoints --- .../http-client-server-api.rst | 61 ++++++++++++++++--- 1 file changed, 52 insertions(+), 9 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 126a7903..95f08bd7 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -25,34 +25,40 @@ with something like the following in the body: .. code-block:: json { + "_links": { + "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" } + } "keyring": [ "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", "AdDuyrTyjrDt935YnFu4VBCVDhHtY2Y6rcy7x2TFeiRi" ], "public_key": "AiygKSRhZWTxxYT4AfgKoTG4TZAoPsWoEt6C6bLq4jJR", "software": "BigchainDB", - "version": "0.9.0" + "version": "0.9.0", } -API Root URL +API Root Endpoint ------------------- -If you send an HTTP GET request to the API Root URL -e.g. ``http://localhost:9984/api/v1/`` -or ``http://apihosting4u.net:9984/api/v1/``, +If you send an HTTP GET request to the API Root Endpoint +e.g. ``http://localhost:9984/api/v0.9/`` +or ``http://apihosting4u.net:9984/api/v0.9/``, then you should get an HTTP response -that allows you to discover the BigchainDB endpoints: +that allows you to discover the BigchainDB API endpoints: .. code-block:: json { "_links": { - "self": { "href": "/" }, - "transactions": { "href": "/transactions" }, - "statuses": { "href": "/statuses" }, "blocks": { "href": "/blocks" }, + "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, + "self": { "href": "/" }, + "statuses": { "href": "/statuses" }, + "transactions": { "href": "/transactions" }, "votes": { "href": "/votes" } + }, + "version" : "0.9.0" } Transactions @@ -455,3 +461,40 @@ Votes .. http:get:: /votes?block_id={block_id}&voter={voter} Description: TODO + + +Determining the API Root URL +---------------------------- + +When you start BigchainDB Server using ``bigchaindb start``, +an HTTP API is exposed at some address. The default is: + +`http://localhost:9984/api/v0.9/ `_ + +It's bound to ``localhost``, +so you can access it from the same machine, +but it won't be directly accessible from the outside world. +(The outside world could connect via a SOCKS proxy or whatnot.) + +The documentation about BigchainDB Server :any:`Configuration Settings` +has a section about how to set ``server.bind`` so as to make +the HTTP API publicly accessible. + +If the API endpoint is publicly accessible, +then the public API Root URL is determined as follows: + +- The public IP address (like 12.34.56.78) + is the public IP address of the machine exposing + the HTTP API to the public internet (e.g. either the machine hosting + Gunicorn or the machine running the reverse proxy such as Nginx). + It's determined by AWS, Azure, Rackspace, or whoever is hosting the machine. + +- The DNS hostname (like apihosting4u.net) is determined by DNS records, + such as an "A Record" associating apihosting4u.net with 12.34.56.78 + +- The port (like 9984) is determined by the ``server.bind`` setting + if Gunicorn is exposed directly to the public Internet. + If a reverse proxy (like Nginx) is exposed directly to the public Internet + instead, then it could expose the HTTP API on whatever port it wants to. + (It should expose the HTTP API on port 9984, but it's not bound to do + that by anything other than convention.) From e79a76512f1dd70f87918c0f6753c3f77b0f8827 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 2 Jan 2017 16:45:00 +0100 Subject: [PATCH 068/155] remove rudimentary note and typo's --- .../drivers-clients/http-client-server-api.rst | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 95f08bd7..0e3cb8a4 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -1,11 +1,10 @@ The HTTP Client-Server API ========================== -.. note:: - - The HTTP client-server API is currently quite rudimentary. For example, - there is no ability to do complex queries using the HTTP API. We plan to add - more querying capabilities in the future. +This page assumes you already know an API Root URL +for a BigchainDB node or reverse proxy. +It should be something like ``http://apihosting4u.net:9984`` +or ``http://12.34.56.78:9984``. If you set up a BigchainDB node or reverse proxy yourself, and you're not sure what the API Root URL is, @@ -119,7 +118,7 @@ Transactions A generalization of those parameters follows: - :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. @@ -141,7 +140,7 @@ Transactions This endpoint returns conditions only if the transaction they're in are included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query boolean fulfilled: A flag to indicate if transaction's with fulfilled conditions should be returned. + :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. @@ -159,7 +158,7 @@ Transactions :resheader Content-Type: ``application/json`` - :statuscode 200: A list of transaction's containing unfulfilled conditions was found and returned. + :statuscode 200: A list of transactions containing unfulfilled conditions was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``public_keys`` querystring was not included in the request. .. http:get:: /transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} @@ -196,7 +195,7 @@ Transactions :resheader Content-Type: ``application/json`` - :statuscode 200: A list of transaction's containing an asset with ID ``asset_id`` was found and returned. + :statuscode 200: A list of transactions containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. From be5bc9fafd1ac330feb1394591a7812bc354831c Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 2 Jan 2017 17:10:11 +0100 Subject: [PATCH 069/155] GET blocks?txid examples -> samples --- .../generate_http_server_api_documentation.py | 13 ++++ .../http-client-server-api.rst | 70 ++----------------- 2 files changed, 17 insertions(+), 66 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 350a286a..0716107a 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -114,6 +114,19 @@ Content-Type: application/json %(block)s """ +TPLS['get-block-txid-request'] = """\ +GET /blocks?tx_id=%(txid)s HTTP/1.1 +Host: example.com + +""" + +TPLS['get-block-txid-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +[%(block)s] +""" + def main(): """ Main function """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 0e3cb8a4..b11566c2 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -334,75 +334,13 @@ Blocks **Example request**: - .. sourcecode:: http - - GET /blocks?tx_id=2d431...0b4b0e HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-block-txid-request.http + :language: http **Example response**: - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "block":{ - "node_pubkey":"ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt", - "timestamp":"1479389911", - "transactions":[ - { - "transaction": { - "conditions": [ - { - "cid": 0, - "condition": { - "uri": "cc:4:20:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkk:96", - "details": { - "signature": null, - "type": "fulfillment", - "type_id": 4, - "bitmask": 32, - "public_key": "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - } - }, - "amount": 1, - "owners_after": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ], - "operation": "CREATE", - "asset": { - "divisible": false, - "updatable": false, - "data": null, - "id": "aebeab22-e672-4d3b-a187-bde5fda6533d", - "refillable": false - }, - "metadata": null, - "timestamp": "1477578978", - "fulfillments": [ - { - "fid": 0, - "input": null, - "fulfillment": "cf:4:GG-pi3CeIlySZhQoJVBh9O23PzrOuhnYI7OHqIbHjkn2VnQaEWvecO1x82Qr2Va_JjFywLKIOEV1Ob9Ofkeln2K89ny2mB-s7RLNvYAVzWNiQnp18_nQEUsvwACEXTYJ", - "owners_before": [ - "2ePYHfV3yS3xTxF9EE3Xjo8zPwq2RmLPFAJGQqQKc3j6" - ] - } - ] - }, - "id": "2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e", - "version": 1 - }], - "voters":[ - "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" - ] - }, - "id":"6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202", - "signature":"53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" - } + .. literalinclude:: samples/get-block-txid-response.http + :language: http :resheader Content-Type: ``application/json`` From b252c4079358d514653a073cdf924fc0ab91b7ba Mon Sep 17 00:00:00 2001 From: diminator Date: Tue, 3 Jan 2017 17:20:16 +0100 Subject: [PATCH 070/155] GET /votes examples -> samples --- .../generate_http_server_api_documentation.py | 34 ++++++++++++++++++- .../http-client-server-api.rst | 31 +++-------------- 2 files changed, 38 insertions(+), 27 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 0716107a..c6c9b63f 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -5,9 +5,11 @@ import os import os.path from bigchaindb.common.transaction import Transaction, Input, TransactionLink +from bigchaindb.core import Bigchain from bigchaindb.models import Block + TPLS = {} @@ -80,6 +82,7 @@ Host: example.com """ + TPLS['get-statuses-tx-invalid-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json @@ -107,6 +110,7 @@ Host: example.com """ + TPLS['get-block-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json @@ -114,12 +118,14 @@ Content-Type: application/json %(block)s """ + TPLS['get-block-txid-request'] = """\ GET /blocks?tx_id=%(txid)s HTTP/1.1 Host: example.com """ + TPLS['get-block-txid-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json @@ -128,8 +134,25 @@ Content-Type: application/json """ +TPLS['get-vote-request'] = """\ +GET /votes?block_id=%(blockid)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-vote-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +[%(vote)s] +""" + + def main(): """ Main function """ + + # tx create privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' pubkey = '4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD' asset = {'msg': 'Hello BigchainDB!'} @@ -137,6 +160,7 @@ def main(): tx = tx.sign([privkey]) tx_json = json.dumps(tx.to_dict(), indent=2, sort_keys=True) + # tx transfer privkey_transfer = '3AeWpPdhEZzWLYfkfYHBfMFC2r1f8HEaGS9NtbbKssya' pubkey_transfer = '3yfQPHeWAa1MxTX9Zf9176QqcpcnWcanVZZbaHb8B3h9' @@ -159,6 +183,7 @@ def main(): tx_transfer_last = tx_transfer_last.sign([privkey_transfer]) tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) + # block node = "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" signature = "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" block = Block(transactions=[tx], node_pubkey=node, voters=[node], signature=signature) @@ -167,6 +192,12 @@ def main(): base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') + # vote + DUMMY_SHA3 = '0123456789abcdef' * 4 + b = Bigchain(public_key=node) + vote = b.vote(block.id, DUMMY_SHA3, True) + vote_json = json.dumps(vote, indent=2, sort_keys=True) + if not os.path.exists(base_path): os.makedirs(base_path) @@ -182,7 +213,8 @@ def main(): 'public_keys_transfer': tx_transfer.outputs[0].public_keys[0], 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0], 'block': block_json, - 'blockid': block.id} + 'blockid': block.id, + 'vote': vote_json} with open(path, 'w') as handle: handle.write(code) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index b11566c2..90ccc58c 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -26,7 +26,7 @@ with something like the following in the body: { "_links": { "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" } - } + }, "keyring": [ "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", "AdDuyrTyjrDt935YnFu4VBCVDhHtY2Y6rcy7x2TFeiRi" @@ -365,29 +365,13 @@ Votes **Example request**: - .. sourcecode:: http - - GET /votes?block_id=6152f...e7202 HTTP/1.1 - Host: example.com + .. literalinclude:: samples/get-vote-request.http + :language: http **Example response**: - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - [{ - "node_pubkey": "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" , - "signature": "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA", - "vote": { - "invalid_reason": null , - "is_block_valid": true , - "previous_block": "6152fbc7e0f7686512ed6b92c01e8c73ea1e3f51a7b037ac5cc8c860215e7202" , - "timestamp": "1480082692" , - "voting_for_block": "6152f...e7202" - } - }] + .. literalinclude:: samples/get-vote-response.http + :language: http :resheader Content-Type: ``application/json`` @@ -395,11 +379,6 @@ Votes :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/votes``, without defining ``block_id``. -.. http:get:: /votes?block_id={block_id}&voter={voter} - - Description: TODO - - Determining the API Root URL ---------------------------- From 14f22cb8afe834935bab2756797dc74eda7a741d Mon Sep 17 00:00:00 2001 From: diminator Date: Tue, 3 Jan 2017 17:25:40 +0100 Subject: [PATCH 071/155] status with block and transaction context --- .../generate_http_server_api_documentation.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index c6c9b63f..d51050d3 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -88,7 +88,10 @@ HTTP/1.1 200 OK Content-Type: application/json { - "status": "invalid" + "status": "invalid", + "_links" : { + "block": "/blocks/%(blockid)s" + } } """ @@ -99,7 +102,11 @@ Content-Type: application/json Location: ../transactions/%(txid)s { - "status": "valid" + "status": "valid", + "_links" : { + "tx" : "/transactions/%(txid)s", + "block": "/blocks/%(blockid)s" + } } """ @@ -189,15 +196,14 @@ def main(): block = Block(transactions=[tx], node_pubkey=node, voters=[node], signature=signature) block_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) - base_path = os.path.join(os.path.dirname(__file__), - 'source/drivers-clients/samples') - # vote DUMMY_SHA3 = '0123456789abcdef' * 4 b = Bigchain(public_key=node) vote = b.vote(block.id, DUMMY_SHA3, True) vote_json = json.dumps(vote, indent=2, sort_keys=True) + base_path = os.path.join(os.path.dirname(__file__), + 'source/drivers-clients/samples') if not os.path.exists(base_path): os.makedirs(base_path) From 6aca7e2605da97706b59892830fc7fb9ba10b2fa Mon Sep 17 00:00:00 2001 From: diminator Date: Tue, 3 Jan 2017 17:50:20 +0100 Subject: [PATCH 072/155] list assets recipe and sample --- .../generate_http_server_api_documentation.py | 14 +++++++ .../http-client-server-api.rst | 37 ++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index d51050d3..6376ae1c 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -59,6 +59,20 @@ Content-Type: application/json %(tx_transfer_last)s] """ +TPLS['get-assets-request'] = """\ +GET /transactions?operation=CREATE&is_asset=true&public_keys=%(public_keys)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-assets-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +[%(tx)s] +""" + TPLS['post-tx-request'] = """\ POST /transactions/ HTTP/1.1 diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 90ccc58c..45821afc 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -106,7 +106,8 @@ Transactions that include: * `Unfulfilled outputs <#get--transactions?fulfilled=false&public_keys=public_keys>`_ - * `Transactions related to a specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ + * `Transactions related to a specific asset <#get--transactions?operation=GENESIS|CREATE|TRANSFER&asset_id=asset_id>`_ + * `Listing of assets <#get--transactions?operation=CREATE&is_asset=true&public_keys=public_keys>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. @@ -120,12 +121,15 @@ Transactions :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. + :query boolean is_asset: A flag to indicate if the ``asset`` field of the transaction is ``null`` or not. + :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. + :statuscode 404: BigchainDB does not expose this endpoint. @@ -198,6 +202,37 @@ Transactions :statuscode 200: A list of transactions containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. +.. http:get:: /transactions?operation=CREATE&is_asset=true&public_keys={public_keys} + + Get a list of ``CREATE`` transactions that have the asset field defined. + This can serve as a recipe for retrieving your list of assets. + Currently, filtering on specific fields in the ``asset`` or ``metadata`` is assumed to be done clientside. + + This endpoint returns assets only if the transaction they're in are + included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + + :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. + + :query boolean is_asset: A flag to indicate if the ``asset`` field of the transaction is ``null`` or not. + + :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. + + + **Example request**: + + .. literalinclude:: samples/get-assets-request.http + :language: http + + **Example response**: + + .. literalinclude:: samples/get-assets-response.http + :language: http + + + :resheader Content-Type: ``application/json`` + + :statuscode 200: A list of transactions containing an asset and ``public_keys`` found and returned. + :statuscode 400: The request wasn't understood by the server, e.g. the ``is_asset`` querystring was not included in the request. .. http:post:: /transactions From 0ce9cc4f551d8e985b2fe2861e518bc2de4ef00a Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 4 Jan 2017 10:55:51 +0100 Subject: [PATCH 073/155] Return transaction if it's in backlog also --- .../source/drivers-clients/http-client-server-api.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 45821afc..e5a552a4 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -67,7 +67,7 @@ Transactions Get the transaction with the ID ``tx_id``. - This endpoint returns only a transaction from a ``VALID`` or ``UNDECIDED`` + This endpoint returns only a transaction from the ``BACKLOG`` or a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. A transaction itself doesn't include a ``timestamp`` property. Only the @@ -142,7 +142,7 @@ Transactions an empty list. This endpoint returns conditions only if the transaction they're in are - included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. @@ -170,7 +170,7 @@ Transactions Get a list of transactions that use an asset with the ID ``asset_id``. This endpoint returns assets only if the transaction they're in are - included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. .. note:: The BigchainDB API currently doesn't expose an @@ -209,7 +209,7 @@ Transactions Currently, filtering on specific fields in the ``asset`` or ``metadata`` is assumed to be done clientside. This endpoint returns assets only if the transaction they're in are - included in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. + included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. From 8c46cc3fb4fcda21bf9e9bc3d539403b3421a4cb Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 4 Jan 2017 10:59:33 +0100 Subject: [PATCH 074/155] (fix): travis error on keypair --- docs/server/generate_http_server_api_documentation.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 6376ae1c..7d8c0ad9 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -205,14 +205,15 @@ def main(): tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) # block - node = "ErEeVZt8AfLbMJub25tjNxbpzzTNp3mGidL3GxGdd9bt" + node_private = "5G2kE1zJAgTajkVSbPAQWo4c2izvtwqaNHYsaNpbbvxX" + node_public = "DngBurxfeNVKZWCEcDnLj1eMPAS7focUZTE5FndFGuHT" signature = "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" - block = Block(transactions=[tx], node_pubkey=node, voters=[node], signature=signature) + block = Block(transactions=[tx], node_pubkey=node_public, voters=[node_public], signature=signature) block_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) # vote DUMMY_SHA3 = '0123456789abcdef' * 4 - b = Bigchain(public_key=node) + b = Bigchain(public_key=node_public) vote = b.vote(block.id, DUMMY_SHA3, True) vote_json = json.dumps(vote, indent=2, sort_keys=True) From 940a0cd4dff141535c60291fede373d7ed6d5dcd Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 4 Jan 2017 11:00:08 +0100 Subject: [PATCH 075/155] (fix): add private_key of node to bigchain instance --- docs/server/generate_http_server_api_documentation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 7d8c0ad9..64899535 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -213,7 +213,7 @@ def main(): # vote DUMMY_SHA3 = '0123456789abcdef' * 4 - b = Bigchain(public_key=node_public) + b = Bigchain(public_key=node_public, private_key=node_private) vote = b.vote(block.id, DUMMY_SHA3, True) vote_json = json.dumps(vote, indent=2, sort_keys=True) From 305adba3a419b39a85b7e1de8b5bcd004d580f2d Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 4 Jan 2017 11:02:50 +0100 Subject: [PATCH 076/155] include metadata in samples --- docs/server/generate_http_server_api_documentation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 64899535..aa9b5ccc 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -177,7 +177,7 @@ def main(): privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' pubkey = '4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD' asset = {'msg': 'Hello BigchainDB!'} - tx = Transaction.create([pubkey], [([pubkey], 1)], asset=asset) + tx = Transaction.create([pubkey], [([pubkey], 1)], asset=asset, metadata={'sequence': 0}) tx = tx.sign([privkey]) tx_json = json.dumps(tx.to_dict(), indent=2, sort_keys=True) @@ -189,7 +189,7 @@ def main(): input_ = Input(fulfillment=tx.outputs[cid].fulfillment, fulfills=TransactionLink(txid=tx.id, output=cid), owners_before=tx.outputs[cid].public_keys) - tx_transfer = Transaction.transfer([input_], [([pubkey_transfer], 1)], asset_id=tx.id) + tx_transfer = Transaction.transfer([input_], [([pubkey_transfer], 1)], asset_id=tx.id, metadata={'sequence': 1}) tx_transfer = tx_transfer.sign([privkey]) tx_transfer_json = json.dumps(tx_transfer.to_dict(), indent=2, sort_keys=True) @@ -200,7 +200,7 @@ def main(): input_ = Input(fulfillment=tx_transfer.outputs[cid].fulfillment, fulfills=TransactionLink(txid=tx_transfer.id, output=cid), owners_before=tx_transfer.outputs[cid].public_keys) - tx_transfer_last = Transaction.transfer([input_], [([pubkey_transfer_last], 1)], asset_id=tx.id) + tx_transfer_last = Transaction.transfer([input_], [([pubkey_transfer_last], 1)], asset_id=tx.id, metadata={'sequence': 2}) tx_transfer_last = tx_transfer_last.sign([privkey_transfer]) tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) From 5fa3cddbb7fadd12b4de7750e5b1ac70f4b47412 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 4 Jan 2017 11:29:42 +0100 Subject: [PATCH 077/155] transactions and blocks root endpoints --- .../http-client-server-api.rst | 98 ++++++++++++++----- 1 file changed, 74 insertions(+), 24 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index e5a552a4..3eef71fb 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -3,8 +3,8 @@ The HTTP Client-Server API This page assumes you already know an API Root URL for a BigchainDB node or reverse proxy. -It should be something like ``http://apihosting4u.net:9984`` -or ``http://12.34.56.78:9984``. +It should be something like ``https://example.com:9984`` +or ``https://12.34.56.78:9984``. If you set up a BigchainDB node or reverse proxy yourself, and you're not sure what the API Root URL is, @@ -14,11 +14,11 @@ then see the last section of this page for help. BigchainDB Root URL ------------------- -If you send an HTTP GET request to the API Root URL -e.g. ``http://localhost:9984`` -or ``http://apihosting4u.net:9984`` -(with no ``/api/v1/`` on the end), -then you should get an HTTP response +If you send an HTTP GET request to the BigchainDB Root URL +e.g. ``http://localhost:9984`` +or ``https://example.com:9984`` +(with no ``/api/v1/`` on the end), +then you should get an HTTP response with something like the following in the body: .. code-block:: json @@ -42,7 +42,7 @@ API Root Endpoint If you send an HTTP GET request to the API Root Endpoint e.g. ``http://localhost:9984/api/v0.9/`` -or ``http://apihosting4u.net:9984/api/v0.9/``, +or ``https://example.com:9984/api/v0.9/``, then you should get an HTTP response that allows you to discover the BigchainDB API endpoints: @@ -50,12 +50,12 @@ that allows you to discover the BigchainDB API endpoints: { "_links": { - "blocks": { "href": "/blocks" }, + "blocks": { "href": "https://example.com:9984/api/v0.9/blocks" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "self": { "href": "/" }, - "statuses": { "href": "/statuses" }, - "transactions": { "href": "/transactions" }, - "votes": { "href": "/votes" } + "self": { "href": "https://example.com:9984/api/v0.9" }, + "statuses": { "href": "https://example.com:9984/api/v0.9/statuses" }, + "transactions": { "href": "https://example.com:9984/api/v0.9/transactions" }, + "votes": { "href": "https://example.com:9984/api/v0.9/votes" } }, "version" : "0.9.0" } @@ -96,12 +96,40 @@ Transactions .. http:get:: /transactions - The current ``/transactions`` endpoint returns a ``404 Not Found`` HTTP - status code. Eventually, this functionality will get implemented. + The unfiltered ``/transactions`` endpoint without any query parameters + returns a list of available transaction usages and relevant endpoints. We believe a PUSH rather than a PULL pattern is more appropriate, as the items returned in the collection would change by the second. - There are however requests that might come of use, given the endpoint is + **Example request**: + + .. sourcecode:: http + + GET /transactions HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "_links": { + "asset_history": { "href": "https://example.com:9984/api/v0.9/transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id}" }, + "asset_list": { "href": "https://example.com:9984/api/v0.9/transactions?operation=CREATE&is_asset=true&public_keys={public_keys}" }, + "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, + "item": { "href": "https://example.com:9984/api/v0.9/transactions/{tx_id}" }, + "self": { "href": "https://example.com:9984/api/v0.9/transactions" }, + "unfulfilled": { "href": "https://example.com:9984/api/v0.9/transactions?fulfilled=false&public_keys={public_keys}" } + }, + "version" : "0.9.0" + } + + :statuscode 200: BigchainDB transactions root endpoint. + + There are however filtered requests that might come of use, given the endpoint is queried correctly. Some of them include retrieving a list of transactions that include: @@ -130,9 +158,6 @@ Transactions :query string asset_id: asset ID. - :statuscode 404: BigchainDB does not expose this endpoint. - - .. http:get:: /transactions?fulfilled=false&public_keys={public_keys} Get a list of transactions with unfulfilled conditions. @@ -344,12 +369,37 @@ Blocks .. http:get:: /blocks - The current ``/blocks`` endpoint returns a ``404 Not Found`` HTTP status - code. Eventually, this functionality will get implemented. + The unfiltered ``/blocks`` endpoint without any query parameters + returns a list of available block usages and relevant endpoints. We believe a PUSH rather than a PULL pattern is more appropriate, as the items returned in the collection would change by the second. - :statuscode 404: BigchainDB does not expose this endpoint. + + **Example request**: + + .. sourcecode:: http + + GET /blocks HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "_links": { + "blocks": { "href": "https://example.com:9984/api/v0.9/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}" }, + "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, + "item": { "href": "https://example.com:9984/api/v0.9/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}" }, + "self": { "href": "https://example.com:9984/api/v0.9/blocks" } + }, + "version" : "0.9.0" + } + + :statuscode 200: BigchainDB blocks root endpoint. .. http:get:: /blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID} @@ -440,8 +490,8 @@ then the public API Root URL is determined as follows: Gunicorn or the machine running the reverse proxy such as Nginx). It's determined by AWS, Azure, Rackspace, or whoever is hosting the machine. -- The DNS hostname (like apihosting4u.net) is determined by DNS records, - such as an "A Record" associating apihosting4u.net with 12.34.56.78 +- The DNS hostname (like example.com) is determined by DNS records, + such as an "A Record" associating example.com with 12.34.56.78 - The port (like 9984) is determined by the ``server.bind`` setting if Gunicorn is exposed directly to the public Internet. From 9e5623f881a952512431ef0c4981b994faa8f842 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 10:36:34 +0100 Subject: [PATCH 078/155] Removed X-bigchaindb-timestamp --- docs/server/generate_http_server_api_documentation.py | 1 - .../source/drivers-clients/http-client-server-api.rst | 6 ------ 2 files changed, 7 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index aa9b5ccc..6f5ad04c 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -23,7 +23,6 @@ Host: example.com TPLS['get-tx-id-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json -X-BigchainDB-Timestamp: 1482766245 %(tx)s """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 3eef71fb..c2e9cd60 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -70,11 +70,6 @@ Transactions This endpoint returns only a transaction from the ``BACKLOG`` or a ``VALID`` or ``UNDECIDED`` block on ``bigchain``, if exists. - A transaction itself doesn't include a ``timestamp`` property. Only the - block a transaction was included in has a unix ``timestamp`` property. It is - returned by this endpoint in a HTTP custom entity header called - ``X-BigchainDB-Timestamp``. - :param tx_id: transaction ID :type tx_id: hex string @@ -88,7 +83,6 @@ Transactions .. literalinclude:: samples/get-tx-id-response.http :language: http - :resheader X-BigchainDB-Timestamp: A unix timestamp describing when a transaction was included into a valid block. The timestamp provided is taken from the block the transaction was included in. :resheader Content-Type: ``application/json`` :statuscode 200: A transaction with that ID was found. From f17a7226343cbfb55026924ea8c0cd66ab679426 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 10:52:22 +0100 Subject: [PATCH 079/155] remove is_asset --- .../http-client-server-api.rst | 37 +------------------ 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index c2e9cd60..7b91c69d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -111,8 +111,7 @@ Transactions { "_links": { - "asset_history": { "href": "https://example.com:9984/api/v0.9/transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id}" }, - "asset_list": { "href": "https://example.com:9984/api/v0.9/transactions?operation=CREATE&is_asset=true&public_keys={public_keys}" }, + "assets": { "href": "https://example.com:9984/api/v0.9/transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id}" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, "item": { "href": "https://example.com:9984/api/v0.9/transactions/{tx_id}" }, "self": { "href": "https://example.com:9984/api/v0.9/transactions" }, @@ -129,7 +128,6 @@ Transactions * `Unfulfilled outputs <#get--transactions?fulfilled=false&public_keys=public_keys>`_ * `Transactions related to a specific asset <#get--transactions?operation=GENESIS|CREATE|TRANSFER&asset_id=asset_id>`_ - * `Listing of assets <#get--transactions?operation=CREATE&is_asset=true&public_keys=public_keys>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. @@ -143,8 +141,6 @@ Transactions :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. - :query boolean is_asset: A flag to indicate if the ``asset`` field of the transaction is ``null`` or not. - :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. @@ -221,37 +217,6 @@ Transactions :statuscode 200: A list of transactions containing an asset with ID ``asset_id`` was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. -.. http:get:: /transactions?operation=CREATE&is_asset=true&public_keys={public_keys} - - Get a list of ``CREATE`` transactions that have the asset field defined. - This can serve as a recipe for retrieving your list of assets. - Currently, filtering on specific fields in the ``asset`` or ``metadata`` is assumed to be done clientside. - - This endpoint returns assets only if the transaction they're in are - included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - - :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. - - :query boolean is_asset: A flag to indicate if the ``asset`` field of the transaction is ``null`` or not. - - :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - - - **Example request**: - - .. literalinclude:: samples/get-assets-request.http - :language: http - - **Example response**: - - .. literalinclude:: samples/get-assets-response.http - :language: http - - - :resheader Content-Type: ``application/json`` - - :statuscode 200: A list of transactions containing an asset and ``public_keys`` found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``is_asset`` querystring was not included in the request. .. http:post:: /transactions From 6ea7b8a411339901155ae65aae11dcce10ccd0c2 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 11:08:21 +0100 Subject: [PATCH 080/155] remove is_assets sample --- .../generate_http_server_api_documentation.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 6f5ad04c..40204c8b 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -58,21 +58,6 @@ Content-Type: application/json %(tx_transfer_last)s] """ -TPLS['get-assets-request'] = """\ -GET /transactions?operation=CREATE&is_asset=true&public_keys=%(public_keys)s HTTP/1.1 -Host: example.com - -""" - - -TPLS['get-assets-response'] = """\ -HTTP/1.1 200 OK -Content-Type: application/json - -[%(tx)s] -""" - - TPLS['post-tx-request'] = """\ POST /transactions/ HTTP/1.1 Host: example.com From df94427ccaf2cc72f15bc79f0def33fe3162e77d Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 12:17:15 +0100 Subject: [PATCH 081/155] fulfilled conditions -> unspent outputs --- .../generate_http_server_api_documentation.py | 6 ++--- .../http-client-server-api.rst | 27 ++++++++++--------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 40204c8b..37d5facc 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -28,14 +28,14 @@ Content-Type: application/json """ -TPLS['get-tx-unfulfilled-request'] = """\ -GET /transactions?fulfilled=false&public_keys=%(public_keys_transfer_last)s HTTP/1.1 +TPLS['get-tx-unspent-request'] = """\ +GET /transactions?unspent=true&public_keys=%(public_keys_transfer_last)s HTTP/1.1 Host: example.com """ -TPLS['get-tx-unfulfilled-response'] = """\ +TPLS['get-tx-unspent-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 7b91c69d..76e3e74a 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -115,7 +115,7 @@ Transactions "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, "item": { "href": "https://example.com:9984/api/v0.9/transactions/{tx_id}" }, "self": { "href": "https://example.com:9984/api/v0.9/transactions" }, - "unfulfilled": { "href": "https://example.com:9984/api/v0.9/transactions?fulfilled=false&public_keys={public_keys}" } + "unspent": { "href": "https://example.com:9984/api/v0.9/transactions?unspent=true&public_keys={public_keys}" } }, "version" : "0.9.0" } @@ -126,7 +126,7 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Unfulfilled outputs <#get--transactions?fulfilled=false&public_keys=public_keys>`_ + * `Unspent outputs <#get--transactions?unspent=true&public_keys=public_keys>`_ * `Transactions related to a specific asset <#get--transactions?operation=GENESIS|CREATE|TRANSFER&asset_id=asset_id>`_ In this section, we've listed those particular requests, as they will likely @@ -139,7 +139,7 @@ Transactions A generalization of those parameters follows: - :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. + :query boolean unspent: A flag to indicate whether only transactions with unspent outputs should be returned. :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. @@ -148,36 +148,37 @@ Transactions :query string asset_id: asset ID. -.. http:get:: /transactions?fulfilled=false&public_keys={public_keys} +.. http:get:: /transactions?unspent=true&public_keys={public_keys} - Get a list of transactions with unfulfilled conditions. + Get a list of transactions with unspent outputs. - If the querystring ``fulfilled`` is set to ``false`` and all conditions for - ``public_keys`` happen to be fulfilled already, this endpoint will return - an empty list. + If the querystring ``unspent`` is set to ``false`` and all outputs for + ``public_keys`` happen to be spent already, this endpoint will return + an empty list. Transactions with multiple outputs that have not all been spent + will be included in the response. - This endpoint returns conditions only if the transaction they're in are + This endpoint returns transactions only if they are included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - :query boolean fulfilled: A flag to indicate if transactions with fulfilled conditions should be returned. + :query boolean unspent: A flag to indicate if transactions with unspent outputs should be returned. :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. **Example request**: - .. literalinclude:: samples/get-tx-unfulfilled-request.http + .. literalinclude:: samples/get-tx-unspent-request.http :language: http **Example response**: - .. literalinclude:: samples/get-tx-unfulfilled-response.http + .. literalinclude:: samples/get-tx-unspent-response.http :language: http :resheader Content-Type: ``application/json`` - :statuscode 200: A list of transactions containing unfulfilled conditions was found and returned. + :statuscode 200: A list of transactions containing unspent outputs was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``public_keys`` querystring was not included in the request. .. http:get:: /transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} From 7576210c82dfb7ec6c6adfbfacca45c5ed3aa00c Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 13:39:38 +0100 Subject: [PATCH 082/155] remove GENESIS from operations --- .../source/drivers-clients/http-client-server-api.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 76e3e74a..8437cfc9 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -111,7 +111,7 @@ Transactions { "_links": { - "assets": { "href": "https://example.com:9984/api/v0.9/transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id}" }, + "assets": { "href": "https://example.com:9984/api/v0.9/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, "item": { "href": "https://example.com:9984/api/v0.9/transactions/{tx_id}" }, "self": { "href": "https://example.com:9984/api/v0.9/transactions" }, @@ -127,7 +127,7 @@ Transactions that include: * `Unspent outputs <#get--transactions?unspent=true&public_keys=public_keys>`_ - * `Transactions related to a specific asset <#get--transactions?operation=GENESIS|CREATE|TRANSFER&asset_id=asset_id>`_ + * `Transactions related to a specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. @@ -143,7 +143,7 @@ Transactions :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. + :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. @@ -181,7 +181,7 @@ Transactions :statuscode 200: A list of transactions containing unspent outputs was found and returned. :statuscode 400: The request wasn't understood by the server, e.g. the ``public_keys`` querystring was not included in the request. -.. http:get:: /transactions?operation={GENESIS|CREATE|TRANSFER}&asset_id={asset_id} +.. http:get:: /transactions?operation={CREATE|TRANSFER}&asset_id={asset_id} Get a list of transactions that use an asset with the ID ``asset_id``. @@ -199,7 +199,7 @@ Transactions any case only be one transaction returned (in a list though, since ``/transactions`` is a list-returning endpoint). - :query string operation: One of the three supported operations of a transaction: ``GENESIS``, ``CREATE``, ``TRANSFER``. + :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. From 9d6ca861a7939e74bd4940610a9c7d1dca325667 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 13:52:03 +0100 Subject: [PATCH 083/155] Note on retrieving the list of assets --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 8437cfc9..a17486d0 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -198,6 +198,8 @@ Transactions ``/transactions?operation=CREATE&asset_id={asset_id}``, there will in any case only be one transaction returned (in a list though, since ``/transactions`` is a list-returning endpoint). + Leaving out the ``asset_id`` query and calling + ``/transactions?operation=CREATE`` returns the list of assets. :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. From 1ef2da7c32248c54d1dbd377ea2736506f69e714 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 14:22:37 +0100 Subject: [PATCH 084/155] mention history and provenance --- .../server/source/drivers-clients/http-client-server-api.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index a17486d0..3a3bdd71 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -184,8 +184,11 @@ Transactions .. http:get:: /transactions?operation={CREATE|TRANSFER}&asset_id={asset_id} Get a list of transactions that use an asset with the ID ``asset_id``. + Every ``TRANSFER`` transaction that originates from a ``CREATE`` transaction + with ``asset_id`` will be included. This allows users to query the entire history or + provenance of an asset. - This endpoint returns assets only if the transaction they're in are + This endpoint returns transactions only if they are included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. .. note:: From 005a164e6b86174719a6cf0a2fa31c937f9a1072 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 15:15:17 +0100 Subject: [PATCH 085/155] additional info on INVALID block --- .../server/source/drivers-clients/http-client-server-api.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 3a3bdd71..f60c5f0e 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -303,12 +303,13 @@ Blocks Get the block with the ID ``block_id``. .. note:: - As ``status``'s default value is set to ``VALID``, only ``VALID`` blocks + As ``status``'s default value is set to ``VALID``, hence only ``VALID`` blocks will be returned by this endpoint. In case ``status=VALID``, but a block that was labeled ``UNDECIDED`` or ``INVALID`` is requested by ``block_id``, this endpoint will return a ``404 Not Found`` status code to warn the user. To check a block's status independently, use the - `Statuses endpoint <#get--statuses-tx_id|block_id>`_. + `Statuses endpoint <#get--statuses-tx_id|block_id>`_. The ``INVALID`` status + can be handy to figure out why the block was rejected. :param block_id: block ID :type block_id: hex string From fde3d21ba71776fd55fbcc0c07c69f3a43477028 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 15:22:22 +0100 Subject: [PATCH 086/155] POST /transactions returns statuses payload --- docs/server/generate_http_server_api_documentation.py | 4 ++++ docs/server/source/drivers-clients/http-client-server-api.rst | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 37d5facc..65ce61c0 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -71,6 +71,10 @@ TPLS['post-tx-response'] = """\ HTTP/1.1 202 Accepted Content-Type: application/json Location: ../statuses/%(txid)s + +{ + "status": "/statuses/%(txid)s" +} """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index f60c5f0e..5d59b85d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -226,7 +226,8 @@ Transactions .. http:post:: /transactions - Push a new transaction. + Push a new transaction. The endpoint will return a ``statuses`` endpoint to track + the status of the transaction. .. note:: The posted transaction should be valid `transaction From 6cf39542eae6fec3a9b1bb41242cf0596e47af67 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 5 Jan 2017 16:06:27 +0100 Subject: [PATCH 087/155] improve wording on post transactions status codes --- .../source/drivers-clients/http-client-server-api.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 5d59b85d..24e354c7 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -247,8 +247,11 @@ Transactions .. literalinclude:: samples/post-tx-response.http :language: http - :statuscode 202: The pushed transaction was accepted, but the processing has not been completed. - :statuscode 400: The transaction was invalid and not created. + :resheader Content-Type: ``application/json`` + :resheader Location: As the transaction will be persisted asynchronously, an endpoint to monitor its status is provided in this header. + + :statuscode 202: The pushed transaction was accepted in the ``BACKLOG``, but the processing has not been completed. + :statuscode 400: The transaction was malformed and not accepted in the ``BACKLOG``. Statuses From 8bbaa0e40ed210b2c956c55e94d294ad3bbf64e3 Mon Sep 17 00:00:00 2001 From: diminator Date: Fri, 6 Jan 2017 11:58:34 +0100 Subject: [PATCH 088/155] status endpoint query params and remove links --- .../generate_http_server_api_documentation.py | 17 +++++------------ .../drivers-clients/http-client-server-api.rst | 7 ++++--- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 65ce61c0..ed76ed15 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -70,16 +70,16 @@ Content-Type: application/json TPLS['post-tx-response'] = """\ HTTP/1.1 202 Accepted Content-Type: application/json -Location: ../statuses/%(txid)s +Location: ../statuses?tx_id=%(txid)s { - "status": "/statuses/%(txid)s" + "status": "/statuses?tx_id=%(txid)s" } """ TPLS['get-statuses-tx-request'] = """\ -GET /statuses/%(txid)s HTTP/1.1 +GET /statuses?tx_id=%(txid)s HTTP/1.1 Host: example.com """ @@ -90,10 +90,7 @@ HTTP/1.1 200 OK Content-Type: application/json { - "status": "invalid", - "_links" : { - "block": "/blocks/%(blockid)s" - } + "status": "invalid" } """ @@ -104,11 +101,7 @@ Content-Type: application/json Location: ../transactions/%(txid)s { - "status": "valid", - "_links" : { - "tx" : "/transactions/%(txid)s", - "block": "/blocks/%(blockid)s" - } + "status": "valid" } """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 24e354c7..5cbb7bed 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -257,12 +257,13 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses/{tx_id|block_id} +.. http:get:: /statuses?tx_id={tx_id}|block_id={block_id} Get the status of an asynchronously written resource by their id. Supports the retrieval of a status for a transaction using ``tx_id`` or the - retrieval of a status for a block using ``block_id``. + retrieval of a status for a block using ``block_id``. Only use exactly one of both + queries, as they are required but mutually exclusive. The possible status values are ``backlog``, ``undecided``, ``valid`` or ``invalid``. @@ -312,7 +313,7 @@ Blocks that was labeled ``UNDECIDED`` or ``INVALID`` is requested by ``block_id``, this endpoint will return a ``404 Not Found`` status code to warn the user. To check a block's status independently, use the - `Statuses endpoint <#get--statuses-tx_id|block_id>`_. The ``INVALID`` status + `Statuses endpoint <#get--statuses?tx_id=tx_id|block_id=block_id>`_. The ``INVALID`` status can be handy to figure out why the block was rejected. :param block_id: block ID From cb4207fb32ab324942451a2411ae14e590e6315e Mon Sep 17 00:00:00 2001 From: diminator Date: Fri, 6 Jan 2017 13:55:17 +0100 Subject: [PATCH 089/155] version 0.9 to api version 1 --- .../http-client-server-api.rst | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 5cbb7bed..5bde1207 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -41,8 +41,8 @@ API Root Endpoint ------------------- If you send an HTTP GET request to the API Root Endpoint -e.g. ``http://localhost:9984/api/v0.9/`` -or ``https://example.com:9984/api/v0.9/``, +e.g. ``http://localhost:9984/api/v1/`` +or ``https://example.com:9984/api/v1/``, then you should get an HTTP response that allows you to discover the BigchainDB API endpoints: @@ -50,12 +50,12 @@ that allows you to discover the BigchainDB API endpoints: { "_links": { - "blocks": { "href": "https://example.com:9984/api/v0.9/blocks" }, + "blocks": { "href": "https://example.com:9984/api/v1/blocks" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "self": { "href": "https://example.com:9984/api/v0.9" }, - "statuses": { "href": "https://example.com:9984/api/v0.9/statuses" }, - "transactions": { "href": "https://example.com:9984/api/v0.9/transactions" }, - "votes": { "href": "https://example.com:9984/api/v0.9/votes" } + "self": { "href": "https://example.com:9984/api/v1" }, + "statuses": { "href": "https://example.com:9984/api/v1/statuses" }, + "transactions": { "href": "https://example.com:9984/api/v1/transactions" }, + "votes": { "href": "https://example.com:9984/api/v1/votes" } }, "version" : "0.9.0" } @@ -111,11 +111,11 @@ Transactions { "_links": { - "assets": { "href": "https://example.com:9984/api/v0.9/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}" }, + "assets": { "href": "https://example.com:9984/api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "item": { "href": "https://example.com:9984/api/v0.9/transactions/{tx_id}" }, - "self": { "href": "https://example.com:9984/api/v0.9/transactions" }, - "unspent": { "href": "https://example.com:9984/api/v0.9/transactions?unspent=true&public_keys={public_keys}" } + "item": { "href": "https://example.com:9984/api/v1/transactions/{tx_id}" }, + "self": { "href": "https://example.com:9984/api/v1/transactions" }, + "unspent": { "href": "https://example.com:9984/api/v1/transactions?unspent=true&public_keys={public_keys}" } }, "version" : "0.9.0" } @@ -362,10 +362,10 @@ Blocks { "_links": { - "blocks": { "href": "https://example.com:9984/api/v0.9/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}" }, + "blocks": { "href": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}" }, "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "item": { "href": "https://example.com:9984/api/v0.9/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}" }, - "self": { "href": "https://example.com:9984/api/v0.9/blocks" } + "item": { "href": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}" }, + "self": { "href": "https://example.com:9984/api/v1/blocks" } }, "version" : "0.9.0" } @@ -441,7 +441,7 @@ Determining the API Root URL When you start BigchainDB Server using ``bigchaindb start``, an HTTP API is exposed at some address. The default is: -`http://localhost:9984/api/v0.9/ `_ +`http://localhost:9984/api/v1/ `_ It's bound to ``localhost``, so you can access it from the same machine, From 7d7a05c7064c5782e595952ff9d3f63ff7f11335 Mon Sep 17 00:00:00 2001 From: Dimitri De Jonghe Date: Fri, 6 Jan 2017 14:45:15 +0100 Subject: [PATCH 090/155] remove href from links --- .../http-client-server-api.rst | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 5bde1207..15cf8a1d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -25,7 +25,7 @@ with something like the following in the body: { "_links": { - "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" } + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" }, "keyring": [ "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", @@ -50,12 +50,12 @@ that allows you to discover the BigchainDB API endpoints: { "_links": { - "blocks": { "href": "https://example.com:9984/api/v1/blocks" }, - "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "self": { "href": "https://example.com:9984/api/v1" }, - "statuses": { "href": "https://example.com:9984/api/v1/statuses" }, - "transactions": { "href": "https://example.com:9984/api/v1/transactions" }, - "votes": { "href": "https://example.com:9984/api/v1/votes" } + "blocks": "https://example.com:9984/api/v1/blocks", + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", + "self": "https://example.com:9984/api/v1", + "statuses": "https://example.com:9984/api/v1/statuses", + "transactions": "https://example.com:9984/api/v1/transactions", + "votes": "https://example.com:9984/api/v1/votes" }, "version" : "0.9.0" } @@ -111,11 +111,11 @@ Transactions { "_links": { - "assets": { "href": "https://example.com:9984/api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}" }, - "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "item": { "href": "https://example.com:9984/api/v1/transactions/{tx_id}" }, - "self": { "href": "https://example.com:9984/api/v1/transactions" }, - "unspent": { "href": "https://example.com:9984/api/v1/transactions?unspent=true&public_keys={public_keys}" } + "assets": "https://example.com:9984/api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}", + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", + "item": "https://example.com:9984/api/v1/transactions/{tx_id}", + "self": "https://example.com:9984/api/v1/transactions", + "unspent": "https://example.com:9984/api/v1/transactions?unspent=true&public_keys={public_keys}" }, "version" : "0.9.0" } @@ -362,10 +362,10 @@ Blocks { "_links": { - "blocks": { "href": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}" }, - "docs": { "href": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html" }, - "item": { "href": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}" }, - "self": { "href": "https://example.com:9984/api/v1/blocks" } + "blocks": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}", + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", + "item": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}", + "self": "https://example.com:9984/api/v1/blocks" }, "version" : "0.9.0" } From 9e163ed2e5402373461b49c5e9cb201b36610849 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 6 Jan 2017 15:19:42 +0100 Subject: [PATCH 091/155] update api root informational endpoint docs --- docs/server/source/drivers-clients/http-client-server-api.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 15cf8a1d..f580ef5b 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -26,6 +26,7 @@ with something like the following in the body: { "_links": { "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" + "api_v1": "http://example.com:9984/api/v1/" }, "keyring": [ "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", @@ -50,12 +51,10 @@ that allows you to discover the BigchainDB API endpoints: { "_links": { - "blocks": "https://example.com:9984/api/v1/blocks", "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", "self": "https://example.com:9984/api/v1", "statuses": "https://example.com:9984/api/v1/statuses", "transactions": "https://example.com:9984/api/v1/transactions", - "votes": "https://example.com:9984/api/v1/votes" }, "version" : "0.9.0" } From 60b21fd24c738d7b1aaeffa44b7f2a78c07dac78 Mon Sep 17 00:00:00 2001 From: Dimitri De Jonghe Date: Mon, 9 Jan 2017 16:55:16 +0100 Subject: [PATCH 092/155] add comma --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index f580ef5b..97c8f017 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -25,7 +25,7 @@ with something like the following in the body: { "_links": { - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/" + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/", "api_v1": "http://example.com:9984/api/v1/" }, "keyring": [ From 4631c93dbf09fb543e8c0d97e578b9a978ee13b9 Mon Sep 17 00:00:00 2001 From: diminator Date: Mon, 9 Jan 2017 17:00:36 +0100 Subject: [PATCH 093/155] statuses remove 303 and location, links in payload --- docs/server/generate_http_server_api_documentation.py | 8 +++++--- .../source/drivers-clients/http-client-server-api.rst | 7 +++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index ed76ed15..1581a5fe 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -96,12 +96,14 @@ Content-Type: application/json TPLS['get-statuses-tx-valid-response'] = """\ -HTTP/1.1 303 See Other +HTTP/1.1 200 OK Content-Type: application/json -Location: ../transactions/%(txid)s { - "status": "valid" + "status": "valid", + "_links": { + "tx": "/transactions/%(txid)s" + } } """ diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 97c8f017..18dc0dbd 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -268,8 +268,8 @@ Statuses ``invalid``. If a transaction or block is persisted to the chain and it's status is set - to ``valid`` or ``undecided``, a ``303 See Other`` status code is returned, - as well as an URL to the resource in the location header. + to ``valid`` or ``undecided``, a ``200`` status code is returned, + as well as an URL to the resource. :param tx_id: transaction ID :type tx_id: hex string @@ -295,8 +295,7 @@ Statuses :resheader Content-Type: ``application/json`` :resheader Location: Once the transaction has been persisted, this header will link to the actual resource. - :statuscode 200: A transaction or block with that ID was found. The status is either ``backlog``, ``invalid``. - :statuscode 303: A transaction or block with that ID was found and persisted to the chain. A location header to the resource is provided. + :statuscode 200: A transaction or block with that ID was found. :statuscode 404: A transaction or block with that ID was not found. Blocks From 86be0e5983b5016b148350c05942127bad357cb1 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 11 Jan 2017 10:48:52 +0100 Subject: [PATCH 094/155] move blocks and votes to advanced with intro --- .../generate_http_server_api_documentation.py | 13 ++- .../http-client-server-api.rst | 95 +++++++++++-------- 2 files changed, 66 insertions(+), 42 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 1581a5fe..131b6a0a 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -134,7 +134,7 @@ TPLS['get-block-txid-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json -[%(block)s] +%(block_status)s """ @@ -194,12 +194,22 @@ def main(): block = Block(transactions=[tx], node_pubkey=node_public, voters=[node_public], signature=signature) block_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) + block_transfer = Block(transactions=[tx_transfer], node_pubkey=node_public, voters=[node_public], signature=signature) + block_transfer_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) + # vote DUMMY_SHA3 = '0123456789abcdef' * 4 b = Bigchain(public_key=node_public, private_key=node_private) vote = b.vote(block.id, DUMMY_SHA3, True) vote_json = json.dumps(vote, indent=2, sort_keys=True) + # block status + block_status = { + block_transfer.id: 'invalid', + block.id: 'valid' + } + block_status_json = json.dumps(block_status, indent=2, sort_keys=True) + base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') if not os.path.exists(base_path): @@ -218,6 +228,7 @@ def main(): 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0], 'block': block_json, 'blockid': block.id, + 'block_status': block_status_json, 'vote': vote_json} with open(path, 'w') as handle: handle.write(code) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 18dc0dbd..b9b1e59c 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -298,9 +298,58 @@ Statuses :statuscode 200: A transaction or block with that ID was found. :statuscode 404: A transaction or block with that ID was not found. -Blocks +Advanced Usage -------------------------------- +The following endpoints are more advanced and meant for debugging and transparency purposes. + +More precisely, the `blocks endpoint <#blocks>`_ allows you to retrieve a block by ``block_id`` as well the list of blocks that +a certain transaction with ``tx_id`` occured in (a transaction can occur in multiple ``invalid`` blocks until it +either gets rejected or validated by the system). This endpoint gives the ability to drill down on the lifecycle of a +transaction + +The `votes endpoint <#votes>`_ contains all the voting information for a specific block. So after retrieving the +``block_id`` for a given ``tx_id``, one can now simply inspect the votes that happened at a specific time on that block. + + + +Blocks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. http:get:: /blocks + + The unfiltered ``/blocks`` endpoint without any query parameters + returns a list of available block usages and relevant endpoints. + We believe a PUSH rather than a PULL pattern is more appropriate, as the + items returned in the collection would change by the second. + + + **Example request**: + + .. sourcecode:: http + + GET /blocks HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "_links": { + "blocks": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}", + "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", + "item": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}", + "self": "https://example.com:9984/api/v1/blocks" + }, + "version" : "0.9.0" + } + + :statuscode 200: BigchainDB blocks root endpoint. + .. http:get:: /blocks/{block_id}?status={VALID|UNDECIDED|INVALID} Get the block with the ID ``block_id``. @@ -336,48 +385,12 @@ Blocks :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. :statuscode 404: A block with that ID and a certain ``status`` was not found. -.. http:get:: /blocks +.. http:get:: /blocks?tx_id={tx_id} - The unfiltered ``/blocks`` endpoint without any query parameters - returns a list of available block usages and relevant endpoints. - We believe a PUSH rather than a PULL pattern is more appropriate, as the - items returned in the collection would change by the second. - - - **Example request**: - - .. sourcecode:: http - - GET /blocks HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "_links": { - "blocks": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}", - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", - "item": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}", - "self": "https://example.com:9984/api/v1/blocks" - }, - "version" : "0.9.0" - } - - :statuscode 200: BigchainDB blocks root endpoint. - - -.. http:get:: /blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID} - - Retrieve a list of blocks that contain a transaction with the ID ``tx_id``. + Retrieve a list of ``block_id`` with their corresponding status that contain a transaction with the ID ``tx_id``. Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be - returned. To filter blocks by their status, use the optional ``status`` - querystring. + returned. .. note:: In case no block was found, an empty list and an HTTP status code @@ -403,7 +416,7 @@ Blocks Votes --------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. http:get:: /votes?block_id={block_id} From a6facc8ada03b622c22c26a67a3dae99555ee8d9 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 11 Jan 2017 11:33:25 +0100 Subject: [PATCH 095/155] reformat blocks + blocks endpoint as list --- .../generate_http_server_api_documentation.py | 14 +-- .../http-client-server-api.rst | 87 ++++++++----------- 2 files changed, 42 insertions(+), 59 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 131b6a0a..975e6550 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -134,7 +134,7 @@ TPLS['get-block-txid-response'] = """\ HTTP/1.1 200 OK Content-Type: application/json -%(block_status)s +%(block_list)s """ @@ -204,11 +204,11 @@ def main(): vote_json = json.dumps(vote, indent=2, sort_keys=True) # block status - block_status = { - block_transfer.id: 'invalid', - block.id: 'valid' - } - block_status_json = json.dumps(block_status, indent=2, sort_keys=True) + block_list = [ + block_transfer.id, + block.id + ] + block_list_json = json.dumps(block_list, indent=2, sort_keys=True) base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') @@ -228,7 +228,7 @@ def main(): 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0], 'block': block_json, 'blockid': block.id, - 'block_status': block_status_json, + 'block_list': block_list_json, 'vote': vote_json} with open(path, 'w') as handle: handle.write(code) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index b9b1e59c..4115ed64 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -316,58 +316,15 @@ The `votes endpoint <#votes>`_ contains all the voting information for a specifi Blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. http:get:: /blocks +.. http:get:: /blocks/{block_id} - The unfiltered ``/blocks`` endpoint without any query parameters - returns a list of available block usages and relevant endpoints. - We believe a PUSH rather than a PULL pattern is more appropriate, as the - items returned in the collection would change by the second. - - - **Example request**: - - .. sourcecode:: http - - GET /blocks HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "_links": { - "blocks": "https://example.com:9984/api/v1/blocks?tx_id={tx_id}&status={VALID|UNDECIDED|INVALID}", - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", - "item": "https://example.com:9984/api/v1/blocks/{block_id}?status={VALID|UNDECIDED|INVALID}", - "self": "https://example.com:9984/api/v1/blocks" - }, - "version" : "0.9.0" - } - - :statuscode 200: BigchainDB blocks root endpoint. - -.. http:get:: /blocks/{block_id}?status={VALID|UNDECIDED|INVALID} - - Get the block with the ID ``block_id``. - - .. note:: - As ``status``'s default value is set to ``VALID``, hence only ``VALID`` blocks - will be returned by this endpoint. In case ``status=VALID``, but a block - that was labeled ``UNDECIDED`` or ``INVALID`` is requested by - ``block_id``, this endpoint will return a ``404 Not Found`` status code - to warn the user. To check a block's status independently, use the - `Statuses endpoint <#get--statuses?tx_id=tx_id|block_id=block_id>`_. The ``INVALID`` status - can be handy to figure out why the block was rejected. + Get the block with the ID ``block_id``. Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be + returned. To check a block's status independently, use the `Statuses endpoint <#get--statuses?tx_id=tx_id|block_id=block_id>`_. + To check the votes on a block, have a look at the `votes endpoint <#votes>`_. :param block_id: block ID :type block_id: hex string - :query string status: Per default set to ``VALID``. One of ``VALID``, ``UNDECIDED`` or ``INVALID``. - **Example request**: .. literalinclude:: samples/get-block-request.http @@ -383,20 +340,44 @@ Blocks :statuscode 200: A block with that ID was found. :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. - :statuscode 404: A block with that ID and a certain ``status`` was not found. + :statuscode 404: A block with that ID was not found. -.. http:get:: /blocks?tx_id={tx_id} + +.. http:get:: /blocks + + The unfiltered ``/blocks`` endpoint without any query parameters returns a `400` status code. + The list endpoint should be filtered with a ``tx_id`` query parameter, + see the ``/blocks?tx_id={tx_id}&status=UNDECIDED|VALID|INVALID`` + `endpoint <#get--blocks?tx_id=tx_id&status=UNDECIDED|VALID|INVALID>`_. + + + **Example request**: + + .. sourcecode:: http + + GET /blocks HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 400 OK + + :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. + +.. http:get:: /blocks?tx_id={tx_id}&status={UNDECIDED|VALID|INVALID} Retrieve a list of ``block_id`` with their corresponding status that contain a transaction with the ID ``tx_id``. - Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be - returned. + Any blocks, be they ``UNDECIDED``, ``VALID`` or ``INVALID`` will be + returned if no status filter is provided. .. note:: In case no block was found, an empty list and an HTTP status code ``200 OK`` is returned, as the request was still successful. - :query string tx_id: transaction ID + :query string tx_id: transaction ID *(required)* :query string status: Filter blocks by their status. One of ``VALID``, ``UNDECIDED`` or ``INVALID``. **Example request**: @@ -415,6 +396,8 @@ Blocks :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks``, without defining ``tx_id``. + + Votes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From deba454eb0c48f63c9235c6c7a8576692115e006 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 11 Jan 2017 11:34:35 +0100 Subject: [PATCH 096/155] 400 OK -> bad request --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 4115ed64..bc572e5b 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -362,7 +362,7 @@ Blocks .. sourcecode:: http - HTTP/1.1 400 OK + HTTP/1.1 400 Bad Request :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. From 4dea64f3beba01aa9f5962f2e77734fcf9ea4bdd Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 11 Jan 2017 11:38:57 +0100 Subject: [PATCH 097/155] /transactions root endpoint returns 400 --- .../http-client-server-api.rst | 20 +++---------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index bc572e5b..2990af44 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -90,9 +90,7 @@ Transactions .. http:get:: /transactions The unfiltered ``/transactions`` endpoint without any query parameters - returns a list of available transaction usages and relevant endpoints. - We believe a PUSH rather than a PULL pattern is more appropriate, as the - items returned in the collection would change by the second. + returns a status code `400`. For valid filters, see the sections below. **Example request**: @@ -105,21 +103,9 @@ Transactions .. sourcecode:: http - HTTP/1.1 200 OK - Content-Type: application/json + HTTP/1.1 400 Bad Request - { - "_links": { - "assets": "https://example.com:9984/api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id}", - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", - "item": "https://example.com:9984/api/v1/transactions/{tx_id}", - "self": "https://example.com:9984/api/v1/transactions", - "unspent": "https://example.com:9984/api/v1/transactions?unspent=true&public_keys={public_keys}" - }, - "version" : "0.9.0" - } - - :statuscode 200: BigchainDB transactions root endpoint. + :statuscode 400: The request wasn't understood by the server, a mandatory querystring was not included in the request. There are however filtered requests that might come of use, given the endpoint is queried correctly. Some of them include retrieving a list of transactions From ec5000bd47fd0520bf96300a0d3af07f15a41d49 Mon Sep 17 00:00:00 2001 From: diminator Date: Wed, 11 Jan 2017 12:03:28 +0100 Subject: [PATCH 098/155] add curly brackets around url --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 2990af44..552f4d39 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -333,7 +333,7 @@ Blocks The unfiltered ``/blocks`` endpoint without any query parameters returns a `400` status code. The list endpoint should be filtered with a ``tx_id`` query parameter, - see the ``/blocks?tx_id={tx_id}&status=UNDECIDED|VALID|INVALID`` + see the ``/blocks?tx_id={tx_id}&status={UNDECIDED|VALID|INVALID}`` `endpoint <#get--blocks?tx_id=tx_id&status=UNDECIDED|VALID|INVALID>`_. From 7d5d79a50cdecaf21337e25e37e3c06006907049 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 12 Jan 2017 16:19:49 +0100 Subject: [PATCH 099/155] remove location header from status --- docs/server/generate_http_server_api_documentation.py | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 975e6550..1c6301aa 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -70,7 +70,6 @@ Content-Type: application/json TPLS['post-tx-response'] = """\ HTTP/1.1 202 Accepted Content-Type: application/json -Location: ../statuses?tx_id=%(txid)s { "status": "/statuses?tx_id=%(txid)s" From d68d70ebc310ab4eb1dd25ab13b6f5a642e77da6 Mon Sep 17 00:00:00 2001 From: diminator Date: Thu, 12 Jan 2017 16:48:58 +0100 Subject: [PATCH 100/155] improved documentation on statuses links and values --- .../drivers-clients/http-client-server-api.rst | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 552f4d39..e6ef58bb 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -248,14 +248,12 @@ Statuses Supports the retrieval of a status for a transaction using ``tx_id`` or the retrieval of a status for a block using ``block_id``. Only use exactly one of both - queries, as they are required but mutually exclusive. + queries, as they are required but mutually exclusive. A URL to the resource is also + provided under ``_links``. - The possible status values are ``backlog``, ``undecided``, ``valid`` or - ``invalid``. - - If a transaction or block is persisted to the chain and it's status is set - to ``valid`` or ``undecided``, a ``200`` status code is returned, - as well as an URL to the resource. + The possible status values are ``undecided``, ``valid`` or + ``invalid`` for both blocks and transactions. An additional state ``backlog`` is provided + for transactions. :param tx_id: transaction ID :type tx_id: hex string From 787512014a6b6221c8f02425edba9de909b6690d Mon Sep 17 00:00:00 2001 From: Brett Sun Date: Fri, 13 Jan 2017 16:03:18 +0100 Subject: [PATCH 101/155] Fix small typos in API docs --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index e6ef58bb..36084b86 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -34,7 +34,7 @@ with something like the following in the body: ], "public_key": "AiygKSRhZWTxxYT4AfgKoTG4TZAoPsWoEt6C6bLq4jJR", "software": "BigchainDB", - "version": "0.9.0", + "version": "0.9.0" } From 2d1699e79063f78133a517fa1113879ef9c4329c Mon Sep 17 00:00:00 2001 From: Brett Sun Date: Fri, 13 Jan 2017 17:59:40 +0100 Subject: [PATCH 102/155] Split block and transaction status endpoint descriptions --- .../generate_http_server_api_documentation.py | 30 +++++++++ .../http-client-server-api.rst | 66 ++++++++++++++----- 2 files changed, 80 insertions(+), 16 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 1c6301aa..b32bda02 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -107,6 +107,36 @@ Content-Type: application/json """ +TPLS['get-statuses-block-request'] = """\ +GET /statuses?block_id=%(blockid)s HTTP/1.1 +Host: example.com + +""" + + +TPLS['get-statuses-block-invalid-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +{ + "status": "invalid" +} +""" + + +TPLS['get-statuses-block-valid-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +{ + "status": "valid", + "_links": { + "block": "/blocks/%(blockid)s" + } +} +""" + + TPLS['get-block-request'] = """\ GET /blocks/%(blockid)s HTTP/1.1 Host: example.com diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 36084b86..75dbffe0 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -242,24 +242,31 @@ Transactions Statuses -------------------------------- -.. http:get:: /statuses?tx_id={tx_id}|block_id={block_id} +.. http:get:: /statuses - Get the status of an asynchronously written resource by their id. + Get the status of an asynchronously written transaction or block by their id. - Supports the retrieval of a status for a transaction using ``tx_id`` or the - retrieval of a status for a block using ``block_id``. Only use exactly one of both - queries, as they are required but mutually exclusive. A URL to the resource is also - provided under ``_links``. - - The possible status values are ``undecided``, ``valid`` or - ``invalid`` for both blocks and transactions. An additional state ``backlog`` is provided + The possible status values are ``undecided``, ``valid`` or ``invalid`` for + both blocks and transactions. An additional state ``backlog`` is provided for transactions. - :param tx_id: transaction ID - :type tx_id: hex string + A link to the resource is also provided in the returned payload under + ``_links``. - :param block_id: block ID - :type block_id: hex string + :query string tx_id: transaction ID + :query string block_id: block ID + + .. note:: + + Exactly one of the ``tx_id`` or ``block_id`` query parameters must be + used together with this endpoint (see below for getting `transaction + statuses <#get--statuses?tx_id=tx_id>`_ and `block statuses + <#get--statuses?block_id=block_id>`_). + + +.. http:get:: /statuses?tx_id={tx_id} + + Get the status of a transaction. **Example request**: @@ -279,8 +286,35 @@ Statuses :resheader Content-Type: ``application/json`` :resheader Location: Once the transaction has been persisted, this header will link to the actual resource. - :statuscode 200: A transaction or block with that ID was found. - :statuscode 404: A transaction or block with that ID was not found. + :statuscode 200: A transaction with that ID was found. + :statuscode 404: A transaction with that ID was not found. + + +.. http:get:: /statuses?block_id={block_id} + + Get the status of a block. + + **Example request**: + + .. literalinclude:: samples/get-statuses-block-request.http + :language: http + + **Example response**: + + .. literalinclude:: samples/get-statuses-block-invalid-response.http + :language: http + + **Example response**: + + .. literalinclude:: samples/get-statuses-block-valid-response.http + :language: http + + :resheader Content-Type: ``application/json`` + :resheader Location: Once the block has been persisted, this header will link to the actual resource. + + :statuscode 200: A block with that ID was found. + :statuscode 404: A block with that ID was not found. + Advanced Usage -------------------------------- @@ -303,7 +337,7 @@ Blocks .. http:get:: /blocks/{block_id} Get the block with the ID ``block_id``. Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be - returned. To check a block's status independently, use the `Statuses endpoint <#get--statuses?tx_id=tx_id|block_id=block_id>`_. + returned. To check a block's status independently, use the `Statuses endpoint <#status>`_. To check the votes on a block, have a look at the `votes endpoint <#votes>`_. :param block_id: block ID From d932184b8842456f1eba6efcdd50977c10fb2fa7 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 23 Jan 2017 14:30:29 +0100 Subject: [PATCH 103/155] update http docs to reflect changes implemented for 0.9 --- .../generate_http_server_api_documentation.py | 118 ++++++----- .../http-client-server-api.rst | 188 +++++++----------- 2 files changed, 136 insertions(+), 170 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index b32bda02..4407cda4 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -7,14 +7,28 @@ import os.path from bigchaindb.common.transaction import Transaction, Input, TransactionLink from bigchaindb.core import Bigchain from bigchaindb.models import Block - +from bigchaindb.web import server TPLS = {} +TPLS['index-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +%(index)s +""" + +TPLS['api-index-response'] = """\ +HTTP/1.1 200 OK +Content-Type: application/json + +%(api_index)s +""" + TPLS['get-tx-id-request'] = """\ -GET /transactions/%(txid)s HTTP/1.1 +GET /api/v1/transactions/%(txid)s HTTP/1.1 Host: example.com """ @@ -28,23 +42,8 @@ Content-Type: application/json """ -TPLS['get-tx-unspent-request'] = """\ -GET /transactions?unspent=true&public_keys=%(public_keys_transfer_last)s HTTP/1.1 -Host: example.com - -""" - - -TPLS['get-tx-unspent-response'] = """\ -HTTP/1.1 200 OK -Content-Type: application/json - -[%(tx_transfer_last)s] -""" - - TPLS['get-tx-by-asset-request'] = """\ -GET /transactions?operation=transfer&asset_id=%(txid)s HTTP/1.1 +GET /api/v1/transactions?operation=TRANSFER&asset_id=%(txid)s HTTP/1.1 Host: example.com """ @@ -59,7 +58,7 @@ Content-Type: application/json """ TPLS['post-tx-request'] = """\ -POST /transactions/ HTTP/1.1 +POST /api/v1/transactions/ HTTP/1.1 Host: example.com Content-Type: application/json @@ -68,12 +67,10 @@ Content-Type: application/json TPLS['post-tx-response'] = """\ -HTTP/1.1 202 Accepted +HTTP/1.1 200 OK Content-Type: application/json -{ - "status": "/statuses?tx_id=%(txid)s" -} +%(tx)s """ @@ -108,7 +105,7 @@ Content-Type: application/json TPLS['get-statuses-block-request'] = """\ -GET /statuses?block_id=%(blockid)s HTTP/1.1 +GET /api/v1/statuses?block_id=%(blockid)s HTTP/1.1 Host: example.com """ @@ -138,7 +135,7 @@ Content-Type: application/json TPLS['get-block-request'] = """\ -GET /blocks/%(blockid)s HTTP/1.1 +GET /api/v1/blocks/%(blockid)s HTTP/1.1 Host: example.com """ @@ -153,7 +150,7 @@ Content-Type: application/json TPLS['get-block-txid-request'] = """\ -GET /blocks?tx_id=%(txid)s HTTP/1.1 +GET /api/v1/blocks?tx_id=%(txid)s HTTP/1.1 Host: example.com """ @@ -168,7 +165,7 @@ Content-Type: application/json TPLS['get-vote-request'] = """\ -GET /votes?block_id=%(blockid)s HTTP/1.1 +GET /api/v1/votes?block_id=%(blockid)s HTTP/1.1 Host: example.com """ @@ -185,13 +182,37 @@ Content-Type: application/json def main(): """ Main function """ + ctx = {} + + def pretty_json(data): + return json.dumps(data, indent=2, sort_keys=True) + + client = server.create_app().test_client() + + host = 'example.com:9984' + + # HTTP Index + res = client.get('/', environ_overrides={'HTTP_HOST': host}) + res_data = json.loads(res.data.decode()) + res_data['keyring'] = [ + "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", + "AdDuyrTyjrDt935YnFu4VBCVDhHtY2Y6rcy7x2TFeiRi" + ] + ctx['index'] = pretty_json(res_data) + + # API index + res = client.get('/api/v1/', environ_overrides={'HTTP_HOST': host}) + ctx['api_index'] = pretty_json(json.loads(res.data.decode())) + # tx create privkey = 'CfdqtD7sS7FgkMoGPXw55MVGGFwQLAoHYTcBhZDtF99Z' pubkey = '4K9sWUMFwTgaDGPfdynrbxWqWS6sWmKbZoTjxLtVUibD' asset = {'msg': 'Hello BigchainDB!'} tx = Transaction.create([pubkey], [([pubkey], 1)], asset=asset, metadata={'sequence': 0}) tx = tx.sign([privkey]) - tx_json = json.dumps(tx.to_dict(), indent=2, sort_keys=True) + ctx['tx'] = pretty_json(tx.to_dict()) + ctx['public_keys'] = tx.outputs[0].public_keys[0] + ctx['txid'] = tx.id # tx transfer privkey_transfer = '3AeWpPdhEZzWLYfkfYHBfMFC2r1f8HEaGS9NtbbKssya' @@ -203,41 +224,48 @@ def main(): owners_before=tx.outputs[cid].public_keys) tx_transfer = Transaction.transfer([input_], [([pubkey_transfer], 1)], asset_id=tx.id, metadata={'sequence': 1}) tx_transfer = tx_transfer.sign([privkey]) - tx_transfer_json = json.dumps(tx_transfer.to_dict(), indent=2, sort_keys=True) + ctx['tx_transfer'] = pretty_json(tx_transfer.to_dict()) + ctx['public_keys_transfer'] = tx_transfer.outputs[0].public_keys[0] + ctx['tx_transfer_id'] = tx_transfer.id - privkey_transfer_last = 'sG3jWDtdTXUidBJK53ucSTrosktG616U3tQHBk81eQe' + # privkey_transfer_last = 'sG3jWDtdTXUidBJK53ucSTrosktG616U3tQHBk81eQe' pubkey_transfer_last = '3Af3fhhjU6d9WecEM9Uw5hfom9kNEwE7YuDWdqAUssqm' cid = 0 input_ = Input(fulfillment=tx_transfer.outputs[cid].fulfillment, fulfills=TransactionLink(txid=tx_transfer.id, output=cid), owners_before=tx_transfer.outputs[cid].public_keys) - tx_transfer_last = Transaction.transfer([input_], [([pubkey_transfer_last], 1)], asset_id=tx.id, metadata={'sequence': 2}) + tx_transfer_last = Transaction.transfer([input_], [([pubkey_transfer_last], 1)], + asset_id=tx.id, metadata={'sequence': 2}) tx_transfer_last = tx_transfer_last.sign([privkey_transfer]) - tx_transfer_last_json = json.dumps(tx_transfer_last.to_dict(), indent=2, sort_keys=True) + ctx['tx_transfer_last'] = pretty_json(tx_transfer_last.to_dict()) + ctx['tx_transfer_last_id'] = tx_transfer_last.id + ctx['public_keys_transfer_last'] = tx_transfer_last.outputs[0].public_keys[0] # block node_private = "5G2kE1zJAgTajkVSbPAQWo4c2izvtwqaNHYsaNpbbvxX" node_public = "DngBurxfeNVKZWCEcDnLj1eMPAS7focUZTE5FndFGuHT" signature = "53wxrEQDYk1dXzmvNSytbCfmNVnPqPkDQaTnAe8Jf43s6ssejPxezkCvUnGTnduNUmaLjhaan1iRLi3peu6s5DzA" block = Block(transactions=[tx], node_pubkey=node_public, voters=[node_public], signature=signature) - block_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) + ctx['block'] = pretty_json(block.to_dict()) + ctx['blockid'] = block.id - block_transfer = Block(transactions=[tx_transfer], node_pubkey=node_public, voters=[node_public], signature=signature) - block_transfer_json = json.dumps(block.to_dict(), indent=2, sort_keys=True) + block_transfer = Block(transactions=[tx_transfer], node_pubkey=node_public, + voters=[node_public], signature=signature) + ctx['block_transfer'] = pretty_json(block.to_dict()) # vote DUMMY_SHA3 = '0123456789abcdef' * 4 b = Bigchain(public_key=node_public, private_key=node_private) vote = b.vote(block.id, DUMMY_SHA3, True) - vote_json = json.dumps(vote, indent=2, sort_keys=True) + ctx['vote'] = pretty_json(vote) # block status block_list = [ block_transfer.id, block.id ] - block_list_json = json.dumps(block_list, indent=2, sort_keys=True) + ctx['block_list'] = pretty_json(block_list) base_path = os.path.join(os.path.dirname(__file__), 'source/drivers-clients/samples') @@ -246,19 +274,7 @@ def main(): for name, tpl in TPLS.items(): path = os.path.join(base_path, name + '.http') - code = tpl % {'tx': tx_json, - 'txid': tx.id, - 'tx_transfer': tx_transfer_json, - 'tx_transfer_id': tx_transfer.id, - 'tx_transfer_last': tx_transfer_last_json, - 'tx_transfer_last_id': tx_transfer_last.id, - 'public_keys': tx.outputs[0].public_keys[0], - 'public_keys_transfer': tx_transfer.outputs[0].public_keys[0], - 'public_keys_transfer_last': tx_transfer_last.outputs[0].public_keys[0], - 'block': block_json, - 'blockid': block.id, - 'block_list': block_list_json, - 'vote': vote_json} + code = tpl % ctx with open(path, 'w') as handle: handle.write(code) @@ -270,5 +286,3 @@ def setup(*_): if __name__ == '__main__': main() - - diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 75dbffe0..72c22870 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -21,21 +21,8 @@ or ``https://example.com:9984`` then you should get an HTTP response with something like the following in the body: -.. code-block:: json - - { - "_links": { - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/", - "api_v1": "http://example.com:9984/api/v1/" - }, - "keyring": [ - "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", - "AdDuyrTyjrDt935YnFu4VBCVDhHtY2Y6rcy7x2TFeiRi" - ], - "public_key": "AiygKSRhZWTxxYT4AfgKoTG4TZAoPsWoEt6C6bLq4jJR", - "software": "BigchainDB", - "version": "0.9.0" - } +.. literalinclude:: samples/index-response.http + :language: http API Root Endpoint @@ -47,22 +34,13 @@ or ``https://example.com:9984/api/v1/``, then you should get an HTTP response that allows you to discover the BigchainDB API endpoints: -.. code-block:: json - - { - "_links": { - "docs": "https://docs.bigchaindb.com/projects/server/en/v0.9.0/drivers-clients/http-client-server-api.html", - "self": "https://example.com:9984/api/v1", - "statuses": "https://example.com:9984/api/v1/statuses", - "transactions": "https://example.com:9984/api/v1/transactions", - }, - "version" : "0.9.0" - } +.. literalinclude:: samples/api-index-response.http + :language: http Transactions ------------------- -.. http:get:: /transactions/{tx_id} +.. http:get:: /api/v1/transactions/{tx_id} Get the transaction with the ID ``tx_id``. @@ -87,107 +65,38 @@ Transactions :statuscode 200: A transaction with that ID was found. :statuscode 404: A transaction with that ID was not found. -.. http:get:: /transactions +.. http:get:: /api/v1/transactions - The unfiltered ``/transactions`` endpoint without any query parameters + The unfiltered ``/api/v1/transactions`` endpoint without any query parameters returns a status code `400`. For valid filters, see the sections below. - **Example request**: - - .. sourcecode:: http - - GET /transactions HTTP/1.1 - Host: example.com - - **Example response**: - - .. sourcecode:: http - - HTTP/1.1 400 Bad Request - - :statuscode 400: The request wasn't understood by the server, a mandatory querystring was not included in the request. - There are however filtered requests that might come of use, given the endpoint is queried correctly. Some of them include retrieving a list of transactions that include: - * `Unspent outputs <#get--transactions?unspent=true&public_keys=public_keys>`_ * `Transactions related to a specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. .. note:: - Looking up transactions with a specific ``metadata`` field is currently not supported. - This functionality requires something like custom indexing per client or read-only followers, - which is not yet on the roadmap. + Looking up transactions with a specific ``metadata`` field is currently not supported, + however, providing a way to query based on ``metadata`` data is on our roadmap. A generalization of those parameters follows: - :query boolean unspent: A flag to indicate whether only transactions with unspent outputs should be returned. - - :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. - :query string asset_id: asset ID. + :query string asset_id: The ID of the asset. - -.. http:get:: /transactions?unspent=true&public_keys={public_keys} - - Get a list of transactions with unspent outputs. - - If the querystring ``unspent`` is set to ``false`` and all outputs for - ``public_keys`` happen to be spent already, this endpoint will return - an empty list. Transactions with multiple outputs that have not all been spent - will be included in the response. - - This endpoint returns transactions only if they are - included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - - :query boolean unspent: A flag to indicate if transactions with unspent outputs should be returned. - - :query string public_keys: Public key able to validly spend an output of a transaction, assuming the user also has the corresponding private key. - - **Example request**: - - - .. literalinclude:: samples/get-tx-unspent-request.http - :language: http - - - **Example response**: - - .. literalinclude:: samples/get-tx-unspent-response.http - :language: http - - :resheader Content-Type: ``application/json`` - - :statuscode 200: A list of transactions containing unspent outputs was found and returned. - :statuscode 400: The request wasn't understood by the server, e.g. the ``public_keys`` querystring was not included in the request. - -.. http:get:: /transactions?operation={CREATE|TRANSFER}&asset_id={asset_id} +.. http:get:: /api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id} Get a list of transactions that use an asset with the ID ``asset_id``. Every ``TRANSFER`` transaction that originates from a ``CREATE`` transaction with ``asset_id`` will be included. This allows users to query the entire history or provenance of an asset. - This endpoint returns transactions only if they are - included in the ``BACKLOG`` or in a ``VALID`` or ``UNDECIDED`` block on ``bigchain``. - - .. note:: - The BigchainDB API currently doesn't expose an - ``/assets/{asset_id}`` endpoint, as there wouldn't be any way for a - client to verify that what was received is consistent with what was - persisted in the database. - However, BigchainDB's consensus ensures that any ``asset_id`` is - a unique key identifying an asset, meaning that when calling - ``/transactions?operation=CREATE&asset_id={asset_id}``, there will in - any case only be one transaction returned (in a list though, since - ``/transactions`` is a list-returning endpoint). - Leaving out the ``asset_id`` query and calling - ``/transactions?operation=CREATE`` returns the list of assets. + This endpoint returns transactions only if they are decided ``VALID`` by the server. :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. @@ -209,14 +118,14 @@ Transactions :statuscode 400: The request wasn't understood by the server, e.g. the ``asset_id`` querystring was not included in the request. -.. http:post:: /transactions +.. http:post:: /api/v1/transactions - Push a new transaction. The endpoint will return a ``statuses`` endpoint to track - the status of the transaction. + Push a new transaction. .. note:: - The posted transaction should be valid `transaction - `_. + The posted `transaction + `_ + should be structurally valid and not spending an already spent output. The steps to build a valid transaction are beyond the scope of this page. One would normally use a driver such as the `BigchainDB Python Driver `_ @@ -233,16 +142,59 @@ Transactions :language: http :resheader Content-Type: ``application/json`` - :resheader Location: As the transaction will be persisted asynchronously, an endpoint to monitor its status is provided in this header. - :statuscode 202: The pushed transaction was accepted in the ``BACKLOG``, but the processing has not been completed. + :statuscode 200: The pushed transaction was accepted in the ``BACKLOG``, but the processing has not been completed. :statuscode 400: The transaction was malformed and not accepted in the ``BACKLOG``. +Transaction Outputs +------------------- + +The ``/api/v1/outputs`` endpoint returns transactions outputs filtered by a +given public key, and optionally filtered to only include outputs that have +not already been spent. + + +.. http:get:: /api/v1/outputs?public_key={public_key} + + Get transaction outputs by public key. The `public_key` parameter must be + a base58 encoded ed25519 public key associated with transaction output + ownership. + + Returns a list of links to transaction outputs. + + :param public_key: Base58 encoded public key associated with output ownership. This parameter is mandatory and without it the endpoint will return a ``400`` response code. + :param unspent: Boolean value ("true" or "false") indicating if the result set should be limited to outputs that are available to spend. + + + **Example request**: + + .. sourcecode:: http + + GET /api/v1/outputs?public_key=1AAAbbb...ccc HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + [ + "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/0", + "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/1" + ] + + :statuscode 200: A list of outputs were found and returned in the body of the response. + :statuscode 400: The request wasn't understood by the server, e.g. the ``public_key`` querystring was not included in the request. + + + Statuses -------------------------------- -.. http:get:: /statuses +.. http:get:: /api/v1/statuses Get the status of an asynchronously written transaction or block by their id. @@ -264,7 +216,7 @@ Statuses <#get--statuses?block_id=block_id>`_). -.. http:get:: /statuses?tx_id={tx_id} +.. http:get:: /api/v1/statuses?tx_id={tx_id} Get the status of a transaction. @@ -290,7 +242,7 @@ Statuses :statuscode 404: A transaction with that ID was not found. -.. http:get:: /statuses?block_id={block_id} +.. http:get:: /api/v1/statuses?block_id={block_id} Get the status of a block. @@ -334,7 +286,7 @@ The `votes endpoint <#votes>`_ contains all the voting information for a specifi Blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. http:get:: /blocks/{block_id} +.. http:get:: /api/v1/blocks/{block_id} Get the block with the ID ``block_id``. Any blocks, be they ``VALID``, ``UNDECIDED`` or ``INVALID`` will be returned. To check a block's status independently, use the `Statuses endpoint <#status>`_. @@ -361,7 +313,7 @@ Blocks :statuscode 404: A block with that ID was not found. -.. http:get:: /blocks +.. http:get:: /api/v1/blocks The unfiltered ``/blocks`` endpoint without any query parameters returns a `400` status code. The list endpoint should be filtered with a ``tx_id`` query parameter, @@ -373,7 +325,7 @@ Blocks .. sourcecode:: http - GET /blocks HTTP/1.1 + GET /api/v1/blocks HTTP/1.1 Host: example.com **Example response**: @@ -384,7 +336,7 @@ Blocks :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks`` without the ``block_id``. -.. http:get:: /blocks?tx_id={tx_id}&status={UNDECIDED|VALID|INVALID} +.. http:get:: /api/v1/blocks?tx_id={tx_id}&status={UNDECIDED|VALID|INVALID} Retrieve a list of ``block_id`` with their corresponding status that contain a transaction with the ID ``tx_id``. @@ -419,7 +371,7 @@ Blocks Votes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. http:get:: /votes?block_id={block_id} +.. http:get:: /api/v1/votes?block_id={block_id} Retrieve a list of votes for a certain block with ID ``block_id``. To check for the validity of a vote, a user of this endpoint needs to From 88b99d7bdc98de20694490365b0185f675d39b7e Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 23 Jan 2017 16:37:50 +0100 Subject: [PATCH 104/155] document optional operation parameter in transaction --- .../source/drivers-clients/http-client-server-api.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 72c22870..6c67bfda 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -74,7 +74,7 @@ Transactions queried correctly. Some of them include retrieving a list of transactions that include: - * `Transactions related to a specific asset <#get--transactions?operation=CREATE|TRANSFER&asset_id=asset_id>`_ + * `Transactions related to a specific asset <#get--transactions?asset_id=asset_id&operation=CREATE|TRANSFER>`_ In this section, we've listed those particular requests, as they will likely to be very handy when implementing your application on top of BigchainDB. @@ -85,11 +85,11 @@ Transactions A generalization of those parameters follows: - :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. - :query string asset_id: The ID of the asset. -.. http:get:: /api/v1/transactions?operation={CREATE|TRANSFER}&asset_id={asset_id} + :query string operation: (Optional) One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. + +.. http:get:: /api/v1/transactions?asset_id={asset_id}&operation={CREATE|TRANSFER} Get a list of transactions that use an asset with the ID ``asset_id``. Every ``TRANSFER`` transaction that originates from a ``CREATE`` transaction @@ -98,7 +98,7 @@ Transactions This endpoint returns transactions only if they are decided ``VALID`` by the server. - :query string operation: One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. + :query string operation: (Optional) One of the two supported operations of a transaction: ``CREATE``, ``TRANSFER``. :query string asset_id: asset ID. From 7a71e386f33b38e7f279d45074792755eec5f7db Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 25 Jan 2017 10:47:38 +0100 Subject: [PATCH 105/155] Fix whitespace --- .../http-client-server-api.rst | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 6c67bfda..b1b4686d 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -37,6 +37,7 @@ that allows you to discover the BigchainDB API endpoints: .. literalinclude:: samples/api-index-response.http :language: http + Transactions ------------------- @@ -152,7 +153,7 @@ Transaction Outputs The ``/api/v1/outputs`` endpoint returns transactions outputs filtered by a given public key, and optionally filtered to only include outputs that have -not already been spent. +not already been spent. .. http:get:: /api/v1/outputs?public_key={public_key} @@ -162,20 +163,20 @@ not already been spent. ownership. Returns a list of links to transaction outputs. - + :param public_key: Base58 encoded public key associated with output ownership. This parameter is mandatory and without it the endpoint will return a ``400`` response code. :param unspent: Boolean value ("true" or "false") indicating if the result set should be limited to outputs that are available to spend. - - + + **Example request**: - + .. sourcecode:: http - + GET /api/v1/outputs?public_key=1AAAbbb...ccc HTTP/1.1 Host: example.com **Example response**: - + .. sourcecode:: http HTTP/1.1 200 OK @@ -185,12 +186,11 @@ not already been spent. "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/0", "../transactions/2d431073e1477f3073a4693ac7ff9be5634751de1b8abaa1f4e19548ef0b4b0e/outputs/1" ] - + :statuscode 200: A list of outputs were found and returned in the body of the response. :statuscode 400: The request wasn't understood by the server, e.g. the ``public_key`` querystring was not included in the request. - Statuses -------------------------------- @@ -282,7 +282,6 @@ The `votes endpoint <#votes>`_ contains all the voting information for a specifi ``block_id`` for a given ``tx_id``, one can now simply inspect the votes that happened at a specific time on that block. - Blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -366,8 +365,6 @@ Blocks :statuscode 400: The request wasn't understood by the server, e.g. just requesting ``/blocks``, without defining ``tx_id``. - - Votes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 5b7dd672b8d8f490045d353466044196a057e01f Mon Sep 17 00:00:00 2001 From: tim Date: Wed, 25 Jan 2017 11:30:40 +0100 Subject: [PATCH 106/155] Remove controversial endpoints for now --- .../generate_http_server_api_documentation.py | 2 +- .../http-client-server-api.rst | 21 ++++++++----------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index 4407cda4..c36b10b5 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -67,7 +67,7 @@ Content-Type: application/json TPLS['post-tx-response'] = """\ -HTTP/1.1 200 OK +HTTP/1.1 202 Accepted Content-Type: application/json %(tx)s diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index b1b4686d..9e66f603 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -45,8 +45,8 @@ Transactions Get the transaction with the ID ``tx_id``. - This endpoint returns only a transaction from the ``BACKLOG`` or a ``VALID`` or ``UNDECIDED`` - block on ``bigchain``, if exists. + This endpoint returns a transaction only if a ``VALID`` block on + ``bigchain`` exists. :param tx_id: transaction ID :type tx_id: hex string @@ -144,7 +144,7 @@ Transactions :resheader Content-Type: ``application/json`` - :statuscode 200: The pushed transaction was accepted in the ``BACKLOG``, but the processing has not been completed. + :statuscode 202: The pushed transaction was accepted in the ``BACKLOG``, but the processing has not been completed. :statuscode 400: The transaction was malformed and not accepted in the ``BACKLOG``. @@ -198,10 +198,6 @@ Statuses Get the status of an asynchronously written transaction or block by their id. - The possible status values are ``undecided``, ``valid`` or ``invalid`` for - both blocks and transactions. An additional state ``backlog`` is provided - for transactions. - A link to the resource is also provided in the returned payload under ``_links``. @@ -220,6 +216,10 @@ Statuses Get the status of a transaction. + The possible status values are ``undecided``, ``valid`` or ``backlog``. + If a transaction in neither of those states is found, a ``404 Not Found`` + HTTP status code is returned. `We're currently looking into ways to unambigously let the user know about a transaction's status that was included in an invalid block. `_ + **Example request**: .. literalinclude:: samples/get-statuses-tx-request.http @@ -227,11 +227,6 @@ Statuses **Example response**: - .. literalinclude:: samples/get-statuses-tx-invalid-response.http - :language: http - - **Example response**: - .. literalinclude:: samples/get-statuses-tx-valid-response.http :language: http @@ -246,6 +241,8 @@ Statuses Get the status of a block. + The possible status values are ``undecided``, ``valid`` or ``invalid``. + **Example request**: .. literalinclude:: samples/get-statuses-block-request.http From 7af997508141d7281ae6247a4b3a12ace688bbd5 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 25 Jan 2017 12:22:34 +0100 Subject: [PATCH 107/155] return 202 on successful transaction POST --- bigchaindb/web/views/transactions.py | 2 +- tests/web/test_transactions.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index 3059b34f..a4a983ef 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -113,4 +113,4 @@ class TransactionListApi(Resource): with monitor.timer('write_transaction', rate=rate): bigchain.write_transaction(tx_obj) - return tx + return tx, 202 diff --git a/tests/web/test_transactions.py b/tests/web/test_transactions.py index 28e0fab0..6970c725 100644 --- a/tests/web/test_transactions.py +++ b/tests/web/test_transactions.py @@ -38,6 +38,9 @@ def test_post_create_transaction_endpoint(b, client): tx = tx.sign([user_priv]) res = client.post(TX_ENDPOINT, data=json.dumps(tx.to_dict())) + + assert res.status_code == 202 + assert res.json['inputs'][0]['owners_before'][0] == user_pub assert res.json['outputs'][0]['public_keys'][0] == user_pub @@ -157,6 +160,8 @@ def test_post_transfer_transaction_endpoint(b, client, user_pk, user_sk): res = client.post(TX_ENDPOINT, data=json.dumps(transfer_tx.to_dict())) + assert res.status_code == 202 + assert res.json['inputs'][0]['owners_before'][0] == user_pk assert res.json['outputs'][0]['public_keys'][0] == user_pub From 391da2cf604287acf217051acd2743f65a8b94a8 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Wed, 25 Jan 2017 12:36:08 +0100 Subject: [PATCH 108/155] Added tests --- bigchaindb/backend/admin.py | 6 +- bigchaindb/commands/bigchain.py | 4 +- tests/backend/mongodb/test_admin.py | 118 ++++++++++++++++++++++++++++ tests/backend/test_generics.py | 2 + tests/commands/test_commands.py | 54 ++++++++++++- 5 files changed, 179 insertions(+), 5 deletions(-) create mode 100644 tests/backend/mongodb/test_admin.py diff --git a/bigchaindb/backend/admin.py b/bigchaindb/backend/admin.py index da54397b..f0ea62fd 100644 --- a/bigchaindb/backend/admin.py +++ b/bigchaindb/backend/admin.py @@ -24,9 +24,11 @@ def set_replicas(connection, *, replicas): @singledispatch def add_replicas(connection, replicas): - raise NotImplementedError + raise NotImplementedError('This command is specific to the ' + 'MongoDB backend.') @singledispatch def remove_replicas(connection, replicas): - raise NotImplementedError + raise NotImplementedError('This command is specific to the ' + 'MongoDB backend.') diff --git a/bigchaindb/commands/bigchain.py b/bigchaindb/commands/bigchain.py index 78b3b745..98e9d81c 100644 --- a/bigchaindb/commands/bigchain.py +++ b/bigchaindb/commands/bigchain.py @@ -277,7 +277,7 @@ def run_add_replicas(args): try: add_replicas(conn, args.replicas) - except DatabaseOpFailedError as e: + except (DatabaseOpFailedError, NotImplementedError) as e: logger.warn(e) else: logger.info('Added {} to the replicaset.'.format(args.replicas)) @@ -290,7 +290,7 @@ def run_remove_replicas(args): try: remove_replicas(conn, args.replicas) - except DatabaseOpFailedError as e: + except (DatabaseOpFailedError, NotImplementedError) as e: logger.warn(e) else: logger.info('Removed {} from the replicaset.'.format(args.replicas)) diff --git a/tests/backend/mongodb/test_admin.py b/tests/backend/mongodb/test_admin.py new file mode 100644 index 00000000..138bc616 --- /dev/null +++ b/tests/backend/mongodb/test_admin.py @@ -0,0 +1,118 @@ +"""Tests for the :mod:`bigchaindb.backend.mongodb.admin` module.""" +import copy +from unittest import mock + +import pytest +from pymongo.database import Database +from pymongo.errors import OperationFailure + + +@pytest.fixture +def mock_replicaset_config(): + return { + 'config': { + '_id': 'bigchain-rs', + 'members': [ + { + '_id': 0, + 'arbiterOnly': False, + 'buildIndexes': True, + 'hidden': False, + 'host': 'localhost:27017', + 'priority': 1.0, + 'slaveDelay': 0, + 'tags': {}, + 'votes': 1 + } + ], + 'version': 1 + } + } + + +def test_add_replicas(mock_replicaset_config): + from bigchaindb.backend import connect + from bigchaindb.backend.admin import add_replicas + + connection = connect() + # force the connection object to setup a connection to the database + # before we mock `Database.command` + connection.conn + + expected_config = copy.deepcopy(mock_replicaset_config) + expected_config['config']['members'] += [ + {'_id': 1, 'host': 'localhost:27018'}, + {'_id': 2, 'host': 'localhost:27019'} + ] + expected_config['config']['version'] += 1 + + with mock.patch.object(Database, 'command') as mock_command: + mock_command.return_value = mock_replicaset_config + add_replicas(connection, ['localhost:27018', 'localhost:27019']) + + mock_command.assert_called_with('replSetReconfig', + expected_config['config']) + + +def test_add_replicas_raises(mock_replicaset_config): + from bigchaindb.backend import connect + from bigchaindb.backend.admin import add_replicas + from bigchaindb.backend.exceptions import DatabaseOpFailedError + + connection = connect() + # force the connection object to setup a connection to the database + # before we mock `Database.command` + connection.conn + + with mock.patch.object(Database, 'command') as mock_command: + mock_command.side_effect = [ + mock_replicaset_config, + OperationFailure(error=1, details={'errmsg': ''}) + ] + with pytest.raises(DatabaseOpFailedError): + add_replicas(connection, ['localhost:27018']) + + +def test_remove_replicas(mock_replicaset_config): + from bigchaindb.backend import connect + from bigchaindb.backend.admin import remove_replicas + + connection = connect() + # force the connection object to setup a connection to the database + # before we mock `Database.command` + connection.conn + + expected_config = copy.deepcopy(mock_replicaset_config) + expected_config['config']['version'] += 1 + + # add some hosts to the configuration to remove + mock_replicaset_config['config']['members'] += [ + {'_id': 1, 'host': 'localhost:27018'}, + {'_id': 2, 'host': 'localhost:27019'} + ] + + with mock.patch.object(Database, 'command') as mock_command: + mock_command.return_value = mock_replicaset_config + remove_replicas(connection, ['localhost:27018', 'localhost:27019']) + + mock_command.assert_called_with('replSetReconfig', + expected_config['config']) + + +def test_remove_replicas_raises(mock_replicaset_config): + from bigchaindb.backend import connect + from bigchaindb.backend.admin import remove_replicas + from bigchaindb.backend.exceptions import DatabaseOpFailedError + + connection = connect() + # force the connection object to setup a connection to the database + # before we mock `Database.command` + connection.conn + + with mock.patch.object(Database, 'command') as mock_command: + mock_command.side_effect = [ + mock_replicaset_config, + OperationFailure(error=1, details={'errmsg': ''}) + ] + with pytest.raises(DatabaseOpFailedError): + remove_replicas(connection, ['localhost:27018']) diff --git a/tests/backend/test_generics.py b/tests/backend/test_generics.py index 2049d72b..0dd2637f 100644 --- a/tests/backend/test_generics.py +++ b/tests/backend/test_generics.py @@ -100,6 +100,8 @@ def test_init_database(mock_create_database, mock_create_tables, ('reconfigure', {'table': None, 'shards': None, 'replicas': None}), ('set_shards', {'shards': None}), ('set_replicas', {'replicas': None}), + ('add_replicas', {'replicas': None}), + ('remove_replicas', {'replicas': None}), )) def test_admin(admin_func_name, kwargs): from bigchaindb.backend import admin diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index 1a1291e3..f61c4c6f 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -1,6 +1,6 @@ import json from unittest.mock import Mock, patch -from argparse import Namespace +from argparse import Namespace, ArgumentTypeError import copy import pytest @@ -376,3 +376,55 @@ def test_calling_main(start_mock, base_parser_mock, parse_args_mock, 'distributed equally to all ' 'the processes') assert start_mock.called is True + + +@patch('bigchaindb.backend.admin.add_replicas') +def test_run_add_replicas(mock_add_replicas): + from bigchaindb.commands.bigchain import run_add_replicas + from bigchaindb.backend.exceptions import DatabaseOpFailedError + + args = Namespace(config=None, replicas=['localhost:27017']) + + # test add_replicas no raises + mock_add_replicas.return_value = None + assert run_add_replicas(args) is None + + # test add_replicas with `DatabaseOpFailedError` + mock_add_replicas.side_effect = DatabaseOpFailedError() + assert run_add_replicas(args) is None + + # test add_replicas with `NotImplementedError` + mock_add_replicas.side_effect = NotImplementedError() + assert run_add_replicas(args) is None + + +@patch('bigchaindb.backend.admin.remove_replicas') +def test_run_remove_replicas(mock_remove_replicas): + from bigchaindb.commands.bigchain import run_remove_replicas + from bigchaindb.backend.exceptions import DatabaseOpFailedError + + args = Namespace(config=None, replicas=['localhost:27017']) + + # test add_replicas no raises + mock_remove_replicas.return_value = None + assert run_remove_replicas(args) is None + + # test add_replicas with `DatabaseOpFailedError` + mock_remove_replicas.side_effect = DatabaseOpFailedError() + assert run_remove_replicas(args) is None + + # test add_replicas with `NotImplementedError` + mock_remove_replicas.side_effect = NotImplementedError() + assert run_remove_replicas(args) is None + + +def test_mongodb_host_type(): + from bigchaindb.commands.utils import mongodb_host + + # bad port provided + with pytest.raises(ArgumentTypeError): + mongodb_host('localhost:11111111111') + + # no port information provided + with pytest.raises(ArgumentTypeError): + mongodb_host('localhost') From 8e8a60a5399a43804c153a2209f4e5431d069335 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Wed, 25 Jan 2017 13:58:35 +0100 Subject: [PATCH 109/155] Get the correct configuration if backend is set by envs --- bigchaindb/__init__.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/bigchaindb/__init__.py b/bigchaindb/__init__.py index 315774e5..79118e23 100644 --- a/bigchaindb/__init__.py +++ b/bigchaindb/__init__.py @@ -5,6 +5,12 @@ import os # PORT_NUMBER = reduce(lambda x, y: x * y, map(ord, 'BigchainDB')) % 2**16 # basically, the port number is 9984 + +def _get_database_from_env(): + return globals()['_database_' + os.environ.get( + 'BIGCHAINDB_DATABASE_BACKEND', 'rethinkdb')] + + _database_rethinkdb = { 'backend': os.environ.get('BIGCHAINDB_DATABASE_BACKEND', 'rethinkdb'), 'host': os.environ.get('BIGCHAINDB_DATABASE_HOST', 'localhost'), @@ -28,7 +34,7 @@ config = { 'workers': None, # if none, the value will be cpu_count * 2 + 1 'threads': None, # if none, the value will be cpu_count * 2 + 1 }, - 'database': _database_rethinkdb, + 'database': _get_database_from_env(), 'keypair': { 'public': None, 'private': None, From 05fdcef670c403fcb2c4dafc6fb2db859fc2799c Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Wed, 25 Jan 2017 18:54:03 +0100 Subject: [PATCH 110/155] Document default value for GET /outputs?unspent= --- docs/server/source/drivers-clients/http-client-server-api.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/drivers-clients/http-client-server-api.rst b/docs/server/source/drivers-clients/http-client-server-api.rst index 9e66f603..5444be8f 100644 --- a/docs/server/source/drivers-clients/http-client-server-api.rst +++ b/docs/server/source/drivers-clients/http-client-server-api.rst @@ -165,7 +165,7 @@ not already been spent. Returns a list of links to transaction outputs. :param public_key: Base58 encoded public key associated with output ownership. This parameter is mandatory and without it the endpoint will return a ``400`` response code. - :param unspent: Boolean value ("true" or "false") indicating if the result set should be limited to outputs that are available to spend. + :param unspent: Boolean value ("true" or "false") indicating if the result set should be limited to outputs that are available to spend. Defaults to "false". **Example request**: From 9762b4b96854cd5896f4b71c7fbfcc82d6f24f5c Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Thu, 26 Jan 2017 13:39:06 +0100 Subject: [PATCH 111/155] fix spend input twice bug (https://github.com/bigchaindb/bigchaindb/issues/1099) --- bigchaindb/models.py | 5 +++++ tests/db/test_bigchain_api.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/bigchaindb/models.py b/bigchaindb/models.py index 159e9f49..c6e81956 100644 --- a/bigchaindb/models.py +++ b/bigchaindb/models.py @@ -88,6 +88,11 @@ class Transaction(Transaction): if output.amount < 1: raise AmountError('`amount` needs to be greater than zero') + # Validate that all inputs are distinct + links = [i.fulfills.to_uri() for i in self.inputs] + if len(links) != len(set(links)): + raise DoubleSpend('tx "{}" spends inputs twice'.format(self.id)) + # validate asset id asset_id = Transaction.get_asset_id(input_txs) if asset_id != self.asset['id']: diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index 8a2040e8..4d9314a1 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1192,3 +1192,33 @@ def test_get_outputs_filtered(): get_outputs.assert_called_once_with('abc') get_spent.assert_not_called() assert out == get_outputs.return_value + + +@pytest.mark.bdb +def test_cant_spend_same_input_twice_in_tx(b, genesis_block): + """ + Recreate duplicated fulfillments bug + https://github.com/bigchaindb/bigchaindb/issues/1099 + """ + from bigchaindb.models import Transaction + from bigchaindb.common.exceptions import DoubleSpend + + # create a divisible asset + tx_create = Transaction.create([b.me], [([b.me], 100)]) + tx_create_signed = tx_create.sign([b.me_private]) + assert b.validate_transaction(tx_create_signed) == tx_create_signed + + # create a block and valid vote + block = b.create_block([tx_create_signed]) + b.write_block(block) + vote = b.vote(block.id, genesis_block.id, True) + b.write_vote(vote) + + # Create a transfer transaction with duplicated fulfillments + dup_inputs = tx_create.to_inputs() + tx_create.to_inputs() + tx_transfer = Transaction.transfer(dup_inputs, [([b.me], 200)], + asset_id=tx_create.id) + tx_transfer_signed = tx_transfer.sign([b.me_private]) + assert b.is_valid_transaction(tx_transfer_signed) is False + with pytest.raises(DoubleSpend): + tx_transfer_signed.validate(b) From adb579ac0a29ac857eed5886cabfed17b1121994 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Thu, 26 Jan 2017 13:52:09 +0100 Subject: [PATCH 112/155] Revert "duplicate asset ID" and apply "get_txids_filtered" interface. --- bigchaindb/backend/mongodb/query.py | 55 +++++++++++++------ bigchaindb/backend/rethinkdb/query.py | 43 +++++++++------ bigchaindb/common/schema/transaction.yaml | 4 +- bigchaindb/common/transaction.py | 16 +----- docs/server/source/data-models/asset-model.md | 5 +- tests/common/test_transaction.py | 28 +--------- 6 files changed, 73 insertions(+), 78 deletions(-) diff --git a/bigchaindb/backend/mongodb/query.py b/bigchaindb/backend/mongodb/query.py index c4e3cdc8..d7ee6afc 100644 --- a/bigchaindb/backend/mongodb/query.py +++ b/bigchaindb/backend/mongodb/query.py @@ -1,12 +1,14 @@ """Query implementation for MongoDB""" from time import time +from itertools import chain from pymongo import ReturnDocument from pymongo import errors from bigchaindb import backend from bigchaindb.common.exceptions import CyclicBlockchainError +from bigchaindb.common.transaction import Transaction from bigchaindb.backend.utils import module_dispatch_registrar from bigchaindb.backend.mongodb.connection import MongoDBConnection @@ -82,6 +84,43 @@ def get_blocks_status_from_transaction(conn, transaction_id): projection=['id', 'block.voters']) +@register_query(MongoDBConnection) +def get_txids_filtered(conn, asset_id, operation=None): + parts = [] + + if operation in (Transaction.CREATE, None): + # get the txid of the create transaction for asset_id + cursor = conn.db['bigchain'].aggregate([ + {'$match': { + 'block.transactions.id': asset_id, + 'block.transactions.operation': 'CREATE' + }}, + {'$unwind': '$block.transactions'}, + {'$match': { + 'block.transactions.id': asset_id, + 'block.transactions.operation': 'CREATE' + }}, + {'$project': {'block.transactions.id': True}} + ]) + parts.append(elem['block']['transactions']['id'] for elem in cursor) + + if operation in (Transaction.TRANSFER, None): + # get txids of transfer transaction with asset_id + cursor = conn.db['bigchain'].aggregate([ + {'$match': { + 'block.transactions.asset.id': asset_id + }}, + {'$unwind': '$block.transactions'}, + {'$match': { + 'block.transactions.asset.id': asset_id + }}, + {'$project': {'block.transactions.id': True}} + ]) + parts.append(elem['block']['transactions']['id'] for elem in cursor) + + return chain(*parts) + + @register_query(MongoDBConnection) def get_asset_by_id(conn, asset_id): cursor = conn.db['bigchain'].aggregate([ @@ -234,19 +273,3 @@ def get_unvoted_blocks(conn, node_pubkey): 'votes': False, '_id': False }} ]) - - -@register_query(MongoDBConnection) -def get_txids_filtered(conn, asset_id, operation=None): - match = {'block.transactions.asset.id': asset_id} - - if operation: - match['block.transactions.operation'] = operation - - cursor = conn.db['bigchain'].aggregate([ - {'$match': match}, - {'$unwind': '$block.transactions'}, - {'$match': match}, - {'$project': {'block.transactions.id': True}} - ]) - return (r['block']['transactions']['id'] for r in cursor) diff --git a/bigchaindb/backend/rethinkdb/query.py b/bigchaindb/backend/rethinkdb/query.py index fd0bdcb3..aa7c3be6 100644 --- a/bigchaindb/backend/rethinkdb/query.py +++ b/bigchaindb/backend/rethinkdb/query.py @@ -1,9 +1,11 @@ +from itertools import chain from time import time import rethinkdb as r from bigchaindb import backend, utils from bigchaindb.common import exceptions +from bigchaindb.common.transaction import Transaction from bigchaindb.backend.utils import module_dispatch_registrar from bigchaindb.backend.rethinkdb.connection import RethinkDBConnection @@ -71,6 +73,30 @@ def get_blocks_status_from_transaction(connection, transaction_id): .pluck('votes', 'id', {'block': ['voters']})) +@register_query(RethinkDBConnection) +def get_txids_filtered(connection, asset_id, operation=None): + # here we only want to return the transaction ids since later on when + # we are going to retrieve the transaction with status validation + + parts = [] + + if operation in (Transaction.CREATE, None): + # First find the asset's CREATE transaction + parts.append(connection.run( + _get_asset_create_tx_query(asset_id).get_field('id'))) + + if operation in (Transaction.TRANSFER, None): + # Then find any TRANSFER transactions related to the asset + parts.append(connection.run( + r.table('bigchain') + .get_all(asset_id, index='asset_id') + .concat_map(lambda block: block['block']['transactions']) + .filter(lambda transaction: transaction['asset']['id'] == asset_id) + .get_field('id'))) + + return chain(*parts) + + @register_query(RethinkDBConnection) def get_asset_by_id(connection, asset_id): return connection.run(_get_asset_create_tx_query(asset_id).pluck('asset')) @@ -233,20 +259,3 @@ def get_unvoted_blocks(connection, node_pubkey): # database level. Solving issue #444 can help untangling the situation unvoted_blocks = filter(lambda block: not utils.is_genesis_block(block), unvoted) return unvoted_blocks - - -@register_query(RethinkDBConnection) -def get_txids_filtered(connection, asset_id, operation=None): - # here we only want to return the transaction ids since later on when - # we are going to retrieve the transaction with status validation - - tx_filter = r.row['asset']['id'] == asset_id - if operation: - tx_filter &= r.row['operation'] == operation - - return connection.run( - r.table('bigchain') - .get_all(asset_id, index='asset_id') - .concat_map(lambda block: block['block']['transactions']) - .filter(tx_filter) - .get_field('id')) diff --git a/bigchaindb/common/schema/transaction.yaml b/bigchaindb/common/schema/transaction.yaml index a0edd1e3..86e5947b 100644 --- a/bigchaindb/common/schema/transaction.yaml +++ b/bigchaindb/common/schema/transaction.yaml @@ -103,8 +103,8 @@ definitions: description: | Description of the asset being transacted. In the case of a ``TRANSFER`` transaction, this field contains only the ID of asset. In the case - of a ``CREATE`` transaction, this field contains the user-defined - payload and the asset ID (duplicated from the Transaction ID). + of a ``CREATE`` transaction, this field contains only the user-defined + payload. additionalProperties: false properties: id: diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index 0e6d84f2..65b12eed 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -444,7 +444,6 @@ class Transaction(object): asset is not None and not (isinstance(asset, dict) and 'data' in asset)): raise TypeError(('`asset` must be None or a dict holding a `data` ' " property instance for '{}' Transactions".format(operation))) - asset.pop('id', None) # Remove duplicated asset ID if there is one elif (operation == Transaction.TRANSFER and not (isinstance(asset, dict) and 'id' in asset)): raise TypeError(('`asset` must be a dict holding an `id` property ' @@ -927,11 +926,9 @@ class Transaction(object): tx_no_signatures = Transaction._remove_signatures(tx) tx_serialized = Transaction._to_str(tx_no_signatures) - tx['id'] = Transaction._to_hash(tx_serialized) - if self.operation == Transaction.CREATE: - # Duplicate asset into asset for consistency with TRANSFER - # transactions - tx['asset']['id'] = tx['id'] + tx_id = Transaction._to_hash(tx_serialized) + + tx['id'] = tx_id return tx @staticmethod @@ -955,9 +952,6 @@ class Transaction(object): # case could yield incorrect signatures. This is why we only # set it to `None` if it's set in the dict. input_['fulfillment'] = None - # Pop duplicated asset_id from CREATE tx - if tx_dict['operation'] == Transaction.CREATE: - tx_dict['asset'].pop('id', None) return tx_dict @staticmethod @@ -1037,10 +1031,6 @@ class Transaction(object): "the hash of its body, i.e. it's not valid.") raise InvalidHash(err_msg.format(proposed_tx_id)) - if tx_body.get('operation') == Transaction.CREATE: - if proposed_tx_id != tx_body['asset'].get('id'): - raise InvalidHash('CREATE tx has wrong asset_id') - @classmethod def from_dict(cls, tx): """Transforms a Python dictionary to a Transaction object. diff --git a/docs/server/source/data-models/asset-model.md b/docs/server/source/data-models/asset-model.md index 16188400..312c6765 100644 --- a/docs/server/source/data-models/asset-model.md +++ b/docs/server/source/data-models/asset-model.md @@ -1,11 +1,10 @@ # The Digital Asset Model -The asset ID is the same as the ID of the CREATE transaction that defined the asset. +To avoid redundant data in transactions, the digital asset model is different for `CREATE` and `TRANSFER` transactions. -In the case of a CREATE transaction, the transaction ID is duplicated into the asset object for clarity and consistency in the database. The CREATE transaction also contains a user definable payload to describe the asset: +A digital asset's properties are defined in a `CREATE` transaction with the following model: ```json { - "id": "", "data": "" } ``` diff --git a/tests/common/test_transaction.py b/tests/common/test_transaction.py index 7e70939d..a2782583 100644 --- a/tests/common/test_transaction.py +++ b/tests/common/test_transaction.py @@ -300,7 +300,6 @@ def test_transaction_serialization(user_input, user_output, data): 'operation': Transaction.CREATE, 'metadata': None, 'asset': { - 'id': tx_id, 'data': data, } } @@ -308,7 +307,7 @@ def test_transaction_serialization(user_input, user_output, data): tx = Transaction(Transaction.CREATE, {'data': data}, [user_input], [user_output]) tx_dict = tx.to_dict() - tx_dict['id'] = tx_dict['asset']['id'] = tx_id + tx_dict['id'] = tx_id assert tx_dict == expected @@ -335,7 +334,6 @@ def test_transaction_deserialization(user_input, user_output, data): } tx_no_signatures = Transaction._remove_signatures(tx) tx['id'] = Transaction._to_hash(Transaction._to_str(tx_no_signatures)) - tx['asset']['id'] = tx['id'] tx = Transaction.from_dict(tx) assert tx == expected @@ -691,7 +689,6 @@ def test_create_create_transaction_single_io(user_output, user_pub, data): tx_dict = tx.to_dict() tx_dict['inputs'][0]['fulfillment'] = None tx_dict.pop('id') - tx_dict['asset'].pop('id') assert tx_dict == expected @@ -775,7 +772,6 @@ def test_create_create_transaction_threshold(user_pub, user2_pub, user3_pub, metadata=data, asset=data) tx_dict = tx.to_dict() tx_dict.pop('id') - tx_dict['asset'].pop('id') tx_dict['inputs'][0]['fulfillment'] = None assert tx_dict == expected @@ -989,25 +985,3 @@ def test_validate_version(utx): utx.version = '1.0.0' with raises(SchemaValidationError): validate_transaction_model(utx) - - -def test_create_tx_has_asset_id(tx): - tx = tx.to_dict() - assert tx['id'] == tx['asset']['id'] - - -def test_create_tx_validates_asset_id(tx): - from bigchaindb.common.transaction import Transaction - from bigchaindb.common.exceptions import InvalidHash - - tx = tx.to_dict() - - # Test fails with wrong asset_id - tx['asset']['id'] = tx['asset']['id'][::-1] - with raises(InvalidHash): - Transaction.from_dict(tx) - - # Test fails with no asset_id - tx['asset'].pop('id') - with raises(InvalidHash): - Transaction.from_dict(tx) From 1243322aad661bf62efa16cf1865c8aff658f1d2 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Thu, 26 Jan 2017 13:59:52 +0100 Subject: [PATCH 113/155] Case insensitive "unspent" and "operation" parameters" --- bigchaindb/web/views/parameters.py | 2 ++ tests/web/test_parameters.py | 16 ++++++---------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/bigchaindb/web/views/parameters.py b/bigchaindb/web/views/parameters.py index 222adb97..9759563e 100644 --- a/bigchaindb/web/views/parameters.py +++ b/bigchaindb/web/views/parameters.py @@ -8,6 +8,7 @@ def valid_txid(txid): def valid_bool(val): + val = val.lower() if val == 'true': return True if val == 'false': @@ -23,6 +24,7 @@ def valid_ed25519(key): def valid_operation(op): + op = op.upper() if op == 'CREATE': return 'CREATE' if op == 'TRANSFER': diff --git a/tests/web/test_parameters.py b/tests/web/test_parameters.py index d39c6f38..7da2b739 100644 --- a/tests/web/test_parameters.py +++ b/tests/web/test_parameters.py @@ -24,11 +24,9 @@ def test_valid_bool(): assert valid_bool('true') is True assert valid_bool('false') is False + assert valid_bool('tRUE') is True + assert valid_bool('fALSE') is False - with pytest.raises(ValueError): - valid_bool('TRUE') - with pytest.raises(ValueError): - valid_bool('FALSE') with pytest.raises(ValueError): valid_bool('0') with pytest.raises(ValueError): @@ -64,13 +62,11 @@ def test_valid_ed25519(): def test_valid_operation(): from bigchaindb.web.views.parameters import valid_operation - assert valid_operation('CREATE') == 'CREATE' - assert valid_operation('TRANSFER') == 'TRANSFER' + assert valid_operation('create') == 'CREATE' + assert valid_operation('transfer') == 'TRANSFER' + assert valid_operation('CREATe') == 'CREATE' + assert valid_operation('TRANSFEr') == 'TRANSFER' - with pytest.raises(ValueError): - valid_operation('create') - with pytest.raises(ValueError): - valid_operation('transfer') with pytest.raises(ValueError): valid_operation('GENESIS') with pytest.raises(ValueError): From 9d03aeb72a8debea42e7775e8b77983620efa4d3 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Thu, 26 Jan 2017 15:02:48 +0100 Subject: [PATCH 114/155] fixed tests --- tests/commands/test_commands.py | 2 ++ tests/test_config_utils.py | 27 +++++++++++++++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index f61c4c6f..16b615eb 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -378,6 +378,7 @@ def test_calling_main(start_mock, base_parser_mock, parse_args_mock, assert start_mock.called is True +@pytest.mark.usefixtures('ignore_local_config_file') @patch('bigchaindb.backend.admin.add_replicas') def test_run_add_replicas(mock_add_replicas): from bigchaindb.commands.bigchain import run_add_replicas @@ -398,6 +399,7 @@ def test_run_add_replicas(mock_add_replicas): assert run_add_replicas(args) is None +@pytest.mark.usefixtures('ignore_local_config_file') @patch('bigchaindb.backend.admin.remove_replicas') def test_run_remove_replicas(mock_remove_replicas): from bigchaindb.commands.bigchain import run_remove_replicas diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index c1f63742..7ebe5579 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -131,6 +131,26 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): from bigchaindb import config_utils config_utils.autoconfigure() + backend = request.config.getoption('--database-backend') + database_rethinkdb = { + 'backend': 'rethinkdb', + 'host': 'test-host', + 'port': 4242, + 'name': 'test-dbname', + } + database_mongodb = { + 'backend': 'mongodb', + 'host': 'test-host', + 'port': 4242, + 'name': 'test-dbname', + 'replicaset': 'bigchain-rs', + } + + # default + database = database_rethinkdb + if backend == 'mongodb': + database = database_mongodb + assert bigchaindb.config == { 'CONFIGURED': True, 'server': { @@ -138,12 +158,7 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): 'workers': None, 'threads': None, }, - 'database': { - 'backend': request.config.getoption('--database-backend'), - 'host': 'test-host', - 'port': 4242, - 'name': 'test-dbname', - }, + 'database': database, 'keypair': { 'public': None, 'private': None, From 3c5511563627f4311e99f91bac11738cdf2399d5 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Thu, 26 Jan 2017 15:53:51 +0100 Subject: [PATCH 115/155] Add changes for 0.8.1 release to changelog --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fdfe8c2..b6fd28ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,19 @@ For reference, the possible headings are: * **Notes** +## [0.8.1] - 2017-01-16 +Tag name: v0.8.1 += commit: +committed: + +### Changed +- Upgrade pysha3 to 1.0.0 (supports official NIST standard). + +### Fixed +- Workaround for rapidjson problem with package metadata extraction + (https://github.com/kenrobbins/python-rapidjson/pull/52). + + ## [0.8.0] - 2016-11-29 Tag name: v0.8.0 = commit: From 509b590b32c1e19b1c8970cfdfd64bf582811721 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 27 Jan 2017 11:40:41 +0100 Subject: [PATCH 116/155] pull changelog from 0.8.2 --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6fd28ea..312c589f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,14 @@ For reference, the possible headings are: * **Notes** +## [0.8.2] - 2017-01-27 +Tag name: v0.8.2 + +### Fixed +- Fix spend input twice in same transaction + (https://github.com/bigchaindb/bigchaindb/issues/1099). + + ## [0.8.1] - 2017-01-16 Tag name: v0.8.1 = commit: From aa3a525dc1c496ca2a4b958d8046be50bd8018ea Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 27 Jan 2017 15:27:44 +0100 Subject: [PATCH 117/155] Release process changes for Minor and Patch version --- Release_Process.md | 55 +++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/Release_Process.md b/Release_Process.md index 16dc800b..b24398af 100644 --- a/Release_Process.md +++ b/Release_Process.md @@ -1,23 +1,48 @@ # Our Release Process -This is a summary of the steps we go through to release a new version of BigchainDB Server. +The release process for BigchainDB server differs slightly depending on whether it's a minor or a patch release. -1. Update the `CHANGELOG.md` file -1. Update the version numbers in `bigchaindb/version.py`. Note that we try to use [semantic versioning](http://semver.org/) (i.e. MAJOR.MINOR.PATCH) -1. Go to the [bigchaindb/bigchaindb Releases page on GitHub](https://github.com/bigchaindb/bigchaindb/releases) - and click the "Draft a new release" button -1. Name the tag something like v0.7.0 -1. The target should be a specific commit: the one when the update of `bigchaindb/version.py` got merged into master -1. The release title should be something like v0.7.0 -1. The description should be copied from the `CHANGELOG.md` file updated above -1. Generate and send the latest `bigchaindb` package to PyPI. Dimi and Sylvain can do this, maybe others -1. Login to readthedocs.org as a maintainer of the BigchainDB Server docs. - Go to Admin --> Versions and under **Choose Active Versions**, make sure that the new version's tag is - "Active" and "Public" +BigchainDB follows [semantic versioning](http://semver.org/) (i.e. MAJOR.MINOR.PATCH), taking into account +that [major version 0 does not export a stable API](http://semver.org/#spec-item-4). -After the release: +## Minor release -1. Update `bigchaindb/version.py` again, to be something like 0.8.0.dev (with a dev on the end). +A minor release is preceeded by a feature freeze and created from the 'master' branch. This is a summary of the steps we go through to release a new minor version of BigchainDB Server. + +1. Update the `CHANGELOG.md` file in master +1. Create and checkout a new branch for the release, named after the minor version, without preceeding 'v', ie: `git checkout -b 0.9` +1. Commit changes and push new branch to Github +1. Follow steps outlined in [Common Steps](#common-steps) +1. In 'master' branch, Edit `bigchaindb/version.py`, increment the minor version to the next planned release ie: `0.10.0.dev'. This is so people reading the latest docs will know that they're for the latest (master branch) version of BigchainDB Server, not the docs at the time of the most recent release (which are also available). + +Congratulations, you have released BigchainDB! + +## Patch release + +A patch release is similar to a minor release, but piggybacks on an existing minor release branch: + +1. Check out the minor release branch +1. Apply the changes you want, ie using `git cherry-pick`. +1. Update the `CHANGELOG.md` file +1. Increment the patch version in `bigchaindb/version.py`, ie: "0.9.1" +1. Follow steps outlined in [Common Steps](#common-steps) + +## Common steps + +These steps are common between minor and patch releases: + +1. Go to the [bigchaindb/bigchaindb Releases page on GitHub](https://github.com/bigchaindb/bigchaindb/releases) + and click the "Draft a new release" button +1. Fill in the details: + - Tag version: version number preceeded by 'v', ie: "v0.9.1" + - Target: the release branch that was just pushed + - Title: Same as tag name + - Description: The body of the changelog entry (Added, Changed etc) +1. Publish the release on Github +1. Generate the release tarball with `python setup.py sdist`. Upload the release to Pypi. +1. Login to readthedocs.org as a maintainer of the BigchainDB Server docs. + Go to Admin --> Versions and under **Choose Active Versions**, make sure that the new version's tag is + "Active" and "Public" From f6a6b72a9c965360dad113a2d327cae3076c5f38 Mon Sep 17 00:00:00 2001 From: libscott Date: Fri, 27 Jan 2017 17:48:11 +0100 Subject: [PATCH 118/155] Update Release_Process.md --- Release_Process.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Release_Process.md b/Release_Process.md index b24398af..bf267d34 100644 --- a/Release_Process.md +++ b/Release_Process.md @@ -3,7 +3,7 @@ The release process for BigchainDB server differs slightly depending on whether it's a minor or a patch release. BigchainDB follows [semantic versioning](http://semver.org/) (i.e. MAJOR.MINOR.PATCH), taking into account -that [major version 0 does not export a stable API](http://semver.org/#spec-item-4). +that [major version 0.x does not export a stable API](http://semver.org/#spec-item-4). ## Minor release From 5b084edaf405bccc697497e89970ce0309ea1093 Mon Sep 17 00:00:00 2001 From: vrde Date: Mon, 30 Jan 2017 10:56:46 +0100 Subject: [PATCH 119/155] Break out of the loop once a connection is established closes #1068 --- bigchaindb/backend/rethinkdb/connection.py | 2 ++ tests/backend/rethinkdb/test_connection.py | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/bigchaindb/backend/rethinkdb/connection.py b/bigchaindb/backend/rethinkdb/connection.py index 173cdc7b..601125f2 100644 --- a/bigchaindb/backend/rethinkdb/connection.py +++ b/bigchaindb/backend/rethinkdb/connection.py @@ -77,3 +77,5 @@ class RethinkDBConnection(Connection): wait_time = 2**i logging.debug('Error connecting to database, waiting %ss', wait_time) time.sleep(wait_time) + else: + break diff --git a/tests/backend/rethinkdb/test_connection.py b/tests/backend/rethinkdb/test_connection.py index 65c665af..073fecee 100644 --- a/tests/backend/rethinkdb/test_connection.py +++ b/tests/backend/rethinkdb/test_connection.py @@ -1,6 +1,7 @@ import time import multiprocessing as mp from threading import Thread +from unittest.mock import patch import pytest import rethinkdb as r @@ -118,3 +119,15 @@ def test_changefeed_reconnects_when_connection_lost(monkeypatch): fact = changefeed.outqueue.get()['fact'] assert fact == 'Cats sleep 70% of their lives.' + + +@patch('rethinkdb.connect') +def test_connection_happens_one_time_if_successful(mock_connect): + from bigchaindb.backend import connect + + query = r.expr('1') + conn = connect('rethinkdb', 'localhost', 1337, 'whatev') + conn.run(query) + mock_connect.assert_called_once_with(host='localhost', + port=1337, + db='whatev') From 736ecb0bc8d7d1a57981a5a01671afd5e32b77c6 Mon Sep 17 00:00:00 2001 From: libscott Date: Mon, 30 Jan 2017 12:04:07 +0100 Subject: [PATCH 120/155] Update Release_Process.md --- Release_Process.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Release_Process.md b/Release_Process.md index bf267d34..0f89c509 100644 --- a/Release_Process.md +++ b/Release_Process.md @@ -45,4 +45,8 @@ These steps are common between minor and patch releases: 1. Generate the release tarball with `python setup.py sdist`. Upload the release to Pypi. 1. Login to readthedocs.org as a maintainer of the BigchainDB Server docs. Go to Admin --> Versions and under **Choose Active Versions**, make sure that the new version's tag is - "Active" and "Public" + "Active" and "Public", and make sure the new version's branch + (without the 'v' in front) is _not_ active +1. Also in readthedocs.org, go to Admin --> Advanced Settings + and make sure that "Default branch:" (i.e. what "latest" points to) + is set to the new release's tag, e.g. `v0.9.1`. (Don't miss the 'v' in front.) From 49464484d7add4481f09caf174849235ad1df54a Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 30 Jan 2017 14:04:32 +0100 Subject: [PATCH 121/155] set public_key manually in bigchaindb root url docs example --- docs/server/generate_http_server_api_documentation.py | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/server/generate_http_server_api_documentation.py b/docs/server/generate_http_server_api_documentation.py index c36b10b5..ba082ba3 100644 --- a/docs/server/generate_http_server_api_documentation.py +++ b/docs/server/generate_http_server_api_documentation.py @@ -198,6 +198,7 @@ def main(): "6qHyZew94NMmUTYyHnkZsB8cxJYuRNEiEpXHe1ih9QX3", "AdDuyrTyjrDt935YnFu4VBCVDhHtY2Y6rcy7x2TFeiRi" ] + res_data['public_key'] = 'NC8c8rYcAhyKVpx1PCV65CBmyq4YUbLysy3Rqrg8L8mz' ctx['index'] = pretty_json(res_data) # API index From 2a07362bad9c0d6bc0c52bbd42b109cda85bc80e Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Mon, 30 Jan 2017 16:11:44 +0100 Subject: [PATCH 122/155] test transaction supports unicode --- tests/db/test_bigchain_api.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index 4d9314a1..aa8488c4 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1222,3 +1222,15 @@ def test_cant_spend_same_input_twice_in_tx(b, genesis_block): assert b.is_valid_transaction(tx_transfer_signed) is False with pytest.raises(DoubleSpend): tx_transfer_signed.validate(b) + + +@pytest.mark.bdb +def test_transaction_unicode(b): + import json + from bigchaindb.models import Transaction + tx = (Transaction.create([b.me], [([b.me], 100)], + {'beer': '\N{BEER MUG}'}) + ).sign([b.me_private]) + block = b.create_block([tx]) + assert block.validate(b) == block + assert '{"beer": "\\ud83c\\udf7a"}' in json.dumps(block.to_dict()) From a1aa64aa61adda32985d996669308ddcc626b4d2 Mon Sep 17 00:00:00 2001 From: Brett Sun Date: Tue, 24 Jan 2017 19:03:59 +0100 Subject: [PATCH 123/155] Fix Makefile for new docs structure --- Makefile | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 95b18f0d..d8ef2bf4 100644 --- a/Makefile +++ b/Makefile @@ -65,12 +65,11 @@ coverage: ## check code coverage quickly with the default Python $(BROWSER) htmlcov/index.html docs: ## generate Sphinx HTML documentation, including API docs - rm -f docs/bigchaindb.rst - rm -f docs/modules.rst - sphinx-apidoc -o docs/ bigchaindb - $(MAKE) -C docs clean - $(MAKE) -C docs html - $(BROWSER) docs/_build/html/index.html + $(MAKE) -C docs/root clean + $(MAKE) -C docs/root html + $(MAKE) -C docs/server clean + $(MAKE) -C docs/server html + $(BROWSER) docs/root/_build/html/index.html servedocs: docs ## compile the docs watching for changes watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . From 17a07a80f1db317094ce3778d0eef114aa47464b Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Mon, 30 Jan 2017 18:11:29 +0100 Subject: [PATCH 124/155] Removed 'Example Apps' page from the docs --- docs/server/source/drivers-clients/example-apps.rst | 10 ---------- docs/server/source/drivers-clients/index.rst | 1 - 2 files changed, 11 deletions(-) delete mode 100644 docs/server/source/drivers-clients/example-apps.rst diff --git a/docs/server/source/drivers-clients/example-apps.rst b/docs/server/source/drivers-clients/example-apps.rst deleted file mode 100644 index 0aab953e..00000000 --- a/docs/server/source/drivers-clients/example-apps.rst +++ /dev/null @@ -1,10 +0,0 @@ -Example Apps -============ - -.. warning:: - - There are some example BigchainDB apps (i.e. apps which use BigchainDB) in the GitHub repository named `bigchaindb-examples `_. They were created before there was much of an HTTP API, so instead of communicating with a BigchainDB node via the HTTP API, they communicate directly with the node using the BigchainDB Python server API and the RethinkDB Python Driver. That's not how a real production app would work. The HTTP API is getting better, and we recommend using it to communicate with BigchainDB nodes. - - Moreover, because of changes to the BigchainDB Server code, some of the examples in the bigchaindb-examples repo might not work anymore, or they might not work as expected. - - In the future, we hope to create a set of examples using the HTTP API (or wrappers of it, such as the Python Driver API). diff --git a/docs/server/source/drivers-clients/index.rst b/docs/server/source/drivers-clients/index.rst index 9eb81f6c..dd33e18b 100644 --- a/docs/server/source/drivers-clients/index.rst +++ b/docs/server/source/drivers-clients/index.rst @@ -14,4 +14,3 @@ your choice, and then use the HTTP API directly to post transactions. http-client-server-api The Python Driver Transaction CLI - example-apps From 86542fd74583902cc0a8d2826d0adff9b6b8719a Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 09:58:20 +0100 Subject: [PATCH 125/155] remove unnecessary test --- tests/backend/test_generics.py | 27 --------------------------- 1 file changed, 27 deletions(-) diff --git a/tests/backend/test_generics.py b/tests/backend/test_generics.py index 2049d72b..956b698f 100644 --- a/tests/backend/test_generics.py +++ b/tests/backend/test_generics.py @@ -68,33 +68,6 @@ def test_changefeed_class(changefeed_class_func_name, args_qty): changefeed_class_func(None, *range(args_qty)) -@patch('bigchaindb.backend.schema.create_indexes', - autospec=True, return_value=None) -@patch('bigchaindb.backend.schema.create_tables', - autospec=True, return_value=None) -@patch('bigchaindb.backend.schema.create_database', - autospec=True, return_value=None) -def test_init_database(mock_create_database, mock_create_tables, - mock_create_indexes): - from bigchaindb.backend.schema import init_database - from bigchaindb.backend.rethinkdb.connection import RethinkDBConnection - from bigchaindb.backend.mongodb.connection import MongoDBConnection - - # rethinkdb - conn = RethinkDBConnection('host', 'port', 'dbname') - init_database(connection=conn, dbname='mickeymouse') - mock_create_database.assert_called_with(conn, 'mickeymouse') - mock_create_tables.assert_called_with(conn, 'mickeymouse') - mock_create_indexes.assert_called_with(conn, 'mickeymouse') - - # mongodb - conn = MongoDBConnection('host', 'port', 'dbname', replicaset='rs') - init_database(connection=conn, dbname='mickeymouse') - mock_create_database.assert_called_with(conn, 'mickeymouse') - mock_create_tables.assert_called_with(conn, 'mickeymouse') - mock_create_indexes.assert_called_with(conn, 'mickeymouse') - - @mark.parametrize('admin_func_name,kwargs', ( ('get_config', {'table': None}), ('reconfigure', {'table': None, 'shards': None, 'replicas': None}), From 555745abbf69753acdce82d83c0ec3b611a93f6f Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 10:04:45 +0100 Subject: [PATCH 126/155] fixed pep8 issue --- tests/backend/test_generics.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/backend/test_generics.py b/tests/backend/test_generics.py index 956b698f..946b694f 100644 --- a/tests/backend/test_generics.py +++ b/tests/backend/test_generics.py @@ -1,5 +1,3 @@ -from unittest.mock import patch - from pytest import mark, raises From fafdac252308314ade77e4ec175aef3869a74347 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 10:34:45 +0100 Subject: [PATCH 127/155] Retrieve default backend from env if set. Fixed tests. --- bigchaindb/__init__.py | 9 ++++++++- tests/test_config_utils.py | 28 ++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/bigchaindb/__init__.py b/bigchaindb/__init__.py index 315774e5..072c7b6b 100644 --- a/bigchaindb/__init__.py +++ b/bigchaindb/__init__.py @@ -20,6 +20,11 @@ _database_mongodb = { 'replicaset': os.environ.get('BIGCHAINDB_DATABASE_REPLICASET', 'bigchain-rs'), } +_database_map = { + 'mongodb': _database_mongodb, + 'rethinkdb': _database_rethinkdb +} + config = { 'server': { # Note: this section supports all the Gunicorn settings: @@ -28,7 +33,9 @@ config = { 'workers': None, # if none, the value will be cpu_count * 2 + 1 'threads': None, # if none, the value will be cpu_count * 2 + 1 }, - 'database': _database_rethinkdb, + 'database': _database_map[ + os.environ.get('BIGCHAINDB_DATABASE_BACKEND', 'rethinkdb') + ], 'keypair': { 'public': None, 'private': None, diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index c1f63742..ebf630a9 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -131,6 +131,27 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): from bigchaindb import config_utils config_utils.autoconfigure() + backend = request.config.getoption('--database-backend') + database_rethinkdb = { + 'backend': 'rethinkdb', + 'host': 'test-host', + 'port': 4242, + 'name': 'test-dbname', + } + database_mongodb = { + 'backend': 'mongodb', + 'host': 'test-host', + 'port': 4242, + 'name': 'test-dbname', + 'replicaset': 'bigchain-rs', + } + + database = {} + if backend == 'mongodb': + database = database_mongodb + elif backend == 'rethinkdb': + database = database_rethinkdb + assert bigchaindb.config == { 'CONFIGURED': True, 'server': { @@ -138,12 +159,7 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): 'workers': None, 'threads': None, }, - 'database': { - 'backend': request.config.getoption('--database-backend'), - 'host': 'test-host', - 'port': 4242, - 'name': 'test-dbname', - }, + 'database': database, 'keypair': { 'public': None, 'private': None, From 4740150f6d772bc3b8cf9ccf2a3fc56d9909cee9 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 10:57:58 +0100 Subject: [PATCH 128/155] Updated config fixture Simplified tests. --- tests/conftest.py | 3 +-- tests/test_config_utils.py | 10 ---------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index c3177c14..9612f38b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -118,9 +118,8 @@ def _configure_bigchaindb(request): test_db_name = '{}_{}'.format(TEST_DB_NAME, xdist_suffix) backend = request.config.getoption('--database-backend') - backend_conf = getattr(bigchaindb, '_database_' + backend) config = { - 'database': backend_conf, + 'database': bigchaindb._database_map[backend], 'keypair': { 'private': '31Lb1ZGKTyHnmVK3LUMrAUrPNfd4sE2YyBt3UA4A25aA', 'public': '4XYfCbabAWVUCbjTmRTFEu2sc3dFEdkse4r6X498B1s8', diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index ebf630a9..7feec4c9 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -23,11 +23,6 @@ def test_bigchain_instance_is_initialized_when_conf_provided(request): assert bigchaindb.config['CONFIGURED'] is True - # set the current backend so that Bigchain can create a connection - backend = request.config.getoption('--database-backend') - backend_conf = getattr(bigchaindb, '_database_' + backend) - bigchaindb.config['database'] = backend_conf - b = bigchaindb.Bigchain() assert b.me @@ -44,11 +39,6 @@ def test_bigchain_instance_raises_when_not_configured(request, monkeypatch): # from existing configurations monkeypatch.setattr(config_utils, 'autoconfigure', lambda: 0) - # set the current backend so that Bigchain can create a connection - backend = request.config.getoption('--database-backend') - backend_conf = getattr(bigchaindb, '_database_' + backend) - bigchaindb.config['database'] = backend_conf - with pytest.raises(exceptions.KeypairNotFoundException): bigchaindb.Bigchain() From 002c567bdfd26aa2e234fc25da700b43dff52ac4 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Tue, 31 Jan 2017 11:13:45 +0100 Subject: [PATCH 129/155] Updated the AMIs to Ubuntu 16.04 images in amis.tf --- ntools/one-m/aws/amis.tf | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/ntools/one-m/aws/amis.tf b/ntools/one-m/aws/amis.tf index 1e3910cc..7e15ed5b 100644 --- a/ntools/one-m/aws/amis.tf +++ b/ntools/one-m/aws/amis.tf @@ -2,19 +2,20 @@ # even though the contents are the same. # This file has the mapping from region --> AMI name. # -# These are all Ubuntu 14.04 LTS AMIs +# These are all Ubuntu 16.04 LTS AMIs # with Arch = amd64, Instance Type = hvm:ebs-ssd # from https://cloud-images.ubuntu.com/locator/ec2/ +# as of Jan. 31, 2017 variable "amis" { type = "map" default = { - eu-west-1 = "ami-55452e26" - eu-central-1 = "ami-b1cf39de" - us-east-1 = "ami-8e0b9499" - us-west-2 = "ami-547b3834" - ap-northeast-1 = "ami-49d31328" - ap-southeast-1 = "ami-5e429c3d" - ap-southeast-2 = "ami-25f3c746" - sa-east-1 = "ami-97980efb" + eu-west-1 = "ami-d8f4deab" + eu-central-1 = "ami-5aee2235" + us-east-1 = "ami-6edd3078" + us-west-2 = "ami-7c803d1c" + ap-northeast-1 = "ami-eb49358c" + ap-southeast-1 = "ami-b1943fd2" + ap-southeast-2 = "ami-fe71759d" + sa-east-1 = "ami-7379e31f" } } From 375873b6ede2b8f77c7ba840ea54353ba91c0b57 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Tue, 31 Jan 2017 11:24:46 +0100 Subject: [PATCH 130/155] Updated docs page about Terraform: Ubuntu 14.04 --> 16.04 --- .../template-terraform-aws.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/server/source/cloud-deployment-starter-templates/template-terraform-aws.md b/docs/server/source/cloud-deployment-starter-templates/template-terraform-aws.md index 5d1292d3..85e4cf9d 100644 --- a/docs/server/source/cloud-deployment-starter-templates/template-terraform-aws.md +++ b/docs/server/source/cloud-deployment-starter-templates/template-terraform-aws.md @@ -2,7 +2,7 @@ If you didn't read the introduction to the [cloud deployment starter templates](index.html), please do that now. The main point is that they're not for deploying a production node; they can be used as a starting point. -This page explains a way to use [Terraform](https://www.terraform.io/) to provision an Ubuntu machine (i.e. an EC2 instance with Ubuntu 14.04) and other resources on [AWS](https://aws.amazon.com/). That machine can then be used to host a one-machine BigchainDB node. +This page explains a way to use [Terraform](https://www.terraform.io/) to provision an Ubuntu machine (i.e. an EC2 instance with Ubuntu 16.04) and other resources on [AWS](https://aws.amazon.com/). That machine can then be used to host a one-machine BigchainDB node. ## Install Terraform @@ -65,7 +65,7 @@ terraform apply Terraform will report its progress as it provisions all the resources. Once it's done, you can go to the Amazon EC2 web console and see the instance, its security group, its elastic IP, and its attached storage volumes (one for the root directory and one for RethinkDB storage). -At this point, there is no software installed on the instance except for Ubuntu 14.04 and whatever else came with the Amazon Machine Image (AMI) specified in the Terraform configuration (files). +At this point, there is no software installed on the instance except for Ubuntu 16.04 and whatever else came with the Amazon Machine Image (AMI) specified in the Terraform configuration (files). The next step is to install, configure and run all the necessary software for a BigchainDB node. You could use [our example Ansible playbook](template-ansible.html) to do that. From 2c26468cea61404d59329be5d055fef80e47dfd6 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 13:51:49 +0100 Subject: [PATCH 131/155] Added some constants to simplify test --- tests/test_config_utils.py | 50 +++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index 7feec4c9..af78585e 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -10,8 +10,13 @@ ORIGINAL_CONFIG = copy.deepcopy(bigchaindb._config) @pytest.fixture(scope='function', autouse=True) -def clean_config(monkeypatch): - monkeypatch.setattr('bigchaindb.config', copy.deepcopy(ORIGINAL_CONFIG)) +def clean_config(monkeypatch, request): + + import bigchaindb + original_config = copy.deepcopy(ORIGINAL_CONFIG) + backend = request.config.getoption('--database-backend') + original_config['database'] = bigchaindb._database_map[backend] + monkeypatch.setattr('bigchaindb.config', original_config) def test_bigchain_instance_is_initialized_when_conf_provided(request): @@ -104,48 +109,55 @@ def test_env_config(monkeypatch): def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): + # constants + DATABASE_HOST = 'test-host' + DATABASE_NAME = 'test-dbname' + DATABASE_PORT = 4242 + DATABASE_BACKEND = request.config.getoption('--database-backend') + SERVER_BIND = '1.2.3.4:56' + KEYRING = 'pubkey_0:pubkey_1:pubkey_2' + file_config = { 'database': { - 'host': 'test-host', - 'backend': request.config.getoption('--database-backend') + 'host': DATABASE_HOST }, 'backlog_reassign_delay': 5 } monkeypatch.setattr('bigchaindb.config_utils.file_config', lambda *args, **kwargs: file_config) - monkeypatch.setattr('os.environ', {'BIGCHAINDB_DATABASE_NAME': 'test-dbname', - 'BIGCHAINDB_DATABASE_PORT': '4242', - 'BIGCHAINDB_SERVER_BIND': '1.2.3.4:56', - 'BIGCHAINDB_KEYRING': 'pubkey_0:pubkey_1:pubkey_2'}) + monkeypatch.setattr('os.environ', {'BIGCHAINDB_DATABASE_NAME': DATABASE_NAME, + 'BIGCHAINDB_DATABASE_PORT': str(DATABASE_PORT), + 'BIGCHAINDB_DATABASE_BACKEND': DATABASE_BACKEND, + 'BIGCHAINDB_SERVER_BIND': SERVER_BIND, + 'BIGCHAINDB_KEYRING': KEYRING}) import bigchaindb from bigchaindb import config_utils config_utils.autoconfigure() - backend = request.config.getoption('--database-backend') database_rethinkdb = { 'backend': 'rethinkdb', - 'host': 'test-host', - 'port': 4242, - 'name': 'test-dbname', + 'host': DATABASE_HOST, + 'port': DATABASE_PORT, + 'name': DATABASE_NAME, } database_mongodb = { 'backend': 'mongodb', - 'host': 'test-host', - 'port': 4242, - 'name': 'test-dbname', + 'host': DATABASE_HOST, + 'port': DATABASE_PORT, + 'name': DATABASE_NAME, 'replicaset': 'bigchain-rs', } database = {} - if backend == 'mongodb': + if DATABASE_BACKEND == 'mongodb': database = database_mongodb - elif backend == 'rethinkdb': + elif DATABASE_BACKEND == 'rethinkdb': database = database_rethinkdb assert bigchaindb.config == { 'CONFIGURED': True, 'server': { - 'bind': '1.2.3.4:56', + 'bind': SERVER_BIND, 'workers': None, 'threads': None, }, @@ -154,7 +166,7 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): 'public': None, 'private': None, }, - 'keyring': ['pubkey_0', 'pubkey_1', 'pubkey_2'], + 'keyring': KEYRING.split(':'), 'statsd': { 'host': 'localhost', 'port': 8125, From 69068fc919279699dbc02da714dea0166a38c336 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 13:53:36 +0100 Subject: [PATCH 132/155] Document how to run BigchainDB with MongoDB (#1116) * Document changes in the configure command. Document new add/remove replicas commands. * updated quickstart with mongodb instructions * Docs on how to setup mongodb dev node with and without docker. Update replSet option in docker-compose * Fixed typo. More explicit on how to run the tests. * Fixed typo in mongodb docker instructions. More explicit about requiring mongodb 3.4+ --- docker-compose.yml | 2 +- .../source/dev-and-test/setup-run-node.md | 88 ++++++++++++++++--- docs/server/source/quickstart.md | 43 ++++++--- .../source/server-reference/bigchaindb-cli.md | 32 ++++++- 4 files changed, 140 insertions(+), 25 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index db8abd4f..f5dbcdc9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: image: mongo:3.4.1 ports: - "27017" - command: mongod --replSet=rs0 + command: mongod --replSet=bigchain-rs rdb: image: rethinkdb diff --git a/docs/server/source/dev-and-test/setup-run-node.md b/docs/server/source/dev-and-test/setup-run-node.md index 0cf5334c..bb7285b4 100644 --- a/docs/server/source/dev-and-test/setup-run-node.md +++ b/docs/server/source/dev-and-test/setup-run-node.md @@ -7,25 +7,27 @@ The BigchainDB core dev team develops BigchainDB on recent Ubuntu and Fedora dis ## Option A: Using a Local Dev Machine -First, read through the BigchainDB [CONTRIBUTING.md file](https://github.com/bigchaindb/bigchaindb/blob/master/CONTRIBUTING.md). It outlines the steps to setup a machine for developing and testing BigchainDB. +Read through the BigchainDB [CONTRIBUTING.md file](https://github.com/bigchaindb/bigchaindb/blob/master/CONTRIBUTING.md). It outlines the steps to setup a machine for developing and testing BigchainDB. -Next, create a default BigchainDB config file (in `$HOME/.bigchaindb`): +### With RethinkDB + +Create a default BigchainDB config file (in `$HOME/.bigchaindb`): ```text -bigchaindb -y configure +$ bigchaindb -y configure rethinkdb ``` Note: [The BigchainDB CLI](../server-reference/bigchaindb-cli.html) and the [BigchainDB Configuration Settings](../server-reference/configuration.html) are documented elsewhere. (Click the links.) Start RethinkDB using: ```text -rethinkdb +$ rethinkdb ``` You can verify that RethinkDB is running by opening the RethinkDB web interface in your web browser. It should be at [http://localhost:8080/](http://localhost:8080/). To run BigchainDB Server, do: ```text -bigchaindb start +$ bigchaindb start ``` You can [run all the unit tests](running-unit-tests.html) to test your installation. @@ -33,13 +35,37 @@ You can [run all the unit tests](running-unit-tests.html) to test your installat The BigchainDB [CONTRIBUTING.md file](https://github.com/bigchaindb/bigchaindb/blob/master/CONTRIBUTING.md) has more details about how to contribute. -## Option B: Using a Dev Machine on Cloud9 +### With MongoDB -Ian Worrall of [Encrypted Labs](http://www.encryptedlabs.com/) wrote a document (PDF) explaining how to set up a BigchainDB (Server) dev machine on Cloud9: +Create a default BigchainDB config file (in `$HOME/.bigchaindb`): +```text +$ bigchaindb -y configure mongodb +``` -[Download that document from GitHub](https://raw.githubusercontent.com/bigchaindb/bigchaindb/master/docs/server/source/_static/cloud9.pdf) +Note: [The BigchainDB CLI](../server-reference/bigchaindb-cli.html) and the [BigchainDB Configuration Settings](../server-reference/configuration.html) are documented elsewhere. (Click the links.) -## Option C: Using a Local Dev Machine and Docker +Start MongoDB __3.4+__ using: +```text +$ mongod --replSet=bigchain-rs +``` + +You can verify that MongoDB is running correctly by checking the output of the +previous command for the line: +```text +waiting for connections on port 27017 +``` + +To run BigchainDB Server, do: +```text +$ bigchaindb start +``` + +You can [run all the unit tests](running-unit-tests.html) to test your installation. + +The BigchainDB [CONTRIBUTING.md file](https://github.com/bigchaindb/bigchaindb/blob/master/CONTRIBUTING.md) has more details about how to contribute. + + +## Option B: Using a Local Dev Machine and Docker You need to have recent versions of [Docker Engine](https://docs.docker.com/engine/installation/) and (Docker) [Compose](https://docs.docker.com/compose/install/). @@ -50,6 +76,8 @@ Build the images: docker-compose build ``` +### Docker with RethinkDB + **Note**: If you're upgrading BigchainDB and have previously already built the images, you may need to rebuild them after the upgrade to install any new dependencies. @@ -62,7 +90,7 @@ docker-compose up -d rdb The RethinkDB web interface should be accessible at . Depending on which platform, and/or how you are running docker, you may need to change `localhost` for the `ip` of the machine that is running docker. As a -dummy example, if the `ip` of that machine was `0.0.0.0`, you would accees the +dummy example, if the `ip` of that machine was `0.0.0.0`, you would access the web interface at: . Start a BigchainDB node: @@ -83,6 +111,40 @@ If you wish to run the tests: docker-compose run --rm bdb py.test -v -n auto ``` +### Docker with MongoDB + +Start MongoDB: + +```bash +docker-compose up -d mdb +``` + +MongoDB should now be up and running. You can check the port binding for the +MongoDB driver port using: +```bash +$ docker-compose port mdb 27017 +``` + +Start a BigchainDB node: + +```bash +docker-compose up -d bdb-mdb +``` + +You can monitor the logs: + +```bash +docker-compose logs -f bdb-mdb +``` + +If you wish to run the tests: + +```bash +docker-compose run --rm bdb-mdb py.test -v --database-backend=mongodb +``` + +### Accessing the HTTP API + A quick check to make sure that the BigchainDB server API is operational: ```bash @@ -123,3 +185,9 @@ root: ```bash curl 0.0.0.0:32772 ``` + +## Option C: Using a Dev Machine on Cloud9 + +Ian Worrall of [Encrypted Labs](http://www.encryptedlabs.com/) wrote a document (PDF) explaining how to set up a BigchainDB (Server) dev machine on Cloud9: + +[Download that document from GitHub](https://raw.githubusercontent.com/bigchaindb/bigchaindb/master/docs/server/source/_static/cloud9.pdf) diff --git a/docs/server/source/quickstart.md b/docs/server/source/quickstart.md index dfe485c5..3c6a78f3 100644 --- a/docs/server/source/quickstart.md +++ b/docs/server/source/quickstart.md @@ -2,34 +2,55 @@ This page has instructions to set up a single stand-alone BigchainDB node for learning or experimenting. Instructions for other cases are [elsewhere](introduction.html). We will assume you're using Ubuntu 16.04 or similar. If you're not using Linux, then you might try [running BigchainDB with Docker](appendices/run-with-docker.html). -A. [Install RethinkDB Server](https://rethinkdb.com/docs/install/ubuntu/) +A. Install the database backend. -B. Open a Terminal and run RethinkDB Server with the command: +[Install RethinkDB Server](https://rethinkdb.com/docs/install/ubuntu/) or +[Install MongoDB Server 3.4+](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/) + +B. Run the database backend. Open a Terminal and run the command: + +with RethinkDB ```text -rethinkdb +$ rethinkdb +``` + +with MongoDB __3.4+__ +```text +$ mongod --replSet=bigchain-rs ``` C. Ubuntu 16.04 already has Python 3.5, so you don't need to install it, but you do need to install some other things: ```text -sudo apt-get update -sudo apt-get install g++ python3-dev libffi-dev +$ sudo apt-get update +$ sudo apt-get install g++ python3-dev libffi-dev ``` D. Get the latest version of pip and setuptools: ```text -sudo apt-get install python3-pip -sudo pip3 install --upgrade pip setuptools +$ sudo apt-get install python3-pip +$ sudo pip3 install --upgrade pip setuptools ``` E. Install the `bigchaindb` Python package from PyPI: ```text -sudo pip3 install bigchaindb +$ sudo pip3 install bigchaindb ``` -F. Configure and run BigchainDB Server: +F. Configure the BigchainDB Server: and run BigchainDB Server: + +with RethinkDB ```text -bigchaindb -y configure -bigchaindb start +$ bigchaindb -y configure rethinkdb +``` + +with MongoDB +```text +$ bigchaindb -y configure mongodb +``` + +G. Run the BigchainDB Server: +```text +$ bigchaindb start ``` That's it! diff --git a/docs/server/source/server-reference/bigchaindb-cli.md b/docs/server/source/server-reference/bigchaindb-cli.md index 869ef804..f647b4bf 100644 --- a/docs/server/source/server-reference/bigchaindb-cli.md +++ b/docs/server/source/server-reference/bigchaindb-cli.md @@ -15,18 +15,22 @@ Show the version number. `bigchaindb -v` does the same thing. ## bigchaindb configure -Generate a local config file (which can be used to set some or all [BigchainDB node configuration settings](configuration.html)). It will auto-generate a public-private keypair and then ask you for the values of other configuration settings. If you press Enter for a value, it will use the default value. +Generate a local configuration file (which can be used to set some or all [BigchainDB node configuration settings](configuration.html)). It will auto-generate a public-private keypair and then ask you for the values of other configuration settings. If you press Enter for a value, it will use the default value. + +Since BigchainDB supports multiple databases you need to always specify the +database backend that you want to use. At this point only two database backends +are supported: `rethinkdb` and `mongodb`. If you use the `-c` command-line option, it will generate the file at the specified path: ```text -bigchaindb -c path/to/new_config.json configure +bigchaindb -c path/to/new_config.json configure rethinkdb ``` If you don't use the `-c` command-line option, the file will be written to `$HOME/.bigchaindb` (the default location where BigchainDB looks for a config file, if one isn't specified). If you use the `-y` command-line option, then there won't be any interactive prompts: it will just generate a keypair and use the default values for all the other configuration settings. ```text -bigchaindb -y configure +bigchaindb -y configure rethinkdb ``` @@ -83,3 +87,25 @@ Set the number of replicas (of each shard) in the underlying datastore. For exam ```text $ bigchaindb set-replicas 3 ``` + +## bigchaindb add-replicas + +This command is specific to MongoDB so it will only run if BigchainDB is +configured with `mongodb` as the backend. + +This command is used to add nodes to a BigchainDB cluster. It accepts a list of +space separated hosts in the form _hostname:port_: +```text +$ bigchaindb add-replicas server1.com:27017 server2.com:27017 server3.com:27017 +``` + +## bigchaindb remove-replicas + +This command is specific to MongoDB so it will only run if BigchainDB is +configured with `mongodb` as the backend. + +This command is used to remove nodes from a BigchainDB cluster. It accepts a +list of space separated hosts in the form _hostname:port_: +```text +$ bigchaindb remove-replicas server1.com:27017 server2.com:27017 server3.com:27017 +``` From f0e298bcd7d436ffd42a9562ac1495952a64dc8e Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 14:54:36 +0100 Subject: [PATCH 133/155] Added docstrings. Removed unnecessary returns. Created fixture to simplify the tests. Better comments. --- bigchaindb/backend/mongodb/admin.py | 28 ++++++++++++++---- tests/backend/mongodb/test_admin.py | 44 +++++++++++------------------ 2 files changed, 40 insertions(+), 32 deletions(-) diff --git a/bigchaindb/backend/mongodb/admin.py b/bigchaindb/backend/mongodb/admin.py index 3c2001d5..afe909ac 100644 --- a/bigchaindb/backend/mongodb/admin.py +++ b/bigchaindb/backend/mongodb/admin.py @@ -18,13 +18,20 @@ def add_replicas(connection, replicas): """Add a set of replicas to the replicaset Args: - replicas list of strings: of the form "hostname:port". + connection (:class:`~bigchaindb.backend.connection.Connection`): + A connection to the database. + replicas (:obj:`list` of :obj:`str`): replica addresses in the + form "hostname:port". + + Raises: + DatabaseOpFailedError: If the reconfiguration fails due to a MongoDB + :exc:`OperationFailure` """ # get current configuration conf = connection.conn.admin.command('replSetGetConfig') - # MongoDB does not automatically add and id for the members so we need - # to chose one that does not exists yet. The safest way is to use + # MongoDB does not automatically add an id for the members so we need + # to choose one that does not exists yet. The safest way is to use # incrementing ids, so we first check what is the highest id already in # the set and continue from there. cur_id = max([member['_id'] for member in conf['config']['members']]) @@ -35,11 +42,13 @@ def add_replicas(connection, replicas): conf['config']['members'].append({'_id': cur_id, 'host': replica}) # increase the configuration version number + # when reconfiguring, mongodb expects a version number higher than the one + # it currently has conf['config']['version'] += 1 # apply new configuration try: - return connection.conn.admin.command('replSetReconfig', conf['config']) + connection.conn.admin.command('replSetReconfig', conf['config']) except OperationFailure as exc: raise DatabaseOpFailedError(exc.details['errmsg']) @@ -48,6 +57,15 @@ def add_replicas(connection, replicas): def remove_replicas(connection, replicas): """Remove a set of replicas from the replicaset + Args: + connection (:class:`~bigchaindb.backend.connection.Connection`): + A connection to the database. + replicas (:obj:`list` of :obj:`str`): replica addresses in the + form "hostname:port". + + Raises: + DatabaseOpFailedError: If the reconfiguration fails due to a MongoDB + :exc:`OperationFailure` """ # get the current configuration conf = connection.conn.admin.command('replSetGetConfig') @@ -63,6 +81,6 @@ def remove_replicas(connection, replicas): # apply new configuration try: - return connection.conn.admin.command('replSetReconfig', conf['config']) + connection.conn.admin.command('replSetReconfig', conf['config']) except OperationFailure as exc: raise DatabaseOpFailedError(exc.details['errmsg']) diff --git a/tests/backend/mongodb/test_admin.py b/tests/backend/mongodb/test_admin.py index 138bc616..a7784369 100644 --- a/tests/backend/mongodb/test_admin.py +++ b/tests/backend/mongodb/test_admin.py @@ -30,14 +30,22 @@ def mock_replicaset_config(): } -def test_add_replicas(mock_replicaset_config): +@pytest.fixture +def connection(): from bigchaindb.backend import connect - from bigchaindb.backend.admin import add_replicas - connection = connect() - # force the connection object to setup a connection to the database - # before we mock `Database.command` - connection.conn + # connection is a lazy object. It only actually creates a connection to + # the database when its first used. + # During the setup of a MongoDBConnection some `Database.command` are + # executed to make sure that the replica set is correctly initialized. + # Here we force the the connection setup so that all required + # `Database.command` are executed before we mock them it in the tests. + connection._connect() + return connection + + +def test_add_replicas(mock_replicaset_config, connection): + from bigchaindb.backend.admin import add_replicas expected_config = copy.deepcopy(mock_replicaset_config) expected_config['config']['members'] += [ @@ -54,16 +62,10 @@ def test_add_replicas(mock_replicaset_config): expected_config['config']) -def test_add_replicas_raises(mock_replicaset_config): - from bigchaindb.backend import connect +def test_add_replicas_raises(mock_replicaset_config, connection): from bigchaindb.backend.admin import add_replicas from bigchaindb.backend.exceptions import DatabaseOpFailedError - connection = connect() - # force the connection object to setup a connection to the database - # before we mock `Database.command` - connection.conn - with mock.patch.object(Database, 'command') as mock_command: mock_command.side_effect = [ mock_replicaset_config, @@ -73,15 +75,9 @@ def test_add_replicas_raises(mock_replicaset_config): add_replicas(connection, ['localhost:27018']) -def test_remove_replicas(mock_replicaset_config): - from bigchaindb.backend import connect +def test_remove_replicas(mock_replicaset_config, connection): from bigchaindb.backend.admin import remove_replicas - connection = connect() - # force the connection object to setup a connection to the database - # before we mock `Database.command` - connection.conn - expected_config = copy.deepcopy(mock_replicaset_config) expected_config['config']['version'] += 1 @@ -99,16 +95,10 @@ def test_remove_replicas(mock_replicaset_config): expected_config['config']) -def test_remove_replicas_raises(mock_replicaset_config): - from bigchaindb.backend import connect +def test_remove_replicas_raises(mock_replicaset_config, connection): from bigchaindb.backend.admin import remove_replicas from bigchaindb.backend.exceptions import DatabaseOpFailedError - connection = connect() - # force the connection object to setup a connection to the database - # before we mock `Database.command` - connection.conn - with mock.patch.object(Database, 'command') as mock_command: mock_command.side_effect = [ mock_replicaset_config, From b68557507f2ab7ad0720e0745180ab6be076eabc Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Tue, 31 Jan 2017 15:40:39 +0100 Subject: [PATCH 134/155] Updated Ansible playbooks & docs for Ubuntu 16.04 deployment --- .../template-ansible.md | 22 ++++++++++++------- ntools/one-m/ansible/install-python2.yml | 15 +++++++++++++ .../ansible/roles/bigchaindb/tasks/main.yml | 18 ++++++++------- .../ansible/roles/db_storage/tasks/main.yml | 4 +++- .../ansible/roles/rethinkdb/tasks/main.yml | 9 ++++---- 5 files changed, 47 insertions(+), 21 deletions(-) create mode 100644 ntools/one-m/ansible/install-python2.yml diff --git a/docs/server/source/cloud-deployment-starter-templates/template-ansible.md b/docs/server/source/cloud-deployment-starter-templates/template-ansible.md index 1fd55950..e71d4cc1 100644 --- a/docs/server/source/cloud-deployment-starter-templates/template-ansible.md +++ b/docs/server/source/cloud-deployment-starter-templates/template-ansible.md @@ -2,12 +2,12 @@ If you didn't read the introduction to the [cloud deployment starter templates](index.html), please do that now. The main point is that they're not for deploying a production node; they can be used as a starting point. -This page explains how to use [Ansible](https://www.ansible.com/) to install, configure and run all the software needed to run a one-machine BigchainDB node on a server running Ubuntu 14.04. +This page explains how to use [Ansible](https://www.ansible.com/) to install, configure and run all the software needed to run a one-machine BigchainDB node on a server running Ubuntu 16.04. ## Install Ansible -The Ansible documentation has [installation instructions](https://docs.ansible.com/ansible/intro_installation.html). Note the control machine requirements: at the time of writing, Ansible required Python 2.6 or 2.7. (Support for Python 3 [is a goal of Ansible 2.2](https://github.com/ansible/ansible/issues/15976#issuecomment-221264089).) +The Ansible documentation has [installation instructions](https://docs.ansible.com/ansible/intro_installation.html). Note the control machine requirements: at the time of writing, Ansible required Python 2.6 or 2.7. ([Python 3 support is coming](https://docs.ansible.com/ansible/python_3_support.html): "Ansible 2.2 features a tech preview of Python 3 support." and the latest version, as of January 31, 2017, was 2.2.1.0. For now, it's probably best to use it with Python 2.) For example, you could create a special Python 2.x virtualenv named `ansenv` and then install Ansible in it: ```text @@ -19,9 +19,9 @@ pip install ansible ## About Our Example Ansible Playbook -Our example Ansible playbook installs, configures and runs a basic BigchainDB node on an Ubuntu 14.04 machine. That playbook is in `.../bigchaindb/ntools/one-m/ansible/one-m-node.yml`. +Our example Ansible playbook installs, configures and runs a basic BigchainDB node on an Ubuntu 16.04 machine. That playbook is in `.../bigchaindb/ntools/one-m/ansible/one-m-node.yml`. -When you run the playbook (as per the instructions below), it ensures all the necessary software is installed, configured and running. It can be used to get a BigchainDB node set up on a bare Ubuntu 14.04 machine, but it can also be used to ensure that everything is okay on a running BigchainDB node. (If you run the playbook against a host where everything is okay, then it won't change anything on that host.) +When you run the playbook (as per the instructions below), it ensures all the necessary software is installed, configured and running. It can be used to get a BigchainDB node set up on a bare Ubuntu 16.04 machine, but it can also be used to ensure that everything is okay on a running BigchainDB node. (If you run the playbook against a host where everything is okay, then it won't change anything on that host.) ## Create an Ansible Inventory File @@ -39,7 +39,15 @@ echo "192.0.2.128" > hosts but replace `192.0.2.128` with the IP address of the host. -## Run the Ansible Playbook +## Run the Ansible Playbook(s) + +The latest Ubuntu 16.04 AMIs from Canonical don't include Python 2 (which is required by Ansible), so the first step is to run a small Ansible playbook to install Python 2 on the managed node: +```text +# cd to the directory .../bigchaindb/ntools/one-m/ansible +ansible-playbook -i hosts --private-key ~/.ssh/ install-python2.yml +``` + +where `` should be replaced by the name of the SSH private key you created earlier (for SSHing to the host machine at your cloud hosting provider). The next step is to run the Ansible playbook named `one-m-node.yml`: ```text @@ -47,14 +55,12 @@ The next step is to run the Ansible playbook named `one-m-node.yml`: ansible-playbook -i hosts --private-key ~/.ssh/ one-m-node.yml ``` -where `` should be replaced by the name of the SSH private key you created earlier (for SSHing to the host machine at your cloud hosting provider). - What did you just do? Running that playbook ensures all the software necessary for a one-machine BigchainDB node is installed, configured, and running properly. You can run that playbook on a regular schedule to ensure that the system stays properly configured. If something is okay, it does nothing; it only takes action when something is not as-desired. ## Some Notes on the One-Machine Node You Just Got Running -* It ensures that the installed version of RethinkDB is `2.3.4~0trusty`. You can change that by changing the installation task. +* It ensures that the installed version of RethinkDB is the latest. You can change that by changing the installation task. * It uses a very basic RethinkDB configuration file based on `bigchaindb/ntools/one-m/ansible/roles/rethinkdb/templates/rethinkdb.conf.j2`. * If you edit the RethinkDB configuration file, then running the Ansible playbook will **not** restart RethinkDB for you. You must do that manually. (You can stop RethinkDB using `sudo /etc/init.d/rethinkdb stop`; run the playbook to get RethinkDB started again. This assumes you're using init.d, which is what the Ansible playbook assumes. If you want to use systemd, you'll have to edit the playbook accordingly, and stop RethinkDB using `sudo systemctl stop rethinkdb@`.) * It generates and uses a default BigchainDB configuration file, which it stores in `~/.bigchaindb` (the default location). diff --git a/ntools/one-m/ansible/install-python2.yml b/ntools/one-m/ansible/install-python2.yml new file mode 100644 index 00000000..54dd7d0a --- /dev/null +++ b/ntools/one-m/ansible/install-python2.yml @@ -0,0 +1,15 @@ +--- +# This playbook ensures Python 2 is installed on the managed node. +# This is inspired by https://gist.github.com/gwillem/4ba393dceb55e5ae276a87300f6b8e6f + +- hosts: all + gather_facts: false + remote_user: ubuntu + + pre_tasks: + - name: Install Python 2 + raw: test -e /usr/bin/python || (apt -y update && apt install -y python-minimal) + become: true + + # action: setup will gather facts after python2 has been installed + - action: setup diff --git a/ntools/one-m/ansible/roles/bigchaindb/tasks/main.yml b/ntools/one-m/ansible/roles/bigchaindb/tasks/main.yml index 7ed7e992..5632bf9e 100644 --- a/ntools/one-m/ansible/roles/bigchaindb/tasks/main.yml +++ b/ntools/one-m/ansible/roles/bigchaindb/tasks/main.yml @@ -10,22 +10,24 @@ apt: name={{item}} state=latest update_cache=yes become: true with_items: + - make - git - g++ - - python3-dev - libffi-dev - - python3-setuptools # mainly for easy_install3, which is used to get latest pip3 - -# This should make both pip and pip3 be pip version >=8.1.2 (python 3.4). -# See the comments about this below. -- name: Ensure the latest pip/pip3 is installed, using easy_install3 - easy_install: executable=easy_install3 name=pip state=latest - become: true + - python3-dev + - python3-pip + - python3-setuptools - name: Ensure the latest setuptools (Python package) is installed pip: executable=pip3 name=setuptools state=latest become: true +# This should make both pip and pip3 be pip version >=8.1.2 (python 3.4). +# See the comments about this below. +#- name: Ensure the latest pip/pip3 is installed, using easy_install3 +# easy_install: executable=easy_install3 name=pip state=latest +# become: true + - name: Install BigchainDB from PyPI using sudo pip3 install bigchaindb pip: executable=pip3 name=bigchaindb state=latest become: true diff --git a/ntools/one-m/ansible/roles/db_storage/tasks/main.yml b/ntools/one-m/ansible/roles/db_storage/tasks/main.yml index 618a154f..0cb93555 100644 --- a/ntools/one-m/ansible/roles/db_storage/tasks/main.yml +++ b/ntools/one-m/ansible/roles/db_storage/tasks/main.yml @@ -12,12 +12,14 @@ # To better understand the /etc/fstab fields/columns, see: # http://man7.org/linux/man-pages/man5/fstab.5.html # https://tinyurl.com/jmmsyon = the soure code of the mount module +# Note: It seems the "nobootwait" option is gone in Ubuntu 16.04. See +# https://askubuntu.com/questions/786928/ubuntu-16-04-fstab-fails-with-nobootwait - name: Ensure /data dir exists and is mounted + update /etc/fstab mount: name=/data src=/dev/xvdp fstype=ext4 - opts="defaults,nofail,nobootwait" + opts="defaults,nofail" dump=0 passno=2 state=mounted diff --git a/ntools/one-m/ansible/roles/rethinkdb/tasks/main.yml b/ntools/one-m/ansible/roles/rethinkdb/tasks/main.yml index 61f3fd52..994a7d4f 100644 --- a/ntools/one-m/ansible/roles/rethinkdb/tasks/main.yml +++ b/ntools/one-m/ansible/roles/rethinkdb/tasks/main.yml @@ -2,11 +2,12 @@ # ansible/roles/rethinkdb/tasks/main.yml # Note: the .list extension will be added to the rethinkdb filename automatically +# Note: xenial is the $DISTRIB_CODENAME for Ubuntu 16.04 - name: > - Ensure RethinkDB's APT repository for Ubuntu trusty is present + Ensure RethinkDB's APT repository for Ubuntu xenial is present in /etc/apt/sources.list.d/rethinkdb.list apt_repository: - repo='deb http://download.rethinkdb.com/apt trusty main' + repo='deb http://download.rethinkdb.com/apt xenial main' filename=rethinkdb state=present become: true @@ -15,8 +16,8 @@ apt_key: url=http://download.rethinkdb.com/apt/pubkey.gpg state=present become: true -- name: Ensure the Ubuntu package rethinkdb 2.3.4~0trusty is installed - apt: name=rethinkdb=2.3.4~0trusty state=present update_cache=yes +- name: Ensure the latest rethinkdb package is installed + apt: name=rethinkdb state=latest update_cache=yes become: true - name: Ensure the /data directory's owner and group are both 'rethinkdb' From 248e89a666be55c32f4dd206b5b2994da7b5734e Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 31 Jan 2017 15:43:46 +0100 Subject: [PATCH 135/155] unicode tests uses serialize() and includes info about unicode symbol --- tests/db/test_bigchain_api.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index aa8488c4..129b77c4 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1226,11 +1226,15 @@ def test_cant_spend_same_input_twice_in_tx(b, genesis_block): @pytest.mark.bdb def test_transaction_unicode(b): - import json + from bigchaindb.common.utils import serialize from bigchaindb.models import Transaction - tx = (Transaction.create([b.me], [([b.me], 100)], - {'beer': '\N{BEER MUG}'}) + + # http://www.fileformat.info/info/unicode/char/1f37a/index.htm + beer_python = {'beer': '\N{BEER MUG}'} + beer_json = '{"beer":"\N{BEER MUG}"}' + + tx = (Transaction.create([b.me], [([b.me], 100)], beer_python) ).sign([b.me_private]) block = b.create_block([tx]) assert block.validate(b) == block - assert '{"beer": "\\ud83c\\udf7a"}' in json.dumps(block.to_dict()) + assert beer_json in serialize(block.to_dict()) From 2af8fcb91863317794a2a8f9c772a394832f718e Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 31 Jan 2017 15:48:34 +0100 Subject: [PATCH 136/155] test unicode write block to disk --- tests/db/test_bigchain_api.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/db/test_bigchain_api.py b/tests/db/test_bigchain_api.py index 129b77c4..31abe176 100644 --- a/tests/db/test_bigchain_api.py +++ b/tests/db/test_bigchain_api.py @@ -1236,5 +1236,7 @@ def test_transaction_unicode(b): tx = (Transaction.create([b.me], [([b.me], 100)], beer_python) ).sign([b.me_private]) block = b.create_block([tx]) + b.write_block(block) + assert b.get_block(block.id) == block.to_dict() assert block.validate(b) == block assert beer_json in serialize(block.to_dict()) From 70e9a7a33cdd1bab80235544b6f2777606eaa7c5 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Tue, 31 Jan 2017 16:03:57 +0100 Subject: [PATCH 137/155] Updated many docs pages from Ubuntu 14.04 to 16.04 --- docs/server/source/appendices/install-latest-pip.md | 2 +- .../source/appendices/install-os-level-deps.md | 4 ++-- docs/server/source/appendices/install-with-lxd.md | 2 ++ docs/server/source/appendices/ntp-notes.md | 4 ++-- .../source/clusters-feds/aws-testing-cluster.md | 6 +++--- docs/server/source/nodes/node-requirements.md | 2 +- docs/server/source/nodes/setup-run-node.md | 12 ++---------- 7 files changed, 13 insertions(+), 19 deletions(-) diff --git a/docs/server/source/appendices/install-latest-pip.md b/docs/server/source/appendices/install-latest-pip.md index fac7dbed..97405882 100644 --- a/docs/server/source/appendices/install-latest-pip.md +++ b/docs/server/source/appendices/install-latest-pip.md @@ -7,7 +7,7 @@ pip -V If it says that `pip` isn't installed, or it says `pip` is associated with a Python version less than 3.4, then you must install a `pip` version associated with Python 3.4+. In the following instructions, we call it `pip3` but you may be able to use `pip` if that refers to the same thing. See [the `pip` installation instructions](https://pip.pypa.io/en/stable/installing/). -On Ubuntu 14.04, we found that this works: +On Ubuntu 16.04, we found that this works: ```text sudo apt-get install python3-pip ``` diff --git a/docs/server/source/appendices/install-os-level-deps.md b/docs/server/source/appendices/install-os-level-deps.md index aa0df363..f1c4da99 100644 --- a/docs/server/source/appendices/install-os-level-deps.md +++ b/docs/server/source/appendices/install-os-level-deps.md @@ -2,13 +2,13 @@ BigchainDB Server has some OS-level dependencies that must be installed. -On Ubuntu 14.04 and 16.04, we found that the following was enough: +On Ubuntu 16.04, we found that the following was enough: ```text sudo apt-get update sudo apt-get install g++ python3-dev libffi-dev ``` -On Fedora 23 and 24, we found that the following was enough: +On Fedora 23–25, we found that the following was enough: ```text sudo dnf update sudo dnf install gcc-c++ redhat-rpm-config python3-devel libffi-devel diff --git a/docs/server/source/appendices/install-with-lxd.md b/docs/server/source/appendices/install-with-lxd.md index cb12b4ff..969f6841 100644 --- a/docs/server/source/appendices/install-with-lxd.md +++ b/docs/server/source/appendices/install-with-lxd.md @@ -1,5 +1,7 @@ # Installing BigchainDB on LXC containers using LXD +**Note: This page was contributed by an external contributor and is not actively maintained. We include it in case someone is interested.** + You can visit this link to install LXD (instructions here): [LXD Install](https://linuxcontainers.org/lxd/getting-started-cli/) (assumption is that you are using Ubuntu 14.04 for host/container) diff --git a/docs/server/source/appendices/ntp-notes.md b/docs/server/source/appendices/ntp-notes.md index 08861cb1..c1a2b261 100644 --- a/docs/server/source/appendices/ntp-notes.md +++ b/docs/server/source/appendices/ntp-notes.md @@ -23,9 +23,9 @@ If your BigchainDB node is running on an Amazon Linux instance (i.e. a Linux ins That said, you should check _which_ NTP daemon is installed. Is it recent? Is it configured securely? -## Ubuntu's ntp Package +## The Ubuntu ntp Packages -The [Ubuntu 14.04 (Trusty Tahr) package `ntp`](https://launchpad.net/ubuntu/trusty/+source/ntp) is based on the reference implementation of an NTP daemon (i.e. `ntpd`). +The [Ubuntu `ntp` packages](https://launchpad.net/ubuntu/+source/ntp) are based on the reference implementation of NTP. The following commands will uninstall the `ntp` and `ntpdate` packages, install the latest `ntp` package (which _might not be based on the latest ntpd code_), and start the NTP daemon (a local NTP server). (`ntpdate` is not reinstalled because it's [deprecated](https://askubuntu.com/questions/297560/ntpd-vs-ntpdate-pros-and-cons) and you shouldn't use it.) ```text diff --git a/docs/server/source/clusters-feds/aws-testing-cluster.md b/docs/server/source/clusters-feds/aws-testing-cluster.md index 2df15917..fbc623f3 100644 --- a/docs/server/source/clusters-feds/aws-testing-cluster.md +++ b/docs/server/source/clusters-feds/aws-testing-cluster.md @@ -14,11 +14,11 @@ We use some Bash and Python scripts to launch several instances (virtual servers ## Python Setup -The instructions that follow have been tested on Ubuntu 14.04, but may also work on similar distros or operating systems. +The instructions that follow have been tested on Ubuntu 16.04. Similar instructions should work on similar Linux distros. **Note: Our Python scripts for deploying to AWS use Python 2 because Fabric doesn't work with Python 3.** -You must install the Python package named `fabric`, but it depends on the `cryptography` package, and that depends on some OS-level packages. On Ubuntu 14.04, you can install those OS-level packages using: +You must install the Python package named `fabric`, but it depends on the `cryptography` package, and that depends on some OS-level packages. On Ubuntu 16.04, you can install those OS-level packages using: ```text sudo apt-get install build-essential libssl-dev libffi-dev python-dev ``` @@ -72,7 +72,7 @@ One way to monitor a BigchainDB cluster is to use the monitoring setup described You can deploy a monitoring server on AWS. To do that, go to the AWS EC2 Console and launch an instance: -1. Choose an AMI: select Ubuntu Server 14.04 LTS. +1. Choose an AMI: select Ubuntu Server 16.04 LTS. 2. Choose an Instance Type: a t2.micro will suffice. 3. Configure Instance Details: you can accept the defaults, but feel free to change them. 4. Add Storage: A "Root" volume type should already be included. You _could_ store monitoring data there (e.g. in a folder named `/influxdb-data`) but we will attach another volume and store the monitoring data there instead. Select "Add New Volume" and an EBS volume type. diff --git a/docs/server/source/nodes/node-requirements.md b/docs/server/source/nodes/node-requirements.md index bd72b9f4..56d52f13 100644 --- a/docs/server/source/nodes/node-requirements.md +++ b/docs/server/source/nodes/node-requirements.md @@ -9,7 +9,7 @@ Note: This section will be broken apart into several pages, e.g. NTP requirement * BigchainDB Server requires Python 3.4+ and Python 3.4+ [will run on any modern OS](https://docs.python.org/3.4/using/index.html). * BigchaindB Server uses the Python `multiprocessing` package and [some functionality in the `multiprocessing` package doesn't work on OS X](https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.Queue.qsize). You can still use Mac OS X if you use Docker or a virtual machine. -The BigchainDB core dev team uses Ubuntu 14.04, Ubuntu 16.04, Fedora 23, and Fedora 24. +The BigchainDB core dev team uses recent LTS versions of Ubuntu and recent versions of Fedora. We don't test BigchainDB on Windows or Mac OS X, but you can try. diff --git a/docs/server/source/nodes/setup-run-node.md b/docs/server/source/nodes/setup-run-node.md index b8de7340..2feb800d 100644 --- a/docs/server/source/nodes/setup-run-node.md +++ b/docs/server/source/nodes/setup-run-node.md @@ -96,20 +96,12 @@ If you're testing or developing BigchainDB on a stand-alone node, then you shoul BigchainDB Server has some OS-level dependencies that must be installed. -On Ubuntu 14.04, we found that the following was enough: +On Ubuntu 16.04, we found that the following was enough: ```text sudo apt-get update sudo apt-get install g++ python3-dev libffi-dev ``` -On Fedora 23, we found that the following was enough (tested in February 2015): -```text -sudo dnf update -sudo dnf install gcc-c++ redhat-rpm-config python3-devel libffi-devel -``` - -(If you're using a version of Fedora before version 22, you may have to use `yum` instead of `dnf`.) - With OS-level dependencies installed, you can install BigchainDB Server with `pip` or from source. @@ -122,7 +114,7 @@ pip -V If it says that `pip` isn't installed, or it says `pip` is associated with a Python version less than 3.4, then you must install a `pip` version associated with Python 3.4+. In the following instructions, we call it `pip3` but you may be able to use `pip` if that refers to the same thing. See [the `pip` installation instructions](https://pip.pypa.io/en/stable/installing/). -On Ubuntu 14.04, we found that this works: +On Ubuntu 16.04, we found that this works: ```text sudo apt-get install python3-pip ``` From 9913929b9d3c12af8a073445016a4ec3e0512940 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 16:14:18 +0100 Subject: [PATCH 138/155] simplify run_configure --- bigchaindb/commands/bigchain.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/bigchaindb/commands/bigchain.py b/bigchaindb/commands/bigchain.py index 2fc8df70..272f8107 100644 --- a/bigchaindb/commands/bigchain.py +++ b/bigchaindb/commands/bigchain.py @@ -89,12 +89,7 @@ def run_configure(args, skip_if_exists=False): # select the correct config defaults based on the backend print('Generating default configuration for backend {}' .format(args.backend)) - database = {} - if args.backend == 'rethinkdb': - database = bigchaindb._database_rethinkdb - elif args.backend == 'mongodb': - database = bigchaindb._database_mongodb - conf['database'] = database + conf['database'] = bigchaindb._database_map[args.backend] if not args.yes: for key in ('bind', ): From 88ea6c6564aac020a83468f7ce56c83494383536 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Tue, 31 Jan 2017 16:18:20 +0100 Subject: [PATCH 139/155] In setup-run-node.md, link to page in Appendices re/ installing OS-level deps --- docs/server/source/nodes/setup-run-node.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/docs/server/source/nodes/setup-run-node.md b/docs/server/source/nodes/setup-run-node.md index 2feb800d..9d0a4892 100644 --- a/docs/server/source/nodes/setup-run-node.md +++ b/docs/server/source/nodes/setup-run-node.md @@ -94,13 +94,7 @@ If you're testing or developing BigchainDB on a stand-alone node, then you shoul ## Install BigchainDB Server -BigchainDB Server has some OS-level dependencies that must be installed. - -On Ubuntu 16.04, we found that the following was enough: -```text -sudo apt-get update -sudo apt-get install g++ python3-dev libffi-dev -``` +First, [install the OS-level dependencies of BigchainDB Server (link)](../appendices/install-os-level-deps.html). With OS-level dependencies installed, you can install BigchainDB Server with `pip` or from source. From 84626b6e327369c3e3ee521638ecac6fff8b7598 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Tue, 31 Jan 2017 16:23:09 +0100 Subject: [PATCH 140/155] Improved tests Fixed typo Add extra validation to hostnames to make sure host is not empty --- bigchaindb/backend/mongodb/admin.py | 2 +- bigchaindb/commands/utils.py | 2 +- tests/commands/test_commands.py | 22 ++++++++++++++++++++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/bigchaindb/backend/mongodb/admin.py b/bigchaindb/backend/mongodb/admin.py index afe909ac..7d72c3a4 100644 --- a/bigchaindb/backend/mongodb/admin.py +++ b/bigchaindb/backend/mongodb/admin.py @@ -31,7 +31,7 @@ def add_replicas(connection, replicas): conf = connection.conn.admin.command('replSetGetConfig') # MongoDB does not automatically add an id for the members so we need - # to choose one that does not exists yet. The safest way is to use + # to choose one that does not exist yet. The safest way is to use # incrementing ids, so we first check what is the highest id already in # the set and continue from there. cur_id = max([member['_id'] for member in conf['config']['members']]) diff --git a/bigchaindb/commands/utils.py b/bigchaindb/commands/utils.py index 7b662308..80ee7a6b 100644 --- a/bigchaindb/commands/utils.py +++ b/bigchaindb/commands/utils.py @@ -116,7 +116,7 @@ def mongodb_host(host): raise argparse.ArgumentTypeError(exc.args[0]) # we do require the port to be provided. - if port is None: + if port is None or hostname == '': raise argparse.ArgumentTypeError('expected host in the form ' '`host:port`. Got `{}` instead.' .format(host)) diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index 16b615eb..95bb0db7 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -22,6 +22,8 @@ def test_make_sure_we_dont_remove_any_command(): assert parser.parse_args(['set-shards', '1']).command assert parser.parse_args(['set-replicas', '1']).command assert parser.parse_args(['load']).command + assert parser.parse_args(['add-replicas', 'localhost:27017']).command + assert parser.parse_args(['remove-replicas', 'localhost:27017']).command def test_start_raises_if_command_not_implemented(): @@ -379,7 +381,7 @@ def test_calling_main(start_mock, base_parser_mock, parse_args_mock, @pytest.mark.usefixtures('ignore_local_config_file') -@patch('bigchaindb.backend.admin.add_replicas') +@patch('bigchaindb.commands.bigchain.add_replicas') def test_run_add_replicas(mock_add_replicas): from bigchaindb.commands.bigchain import run_add_replicas from bigchaindb.backend.exceptions import DatabaseOpFailedError @@ -389,18 +391,24 @@ def test_run_add_replicas(mock_add_replicas): # test add_replicas no raises mock_add_replicas.return_value = None assert run_add_replicas(args) is None + assert mock_add_replicas.call_count == 1 + mock_add_replicas.reset_mock() # test add_replicas with `DatabaseOpFailedError` mock_add_replicas.side_effect = DatabaseOpFailedError() assert run_add_replicas(args) is None + assert mock_add_replicas.call_count == 1 + mock_add_replicas.reset_mock() # test add_replicas with `NotImplementedError` mock_add_replicas.side_effect = NotImplementedError() assert run_add_replicas(args) is None + assert mock_add_replicas.call_count == 1 + mock_add_replicas.reset_mock() @pytest.mark.usefixtures('ignore_local_config_file') -@patch('bigchaindb.backend.admin.remove_replicas') +@patch('bigchaindb.commands.bigchain.remove_replicas') def test_run_remove_replicas(mock_remove_replicas): from bigchaindb.commands.bigchain import run_remove_replicas from bigchaindb.backend.exceptions import DatabaseOpFailedError @@ -410,14 +418,20 @@ def test_run_remove_replicas(mock_remove_replicas): # test add_replicas no raises mock_remove_replicas.return_value = None assert run_remove_replicas(args) is None + assert mock_remove_replicas.call_count == 1 + mock_remove_replicas.reset_mock() # test add_replicas with `DatabaseOpFailedError` mock_remove_replicas.side_effect = DatabaseOpFailedError() assert run_remove_replicas(args) is None + assert mock_remove_replicas.call_count == 1 + mock_remove_replicas.reset_mock() # test add_replicas with `NotImplementedError` mock_remove_replicas.side_effect = NotImplementedError() assert run_remove_replicas(args) is None + assert mock_remove_replicas.call_count == 1 + mock_remove_replicas.reset_mock() def test_mongodb_host_type(): @@ -430,3 +444,7 @@ def test_mongodb_host_type(): # no port information provided with pytest.raises(ArgumentTypeError): mongodb_host('localhost') + + # bad host provided + with pytest.raises(ArgumentTypeError): + mongodb_host(':27017') From aae60ea467b085ed6234b5594eae2bd3ef592c28 Mon Sep 17 00:00:00 2001 From: "krish7919 (Krish)" Date: Tue, 31 Jan 2017 17:03:02 +0100 Subject: [PATCH 141/155] Solves #1105. The `apt-get update` command executed with the install instructions should not use a locally cached storage layer. --- Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index c181625a..54fdc41b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,9 +11,9 @@ RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \ ENV LANG en_US.UTF-8 -RUN apt-get -y install python3 python3-pip libffi-dev -RUN pip3 install --upgrade pip -RUN pip3 install --upgrade setuptools +RUN apt-get update && apt-get -y install python3 python3-pip libffi-dev \ + && pip3 install --upgrade pip \ + && pip3 install --upgrade setuptools RUN mkdir -p /usr/src/app From b318d62f7ec76f308f4d06e19c3951b0bee6cf5b Mon Sep 17 00:00:00 2001 From: "krish7919 (Krish)" Date: Tue, 31 Jan 2017 17:34:25 +0100 Subject: [PATCH 142/155] Update Dockerfile with comments on force refresh --- Dockerfile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Dockerfile b/Dockerfile index 54fdc41b..f5e4b3b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,6 +11,9 @@ RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \ ENV LANG en_US.UTF-8 +# The `apt-get update` command executed with the install instructions should +# not use a locally cached storage layer. Force update the cache again. +# https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#run RUN apt-get update && apt-get -y install python3 python3-pip libffi-dev \ && pip3 install --upgrade pip \ && pip3 install --upgrade setuptools From 2de652ad5c1a9855bf08ebf22fa006e56c286eeb Mon Sep 17 00:00:00 2001 From: ryan Date: Thu, 8 Dec 2016 11:51:23 +0100 Subject: [PATCH 143/155] add replicating test --- tests/integration/test_integration.py | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 70781096..78de03d3 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -44,3 +44,35 @@ def test_double_create(b, user_pk): last_voted_block = b.get_last_voted_block() assert len(last_voted_block.transactions) == 1 assert count_blocks(b.connection) == 2 + + +@pytest.mark.usefixtures('processes', 'inputs') +def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): + """See issue 633.""" + from bigchaindb.models import Transaction + input_valid = b.get_owned_ids(user_pk).pop() + input_valid = b.get_transaction(input_valid.txid) + tx_valid = Transaction.transfer(input_valid.to_inputs(), + [([user_pk], 1)], + input_valid.asset).sign([user_sk]) + + # write the valid tx and wait for voting/block to catch up + b.write_transaction(tx_valid) + time.sleep(2) + + # doesn't throw an exception + b.get_owned_ids(user_pk) + + # create another transaction with the same input + tx_double_spend = Transaction.transfer(input_valid.to_inputs(), + [([user_pk], 1)], + input_valid.asset) \ + .sign([user_sk]) + + # write the double spend tx + b.write_transaction(tx_double_spend) + time.sleep(2) + + # still doesn't throw an exception + b.get_owned_ids(user_pk) + assert b.is_valid_transaction(tx_double_spend) is False From d1b3a206ca5c54e52d6fb7f673a2ac267ca9709e Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Tue, 31 Jan 2017 16:52:23 +0100 Subject: [PATCH 144/155] get integration test working issue 633 --- tests/integration/test_integration.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 78de03d3..ceb18b04 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -46,15 +46,16 @@ def test_double_create(b, user_pk): assert count_blocks(b.connection) == 2 -@pytest.mark.usefixtures('processes', 'inputs') +@pytest.mark.usefixtures('inputs') def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): - """See issue 633.""" + """ Test for #633 https://github.com/bigchaindb/bigchaindb/issues/633 """ from bigchaindb.models import Transaction input_valid = b.get_owned_ids(user_pk).pop() input_valid = b.get_transaction(input_valid.txid) tx_valid = Transaction.transfer(input_valid.to_inputs(), [([user_pk], 1)], - input_valid.asset).sign([user_sk]) + input_valid.id, + {'1': 1}).sign([user_sk]) # write the valid tx and wait for voting/block to catch up b.write_transaction(tx_valid) @@ -66,8 +67,8 @@ def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): # create another transaction with the same input tx_double_spend = Transaction.transfer(input_valid.to_inputs(), [([user_pk], 1)], - input_valid.asset) \ - .sign([user_sk]) + input_valid.id, + {'2': 2}).sign([user_sk]) # write the double spend tx b.write_transaction(tx_double_spend) From 7f5318cba43a1cbffe63280fe04ee1b9840fe816 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 1 Feb 2017 14:33:53 +0100 Subject: [PATCH 145/155] check validate_transaction raises DoubleSpend in integration test --- tests/integration/test_integration.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index ceb18b04..6597a0e7 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -49,6 +49,7 @@ def test_double_create(b, user_pk): @pytest.mark.usefixtures('inputs') def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): """ Test for #633 https://github.com/bigchaindb/bigchaindb/issues/633 """ + from bigchaindb.common.exceptions import DoubleSpend from bigchaindb.models import Transaction input_valid = b.get_owned_ids(user_pk).pop() input_valid = b.get_transaction(input_valid.txid) @@ -76,4 +77,5 @@ def test_get_owned_ids_works_after_double_spend(b, user_pk, user_sk): # still doesn't throw an exception b.get_owned_ids(user_pk) - assert b.is_valid_transaction(tx_double_spend) is False + with pytest.raises(DoubleSpend): + b.validate_transaction(tx_double_spend) From c572464be656f829a3cb935d2bc71dd680f7d645 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Wed, 1 Feb 2017 14:47:19 +0100 Subject: [PATCH 146/155] fix asset_id index in mongodb --- bigchaindb/backend/mongodb/schema.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bigchaindb/backend/mongodb/schema.py b/bigchaindb/backend/mongodb/schema.py index 2c526e7c..f6aac93d 100644 --- a/bigchaindb/backend/mongodb/schema.py +++ b/bigchaindb/backend/mongodb/schema.py @@ -60,8 +60,7 @@ def create_bigchain_secondary_index(conn, dbname): # secondary index for asset uuid, this field is unique conn.conn[dbname]['bigchain']\ - .create_index('block.transactions.transaction.asset.id', - name='asset_id') + .create_index('block.transactions.asset.id', name='asset_id') def create_backlog_secondary_index(conn, dbname): From b7f70befe6cd6d8647aa2eaa3e9505348be8cf0e Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Wed, 1 Feb 2017 15:10:17 +0100 Subject: [PATCH 147/155] fix wrong logic in validate_block --- bigchaindb/models.py | 5 ----- tests/test_models.py | 13 ------------- 2 files changed, 18 deletions(-) diff --git a/bigchaindb/models.py b/bigchaindb/models.py index c6e81956..c3683a03 100644 --- a/bigchaindb/models.py +++ b/bigchaindb/models.py @@ -202,11 +202,6 @@ class Block(object): OperationError: If a non-federation node signed the Block. InvalidSignature: If a Block's signature is invalid. """ - - # First, make sure this node hasn't already voted on this block - if bigchain.has_previous_vote(self.id, self.voters): - return self - # Check if the block was created by a federation node possible_voters = (bigchain.nodes_except_me + [bigchain.me]) if self.node_pubkey not in possible_voters: diff --git a/tests/test_models.py b/tests/test_models.py index 7ab97e9e..58aa64fd 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -163,16 +163,3 @@ class TestBlockModel(object): public_key = PublicKey(b.me) assert public_key.verify(expected_block_serialized, block.signature) - - def test_validate_already_voted_on_block(self, b, monkeypatch): - from unittest.mock import Mock - from bigchaindb.models import Transaction - - tx = Transaction.create([b.me], [([b.me], 1)]) - block = b.create_block([tx]) - - has_previous_vote = Mock() - has_previous_vote.return_value = True - monkeypatch.setattr(b, 'has_previous_vote', has_previous_vote) - assert block == block.validate(b) - assert has_previous_vote.called is True From d49b06933a0237ecbedde9c0cba033d4d7af12ca Mon Sep 17 00:00:00 2001 From: Brett Sun Date: Wed, 1 Feb 2017 16:24:34 +0100 Subject: [PATCH 148/155] Fix docstring of `recipient` argument to be a list of tuples (#1091) --- bigchaindb/common/transaction.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bigchaindb/common/transaction.py b/bigchaindb/common/transaction.py index 65b12eed..e4bd642f 100644 --- a/bigchaindb/common/transaction.py +++ b/bigchaindb/common/transaction.py @@ -482,8 +482,8 @@ class Transaction(object): Args: tx_signers (:obj:`list` of :obj:`str`): A list of keys that represent the signers of the CREATE Transaction. - recipients (:obj:`list` of :obj:`str`): A list of keys that - represent the recipients of the outputs of this + recipients (:obj:`list` of :obj:`tuple`): A list of + ([keys],amount) that represent the recipients of this Transaction. metadata (dict): The metadata to be stored along with the Transaction. @@ -549,7 +549,7 @@ class Transaction(object): inputs (:obj:`list` of :class:`~bigchaindb.common.transaction. Input`): Converted `Output`s, intended to be used as inputs in the transfer to generate. - recipients (:obj:`list` of :obj:`str`): A list of + recipients (:obj:`list` of :obj:`tuple`): A list of ([keys],amount) that represent the recipients of this Transaction. asset_id (str): The asset ID of the asset to be transferred in From 6fd8c7a20bdcf9295b0ec63ef14ed3cb67f49868 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Thu, 2 Feb 2017 09:45:13 +0100 Subject: [PATCH 149/155] Feat/105/secondary indexes inputs outputs (#1125) * Added inputs/outputs secondary indexes for rethinkdb Added tests. * Added inputs/outputs secondary indexes for mongodb Fixed tests. * fixed comment --- bigchaindb/backend/mongodb/query.py | 11 ++++++----- bigchaindb/backend/mongodb/schema.py | 12 ++++++++++++ bigchaindb/backend/rethinkdb/query.py | 15 ++++++++------- bigchaindb/backend/rethinkdb/schema.py | 25 +++++++++++++++++++++++++ tests/backend/mongodb/test_schema.py | 8 ++++---- tests/backend/rethinkdb/test_schema.py | 4 ++++ 6 files changed, 59 insertions(+), 16 deletions(-) diff --git a/bigchaindb/backend/mongodb/query.py b/bigchaindb/backend/mongodb/query.py index d7ee6afc..e3b71315 100644 --- a/bigchaindb/backend/mongodb/query.py +++ b/bigchaindb/backend/mongodb/query.py @@ -143,6 +143,10 @@ def get_asset_by_id(conn, asset_id): @register_query(MongoDBConnection) def get_spent(conn, transaction_id, output): cursor = conn.db['bigchain'].aggregate([ + {'$match': { + 'block.transactions.inputs.fulfills.txid': transaction_id, + 'block.transactions.inputs.fulfills.output': output + }}, {'$unwind': '$block.transactions'}, {'$match': { 'block.transactions.inputs.fulfills.txid': transaction_id, @@ -157,12 +161,9 @@ def get_spent(conn, transaction_id, output): @register_query(MongoDBConnection) def get_owned_ids(conn, owner): cursor = conn.db['bigchain'].aggregate([ + {'$match': {'block.transactions.outputs.public_keys': owner}}, {'$unwind': '$block.transactions'}, - {'$match': { - 'block.transactions.outputs.public_keys': { - '$elemMatch': {'$eq': owner} - } - }} + {'$match': {'block.transactions.outputs.public_keys': owner}} ]) # we need to access some nested fields before returning so lets use a # generator to avoid having to read all records on the cursor at this point diff --git a/bigchaindb/backend/mongodb/schema.py b/bigchaindb/backend/mongodb/schema.py index 2c526e7c..95c2d02a 100644 --- a/bigchaindb/backend/mongodb/schema.py +++ b/bigchaindb/backend/mongodb/schema.py @@ -63,6 +63,18 @@ def create_bigchain_secondary_index(conn, dbname): .create_index('block.transactions.transaction.asset.id', name='asset_id') + # secondary index on the public keys of outputs + conn.conn[dbname]['bigchain']\ + .create_index('block.transactions.outputs.public_keys', + name='outputs') + + # secondary index on inputs/transaction links (txid, output) + conn.conn[dbname]['bigchain']\ + .create_index([ + ('block.transactions.inputs.fulfills.txid', ASCENDING), + ('block.transactions.inputs.fulfills.output', ASCENDING), + ], name='inputs') + def create_backlog_secondary_index(conn, dbname): logger.info('Create `backlog` secondary index.') diff --git a/bigchaindb/backend/rethinkdb/query.py b/bigchaindb/backend/rethinkdb/query.py index aa7c3be6..99346984 100644 --- a/bigchaindb/backend/rethinkdb/query.py +++ b/bigchaindb/backend/rethinkdb/query.py @@ -111,21 +111,22 @@ def _get_asset_create_tx_query(asset_id): @register_query(RethinkDBConnection) def get_spent(connection, transaction_id, output): - # TODO: use index! return connection.run( r.table('bigchain', read_mode=READ_MODE) - .concat_map(lambda doc: doc['block']['transactions']) - .filter(lambda transaction: transaction['inputs'].contains( - lambda input: input['fulfills'] == {'txid': transaction_id, 'output': output}))) + .get_all([transaction_id, output], index='inputs') + .concat_map(lambda doc: doc['block']['transactions']) + .filter(lambda transaction: transaction['inputs'].contains( + lambda input_: input_['fulfills'] == {'txid': transaction_id, 'output': output}))) @register_query(RethinkDBConnection) def get_owned_ids(connection, owner): - # TODO: use index! return connection.run( r.table('bigchain', read_mode=READ_MODE) - .concat_map(lambda doc: doc['block']['transactions']) - .filter(lambda tx: tx['outputs'].contains( + .get_all(owner, index='outputs') + .distinct() + .concat_map(lambda doc: doc['block']['transactions']) + .filter(lambda tx: tx['outputs'].contains( lambda c: c['public_keys'].contains(owner)))) diff --git a/bigchaindb/backend/rethinkdb/schema.py b/bigchaindb/backend/rethinkdb/schema.py index 4a76a06b..997ec5fc 100644 --- a/bigchaindb/backend/rethinkdb/schema.py +++ b/bigchaindb/backend/rethinkdb/schema.py @@ -66,6 +66,31 @@ def create_bigchain_secondary_index(connection, dbname): .table('bigchain') .index_create('asset_id', r.row['block']['transactions']['asset']['id'], multi=True)) + # secondary index on the public keys of outputs + # the last reduce operation is to return a flatten list of public_keys + # without it we would need to match exactly the public_keys list. + # For instance querying for `pk1` would not match documents with + # `public_keys: [pk1, pk2, pk3]` + connection.run( + r.db(dbname) + .table('bigchain') + .index_create('outputs', + r.row['block']['transactions'] + .concat_map(lambda tx: tx['outputs']['public_keys']) + .reduce(lambda l, r: l + r), multi=True)) + + # secondary index on inputs/transaction links (txid, output) + connection.run( + r.db(dbname) + .table('bigchain') + .index_create('inputs', + r.row['block']['transactions'] + .concat_map(lambda tx: tx['inputs']['fulfills']) + .with_fields('txid', 'output') + .map(lambda fulfills: [fulfills['txid'], + fulfills['output']]), + multi=True)) + # wait for rethinkdb to finish creating secondary indexes connection.run( r.db(dbname) diff --git a/tests/backend/mongodb/test_schema.py b/tests/backend/mongodb/test_schema.py index 34b6edf9..71eac7ff 100644 --- a/tests/backend/mongodb/test_schema.py +++ b/tests/backend/mongodb/test_schema.py @@ -21,8 +21,8 @@ def test_init_creates_db_tables_and_indexes(): assert sorted(collection_names) == ['backlog', 'bigchain', 'votes'] indexes = conn.conn[dbname]['bigchain'].index_information().keys() - assert sorted(indexes) == ['_id_', 'asset_id', 'block_timestamp', - 'transaction_id'] + assert sorted(indexes) == ['_id_', 'asset_id', 'block_timestamp', 'inputs', + 'outputs', 'transaction_id'] indexes = conn.conn[dbname]['backlog'].index_information().keys() assert sorted(indexes) == ['_id_', 'assignee__transaction_timestamp', @@ -81,8 +81,8 @@ def test_create_secondary_indexes(): # Bigchain table indexes = conn.conn[dbname]['bigchain'].index_information().keys() - assert sorted(indexes) == ['_id_', 'asset_id', 'block_timestamp', - 'transaction_id'] + assert sorted(indexes) == ['_id_', 'asset_id', 'block_timestamp', 'inputs', + 'outputs', 'transaction_id'] # Backlog table indexes = conn.conn[dbname]['backlog'].index_information().keys() diff --git a/tests/backend/rethinkdb/test_schema.py b/tests/backend/rethinkdb/test_schema.py index 1447e80f..e19dfdc2 100644 --- a/tests/backend/rethinkdb/test_schema.py +++ b/tests/backend/rethinkdb/test_schema.py @@ -85,6 +85,10 @@ def test_create_secondary_indexes(): 'transaction_id')) is True assert conn.run(r.db(dbname).table('bigchain').index_list().contains( 'asset_id')) is True + assert conn.run(r.db(dbname).table('bigchain').index_list().contains( + 'inputs')) is True + assert conn.run(r.db(dbname).table('bigchain').index_list().contains( + 'outputs')) is True # Backlog table assert conn.run(r.db(dbname).table('backlog').index_list().contains( From 516c7539108c2d69dd40a826d2ac4d5801369c54 Mon Sep 17 00:00:00 2001 From: Krish Date: Thu, 2 Feb 2017 16:06:50 +0100 Subject: [PATCH 150/155] Add param 'rethinkdb' in docs for configure cmd. --- docs/server/source/appendices/run-with-docker.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/server/source/appendices/run-with-docker.md b/docs/server/source/appendices/run-with-docker.md index 455331ed..d6e33a70 100644 --- a/docs/server/source/appendices/run-with-docker.md +++ b/docs/server/source/appendices/run-with-docker.md @@ -21,7 +21,7 @@ be stored in a file on your host machine at `~/bigchaindb_docker/.bigchaindb`: ```text docker run --rm -v "$HOME/bigchaindb_docker:/data" -ti \ - bigchaindb/bigchaindb -y configure + bigchaindb/bigchaindb -y configure rethinkdb Generating keypair Configuration written to /data/.bigchaindb Ready to go! From e98a16180515390151e4c02227f1bb47d8bf1b04 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Fri, 3 Feb 2017 09:57:10 +0100 Subject: [PATCH 151/155] set -euo pipefail in make_confiles.sh --- deploy-cluster-aws/make_confiles.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/deploy-cluster-aws/make_confiles.sh b/deploy-cluster-aws/make_confiles.sh index 72735cb3..35f1f0e6 100755 --- a/deploy-cluster-aws/make_confiles.sh +++ b/deploy-cluster-aws/make_confiles.sh @@ -1,8 +1,6 @@ #! /bin/bash -# The set -e option instructs bash to immediately exit -# if any command has a non-zero exit status -set -e +set -euo pipefail function printErr() { From 5750027cd4e25ccfc439269443a7ab2a9f90f2f1 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Fri, 3 Feb 2017 10:01:36 +0100 Subject: [PATCH 152/155] Include db backend (rethinkdb) when call bigchaindb configure --- deploy-cluster-aws/fabfile.py | 2 +- deploy-cluster-aws/make_confiles.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/deploy-cluster-aws/fabfile.py b/deploy-cluster-aws/fabfile.py index 77d0e558..9ef24edd 100644 --- a/deploy-cluster-aws/fabfile.py +++ b/deploy-cluster-aws/fabfile.py @@ -221,7 +221,7 @@ def install_bigchaindb_from_git_archive(): @task @parallel def configure_bigchaindb(): - run('bigchaindb -y configure', pty=False) + run('bigchaindb -y configure rethinkdb', pty=False) # Send the specified configuration file to diff --git a/deploy-cluster-aws/make_confiles.sh b/deploy-cluster-aws/make_confiles.sh index 35f1f0e6..052ecaf0 100755 --- a/deploy-cluster-aws/make_confiles.sh +++ b/deploy-cluster-aws/make_confiles.sh @@ -34,5 +34,5 @@ mkdir $CONFDIR for (( i=0; i<$NUMFILES; i++ )); do CONPATH=$CONFDIR"/bcdb_conf"$i echo "Writing "$CONPATH - bigchaindb -y -c $CONPATH configure + bigchaindb -y -c $CONPATH configure rethinkdb done From b9db0de6574fb34a5475abe6883514fa7aef34f8 Mon Sep 17 00:00:00 2001 From: Troy McConaghy Date: Fri, 3 Feb 2017 10:12:42 +0100 Subject: [PATCH 153/155] Minor changes in .gitattributes --- .gitattributes | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index c82148e4..cd945c78 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,7 @@ benchmarking-tests export-ignore deploy-cluster-aws export-ignore -docs export-ignore export-ignore +docs export-ignore +ntools export-ignore speed-tests export-ignore tests export-ignore .gitattributes export-ignore From 2fe9c47b630e44f38748366d09bd4e6185ce0bd7 Mon Sep 17 00:00:00 2001 From: Rodolphe Marques Date: Fri, 3 Feb 2017 10:28:28 +0100 Subject: [PATCH 154/155] Feat/990/cleanup monitoring code (#1138) * remove statsd dependencie * remove monitoring related code * removed statsd configuration * fixed tests * Removed monitoring docker compose file. Remove statsd settings from test fixture. Removed statsd related code from benchmarking tests * removed monitoring related documentation * remove unused import --- benchmarking-tests/benchmark_utils.py | 18 ---- benchmarking-tests/fabfile.py | 8 -- benchmarking-tests/test1/README.md | 3 +- bigchaindb/README.md | 4 - bigchaindb/__init__.py | 5 -- bigchaindb/commands/bigchain.py | 6 -- bigchaindb/monitor.py | 32 ------- bigchaindb/web/server.py | 3 - bigchaindb/web/views/transactions.py | 6 +- deploy-cluster-aws/fabfile-monitor.py | 89 ------------------- docker-compose-monitor.yml | 28 ------ .../source/appendices/firewall-notes.md | 10 --- .../clusters-feds/aws-testing-cluster.md | 44 --------- docs/server/source/clusters-feds/index.rst | 3 +- .../server/source/clusters-feds/monitoring.md | 40 --------- .../source/server-reference/configuration.md | 20 ----- ntools/one-m/aws/security_group.tf | 8 -- setup.py | 1 - tests/commands/conftest.py | 1 - tests/test_config_utils.py | 5 -- tests/test_monitor.py | 14 --- 21 files changed, 3 insertions(+), 345 deletions(-) delete mode 100644 bigchaindb/monitor.py delete mode 100644 deploy-cluster-aws/fabfile-monitor.py delete mode 100644 docker-compose-monitor.yml delete mode 100644 docs/server/source/clusters-feds/monitoring.md delete mode 100644 tests/test_monitor.py diff --git a/benchmarking-tests/benchmark_utils.py b/benchmarking-tests/benchmark_utils.py index 807146e8..510eae41 100644 --- a/benchmarking-tests/benchmark_utils.py +++ b/benchmarking-tests/benchmark_utils.py @@ -1,13 +1,11 @@ import multiprocessing as mp import uuid -import json import argparse import csv import time import logging import rethinkdb as r -from os.path import expanduser from bigchaindb.common.transaction import Transaction from bigchaindb import Bigchain @@ -48,15 +46,6 @@ def run_add_backlog(args): workers.start() -def run_set_statsd_host(args): - with open(expanduser('~') + '/.bigchaindb', 'r') as f: - conf = json.load(f) - - conf['statsd']['host'] = args.statsd_host - with open(expanduser('~') + '/.bigchaindb', 'w') as f: - json.dump(conf, f) - - def run_gather_metrics(args): # setup a rethinkdb connection conn = r.connect(args.bigchaindb_host, 28015, 'bigchain') @@ -126,12 +115,6 @@ def main(): default='minimal', help='Payload size') - # set statsd host - statsd_parser = subparsers.add_parser('set-statsd-host', - help='Set statsd host') - statsd_parser.add_argument('statsd_host', metavar='statsd_host', default='localhost', - help='Hostname of the statsd server') - # metrics metrics_parser = subparsers.add_parser('gather-metrics', help='Gather metrics to a csv file') @@ -149,4 +132,3 @@ def main(): if __name__ == '__main__': main() - diff --git a/benchmarking-tests/fabfile.py b/benchmarking-tests/fabfile.py index 44a31888..0dd4e964 100644 --- a/benchmarking-tests/fabfile.py +++ b/benchmarking-tests/fabfile.py @@ -28,14 +28,6 @@ def put_benchmark_utils(): put('benchmark_utils.py') -@task -@parallel -def set_statsd_host(statsd_host='localhost'): - run('python3 benchmark_utils.py set-statsd-host {}'.format(statsd_host)) - print('update configuration') - run('bigchaindb show-config') - - @task @parallel def prepare_backlog(num_transactions=10000): diff --git a/benchmarking-tests/test1/README.md b/benchmarking-tests/test1/README.md index aadccfdc..38a4569b 100644 --- a/benchmarking-tests/test1/README.md +++ b/benchmarking-tests/test1/README.md @@ -15,7 +15,6 @@ Then: ```bash fab put_benchmark_utils -fab set_statsd_host: fab prepare_backlog: # wait for process to finish fab start_bigchaindb -``` \ No newline at end of file +``` diff --git a/bigchaindb/README.md b/bigchaindb/README.md index 3bad7331..dbb59a1e 100644 --- a/bigchaindb/README.md +++ b/bigchaindb/README.md @@ -26,10 +26,6 @@ Entry point for the BigchainDB process, after initialization. All subprocesses Methods for managing the configuration, including loading configuration files, automatically generating the configuration, and keeping the configuration consistent across BigchainDB instances. -### [`monitor.py`](./monitor.py) - -Code for monitoring speed of various processes in BigchainDB via `statsd` and Grafana. [See documentation.](https://docs.bigchaindb.com/projects/server/en/latest/clusters-feds/monitoring.html) - ## Folders ### [`pipelines`](./pipelines) diff --git a/bigchaindb/__init__.py b/bigchaindb/__init__.py index 072c7b6b..10e9e6ce 100644 --- a/bigchaindb/__init__.py +++ b/bigchaindb/__init__.py @@ -41,11 +41,6 @@ config = { 'private': None, }, 'keyring': [], - 'statsd': { - 'host': 'localhost', - 'port': 8125, - 'rate': 0.01, - }, 'backlog_reassign_delay': 120 } diff --git a/bigchaindb/commands/bigchain.py b/bigchaindb/commands/bigchain.py index 4e8de28b..70836f3c 100644 --- a/bigchaindb/commands/bigchain.py +++ b/bigchaindb/commands/bigchain.py @@ -105,12 +105,6 @@ def run_configure(args, skip_if_exists=False): input_on_stderr('Database {}? (default `{}`): '.format(key, val)) \ or val - for key in ('host', 'port', 'rate'): - val = conf['statsd'][key] - conf['statsd'][key] = \ - input_on_stderr('Statsd {}? (default `{}`): '.format(key, val)) \ - or val - val = conf['backlog_reassign_delay'] conf['backlog_reassign_delay'] = \ input_on_stderr(('Stale transaction reassignment delay (in ' diff --git a/bigchaindb/monitor.py b/bigchaindb/monitor.py deleted file mode 100644 index 9d2bc527..00000000 --- a/bigchaindb/monitor.py +++ /dev/null @@ -1,32 +0,0 @@ -from platform import node - -import statsd - -import bigchaindb -from bigchaindb import config_utils - - -class Monitor(statsd.StatsClient): - """Set up statsd monitoring.""" - - def __init__(self, *args, **kwargs): - """Overrides statsd client, fixing prefix to messages and loading configuration - - Args: - *args: arguments (identical to Statsclient) - **kwargs: keyword arguments (identical to Statsclient) - """ - - config_utils.autoconfigure() - - if not kwargs: - kwargs = {} - - # set prefix, parameters from configuration file - if 'prefix' not in kwargs: - kwargs['prefix'] = '{hostname}.'.format(hostname=node()) - if 'host' not in kwargs: - kwargs['host'] = bigchaindb.config['statsd']['host'] - if 'port' not in kwargs: - kwargs['port'] = bigchaindb.config['statsd']['port'] - super().__init__(*args, **kwargs) diff --git a/bigchaindb/web/server.py b/bigchaindb/web/server.py index d8ce2e0b..bcd44d11 100644 --- a/bigchaindb/web/server.py +++ b/bigchaindb/web/server.py @@ -13,8 +13,6 @@ from bigchaindb import utils from bigchaindb import Bigchain from bigchaindb.web.routes import add_routes -from bigchaindb.monitor import Monitor - # TODO: Figure out if we do we need all this boilerplate. class StandaloneApplication(gunicorn.app.base.BaseApplication): @@ -65,7 +63,6 @@ def create_app(*, debug=False, threads=4): app.debug = debug app.config['bigchain_pool'] = utils.pool(Bigchain, size=threads) - app.config['monitor'] = Monitor() add_routes(app) diff --git a/bigchaindb/web/views/transactions.py b/bigchaindb/web/views/transactions.py index a4a983ef..7acaa279 100644 --- a/bigchaindb/web/views/transactions.py +++ b/bigchaindb/web/views/transactions.py @@ -23,7 +23,6 @@ from bigchaindb.common.exceptions import ( ValidationError, ) -import bigchaindb from bigchaindb.models import Transaction from bigchaindb.web.views.base import make_error from bigchaindb.web.views import parameters @@ -72,7 +71,6 @@ class TransactionListApi(Resource): A ``dict`` containing the data about the transaction. """ pool = current_app.config['bigchain_pool'] - monitor = current_app.config['monitor'] # `force` will try to format the body of the POST request even if the # `content-type` header is not set to `application/json` @@ -109,8 +107,6 @@ class TransactionListApi(Resource): 'Invalid transaction ({}): {}'.format(type(e).__name__, e) ) else: - rate = bigchaindb.config['statsd']['rate'] - with monitor.timer('write_transaction', rate=rate): - bigchain.write_transaction(tx_obj) + bigchain.write_transaction(tx_obj) return tx, 202 diff --git a/deploy-cluster-aws/fabfile-monitor.py b/deploy-cluster-aws/fabfile-monitor.py deleted file mode 100644 index 8d2d282c..00000000 --- a/deploy-cluster-aws/fabfile-monitor.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -"""A Fabric fabfile with functionality to install Docker, -install Docker Compose, and run a BigchainDB monitoring server -(using the docker-compose-monitor.yml file) -""" - -from __future__ import with_statement, unicode_literals - -from fabric.api import sudo, env -from fabric.api import task -from fabric.operations import put, run - -from ssh_key import ssh_key_path - -# Ignore known_hosts -# http://docs.fabfile.org/en/1.10/usage/env.html#disable-known-hosts -env.disable_known_hosts = True - -env.user = 'ubuntu' -env.key_filename = ssh_key_path - - -@task -def install_docker_engine(): - """Install Docker on an EC2 Ubuntu 14.04 instance - - Example: - fab --fabfile=fabfile-monitor.py \ - --hosts=ec2-52-58-106-17.eu-central-1.compute.amazonaws.com \ - install_docker_engine - """ - - # install prerequisites - sudo('apt-get update') - sudo('apt-get -y install apt-transport-https ca-certificates linux-image-extra-$(uname -r) apparmor') - - # install docker repositories - sudo('apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 \ - --recv-keys 58118E89F3A912897C070ADBF76221572C52609D') - sudo("echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' | \ - sudo tee /etc/apt/sources.list.d/docker.list") - - # install docker engine - sudo('apt-get update') - sudo('apt-get -y install docker-engine') - - # add ubuntu user to the docker group - sudo('usermod -aG docker ubuntu') - - -@task -def install_docker_compose(): - """Install Docker Compose on an EC2 Ubuntu 14.04 instance - - Example: - fab --fabfile=fabfile-monitor.py \ - --hosts=ec2-52-58-106-17.eu-central-1.compute.amazonaws.com \ - install_docker_compose - """ - sudo('curl -L https://github.com/docker/compose/releases/download/1.7.0/docker-compose-`uname \ - -s`-`uname -m` > /usr/local/bin/docker-compose') - sudo('chmod +x /usr/local/bin/docker-compose') - - -@task -def install_docker(): - """Install Docker and Docker Compose on an EC2 Ubuntu 14.04 instance - - Example: - fab --fabfile=fabfile-monitor.py \ - --hosts=ec2-52-58-106-17.eu-central-1.compute.amazonaws.com \ - install_docker - """ - install_docker_engine() - install_docker_compose() - - -@task -def run_monitor(): - """Run BigchainDB monitor on an EC2 Ubuntu 14.04 instance - - Example: - fab --fabfile=fabfile-monitor.py \ - --hosts=ec2-52-58-106-17.eu-central-1.compute.amazonaws.com \ - run_monitor - """ - # copy docker-compose-monitor to the ec2 instance - put('../docker-compose-monitor.yml') - run('INFLUXDB_DATA=/influxdb-data docker-compose -f docker-compose-monitor.yml up -d') diff --git a/docker-compose-monitor.yml b/docker-compose-monitor.yml deleted file mode 100644 index e695387c..00000000 --- a/docker-compose-monitor.yml +++ /dev/null @@ -1,28 +0,0 @@ -version: '2' -services: - influxdb: - image: tutum/influxdb - ports: - - "8083:8083" - - "8086:8086" - - "8090" - - "8099" - environment: - PRE_CREATE_DB: "telegraf" - volumes: - - $INFLUXDB_DATA:/data - - grafana: - image: bigchaindb/grafana-bigchaindb-docker - tty: true - ports: - - "3000:3000" - environment: - INFLUXDB_HOST: "influxdb" - - statsd: - image: bigchaindb/docker-telegraf-statsd - ports: - - "8125:8125/udp" - environment: - INFLUXDB_HOST: "influxdb" \ No newline at end of file diff --git a/docs/server/source/appendices/firewall-notes.md b/docs/server/source/appendices/firewall-notes.md index bad09b05..19d7c234 100644 --- a/docs/server/source/appendices/firewall-notes.md +++ b/docs/server/source/appendices/firewall-notes.md @@ -44,11 +44,6 @@ Port 161 is the default SNMP port (usually UDP, sometimes TCP). SNMP is used, fo Port 443 is the default HTTPS port (TCP). You may need to open it up for outbound requests (and inbound responses) temporarily because some RethinkDB installation instructions use wget over HTTPS to get the RethinkDB GPG key. Package managers might also get some packages using HTTPS. -## Port 8125 - -If you set up a [cluster-monitoring server](../clusters-feds/monitoring.html), then StatsD will send UDP packets to Telegraf (on the monitoring server) via port 8125. - - ## Port 8080 Port 8080 is the default port used by RethinkDB for its adminstrative web (HTTP) interface (TCP). While you _can_, you shouldn't allow traffic arbitrary external sources. You can still use the RethinkDB web interface by binding it to localhost and then accessing it via a SOCKS proxy or reverse proxy; see "Binding the web interface port" on [the RethinkDB page about securing your cluster](https://rethinkdb.com/docs/security/). @@ -76,8 +71,3 @@ Port 29015 is the default port for RethinkDB intracluster connections (TCP). It ## Other Ports On Linux, you can use commands such as `netstat -tunlp` or `lsof -i` to get a sense of currently open/listening ports and connections, and the associated processes. - - -## Cluster-Monitoring Server - -If you set up a [cluster-monitoring server](../clusters-feds/monitoring.html) (running Telegraf, InfluxDB & Grafana), Telegraf will listen on port 8125 for UDP packets from StatsD, and the Grafana web dashboard will use port 3000. (Those are the default ports.) diff --git a/docs/server/source/clusters-feds/aws-testing-cluster.md b/docs/server/source/clusters-feds/aws-testing-cluster.md index fbc623f3..ac1deff1 100644 --- a/docs/server/source/clusters-feds/aws-testing-cluster.md +++ b/docs/server/source/clusters-feds/aws-testing-cluster.md @@ -64,50 +64,6 @@ For a super lax, somewhat risky, anything-can-enter security group, add these ru If you want to set up a more secure security group, see the [Notes for Firewall Setup](../appendices/firewall-notes.html). -## Deploy a BigchainDB Monitor - -This step is optional. - -One way to monitor a BigchainDB cluster is to use the monitoring setup described in the [Monitoring](monitoring.html) section of this documentation. If you want to do that, then you may want to deploy the monitoring server first, so you can tell your BigchainDB nodes where to send their monitoring data. - -You can deploy a monitoring server on AWS. To do that, go to the AWS EC2 Console and launch an instance: - -1. Choose an AMI: select Ubuntu Server 16.04 LTS. -2. Choose an Instance Type: a t2.micro will suffice. -3. Configure Instance Details: you can accept the defaults, but feel free to change them. -4. Add Storage: A "Root" volume type should already be included. You _could_ store monitoring data there (e.g. in a folder named `/influxdb-data`) but we will attach another volume and store the monitoring data there instead. Select "Add New Volume" and an EBS volume type. -5. Tag Instance: give your instance a memorable name. -6. Configure Security Group: choose your bigchaindb security group. -7. Review and launch your instance. - -When it asks, choose an existing key pair: the one you created earlier (named `bigchaindb`). - -Give your instance some time to launch and become able to accept SSH connections. You can see its current status in the AWS EC2 Console (in the "Instances" section). SSH into your instance using something like: -```text -cd deploy-cluster-aws -ssh -i pem/bigchaindb.pem ubuntu@ec2-52-58-157-229.eu-central-1.compute.amazonaws.com -``` - -where `ec2-52-58-157-229.eu-central-1.compute.amazonaws.com` should be replaced by your new instance's EC2 hostname. (To get that, go to the AWS EC2 Console, select Instances, click on your newly-launched instance, and copy its "Public DNS" name.) - -Next, create a file system on the attached volume, make a directory named `/influxdb-data`, and set the attached volume's mount point to be `/influxdb-data`. For detailed instructions on how to do that, see the AWS documentation for [Making an Amazon EBS Volume Available for Use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html). - -Then install Docker and Docker Compose: -```text -# in a Python 2.5-2.7 virtual environment where fabric, boto3, etc. are installed -fab --fabfile=fabfile-monitor.py --hosts= install_docker -``` - -After Docker is installed, we can run the monitor with: -```text -fab --fabfile=fabfile-monitor.py --hosts= run_monitor -``` - -For more information about monitoring (e.g. how to view the Grafana dashboard in your web browser), see the [Monitoring](monitoring.html) section of this documentation. - -To configure a BigchainDB node to send monitoring data to the monitoring server, change the statsd host in the configuration of the BigchainDB node. The section on [Configuring a BigchainDB Node](../server-reference/configuration.html) explains how you can do that. (For example, you can change the statsd host in `$HOME/.bigchaindb`.) - - ## Deploy a BigchainDB Cluster ### Step 1 diff --git a/docs/server/source/clusters-feds/index.rst b/docs/server/source/clusters-feds/index.rst index e55867fa..d13221ce 100644 --- a/docs/server/source/clusters-feds/index.rst +++ b/docs/server/source/clusters-feds/index.rst @@ -7,5 +7,4 @@ Clusters & Federations set-up-a-federation backup aws-testing-cluster - monitoring - \ No newline at end of file + diff --git a/docs/server/source/clusters-feds/monitoring.md b/docs/server/source/clusters-feds/monitoring.md deleted file mode 100644 index 4a5de698..00000000 --- a/docs/server/source/clusters-feds/monitoring.md +++ /dev/null @@ -1,40 +0,0 @@ -# Cluster Monitoring - -BigchainDB uses [StatsD](https://github.com/etsy/statsd) for cluster monitoring. We require some additional infrastructure to take full advantage of its functionality: - -* an agent to listen for metrics: [Telegraf](https://github.com/influxdata/telegraf), -* a time-series database: [InfluxDB](https://www.influxdata.com/time-series-platform/influxdb/), and -* a frontend to display analytics: [Grafana](http://grafana.org/). - -We put each of those inside its own Docker container. The whole system is illustrated below. - -![BigchainDB monitoring system diagram: Application metrics flow from servers running BigchainDB to Telegraf to InfluxDB to Grafana](../_static/monitoring_system_diagram.png) - -For ease of use, we've created a Docker [_Compose file_](https://docs.docker.com/compose/compose-file/) (named `docker-compose-monitor.yml`) to define the monitoring system setup. To use it, just go to to the top `bigchaindb` directory and run: -```text -$ docker-compose -f docker-compose-monitor.yml build -$ docker-compose -f docker-compose-monitor.yml up -``` - -It is also possible to mount a host directory as a data volume for InfluxDB -by setting the `INFLUXDB_DATA` environment variable: -```text -$ INFLUXDB_DATA=/data docker-compose -f docker-compose-monitor.yml up -``` - -You can view the Grafana dashboard in your web browser at: - -[http://localhost:3000/dashboard/script/bigchaindb_dashboard.js](http://localhost:3000/dashboard/script/bigchaindb_dashboard.js) - -(You may want to replace `localhost` with another hostname in that URL, e.g. the hostname of a remote monitoring server.) - -The login and password are `admin` by default. If BigchainDB is running and processing transactions, you should see analytics—if not, [start BigchainDB](../dev-and-test/setup-run-node.html#run-bigchaindb) and load some test transactions: -```text -$ bigchaindb load -``` - -then refresh the page after a few seconds. - -If you're not interested in monitoring, don't worry: BigchainDB will function just fine without any monitoring setup. - -Feel free to modify the [custom Grafana dashboard](https://github.com/rhsimplex/grafana-bigchaindb-docker/blob/master/bigchaindb_dashboard.js) to your liking! diff --git a/docs/server/source/server-reference/configuration.md b/docs/server/source/server-reference/configuration.md index 783591ca..b7842d6a 100644 --- a/docs/server/source/server-reference/configuration.md +++ b/docs/server/source/server-reference/configuration.md @@ -19,9 +19,6 @@ For convenience, here's a list of all the relevant environment variables (docume `BIGCHAINDB_SERVER_BIND`
`BIGCHAINDB_SERVER_WORKERS`
`BIGCHAINDB_SERVER_THREADS`
-`BIGCHAINDB_STATSD_HOST`
-`BIGCHAINDB_STATSD_PORT`
-`BIGCHAINDB_STATSD_RATE`
`BIGCHAINDB_CONFIG_PATH`
`BIGCHAINDB_BACKLOG_REASSIGN_DELAY`
@@ -151,23 +148,6 @@ export BIGCHAINDB_SERVER_THREADS=5 } ``` - -## statsd.host, statsd.port & statsd.rate - -These settings are used to configure where, and how often, [StatsD](https://github.com/etsy/statsd) should send data for [cluster monitoring](../clusters-feds/monitoring.html) purposes. `statsd.host` is the hostname of the monitoring server, where StatsD should send its data. `stats.port` is the port. `statsd.rate` is the fraction of transaction operations that should be sampled. It's a float between 0.0 and 1.0. - -**Example using environment variables** -```text -export BIGCHAINDB_STATSD_HOST="http://monitor.monitors-r-us.io" -export BIGCHAINDB_STATSD_PORT=8125 -export BIGCHAINDB_STATSD_RATE=0.01 -``` - -**Example config file snippet: the default** -```js -"statsd": {"host": "localhost", "port": 8125, "rate": 0.01} -``` - ## backlog_reassign_delay Specifies how long, in seconds, transactions can remain in the backlog before being reassigned. Long-waiting transactions must be reassigned because the assigned node may no longer be responsive. The default duration is 120 seconds. diff --git a/ntools/one-m/aws/security_group.tf b/ntools/one-m/aws/security_group.tf index f8fa3e1d..64037ff6 100644 --- a/ntools/one-m/aws/security_group.tf +++ b/ntools/one-m/aws/security_group.tf @@ -62,14 +62,6 @@ resource "aws_security_group" "node_sg1" { cidr_blocks = ["0.0.0.0/0"] } - # StatsD - ingress { - from_port = 8125 - to_port = 8125 - protocol = "udp" - cidr_blocks = ["0.0.0.0/0"] - } - # Future: Don't allow port 8080 for the RethinkDB web interface. # Use a SOCKS proxy or reverse proxy instead. diff --git a/setup.py b/setup.py index f7085218..d1a22279 100644 --- a/setup.py +++ b/setup.py @@ -65,7 +65,6 @@ install_requires = [ 'pymongo~=3.4', 'pysha3==1.0.0', 'cryptoconditions>=0.5.0', - 'statsd>=3.2.1', 'python-rapidjson>=0.0.8', 'logstats>=0.2.1', 'flask>=0.10.1', diff --git a/tests/commands/conftest.py b/tests/commands/conftest.py index d3ecdadc..1cffbc2f 100644 --- a/tests/commands/conftest.py +++ b/tests/commands/conftest.py @@ -35,7 +35,6 @@ def mock_bigchaindb_backup_config(monkeypatch): config = { 'keypair': {}, 'database': {'host': 'host', 'port': 12345, 'name': 'adbname'}, - 'statsd': {'host': 'host', 'port': 12345, 'rate': 0.1}, 'backlog_reassign_delay': 5 } monkeypatch.setattr('bigchaindb._config', config) diff --git a/tests/test_config_utils.py b/tests/test_config_utils.py index af78585e..d69b789a 100644 --- a/tests/test_config_utils.py +++ b/tests/test_config_utils.py @@ -167,11 +167,6 @@ def test_autoconfigure_read_both_from_file_and_env(monkeypatch, request): 'private': None, }, 'keyring': KEYRING.split(':'), - 'statsd': { - 'host': 'localhost', - 'port': 8125, - 'rate': 0.01, - }, 'backlog_reassign_delay': 5 } diff --git a/tests/test_monitor.py b/tests/test_monitor.py deleted file mode 100644 index a138b9b1..00000000 --- a/tests/test_monitor.py +++ /dev/null @@ -1,14 +0,0 @@ -from platform import node - - -def test_monitor_class_init_defaults(): - import bigchaindb - from bigchaindb.monitor import Monitor - monitor = Monitor() - assert monitor - assert len(monitor._addr) == 2 - # TODO get value from config - # assert monitor._addr[0] == bigchaindb.config['statsd']['host'] - assert monitor._addr[0] == '127.0.0.1' - assert monitor._addr[1] == bigchaindb.config['statsd']['port'] - assert monitor._prefix == node() + '.' From d3e394e7edf1facb05260b97833c2221b08f8491 Mon Sep 17 00:00:00 2001 From: Scott Sadler Date: Fri, 3 Feb 2017 10:44:06 +0100 Subject: [PATCH 155/155] refactor get_txids_filtered query to be more efficient and add test to check that appropriate indexes are used --- bigchaindb/backend/mongodb/query.py | 54 +++++++++++---------------- tests/backend/mongodb/test_indexes.py | 23 ++++++++++++ 2 files changed, 45 insertions(+), 32 deletions(-) create mode 100644 tests/backend/mongodb/test_indexes.py diff --git a/bigchaindb/backend/mongodb/query.py b/bigchaindb/backend/mongodb/query.py index d7ee6afc..2bbfa08f 100644 --- a/bigchaindb/backend/mongodb/query.py +++ b/bigchaindb/backend/mongodb/query.py @@ -1,7 +1,6 @@ """Query implementation for MongoDB""" from time import time -from itertools import chain from pymongo import ReturnDocument from pymongo import errors @@ -86,39 +85,30 @@ def get_blocks_status_from_transaction(conn, transaction_id): @register_query(MongoDBConnection) def get_txids_filtered(conn, asset_id, operation=None): - parts = [] + match_create = { + 'block.transactions.operation': 'CREATE', + 'block.transactions.id': asset_id + } + match_transfer = { + 'block.transactions.operation': 'TRANSFER', + 'block.transactions.asset.id': asset_id + } - if operation in (Transaction.CREATE, None): - # get the txid of the create transaction for asset_id - cursor = conn.db['bigchain'].aggregate([ - {'$match': { - 'block.transactions.id': asset_id, - 'block.transactions.operation': 'CREATE' - }}, - {'$unwind': '$block.transactions'}, - {'$match': { - 'block.transactions.id': asset_id, - 'block.transactions.operation': 'CREATE' - }}, - {'$project': {'block.transactions.id': True}} - ]) - parts.append(elem['block']['transactions']['id'] for elem in cursor) + if operation == Transaction.CREATE: + match = match_create + elif operation == Transaction.TRANSFER: + match = match_transfer + else: + match = {'$or': [match_create, match_transfer]} - if operation in (Transaction.TRANSFER, None): - # get txids of transfer transaction with asset_id - cursor = conn.db['bigchain'].aggregate([ - {'$match': { - 'block.transactions.asset.id': asset_id - }}, - {'$unwind': '$block.transactions'}, - {'$match': { - 'block.transactions.asset.id': asset_id - }}, - {'$project': {'block.transactions.id': True}} - ]) - parts.append(elem['block']['transactions']['id'] for elem in cursor) - - return chain(*parts) + pipeline = [ + {'$match': match}, + {'$unwind': '$block.transactions'}, + {'$match': match}, + {'$project': {'block.transactions.id': True}} + ] + cursor = conn.db['bigchain'].aggregate(pipeline) + return (elem['block']['transactions']['id'] for elem in cursor) @register_query(MongoDBConnection) diff --git a/tests/backend/mongodb/test_indexes.py b/tests/backend/mongodb/test_indexes.py new file mode 100644 index 00000000..ba6afae1 --- /dev/null +++ b/tests/backend/mongodb/test_indexes.py @@ -0,0 +1,23 @@ +import pytest +from unittest.mock import MagicMock + +pytestmark = pytest.mark.bdb + + +def test_asset_id_index(): + from bigchaindb.backend.mongodb.query import get_txids_filtered + from bigchaindb.backend import connect + + # Passes a mock in place of a connection to get the query params from the + # query function, then gets the explain plan from MongoDB to test that + # it's using certain indexes. + + m = MagicMock() + get_txids_filtered(m, '') + pipeline = m.db['bigchain'].aggregate.call_args[0][0] + run = connect().db.command + res = run('aggregate', 'bigchain', pipeline=pipeline, explain=True) + stages = (res['stages'][0]['$cursor']['queryPlanner']['winningPlan'] + ['inputStage']['inputStages']) + indexes = [s['inputStage']['indexName'] for s in stages] + assert set(indexes) == {'asset_id', 'transaction_id'}