code: def handle_cancelpayment(
          payment_state: InitiatorPaymentState,
          channelidentifiers_to_channels: ChannelMap,
  ) -> TransitionResult[InitiatorPaymentState]:
      
      # Cannot cancel a transfer after the secret is revealed
      events = list()
      for initiator_state in payment_state.initiator_transfers.values():
          channel_identifier = initiator_state.channel_identifier
          channel_state = channelidentifiers_to_channels.get(channel_identifier)
  
          if not channel_state:
              continue
  
          if can_cancel(initiator_state):
              transfer_description = initiator_state.transfer_description
              cancel_events = cancel_current_route(payment_state, initiator_state)
  
              initiator_state.transfer_state = 'transfer_cancelled'
  
              cancel = EventPaymentSentFailed(
                  payment_network_identifier=channel_state.payment_network_identifier,
                  token_network_identifier=TokenNetworkID(channel_state.token_network_identifier),
                  identifier=transfer_description.payment_identifier,
                  target=transfer_description.target,
                  reason='user canceled payment',
              )
              cancel_events.append(cancel)
  
              events.extend(cancel_events)
  
      return TransitionResult(payment_state, events)
docs: Cancel the payment and all related transfers.