Browse Source

Add a script for computing tx fee

master
Roman Zeyde 5 years ago
parent
commit
b33b570704
No known key found for this signature in database GPG Key ID: 87CAE5FA46917CBB
  1. 2
      contrib/addr.py
  2. 2
      contrib/client.py
  3. 41
      contrib/daemon.py
  4. 42
      contrib/mempool.py
  5. 33
      contrib/tx_fee.py
  6. 2
      contrib/xpub.py

2
contrib/addr.py

@ -20,7 +20,7 @@ def main():
Network = BitcoinMainnet Network = BitcoinMainnet
port = 50001 port = 50001
conn = client.Connection(('localhost', port)) conn = client.Client(('localhost', port))
for addr in args.address: for addr in args.address:
script = Network.ui.script_for_address(addr) script = Network.ui.script_for_address(addr)
script_hash = hashlib.sha256(script).digest()[::-1].hex() script_hash = hashlib.sha256(script).digest()[::-1].hex()

2
contrib/client.py

@ -1,7 +1,7 @@
import json import json
import socket import socket
class Connection: class Client:
def __init__(self, addr): def __init__(self, addr):
self.s = socket.create_connection(addr) self.s = socket.create_connection(addr)
self.f = self.s.makefile('r') self.f = self.s.makefile('r')

41
contrib/daemon.py

@ -0,0 +1,41 @@
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]

42
contrib/mempool.py

@ -1,49 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import argparse import argparse
import binascii from daemon import Daemon
import json
import os
import socket
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
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
assert reply['id'] == self.index
self.index += 1
return [d['result'] for d in replies]
def main(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()

33
contrib/tx_fee.py

@ -0,0 +1,33 @@
#!/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()

2
contrib/xpub.py

@ -15,7 +15,7 @@ script_for_address = BitcoinMainnet.ui.script_for_address
log = Logger(__name__) log = Logger(__name__)
def main(): def main():
conn = client.Connection(('localhost', 50001)) conn = client.Client(('localhost', 50001))
xpub, = sys.argv[1:] xpub, = sys.argv[1:]
total = 0 total = 0
k = pycoin.ui.key_from_text.key_from_text(xpub) k = pycoin.ui.key_from_text.key_from_text(xpub)

Loading…
Cancel
Save