As seen in the previous section, using multi-sig is easily done in code. However, before P2SH there was no way to ask someone to pay to a multi-sig scriptPubKey in a way that was as simple as just providing them with a regular BitcoinAddress.
Pay To Script Hash (or P2SH as it is often known), is an easy way to represent a scriptPubKey as a simple BitcoinScriptAddress, no matter how complicated it is in terms of it's underlying m-of-n signature set up.
Do you see the difference? This P2SH scriptPubKey represents the hash of the multi-sig script: redeemScript.Hash.ScriptPubKey
Since it is a hash, you can easily convert it to a base58 string BitcoinScriptAddress.
Such an address will still be understood by any existing client wallet, even if the wallet does not understand what “multi-sig” is.
In P2SH payments, we refer to the hash of the Redeem Script as the scriptPubKey.
Since anyone sending a payment to such an address only sees the Hash of the RedeemScript, and do not know the Redeem Script itself, they don’t even have to know that they are sending money to a multi sig of Alice/Bob/Satoshi.
Signing such a transaction is similar to what we have done before. The only difference is that you also have to provide the Redeem Script when you build the Coin for the TransactionBuilder.
Imagine that the multi-sig P2SH receives a coin in a transaction called received.
Warning: The payment is sent to redeemScript.Hash and not to redeemScript!
When any two owners out of the three that control the multi-sig address (Alice/Bob/Satoshi) then want to spend what they have received, instead of creating a Coin they will need to create a ScriptCoin.
The rest of the code concerning transaction generation and signing is exactly the same as in the previous section about native multi sig.
Key bob = new Key();
Key alice = new Key();
Key satoshi = new Key();
Script redeemScript =
PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, satoshi.PubKey });
//Console.WriteLine(redeemScript.Hash.ScriptPubKey);
Console.WriteLine(redeemScript.Hash.GetAddress(Network.Main)); // 3E6RvwLNfkH6PyX3bqoVGKzrx2AqSJFhjo
Script redeemScript =
PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, satoshi.PubKey });
////Console.WriteLine(redeemScript.Hash.ScriptPubKey);
//Console.WriteLine(redeemScript.Hash.GetAddress(Network.Main));
Transaction received = Transaction.Create(Network.Main)
//Pay to the script hash
received.Outputs.Add(Money.Coins(1.0m), redeemScript.Hash);
//Give the redeemScript to the coin for Transaction construction
//and signing
ScriptCoin coin = received.Outputs.AsCoins().First()
.ToScriptCoin(redeemScript);