Pycoin 库同时支持 Python2(2.7x)与 Python3,以及一些便于使用的命令行工具,比如 ku 和 tx。如果在 Python3 的虚拟环境下安装 pycoin0.42,请输入以下命令:
$ python3 -m venv /tmp/pycoin
$ . /tmp/pycoin/bin/activate
$ pip install pycoin==0.42 Downloading/unpacking pycoin==0.42
Downloading pycoin-0.42.tar.gz (66kB): 66kB downloaded Runningsetup.py(path:/tmp/pycoin/build/pycoin/setup.py)
egg_info for pack-age pycoin
Installing collected packages: pycoin Running setup.py install for pycoin
Installing tx script to /tmp/pycoin/bin Installing cache_tx script to /tmp/pycoin/bin Installing bu script to /tmp/pycoin/bin Installing fetch_unspent script to/tmp/pycoin/bin
Installing block script to /tmp/pycoin/bin Installing spend script to /tmp/pycoin/bin Installing ku script to /tmp/pycoin/bin Installing genwallet script to /tmp/pycoin/bin
Successfully installed pycoin Cleaning up...
$
这里有一个简单的 Python 脚本,通过 pycoin 库来交易比特币:
#!/usr/bin/env python
from pycoin.key import Key
from pycoin.key.validate import is_address_valid, is_wif_valid from pycoin.services import spendables_for_address
from pycoin.tx.tx_utils import create_signed_tx
def get_address(which): while 1:
print("enter the %s address=> " % which, end='') address = input()
is_valid = is_address_valid(address) if is_valid:
return address
print("invalid address, please try again")
src_address = get_address("source")
spendables = spendables_for_address(src_address) print(spendables)
while 1:
print("enter the WIF for %s=> " % src_address, end='') wif = input()
is_valid = is_wif_valid(wif) if is_valid:
break
print("invalid wif, please try again")
key = Key.from_text(wif)
ifsrc_addressnotin(key.address(use_uncompressed=False), key.address(use_un compressed=True)):
print("** WIF doesn't correspond to %s" % src_address) print("The secret exponent is %d" %key.secret_exponent())
dst_address = get_address("destination")
tx = create_signed_tx(spendables, payables=[dst_address], wifs=[wif])
print("here is the signed output transaction") print(tx.as_hex())