Exemple #1
0
def test_message_identical() -> None:
    """ Will fail if the messages changed since the committed version

    If you intend to change the serialized messages, then update the messages
    on disc (see comment inside test). This test exists only to prevent
    accidental breaking of compatibility.

    If many values change in unexpected ways, that might have to do with the
    pseudo-random initialization of the messages (see random.seed() above).
    """
    signer = LocalSigner(bytes(range(32)))
    for message in messages:
        # The messages contain only random signatures. We don't want to test
        # only the serialization itself, but also prevent accidental changes of
        # the signature. To do this, we have to create proper signatures.
        message.sign(signer)

        filename = os.path.join(
            os.path.dirname(__file__), "serialized_messages", message.__class__.__name__ + ".json"
        )

        # Uncomment this for one run if you intentionally changed the message
        # with open(filename, "w") as f:
        #     json_msg = MessageSerializer.serialize(message)
        #     # pretty print for more readable diffs
        #     json_msg = json.dumps(json.loads(json_msg), indent=4, sort_keys=True)
        #     f.write(json_msg)

        with open(filename) as f:
            saved_message_dict = JSONSerializer.deserialize(f.read())

        # The assert output is more readable when we used dicts than with plain JSON
        message_dict = JSONSerializer.deserialize(MessageSerializer.serialize(message))
        assert message_dict == saved_message_dict
Exemple #2
0
def test_actioninitchain_restore():
    """ ActionInitChain *must* restore the previous pseudo random generator
    state.

    Message identifiers are used for confirmation messages, e.g. delivered and
    processed messages, therefore it's important for each message identifier to
    not collide with a previous identifier, for this reason the PRNG is used.

    Additionally, during restarts the state changes are reapplied, and it's
    really important for the re-execution of the state changes to be
    deterministic, otherwise undefined behavior may happen. For this reason the
    state of the PRNG must be restored.

    If the above is not respected, the message ids generated during restart
    will not match the previous IDs and the message queues won't be properly
    cleared up.
    """
    pseudo_random_generator = random.Random()
    block_number = 577
    our_address = factories.make_address()
    chain_id = 777

    original_obj = state_change.ActionInitChain(
        pseudo_random_generator=pseudo_random_generator,
        block_number=block_number,
        block_hash=factories.make_block_hash(),
        our_address=our_address,
        chain_id=chain_id,
    )

    decoded_obj = JSONSerializer.deserialize(
        JSONSerializer.serialize(original_obj))

    assert original_obj == decoded_obj
Exemple #3
0
def test_serialize_contract_send_subclass(chain_state):
    """Serializing must preserve class

    Regression test for https://github.com/raiden-network/raiden/issues/6075
    """
    canonical_identifier = CanonicalIdentifier(
        chain_identifier=ChainID(1),
        token_network_address=TokenNetworkAddress(factories.make_address()),
        channel_identifier=factories.make_channel_identifier(),
    )
    chain_state.pending_transactions = [
        ContractSendChannelClose(
            canonical_identifier=canonical_identifier,
            triggered_by_block_hash=factories.make_block_hash(),
            balance_proof=None,
        )
    ]

    serialized_chain_state = JSONSerializer.serialize(chain_state)
    deserialized_chain_state = JSONSerializer.deserialize(
        serialized_chain_state)
    assert (
        chain_state.pending_transactions[0].__class__.__name__ ==
        deserialized_chain_state.pending_transactions[0].__class__.__name__)
    assert chain_state == deserialized_chain_state
Exemple #4
0
def test_restore_queueids_to_queues(chain_state, netting_channel_state):
    """Test that withdraw messages are restorable if they exist in
    chain_state.queueids_to_queues.
    """
    recipient = netting_channel_state.partner_state.address

    queue_identifier = QueueIdentifier(
        recipient=recipient,
        canonical_identifier=netting_channel_state.canonical_identifier)

    msg_args = dict(
        recipient=recipient,
        canonical_identifier=netting_channel_state.canonical_identifier,
        message_identifier=factories.make_message_identifier(),
        total_withdraw=WithdrawAmount(1),
        participant=recipient,
        expiration=BlockExpiration(10),
        nonce=Nonce(15),
    )
    messages = [
        SendWithdrawRequest(**msg_args),
        SendWithdrawConfirmation(**msg_args),
        SendWithdrawExpired(**msg_args),
    ]

    chain_state.queueids_to_queues[queue_identifier] = messages

    serialized_chain_state = JSONSerializer.serialize(chain_state)

    deserialized_chain_state = JSONSerializer.deserialize(
        serialized_chain_state)

    assert chain_state == deserialized_chain_state
def test_mediated_transfer_min_max(amount, payment_identifier, nonce, transferred_amount):
    mediated_transfer = factories.create(
        factories.LockedTransferProperties(
            amount=amount,
            payment_identifier=payment_identifier,
            nonce=nonce,
            transferred_amount=transferred_amount,
        )
    )

    mediated_transfer.sign(signer)
    data = JSONSerializer.serialize(mediated_transfer)
    assert JSONSerializer.deserialize(data) == mediated_transfer
Exemple #6
0
def test_send_refund_transfer_contains_balance_proof():
    recipient = factories.make_address()
    transfer = factories.create(factories.LockedTransferUnsignedStateProperties())
    message_identifier = 1
    event = SendRefundTransfer(
        recipient=recipient,
        message_identifier=message_identifier,
        transfer=transfer,
        canonical_identifier=factories.make_canonical_identifier(),
    )

    assert hasattr(event, "balance_proof")
    assert JSONSerializer.deserialize(JSONSerializer.serialize(event)) == event
def test_refund_transfer_min_max(amount, payment_identifier, nonce, transferred_amount):
    refund_transfer = factories.create(
        factories.RefundTransferProperties(
            amount=amount,
            payment_identifier=payment_identifier,
            nonce=nonce,
            transferred_amount=transferred_amount,
        )
    )

    refund_transfer.sign(signer)

    data = JSONSerializer.serialize(refund_transfer)
    assert JSONSerializer.deserialize(data) == refund_transfer
Exemple #8
0
def test_serialization_networkx_graph():
    p1 = to_canonical_address("0x5522070585a1a275631ba69c444ac0451AA9Fe4C")
    p2 = to_canonical_address("0x5522070585a1a275631ba69c444ac0451AA9Fe4D")
    p3 = to_canonical_address("0x5522070585a1a275631ba69c444ac0451AA9Fe4E")
    p4 = to_canonical_address("0x5522070585a1a275631ba69c444ac0451AA9Fe4F")

    e = [(p1, p2), (p2, p3), (p3, p4)]
    graph = Graph(e)
    instance = ClassWithGraphObject(graph)

    data = JSONSerializer.serialize(instance)
    restored_instance = JSONSerializer.deserialize(data)

    assert instance.graph.edges == restored_instance.graph.edges
Exemple #9
0
def test_chainstate_restore():
    pseudo_random_generator = random.Random()
    block_number = 577
    our_address = factories.make_address()
    chain_id = 777

    original_obj = state.ChainState(
        pseudo_random_generator=pseudo_random_generator,
        block_number=block_number,
        block_hash=factories.make_block_hash(),
        our_address=our_address,
        chain_id=chain_id,
    )

    decoded_obj = JSONSerializer.deserialize(JSONSerializer.serialize(original_obj))

    assert original_obj == decoded_obj
Exemple #10
0
def test_decode_with_unknown_type():
    test_str = """{"_type": "some.non.existent.package"}"""
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize(test_str)

    test_str = """{"_type": "raiden.tests.NonExistentClass"}"""
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize(test_str)

    test_str = """{"_type": "NonExistentClass"}"""
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize(test_str)
Exemple #11
0
def test_deserialize_missing_attribute():
    test_input = json.dumps(
        {"_type": f"{ClassWithInt.__module__}.ClassWithInt"})
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize(test_input)
Exemple #12
0
def test_deserialize_wrong_type():
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize("[]")
Exemple #13
0
def test_deserialize_invalid_json(input_value):
    with pytest.raises(SerializationError):
        JSONSerializer.deserialize(input_value)