def sweep_our_ctx(
        *, chan: 'AbstractChannel',
        ctx: Transaction,
        actual_htlc_tx: Transaction=None, # if passed, return second stage htlcs
) -> Dict[str, SweepInfo]:

    """Handle the case where we force-close unilaterally with our latest ctx.

    We sweep:
        to_local: CSV delayed
        htlc success: CSV delay with anchors, no delay otherwise
        htlc timeout: CSV delay with anchors, CLTV locktime
        second-stage htlc transactions: CSV delay

    'to_local' can be swept even if this is a breach (by us),
    but HTLCs cannot (old HTLCs are no longer stored).

    Outputs with CSV/CLTV are redeemed by LNWatcher.
    """
    ctn = extract_ctn_from_tx_and_chan(ctx, chan)
    our_conf, their_conf = get_ordered_channel_configs(chan=chan, for_us=True)
    our_per_commitment_secret = get_per_commitment_secret_from_seed(
        our_conf.per_commitment_secret_seed, RevocationStore.START_INDEX - ctn)
    our_pcp = ecc.ECPrivkey(our_per_commitment_secret).get_public_key_bytes(compressed=True)
    our_delayed_bp_privkey = ecc.ECPrivkey(our_conf.delayed_basepoint.privkey)
    our_localdelayed_privkey = derive_privkey(our_delayed_bp_privkey.secret_scalar, our_pcp)
    our_localdelayed_privkey = ecc.ECPrivkey.from_secret_scalar(our_localdelayed_privkey)
    their_revocation_pubkey = derive_blinded_pubkey(their_conf.revocation_basepoint.pubkey, our_pcp)
    to_self_delay = their_conf.to_self_delay
    our_htlc_privkey = derive_privkey(secret=int.from_bytes(our_conf.htlc_basepoint.privkey, 'big'),
                                       per_commitment_point=our_pcp).to_bytes(32, 'big')
    our_localdelayed_pubkey = our_localdelayed_privkey.get_public_key_bytes(compressed=True)
    to_local_witness_script = make_commitment_output_to_local_witness_script(
        their_revocation_pubkey, to_self_delay, our_localdelayed_pubkey)
    to_local_address = redeem_script_to_address('p2wsh', to_local_witness_script)
    to_remote_address = None
    # test if this is our_ctx
    found_to_local = bool(ctx.get_output_idxs_from_address(to_local_address))
    if not chan.is_backup():
        assert chan.is_static_remotekey_enabled()
        their_payment_pubkey = their_conf.payment_basepoint.pubkey
        to_remote_address = make_commitment_output_to_remote_address(their_payment_pubkey, has_anchors=chan.has_anchors())
        found_to_remote = bool(ctx.get_output_idxs_from_address(to_remote_address))
    else:
        found_to_remote = False
    if not found_to_local and not found_to_remote:
        return {}
    #chan.logger.debug(f'(lnsweep) found our ctx: {to_local_address} {to_remote_address}')
    # other outputs are htlcs
    # if they are spent, we need to generate the script
    # so, second-stage htlc sweep should not be returned here
    txs = {}  # type: Dict[str, SweepInfo]

    # local anchor
    if actual_htlc_tx is None and chan.has_anchors():
        if txin := sweep_ctx_anchor(ctx=ctx, multisig_key=our_conf.multisig_key):
            txs[txin.prevout.to_str()] = SweepInfo(
                name='local_anchor',
                cltv_abs=None,
                txin=txin,
                txout=None,
                can_be_batched=True,
            )

    # to_local
    output_idxs = ctx.get_output_idxs_from_address(to_local_address)
    if actual_htlc_tx is None and output_idxs:
        output_idx = output_idxs.pop()
        if txin := sweep_ctx_to_local(
                ctx=ctx,
                output_idx=output_idx,
                witness_script=to_local_witness_script,
                privkey=our_localdelayed_privkey.get_secret_bytes(),
                is_revocation=False,
                to_self_delay=to_self_delay,
        ):
            prevout = ctx.txid() + ':%d'%output_idx
            txs[prevout] = SweepInfo(
                name='our_ctx_to_local',
                cltv_abs=None,
                txin=txin,
                txout=None,
                can_be_batched=True,
            )
    we_breached = ctn < chan.get_oldest_unrevoked_ctn(LOCAL)
    if we_breached:
        chan.logger.info(f"(lnsweep) we breached. txid: {ctx.txid()}")
        # return only our_ctx_to_local, because we don't keep htlc_signatures for old states
        return txs

    # HTLCs
    def txs_htlc(
            *, htlc: 'UpdateAddHtlc',
            htlc_direction: Direction,
            ctx_output_idx: int,
            htlc_relative_idx,
            preimage: Optional[bytes]):

        htlctx_witness_script, htlc_tx = tx_our_ctx_htlctx(
            chan=chan,
            our_pcp=our_pcp,
            ctx=ctx,
            htlc=htlc,
            local_htlc_privkey=our_htlc_privkey,
            preimage=preimage,
            htlc_direction=htlc_direction,
            ctx_output_idx=ctx_output_idx,
            htlc_relative_idx=htlc_relative_idx)

        if actual_htlc_tx is None:
            name = 'offered-htlc' if htlc_direction == SENT else 'received-htlc'
            prevout = ctx.txid() + f':{ctx_output_idx}'
            txs[prevout] = SweepInfo(
                name=name,
                cltv_abs=htlc_tx.locktime,
                txin=htlc_tx.inputs()[0],
                txout=htlc_tx.outputs()[0],
                can_be_batched=False,  # both parties can spend
                # - actually, we might want to batch depending on the context
                #   f(amount in htlc, remaining_time, number of available utxos for anchors)
                #   - in particular, it would be safe to batch htlcs where
                #        htlc_direction, htlc.payment_hash, htlc.cltv_abs
                #     all match. That is, MPP htlcs for the same payment.
            )
        else:
            # second-stage
            address = bitcoin.script_to_p2wsh(htlctx_witness_script)
            output_idxs = actual_htlc_tx.get_output_idxs_from_address(address)
            for output_idx in output_idxs:
                if sweep_txin := sweep_htlctx_output(
                        to_self_delay=to_self_delay,
                        htlc_tx=actual_htlc_tx,
                        output_idx=output_idx,
                        htlctx_witness_script=htlctx_witness_script,
                        privkey=our_localdelayed_privkey.get_secret_bytes(),
                        is_revocation=False,
                ):
                    txs[actual_htlc_tx.txid() + f':{output_idx}'] = SweepInfo(
                        name=f'second-stage-htlc:{output_idx}',
                        cltv_abs=0,
                        txin=sweep_txin,
                        txout=None,
                        # this is safe to batch, we are the only ones who can spend
                        # (assuming we did not broadcast a revoked state)
                        can_be_batched=True,
                    )

    # offered HTLCs, in our ctx --> "timeout"
    # received HTLCs, in our ctx --> "success"
    htlc_to_ctx_output_idx_map = map_htlcs_to_ctx_output_idxs(
        chan=chan,
        ctx=ctx,
        pcp=our_pcp,
        subject=LOCAL,
        ctn=ctn)
    for (direction, htlc), (ctx_output_idx, htlc_relative_idx) in htlc_to_ctx_output_idx_map.items():
        if direction == RECEIVED:
            if not chan.lnworker.is_accepted_mpp(htlc.payment_hash):
                # do not redeem this, it might publish the preimage of an incomplete MPP
                continue
            preimage = chan.lnworker.get_preimage(htlc.payment_hash)
            if not preimage:
                # we might not have the preimage if this is a hold invoice
                continue
        else:
            preimage = None
        try:
            txs_htlc(
                htlc=htlc,
                htlc_direction=direction,
                ctx_output_idx=ctx_output_idx,
                htlc_relative_idx=htlc_relative_idx,
                preimage=preimage)
        except UneconomicFee:
            continue
    return txs
Handle the case where we force-close unilaterally with our latest ctx.

    We sweep:
        to_local: CSV delayed
        htlc success: CSV delay with anchors, no delay otherwise
        htlc timeout: CSV delay with anchors, CLTV locktime
        second-stage htlc transactions: CSV delay

    'to_local' can be swept even if this is a breach (by us),
    but HTLCs cannot (old HTLCs are no longer stored).

    Outputs with CSV/CLTV are redeemed by LNWatcher.
    
electrum/lnsweep.py