0

I used the following script to generate my private key and the corresponding segwit address.

Then to test it, i sent funds to the address and imported the private key on blockchain wallet;

RESULT: No funds in private key, and the address displaied is not the segwit address but just another P2PKH address.

What is the problem?

import random,ecdsa,hashlib,base58
private_key=(random.getrandbits(256)).to_bytes(32,byteorder="little",signed=False)

signed_key=ecdsa.SigningKey.from_string(private_key,curve=ecdsa.SECP256k1)

verifying_key=signed_key.get_verifying_key()

x_cor=bytes.fromhex(verifying_key.to_string().hex())[:32]
y_cor=bytes.fromhex(verifying_key.to_string().hex())[32:]


if int.from_bytes(y_cor,byteorder="big",signed=True)%2==0:
    public_key = bytes.fromhex(f'02{x_cor.hex()}')

else:
    public_key = bytes.fromhex(f'03{x_cor.hex()}')


sha256_key = hashlib.sha256(public_key)
ripemd160_key = hashlib.new("ripemd160")
ripemd160_key.update(sha256_key.digest())

key_hash=ripemd160_key.digest()

P2WPKH_V0 = bytes.fromhex(f'0014{key_hash.hex()}')

sha256_P2WPKH_V0 = hashlib.sha256(public_key)
ripemd160_P2WPKH_V0 = hashlib.new("ripemd160")
ripemd160_P2WPKH_V0.update(sha256_P2WPKH_V0.digest())

script_hash=ripemd160_key.digest()


P2SH_P2WPKH_V0 = bytes.fromhex(f'a9{script_hash.hex()}87')

flagged_scripthash = bytes.fromhex(f'05{script_hash.hex()}')

checksum = hashlib.sha256(hashlib.sha256(flagged_scripthash).digest()).digest()[:4]
bin_addr = flagged_scripthash + checksum

nested_address = base58.b58encode(bin_addr)



compressed_private_key = private_key + '01'
wifcomp1 = bitcoin.encode_privkey(bitcoin.decode_privkey(private_key, 'hex'), \
             'wif_compressed')

print("Private key: "+ private_key.hex())
print("WIF key: "+ wifcomp1)
print("Nested Address: " + nested_address.decode())
  • This sounds like whatever wallet you are using does not know what address type to generate. You need to find whatever setting in that wallet to tell it that it should produce a bech32 address, or use a wallet that allows you to do that. – Andrew Chow Dec 1 at 22:08
  • Thank you for the answer, some advice? I'm using blockchain wallet – Riccardo Brugnolini Dec 1 at 22:49
  • Don't use blockchain.com! Use a decent desktop wallet such as Electrum: electrum.org – Coding Enthusiast Dec 3 at 6:10
  • If i import the private keys in electrum the result is the same.. – Riccardo Brugnolini Dec 3 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.