commit 66f224eab4e2ff4bf630db9cc1355c5b446ae934
parent 33b41f22fef4c46ec92a139f97b7a962225a2b5c
Author: ThomasV <thomasv@gitorious>
Date: Sun, 6 Oct 2013 12:28:45 +0200
update a few scripts
Diffstat:
10 files changed, 66 insertions(+), 119 deletions(-)
diff --git a/electrum b/electrum
@@ -120,6 +120,7 @@ if __name__ == '__main__':
options, args = parser.parse_args()
if options.portable and options.wallet_path is None:
options.wallet_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum.dat')
+
set_verbosity(options.verbose)
# config is an object passed to the various constructors (wallet, interface, gui)
@@ -130,7 +131,6 @@ if __name__ == '__main__':
for k, v in config_options.items():
if v is None: config_options.pop(k)
-
config = SimpleConfig(config_options)
if len(args)==0:
diff --git a/lib/interface.py b/lib/interface.py
@@ -85,14 +85,11 @@ def cert_verify_hostname(s):
class Interface(threading.Thread):
- def __init__(self, config=None):
-
- if config is None:
- config = SimpleConfig()
+ def __init__(self, server, config = None):
threading.Thread.__init__(self)
self.daemon = True
- self.config = config
+ self.config = config if config is not None else SimpleConfig()
self.connect_event = threading.Event()
self.subscriptions = {}
@@ -111,7 +108,7 @@ class Interface(threading.Thread):
self.pending_transactions_for_notifications= []
# parse server
- self.server = config.get('server')
+ self.server = server
host, port, protocol = self.server.split(':')
port = int(port)
@@ -122,7 +119,7 @@ class Interface(threading.Thread):
self.port = port
self.protocol = protocol
self.use_ssl = ( protocol in 'sg' )
- self.proxy = self.parse_proxy_options(config.get('proxy'))
+ self.proxy = self.parse_proxy_options(self.config.get('proxy'))
if self.proxy:
self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
@@ -308,7 +305,7 @@ class Interface(threading.Thread):
socket.getaddrinfo = getaddrinfo
if self.use_ssl:
- cert_path = os.path.join( self.config.get('path'), 'certs', self.host)
+ cert_path = os.path.join( self.config.path, 'certs', self.host)
if not os.path.exists(cert_path):
is_new = True
@@ -539,9 +536,11 @@ class Interface(threading.Thread):
- def start(self, queue):
- self.queue = queue
+ def start(self, queue = None, wait = False):
+ self.queue = queue if queue else Queue.Queue()
threading.Thread.start(self)
+ if wait:
+ self.connect_event.wait()
def run(self):
diff --git a/lib/network.py b/lib/network.py
@@ -38,15 +38,16 @@ def filter_protocol(servers, p):
#def pick_random_server():
# return random.choice( filter_protocol(DEFAULT_SERVERS,'s') )
+from simple_config import SimpleConfig
class Network(threading.Thread):
- def __init__(self, config):
+ def __init__(self, config = {}):
threading.Thread.__init__(self)
self.daemon = True
- self.config = config
+ self.config = SimpleConfig(config) if type(config) == type({}) else config
self.lock = threading.Lock()
- self.blockchain = Blockchain(config, self)
+ self.blockchain = Blockchain(self.config, self)
self.interfaces = {}
self.queue = Queue.Queue()
self.default_server = self.config.get('server')
@@ -138,7 +139,7 @@ class Network(threading.Thread):
def start_interface(self, server):
if server in self.interfaces.keys():
return
- i = interface.Interface({'server':server, 'path':self.config.path, 'proxy':self.proxy})
+ i = interface.Interface(server, self.config)
self.interfaces[server] = i
i.start(self.queue)
diff --git a/scripts/block_headers b/scripts/block_headers
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+
+# A simple script that connects to a server and displays block headers
+
+import time, electrum
+
+# 1. start the interface and wait for connection
+interface = electrum.Interface('electrum.no-ip.org:50002:s')
+interface.start(wait = True)
+if not interface.is_connected:
+ print "not connected"
+ exit()
+
+# 2. send the subscription
+callback = lambda _,result: electrum.print_json(result.get('result'))
+interface.send([('blockchain.headers.subscribe',[])], callback)
+
+# 3. wait for results
+while True:
+ time.sleep(1)
diff --git a/scripts/blocks b/scripts/blocks
@@ -1,16 +0,0 @@
-#!/usr/bin/env python
-
-import sys, electrum
-
-i = electrum.Interface()
-i.register_callback('connected', lambda: sys.stderr.write("Connected to %s\n" % i.connection_msg))
-i.start()
-i.send([('blockchain.numblocks.subscribe',[])])
-
-while True:
- try:
- r = i.get_response()
- except KeyboardInterrupt:
- break
- if r.get('method') == 'blockchain.numblocks.subscribe':
- print r.get('result')
diff --git a/scripts/get_balance b/scripts/get_balance
@@ -2,8 +2,8 @@
import sys
from electrum import Interface
-from electrum import bitcoin, Transaction
-from electrum import Network, SimpleConfig
+from electrum import bitcoin, Transaction, Network
+
def get_transaction(network, tx_hash, tx_height):
@@ -75,7 +75,7 @@ def update_tx_outputs(tx, prevout_values):
def main(address):
- network = Network(SimpleConfig({'server':'btc.it-zone.org:110:s','verbose':False}))
+ network = Network()
network.start(wait=True)
c, u = get_addr_balance(network, address)
diff --git a/scripts/get_history b/scripts/get_history
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import sys
-from electrum import Interface
+from electrum import Network
try:
addr = sys.argv[1]
@@ -9,9 +9,9 @@ except:
print "usage: get_history <bitcoin_address>"
sys.exit(1)
-i = Interface({'server':'electrum.be:50001:t'})
-i.start()
-h = i.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
+n = Network()
+n.start(wait=True)
+h = n.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
for item in h:
print item['tx_hash'], item['height']
diff --git a/scripts/peers b/scripts/peers
@@ -1,9 +1,12 @@
#!/usr/bin/env python
-from electrum import interface, Interface
+import time, electrum
+
+electrum.set_verbosity(False) # default is True
+
+network = electrum.Network({'verbose':False})
+network.start(wait=True)
+time.sleep(1)
+electrum.print_json( network.heights )
+
-i = Interface()
-i.start()
-servers = i.synchronous_get([('server.peers.subscribe',[])])[0]
-servers = i.parse_servers( servers )
-print servers
diff --git a/scripts/validate_tx b/scripts/validate_tx
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-
-import sys, hashlib
-from electrum import Interface
-from electrum.bitcoin import Hash, rev_hex, int_to_hex, hash_encode, hash_decode
-
-"""validate a transaction (SPV)"""
-
-i = Interface({'server':'ecdsa.org:50002:s'})
-i.start()
-
-
-def hash_merkle_root(merkle_s, target_hash, pos):
- h = hash_decode(target_hash)
- for i in range(len(merkle_s)):
- item = merkle_s[i]
- h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
- return hash_encode(h)
-
-
-def hash_header(res):
- header = int_to_hex(res.get('version'),4) \
- + rev_hex(res.get('prev_block_hash')) \
- + rev_hex(res.get('merkle_root')) \
- + int_to_hex(int(res.get('timestamp')),4) \
- + int_to_hex(int(res.get('bits')),4) \
- + int_to_hex(int(res.get('nonce')),4)
- return rev_hex(Hash(header.decode('hex')).encode('hex'))
-
-
-def verify_tx(tx_hash):
-
- res = i.synchronous_get([ ('blockchain.transaction.get_merkle',[tx_hash]) ])[0]
- raw_tx = i.synchronous_get([ ('blockchain.transaction.get',[tx_hash, res['block_height']]) ])[0]
- assert hash_encode(Hash(raw_tx.decode('hex'))) == tx_hash
-
- merkle_root = hash_merkle_root(res['merkle'], tx_hash, res['pos'])
- tx_height = res.get('block_height')
- headers_requests = []
- for height in range(tx_height-10,tx_height+10):
- headers_requests.append( ('blockchain.block.get_header',[height]) )
- headers = i.synchronous_get(headers_requests)
- _hash = None
- for header in headers:
- if _hash: assert _hash == header.get('prev_block_hash')
- _hash = hash_header(header)
- height = header.get('block_height')
- if height==tx_height:
- assert header.get('merkle_root') == merkle_root
- print height, _hash, '*'
- else:
- print height, _hash
-
-try:
- tx = sys.argv[1]
-except:
- tx = '587430e52af2cec98b3fd543083469ffa7a5f5dd2bd569898a7897a64e2eb031'
-
-verify_tx(tx)
-
diff --git a/scripts/watch_address b/scripts/watch_address
@@ -1,7 +1,6 @@
#!/usr/bin/env python
-import sys, time
-from electrum import Interface
+import sys, time, electrum
try:
addr = sys.argv[1]
@@ -9,18 +8,19 @@ except:
print "usage: watch_address <bitcoin_address>"
sys.exit(1)
-i = Interface()
-i.start()
-i.send([('blockchain.address.subscribe',[addr])] )
-time.sleep(1)
+# 1. start the interface and wait for connection
+interface = electrum.Interface('electrum.no-ip.org:50002:s')
+interface.start(wait = True)
+if not interface.is_connected:
+ print "not connected"
+ exit()
+
+# 2. send the subscription
+callback = lambda _,result: electrum.print_json(result.get('result'))
+interface.send([('blockchain.address.subscribe',[addr])], callback)
+
+# 3. wait for results
while True:
- r = i.get_response()
- method = r.get('method')
- if method == 'blockchain.address.subscribe':
- i.send([('blockchain.address.get_history',[addr])])
-
- elif method == 'blockchain.address.get_history':
- for line in r.get('result'):
- print line
- print "---"
+ time.sleep(1)
+