basicswap_miserver/tests/basicswap/test_reload.py

234 lines
8.0 KiB
Python
Raw Normal View History

2019-07-27 17:26:06 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2021-01-10 18:30:07 +00:00
# Copyright (c) 2019-2021 tecnovert
2019-07-27 17:26:06 +00:00
# Distributed under the MIT software license, see the accompanying
2020-10-30 08:55:45 +00:00
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
2019-07-27 17:26:06 +00:00
"""
export TEST_RELOAD_PATH=/tmp/test_basicswap
mkdir -p ${TEST_RELOAD_PATH}/bin/{particl,bitcoin}
2022-05-23 21:51:48 +00:00
cp ~/tmp/particl-0.21.2.9-x86_64-linux-gnu.tar.gz ${TEST_RELOAD_PATH}/bin/particl
2021-09-04 16:54:48 +00:00
cp ~/tmp/bitcoin-0.21.1-x86_64-linux-gnu.tar.gz ${TEST_RELOAD_PATH}/bin/bitcoin
export PYTHONPATH=$(pwd)
python tests/basicswap/test_reload.py
2019-07-27 17:26:06 +00:00
"""
import os
import sys
import json
2019-07-27 17:26:06 +00:00
import shutil
import logging
import unittest
import traceback
2019-10-02 20:34:03 +00:00
import threading
import multiprocessing
from urllib import parse
from urllib.request import urlopen
from unittest.mock import patch
2020-02-01 23:18:29 +00:00
from basicswap.rpc import (
callrpc_cli,
)
from tests.basicswap.mnemonics import mnemonics
2021-01-11 22:15:06 +00:00
from tests.basicswap.common import (
waitForServer,
waitForNumOffers,
waitForNumBids,
waitForNumSwapping,
)
2020-02-01 18:57:20 +00:00
import basicswap.config as cfg
2019-07-27 17:26:06 +00:00
import bin.basicswap_prepare as prepareSystem
import bin.basicswap_run as runSystem
2019-08-15 22:31:39 +00:00
test_path = os.path.expanduser(os.getenv('TEST_RELOAD_PATH', '~/test_basicswap1'))
PARTICL_PORT_BASE = int(os.getenv('PARTICL_PORT_BASE', '11938'))
BITCOIN_PORT_BASE = int(os.getenv('BITCOIN_PORT_BASE', '10938'))
2021-01-11 22:15:06 +00:00
delay_event = threading.Event()
2019-07-27 17:26:06 +00:00
logger = logging.getLogger()
logger.level = logging.DEBUG
if not len(logger.handlers):
logger.addHandler(logging.StreamHandler(sys.stdout))
def btcRpc(client_no, cmd):
bin_path = os.path.join(test_path, 'bin', 'bitcoin')
data_path = os.path.join(test_path, 'client{}'.format(client_no), 'bitcoin')
return callrpc_cli(bin_path, data_path, 'regtest', cmd, 'bitcoin-cli')
2019-10-02 20:34:03 +00:00
def updateThread():
btc_addr = btcRpc(0, 'getnewaddress mining_addr bech32')
2021-01-11 22:15:06 +00:00
while not delay_event.is_set():
2019-10-02 20:34:03 +00:00
btcRpc(0, 'generatetoaddress {} {}'.format(1, btc_addr))
2021-01-11 22:15:06 +00:00
delay_event.wait(5)
2019-10-02 20:34:03 +00:00
2019-07-27 17:26:06 +00:00
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(Test, cls).setUpClass()
for i in range(3):
client_path = os.path.join(test_path, 'client{}'.format(i))
2020-02-01 18:57:20 +00:00
config_path = os.path.join(client_path, cfg.CONFIG_FILENAME)
try:
shutil.rmtree(client_path)
except Exception as ex:
logger.warning('setUpClass %s', str(ex))
2019-08-15 22:31:39 +00:00
testargs = [
'basicswap-prepare',
'-datadir="{}"'.format(client_path),
'-bindir="{}"'.format(os.path.join(test_path, 'bin')),
'-portoffset={}'.format(i),
'-particl_mnemonic="{}"'.format(mnemonics[i]),
'-regtest', '-withoutcoin=litecoin', '-withcoin=bitcoin']
with patch.object(sys, 'argv', testargs):
prepareSystem.main()
2019-10-02 20:34:03 +00:00
with open(os.path.join(client_path, 'particl', 'particl.conf'), 'r') as fp:
lines = fp.readlines()
with open(os.path.join(client_path, 'particl', 'particl.conf'), 'w') as fp:
for line in lines:
if not line.startswith('staking'):
fp.write(line)
2019-08-15 22:31:39 +00:00
fp.write('port={}\n'.format(PARTICL_PORT_BASE + i))
fp.write('bind=127.0.0.1\n')
fp.write('dnsseed=0\n')
2021-01-16 08:21:59 +00:00
fp.write('discover=0\n')
fp.write('listenonion=0\n')
fp.write('upnp=0\n')
2019-10-02 20:34:03 +00:00
fp.write('minstakeinterval=5\n')
fp.write('smsgsregtestadjust=0\n')
for ip in range(3):
2019-10-02 20:34:03 +00:00
if ip != i:
fp.write('connect=127.0.0.1:{}\n'.format(PARTICL_PORT_BASE + ip))
# Pruned nodes don't provide blocks
with open(os.path.join(client_path, 'bitcoin', 'bitcoin.conf'), 'r') as fp:
lines = fp.readlines()
with open(os.path.join(client_path, 'bitcoin', 'bitcoin.conf'), 'w') as fp:
for line in lines:
if not line.startswith('prune'):
fp.write(line)
2019-08-15 22:31:39 +00:00
fp.write('port={}\n'.format(BITCOIN_PORT_BASE + i))
2021-01-16 08:21:59 +00:00
fp.write('bind=127.0.0.1\n')
fp.write('dnsseed=0\n')
2021-01-16 08:21:59 +00:00
fp.write('discover=0\n')
fp.write('listenonion=0\n')
fp.write('upnp=0\n')
for ip in range(3):
2019-10-02 20:34:03 +00:00
if ip != i:
fp.write('connect=127.0.0.1:{}\n'.format(BITCOIN_PORT_BASE + ip))
2019-08-15 22:31:39 +00:00
assert(os.path.exists(config_path))
def run_thread(self, client_id):
client_path = os.path.join(test_path, 'client{}'.format(client_id))
2019-08-15 22:31:39 +00:00
testargs = ['basicswap-run', '-datadir=' + client_path, '-regtest']
2019-07-27 17:26:06 +00:00
with patch.object(sys, 'argv', testargs):
runSystem.main()
def test_reload(self):
2019-10-04 18:23:33 +00:00
global stop_test
2019-08-15 22:31:39 +00:00
processes = []
2019-07-27 17:26:06 +00:00
2019-08-15 22:31:39 +00:00
for i in range(3):
processes.append(multiprocessing.Process(target=self.run_thread, args=(i,)))
processes[-1].start()
try:
2021-01-11 22:15:06 +00:00
waitForServer(delay_event, 12700)
num_blocks = 500
btc_addr = btcRpc(1, 'getnewaddress mining_addr bech32')
2020-11-21 13:16:27 +00:00
logging.info('Mining %d Bitcoin blocks to %s', num_blocks, btc_addr)
btcRpc(1, 'generatetoaddress {} {}'.format(num_blocks, btc_addr))
for i in range(20):
2021-01-11 22:15:06 +00:00
if delay_event.is_set():
raise ValueError('Test stopped.')
blocks = btcRpc(0, 'getblockchaininfo')['blocks']
if blocks >= num_blocks:
break
2021-01-11 22:15:06 +00:00
delay_event.wait(2)
assert(blocks >= num_blocks)
data = parse.urlencode({
'addr_from': '-1',
'coin_from': '1',
'coin_to': '2',
'amt_from': '1',
'amt_to': '1',
'lockhrs': '24'}).encode()
offer_id = json.loads(urlopen('http://127.0.0.1:12700/json/offers/new', data=data).read())
summary = json.loads(urlopen('http://127.0.0.1:12700/json').read())
assert(summary['num_sent_offers'] == 1)
except Exception:
traceback.print_exc()
2019-07-27 17:26:06 +00:00
logger.info('Waiting for offer:')
2021-01-11 22:15:06 +00:00
waitForNumOffers(delay_event, 12701, 1)
offers = json.loads(urlopen('http://127.0.0.1:12701/json/offers').read())
offer = offers[0]
data = parse.urlencode({
'offer_id': offer['offer_id'],
'amount_from': offer['amount_from']}).encode()
bid_id = json.loads(urlopen('http://127.0.0.1:12701/json/bids/new', data=data).read())
2021-01-11 22:15:06 +00:00
waitForNumBids(delay_event, 12700, 1)
bids = json.loads(urlopen('http://127.0.0.1:12700/json/bids').read())
2019-10-02 20:34:03 +00:00
bid = bids[0]
2019-10-02 20:34:03 +00:00
data = parse.urlencode({
'accept': True
}).encode()
rv = json.loads(urlopen('http://127.0.0.1:12700/json/bids/{}'.format(bid['bid_id']), data=data).read())
2019-10-02 20:34:03 +00:00
assert(rv['bid_state'] == 'Accepted')
2021-01-11 22:15:06 +00:00
waitForNumSwapping(delay_event, 12701, 1)
2019-10-02 20:34:03 +00:00
logger.info('Restarting client:')
c1 = processes[1]
c1.terminate()
c1.join()
processes[1] = multiprocessing.Process(target=self.run_thread, args=(1,))
processes[1].start()
2021-01-11 22:15:06 +00:00
waitForServer(delay_event, 12701)
rv = json.loads(urlopen('http://127.0.0.1:12701/json').read())
2019-10-02 20:34:03 +00:00
assert(rv['num_swapping'] == 1)
update_thread = threading.Thread(target=updateThread)
update_thread.start()
logger.info('Completing swap:')
for i in range(240):
2021-01-11 22:15:06 +00:00
delay_event.wait(5)
2019-10-02 20:34:03 +00:00
rv = json.loads(urlopen('http://127.0.0.1:12700/json/bids/{}'.format(bid['bid_id'])).read())
2019-10-02 20:34:03 +00:00
print(rv)
if rv['bid_state'] == 'Completed':
break
assert(rv['bid_state'] == 'Completed')
2021-01-11 22:15:06 +00:00
delay_event.set()
2019-10-02 20:34:03 +00:00
update_thread.join()
2019-08-15 22:31:39 +00:00
for p in processes:
p.terminate()
for p in processes:
p.join()
2019-07-27 17:26:06 +00:00
if __name__ == '__main__':
unittest.main()