Bitcoin and BlockChain are too popular to ignored by technical people. Hence I also spend some hours to read some books, and do some coding. This blog explains basic steps to create bitcoin address.
Step 1: Generate private key (256 bit, 64 bytes)
import binascii as ba import ecdsa import hashlib import random def create_priv_key(): digits = ['%x' % random.randrange(16) for _ in range(64)] return''.join(digits)
priv_key = create_priv_key() print('1. Private key:%s' % priv_key)
Step 2: Generate public key
def build_pub_key(priv_key): buff = bytes.fromhex(priv_key) sk = ecdsa.SigningKey.from_string(buff, curve=ecdsa.SECP256k1) pub_key = b'\x04' + sk.verifying_key.to_string() return ba.b2a_hex(pub_key).decode()
pub_key = build_pub_key(priv_key) print('2. Public key:%s' % pub_key)
Step 3: Calculate sha-256
def sha256(key): sha = hashlib.sha256(bytes.fromhex(key)) return ba.hexlify(sha.digest()).decode()
r_3 = sha256(pub_key) print('3. Public key sha-256:%s' % r_3)
Step 4: Calculate ripedm160
def ripemd160(key): rm = hashlib.new('ripemd160') rm.update(bytes.fromhex(key)) return ba.hexlify(rm.digest()).decode()
r_4 = ripemd160(r_3) print('4. Calculate Step 3 ripemd-160:%s' % r_4)
Step 5: Prefix address with protocol version
r_5 = '00' + r_4 print('5. Prefix Bitcoin protocol version :%s' % r_5)
Step 6: Calculate sha-256 twice
r_6 = sha256(sha256(r_5)) print('6. Calculate Step 5 with sha-256 twice:%s' % r_6)
Step 7: Validation
r_7 = r_5 + r_6[:8] print('7. Append output last step into Step 5 for validation:%s' % r_7)
Step 8: Encode with base58
addr = base58.b58encode(bytes.fromhex(r_7))
print(‘8. Wallet address: %s’ % addr)