Commit 586563cc authored by kenshin-samourai's avatar kenshin-samourai
Browse files

delete python scripts from /contrib

parent bd52eae7
#!/usr/bin/env python3
import hashlib
import sys
import argparse
from pycoin.coins.bitcoin.networks import BitcoinTestnet, BitcoinMainnet
import client
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--testnet', action='store_true')
parser.add_argument('address', nargs='+')
args = parser.parse_args()
if args.testnet:
Network = BitcoinTestnet
port = 60001
else:
Network = BitcoinMainnet
port = 50001
conn = client.Client(('localhost', port))
for addr in args.address:
script = Network.ui.script_for_address(addr)
script_hash = hashlib.sha256(script).digest()[::-1].hex()
reply = conn.call('blockchain.scripthash.get_balance', script_hash)
result = reply['result']
print('{} has {} satoshis'.format(addr, result))
if __name__ == '__main__':
main()
import json
import socket
class Client:
def __init__(self, addr):
self.s = socket.create_connection(addr)
self.f = self.s.makefile('r')
self.id = 0
def call(self, method, *args):
req = {
'id': self.id,
'method': method,
'params': list(args),
}
msg = json.dumps(req) + '\n'
self.s.sendall(msg.encode('ascii'))
return json.loads(self.f.readline())
import binascii
import json
import os
import socket
class Daemon:
def __init__(self, port, cookie_dir):
self.sock = socket.create_connection(('localhost', port))
self.fd = self.sock.makefile()
path = os.path.join(os.path.expanduser(cookie_dir), '.cookie')
cookie = binascii.b2a_base64(open(path, 'rb').read())
self.cookie = cookie.decode('ascii').strip()
self.index = 0
def request(self, method, params_list):
obj = [{"method": method, "params": params, "id": self.index}
for params in params_list]
request = json.dumps(obj)
msg = ('POST / HTTP/1.1\n'
'Authorization: Basic {}\n'
'Content-Length: {}\n\n'
'{}'.format(self.cookie, len(request), request))
self.sock.sendall(msg.encode('ascii'))
status = self.fd.readline().strip()
while True:
if self.fd.readline().strip():
continue # skip headers
else:
break # next line will contain the response
data = self.fd.readline().strip()
replies = json.loads(data)
for reply in replies:
assert reply['error'] is None, reply
assert reply['id'] == self.index
self.index += 1
return [d['result'] for d in replies]
#!/usr/bin/env python3
import argparse
from daemon import Daemon
import numpy as np
import matplotlib.pyplot as plt
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--testnet', action='store_true')
args = parser.parse_args()
if args.testnet:
d = Daemon(port=18332, cookie_dir='~/.bitcoin/testnet3')
else:
d = Daemon(port=8332, cookie_dir='~/.bitcoin')
txids, = d.request('getrawmempool', [[False]])
txids = list(map(lambda a: [a], txids))
entries = d.request('getmempoolentry', txids)
entries = [{'fee': e['fee']*1e8, 'vsize': e['vsize']} for e in entries]
for e in entries:
e['rate'] = e['fee'] / e['vsize'] # sat/vbyte
entries.sort(key=lambda e: e['rate'], reverse=True)
vsize = np.array([e['vsize'] for e in entries]).cumsum()
rate = np.array([e['rate'] for e in entries])
plt.semilogy(vsize / 1e6, rate, '-')
plt.xlabel('Mempool size (MB)')
plt.ylabel('Fee rate (sat/vbyte)')
plt.title('{} transactions'.format(len(entries)))
plt.grid()
plt.show()
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import argparse
import daemon
def main():
parser = argparse.ArgumentParser()
parser.add_argument('txid')
args = parser.parse_args()
d = daemon.Daemon(port=8332, cookie_dir='~/.bitcoin')
txid = args.txid
txn, = d.request('getrawtransaction', [[txid, True]])
vin = txn['vin']
fee = 0.0
for txi in txn['vin']:
prev_txid = txi['txid']
prev_tx, = d.request('getrawtransaction', [[prev_txid, True]])
index = txi['vout']
prev_txo = prev_tx['vout'][index]
print(f"{prev_txid}:{index:<5} {prev_txo['value']:+20.8f}")
fee += prev_txo['value']
for i, txo in enumerate(txn['vout']):
print(f"{txid}:{i:<5} {-txo['value']:+20.8f}")
fee -= txo['value']
print(f"Fee = {1e6 * fee:.2f} uBTC = {1e8 * fee / txn['vsize']:.2f} sat/vB")
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import hashlib
import sys
from logbook import Logger, StreamHandler
from pycoin.coins.bitcoin.networks import BitcoinMainnet
import pycoin.ui.key_from_text
import pycoin.key
import client
script_for_address = BitcoinMainnet.ui.script_for_address
log = Logger(__name__)
def main():
conn = client.Client(('localhost', 50001))
xpub, = sys.argv[1:]
total = 0
k = pycoin.ui.key_from_text.key_from_text(xpub)
for change in (0, 1):
empty = 0
for n in range(100):
address = k.subkey(change).subkey(n).address()
script = script_for_address(address)
script_hash = hashlib.sha256(script).digest()[::-1].hex()
log.debug('{}', conn.call('blockchain.scripthash.get_history',
script_hash))
reply = conn.call('blockchain.scripthash.get_balance', script_hash)
result = reply['result']
confirmed = result['confirmed'] / 1e8
total += confirmed
if confirmed:
log.info('{}/{} => {} has {:11.8f} BTC',
change, n, address, confirmed)
empty = 0
else:
empty += 1
if empty >= 10:
break
log.info('total balance: {} BTC', total)
if __name__ == '__main__':
with StreamHandler(sys.stderr, level='INFO').applicationbound():
main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment