Auto merge of #2458 - daira:2450.pyflakes-cleanup, r=str4d

pyflakes cleanup

Make the RPC tests pyflakes-clean. fixes #2450

Includes a fix that upstream had in https://github.com/bitcoin/bitcoin/pull/7802
This commit is contained in:
Homu
2017-07-14 18:03:03 -07:00
50 changed files with 342 additions and 300 deletions

View File

@@ -4,7 +4,9 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes
class DecodeScriptTest(BitcoinTestFramework): class DecodeScriptTest(BitcoinTestFramework):
"""Tests decoding scripts via RPC command "decodescript".""" """Tests decoding scripts via RPC command "decodescript"."""

View File

@@ -8,7 +8,8 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import initialize_chain_clean, start_nodes
class DisableWalletTest (BitcoinTestFramework): class DisableWalletTest (BitcoinTestFramework):

View File

@@ -8,9 +8,9 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import start_node, connect_nodes
import os import os
import shutil
class ForkNotifyTest(BitcoinTestFramework): class ForkNotifyTest(BitcoinTestFramework):
@@ -19,7 +19,7 @@ class ForkNotifyTest(BitcoinTestFramework):
def setup_network(self): def setup_network(self):
self.nodes = [] self.nodes = []
self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt")
with open(self.alert_filename, 'w') as f: with open(self.alert_filename, 'w'):
pass # Just open then close to create zero-length file pass # Just open then close to create zero-length file
self.nodes.append(start_node(0, self.options.tmpdir, self.nodes.append(start_node(0, self.options.tmpdir,
["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""])) ["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""]))

View File

@@ -4,9 +4,12 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from pprint import pprint from test_framework.util import assert_equal, assert_greater_than, \
from time import sleep initialize_chain_clean, start_nodes, connect_nodes_bi, stop_nodes, \
wait_bitcoinds
from decimal import Decimal
# Create one-input, one-output, no-fee transaction: # Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework): class RawTransactionsTest(BitcoinTestFramework):

View File

@@ -4,7 +4,8 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import initialize_chain_clean, start_nodes, \
connect_nodes_bi
class GetBlockTemplateTest(BitcoinTestFramework): class GetBlockTemplateTest(BitcoinTestFramework):

View File

@@ -4,8 +4,10 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import AuthServiceProxy
from test_framework.util import random_transaction
from decimal import Decimal
def check_array_result(object_array, to_match, expected): def check_array_result(object_array, to_match, expected):
""" """

View File

@@ -4,7 +4,7 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from binascii import a2b_hex, b2a_hex from binascii import a2b_hex, b2a_hex
from hashlib import sha256 from hashlib import sha256

View File

@@ -5,9 +5,10 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from test_framework.util import assert_equal, start_node
import os import os
import shutil
class HardForkDetectionTest(BitcoinTestFramework): class HardForkDetectionTest(BitcoinTestFramework):
@@ -16,7 +17,7 @@ class HardForkDetectionTest(BitcoinTestFramework):
def setup_network(self): def setup_network(self):
self.nodes = [] self.nodes = []
self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt")
with open(self.alert_filename, 'w') as f: with open(self.alert_filename, 'w'):
pass # Just open then close to create zero-length file pass # Just open then close to create zero-length file
self.nodes.append(start_node(0, self.options.tmpdir, self.nodes.append(start_node(0, self.options.tmpdir,
["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""])) ["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""]))

View File

@@ -8,7 +8,8 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_nodes
import base64 import base64
try: try:
@@ -36,45 +37,45 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn = httplib.HTTPConnection(url.hostname, url.port) conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read(); out1 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! assert_equal(conn.sock!=None, True) # according to http/1.1 connection must still be open!
#send 2nd request without closing connection # send 2nd request without closing connection
conn.request('POST', '/', '{"method": "getchaintips"}', headers) conn.request('POST', '/', '{"method": "getchaintips"}', headers)
out2 = conn.getresponse().read(); out2 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message assert_equal('"error":null' in out2, True) # must also response with a correct json-rpc message
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! assert_equal(conn.sock!=None, True) # according to http/1.1 connection must still be open!
conn.close() conn.close()
#same should be if we add keep-alive because this should be the std. behaviour # same should be if we add keep-alive because this should be the std. behaviour
headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection": "keep-alive"} headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection": "keep-alive"}
conn = httplib.HTTPConnection(url.hostname, url.port) conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read(); out1 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! assert_equal(conn.sock!=None, True) # according to http/1.1 connection must still be open!
#send 2nd request without closing connection # send 2nd request without closing connection
conn.request('POST', '/', '{"method": "getchaintips"}', headers) conn.request('POST', '/', '{"method": "getchaintips"}', headers)
out2 = conn.getresponse().read(); out2 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message assert_equal('"error":null' in out2, True) # must also response with a correct json-rpc message
assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! assert_equal(conn.sock!=None, True) # according to http/1.1 connection must still be open!
conn.close() conn.close()
#now do the same with "Connection: close" # now do the same with "Connection: close"
headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection":"close"} headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection":"close"}
conn = httplib.HTTPConnection(url.hostname, url.port) conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read(); out1 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, False) #now the connection must be closed after the response assert_equal(conn.sock!=None, False) # now the connection must be closed after the response
#node1 (2nd node) is running with disabled keep-alive option # node1 (2nd node) is running with disabled keep-alive option
urlNode1 = urlparse.urlparse(self.nodes[1].url) urlNode1 = urlparse.urlparse(self.nodes[1].url)
authpair = urlNode1.username + ':' + urlNode1.password authpair = urlNode1.username + ':' + urlNode1.password
headers = {"Authorization": "Basic " + base64.b64encode(authpair)} headers = {"Authorization": "Basic " + base64.b64encode(authpair)}
@@ -82,10 +83,10 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn = httplib.HTTPConnection(urlNode1.hostname, urlNode1.port) conn = httplib.HTTPConnection(urlNode1.hostname, urlNode1.port)
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read(); out1 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) assert_equal('"error":null' in out1, True)
#node2 (third node) is running with standard keep-alive parameters which means keep-alive is on # node2 (third node) is running with standard keep-alive parameters which means keep-alive is on
urlNode2 = urlparse.urlparse(self.nodes[2].url) urlNode2 = urlparse.urlparse(self.nodes[2].url)
authpair = urlNode2.username + ':' + urlNode2.password authpair = urlNode2.username + ':' + urlNode2.password
headers = {"Authorization": "Basic " + base64.b64encode(authpair)} headers = {"Authorization": "Basic " + base64.b64encode(authpair)}
@@ -93,9 +94,9 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port) conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port)
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read(); out1 = conn.getresponse().read()
assert_equal('"error":null' in out1, True) assert_equal('"error":null' in out1, True)
assert_equal(conn.sock!=None, True) #connection must be closed because bitcoind should use keep-alive by default assert_equal(conn.sock!=None, True) # connection must be closed because bitcoind should use keep-alive by default
if __name__ == '__main__': if __name__ == '__main__':
HTTPBasicsTest ().main () HTTPBasicsTest().main()

View File

@@ -8,22 +8,23 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import initialize_chain_clean, start_node, \
connect_nodes_bi, sync_blocks
import time
class InvalidateTest(BitcoinTestFramework): class InvalidateTest(BitcoinTestFramework):
def setup_chain(self): def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir) print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 3) initialize_chain_clean(self.options.tmpdir, 3)
def setup_network(self): def setup_network(self):
self.nodes = [] self.nodes = []
self.is_network_split = False self.is_network_split = False
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"]))
self.nodes.append(start_node(1, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug"]))
self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"])) self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"]))
def run_test(self): def run_test(self):
print "Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:" print "Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:"
print "Mine 4 blocks on Node 0" print "Mine 4 blocks on Node 0"

View File

@@ -5,11 +5,11 @@
# #
from test_framework.test_framework import ComparisonTestFramework from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import * from test_framework.util import assert_equal
from test_framework.comptool import TestManager, TestInstance from test_framework.comptool import TestManager, TestInstance
from test_framework.mininode import * from test_framework.mininode import NetworkThread
from test_framework.blocktools import * from test_framework.blocktools import create_block, create_coinbase, create_transaction
import logging
import copy import copy
import time import time
@@ -25,7 +25,7 @@ re-requested.
# Use the ComparisonTestFramework with 1 node: only use --testbinary. # Use the ComparisonTestFramework with 1 node: only use --testbinary.
class InvalidBlockRequestTest(ComparisonTestFramework): class InvalidBlockRequestTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them. ''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. ''' Change the "outcome" variable from each TestInstance object to only do the comparison. '''
def __init__(self): def __init__(self):
self.num_nodes = 1 self.num_nodes = 1

View File

@@ -6,18 +6,17 @@
# Exercise the wallet keypool, and interaction with wallet encryption/locking # Exercise the wallet keypool, and interaction with wallet encryption/locking
# Add python-bitcoinrpc to module search path: # Add python-bitcoinrpc to module search path:
from test_framework.authproxy import JSONRPCException
from test_framework.util import check_json_precision, initialize_chain, \
start_nodes, start_node, stop_nodes, wait_bitcoinds, bitcoind_processes
import os import os
import sys import sys
import json
import shutil import shutil
import subprocess
import tempfile import tempfile
import traceback import traceback
from test_framework.util import *
def check_array_result(object_array, to_match, expected): def check_array_result(object_array, to_match, expected):
""" """
Pass in array of JSON objects, a dictionary with key/value pairs Pass in array of JSON objects, a dictionary with key/value pairs

View File

@@ -6,8 +6,8 @@
# Exercise the listtransactions API # Exercise the listtransactions API
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from decimal import Decimal
def check_array_result(object_array, to_match, expected): def check_array_result(object_array, to_match, expected):
""" """

View File

@@ -4,9 +4,15 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
from test_framework.mininode import * from test_framework.mininode import NodeConn, NodeConnCB, NetworkThread, \
EarlyDisconnectError, CInv, msg_inv, mininode_lock
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import initialize_chain_clean, start_nodes, \
p2p_port
import os
import time
import random
import logging import logging
''' '''
@@ -43,7 +49,6 @@ class TestManager(NodeConnCB):
def run(self): def run(self):
try: try:
fail = False
self.connection.rpc.generate(1) # Leave IBD self.connection.rpc.generate(1) # Leave IBD
numBlocksToGenerate = [ 8, 16, 128, 1024 ] numBlocksToGenerate = [ 8, 16, 128, 1024 ]
@@ -56,7 +61,7 @@ class TestManager(NodeConnCB):
current_invs = [] current_invs = []
if len(current_invs) > 0: if len(current_invs) > 0:
self.connection.send_message(msg_inv(current_invs)) self.connection.send_message(msg_inv(current_invs))
# Wait and see how many blocks were requested # Wait and see how many blocks were requested
time.sleep(2) time.sleep(2)
@@ -75,7 +80,7 @@ class TestManager(NodeConnCB):
self.disconnectOkay = True self.disconnectOkay = True
self.connection.disconnect_node() self.connection.disconnect_node()
class MaxBlocksInFlightTest(BitcoinTestFramework): class MaxBlocksInFlightTest(BitcoinTestFramework):
def add_options(self, parser): def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary", parser.add_option("--testbinary", dest="testbinary",

View File

@@ -9,9 +9,8 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_node, connect_nodes
import os
import shutil
# Create one-input, one-output, no-fee transaction: # Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework): class MempoolCoinbaseTest(BitcoinTestFramework):
@@ -36,8 +35,6 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
return signresult["hex"] return signresult["hex"]
def run_test(self): def run_test(self):
start_count = self.nodes[0].getblockcount()
# Mine three blocks. After this, nodes[0] blocks # Mine three blocks. After this, nodes[0] blocks
# 101, 102, and 103 are spend-able. # 101, 102, and 103 are spend-able.
new_blocks = self.nodes[1].generate(4) new_blocks = self.nodes[1].generate(4)
@@ -69,6 +66,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# Broadcast and mine 103_1: # Broadcast and mine 103_1:
spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw) spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw)
[spend_103_1_id] # hush pyflakes
self.nodes[0].generate(1) self.nodes[0].generate(1)
# ... now put spend_101 and spend_102_1 in memory pools: # ... now put spend_101 and spend_102_1 in memory pools:

View File

@@ -9,9 +9,8 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_node
import os
import shutil
# Create one-input, one-output, no-fee transaction: # Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework): class MempoolCoinbaseTest(BitcoinTestFramework):

View File

@@ -14,9 +14,10 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
import os from test_framework.util import assert_equal, assert_greater_than, assert_raises, \
import shutil start_node
# Create one-input, one-output, no-fee transaction: # Create one-input, one-output, no-fee transaction:
class MempoolSpendCoinbaseTest(BitcoinTestFramework): class MempoolSpendCoinbaseTest(BitcoinTestFramework):

View File

@@ -4,10 +4,12 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
import os from test_framework.util import assert_equal, initialize_chain_clean, \
import shutil start_node, connect_nodes
from time import sleep
import time
from decimal import Decimal
# Test -mempooltxinputlimit # Test -mempooltxinputlimit
class MempoolTxInputLimitTest(BitcoinTestFramework): class MempoolTxInputLimitTest(BitcoinTestFramework):
@@ -44,7 +46,7 @@ class MempoolTxInputLimitTest(BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
if status == "failed": if status == "failed":
@@ -61,8 +63,6 @@ class MempoolTxInputLimitTest(BitcoinTestFramework):
return txid return txid
def run_test(self): def run_test(self):
start_count = self.nodes[0].getblockcount()
self.nodes[0].generate(100) self.nodes[0].generate(100)
self.sync_all() self.sync_all()
# Mine three blocks. After this, nodes[0] blocks # Mine three blocks. After this, nodes[0] blocks
@@ -90,7 +90,7 @@ class MempoolTxInputLimitTest(BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
msg = results[0]["error"]["message"] msg = results[0]["error"]["message"]
@@ -116,7 +116,6 @@ class MempoolTxInputLimitTest(BitcoinTestFramework):
assert_equal(set(self.nodes[0].getrawmempool()), set()) assert_equal(set(self.nodes[0].getrawmempool()), set())
# Check 2: sendfrom is limited by -mempooltxinputlimit # Check 2: sendfrom is limited by -mempooltxinputlimit
node1_taddr = self.nodes[1].getnewaddress();
recipients = [] recipients = []
spend_taddr_amount = spend_zaddr_amount - Decimal('0.0001') spend_taddr_amount = spend_zaddr_amount - Decimal('0.0001')
spend_taddr_output = Decimal('8') spend_taddr_output = Decimal('8')

View File

@@ -8,9 +8,10 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
import os from test_framework.util import assert_equal, assert_raises, \
import shutil initialize_chain_clean, start_node, connect_nodes
class MerkleBlockTest(BitcoinTestFramework): class MerkleBlockTest(BitcoinTestFramework):

View File

@@ -8,13 +8,10 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, connect_nodes_bi, p2p_port
import base64
import time
try:
import http.client as httplib
except ImportError:
import httplib
try: try:
import urllib.parse as urlparse import urllib.parse as urlparse
except ImportError: except ImportError:

View File

@@ -4,12 +4,17 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
from test_framework.mininode import * from test_framework.mininode import CBlockHeader, CInv, NodeConn, NodeConnCB, \
NetworkThread, msg_block, msg_headers, msg_inv, msg_ping, msg_pong, \
mininode_lock
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
import time start_node, p2p_port
from test_framework.blocktools import create_block, create_coinbase from test_framework.blocktools import create_block, create_coinbase
import os
import time
''' '''
AcceptBlockTest -- test processing of unrequested blocks. AcceptBlockTest -- test processing of unrequested blocks.

View File

@@ -4,9 +4,10 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
from time import * start_node, connect_nodes
from test_framework.mininode import COIN from test_framework.mininode import COIN
import time import time
@@ -37,7 +38,7 @@ class PrioritiseTransactionTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
if status == "failed": if status == "failed":
@@ -120,7 +121,7 @@ class PrioritiseTransactionTest (BitcoinTestFramework):
break break
if time.time() - start > 30: if time.time() - start > 30:
raise AssertionError("Test timed out because prioritised transaction was not returned by getblocktemplate within 30 seconds.") raise AssertionError("Test timed out because prioritised transaction was not returned by getblocktemplate within 30 seconds.")
sleep(1) time.sleep(1)
block_template = self.nodes[0].getblocktemplate() block_template = self.nodes[0].getblocktemplate()
assert(in_block_template) assert(in_block_template)

View File

@@ -14,21 +14,13 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, bytes_to_hex_str, \
start_nodes
from proton.handlers import MessagingHandler from proton.handlers import MessagingHandler
from proton.reactor import Container from proton.reactor import Container
import binascii
import struct
import threading
try: import threading
import http.client as httplib
except ImportError:
import httplib
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
class Server(MessagingHandler): class Server(MessagingHandler):

View File

@@ -2,14 +2,14 @@
# Copyright (c) 2015 The Bitcoin Core developers # Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
import socket
import traceback, sys
from binascii import hexlify
import time, os
from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_nodes
import socket
import os
''' '''
Test plan: Test plan:
- Start bitcoind's with different proxy configurations - Start bitcoind's with different proxy configurations

View File

@@ -12,8 +12,12 @@
# ******** # ********
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from test_framework.util import initialize_chain_clean, start_node, \
connect_nodes, stop_node, sync_blocks
import os.path import os.path
import time
def calc_usage(blockdir): def calc_usage(blockdir):
return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f))/(1024*1024) return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f))/(1024*1024)
@@ -190,7 +194,7 @@ class PruneTest(BitcoinTestFramework):
try: try:
self.nodes[2].getblock(self.forkhash) self.nodes[2].getblock(self.forkhash)
raise AssertionError("Old block wasn't pruned so can't test redownload") raise AssertionError("Old block wasn't pruned so can't test redownload")
except JSONRPCException as e: except JSONRPCException:
print "Will need to redownload block",self.forkheight print "Will need to redownload block",self.forkheight
# Verify that we have enough history to reorg back to the fork point # Verify that we have enough history to reorg back to the fork point
@@ -253,7 +257,7 @@ class PruneTest(BitcoinTestFramework):
newtx = newtx + rawtx[94:] newtx = newtx + rawtx[94:]
# Appears to be ever so slightly faster to sign with SIGHASH_NONE # Appears to be ever so slightly faster to sign with SIGHASH_NONE
signresult = node.signrawtransaction(newtx,None,None,"NONE") signresult = node.signrawtransaction(newtx,None,None,"NONE")
txid = node.sendrawtransaction(signresult["hex"], True) node.sendrawtransaction(signresult["hex"], True)
# Mine a full sized block which will be these transactions we just created # Mine a full sized block which will be these transactions we just created
node.generate(1) node.generate(1)

View File

@@ -9,9 +9,11 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from pprint import pprint from test_framework.util import assert_equal, initialize_chain_clean, \
from time import sleep start_nodes, connect_nodes_bi
from decimal import Decimal
# Create one-input, one-output, no-fee transaction: # Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework): class RawTransactionsTest(BitcoinTestFramework):
@@ -104,18 +106,20 @@ class RawTransactionsTest(BitcoinTestFramework):
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']]) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])
mSigObjValid = self.nodes[2].validateaddress(mSigObj) mSigObjValid = self.nodes[2].validateaddress(mSigObj)
assert_equal(mSigObjValid['isvalid'], True)
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2); txId = self.nodes[0].sendtoaddress(mSigObj, 2.2);
decTx = self.nodes[0].gettransaction(txId) decTx = self.nodes[0].gettransaction(txId)
rawTx = self.nodes[0].decoderawtransaction(decTx['hex']) rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
sPK = rawTx['vout'][0]['scriptPubKey']['hex'] sPK = rawTx['vout'][0]['scriptPubKey']['hex']
[sPK] # hush pyflakes
self.sync_all() self.sync_all()
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
#THIS IS A INCOMPLETE FEATURE # THIS IS A INCOMPLETE FEATURE
#NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION # NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
assert_equal(self.nodes[2].getbalance(), bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable assert_equal(self.nodes[2].getbalance(), bal) # for now, assume the funds of a 2of3 multisig tx are not marked as spendable
txDetails = self.nodes[0].gettransaction(txId, True) txDetails = self.nodes[0].gettransaction(txId, True)
rawTx = self.nodes[0].decoderawtransaction(txDetails['hex']) rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
@@ -130,10 +134,10 @@ class RawTransactionsTest(BitcoinTestFramework):
outputs = { self.nodes[0].getnewaddress() : 2.199 } outputs = { self.nodes[0].getnewaddress() : 2.199 }
rawTx = self.nodes[2].createrawtransaction(inputs, outputs) rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxPartialSigned = self.nodes[1].signrawtransaction(rawTx, inputs) rawTxPartialSigned = self.nodes[1].signrawtransaction(rawTx, inputs)
assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx assert_equal(rawTxPartialSigned['complete'], False) # node1 only has one key, can't comp. sign the tx
rawTxSigned = self.nodes[2].signrawtransaction(rawTx, inputs) rawTxSigned = self.nodes[2].signrawtransaction(rawTx, inputs)
assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys assert_equal(rawTxSigned['complete'], True) # node2 can sign the tx compl., own two of three keys
self.nodes[2].sendrawtransaction(rawTxSigned['hex']) self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex']) rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
self.sync_all() self.sync_all()

View File

@@ -6,15 +6,14 @@
# Exercise the listreceivedbyaddress API # Exercise the listreceivedbyaddress API
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from decimal import Decimal
def get_sub_array_from_array(object_array, to_match): def get_sub_array_from_array(object_array, to_match):
''' '''
Finds and returns a sub array from an array of arrays. Finds and returns a sub array from an array of arrays.
to_match should be a unique idetifier of a sub array to_match should be a unique idetifier of a sub array
''' '''
num_matched = 0
for item in object_array: for item in object_array:
all_match = True all_match = True
for key,value in to_match.items(): for key,value in to_match.items():
@@ -26,12 +25,12 @@ def get_sub_array_from_array(object_array, to_match):
return [] return []
def check_array_result(object_array, to_match, expected, should_not_find = False): def check_array_result(object_array, to_match, expected, should_not_find = False):
""" '''
Pass in array of JSON objects, a dictionary with key/value pairs Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value to match against, and another dictionary with expected key/value
pairs. pairs.
If the should_not_find flag is true, to_match should not be found in object_array If the should_not_find flag is true, to_match should not be found in object_array
""" '''
if should_not_find == True: if should_not_find == True:
expected = { } expected = { }
num_matched = 0 num_matched = 0
@@ -62,49 +61,49 @@ class ReceivedByTest(BitcoinTestFramework):
txid = self.nodes[0].sendtoaddress(addr, 0.1) txid = self.nodes[0].sendtoaddress(addr, 0.1)
self.sync_all() self.sync_all()
#Check not listed in listreceivedbyaddress because has 0 confirmations # Check not listed in listreceivedbyaddress because has 0 confirmations
check_array_result(self.nodes[1].listreceivedbyaddress(), check_array_result(self.nodes[1].listreceivedbyaddress(),
{"address":addr}, {"address":addr},
{ }, { },
True) True)
#Bury Tx under 10 block so it will be returned by listreceivedbyaddress # Bury Tx under 10 block so it will be returned by listreceivedbyaddress
self.nodes[1].generate(10) self.nodes[1].generate(10)
self.sync_all() self.sync_all()
check_array_result(self.nodes[1].listreceivedbyaddress(), check_array_result(self.nodes[1].listreceivedbyaddress(),
{"address":addr}, {"address":addr},
{"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]}) {"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]})
#With min confidence < 10 # With min confidence < 10
check_array_result(self.nodes[1].listreceivedbyaddress(5), check_array_result(self.nodes[1].listreceivedbyaddress(5),
{"address":addr}, {"address":addr},
{"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]}) {"address":addr, "account":"", "amount":Decimal("0.1"), "confirmations":10, "txids":[txid,]})
#With min confidence > 10, should not find Tx # With min confidence > 10, should not find Tx
check_array_result(self.nodes[1].listreceivedbyaddress(11),{"address":addr},{ },True) check_array_result(self.nodes[1].listreceivedbyaddress(11),{"address":addr},{ },True)
#Empty Tx # Empty Tx
addr = self.nodes[1].getnewaddress() addr = self.nodes[1].getnewaddress()
check_array_result(self.nodes[1].listreceivedbyaddress(0,True), check_array_result(self.nodes[1].listreceivedbyaddress(0,True),
{"address":addr}, {"address":addr},
{"address":addr, "account":"", "amount":0, "confirmations":0, "txids":[]}) {"address":addr, "account":"", "amount":0, "confirmations":0, "txids":[]})
''' '''
getreceivedbyaddress Test getreceivedbyaddress Test
''' '''
# Send from node 0 to 1 # Send from node 0 to 1
addr = self.nodes[1].getnewaddress() addr = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendtoaddress(addr, 0.1) txid = self.nodes[0].sendtoaddress(addr, 0.1)
self.sync_all() self.sync_all()
#Check balance is 0 because of 0 confirmations # Check balance is 0 because of 0 confirmations
balance = self.nodes[1].getreceivedbyaddress(addr) balance = self.nodes[1].getreceivedbyaddress(addr)
if balance != Decimal("0.0"): if balance != Decimal("0.0"):
raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance))
#Check balance is 0.1 # Check balance is 0.1
balance = self.nodes[1].getreceivedbyaddress(addr,0) balance = self.nodes[1].getreceivedbyaddress(addr,0)
if balance != Decimal("0.1"): if balance != Decimal("0.1"):
raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance))
#Bury Tx under 10 block so it will be returned by the default getreceivedbyaddress # Bury Tx under 10 block so it will be returned by the default getreceivedbyaddress
self.nodes[1].generate(10) self.nodes[1].generate(10)
self.sync_all() self.sync_all()
balance = self.nodes[1].getreceivedbyaddress(addr) balance = self.nodes[1].getreceivedbyaddress(addr)
@@ -112,15 +111,15 @@ class ReceivedByTest(BitcoinTestFramework):
raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance)) raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance))
''' '''
listreceivedbyaccount + getreceivedbyaccount Test listreceivedbyaccount + getreceivedbyaccount Test
''' '''
#set pre-state # set pre-state
addrArr = self.nodes[1].getnewaddress() addrArr = self.nodes[1].getnewaddress()
account = self.nodes[1].getaccount(addrArr) account = self.nodes[1].getaccount(addrArr)
received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(),{"account":account}) received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(),{"account":account})
if len(received_by_account_json) == 0: if len(received_by_account_json) == 0:
raise AssertionError("No accounts found in node") raise AssertionError("No accounts found in node")
balance_by_account = rec_by_accountArr = self.nodes[1].getreceivedbyaccount(account) balance_by_account = self.nodes[1].getreceivedbyaccount(account)
txid = self.nodes[0].sendtoaddress(addr, 0.1) txid = self.nodes[0].sendtoaddress(addr, 0.1)
self.sync_all() self.sync_all()
@@ -147,7 +146,7 @@ class ReceivedByTest(BitcoinTestFramework):
if balance != balance_by_account + Decimal("0.1"): if balance != balance_by_account + Decimal("0.1"):
raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance)) raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance))
#Create a new account named "mynewaccount" that has a 0 balance # Create a new account named "mynewaccount" that has a 0 balance
self.nodes[1].getaccountaddress("mynewaccount") self.nodes[1].getaccountaddress("mynewaccount")
received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(0,True),{"account":"mynewaccount"}) received_by_account_json = get_sub_array_from_array(self.nodes[1].listreceivedbyaccount(0,True),{"account":"mynewaccount"})
if len(received_by_account_json) == 0: if len(received_by_account_json) == 0:

View File

@@ -6,9 +6,11 @@
# #
# Test -reindex with CheckBlockIndex # Test -reindex with CheckBlockIndex
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
import os.path start_node, stop_node, wait_bitcoinds
class ReindexTest(BitcoinTestFramework): class ReindexTest(BitcoinTestFramework):

View File

@@ -7,14 +7,15 @@
# Test REST interface # Test REST interface
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, assert_greater_than, \
from struct import * initialize_chain_clean, start_nodes, connect_nodes_bi
import struct
import binascii import binascii
import json import json
import StringIO import StringIO
import decimal from decimal import Decimal
try: try:
import http.client as httplib import http.client as httplib
@@ -28,11 +29,11 @@ except ImportError:
def deser_uint256(f): def deser_uint256(f):
r = 0 r = 0
for i in range(8): for i in range(8):
t = unpack(b"<I", f.read(4))[0] t = struct.unpack(b"<I", f.read(4))[0]
r += t << (i * 32) r += t << (i * 32)
return r return r
#allows simple http get calls # allows simple http get calls
def http_get_call(host, port, path, response_object = 0): def http_get_call(host, port, path, response_object = 0):
conn = httplib.HTTPConnection(host, port) conn = httplib.HTTPConnection(host, port)
conn.request('GET', path) conn.request('GET', path)
@@ -42,7 +43,7 @@ def http_get_call(host, port, path, response_object = 0):
return conn.getresponse().read() return conn.getresponse().read()
#allows simple http post calls with a request body # allows simple http post calls with a request body
def http_post_call(host, port, path, requestdata = '', response_object = 0): def http_post_call(host, port, path, requestdata = '', response_object = 0):
conn = httplib.HTTPConnection(host, port) conn = httplib.HTTPConnection(host, port)
conn.request('POST', path, requestdata) conn.request('POST', path, requestdata)
@@ -84,7 +85,7 @@ class RESTTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
bb_hash = self.nodes[0].getbestblockhash() bb_hash = self.nodes[0].getbestblockhash()
assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) #balance now should be 0.1 on node 1 assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) # balance now should be 0.1 on node 1
# load the latest 0.1 tx over the REST API # load the latest 0.1 tx over the REST API
json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json") json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")
@@ -119,13 +120,13 @@ class RESTTest (BitcoinTestFramework):
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string) json_obj = json.loads(json_string)
#check chainTip response # check chainTip response
assert_equal(json_obj['chaintipHash'], bb_hash) assert_equal(json_obj['chaintipHash'], bb_hash)
#make sure there is no utox in the response because this oupoint has been spent # make sure there is no utox in the response because this oupoint has been spent
assert_equal(len(json_obj['utxos']), 0) assert_equal(len(json_obj['utxos']), 0)
#check bitmap # check bitmap
assert_equal(json_obj['bitmap'], "0") assert_equal(json_obj['bitmap'], "0")
@@ -138,24 +139,24 @@ class RESTTest (BitcoinTestFramework):
assert_equal(len(json_obj['utxos']), 1) assert_equal(len(json_obj['utxos']), 1)
assert_equal(json_obj['bitmap'], "10") assert_equal(json_obj['bitmap'], "10")
#test binary response # test binary response
bb_hash = self.nodes[0].getbestblockhash() bb_hash = self.nodes[0].getbestblockhash()
binaryRequest = b'\x01\x02' binaryRequest = b'\x01\x02'
binaryRequest += binascii.unhexlify(txid) binaryRequest += binascii.unhexlify(txid)
binaryRequest += pack("i", n); binaryRequest += struct.pack("i", n);
binaryRequest += binascii.unhexlify(vintx); binaryRequest += binascii.unhexlify(vintx);
binaryRequest += pack("i", 0); binaryRequest += struct.pack("i", 0);
bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest) bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest)
output = StringIO.StringIO() output = StringIO.StringIO()
output.write(bin_response) output.write(bin_response)
output.seek(0) output.seek(0)
chainHeight = unpack("i", output.read(4))[0] chainHeight = struct.unpack("i", output.read(4))[0]
hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(65).rstrip("L") hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(65).rstrip("L")
assert_equal(bb_hash, hashFromBinResponse) #check if getutxo's chaintip during calculation was fine assert_equal(bb_hash, hashFromBinResponse) # check if getutxo's chaintip during calculation was fine
assert_equal(chainHeight, 102) #chain height must be 102 assert_equal(chainHeight, 102) # chain height must be 102
############################ ############################
@@ -176,41 +177,41 @@ class RESTTest (BitcoinTestFramework):
json_request = '/'+txid+'-'+str(n) json_request = '/'+txid+'-'+str(n)
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string) json_obj = json.loads(json_string)
assert_equal(len(json_obj['utxos']), 0) #there should be a outpoint because it has just added to the mempool assert_equal(len(json_obj['utxos']), 0) # there should be a outpoint because it has just added to the mempool
json_request = '/checkmempool/'+txid+'-'+str(n) json_request = '/checkmempool/'+txid+'-'+str(n)
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string) json_obj = json.loads(json_string)
assert_equal(len(json_obj['utxos']), 1) #there should be a outpoint because it has just added to the mempool assert_equal(len(json_obj['utxos']), 1) # there should be a outpoint because it has just added to the mempool
#do some invalid requests # do some invalid requests
json_request = '{"checkmempool' json_request = '{"checkmempool'
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True) response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True)
assert_equal(response.status, 500) #must be a 500 because we send a invalid json request assert_equal(response.status, 500) # must be a 500 because we send a invalid json request
json_request = '{"checkmempool' json_request = '{"checkmempool'
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True) response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True)
assert_equal(response.status, 500) #must be a 500 because we send a invalid bin request assert_equal(response.status, 500) # must be a 500 because we send a invalid bin request
response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True) response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True)
assert_equal(response.status, 500) #must be a 500 because we send a invalid bin request assert_equal(response.status, 500) # must be a 500 because we send a invalid bin request
#test limits # test limits
json_request = '/checkmempool/' json_request = '/checkmempool/'
for x in range(0, 20): for x in range(0, 20):
json_request += txid+'-'+str(n)+'/' json_request += txid+'-'+str(n)+'/'
json_request = json_request.rstrip("/") json_request = json_request.rstrip("/")
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True) response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)
assert_equal(response.status, 500) #must be a 500 because we exceeding the limits assert_equal(response.status, 500) # must be a 500 because we exceeding the limits
json_request = '/checkmempool/' json_request = '/checkmempool/'
for x in range(0, 15): for x in range(0, 15):
json_request += txid+'-'+str(n)+'/' json_request += txid+'-'+str(n)+'/'
json_request = json_request.rstrip("/"); json_request = json_request.rstrip("/");
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True) response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)
assert_equal(response.status, 200) #must be a 500 because we exceeding the limits assert_equal(response.status, 200) # must be a 500 because we exceeding the limits
self.nodes[0].generate(1) #generate block to not affect upcoming tests self.nodes[0].generate(1) # generate block to not affect upcoming tests
self.sync_all() self.sync_all()
################ ################
@@ -263,11 +264,11 @@ class RESTTest (BitcoinTestFramework):
response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True) response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)
assert_equal(response_header_json.status, 200) assert_equal(response_header_json.status, 200)
response_header_json_str = response_header_json.read() response_header_json_str = response_header_json.read()
json_obj = json.loads(response_header_json_str, parse_float=decimal.Decimal) json_obj = json.loads(response_header_json_str, parse_float=Decimal)
assert_equal(len(json_obj), 1) #ensure that there is one header in the json response assert_equal(len(json_obj), 1) # ensure that there is one header in the json response
assert_equal(json_obj[0]['hash'], bb_hash) #request/response hash should be the same assert_equal(json_obj[0]['hash'], bb_hash) # request/response hash should be the same
#compare with normal RPC block response # compare with normal RPC block response
rpc_block_json = self.nodes[0].getblock(bb_hash) rpc_block_json = self.nodes[0].getblock(bb_hash)
assert_equal(json_obj[0]['hash'], rpc_block_json['hash']) assert_equal(json_obj[0]['hash'], rpc_block_json['hash'])
assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations']) assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations'])
@@ -281,14 +282,14 @@ class RESTTest (BitcoinTestFramework):
assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork']) assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork'])
assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash']) assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash'])
#see if we can get 5 headers in one response # see if we can get 5 headers in one response
self.nodes[1].generate(5) self.nodes[1].generate(5)
self.sync_all() self.sync_all()
response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True) response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)
assert_equal(response_header_json.status, 200) assert_equal(response_header_json.status, 200)
response_header_json_str = response_header_json.read() response_header_json_str = response_header_json.read()
json_obj = json.loads(response_header_json_str) json_obj = json.loads(response_header_json_str)
assert_equal(len(json_obj), 5) #now we should have 5 header objects assert_equal(len(json_obj), 5) # now we should have 5 header objects
# do tx test # do tx test
tx_hash = block_json_obj['tx'][0]['txid']; tx_hash = block_json_obj['tx'][0]['txid'];
@@ -328,20 +329,20 @@ class RESTTest (BitcoinTestFramework):
newblockhash = self.nodes[1].generate(1) newblockhash = self.nodes[1].generate(1)
self.sync_all() self.sync_all()
#check if the 3 tx show up in the new block # check if the 3 tx show up in the new block
json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json') json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string) json_obj = json.loads(json_string)
for tx in json_obj['tx']: for tx in json_obj['tx']:
if not 'coinbase' in tx['vin'][0]: #exclude coinbase if not 'coinbase' in tx['vin'][0]: # exclude coinbase
assert_equal(tx['txid'] in txs, True) assert_equal(tx['txid'] in txs, True)
#check the same but without tx details # check the same but without tx details
json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json') json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string) json_obj = json.loads(json_string)
for tx in txs: for tx in txs:
assert_equal(tx in json_obj['tx'], True) assert_equal(tx in json_obj['tx'], True)
#test rest bestblock # test rest bestblock
bb_hash = self.nodes[0].getbestblockhash() bb_hash = self.nodes[0].getbestblockhash()
json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json') json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json')
@@ -349,4 +350,4 @@ class RESTTest (BitcoinTestFramework):
assert_equal(json_obj['bestblockhash'], bb_hash) assert_equal(json_obj['bestblockhash'], bb_hash)
if __name__ == '__main__': if __name__ == '__main__':
RESTTest ().main () RESTTest().main()

View File

@@ -5,19 +5,20 @@
# Test for -rpcbind, as well as -rpcallowip and -rpcconnect # Test for -rpcbind, as well as -rpcallowip and -rpcconnect
# Add python-bitcoinrpc to module search path: # Dependency: python-bitcoinrpc
from test_framework.util import assert_equal, check_json_precision, \
initialize_chain, start_nodes, stop_nodes, wait_bitcoinds, \
bitcoind_processes, rpc_port
from test_framework.authproxy import AuthServiceProxy
from test_framework.netutil import addr_to_hex, get_bind_addrs, all_interfaces
import os import os
import sys import sys
import json
import shutil import shutil
import subprocess
import tempfile import tempfile
import traceback import traceback
from test_framework.util import *
from test_framework.netutil import *
def run_bind_test(tmpdir, allow_ips, connect_to, addresses, expected): def run_bind_test(tmpdir, allow_ips, connect_to, addresses, expected):
''' '''
Start a node with requested rpcallowip and rpcbind parameters, Start a node with requested rpcallowip and rpcbind parameters,
@@ -119,7 +120,6 @@ def main():
check_json_precision() check_json_precision()
success = False success = False
nodes = []
try: try:
print("Initializing test directory "+options.tmpdir) print("Initializing test directory "+options.tmpdir)
if not os.path.isdir(options.tmpdir): if not os.path.isdir(options.tmpdir):

View File

@@ -20,13 +20,12 @@ NOTE: This test is very slow and may take more than 40 minutes to run.
''' '''
from test_framework.test_framework import ComparisonTestFramework from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestInstance, TestManager from test_framework.comptool import TestInstance, TestManager
from test_framework.mininode import * from test_framework.mininode import NetworkThread
from test_framework.blocktools import * from test_framework.blocktools import create_block, create_coinbase, create_transaction
from test_framework.script import * from test_framework.script import CScript, CScriptOp, CScriptNum, OPCODES_BY_NAME
import logging
import copy import os
import json import json
script_valid_file = "../../src/test/data/script_valid.json" script_valid_file = "../../src/test/data/script_valid.json"

View File

@@ -4,7 +4,8 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes
class SignRawTransactionsTest(BitcoinTestFramework): class SignRawTransactionsTest(BitcoinTestFramework):

View File

@@ -8,7 +8,11 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import start_node, connect_nodes, \
sync_blocks, sync_mempools
import random
from decimal import Decimal, ROUND_DOWN
# Construct 2 trivial P2SH's and the ScriptSigs that spend them # Construct 2 trivial P2SH's and the ScriptSigs that spend them
# So we can create many many transactions without needing to spend # So we can create many many transactions without needing to spend

View File

@@ -3,14 +3,17 @@
# and for constructing a getheaders message # and for constructing a getheaders message
# #
from mininode import * from mininode import CBlock, CBlockHeader, CBlockLocator, CTransaction, msg_block, msg_headers, msg_tx
import sys
import cStringIO
import dbm import dbm
class BlockStore(object): class BlockStore(object):
def __init__(self, datadir): def __init__(self, datadir):
self.blockDB = dbm.open(datadir + "/blocks", 'c') self.blockDB = dbm.open(datadir + "/blocks", 'c')
self.currentBlock = 0L self.currentBlock = 0L
def close(self): def close(self):
self.blockDB.close() self.blockDB.close()

View File

@@ -4,8 +4,7 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
from mininode import * from mininode import CBlock, CTransaction, CTxIn, CTxOut, COutPoint, ser_string
from script import CScript, CScriptOp
# Create a block (with regtest difficulty) # Create a block (with regtest difficulty)
def create_block(hashprev, coinbase, nTime=None): def create_block(hashprev, coinbase, nTime=None):

View File

@@ -4,10 +4,13 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
# #
from mininode import * from mininode import CBlock, CTransaction, CInv, NodeConn, NodeConnCB, \
msg_inv, msg_getheaders, msg_ping, msg_mempool, mininode_lock, MAX_INV_SZ
from blockstore import BlockStore, TxStore from blockstore import BlockStore, TxStore
from util import p2p_port from util import p2p_port
import time
''' '''
This is a tool for comparing two or more bitcoinds to each other This is a tool for comparing two or more bitcoinds to each other
using a script provided. using a script provided.
@@ -25,8 +28,6 @@ generator that returns TestInstance objects. See below for definition.
# on_getheaders: provide headers via BlockStore # on_getheaders: provide headers via BlockStore
# on_getdata: provide blocks via BlockStore # on_getdata: provide blocks via BlockStore
global mininode_lock
def wait_until(predicate, attempts=float('inf'), timeout=float('inf')): def wait_until(predicate, attempts=float('inf'), timeout=float('inf')):
attempt = 0 attempt = 0
elapsed = 0 elapsed = 0

View File

@@ -24,10 +24,10 @@ if sys.version > '3':
bchr = lambda x: bytes([x]) bchr = lambda x: bytes([x])
bord = lambda x: x bord = lambda x: x
import copy
import struct import struct
import binascii
import test_framework.bignum from test_framework import bignum
MAX_SCRIPT_SIZE = 10000 MAX_SCRIPT_SIZE = 10000
MAX_SCRIPT_ELEMENT_SIZE = 520 MAX_SCRIPT_ELEMENT_SIZE = 520

View File

@@ -13,8 +13,11 @@ import shutil
import tempfile import tempfile
import traceback import traceback
from authproxy import AuthServiceProxy, JSONRPCException from authproxy import JSONRPCException
from util import * from util import assert_equal, check_json_precision, \
initialize_chain, initialize_chain_clean, \
start_nodes, connect_nodes_bi, stop_nodes, \
sync_blocks, sync_mempools, wait_bitcoinds
class BitcoinTestFramework(object): class BitcoinTestFramework(object):

View File

@@ -21,8 +21,7 @@ import subprocess
import time import time
import re import re
from authproxy import AuthServiceProxy, JSONRPCException from authproxy import AuthServiceProxy
from util import *
def p2p_port(n): def p2p_port(n):
return 11000 + n + os.getpid()%999 return 11000 + n + os.getpid()%999
@@ -153,7 +152,7 @@ def initialize_chain_clean(test_dir, num_nodes):
Useful if a test case wants complete control over initialization. Useful if a test case wants complete control over initialization.
""" """
for i in range(num_nodes): for i in range(num_nodes):
datadir=initialize_datadir(test_dir, i) initialize_datadir(test_dir, i)
def _rpchost_to_args(rpchost): def _rpchost_to_args(rpchost):

View File

@@ -8,10 +8,9 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, connect_nodes, \
from decimal import Decimal sync_blocks, gather_inputs
import os
import shutil
class TxnMallTest(BitcoinTestFramework): class TxnMallTest(BitcoinTestFramework):
@@ -77,7 +76,7 @@ class TxnMallTest(BitcoinTestFramework):
assert_equal(tx2["confirmations"], 0) assert_equal(tx2["confirmations"], 0)
# Now give doublespend to miner: # Now give doublespend to miner:
mutated_txid = self.nodes[2].sendrawtransaction(doublespend["hex"]) self.nodes[2].sendrawtransaction(doublespend["hex"])
# ... mine a block... # ... mine a block...
self.nodes[2].generate(1) self.nodes[2].generate(1)

View File

@@ -5,8 +5,13 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from time import * from test_framework.util import assert_equal, assert_greater_than, \
initialize_chain_clean, start_nodes, start_node, connect_nodes_bi, \
stop_nodes, sync_blocks, sync_mempools, wait_bitcoinds
import time
from decimal import Decimal
class WalletTest (BitcoinTestFramework): class WalletTest (BitcoinTestFramework):
@@ -112,7 +117,7 @@ class WalletTest (BitcoinTestFramework):
# Send 10 BTC normal # Send 10 BTC normal
address = self.nodes[0].getnewaddress("") address = self.nodes[0].getnewaddress("")
self.nodes[2].settxfee(Decimal('0.001')) self.nodes[2].settxfee(Decimal('0.001'))
txid = self.nodes[2].sendtoaddress(address, 10, "", "", False) self.nodes[2].sendtoaddress(address, 10, "", "", False)
self.sync_all() self.sync_all()
self.nodes[2].generate(1) self.nodes[2].generate(1)
self.sync_all() self.sync_all()
@@ -122,7 +127,7 @@ class WalletTest (BitcoinTestFramework):
assert_equal(self.nodes[0].getbalance("*"), Decimal('10.00000000')) assert_equal(self.nodes[0].getbalance("*"), Decimal('10.00000000'))
# Send 10 BTC with subtract fee from amount # Send 10 BTC with subtract fee from amount
txid = self.nodes[2].sendtoaddress(address, 10, "", "", True) self.nodes[2].sendtoaddress(address, 10, "", "", True)
self.sync_all() self.sync_all()
self.nodes[2].generate(1) self.nodes[2].generate(1)
self.sync_all() self.sync_all()
@@ -132,7 +137,7 @@ class WalletTest (BitcoinTestFramework):
assert_equal(self.nodes[0].getbalance("*"), Decimal('19.99900000')) assert_equal(self.nodes[0].getbalance("*"), Decimal('19.99900000'))
# Sendmany 10 BTC # Sendmany 10 BTC
txid = self.nodes[2].sendmany("", {address: 10}, 0, "", []) self.nodes[2].sendmany("", {address: 10}, 0, "", [])
self.sync_all() self.sync_all()
self.nodes[2].generate(1) self.nodes[2].generate(1)
self.sync_all() self.sync_all()
@@ -142,7 +147,7 @@ class WalletTest (BitcoinTestFramework):
assert_equal(self.nodes[0].getbalance("*"), Decimal('29.99900000')) assert_equal(self.nodes[0].getbalance("*"), Decimal('29.99900000'))
# Sendmany 10 BTC with subtract fee from amount # Sendmany 10 BTC with subtract fee from amount
txid = self.nodes[2].sendmany("", {address: 10}, 0, "", [address]) self.nodes[2].sendmany("", {address: 10}, 0, "", [address])
self.sync_all() self.sync_all()
self.nodes[2].generate(1) self.nodes[2].generate(1)
self.sync_all() self.sync_all()
@@ -183,7 +188,7 @@ class WalletTest (BitcoinTestFramework):
signedRawTx = self.nodes[1].signrawtransaction(rawTx) signedRawTx = self.nodes[1].signrawtransaction(rawTx)
decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex']) decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex'])
zeroValueTxid= decRawTx['txid'] zeroValueTxid= decRawTx['txid']
sendResp = self.nodes[1].sendrawtransaction(signedRawTx['hex']) self.nodes[1].sendrawtransaction(signedRawTx['hex'])
self.sync_all() self.sync_all()
self.nodes[1].generate(1) #mine a block self.nodes[1].generate(1) #mine a block
@@ -250,7 +255,7 @@ class WalletTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
mybalance = self.nodes[2].z_getbalance(mytaddr) mybalance = self.nodes[2].z_getbalance(mytaddr)
assert_equal(self.nodes[2].z_getbalance(mytaddr), Decimal('10.0')); assert_equal(mybalance, Decimal('10.0'));
mytxdetails = self.nodes[2].gettransaction(mytxid) mytxdetails = self.nodes[2].gettransaction(mytxid)
myvjoinsplits = mytxdetails["vjoinsplit"] myvjoinsplits = mytxdetails["vjoinsplit"]
@@ -318,7 +323,7 @@ class WalletTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[2].z_getoperationresult(opids) results = self.nodes[2].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
mytxid = results[0]["result"]["txid"] mytxid = results[0]["result"]["txid"]
@@ -375,7 +380,7 @@ class WalletTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[2].z_getoperationresult(opids) results = self.nodes[2].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
break break

View File

@@ -6,10 +6,12 @@
# This is a regression test for #1941. # This is a regression test for #1941.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
from time import * initialize_datadir, start_nodes, start_node, connect_nodes_bi, \
bitcoind_processes
import sys import time
from decimal import Decimal
starttime = 1388534400 starttime = 1388534400
@@ -49,7 +51,7 @@ class Wallet1941RegressionTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
if status == "failed": if status == "failed":

View File

@@ -5,8 +5,11 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_node, \
from time import * start_nodes, connect_nodes_bi, bitcoind_processes
import time
from decimal import Decimal
class WalletNullifiersTest (BitcoinTestFramework): class WalletNullifiersTest (BitcoinTestFramework):
@@ -32,7 +35,7 @@ class WalletNullifiersTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
assert_equal("success", status) assert_equal("success", status)
@@ -73,7 +76,7 @@ class WalletNullifiersTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
assert_equal("success", status) assert_equal("success", status)
@@ -105,7 +108,7 @@ class WalletNullifiersTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[2].z_getoperationresult(opids) results = self.nodes[2].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
assert_equal("success", status) assert_equal("success", status)
@@ -146,11 +149,12 @@ class WalletNullifiersTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[1].z_getoperationresult(opids) results = self.nodes[1].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
assert_equal("success", status) assert_equal("success", status)
mytxid = results[0]["result"]["txid"] mytxid = results[0]["result"]["txid"]
[mytxid] # hush pyflakes
break break
self.sync_all() self.sync_all()

View File

@@ -5,8 +5,13 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from time import * from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes, connect_nodes_bi
import sys
import time
from decimal import Decimal
class WalletProtectCoinbaseTest (BitcoinTestFramework): class WalletProtectCoinbaseTest (BitcoinTestFramework):
@@ -35,7 +40,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
if status == "failed": if status == "failed":
@@ -94,7 +99,7 @@ class WalletProtectCoinbaseTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
errorString = results[0]["error"]["message"] errorString = results[0]["error"]["message"]

View File

@@ -5,10 +5,11 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
from time import * start_nodes, connect_nodes_bi
import sys import time
from decimal import Decimal
class WalletTreeStateTest (BitcoinTestFramework): class WalletTreeStateTest (BitcoinTestFramework):
@@ -35,7 +36,7 @@ class WalletTreeStateTest (BitcoinTestFramework):
for x in xrange(1, timeout): for x in xrange(1, timeout):
results = self.nodes[0].z_getoperationresult(opids) results = self.nodes[0].z_getoperationresult(opids)
if len(results)==0: if len(results)==0:
sleep(1) time.sleep(1)
else: else:
status = results[0]["status"] status = results[0]["status"]
if status == "failed": if status == "failed":
@@ -106,7 +107,7 @@ class WalletTreeStateTest (BitcoinTestFramework):
status = results[0]["status"] status = results[0]["status"]
if status == "executing": if status == "executing":
break break
sleep(1) time.sleep(1)
# Now mine Tx 1 which will change global treestate before Tx 2's second joinsplit begins processing # Now mine Tx 1 which will change global treestate before Tx 2's second joinsplit begins processing
self.sync_all() self.sync_all()

View File

@@ -34,9 +34,16 @@ and confirm again balances are correct.
""" """
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes, start_node, connect_nodes, stop_node, \
sync_blocks, sync_mempools
import os
import shutil
from random import randint from random import randint
from decimal import Decimal
import logging import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
class WalletBackupTest(BitcoinTestFramework): class WalletBackupTest(BitcoinTestFramework):

View File

@@ -4,7 +4,9 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from test_framework.util import assert_equal, initialize_chain_clean, \
start_nodes, start_node, connect_nodes_bi, bitcoind_processes
class ZapWalletTXesTest (BitcoinTestFramework): class ZapWalletTXesTest (BitcoinTestFramework):
@@ -27,56 +29,56 @@ class ZapWalletTXesTest (BitcoinTestFramework):
self.sync_all() self.sync_all()
self.nodes[1].generate(101) self.nodes[1].generate(101)
self.sync_all() self.sync_all()
assert_equal(self.nodes[0].getbalance(), 40) assert_equal(self.nodes[0].getbalance(), 40)
txid0 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11) txid0 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
txid1 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10) txid1 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.sync_all() self.sync_all()
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
txid2 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11) txid2 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
txid3 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5) txid3 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5)
tx0 = self.nodes[0].gettransaction(txid0) tx0 = self.nodes[0].gettransaction(txid0)
assert_equal(tx0['txid'], txid0) #tx0 must be available (confirmed) assert_equal(tx0['txid'], txid0) # tx0 must be available (confirmed)
tx1 = self.nodes[0].gettransaction(txid1) tx1 = self.nodes[0].gettransaction(txid1)
assert_equal(tx1['txid'], txid1) #tx1 must be available (confirmed) assert_equal(tx1['txid'], txid1) # tx1 must be available (confirmed)
tx2 = self.nodes[0].gettransaction(txid2) tx2 = self.nodes[0].gettransaction(txid2)
assert_equal(tx2['txid'], txid2) #tx2 must be available (unconfirmed) assert_equal(tx2['txid'], txid2) # tx2 must be available (unconfirmed)
tx3 = self.nodes[0].gettransaction(txid3) tx3 = self.nodes[0].gettransaction(txid3)
assert_equal(tx3['txid'], txid3) #tx3 must be available (unconfirmed) assert_equal(tx3['txid'], txid3) # tx3 must be available (unconfirmed)
#restart bitcoind # restart zcashd
self.nodes[0].stop() self.nodes[0].stop()
bitcoind_processes[0].wait() bitcoind_processes[0].wait()
self.nodes[0] = start_node(0,self.options.tmpdir) self.nodes[0] = start_node(0,self.options.tmpdir)
tx3 = self.nodes[0].gettransaction(txid3) tx3 = self.nodes[0].gettransaction(txid3)
assert_equal(tx3['txid'], txid3) #tx must be available (unconfirmed) assert_equal(tx3['txid'], txid3) # tx must be available (unconfirmed)
self.nodes[0].stop() self.nodes[0].stop()
bitcoind_processes[0].wait() bitcoind_processes[0].wait()
#restart bitcoind with zapwallettxes # restart zcashd with zapwallettxes
self.nodes[0] = start_node(0,self.options.tmpdir, ["-zapwallettxes=1"]) self.nodes[0] = start_node(0,self.options.tmpdir, ["-zapwallettxes=1"])
aException = False aException = False
try: try:
tx3 = self.nodes[0].gettransaction(txid3) tx3 = self.nodes[0].gettransaction(txid3)
except JSONRPCException,e: except JSONRPCException,e:
print e print e
aException = True aException = True
assert_equal(aException, True) #there must be a expection because the unconfirmed wallettx0 must be gone by now assert_equal(aException, True) # there must be a expection because the unconfirmed wallettx0 must be gone by now
tx0 = self.nodes[0].gettransaction(txid0) tx0 = self.nodes[0].gettransaction(txid0)
assert_equal(tx0['txid'], txid0) #tx0 (confirmed) must still be available because it was confirmed assert_equal(tx0['txid'], txid0) # tx0 (confirmed) must still be available because it was confirmed
if __name__ == '__main__': if __name__ == '__main__':
ZapWalletTXesTest ().main () ZapWalletTXesTest().main()

View File

@@ -5,11 +5,9 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, start_node, \
from decimal import Decimal gather_inputs
import os
import shutil
import sys
class JoinSplitTest(BitcoinTestFramework): class JoinSplitTest(BitcoinTestFramework):
def setup_network(self): def setup_network(self):

View File

@@ -5,11 +5,10 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.authproxy import JSONRPCException
from decimal import Decimal from test_framework.util import assert_equal, connect_nodes, \
import os gather_inputs, sync_blocks
import shutil
import sys
import time import time
class JoinSplitTest(BitcoinTestFramework): class JoinSplitTest(BitcoinTestFramework):

View File

@@ -8,21 +8,12 @@
# #
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import * from test_framework.util import assert_equal, bytes_to_hex_str, start_nodes
import zmq import zmq
import binascii
import struct import struct
try: class ZMQTest(BitcoinTestFramework):
import http.client as httplib
except ImportError:
import httplib
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
class ZMQTest (BitcoinTestFramework):
port = 28332 port = 28332
@@ -51,8 +42,9 @@ class ZMQTest (BitcoinTestFramework):
assert_equal(topic, b"hashtx") assert_equal(topic, b"hashtx")
body = msg[1] body = msg[1]
nseq = msg[2] nseq = msg[2]
[nseq] # hush pyflakes
msgSequence = struct.unpack('<I', msg[-1])[-1] msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, 0) #must be sequence 0 on hashtx assert_equal(msgSequence, 0) # must be sequence 0 on hashtx
msg = self.zmqSubSocket.recv_multipart() msg = self.zmqSubSocket.recv_multipart()
topic = msg[0] topic = msg[0]