Quick and dirty code for your task. Hope it helps.
1) Let us create address from secret.
static void p2sh_create ( )
{
const MyByteArray secret ( QByteArray ( "My secret phrase" ) );
const MyKey32 sha256 ( secret.sha256 ( ) );
const MyByteArray redeemScript ( MyByteArray ( ).putInt8 ( OP_SHA256 ).putPush ( sha256 ).putInt8 ( OP_EQUAL ) );
const MyKey20 hash160 ( redeemScript.hash160 ( ) );
const QString address ( hash160.toStringP2SH ( ) );
qDebug ( ) << "secret =" << QString ( secret.toHex ( ) ) << "(in hex)";
qDebug ( ) << "sha256 =" << sha256.toStringRev ( );
qDebug ( ) << "redeemScript=" << QString ( redeemScript.toHex ( ) );
qDebug ( ) << "hash160 =" << QString ( hash160.toHex ( ) );
qDebug ( ) << "address =" << address;
}
The output is:
secret = "4d792073656372657420706872617365" (in hex)
sha256 = "73d83ecabab6ba96a47f03d0e21ffbdfeaab5d337b7e93a0cc2e85019190fb3f"
redeemScript= "a82073d83ecabab6ba96a47f03d0e21ffbdfeaab5d337b7e93a0cc2e85019190fb3f87"
hash160 = "fa3156d1e95111b0105fb538711bf8e19dadf1bd"
address = "2NG482PHrj6f41UoqUHYGVkUR39oB3UvWkE"
2) Now let us fund the address 2NG482PHrj6f41UoqUHYGVkUR39oB3UvWkE
. Follow the link https://testnet.coinfaucet.eu/en/ and ask for some test coins. Testnet faucet sent me 0.86978283 TBTC in transaction https://testnet.smartbit.com.au/tx/21c181c6052f6266ea6c936cf86111d6a2662a1f1e3251560b718fb8b1e6457d
3) Now create spending tx from this address.
static void p2sh_spend ( )
{
const MyByteArray secret ( QByteArray ( "My secret phrase" ) );
const MyKey32 sha256 ( secret.sha256 ( ) );
const MyByteArray redeemScript ( MyByteArray ( ).putInt8 ( OP_SHA256 ).putPush ( sha256 ).putInt8 ( OP_EQUAL ) );
const MyByteArray tx ( MyByteArray ( )
.putInt32 ( TX_VERSION )
.putInt8 ( 1 )
.putArray ( MyKey32::fromHex ( "21c181c6052f6266ea6c936cf86111d6a2662a1f1e3251560b718fb8b1e6457d" ) )
.putInt32 ( 1 )
.putPrefixed ( MyByteArray ( ).putPush ( secret ).putPush ( redeemScript ) )
.putInt32 ( TX_SEQUENCE )
.putInt8 ( 1 )
.putInt64 ( 86978283 - 200 )
.putPrefixed ( MyByteArray ( ).putInt8 ( OP_HASH160 ).putPush ( MyKey20::of ( "2N8cj6kf3RkPHzQSCG13bvq6iXXWWPuGurZ" ) ).putInt8 ( OP_EQUAL ) )
.putInt32 ( TX_LOCK ) );
const MyKey32 txid ( tx.sha256d ( ) );
qDebug ( ) << "tx =" << QString ( tx.toHex ( ) );
qDebug ( ) << "txid =" << txid.toString ( );
}
The output is:
tx = "01000000017d45e6b1b88f710b5651321e1f2a66a2d61161f86c936cea66622f05c681c1210100000035104d79207365637265742070687261736523a82073d83ecabab6ba96a47f03d0e21ffbdfeaab5d337b7e93a0cc2e85019190fb3f87ffffffff01232e2f050000000017a914a89aec4cd53e6d74215332459b7fea3ec4aca9758700000000"
txid = "75e0904ca3f8895c6f6af45f1c7f3d1f9dcee32814ca144852bce669a5ee4421"
4) Now push the tx to the network: https://testnet.smartbit.com.au/txs/pushtx
5) Voila! https://testnet.smartbit.com.au/tx/75e0904ca3f8895c6f6af45f1c7f3d1f9dcee32814ca144852bce669a5ee4421