Lorenz Herzberger 4472a1a3ee
refactor tarantool backend (#292)
* added initial interfaces for backend, refactored Asset and MetaData logic

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* adjusted input dataclass, added queries, removed convert

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* created backend models folder, replaced token_hex with uuid

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Add cleanup and add constants

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* added to and from static methods to asset, input model and removed logic from tools

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* simplified store_bulk_transaction and corresponding query, adjusted test cases

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* changed script queries

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Add Output model

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Adapt Output class

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Further fixes

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Further fixes

* Get rid of decompose

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* refactored init.lua

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* refactored drop.lua

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Add transaction data class

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* refactored init.lua

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fix tests

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Fix more tests

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Format file

* Fix recursion error

* More fixes

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Further fixes

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* using init.lua for db setup

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed flush_db for new tarantool implementation

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* changed unique constraints

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* used new indexes on block related db operations

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Adapt models

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Check if blocks is empty

* adjusted get_txids_filtered for new indexes

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Adaptions due to schema change

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* fixed get block test case

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* Fix subcondition serialization

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* Remove unnecessary method

Signed-off-by: cybnon <stefan.weber93@googlemail.com>

* More fixes

* renamed group_txs and used data models in fastquery

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* adjusted query test cases, removed unused code

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* replaced asset search with get_asset_by_cid

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* added limit to asset queries

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* replaced metadata search with cid lookup

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed most of the test_lib test cases

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed election test cases

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed some more test cases

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed 'is' vs '==' issue

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* - blackified & fixed recovery / delete transactions issues becaues of data model transitions
- reintegrated get_transaction() call in query -> delegating this to get_complete_transactions_by_ids

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* show election status uses the governance table from now on
show election status maps the asset["data"] object properly

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed input object differences between old / new version and lookup of transaction in the governance pool

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed TX lookup issues due to different pools

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed wrong index name issue:  transaction_by_asset vs transaction_by_asset_id

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed asset class key mixup

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* moved field removal methods to DbTransaction
redefined strcuture of DbTransction.to_dict() to be equal to the one of Transactions.to_dict()

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added proper input conversion of the test cases and a proper input validation and object converion

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* simplified imports
fixed transfer input issues of the tests

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed comparision issue : dict vs. object

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed schema validation errors

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* added verification of ConditionDetails to the owner verification to avoid mixup between ConditionDetails and SubCondition
fixed Object comparision issues due to object changes

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed object handling issue and complicated stuff

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added missing import

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added proper corner case handling in case a requested block is not found

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed object comparision issue

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed output handling for validate_transfer_inputs

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* fixed wrong search pool usage

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed zenroom testcase

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed last abci issues and blackified the code

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added tarantool exception catching and raising as well as logging

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed obj comparision issue in test_get_spent_issue_1271

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added raiing CriticialDoubleSpend Exception for governance and transactions
fixed search space issue with election / voting commit lookup

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* * made returned outputs unique (get_owned_ids)
* added delete_output method to init.lua
* fixd output deletion issue by relaying the deletion to lua instead of the python code

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed rollback after crash

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* adjusted assets=None to assets=[{"data":None}] to avoid exeptions in the background service

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* removed unused code

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* removed unused code, reverted transaction fetching, added return types to queries

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* removed duplicate code

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* removed depricated code

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

* store transactions of various versions (backwardcompatibility)
added _bdb variable to init/drop DBs for the single use cases (started failing as TXs are looked up in DB - compared to before)

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* added support for v2.0 transaction to DB writing/reading

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* fixed merge errors (arguments ... )

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* blackified

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* Simplified unit tests (#294)

* adjusted make test
* 1st improvments to ease testing
* simplified gh actions
* adjusted gh action file
* removed deps
* added sudo to apt calls
* removed predefined pytest module definitions
* added installing planetmint into the unit test container
* give time to the db container
* added environment variables to unit-test.yml
* removed acceptances tests from test executions

Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>

* removed unused code, updated version number

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>

Signed-off-by: Lorenz Herzberger <lorenzherzberger@gmail.com>
Signed-off-by: cybnon <stefan.weber93@googlemail.com>
Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>
Co-authored-by: cybnon <stefan.weber93@googlemail.com>
Co-authored-by: Jürgen Eckel <juergen@riddleandcode.com>
Co-authored-by: Jürgen Eckel <eckelj@users.noreply.github.com>
2023-01-16 15:21:56 +01:00

399 lines
14 KiB
Python

# Copyright © 2020 Interplanetary Database Association e.V.,
# Planetmint and IPDB software contributors.
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
import os
import pytest
from unittest.mock import patch
from transactions.types.assets.create import Create
from transactions.types.assets.transfer import Transfer
from operator import index
from hashlib import sha3_256
from pymongo import MongoClient
from planetmint import backend
from transactions.common.transaction_mode_types import (
BROADCAST_TX_COMMIT,
BROADCAST_TX_ASYNC,
BROADCAST_TX_SYNC,
)
from planetmint.lib import Block
from ipld import marshal, multihash
from uuid import uuid4
@pytest.mark.bdb
def test_asset_is_separated_from_transaciton(b):
import copy
from transactions.common.crypto import generate_key_pair
from planetmint.backend.tarantool.connection import TarantoolDBConnection
if isinstance(b.connection, TarantoolDBConnection):
pytest.skip("This specific function is skipped because, assets are stored differently if using Tarantool")
alice = generate_key_pair()
bob = generate_key_pair()
assets = [
{
"data": multihash(
marshal(
{
"Never gonna": [
"give you up",
"let you down",
"run around" "desert you",
"make you cry",
"say goodbye",
"tell a lie",
"hurt you",
]
}
)
)
}
]
tx = Create.generate([alice.public_key], [([bob.public_key], 1)], metadata=None, assets=assets).sign(
[alice.private_key]
)
# with store_bulk_transactions we use `insert_many` where PyMongo
# automatically adds an `_id` field to the tx, therefore we need the
# deepcopy, for more info see:
# https://api.mongodb.com/python/current/faq.html#writes-and-ids
tx_dict = copy.deepcopy(tx.to_dict())
b.store_bulk_transactions([tx])
assert "asset" not in backend.query.get_transaction_single(b.connection, tx.id)
assert backend.query.get_asset(b.connection, tx.id).data == assets[0]
assert b.get_transaction(tx.id).to_dict() == tx_dict
@pytest.mark.bdb
def test_get_latest_block(b):
from planetmint.lib import Block
for i in range(10):
app_hash = os.urandom(16).hex()
txn_id = os.urandom(16).hex()
block = Block(app_hash=app_hash, height=i, transactions=[txn_id])._asdict()
b.store_block(block)
block = b.get_latest_block()
assert block["height"] == 9
@pytest.mark.bdb
@patch("planetmint.backend.query.get_block", return_value=None)
@patch("planetmint.Planetmint.get_latest_block", return_value={"height": 10})
def test_get_empty_block(_0, _1, b):
assert b.get_block(5) == {"height": 5, "transactions": []}
def test_validation_error(b):
from transactions.common.crypto import generate_key_pair
alice = generate_key_pair()
tx = (
Create.generate([alice.public_key], [([alice.public_key], 1)], assets=None).sign([alice.private_key]).to_dict()
)
tx["metadata"] = ""
assert not b.validate_transaction(tx)
@patch("requests.post")
def test_write_and_post_transaction(mock_post, b):
from transactions.common.crypto import generate_key_pair
from planetmint.tendermint_utils import encode_transaction
alice = generate_key_pair()
tx = (
Create.generate([alice.public_key], [([alice.public_key], 1)], assets=None).sign([alice.private_key]).to_dict()
)
tx = b.validate_transaction(tx)
b.write_transaction(tx, BROADCAST_TX_ASYNC)
assert mock_post.called
args, kwargs = mock_post.call_args
assert BROADCAST_TX_ASYNC == kwargs["json"]["method"]
encoded_tx = [encode_transaction(tx.to_dict())]
assert encoded_tx == kwargs["json"]["params"]
@patch("requests.post")
@pytest.mark.parametrize("mode", [BROADCAST_TX_SYNC, BROADCAST_TX_ASYNC, BROADCAST_TX_COMMIT])
def test_post_transaction_valid_modes(mock_post, b, mode):
from transactions.common.crypto import generate_key_pair
alice = generate_key_pair()
tx = (
Create.generate([alice.public_key], [([alice.public_key], 1)], assets=None).sign([alice.private_key]).to_dict()
)
tx = b.validate_transaction(tx)
b.write_transaction(tx, mode)
args, kwargs = mock_post.call_args
assert mode == kwargs["json"]["method"]
def test_post_transaction_invalid_mode(b):
from transactions.common.crypto import generate_key_pair
from transactions.common.exceptions import ValidationError
alice = generate_key_pair()
tx = (
Create.generate([alice.public_key], [([alice.public_key], 1)], assets=None).sign([alice.private_key]).to_dict()
)
tx = b.validate_transaction(tx)
with pytest.raises(ValidationError):
b.write_transaction(tx, "nope")
@pytest.mark.bdb
def test_update_utxoset(b, signed_create_tx, signed_transfer_tx, db_conn):
b.update_utxoset(signed_create_tx)
utxoset = db_conn.get_space("utxos")
assert utxoset.select().rowcount == 1
utxo = utxoset.select().data
assert utxo[0][1] == signed_create_tx.id
assert utxo[0][2] == 0
b.update_utxoset(signed_transfer_tx)
assert utxoset.select().rowcount == 1
utxo = utxoset.select().data
assert utxo[0][1] == signed_transfer_tx.id
assert utxo[0][2] == 0
@pytest.mark.bdb
def test_store_transaction(mocker, b, signed_create_tx, signed_transfer_tx):
mocked_store_transaction = mocker.patch("planetmint.backend.query.store_transactions")
b.store_bulk_transactions([signed_create_tx])
mocked_store_transaction.assert_any_call(b.connection, [signed_create_tx.to_dict()], "transactions")
mocked_store_transaction.reset_mock()
b.store_bulk_transactions([signed_transfer_tx])
@pytest.mark.bdb
def test_store_bulk_transaction(mocker, b, signed_create_tx, signed_transfer_tx):
mocked_store_transactions = mocker.patch("planetmint.backend.query.store_transactions")
b.store_bulk_transactions((signed_create_tx,))
mocked_store_transactions.assert_any_call(b.connection, [signed_create_tx.to_dict()], "transactions")
mocked_store_transactions.reset_mock()
b.store_bulk_transactions((signed_transfer_tx,))
@pytest.mark.bdb
def test_delete_zero_unspent_outputs(b, utxoset):
unspent_outputs, utxo_collection = utxoset
num_rows_before_operation = utxo_collection.select().rowcount
delete_res = b.delete_unspent_outputs() # noqa: F841
num_rows_after_operation = utxo_collection.select().rowcount
# assert delete_res is None
assert num_rows_before_operation == num_rows_after_operation
@pytest.mark.bdb
def test_delete_one_unspent_outputs(b, dummy_unspent_outputs):
utxo_space = b.connection.get_space("utxos")
for utxo in dummy_unspent_outputs:
res = utxo_space.insert((uuid4().hex, utxo["transaction_id"], utxo["output_index"], utxo))
assert res
b.delete_unspent_outputs(dummy_unspent_outputs[0])
res1 = utxo_space.select(["a", 1], index="utxo_by_transaction_id_and_output_index").data
res2 = utxo_space.select(["b", 0], index="utxo_by_transaction_id_and_output_index").data
assert len(res1) + len(res2) == 2
res3 = utxo_space.select(["a", 0], index="utxo_by_transaction_id_and_output_index").data
assert len(res3) == 0
@pytest.mark.bdb
def test_delete_many_unspent_outputs(b, dummy_unspent_outputs):
utxo_space = b.connection.get_space("utxos")
for utxo in dummy_unspent_outputs:
res = utxo_space.insert((uuid4().hex, utxo["transaction_id"], utxo["output_index"], utxo))
assert res
b.delete_unspent_outputs(*dummy_unspent_outputs[::2])
res1 = utxo_space.select(["a", 0], index="utxo_by_transaction_id_and_output_index").data
res2 = utxo_space.select(["b", 0], index="utxo_by_transaction_id_and_output_index").data
assert len(res1) + len(res2) == 0
res3 = utxo_space.select([], index="utxo_by_transaction_id_and_output_index").data
assert len(res3) == 1
@pytest.mark.bdb
def test_store_zero_unspent_output(b):
utxos = b.connection.get_space("utxos")
num_rows_before_operation = utxos.select().rowcount
res = b.store_unspent_outputs()
num_rows_after_operation = utxos.select().rowcount
assert res is None
assert num_rows_before_operation == num_rows_after_operation
@pytest.mark.bdb
def test_store_one_unspent_output(b, unspent_output_1, utxo_collection):
from planetmint.backend.tarantool.connection import TarantoolDBConnection
res = b.store_unspent_outputs(unspent_output_1)
if not isinstance(b.connection, TarantoolDBConnection):
assert res.acknowledged
assert len(list(res)) == 1
assert (
utxo_collection.count_documents(
{
"transaction_id": unspent_output_1["transaction_id"],
"output_index": unspent_output_1["output_index"],
}
)
== 1
)
else:
utx_space = b.connection.get_space("utxos")
res = utx_space.select(
[unspent_output_1["transaction_id"], unspent_output_1["output_index"]],
index="utxo_by_transaction_id_and_output_index",
)
assert len(res.data) == 1
@pytest.mark.bdb
def test_store_many_unspent_outputs(b, unspent_outputs):
b.store_unspent_outputs(*unspent_outputs)
utxo_space = b.connection.get_space("utxos")
res = utxo_space.select([unspent_outputs[0]["transaction_id"]], index="utxos_by_transaction_id")
assert len(res.data) == 3
def test_get_utxoset_merkle_root_when_no_utxo(b):
assert b.get_utxoset_merkle_root() == sha3_256(b"").hexdigest()
@pytest.mark.bdb
def test_get_utxoset_merkle_root(b, dummy_unspent_outputs):
utxo_space = b.connection.get_space("utxos")
for utxo in dummy_unspent_outputs:
res = utxo_space.insert((uuid4().hex, utxo["transaction_id"], utxo["output_index"], utxo))
assert res
expected_merkle_root = "86d311c03115bf4d287f8449ca5828505432d69b82762d47077b1c00fe426eac"
merkle_root = b.get_utxoset_merkle_root()
assert merkle_root == expected_merkle_root
@pytest.mark.bdb
def test_get_spent_transaction_double_spend(b, alice, bob, carol):
from transactions.common.exceptions import DoubleSpend
assets = [{"data": multihash(marshal({"test": "asset"}))}]
tx = Create.generate([alice.public_key], [([alice.public_key], 1)], assets=assets).sign([alice.private_key])
tx_transfer = Transfer.generate(tx.to_inputs(), [([bob.public_key], 1)], asset_ids=[tx.id]).sign(
[alice.private_key]
)
double_spend = Transfer.generate(tx.to_inputs(), [([carol.public_key], 1)], asset_ids=[tx.id]).sign(
[alice.private_key]
)
same_input_double_spend = Transfer.generate(
tx.to_inputs() + tx.to_inputs(), [([bob.public_key], 1)], asset_ids=[tx.id]
).sign([alice.private_key])
b.store_bulk_transactions([tx])
with pytest.raises(DoubleSpend):
b.validate_transaction(same_input_double_spend)
assert b.get_spent(tx.id, tx_transfer.inputs[0].fulfills.output, [tx_transfer])
with pytest.raises(DoubleSpend):
b.get_spent(tx.id, tx_transfer.inputs[0].fulfills.output, [tx_transfer, double_spend])
b.store_bulk_transactions([tx_transfer])
with pytest.raises(DoubleSpend):
b.get_spent(tx.id, tx_transfer.inputs[0].fulfills.output, [double_spend])
def test_validation_with_transaction_buffer(b):
from transactions.common.crypto import generate_key_pair
priv_key, pub_key = generate_key_pair()
create_tx = Create.generate([pub_key], [([pub_key], 10)]).sign([priv_key])
transfer_tx = Transfer.generate(create_tx.to_inputs(), [([pub_key], 10)], asset_ids=[create_tx.id]).sign(
[priv_key]
)
double_spend = Transfer.generate(create_tx.to_inputs(), [([pub_key], 10)], asset_ids=[create_tx.id]).sign(
[priv_key]
)
assert b.is_valid_transaction(create_tx)
assert b.is_valid_transaction(transfer_tx, [create_tx])
assert not b.is_valid_transaction(create_tx, [create_tx])
assert not b.is_valid_transaction(transfer_tx, [create_tx, transfer_tx])
assert not b.is_valid_transaction(double_spend, [create_tx, transfer_tx])
@pytest.mark.bdb
def test_migrate_abci_chain_yields_on_genesis(b):
b.migrate_abci_chain()
latest_chain = b.get_latest_abci_chain()
assert latest_chain is None
@pytest.mark.bdb
@pytest.mark.parametrize(
"chain,block_height,expected",
[
(
(1, "chain-XYZ", True),
4,
{"height": 5, "chain_id": "chain-XYZ-migrated-at-height-4", "is_synced": False},
),
(
(5, "chain-XYZ-migrated-at-height-4", True),
13,
{"height": 14, "chain_id": "chain-XYZ-migrated-at-height-13", "is_synced": False},
),
],
)
def test_migrate_abci_chain_generates_new_chains(b, chain, block_height, expected):
b.store_abci_chain(*chain)
b.store_block(Block(app_hash="", height=block_height, transactions=[])._asdict())
b.migrate_abci_chain()
latest_chain = b.get_latest_abci_chain()
assert latest_chain == expected
@pytest.mark.bdb
def test_get_spent_key_order(b, user_pk, user_sk, user2_pk, user2_sk):
from transactions.common.crypto import generate_key_pair
from transactions.common.exceptions import DoubleSpend
alice = generate_key_pair()
bob = generate_key_pair()
tx1 = Create.generate([user_pk], [([alice.public_key], 3), ([user_pk], 2)]).sign([user_sk])
b.store_bulk_transactions([tx1])
inputs = tx1.to_inputs()
tx2 = Transfer.generate([inputs[1]], [([user2_pk], 2)], [tx1.id]).sign([user_sk])
assert b.validate_transaction(tx2)
b.store_bulk_transactions([tx2])
tx3 = Transfer.generate([inputs[1]], [([bob.public_key], 2)], [tx1.id]).sign([user_sk])
with pytest.raises(DoubleSpend):
b.validate_transaction(tx3)