Create P2SH transaction 1-1 – Bitcoin Stack Exchange

I am trying to create a transaction P2SH 1-1 in testnet.
I get an address from (2MsMajWUMmW7BTw6Lw4L3qvZ6rcHgGHHas4)

Then I create the transaction with output script as follows:


Where $ PUBLIC_KEY is not compressed. (I even tried compressed) 51410487c7d95b6334ad37dfb6d423313c580476035d680ec86be444c3c52da95615e15cd044d7d1332e02c33b80fc8e6d6cc94b6f9d618419956fcbbedfc25c16b7e151AE

I used SHA256 and ripemd160 and get the redemption script


Add it to the transaction.
And I get this transaction data.


And I can see this vout:

"vout": (
      "value": 49.999,
      "n": 0,
      "scriptPubKey": {
        "asm": "OP_HASH160 5a3f197d7f9cacc2794120eb169ee3beafa677b1 OP_EQUAL",
        "hex": "a9145a3f197d7f9cacc2794120eb169ee3beafa677b187",
        "reqSigs": 1,
        "type": "scripthash",
        "addresses": (

But the address I can see in vout (2N1UQPnQpHgoLGFZhdCFjZjc8h6MMcWFzan) is different from mine (2MsMajWUMmW7BTw6Lw4L3qvZ6rcHgGHHas4)

Transactions – Redeem P2sh script hash

1. Bitcoin Single Signature P2SH:

Redeem template = “(PubKey) OP_CHECKSIG”

Working Examples:

% echo "(020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) checksig" | bx script-encode

21020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73ac (Script)

% echo "(020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) checksig" | bx script-encode | bx sha256 | bx ripemd160

49e266a68641d2caa6696b00696f00f0a5706350 (Hash answer)

% echo "(020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) checksig" | bx script-encode | bx sha256 | bx ripemd160 | bx base58check-encode -v 5

38RgUAR367PFbFFgS57BYcERHkpqHEMBvA (Address)

or simpler,

% echo "(020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) checksig" | bx script-to-address -v 5


2.Bitcoin BIP16 Multisig:

2 of 3 RedeemScript template OP_2 (PubKey1) (PubKey2) (PubKey3) OP_3 OP_CHECKMULTISIG

Working Examples:

% echo "2 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) (03664d528eb80096671ef9011c533ceb5df133238e3690d88f2960c786398b86b1) (029a449ea4a2155ea10002d704604bb3e8606631d35af20889a74b82b2dab572f6) 3 checkmultisig" | bx script-encode

5221020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d732103664d528eb80096671ef9011c533ceb5df133238e3690d88f2960c786398b86b1290a82960b6b6b6b6b6a70b6a6b (Script)

% echo "2 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) (03664d528eb80096671ef9011c533ceb5df133238e3690d88f2960c786398b86b1) (029a449ea4a2155ea10002d704604bb3e8606631d35af20889a74b82b2dab572f6) 3 checkmultisig" | bx script-encode | bx bitcoin160

7e580c3a86432d96dd60784e99f5a94e463414fe (Hash answer)

% echo "2 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73) (03664d528eb80096671ef9011c533ceb5df133238e3690d88f2960c786398b86b1) (029a449ea4a2155ea10002d704604bb3e8606631d35af20889a74b82b2dab572f6) 3 checkmultisig" | bx script-to-address -v 5

3DD4YP2T75TQtf84KrHzYVLYgNAeaHWqxq (Address)

3. Bitcoin P2WPKH nested in P2SH:

Redeem template = "0 (PubKey)"

Working Examples:

% echo "0 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73)" | bx script-encode

0021020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73 (Script)

% echo "0 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73)" | bx script-encode | bx bitcoin160

7138cbb443e9ed635d3dd02a3e450884e3f9f0c8 (Hash answer)

% echo "0 (020ae29f86f404e4b302cfa17ff15d93149af6a54c80a4172d47e41f55f6a78d73)" | bx script-to-address -v 5

3C1gKTRSAwSLj8Ft1eYooLkWxwJ5cqDdpb (Address)

output p2sh with bitcoinj

I am trying to issue the coins for a p2sh

First I generate p2sh and send coins to this p2sh

ECKey clientKey = new ECKey();
ECKey serverKey = new ECKey();
ECKey thirdPartyKey = new ECKey();
List keys = ImmutableList.of(clientKey, serverKey,thirdPartyKey);
Script multisigScript = ScriptBuilder.createP2SHOutputScript(2, keys);
String address = multisigScript.getToAddress(params).toString();

then i send coins to the "address" of testnet3

secondly i use the wallet in bitcoinj to see the "address" and get the tx

WalletAppKit walletAppKit = new WalletAppKit(params, new File("./btcWallet"), "test");
Wallet walletTemp = walletAppKit.wallet();
Address watchAddress = Address.fromString(params, "2NGY4n3Wc2iftWufhUg2MzZtccbkQWgdUiz");
 Set transSet = walletTemp.getTransactions(false);

third, after receiving the tx and the output, i want to output it

TransactionOutput out = ...//output that the second step i get from the tx
Script scriptOut = out.getScriptPubKey()
Coin outValue = Coin.valueOf(10000);
Script redeemScript = ScriptBuilder.createRedeemScript(2, keys);
Address sendAddress = LegacyAddress.fromBase58(params, "2N6846hvswyZEdJ5DuEcjQZPaT5Xwb6PdGT");
Transaction spendTx = new Transaction(params);
spendTx.addOutput(outValue, sendAddress);
TransactionInput input = spendTx.addInput(out);

Sha256Hash sighash = spendTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL,
ECKey.ECDSASignature cSignature = clientKey.sign(sighash);
ECKey.ECDSASignature sSignature = serverKey.sign(sighash);
TransactionSignature cTransactionSignature = new TransactionSignature(cSignature, Transaction.SigHash.ALL,
TransactionSignature sTransactionSignature = new TransactionSignature(sSignature, Transaction.SigHash.ALL,

Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(cTransactionSignature, sTransactionSignature), scriptOut);

it has an error with "input.verify (out)",Script resulted in a non-true stack: () (3044022043d0cdddb087c4db2937a3b656c37bf240fd95e16714125c0672875bb18b4c1902200f96e1ec0adc2258e324cbacba598cb72d502a4e3185212dea40c50b365d3fb901) ()

I don't know where my code is wrong and how to solve it.

Find a similar problem, but not the same problem (1): Error creating / sending multisig transactions

p2sh – How are nonstandard transactions created, sent and dismounted?

Normally, non-standard transactions are denied by P2P nodes (but they can be mined directly by miners, as this is only a policy rule).

P2SH addresses will not post the hashed script until they are used for the first time. So you can send BTC to any script (valid or not) that uses P2SH addresses. P2SH input scripts are not imposed by default rules. All you have to do is follow the protocol rules (size, use of activated opcodes, etc.).

To create your own scripts, you can use this question as a starting point.

Development – non-Segway P2SH byte structure

I'm working on a bitcoin block explorer in golangin which I want to gather as much information about transactions as possible.
I can extract addresses from all kinds of addresses outputand mostly any kind of entranceunless I try to find it clear P2SH Documentation.
BIP16 does not say much about non-SegWit P2SH Byte structure. I have read many examples where OP_0 is the first byte as opposed to P2WPKH in P2SH and P2WSH in P2SH where the first field is scriptSigTotal length followed by 0x0/OP_0,
As far as I know, a non-Segway P2PH The address is obtained by hashing the redemption script, but I need something to anchor to, such as the 1st byte OP_0, then comes the size of the data (probably a signature), loop to find OP_TRUE followed by OP_PUSHDATA1?
But is this the unique standard format?

Multiple Signature – Is it possible to extract the original P2MS script from the transaction locked with the P2SH address?

This is a stupid question, because if the P2SH contains the hash160 (and the hash160 contains the sha256), the P2MS can not return to the original hex P2MS.

But to verify the P2SH, I have to insert the real Redmee script into the scriptSig. So, when I analyze the scriptSing, can I find the N-signature and the M "public key" in the script P2MS, right?

For example, in a scientific article, this address is cataloged as a fraudulent address, but this address is a script address. So it could be like this:

  • a P2MS script with M "public keys"
  • a script without the "public key"

But I can access the scriptSig and parse the hexadecimal, I should find the original script, right?

Bitcoin Core – How do I sign a multisig P2SH transaction in Python?

How do I sign a Multisig? P2SH Transaction in Python? I use the Python API that comes with the Bitcoin source code in the directory bitcoin/test/functional, I use regtest,

Finally, I want to create a transaction with a complicated lock script that contains conditions, multiple signals, and timeouts. If I understand correctly, I can not call signrawtransactionwithxxx() to sign such a transaction. I have to create and assign the signature manually, I can not get it to work. I think there is a problem in specifying the output quantity.

I'm creating a transaction with a simple lock script that requires two signatures:

redeemScript = CScript((coinbase_pubkey0, OP_CHECKSIGVERIFY, coinbase_pubkey1, OP_CHECKSIG))

I sign it manually:

(sighash, err) = SignatureHash(redeemScript, tx2, 0, SIGHASH_ALL)
sig0 = coinbase_key0.sign_ecdsa(sighash) + bytes(bytearray((SIGHASH_ALL)))
sig1 = coinbase_key1.sign_ecdsa(sighash) + bytes(bytearray((SIGHASH_ALL))) = CScript((sig1, sig0, redeemScript))

Everything works as I expect. I can send the transaction and later receive the output as input to a new transaction and issue it from there.

Now I change the lock script and turn it into a vanilla multisig:

redeemScript = CScript((OP_2, pub1_hex(0), pub1_hex(1), pub1_hex(2), OP_3, OP_CHECKMULTISIG))

I change the signature accordingly: = CScript((OP_0, sig0, sig1, redeemScript))

Now if I call sendrawtransaction()fails with the following error message:

test_framework.authproxy.JSONRPCException: mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation) (code 16) (-26)

I understand that this error can occur when you try to sign a multisig transaction without specifying the amount. This makes sense for me when signing a multisig transaction signrawtransactionwithkey()I have to hand over details of the issue, including the amount.

How do I sign a multisig transaction without calling? signrawtransactionwithkey()?

Here is the full code of my unit test:

#!/usr/bin/env python3

import pprint

from test_framework.test_framework import BitcoinTestFramework
from test_framework.messages import CTransaction, CTxIn, CTxOut, COutPoint, ToHex, COIN, sha256
from test_framework.script import CScript, CScriptOp, OP_1, OP_DROP, OP_2, OP_3, OP_HASH160, OP_EQUAL, hash160, OP_TRUE, OP_DUP, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKMULTISIG, OP_CHECKSIGVERIFY, SignatureHash, SIGHASH_ALL, OP_0
from test_framework.util import hex_str_to_bytes, bytes_to_hex_str
from test_framework.address import byte_to_base58
from test_framework.key import ECKey

class RawTxTest(BitcoinTestFramework):

    def set_test_params(self):
        self.num_nodes = 2
        self.extra_args = ((),("-txindex"))

    def run_test(self):
        """Implement a P2SH transaction with OP_CHECKSIG without using signrawtransactionwithkey()""""n    DEBUG START")

        # initialize node variables
        n0 = self.nodes(0) # This node used for initial balance
        n1 = self.nodes(1) # All test wallets created on this node

        # TRANSACTION #0 - pay from node 0 to addr0
        w0 = n1.createwallet(wallet_name="wallet0")
        w0_rpc = n1.get_wallet_rpc('wallet0')
        addr0 = w0_rpc.getnewaddress()"n    DEBUG addr0={addr0}")

        txid0 = n0.sendtoaddress(addr0, 10.0)

        # dump the tx to the log
        raw_tx0 = w0_rpc.getrawtransaction(txid0, True)
        s = pprint.pformat(raw_tx0)"n    DEBUG tx0={s}")

        # write the balance to the log
        bal0 = w0_rpc.getbalance()"n    DEBUG bal0={bal0:f}")

        # TRANSACTION #1 - Pay from addr0 to P2SH
        coinbase_key0 = ECKey()
        coinbase_pubkey0 = coinbase_key0.get_pubkey().get_bytes()
        coinbase_key1 = ECKey()
        coinbase_pubkey1 = coinbase_key1.get_pubkey().get_bytes()
        redeemScript = CScript((coinbase_pubkey0, OP_CHECKSIGVERIFY, coinbase_pubkey1, OP_CHECKSIG))
        #redeemScript = CScript((OP_2, pub1_hex(0), pub1_hex(1), pub1_hex(2), OP_3, OP_CHECKMULTISIG))
        redeemScriptHex = redeemScript.hex()"n    DEBUG redeemScriptHex={redeemScriptHex}")
        redeemScript160 = hash160(redeemScript)
        madd1 = byte_to_base58(redeemScript160, 196)"n    DEBUG madd1={madd1}")
        p2sh_script = CScript((OP_HASH160, redeemScript160, OP_EQUAL))

        tx1 = CTransaction()
        vout = (v("n") for v in raw_tx0("vout") if addr0 in v("scriptPubKey").get("addresses", ()))
        assert len(vout) == 1
        v = vout(0), 16), v)))
        a1 = w0_rpc.getaddressinfo(madd1)"n    DEBUG a1={a1}")
        scriptPubKey = a1("scriptPubKey")
        pubkey1 = hex_str_to_bytes(scriptPubKey)
        # Here I provide only the pubkey.  The tx contains "OP_HASH160 hash OP_EQUAL" which is automatically generated.
        #tx1.vout.append(CTxOut(int(8 * COIN), pubkey1))
        # Here I provide the full P2SH script in the format OP_HASH160, redeemScript160, OP_EQUAL.
        tx1.vout.append(CTxOut(int(8 * COIN), p2sh_script))

        priv0 = w0_rpc.dumpprivkey(addr0)
        tx1 = w0_rpc.signrawtransactionwithkey(ToHex(tx1), (priv0))("hex")
        txid1 = n0.sendrawtransaction(tx1, True)

        # dump the tx to the log
        raw_tx1 = w0_rpc.getrawtransaction(txid1, True)
        s = pprint.pformat(raw_tx1)"n    DEBUG tx1={s}")

        # write the unspent tx to the log
        us1 = w0_rpc.listunspent()"n    DEBUG us1={us1}")

        # TRANSACTION #2 - Pay from P2SH to addr2
        addr2 = w0_rpc.getnewaddress()"n    DEBUG addr2={addr2}")
        a2 = w0_rpc.getaddressinfo(addr2)
        pubkey2 = hex_str_to_bytes(a2('pubkey'))
        p2pkh2 = CScript((OP_DUP, OP_HASH160, hash160(pubkey2), OP_EQUALVERIFY, OP_CHECKSIG))
        tx2 = CTransaction(), 16), 0)))
        tx2.vout.append(CTxOut(int(7 * COIN), p2pkh2))

        (sighash, err) = SignatureHash(redeemScript, tx2, 0, SIGHASH_ALL)
        sig0 = coinbase_key0.sign_ecdsa(sighash) + bytes(bytearray((SIGHASH_ALL)))
        sig1 = coinbase_key1.sign_ecdsa(sighash) + bytes(bytearray((SIGHASH_ALL))) = CScript((sig1, sig0, redeemScript)) = CScript((OP_0, sig0, sig1, redeemScript))
        s = pprint.pformat(e0)"n    DEBUG tx2={s}")
        txid2 = n0.sendrawtransaction(ToHex(tx2), True)

        # dump the tx to the log
        raw_tx2 = w0_rpc.getrawtransaction(txid2, True)
        s = pprint.pformat(raw_tx2)"n    DEBUG tx2={s}")

        # write the balance to the log
        bal2 = w0_rpc.getbalance()"n    DEBUG bal2={bal2:f}")"n    DEBUG END")

if __name__ == '__main__':

Explanation of the script P2SH, how is Bitcoin Core executed?

This question is a continuation of my post yesterday.

Today I have a question about P2SH execution, so this should be an example of the script

OP_0   OP_2   

or should the P2SH key be used this is (i think something in this script on the left to convert the hash160 within the P2SH key, right?)

OP_0   OP_2   

Well, if I understood it well, the simulation of the execution is divided into two phases

  1. The hash scriptSig is equal to the hash within the scirptPubKey


  1. The script sing is executed like the script multi-signature


My questions are:

  • With the P2SH key is the execution the same? if so, in which other form is the P2SH with the P2SH key?

I also read this post, but I do not believe it contains that answer.

Unfortunately, if my sample script is wrong, I'll have to make a correction

Bitcoin Core – Create P2SH address does not match the address stored on the RPC node

I have a private key and I'm trying to create a P2SH address on testnet how my node was created, but they are not identical. Please help me a bit, thank you.

Private key: c5964e19634e473e9c8fed3b149c4d44b6d62d62724035aad3eb911a1495ae27

P2SH Address of 1 Threshold and 1 Pubkey:

P2WPKH address: 2NGA8uGdnaQ21phNpVyV5uye5cbUtudxBWh || tb1qld2fzw9gj30wxjamsz73fug62das7cyq0em4mn

Address from the node: 2N8qKVKuR3QAy2cA5fF2QbuCpBGfGCmbUHx

Here's more detail from getaddressinfo:

    "result": {
        "address": "2N8qKVKuR3QAy2cA5fF2QbuCpBGfGCmbUHx",
        "scriptPubKey": "a914aafc9f09b99cbb1ba46001ec4868ba4fb32543ca87",
        "ismine": true,
        "solvable": true,
        "desc": "sh(wpkh((a1696bdc/0'/0'/375509')02a7065a210c28d27a591e55ac6be092111349fc4b23927bb4d13c46a683bcfff7))#hrgzj3gs",
        "iswatchonly": false,
        "isscript": true,
        "iswitness": false,
        "script": "witness_v0_keyhash",
        "hex": "00146da71bc5de0c0b59bbf73520df7e7d4048d02594",
        "pubkey": "02a7065a210c28d27a591e55ac6be092111349fc4b23927bb4d13c46a683bcfff7",
        "embedded": {
            "isscript": false,
            "iswitness": true,
            "witness_version": 0,
            "witness_program": "6da71bc5de0c0b59bbf73520df7e7d4048d02594",
            "pubkey": "02a7065a210c28d27a591e55ac6be092111349fc4b23927bb4d13c46a683bcfff7",
            "address": "tb1qdkn3h3w7ps94nwlhx5sd7lnagpydqfv5pyqurf",
            "scriptPubKey": "00146da71bc5de0c0b59bbf73520df7e7d4048d02594"
        "label": "test",
        "ischange": false,
        "timestamp": 1561438016,
        "hdkeypath": "m/0'/0'/375509'",
        "hdseedid": "e2e9dd17501f967b789c28c4be1dbf64897ad8d2",
        "hdmasterfingerprint": "a1696bdc",
        "labels": (
                "name": "test",
                "purpose": "receive"
    "error": null,
    "id": 1