Invalid p2sh transaction accepted by the network I have try to build a 2 of 2 p2sh transaction from scratch using the book &quot;programming bitcoin&quot; by Jimmy Song, we are not directly guided to make one of those so I had to modify some of the function we had to build in the book but I guess it must be working.
Here is my tx on testnet: https://www.blockchain.com/btc-testnet/tx/7eba40f4c00e3da529309011c6fd8066c97fd24adca60b0d024976c360bcdd8b
And here is my code: https://pastebin.com/1mCv73i2
using the functions of the book: https://github.com/jimmysong/programmingbitcoin
My question are:

Why did the transaction was accepted by the network despite not working as intended
Why did my input did not go to the desired p2sh address &quot;2N7e6ZAGXoepdVYu2Y8ho7fTf6oxE3j9UwS&quot;
It is on the testnet but if it was not can I retrieve my satoshis on this tx ?

edit: I found my error about my redeemscript and updated my code, but now I have a &quot;Code: -25, Error: bad-txns-inputs-missingorspent&quot; error when I want to broadcast it
here is my raw transaction, and I have updated the pastebin for the code:
https://pastebin.com/8sQBpnVY
Why did the transaction was accepted by the network despite not working as intended

The network does not check the validity of output scripts. An output script can contain pretty much any data and the transaction will still be consensus valid. But your transaction is not actually invalid. It's just like a bare multisig now, but since the pubkeys are hashes, it isn't.

Why did my input did not go to the desired p2sh address &quot;2N7e6ZAGXoepdVYu2Y8ho7fTf6oxE3j9UwS&quot;

You set the output script to dat_redeem_script_op rather than target_script. So the output script is actually your multisig script rather than the P2SH script you intended.

It is on the testnet but if it was not can I retrieve my satoshis on this tx ?

No. Even if you had done this correctly with P2SH, it would still be unspendable. This is because your &quot;public keys&quot; are actually public key hashes. However you do not use any opcodes to for public key hashing. OP_CHECKMULTISIG takes public keys so it will try to interpret your public key hashes as pubkeys and fail to do so.
If you had constructed the multisig script correctly with public keys, this would be spendable as a bare multisig. It would be spendable in the same way that a P2SH multisig is spendable except you do not provide the multisig script in the input's scriptSig.