To spend it, you'll basically have to do the same as your previous transaction, but for SegWit:
01000000 < Version 1
00 < SegWit marker
01 < SegWit flag
01 < amount of input(s)
f052c63f7cc387e85f96c99dc108f53289943f03d3814e0ff5e8f54f8e22d29e < input0 txid
00000000 < input0 index
00 < script length (0 for p2wpkh)
ffffffff < input0 nSequence
01 < amount of output(s)
60EA000000000000 < output0 amount
19 76a914b77e875983ee5851006ec5bd461208ebd11ea1bf88ac < output0 Size scriptPubkey
-------------------------------------------Witness for input 0--------------------------------------------
02 < Number of Stack Items
01 51 < Stack item 0 (Size OP_PUSHNUM_1)
02 7551 < Stack item 1 (Size OP_Drop 1 OP_PUSHNUM_1)
-------------------------------------------Witness for input 0--------------------------------------------
00000000 < nLocktime
Your previous transaction's scriptSig "0x0451027551" is used as Witness.
But in P2WPKH spend, the number of stack items must be indicated followed by those stack items with their respective sizes.
Transactions:
Spent by: blockstream.info/testnet/tx/1b291f7cf57e827f6e8d1225657264fcee9ad4a8248e769c2788a8196a2bda6b (the example above)
Funded by: blockstream.info/testnet/tx/9ed2228e4ff5e8f50f4e81d3033f948932f508c19dc9965fe887c37c3fc652f0
Excellent, many thanks! This really works.
Amended the code for public address generation, too (now produces the same results as Bitcoin Core):
def hex_to_hash160(hexdata):
return hashlib.new('ripemd', hashlib.sha256(bytes.fromhex(hexdata)).digest()).hexdigest()
def hex_to_sha256(hexdata):
return hashlib.sha256(bytes.fromhex(hexdata)).hexdigest()
the_script = "7551" #feel free to play around
#the_script = bitcoinutils.script.Script(["OP_DROP", "OP_1"]).to_hex() #same result but unnecessary library use
the_script_hash160 = hex_to_hash160(the_script)
the_script_sha256 = hex_to_sha256(the_script)
print('Testnet:')
print(base58.b58encode_check(bytes.fromhex('c4'+ the_script_hash160)).decode())
print(bitcoinutils.bech32.encode('tb', 0, bytes.fromhex(the_script_sha256)))
print()
print('Mainnet:')
print(base58.b58encode_check(bytes.fromhex('05'+ the_script_hash160)).decode())
print(bitcoinutils.bech32.encode('bc', 0, bytes.fromhex(the_script_sha256)))
Testnet:
2NBgCqkaw8r7s15pamKLogvWurSTFVVf1Kf
tb1qxvvc4xl77e6whhdel7499y5qz7uywfu3u4xxp89etunc4343udys6xzc00
Mainnet:
3L7zn1euXPcWoJC36Biw4yXee6F5ksEYdb
bc1qxvvc4xl77e6whhdel7499y5qz7uywfu3u4xxp89etunc4343udysdw5h4q