问题:如何迭代比特币私钥, 然后查询对应的地址有多少余额,最后将币转出
1: 迭代私钥:
私钥是一个有限集, 可以从一个1~2^256(其实是1.158 * 10^77)间选一个数,来生成一个私钥
这里借助pycoin这个库来生成, 因为私钥有不止一种编码方式,所以1个数字可以得到多对公私钥(查看《mastering bitcoin》第70页的Table 4-2)
from pycoin.key.Key import Key
def get_bitcoin_key_pair(i):
k = Key(num)
addr, priv = k.address(), k.wif()
addr2, priv2 = k.address(use_uncompressed=True), k.wif(use_uncompressed=True)
return [{
'privkey': priv,
'address': addr
}, {
'privkey': priv2,
'address': addr2
}]
2: 查询余额:
这里可以用bitcoin+electrumx来实现(都用supervisor来拉起), 因为单单bitcoin节点并没有提供查任意地址余额的接口,electrumx有
安装supervisor
pip3 install supervisor
echo_supervisord_conf > ~/conf/supervisord.conf
root@debian:~# cat >> ~/conf/supervisord.conf << EOF
> [include]
> files = *.ini
> EOF
supervisord -c ~/conf/supervisord.conf
安装bitcoin
为了不浪费生命,直接下载bitcoin的可执行二进制包
# ~/conf/bitcoind.ini
[program:bitcoind]
command=/root/bitcoin-0.16.0/bin/bitcoind -rpcuser=YOUR_RPC_USER -rpcpassword=YOUR_RPC_PASSWD
process_name=bitcoind
numprocs=1
autostart=yes
autorestart=true
redirect_stderr=true
stdout_logfile=/root/.bitcoin/error.log
并用supervisor将bitcoin拉起
supervisorctl reread
supervisorctl update bitcoind
然后是electrumx: 下载地址
# ~/conf/electrumx.ini
[program:electrumx]
command=/root/electrumx/electrumx_server.py
directory=/root/electrumx
environment=DB_DIRECTORY="/root/.electrumx",DAEMON_URL="http://YOUR_RPC_USER:YOUR_RPC_PASSWD@127.0.0.1:8332/",COIN="BitcoinSegwit",ALLOW_ROOT="1",HOST="0.0.0.0",TCP_PORT="50001"
process_name=electrumx
numprocs=1
autostart=yes
autorestart=true
redirect_stderr=true
stdout_logfile=/root/.electrumx/log.log
并用supervisor将electrumx拉起
supervisorctl reread
supervisorctl update electrumx
electrumx同步好所有区块之后,才会提供出rpc接口
然后掉electrumx的查bitcoin地址余额的接口
import asyncio
class Bitcoin:
def __init__(self, loop):
self.loop = loop
self.leveldb_host = '127.0.0.1'
self.electrumx_port = 50001
async def get_bitcoin_balance(self, addr):
reader, writer = await asyncio.open_connection(self.electrumx_host, self.electrumx_port, loop=self.loop)
params = {
'jsonrpc': '2.0',
'method': 'blockchain.address.get_balance',
'params': [addr],
'id': addr
}
writer.write(json.dumps(params).encode()+b'\n')
logger.info('data send')
data = await reader.read(1024)
writer.close()
logger.error('bitcoin_balace: {}'.format(json.loads(data)))
data = json.loads(data)
res = {
'confirmed': data['result']['confirmed'],
'unconfirmed': data['result']['unconfirmed']
}
return res
async def test(self):
await self.get_bitcoin_balance('17eLjNhftbJd826mc1Pdz62Ni2G7MZYi3Q')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
bitcoin = Bitcoin(loop)
loop.run_until_complete(bitcoin.test())
loop.close()
3: 将币转到自己的账号
代码实现待实现 (可先将第二步的私钥记录到文件,导入到钱包转账)
总的代码: https://github.com/ligulfzhou/how-to-scrapy-bitcoin/blob/master/scrap_bitcoins.py
网友评论