def test_processed(): message = Processed(message_identifier=MessageID(18237677588114994956)) message.sign(signer) data_was_signed = message._data_to_sign() print("Processed signature: " + message.signature.hex()) assert recover(data_was_signed, message.signature) == to_canonical_address( "0x7ca28d3d760b4aa2b79e8d42cbdc187c7df9af40")
def test_automatic_secret_registration( raiden_chain: List[App], token_addresses: List[TokenAddress] ) -> None: app0, app1 = raiden_chain token_address = token_addresses[0] token_network_address = views.get_token_network_address_by_token_address( views.state_from_app(app0), app0.raiden.default_registry.address, token_address ) assert token_network_address hold_event_handler = app1.raiden.raiden_event_handler message_handler = app1.raiden.message_handler msg = "hold event handler necessary to control messages" assert isinstance(hold_event_handler, HoldRaidenEventHandler), msg assert isinstance(message_handler, WaitForMessage), msg amount = PaymentAmount(100) identifier = factories.make_payment_id() target = TargetAddress(app1.raiden.address) (secret, secrethash) = factories.make_secret_with_hash() hold_event_handler.hold_secretrequest_for(secrethash=secrethash) locked_transfer_received = message_handler.wait_for_message(LockedTransfer, {}) app0.raiden.start_mediated_transfer_with_secret( token_network_address=token_network_address, amount=amount, target=target, identifier=identifier, secret=secret, ) # Wait for app1 to receive the locked transfer. locked_transfer_received.wait() # Stop app0 to avoid sending the unlock, this must be done after the locked # transfer is sent. app0.raiden.transport.stop() reveal_secret = RevealSecret( message_identifier=MessageID(random.randint(0, UINT64_MAX)), secret=secret, signature=EMPTY_SIGNATURE, ) app0.raiden.sign(reveal_secret) message_handler.on_messages(app1.raiden, [reveal_secret]) chain_state = views.state_from_app(app1) secrethash = sha256_secrethash(secret) target_task = chain_state.payment_mapping.secrethashes_to_task[secrethash] lock_expiration = target_task.target_state.transfer.lock.expiration # type: ignore app1.raiden.proxy_manager.client.wait_until_block(target_block_number=lock_expiration) assert app1.raiden.default_secret_registry.is_secret_registered( secrethash=secrethash, block_identifier=BLOCK_ID_LATEST )
def from_dict(cls, data: Dict[str, Any]) -> 'SendProcessed': restored = cls( recipient=to_canonical_address(data['recipient']), channel_identifier=ChannelID(int(data['channel_identifier'])), message_identifier=MessageID(int(data['message_identifier'])), ) return restored
def test_message_ack_timing_keeper_edge_cases(): matk = MessageAckTimingKeeper() # No measurements -> empty report assert matk.generate_report() == [] # Unknown messages must be ignored processed = Processed(MessageID(999), make_signature()) matk.finalize_message(processed) assert matk.generate_report() == [] reveal_secret = RevealSecret(MessageID(1), make_signature(), make_secret()) matk.add_message(reveal_secret) # In flight messages are not included in reports assert matk.generate_report() == []
def from_dict(cls, data: Dict[str, Any]) -> "SendLockedTransferLight": restored = cls( recipient=to_canonical_address(data["recipient"]), channel_identifier=ChannelID(int(data["channel_identifier"])), message_identifier=MessageID(int(data["message_identifier"])), signed_locked_transfer=data["signed_locked_transfer"], ) return restored
def test_message_ack_timing_keeper(): matk = MessageAckTimingKeeper() matk.add_message(RevealSecret(MessageID(1), make_signature(), make_secret())) gevent.sleep(0.05) matk.finalize_message(Processed(MessageID(1), make_signature())) assert len(matk._durations) == 1 assert 0.05 <= matk._durations[0] <= 0.06 # Set duration to a fixed value matk._durations[0] = 0.05 report = matk.generate_report() assert len(report) == 1 assert report == [0.05]
def from_dict(cls, data: Dict[str, Any]) -> "SendProcessed": restored = cls( recipient=to_canonical_address(data["recipient"]), channel_identifier=ChannelID(int(data["channel_identifier"])), message_identifier=MessageID(int(data["message_identifier"])), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> 'SendLockExpired': restored = cls( recipient=to_canonical_address(data['recipient']), message_identifier=MessageID(int(data['message_identifier'])), balance_proof=data['balance_proof'], secrethash=deserialize_secret_hash(data['secrethash']), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> 'SendSecretReveal': restored = cls( recipient=to_canonical_address(data['recipient']), channel_identifier=ChannelID(int(data['channel_identifier'])), message_identifier=MessageID(int(data['message_identifier'])), secret=Secret(serialization.deserialize_bytes(data['secret'])), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> "SendSecretReveal": restored = cls( recipient=to_canonical_address(data["recipient"]), channel_identifier=ChannelID(int(data["channel_identifier"])), message_identifier=MessageID(int(data["message_identifier"])), secret=deserialize_secret(data["secret"]), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> "SendLockExpired": restored = cls( recipient=to_canonical_address(data["recipient"]), message_identifier=MessageID(int(data["message_identifier"])), balance_proof=data["balance_proof"], secrethash=deserialize_secret_hash(data["secrethash"]), ) return restored
def __init__(self, chain_state: ChainState, channel_state: NettingChannelState): self.secret = random_secret() self.secrethash = SecretHash(sha3(self.secret)) self.lock_expiration = get_initial_lock_expiration( chain_state.block_number, channel_state.reveal_timeout) self.payment_identifier = PaymentID(create_default_identifier()) self.message_identifier = MessageID( message_identifier_from_prng(chain_state.pseudo_random_generator))
def test_automatic_secret_registration(raiden_chain, token_addresses): app0, app1 = raiden_chain token_address = token_addresses[0] token_network_address = views.get_token_network_address_by_token_address( views.state_from_app(app0), app0.raiden.default_registry.address, token_address) hold_event_handler = app1.raiden.raiden_event_handler amount = 100 identifier = 1 message_handler = WaitForMessage() app1.raiden.message_handler = message_handler target = app1.raiden.address secret = Secret(sha3(target)) secrethash = sha256_secrethash(secret) hold_event_handler.hold_secretrequest_for(secrethash=secrethash) locked_transfer_received = message_handler.wait_for_message( LockedTransfer, {}) app0.raiden.start_mediated_transfer_with_secret( token_network_address=token_network_address, amount=amount, target=target, identifier=identifier, secret=secret, ) # Wait for app1 to receive the locked transfer. locked_transfer_received.wait() # Stop app0 to avoid sending the unlock, this must be done after the locked # transfer is sent. app0.raiden.transport.stop() reveal_secret = RevealSecret( message_identifier=MessageID(random.randint(0, UINT64_MAX)), secret=secret, signature=EMPTY_SIGNATURE, ) app0.raiden.sign(reveal_secret) message_handler.on_message(app1.raiden, reveal_secret) chain_state = views.state_from_app(app1) secrethash = sha256_secrethash(secret) target_task = chain_state.payment_mapping.secrethashes_to_task[secrethash] lock_expiration = target_task.target_state.transfer.lock.expiration # type: ignore app1.raiden.proxy_manager.wait_until_block( target_block_number=lock_expiration) assert app1.raiden.default_secret_registry.is_secret_registered( secrethash=secrethash, block_identifier="latest")
def test_reveal_secret_7(): print("Secret {} ".format(secret.hex())) print("SecretHash {} ".format(secrethash.hex())) message = RevealSecret(message_identifier=MessageID(2226977946511089099), secret=secret) message.sign(signer) data_was_signed = message._data_to_sign() print("Reveal Secret signature: " + message.signature.hex()) assert recover(data_was_signed, message.signature) == to_canonical_address( "0x7ca28d3d760b4aa2b79e8d42cbdc187c7df9af40")
def from_dict(cls, data: Dict[str, Any]) -> 'SendBalanceProof': restored = cls( recipient=to_canonical_address(data['recipient']), channel_identifier=ChannelID(int(data['channel_identifier'])), message_identifier=MessageID(int(data['message_identifier'])), payment_identifier=PaymentID(int(data['payment_identifier'])), token_address=to_canonical_address(data['token_address']), secret=Secret(serialization.deserialize_bytes(data['secret'])), balance_proof=data['balance_proof'], ) return restored
def from_dict(cls, data: Dict[str, Any]) -> "SendSecretRequest": restored = cls( recipient=to_canonical_address(data["recipient"]), channel_identifier=ChannelID(int(data["channel_identifier"])), message_identifier=MessageID(int(data["message_identifier"])), payment_identifier=PaymentID(int(data["payment_identifier"])), amount=PaymentWithFeeAmount(int(data["amount"])), expiration=BlockExpiration(int(data["expiration"])), secrethash=deserialize_secret_hash(data["secrethash"]), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> "SendBalanceProof": restored = cls( recipient=to_canonical_address(data["recipient"]), channel_identifier=ChannelID(int(data["channel_identifier"])), message_identifier=MessageID(int(data["message_identifier"])), payment_identifier=PaymentID(int(data["payment_identifier"])), token_address=to_canonical_address(data["token_address"]), secret=deserialize_secret(data["secret"]), balance_proof=data["balance_proof"], ) return restored
def from_dict(cls, data: Dict[str, Any]) -> 'SendSecretRequest': restored = cls( recipient=to_canonical_address(data['recipient']), channel_identifier=ChannelID(int(data['channel_identifier'])), message_identifier=MessageID(int(data['message_identifier'])), payment_identifier=PaymentID(int(data['payment_identifier'])), amount=TokenAmount(int(data['amount'])), expiration=BlockExpiration(int(data['expiration'])), secrethash=SecretHash(serialization.deserialize_bytes(data['secrethash'])), ) return restored
def test_reveal_secret_9(): message = RevealSecret( message_identifier=MessageID(10945162236180065780), secret=Secret( decode_hex( "0xb8ed582d16853c82a9a9a384118fcd10889ab0a5a3224ec6008bd88582319fc3" ))) message.sign(signer) data_was_signed = message._data_to_sign() print("Reveal Secret signature 9: " + message.signature.hex()) assert recover(data_was_signed, message.signature) == to_canonical_address( "0x7ca28d3d760b4aa2b79e8d42cbdc187c7df9af40")
def from_dict(cls, data: Dict[str, Any]) -> "LockedTransferSignedState": restored = cls( message_identifier=MessageID(int(data["message_identifier"])), payment_identifier=PaymentID(int(data["payment_identifier"])), token=to_canonical_address(data["token"]), balance_proof=data["balance_proof"], lock=data["lock"], initiator=to_canonical_address(data["initiator"]), target=to_canonical_address(data["target"]), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> 'LockedTransferSignedState': restored = cls( message_identifier=MessageID(int(data['message_identifier'])), payment_identifier=PaymentID(int(data['payment_identifier'])), token=to_canonical_address(data['token']), balance_proof=data['balance_proof'], lock=data['lock'], initiator=to_canonical_address(data['initiator']), target=to_canonical_address(data['target']), ) return restored
def from_dict(cls, data: Dict[str, Any]) -> "LockedTransferSignedState": if "payment_hash_invoice" not in data: data["payment_hash_invoice"] = EMPTY_PAYMENT_HASH_INVOICE restored = cls( message_identifier=MessageID(int(data["message_identifier"])), payment_identifier=PaymentID(int(data["payment_identifier"])), payment_hash_invoice=PaymentHashInvoice( decode_hex(data["payment_hash_invoice"])), token=to_canonical_address(data["token"]), balance_proof=data["balance_proof"], lock=data["lock"], initiator=to_canonical_address(data["initiator"]), target=to_canonical_address(data["target"]), ) return restored
def test_web_rtc_message_sync(matrix_transports): transport0, transport1 = matrix_transports transport1_messages = set() raiden_service0 = MockRaidenService() raiden_service1 = MockRaidenService() def mock_handle_web_rtc_messages(message_data, partner_address): messages = validate_and_parse_message(message_data, partner_address) transport1_messages.update(messages) # set mock function to make sure messages are sent via web rtc transport1._web_rtc_manager._handle_message_callback = mock_handle_web_rtc_messages transport0.start(raiden_service0, [], None) transport1.start(raiden_service1, [], None) transport0.immediate_health_check_for(transport1._raiden_service.address) transport1.immediate_health_check_for(transport0._raiden_service.address) with Timeout(TIMEOUT_WEB_RTC_CONNECTION): # wait until web rtc connection is ready while not transport0._web_rtc_manager.has_ready_channel(raiden_service1.address): gevent.sleep(1) while not transport1._web_rtc_manager.has_ready_channel(raiden_service0.address): gevent.sleep(1) queue_identifier = QueueIdentifier( recipient=transport1._raiden_service.address, canonical_identifier=factories.UNIT_CANONICAL_ID, ) raiden0_queues = views.get_all_messagequeues(views.state_from_raiden(raiden_service0)) raiden0_queues[queue_identifier] = [] for i in range(5): message = Processed(message_identifier=MessageID(i), signature=EMPTY_SIGNATURE) raiden0_queues[queue_identifier].append(message) transport0._raiden_service.sign(message) transport0.send_async([MessagesQueue(queue_identifier, [message])]) with Timeout(TIMEOUT_MESSAGE_RECEIVE): while not len(transport1_messages) == 5: gevent.sleep(0.1)
def test_unhandled_message(pathfinding_service_mock, log): metrics_state = save_metrics_state(metrics.REGISTRY) unknown_message = Processed(MessageID(123), signature=EMPTY_SIGNATURE) unknown_message.sign(LocalSigner(PARTICIPANT1_PRIVKEY)) pathfinding_service_mock.handle_message(unknown_message) # Although the message is unknown and will be ignored, # it is still logged under it's message type assert (metrics_state.get_delta( "messages_processing_duration_seconds_sum", labels={"message_type": "Processed"}, ) > 0.0) assert (metrics_state.get_delta("messages_exceptions_total", labels={"message_type": "Processed"}) == 0.0) assert log.has("Ignoring message", unknown_message=unknown_message)
def _new_mediator_transfer(self, initiator_address, target_address, payment_id, amount, secret, our_address) -> LockedTransferSignedState: initiator_pkey = self.address_to_privkey[initiator_address] balance_proof_data = self._update_balance_proof_data( initiator_address, amount, self.block_number + 10, secret, our_address) self.secrethash_to_secret[sha256_secrethash(secret)] = secret return factories.create( factories.LockedTransferSignedStateProperties( # type: ignore **balance_proof_data.properties.__dict__, amount=amount, expiration=BlockExpiration(self.block_number + 10), payment_identifier=payment_id, secret=secret, initiator=initiator_address, target=target_address, token=self.token_id, sender=initiator_address, recipient=our_address, pkey=initiator_pkey, message_identifier=MessageID(1), ))
def make_message_identifier() -> MessageID: return MessageID(random.randint(0, UINT64_MAX))
def test_get_event_with_balance_proof(): """ All events which contain a balance proof must be found by when querying the database. """ serializer = JSONSerializer() storage = SerializedSQLiteStorage(":memory:", serializer) counter = itertools.count(1) partner_address = factories.make_address() balance_proof = make_balance_proof_from_counter(counter) lock_expired = SendLockExpired( recipient=partner_address, message_identifier=MessageID(next(counter)), balance_proof=balance_proof, secrethash=factories.make_secret_hash(next(counter)), canonical_identifier=balance_proof.canonical_identifier, ) locked_transfer = SendLockedTransfer( recipient=partner_address, message_identifier=MessageID(next(counter)), transfer=make_transfer_from_counter(counter), canonical_identifier=factories.make_canonical_identifier(), ) send_balance_proof = SendBalanceProof( recipient=partner_address, message_identifier=MessageID(next(counter)), payment_identifier=factories.make_payment_id(), token_address=factories.make_token_address(), secret=factories.make_secret(next(counter)), balance_proof=make_balance_proof_from_counter(counter), canonical_identifier=factories.make_canonical_identifier(), ) refund_transfer = SendRefundTransfer( recipient=partner_address, message_identifier=MessageID(next(counter)), transfer=make_transfer_from_counter(counter), canonical_identifier=factories.make_canonical_identifier(), ) events_balanceproofs = [ (lock_expired, lock_expired.balance_proof), (locked_transfer, locked_transfer.balance_proof), (send_balance_proof, send_balance_proof.balance_proof), (refund_transfer, refund_transfer.transfer.balance_proof), ] state_change = Block(BlockNumber(1), BlockGasLimit(1), factories.make_block_hash()) for event, _ in events_balanceproofs: state_change_identifiers = storage.write_state_changes([state_change]) storage.write_events(events=[(state_change_identifiers[0], event)]) for event, balance_proof in events_balanceproofs: event_record = get_event_with_balance_proof_by_balance_hash( storage=storage, canonical_identifier=balance_proof.canonical_identifier, balance_hash=balance_proof.balance_hash, recipient=partner_address, ) assert event_record assert event_record.data == event event_record = get_event_with_balance_proof_by_locksroot( storage=storage, canonical_identifier=balance_proof.canonical_identifier, recipient=event.recipient, locksroot=balance_proof.locksroot, ) assert event_record assert event_record.data == event # Checking that balance proof attribute can be accessed for all events. # Issue https://github.com/raiden-network/raiden/issues/3179 assert event_record.data.balance_proof == event.balance_proof storage.close()
def from_dict(cls, data: Dict[str, Any]) -> "ReceiveLockExpired": return cls( balance_proof=data["balance_proof"], secrethash=SecretHash(deserialize_bytes(data["secrethash"])), message_identifier=MessageID(int(data["message_identifier"])), )
def from_dict(cls, data: Dict[str, Any]) -> "ReceiveUnlock": return cls( message_identifier=MessageID(int(data["message_identifier"])), secret=deserialize_secret(data["secret"]), balance_proof=data["balance_proof"], )
def from_dict(cls, data: Dict[str, Any]) -> "ReceiveProcessed": return cls( sender=to_canonical_address(data["sender"]), message_identifier=MessageID(int(data["message_identifier"])), )