Angular, Blockchain, Science とか

Angular, Blockchain, Science全般 の情報を主に書いていきます。

pybitcointools を使った鍵操作 Bitcoin

pybitcointoolsについては、

github.com

で見てください。ちなみにブテリンはEthereumの創業者です。

import pybitcointools as bitcoin # learn more: https://python.org/pypi/pybitcointools

# 秘密鍵を作成
valid_private_key = False
while not valid_private_key:
    private_key = bitcoin.random_key()
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    valid_private_key = 0 < decoded_private_key < bitcoin.N

# 秘密鍵を表示    
print "Private Key (hex) is: ", private_key
print "Private Key (decimal) is: ", decoded_private_key

# Wallet Import Format (Base58形式) での表示
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
print "Private Key (WIF) is: ", wif_encoded_private_key

compressd_private_key = private_key + '01'
print "Private Key Compressed (hex) is: ", compressd_private_key

# 圧縮 WIF
wif_compressed_private_key = bitcoin.encode_privkey(
    bitcoin.decode_privkey(compressd_private_key, 'hex'), 'wif')
print "Private Key (WIF-Compressed) is: ", wif_compressed_private_key

# 公開鍵を求める
public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
print "Public Key (hex) is: ", public_key

hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
print "Public Key (hex) is: ", hex_encoded_public_key

# 圧縮公開鍵
(public_key_x, public_key_y) = public_key
if(public_key_y % 2) == 0:
    compressed_prefix = '02'
else:
    compressed_prefix = '03'
hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
print "Compressed Public Key (hex) is: ", hex_compressed_public_key

# ビットコインアドレスの表示
print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(public_key)

# 圧縮ビットコインアドレスの表示
print "Compressed Bitcoin Address (Base58Check) is :", \
    bitcoin.pubkey_to_address(hex_compressed_public_key)