STM32 blackout while flash writing
Try to perform mass erase. Use registers instead of this silly library

The comments about the dangers of the runtime FLASH programming are wrong. There is no other way of FLASH programming and even when you program the chip using your favourite debug probe (it does not matter SWD  or JTAG) the software (in most cases ooenOCD or gdbserver load small program to the RAM which programs the FLASH. There are no hardware mechanisms of STM32 FLASH writing.