def run_test(self):
        nodes = self.nodes

        nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        addr = 'pcwP4hTtaMb7n4urszBTsgxWLdNLU4yNGz'
        nodes[1].importaddress(addr, addr, True)

        ro = nodes[1].getaddressinfo(addr)
        assert (ro['ismine'] == False)
        assert (ro['iswatchonly'] == True)

        assert (isclose(nodes[1].getwalletinfo()['watchonly_balance'],
                        10000.0))
        assert (len(nodes[1].filtertransactions({'include_watchonly':
                                                 True})) == 1)

        ro = nodes[2].extkey(
            'importaccount', nodes[0].extkey('account', 'default',
                                             'true')['epkey'])
        nodes[2].extkey('setdefaultaccount', ro['account_id'])

        w0 = nodes[0].getwalletinfo()
        w2 = nodes[2].getwalletinfo()

        assert (w0['total_balance'] == w2['watchonly_total_balance'])
        assert (w0['txcount'] == w2['txcount'])

        sxaddr0 = nodes[0].getnewstealthaddress()
        sxaddrs = nodes[0].liststealthaddresses(True)
        addr_info = nodes[0].getaddressinfo(sxaddr0)
        scan_vk = sxaddrs[0]['Stealth Addresses'][0]['Scan Secret']
        spend_pk = sxaddrs[0]['Stealth Addresses'][0]['spend_public_key']
        spend_vk = sxaddrs[0]['Stealth Addresses'][0]['Spend Secret']
        ro = nodes[2].importstealthaddress(scan_vk, spend_pk)
        assert (ro['stealth_address'] == sxaddr0)
        assert (ro['watchonly'] == True)
        ro = nodes[2].getaddressinfo(sxaddr0)
        assert (ro['ismine'] == False)
        assert (ro['iswatchonly'] == True)

        txid = nodes[0].sendtoaddress(sxaddr0, 1.0)
        self.stakeBlocks(1)

        w0 = nodes[0].getwalletinfo()
        w2 = nodes[2].getwalletinfo()

        assert (w0['total_balance'] == w2['watchonly_total_balance'])
        assert (w0['txcount'] == w2['txcount'])

        nodes[2].importstealthaddress(scan_vk, spend_vk)
        ro = nodes[2].getaddressinfo(sxaddr0)
        assert (ro['ismine'] == True)
        assert (ro['iswatchonly'] == False)

        nodes[2].rescanblockchain(0)
    def run_test(self):

        # Check that darkpay has been built with USB device enabled
        config = configparser.ConfigParser()
        if not self.options.configfile:
            self.options.configfile = os.path.dirname(__file__) + "/../config.ini"
        config.read_file(open(self.options.configfile))

        if not config["components"].getboolean("ENABLE_USBDEVICE"):
            raise SkipTest("darkpayd has not been built with usb device enabled.")

        nodes = self.nodes

        nodes[0].extkeyimportmaster('abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb')
        assert(nodes[0].getwalletinfo()['total_balance'] == 100000)

        ro = nodes[1].listdevices()
        assert(len(ro) == 1)
        assert(ro[0]['vendor'] == 'Debug')
        assert(ro[0]['product'] == 'Device')

        ro = nodes[1].getdeviceinfo()
        assert(ro['device'] == 'debug')

        ro = nodes[1].getdevicepublickey('0')
        assert(ro['address'] == 'praish9BVxVdhykpqBYEs6L65AQ7iKd9z1')
        assert(ro['path'] == "m/44'/1'/0'/0")

        ro = nodes[1].getdevicepublickey('0/1')
        assert(ro['address'] == 'peWvjy33QptC2Gz3ww7jTTLPjC2QJmifBR')
        assert(ro['path'] == "m/44'/1'/0'/0/1")

        ro = nodes[1].getdevicexpub("m/44'/1'/0'", "")
        assert(ro == 'pparszKXPyRegWYwPacdPduNPNEryRbZDCAiSyo8oZYSsbTjc6FLP4TCPEX58kAeCB6YW9cSdR6fsbpeWDBTgjbkYjXCoD9CNoFVefbkg3exzpQE')

        message = 'This is just a test message'
        sig = nodes[1].devicesignmessage('0/1', message)
        assert(True == nodes[1].verifymessage('peWvjy33QptC2Gz3ww7jTTLPjC2QJmifBR', sig, message))

        ro = nodes[1].initaccountfromdevice('test_acc')
        assert(ro['extkey'] == 'pparszKXPyRegWYwPacdPduNPNEryRbZDCAiSyo8oZYSsbTjc6FLP4TCPEX58kAeCB6YW9cSdR6fsbpeWDBTgjbkYjXCoD9CNoFVefbkg3exzpQE')
        assert(ro['path'] == "m/44'/1'/0'")

        ro = nodes[1].extkey('list', 'true')
        assert(len(ro) == 1)
        assert(ro[0]['path'] == "m/44h/1h/0h")
        assert(ro[0]['epkey'] == 'pparszKXPyRegWYwPacdPduNPNEryRbZDCAiSyo8oZYSsbTjc6FLP4TCPEX58kAeCB6YW9cSdR6fsbpeWDBTgjbkYjXCoD9CNoFVefbkg3exzpQE')
        assert(ro[0]['label'] == 'test_acc')
        assert(ro[0]['hardware_device'] == '0xffff 0x0001')

        ro = nodes[1].extkey('account')
        n = getIndexAtProperty(ro['chains'], 'use_type', 'stealth_spend')
        assert(n > -1)
        assert(ro['chains'][n]['path'] == "m/0h/444445h")


        addr1_0 = nodes[1].getnewaddress('lbl1_0')
        ro = nodes[1].filteraddresses()
        assert(len(ro) == 1)
        assert(ro[0]['path'] == 'm/0/0')
        assert(ro[0]['owned'] == 'true')
        assert(ro[0]['label'] == 'lbl1_0')

        va_addr1_0 = nodes[1].getaddressinfo(addr1_0)
        assert(va_addr1_0['ismine'] == True)
        assert(va_addr1_0['iswatchonly'] == False)
        assert(va_addr1_0['isondevice'] == True)
        assert(va_addr1_0['path'] == 'm/0/0')

        try:
            nodes[1].getnewstealthaddress()
            raise AssertionError('Should have failed.')
        except JSONRPCException as e:
            pass

        extaddr1_0 = nodes[1].getnewextaddress()

        txnid0 = nodes[0].sendtoaddress(addr1_0, 6)
        txnid1 = nodes[0].sendtoaddress(extaddr1_0, 6)

        self.stakeBlocks(1)
        block_txns = nodes[0].getblock(nodes[0].getblockhash(nodes[0].getblockcount()))['tx']
        assert(txnid0 in block_txns)
        assert(txnid1 in block_txns)

        ro = nodes[1].getwalletinfo()
        assert(isclose(ro['balance'], 12.0))

        addr0_0 = nodes[0].getnewaddress()
        hexRaw = nodes[1].createrawtransaction([], {addr0_0:10})
        hexFunded = nodes[1].fundrawtransaction(hexRaw)['hex']
        txDecoded = nodes[1].decoderawtransaction(hexFunded)

        ro = nodes[1].devicesignrawtransaction(hexFunded)
        assert(ro['complete'] == True)

        txnid1 = nodes[1].sendrawtransaction(ro['hex'])

        self.sync_all()
        self.stakeBlocks(1)

        ro = nodes[1].devicesignrawtransaction(hexFunded)
        assert(ro['errors'][0]['error'] == 'Input not found or already spent')

        prevtxns = []
        for vin in txDecoded['vin']:
            rtx = nodes[1].getrawtransaction(vin['txid'], True)
            prev_out = rtx['vout'][vin['vout']]
            prevtxns.append({'txid': vin['txid'], 'vout': vin['vout'], 'scriptPubKey': prev_out['scriptPubKey']['hex'], 'amount': prev_out['value']})
        ro = nodes[1].devicesignrawtransaction(hexFunded, prevtxns, ['0/0', '2/0'])
        assert(ro['complete'] == True)

        ro = nodes[1].listunspent()
        assert(ro[0]['ondevice'] == True)


        txnid2 = nodes[1].sendtoaddress(addr0_0, 0.1)

        self.sync_all()

        assert(nodes[0].filtertransactions()[0]['txid'] == txnid2)

        hwsxaddr = nodes[1].devicegetnewstealthaddress()
        assert(hwsxaddr == 'tps1qqpdwu7gqjqz9s9wfek843akvkzvw0xq3tkzs93sj4ceq60cp54mvzgpqf4tp6d7h0nza2xe362am697dax24hcr33yxqwvq58l5cf6j6q5hkqqqgykgrc')

        hwsxaddr2 = nodes[1].devicegetnewstealthaddress('lbl2 4bits', '4', '0xaaaa', True)
        assert(hwsxaddr2 == 'tps1qqpewyspjp93axk82zahx5xfjyprpvypfgnp95n9aynxxw3w0qs63acpq0s5z2rwk0raczg8jszl9qy5stncud76ahr5etn9hqmp30e3e86w2qqypgh9sgv0')

        ro = nodes[1].getaddressinfo(hwsxaddr2)
        assert(ro['prefix_num_bits'] == 4)
        assert(ro['prefix_bitfield'] == '0x000a')
        assert(ro['isondevice'] == True)

        ro = nodes[1].liststealthaddresses()
        assert(len(ro[0]['Stealth Addresses']) == 2)


        ro = nodes[1].filteraddresses()
        assert(len(ro) == 3)


        txnid3 = nodes[0].sendtoaddress(hwsxaddr, 0.1, '', '', False, 'test msg')
        self.stakeBlocks(1)

        ro = nodes[1].listtransactions()
        assert(len(ro) == 5)
        assert('test msg' in self.dumpj(ro[4]))

        ro = nodes[1].listunspent()
        inputs = []
        for output in ro:
            if output['txid'] == txnid3:
                inputs.append({'txid' : txnid3, 'vout' : output['vout']})
                break
        assert(len(inputs) > 0)
        hexRaw = nodes[1].createrawtransaction(inputs, {addr0_0:0.09})

        ro = nodes[1].devicesignrawtransaction(hexRaw)
        assert(ro['complete'] == True)

        # import privkey in node2
        rootkey = nodes[2].extkeyaltversion('xparFdrwJK7K2nfYzrkEqAKr5EcJNdY4c6ZNoLFFx1pMXQSQpo5MAufjogrS17RkqsLAijZJaBDHhG3G7SuJjtsTmRRTEKZDzGMnVCeX59cQCiR')
        ro = nodes[2].extkey('import', rootkey, 'master key', True)
        ro = nodes[2].extkey('setmaster', ro['id'])
        assert(ro['result'] == 'Success.')
        ro = nodes[2].extkey('deriveaccount', 'test account')
        ro = nodes[2].extkey('setdefaultaccount', ro['account'])
        assert(ro['result'] == 'Success.')

        ro = nodes[1].extkey('account')
        n = getIndexAtProperty(ro['chains'], 'use_type', 'stealth_spend')
        assert(n > -1)
        assert(ro['chains'][n]['path'] == "m/0h/444445h")

        addrtest = nodes[2].getnewaddress()
        ro = nodes[1].getdevicepublickey('0/0')
        assert(addrtest == ro['address'])


        addrtest = nodes[2].getnewstealthaddress('', '0', '', True, True)
        assert(addrtest == hwsxaddr)

        addrtest2 = nodes[2].getnewstealthaddress('lbl2 4bits', '4', '0xaaaa', True, True)
        assert(addrtest2 == hwsxaddr2)

        extaddr2_0 = nodes[2].getnewextaddress()
        assert(extaddr1_0 == extaddr2_0)

        # Ensure account matches after node restarts
        account1 = nodes[1].extkey('account')
        self.restart_node(1)
        account1_r = nodes[1].extkey('account')
        assert(json.dumps(account1) == json.dumps(account1_r))

        # Test for coverage
        assert(nodes[1].promptunlockdevice()['sent'] is True)
        assert(nodes[1].unlockdevice('123')['unlocked'] is True)
        assert_raises_rpc_error(-8, 'Neither a pin nor a passphraseword was provided.', nodes[1].unlockdevice)
        assert('complete' in nodes[1].devicebackup())
        assert('complete' in nodes[1].deviceloadmnemonic())
    def run_test(self):
        nodes = self.nodes

        ro = nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (ro['account_id'] == 'aaaZf2qnNr5T7PWRmqgmusuu5ACnBcX2ev')
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        nodes[3].extkeyimportmaster(
            'pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic',
            '', 'true')
        nodes[3].getnewextaddress('lblExtTest')
        nodes[3].rescanblockchain()
        assert (nodes[3].getwalletinfo()['total_balance'] == 25000)

        txnHashes = []

        nodes[1].extkeyimportmaster(
            'drip fog service village program equip minute dentist series hawk crop sphere olympic lazy garbage segment fox library good alley steak jazz force inmate'
        )
        sxAddrTo1_1 = nodes[1].getnewstealthaddress('lblsx11')
        assert (
            sxAddrTo1_1 ==
            'TetbYTGv5LiqyFiUD3a5HHbpSinQ9KiRYDGAMvRzPfz4RnHMbKGAwDr1fjLGJ5Eqg1XDwpeGyqWMiwdK3qM3zKWjzHNpaatdoHVzzA'
        )

        txnHash = nodes[0].sendparttoblind(sxAddrTo1_1, 3.4, '', '', False,
                                           'node0 -> node1 p->b')
        txnHashes.append(txnHash)

        ro = nodes[0].listtransactions()
        assert (len(ro) == 10)
        assert (ro[9]['narration'] == 'node0 -> node1 p->b')

        ro = nodes[0].getwalletinfo()
        assert (isclose(ro['total_balance'], 99996.597968))
        assert (self.wait_for_mempool(nodes[1], txnHash))

        sync_mempools([nodes[0], nodes[1]])
        ro = nodes[1].getwalletinfo()
        assert (isclose(ro['unconfirmed_blind'], 3.4))

        ro = nodes[1].transactionblinds(txnHash)
        assert (len(ro) == 2)

        ro = nodes[1].listtransactions()
        assert (len(ro) == 2)
        assert (ro[1]['narration'] == 'node0 -> node1 p->b')

        self.stakeBlocks(2)

        nodes[2].extkeyimportmaster(nodes[2].mnemonic('new')['master'])
        sxAddrTo2_1 = nodes[2].getnewstealthaddress('lblsx21')

        txnHash3 = nodes[1].sendblindtoblind(sxAddrTo2_1, 0.2, '', '', False,
                                             'node1 -> node2 b->b')

        ro = nodes[1].getwalletinfo()
        assert (ro['blind_balance'] < 3.2 and ro['blind_balance'] > 3.1)

        ro = nodes[1].listtransactions()
        assert (len(ro) == 3)
        fFound = False
        for e in ro:
            if e['category'] == 'send':
                assert (e['type'] == 'blind')
                assert (isclose(e['amount'], -0.2))
                fFound = True
        assert (fFound)

        assert (self.wait_for_mempool(nodes[2], txnHash3))

        ro = nodes[2].getwalletinfo()
        assert (isclose(ro['unconfirmed_blind'], 0.2))

        ro = nodes[2].listtransactions()
        assert (len(ro) == 1)
        e = ro[0]
        assert (e['category'] == 'receive')
        assert (e['type'] == 'blind')
        assert (isclose(e['amount'], 0.2))
        assert (e['stealth_address'] == sxAddrTo2_1)

        txnHash4 = nodes[1].sendblindtopart(sxAddrTo2_1, 0.5, '', '', False,
                                            'node1 -> node2 b->p')

        ro = nodes[1].getwalletinfo()
        assert (ro['blind_balance'] < 2.7 and ro['blind_balance'] > 2.69)

        ro = nodes[1].listtransactions()
        assert (len(ro) == 4)
        fFound = False
        for e in ro:
            if e['category'] == 'send' and e['type'] == 'standard':
                assert (isclose(e['amount'], -0.5))
                fFound = True
        assert (fFound)

        assert (self.wait_for_mempool(nodes[2], txnHash4))

        ro = nodes[2].getwalletinfo()
        assert (isclose(ro['unconfirmed_balance'], 0.5))
        assert (isclose(ro['unconfirmed_blind'], 0.2))

        ro = nodes[2].listtransactions()
        assert (len(ro) == 2)

        sxAddrTo2_3 = nodes[2].getnewstealthaddress('n2 sx+prefix', '4',
                                                    '0xaaaa')
        ro = nodes[2].validateaddress(sxAddrTo2_3)
        assert (ro['isvalid'] == True)
        assert (ro['isstealthaddress'] == True)
        assert (ro['prefix_num_bits'] == 4)
        assert (ro['prefix_bitfield'] == '0x000a')

        txnHash5 = nodes[0].sendparttoblind(sxAddrTo2_3, 0.5, '', '', False,
                                            'node0 -> node2 p->b')

        assert (self.wait_for_mempool(nodes[2], txnHash5))

        ro = nodes[2].listtransactions()
        assert (ro[-1]['txid'] == txnHash5)

        ro = nodes[0].getwalletinfo()
        # Some of the balance will have staked
        assert (isclose(ro['balance'] + ro['staked_balance'], 99996.09874074))
        availableBalance = ro['balance']

        # Check node0 can spend remaining coin
        addrTo0_2 = nodes[0].getnewaddress()
        txnHash2 = nodes[0].sendtoaddress(addrTo0_2, availableBalance, '', '',
                                          True, 'node0 spend remaining')
        txnHashes.append(txnHash2)

        nodes[0].syncwithvalidationinterfacequeue()
        assert (isclose(nodes[0].getwalletinfo()['total_balance'],
                        99996.09670674))
        assert (isclose(nodes[1].getwalletinfo()['blind_balance'], 2.69580200))

        unspent = nodes[2].listunspentblind(minconf=0)
        assert (len(unspent[0]['stealth_address']))
        assert (len(unspent[0]['label']))

        self.log.info('Test lockunspent')
        unspent = nodes[1].listunspentblind(minconf=0)
        assert (nodes[1].lockunspent(False, [unspent[0]]) == True)
        assert (len(nodes[1].listlockunspent()) == 1)
        assert (len(nodes[1].listunspentblind(minconf=0)) < len(unspent))
        assert (nodes[1].lockunspent(True, [unspent[0]]) == True)
        assert (len(nodes[1].listunspentblind(minconf=0)) == len(unspent))

        outputs = [
            {
                'address': sxAddrTo2_3,
                'amount': 2.691068,
                'subfee': True
            },
        ]
        ro = nodes[1].sendtypeto('blind', 'part', outputs, 'comment_to',
                                 'comment_from', 4, 64, True)
        feePerKB = (1000.0 / ro['bytes']) * float(ro['fee'])
        assert (feePerKB > 0.001 and feePerKB < 0.004)

        ro = nodes[1].sendtypeto('blind', 'blind', outputs, 'comment_to',
                                 'comment_from', 4, 64, True)
        feePerKB = (1000.0 / ro['bytes']) * float(ro['fee'])
        assert (feePerKB > 0.001 and feePerKB < 0.004)

        nodes[1].sendtypeto('blind', 'part', outputs)

        try:
            ro = nodes[1].sendtypeto('blind', 'blind', outputs)
            raise AssertionError('Should have failed.')
        except JSONRPCException as e:
            assert ('Insufficient blinded funds' in e.error['message'])

        self.log.info(
            'Test sending to normal addresses which the wallet knows a pubkey for'
        )
        addrPlain = nodes[0].getnewaddress()
        addrLong = nodes[0].getnewaddress('', False, False, True)
        outputs = [{
            'address': addrPlain,
            'amount': 1.0
        }, {
            'address': addrLong,
            'amount': 1.0
        }]
        nodes[0].sendtypeto('part', 'blind', outputs)

        self.log.info('Test sending all blind to blind')
        bal0 = nodes[0].getwalletinfo()

        assert (isclose(bal0['blind_balance'], 2.0))
        outputs = [{
            'address': sxAddrTo1_1,
            'amount': bal0['blind_balance'],
            'subfee': True
        }]
        nodes[0].sendtypeto('blind', 'blind', outputs)

        self.sync_all()
        self.stakeBlocks(1, nStakeNode=3)

        self.log.info('Test sending all blind to part')
        bal1 = nodes[1].getwalletinfo()

        assert (isclose(bal1['blind_balance'], 2.002582))
        outputs = [{
            'address': sxAddrTo1_1,
            'amount': bal1['blind_balance'],
            'subfee': True
        }]
        nodes[1].sendtypeto('blind', 'part', outputs)

        bal1 = nodes[1].getwalletinfo()
        assert (isclose(bal1['blind_balance'], 0.00000001))

        ro = nodes[2].getblockstats(nodes[2].getblockchaininfo()['blocks'])
        assert (ro['height'] == 3)

        self.log.info('Test gettxoutsetinfobyscript')
        ro = nodes[0].gettxoutsetinfobyscript()
        assert (ro['height'] == 3)
        assert (ro['paytopubkeyhash']['num_blinded'] > 5)
    def run_test(self):
        nodes = self.nodes

        nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        nodes[1].extkeyimportmaster(
            'pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic',
            '', 'true')
        nodes[1].getnewextaddress('lblExtTest')
        nodes[1].rescanblockchain()
        assert (nodes[1].getwalletinfo()['total_balance'] == 25000)

        address0 = nodes[0].getnewaddress()
        address1 = nodes[1].getnewaddress()
        nodes[0].smsgaddlocaladdress(address0)
        nodes[1].smsgaddaddress(
            address0, nodes[0].smsglocalkeys()['wallet_keys'][0]['public_key'])

        text = 'Some text to test'
        ro = nodes[1].smsgsend(address1, address0, text, True, 10, True)
        assert (ro['result'] == 'Not Sent.')
        assert (isclose(ro['fee'], 0.00159000))

        assert (nodes[0].smsggetfeerate() == 50000)
        assert (nodes[1].smsggetfeerate() == 50000)

        ro = nodes[0].walletsettings('stakingoptions',
                                     {'smsgfeeratetarget': 0.001})
        assert (float(ro['stakingoptions']['smsgfeeratetarget']) == 0.001)

        self.stakeBlocks(49)
        assert (nodes[0].smsggetfeerate() == 50000)

        ro = nodes[1].smsgsend(address1, address0, text, True, 10)
        assert (ro['result'] == 'Sent.')
        assert ('msgid' in ro)
        assert ('txid' in ro)
        assert (isclose(ro['fee'], 0.00159000))

        self.stakeBlocks(1)
        assert (nodes[0].smsggetfeerate() == 61939)

        ro = nodes[1].smsgsend(address1, address0, text, True, 10, True)
        assert (ro['result'] == 'Not Sent.')
        assert (isclose(ro['fee'], 0.00189080))

        ro = nodes[1].getblock(nodes[1].getblockhash(50), 2)
        assert (ro['tx'][0]['vout'][0]['smsgfeerate'] * COIN == 61939)
        assert (ro['tx'][0]['vout'][0]['smsgdifficulty'] == '1f0fffff')

        ro = nodes[0].walletsettings(
            'stakingoptions', {
                'smsgdifficultytarget':
                '000000000000bfffffffffffffffffffffffffffffffffffffffffffffffffff',
                'smsgfeeratetarget': 0.001
            })
        assert (float(ro['stakingoptions']['smsgfeeratetarget']) == 0.001)
        assert (
            ro['stakingoptions']['smsgdifficultytarget'] ==
            '000000000000bfffffffffffffffffffffffffffffffffffffffffffffffffff')

        self.sync_all()

        self.stakeBlocks(1)
        assert (nodes[0].smsggetfeerate() == 61939)

        ro = nodes[1].getrawtransaction(
            nodes[1].getblockreward(51)['coinstake'], True)
        block_51_smsgfeerate = ro['vout'][0]['smsgfeerate'] * COIN
        block_51_smsgdifficulty = int(ro['vout'][0]['smsgdifficulty'], 16)
        assert (block_51_smsgfeerate > 61939)
        assert (block_51_smsgdifficulty < 0x1f0fffff)

        self.waitForSmsgExchange(1, 1, 0)

        ro = nodes[0].smsginbox('all')
        assert (len(ro['messages']) == 1)
        assert (ro['messages'][0]['text'] == text)

        self.log.info('Verify node settings survive a restart')
        self.stop_node(0)
        self.start_node(0, self.extra_args[0])
        connect_nodes(self.nodes[0], 1)

        ro = nodes[0].walletsettings('stakingoptions')
        assert (float(ro['stakingoptions']['smsgfeeratetarget']) == 0.001)
        assert (
            ro['stakingoptions']['smsgdifficultytarget'] ==
            '000000000000bfffffffffffffffffffffffffffffffffffffffffffffffffff')

        self.stakeBlocks(1)

        ro = nodes[1].getblock(nodes[1].getblockhash(52), 2)
        assert (ro['tx'][0]['vout'][0]['smsgfeerate'] * COIN >
                block_51_smsgfeerate)
        assert (int(ro['tx'][0]['vout'][0]['smsgdifficulty'], 16) <
                block_51_smsgdifficulty)
示例#5
0
    def run_test(self):
        tmpdir = self.options.tmpdir
        nodes = self.nodes

        nodes[0].extkeyimportmaster(nodes[0].mnemonic('new')['master'])
        nodes[1].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )

        address0 = nodes[0].getnewaddress()  # Will be different each run
        address1 = nodes[1].getnewaddress()
        assert (address1 == 'pX9N6S76ZtA5BfsiJmqBbjaEgLMHpt58it')

        sx_addr0 = nodes[0].getnewstealthaddress()
        nodes[1].sendtypeto('part', 'part', [
            {
                'address': sx_addr0,
                'amount': 20
            },
        ])

        ro = nodes[0].smsglocalkeys()
        assert (len(ro['wallet_keys']) == 0)

        ro = nodes[0].smsgaddlocaladdress(address0)
        assert ('Receiving messages enabled for address' in ro['result'])

        ro = nodes[0].smsglocalkeys()
        assert (len(ro['wallet_keys']) == 1)

        ro = nodes[1].smsgaddaddress(address0,
                                     ro['wallet_keys'][0]['public_key'])
        assert (ro['result'] == 'Public key added to db.')

        text_1 = "['data':'test','value':1]"
        ro = nodes[1].smsgsend(address1, address0, text_1, True, 4, True)
        assert (ro['result'] == 'Not Sent.')
        assert (isclose(ro['fee'], 0.00086600))

        ro = nodes[1].smsgsend(address1, address0, text_1, True, 4)
        assert (ro['result'] == 'Sent.')

        self.stakeBlocks(1, nStakeNode=1)
        for i in range(20):
            nodes[0].sendtypeto('part', 'anon', [
                {
                    'address': sx_addr0,
                    'amount': 0.5
                },
            ])
        self.waitForSmsgExchange(1, 1, 0)

        ro = nodes[0].smsginbox()
        assert (len(ro['messages']) == 1)
        assert (ro['messages'][0]['text'] == text_1)

        self.log.info('Test smsgimportprivkey and smsgdumpprivkey')
        test_privkey = '7pHSJFY1tNwi6d68UttGzB8YnXq2wFWrBVoadLv4Y6ekJD3L1iKs'
        address0_1 = 'pasdoMwEn35xQUXFvsChWAQjuG8rEKJQW9'
        nodes[0].smsgimportprivkey(test_privkey, 'smsg test key')
        assert (nodes[0].smsgdumpprivkey(address0_1) == test_privkey)

        text_2 = "['data':'test','value':2]"
        ro = nodes[0].smsglocalkeys()
        assert (len(ro['smsg_keys']) == 1)
        assert (ro['smsg_keys'][0]['address'] == address0_1)

        ro = nodes[1].smsgaddaddress(address0_1,
                                     ro['smsg_keys'][0]['public_key'])
        assert (ro['result'] == 'Public key added to db.')

        ro = nodes[1].smsgsend(address1, address0_1, text_2, True, 4)
        assert (ro['result'] == 'Sent.')

        self.stakeBlocks(1, nStakeNode=1)
        self.waitForSmsgExchange(2, 1, 0)

        ro = nodes[0].smsginbox()
        assert (len(ro['messages']) == 1)
        assert (ro['messages'][0]['text'] == text_2)

        nodes[0].encryptwallet('qwerty234')
        time.sleep(2)

        ro = nodes[0].getwalletinfo()
        assert (ro['encryptionstatus'] == 'Locked')

        localkeys0 = nodes[0].smsglocalkeys()
        assert (len(localkeys0['smsg_keys']) == 1)
        assert (len(localkeys0['wallet_keys']) == 1)
        assert (localkeys0['smsg_keys'][0]['address'] == address0_1)
        assert (localkeys0['wallet_keys'][0]['address'] == address0)

        text_3 = "['data':'test','value':3]"
        ro = nodes[0].smsglocalkeys()
        assert (len(ro['smsg_keys']) == 1)
        assert (ro['smsg_keys'][0]['address'] == address0_1)

        ro = nodes[1].smsgsend(address1, address0, 'Non paid msg')
        assert (ro['result'] == 'Sent.')

        ro = nodes[1].smsgsend(address1, address0_1, text_3, True, 4)
        assert (ro['result'] == 'Sent.')
        assert (len(ro['txid']) == 64)

        self.sync_all()
        self.stakeBlocks(1, nStakeNode=1)
        self.waitForSmsgExchange(4, 1, 0)

        msgid = ro['msgid']
        for i in range(5):
            try:
                ro = nodes[1].smsg(msgid)
                assert (ro['location'] == 'outbox')
                break
            except Exception as e:
                time.sleep(1)
        assert (ro['text'] == text_3)
        assert (ro['from'] == address1)
        assert (ro['to'] == address0_1)

        ro = nodes[0].walletpassphrase("qwerty234", 300)
        ro = nodes[0].smsginbox()
        assert (len(ro['messages']) == 2)
        flat = self.dumpj(ro)
        assert ('Non paid msg' in flat)
        assert (text_3 in flat)

        ro = nodes[0].walletlock()

        ro = nodes[0].smsginbox("all")
        assert (len(ro['messages']) == 4)
        flat = self.dumpj(ro)
        assert (flat.count('Wallet is locked') == 2)

        ro = nodes[0].smsg(msgid)
        assert (ro['read'] == True)

        ro = nodes[0].smsg(msgid, {'setread': False})
        assert (ro['read'] == False)

        ro = nodes[0].smsg(msgid, {'delete': True})
        assert (ro['operation'] == 'Deleted')

        try:
            ro = nodes[0].smsg(msgid)
            assert (False), 'Read deleted msg.'
        except:
            pass

        ro = nodes[0].smsggetpubkey(address0_1)
        assert (
            ro['publickey'] == 'h2UfzZxbhxQPcXDfYTBRGSC7GM77qrLjhtqcmfAnAia9')

        filepath = tmpdir + '/sendfile.txt'
        msg = b"msg in file\0after null sep"
        with open(filepath, 'wb', encoding=None) as fp:
            fp.write(msg)

        sendoptions = {'fromfile': True}
        ro = nodes[1].smsgsend(address1, address0_1, filepath, True, 4, False,
                               sendoptions)
        assert (ro['result'] == 'Sent.')
        msgid = ro['msgid']

        sendoptions = {'decodehex': True}
        ro = nodes[1].smsgsend(address1, address0_1,
                               binascii.hexlify(msg).decode("utf-8"), True, 4,
                               False, sendoptions)
        msgid2 = ro['msgid']
        self.stakeBlocks(1, nStakeNode=1)

        for i in range(5):
            try:
                ro = nodes[1].smsg(msgid, {'encoding': 'hex'})
                assert (ro['location'] == 'outbox')
                break
            except:
                time.sleep(1)
        assert (msg == bytes.fromhex(ro['hex'][:-2])
                )  # Extra null byte gets tacked on

        for i in range(5):
            try:
                ro = nodes[1].smsg(msgid2, {'encoding': 'hex'})
                assert (ro['location'] == 'outbox')
                break
            except:
                time.sleep(1)
        assert (msg == bytes.fromhex(ro['hex'][:-2]))
        assert (ro['daysretention'] == 4)

        ro = nodes[0].smsgoptions('list', True)
        assert (len(ro['options']) == 3)
        assert (len(ro['options'][0]['description']) > 0)

        ro = nodes[0].smsgoptions('set', 'newAddressAnon', 'false')
        assert ('newAddressAnon = false' in json.dumps(ro))

        addr = nodes[0].getnewaddress('smsg test')
        pubkey = nodes[0].getaddressinfo(addr)['pubkey']
        ro = nodes[1].smsgaddaddress(addr, pubkey)
        assert ('Public key added to db' in json.dumps(ro))

        # Wait for sync
        i = 0
        for i in range(10):
            ro = nodes[0].smsginbox('all')
            if len(ro['messages']) >= 5:
                break
            time.sleep(1)
        assert (i < 10)

        self.log.info('Test filtering')
        ro = nodes[0].smsginbox('all', "'vAlue':2")
        assert (len(ro['messages']) == 1)

        ro = nodes[1].smsgoutbox('all', "'vAlue':2")
        assert (len(ro['messages']) == 1)

        self.log.info('Test clear and rescan')
        ro = nodes[0].smsginbox('clear')
        assert ('Deleted 5 messages' in ro['result'])

        ro = nodes[0].walletpassphrase("qwerty234", 300)
        ro = nodes[0].smsgscanbuckets()
        assert ('Scan Buckets Completed' in ro['result'])

        ro = nodes[0].smsginbox('all')
        # Recover 5 + 1 dropped msg
        assert (len(ro['messages']) == 6)

        self.log.info('Test smsglocalkeys')
        addr = nodes[0].getnewaddress()

        ro = nodes[0].smsglocalkeys('recv', '+', addr)
        assert ('Address not found' in ro['result'])
        ro = nodes[0].smsglocalkeys('anon', '+', addr)
        assert ('Address not found' in ro['result'])

        ro = nodes[0].smsgaddlocaladdress(addr)
        assert ('Receiving messages enabled for address' in ro['result'])

        ro = nodes[0].smsglocalkeys('recv', '-', addr)
        assert ('Receive off' in ro['key'])
        assert (addr in ro['key'])

        ro = nodes[0].smsglocalkeys('anon', '-', addr)
        assert ('Anon off' in ro['key'])
        assert (addr in ro['key'])

        ro = nodes[0].smsglocalkeys('all')

        n = getIndexAtProperty(ro['wallet_keys'], 'address', addr)
        assert (ro['wallet_keys'][n]['receive'] == '0')
        assert (ro['wallet_keys'][n]['anon'] == '0')

        self.log.info('Test smsgpurge')
        ro = nodes[0].smsg(msgid, {'encoding': 'hex'})
        assert (ro['msgid'] == msgid)

        nodes[0].smsgpurge(msgid)

        try:
            nodes[0].smsg(msgid, {'encoding': 'hex'})
            assert (False), 'Purged message in inbox'
        except JSONRPCException as e:
            assert ('Unknown message id' in e.error['message'])

        ro = nodes[0].smsgbuckets()
        assert (int(ro['total']['numpurged']) == 1)
        # Sum all buckets
        num_messages = 0
        num_active = 0
        for b in ro['buckets']:
            num_messages += int(b['no. messages'])
            num_active += int(b['active messages'])
        assert (num_messages == num_active + 1)

        self.log.info('Test listunspent include_immature')
        without_immature = nodes[1].listunspent()

        with_immature = nodes[1].listunspent(
            query_options={'include_immature': True})
        assert (len(with_immature) > len(without_immature))

        self.log.info('Test encoding options')
        options = {'encoding': 'hex'}
        ro = nodes[0].smsginbox('all', '', options)
        assert (len(ro['messages']) == 5)
        for msg in ro['messages']:
            assert ('hex' in msg)
        options = {'encoding': 'text'}
        ro = nodes[0].smsginbox('all', '', options)
        assert (len(ro['messages']) == 5)
        for msg in ro['messages']:
            assert ('text' in msg)
        options = {'encoding': 'none'}
        ro = nodes[0].smsginbox('all', '', options)
        assert (len(ro['messages']) == 5)
        for msg in ro['messages']:
            assert ('text' not in msg)
            assert ('hex' not in msg)

        self.log.info('Test disablewallet')
        assert ('SMSG' in nodes[2].getnetworkinfo()['localservices_str'])
        assert_raises_rpc_error(-32601, 'Method not found',
                                nodes[2].getwalletinfo)
        for i in range(20):
            if nodes[0].smsgbuckets('total')['total']['messages'] != nodes[
                    2].smsgbuckets('total')['total']['messages']:
                time.sleep(0.5)
                continue
            break
        assert (nodes[0].smsgbuckets('total')['total']['messages'] ==
                nodes[2].smsgbuckets('total')['total']['messages'])

        self.log.info('Test smsggetinfo and smsgsetwallet')
        ro = nodes[0].smsggetinfo()
        assert (ro['enabled'] is True)
        assert (ro['active_wallet'] == '')
        assert_raises_rpc_error(-1, 'Wallet not found: "abc"',
                                nodes[0].smsgsetwallet, 'abc')
        nodes[0].smsgsetwallet()
        ro = nodes[0].smsggetinfo()
        assert (ro['enabled'] is True)
        assert (ro['active_wallet'] == 'Not set.')
        nodes[0].createwallet('new_wallet')
        assert (len(nodes[0].listwallets()) == 2)
        nodes[0].smsgsetwallet('new_wallet')
        ro = nodes[0].smsggetinfo()
        assert (ro['enabled'] is True)
        assert (ro['active_wallet'] == 'new_wallet')
        nodes[0].smsgdisable()
        ro = nodes[0].smsggetinfo()
        assert (ro['enabled'] is False)
        nodes[0].smsgenable()
        ro = nodes[0].smsggetinfo()
        assert (ro['enabled'] is True)

        self.log.info('Test funding from RCT balance')
        nodes[1].smsginbox()  # Clear inbox
        ro = nodes[1].smsgaddlocaladdress(address1)
        assert ('Receiving messages enabled for address' in ro['result'])

        msg = 'Test funding from RCT balance'
        sendoptions = {'fund_from_rct': True, 'rct_ring_size': 6}
        sent_msg = nodes[0].smsgsend(address0, address1, msg, True, 4, False,
                                     sendoptions)
        assert (sent_msg['result'] == 'Sent.')
        fund_tx = nodes[0].getrawtransaction(sent_msg['txid'], True)
        assert (fund_tx['vin'][0]['type'] == 'anon')

        ro = nodes[0].smsgoutbox('all', '', {'sending': True})
        assert (ro['messages'][0]['msgid'] == sent_msg['msgid'])

        sync_mempools([nodes[0], nodes[1]])
        self.stakeBlocks(1, nStakeNode=1)
        i = 0
        for i in range(20):
            ro = nodes[1].smsginbox()
            if len(ro['messages']) > 0:
                break
            time.sleep(1)
        assert (i < 19)
        assert (msg == ro['messages'][0]['text'])

        ro = nodes[0].smsgoutbox('all', '', {'sending': True})
        assert (len(ro['messages']) == 0)
示例#6
0
    def run_test(self):
        nodes = self.nodes

        ro = nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (ro['account_id'] == 'aaaZf2qnNr5T7PWRmqgmusuu5ACnBcX2ev')
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        nodes[1].extkeyimportmaster(nodes[1].mnemonic('new')['master'])
        nodes[2].extkeyimportmaster(
            'sección grito médula hecho pauta posada nueve ebrio bruto buceo baúl mitad'
        )

        addrTo256 = nodes[2].getnewaddress('256 test', 'True', 'False', 'True')
        assert (
            addrTo256 ==
            'tpl16a6gjrpfwkqrf8fveajkek07l6a0pxgaayk4y6gyq9zlkxxk2hqqmld6tr')
        [nodes[0].sendtoaddress(addrTo256, 1000) for i in range(4)]

        self.log.info('Test reserve balance')
        nodes[0].walletsettings('stakelimit', {'height': 1})
        assert (isclose(nodes[0].getwalletinfo()['reserve'], 10000000.0))

        ro = nodes[0].reservebalance(True, 100)
        assert (ro['reserve'] == True)
        assert (isclose(ro['amount'], 100.0))

        ro = nodes[0].getwalletinfo()
        assert (ro['reserve'] == 100)

        ro = nodes[0].reservebalance(False)
        assert (ro['reserve'] == False)
        assert (ro['amount'] == 0)

        ro = nodes[0].getwalletinfo()
        assert (ro['reserve'] == 0)

        assert (self.wait_for_height(nodes[0], 1))
        ro = nodes[0].reservebalance(True, 10000000)

        addrTo = nodes[1].getnewaddress()
        txnHash = nodes[0].sendtoaddress(addrTo, 10)
        ro = nodes[0].getmempoolentry(txnHash)
        assert (ro['height'] == 1)

        ro = nodes[0].listtransactions()
        fPass = False
        for txl in ro:
            if txl['address'] == addrTo and txl['amount'] == -10 and txl[
                    'category'] == 'send':
                fPass = True
                break
        assert (fPass), "node0, listtransactions failed."

        assert (self.wait_for_mempool(nodes[1], txnHash))

        ro = nodes[1].listtransactions()
        assert (len(ro) == 1)
        assert (ro[0]['address'] == addrTo)
        assert (ro[0]['amount'] == 10)
        assert (ro[0]['category'] == 'receive')

        self.stakeBlocks(1)
        block2_hash = nodes[0].getblockhash(2)
        ro = nodes[0].getblock(block2_hash)
        assert (txnHash in ro['tx'])

        addrReward = nodes[0].getnewaddress()
        ro = nodes[0].walletsettings('stakingoptions',
                                     {'rewardaddress': addrReward})
        assert (ro['stakingoptions']['rewardaddress'] == addrReward)

        addrReward_stakeonly = nodes[0].validateaddress(
            addrReward, True)['stakeonly_address']
        try:
            ro = nodes[0].walletsettings(
                'stakingoptions', {'rewardaddress': addrReward_stakeonly})
            raise AssertionError('Should have failed.')
        except JSONRPCException as e:
            assert ('Invalid rewardaddress' in e.error['message'])

        self.stakeBlocks(1)
        block3_hash = nodes[0].getblockhash(3)
        coinstakehash = nodes[0].getblock(block3_hash)['tx'][0]
        ro = nodes[0].getrawtransaction(coinstakehash, True)

        fFound = False
        for vout in ro["vout"]:
            try:
                addr0 = vout['scriptPubKey']['addresses'][0]
            except:
                continue
            if addr0 == addrReward:
                fFound = True
                assert (vout['valueSat'] == 39637)
                break
        assert (fFound)

        self.log.info('Test staking pkh256 outputs')
        nodes[2].walletsettings('stakelimit', {'height': 1})
        nodes[2].reservebalance(False)
        assert (nodes[2].getstakinginfo()['weight'] == 400000000000)

        self.stakeBlocks(1, nStakeNode=2)

        self.log.info('Test rewardaddress')
        addrRewardExt = nodes[0].getnewextaddress()
        ro = nodes[0].walletsettings('stakingoptions',
                                     {'rewardaddress': addrRewardExt})
        assert (ro['stakingoptions']['rewardaddress'] == addrRewardExt)
        self.stakeBlocks(1)
        block5_hash = nodes[0].getblockhash(5)
        coinstakehash = nodes[0].getblock(block5_hash)['tx'][0]
        ro = nodes[0].getrawtransaction(coinstakehash, True)

        fFound = False
        for vout in ro["vout"]:
            try:
                addr0 = vout['scriptPubKey']['addresses'][0]
                ro = nodes[0].getaddressinfo(addr0)
                if ro['from_ext_address_id'] == 'xXZRLYvJgbJyrqJhgNzMjEvVGViCdGmVAt':
                    assert (addr0 == 'pgaKYsNmHTuQB83FguN44WW4ADKmwJwV7e')
                    fFound = True
                    assert (vout['valueSat'] == 39637)
            except:
                continue
        assert (fFound)

        addrRewardSx = nodes[0].getnewstealthaddress()
        ro = nodes[0].walletsettings('stakingoptions',
                                     {'rewardaddress': addrRewardSx})
        assert (ro['stakingoptions']['rewardaddress'] == addrRewardSx)
        self.stakeBlocks(1)
        block6_hash = nodes[0].getblockhash(6)
        coinstakehash = nodes[0].getblock(block6_hash)['tx'][0]
        ro = nodes[0].getrawtransaction(coinstakehash, True)

        fFound = False
        for vout in ro['vout']:
            try:
                addr0 = vout['scriptPubKey']['addresses'][0]
                ro = nodes[0].getaddressinfo(addr0)
                if ro['from_stealth_address'] == addrRewardSx:
                    fFound = True
                    assert (vout['valueSat'] == 39637)
            except:
                continue
        assert (fFound)

        self.log.info('Test clearing rewardaddress')
        ro = nodes[0].walletsettings('stakingoptions', {})

        self.stakeBlocks(1)
        coinstakehash = nodes[0].getblock(nodes[0].getblockhash(7))['tx'][0]
        ro = nodes[0].getrawtransaction(coinstakehash, True)
        for output in ro['vout'][1:]:
            assert (output['type'] == 'standard')
            assert (output['value'] > 1.0)
示例#7
0
    def run_test(self):
        nodes = self.nodes

        ro = nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (ro['account_id'] == 'aaaZf2qnNr5T7PWRmqgmusuu5ACnBcX2ev')
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        addrs = []
        pubkeys = []

        ro = nodes[0].getnewaddress()
        addrs.append(ro)
        ro = nodes[0].getaddressinfo(ro)
        pubkeys.append(ro['pubkey'])

        ro = nodes[0].getnewaddress()
        addrs.append(ro)
        ro = nodes[0].getaddressinfo(ro)
        pubkeys.append(ro['pubkey'])

        nodes[1].extkeyimportmaster(
            'drip fog service village program equip minute dentist series hawk crop sphere olympic lazy garbage segment fox library good alley steak jazz force inmate'
        )

        ro = nodes[1].getnewaddress()
        addrs.append(ro)
        ro = nodes[1].getaddressinfo(ro)
        pubkeys.append(ro['pubkey'])

        nodes[2].extkeyimportmaster(nodes[2].mnemonic('new', '',
                                                      'french')['mnemonic'])

        ro = nodes[2].getnewaddress()
        addrs.append(ro)
        ro = nodes[2].getaddressinfo(ro)
        pubkeys.append(ro['pubkey'])

        v = [addrs[0], addrs[1], pubkeys[2]]
        msAddr = nodes[0].addmultisigaddress(2, v)['address']

        ro = nodes[0].getaddressinfo(msAddr)
        assert (ro['isscript'] == True)
        scriptPubKey = ro['scriptPubKey']
        redeemScript = ro['hex']

        ro = nodes[0].sendtoaddress(msAddr, 10)
        mstxid = ro

        ro = nodes[0].gettransaction(mstxid)
        hexfund = ro['hex']
        ro = nodes[0].decoderawtransaction(hexfund)

        fundscriptpubkey = ''
        fundoutid = -1
        for vout in ro['vout']:
            if not isclose(vout['value'], 10.0):
                continue

            fundoutid = vout['n']
            fundscriptpubkey = vout['scriptPubKey']['hex']
        assert (fundoutid >= 0), "fund output not found"

        addrTo = nodes[2].getnewaddress()

        inputs = [{
            "txid": mstxid,
            "vout": fundoutid,
            "scriptPubKey": fundscriptpubkey,
            "redeemScript": redeemScript,
            "amount": 10.0,
        }]

        outputs = {addrTo: 2, msAddr: 7.99}

        hexRaw = nodes[0].createrawtransaction(inputs, outputs)

        vk0 = nodes[0].dumpprivkey(addrs[0])
        signkeys = [
            vk0,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw, signkeys, inputs)
        hexRaw1 = ro['hex']

        vk1 = nodes[0].dumpprivkey(addrs[1])
        signkeys = [
            vk1,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw1, signkeys, inputs)
        hexRaw2 = ro['hex']

        txnid_spendMultisig = nodes[0].sendrawtransaction(hexRaw2)

        self.stakeBlocks(1)
        block1_hash = nodes[0].getblockhash(1)
        ro = nodes[0].getblock(block1_hash)
        assert (txnid_spendMultisig in ro['tx'])

        msAddr256 = nodes[0].addmultisigaddress(2, v, "", False,
                                                True)['address']
        ro = nodes[0].getaddressinfo(msAddr256)
        assert (ro['isscript'] == True)

        ro = nodes[0].addmultisigaddress(2, v, "", True, True)['address']
        msAddr256 = ro
        assert (
            msAddr256 ==
            "tpj1vtll9wnsd7dxzygrjp2j5jr5tgrjsjmj3vwjf7vf60f9p50g5ddqmasmut")

        ro = nodes[0].getaddressinfo(msAddr256)
        assert (ro['isscript'] == True)
        scriptPubKey = ro['scriptPubKey']
        redeemScript = ro['hex']

        mstxid2 = nodes[0].sendtoaddress(msAddr256, 9)

        hexfund = nodes[0].gettransaction(mstxid2)['hex']
        ro = nodes[0].decoderawtransaction(hexfund)

        fundscriptpubkey = ''
        fundoutid = -1
        for vout in ro['vout']:
            if not isclose(vout['value'], 9.0):
                continue
            fundoutid = vout['n']
            fundscriptpubkey = vout['scriptPubKey']['hex']
            assert ('OP_SHA256' in vout['scriptPubKey']['asm'])
        assert (fundoutid >= 0), "fund output not found"

        inputs = [{
            "txid": mstxid2,
            "vout": fundoutid,
            "scriptPubKey": fundscriptpubkey,
            "redeemScript": redeemScript,
            "amount": 9.0,  # Must specify amount
        }]

        addrTo = nodes[2].getnewaddress()
        outputs = {addrTo: 2, msAddr256: 6.99}

        hexRaw = nodes[0].createrawtransaction(inputs, outputs)

        vk0 = nodes[0].dumpprivkey(addrs[0])
        signkeys = [
            vk0,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw, signkeys, inputs)
        hexRaw1 = ro['hex']

        ro = nodes[0].decoderawtransaction(hexRaw1)

        vk1 = nodes[0].dumpprivkey(addrs[1])
        signkeys = [
            vk1,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw1, signkeys, inputs)
        hexRaw2 = ro['hex']

        txnid_spendMultisig2 = nodes[0].sendrawtransaction(hexRaw2)

        self.stakeBlocks(1)
        block2_hash = nodes[0].getblockhash(2)
        ro = nodes[0].getblock(block2_hash)
        assert (txnid_spendMultisig2 in ro['tx'])

        ro = nodes[0].getaddressinfo(msAddr)
        scriptPubKey = ro['scriptPubKey']
        redeemScript = ro['hex']

        opts = {"recipe": "abslocktime", "time": 946684800, "addr": msAddr}
        ro = nodes[0].buildscript(opts)
        scriptTo = ro['hex']

        outputs = [
            {
                'address': 'script',
                'amount': 8,
                'script': scriptTo
            },
        ]
        mstxid3 = nodes[0].sendtypeto('part', 'part', outputs)

        ro = nodes[0].gettransaction(mstxid3)
        hexfund = ro['hex']
        ro = nodes[0].decoderawtransaction(hexfund)

        fundscriptpubkey = ''
        fundoutid = -1
        for vout in ro['vout']:
            if not isclose(vout['value'], 8.0):
                continue
            fundoutid = vout['n']
            fundscriptpubkey = vout['scriptPubKey']['hex']
            assert ('OP_CHECKLOCKTIMEVERIFY' in vout['scriptPubKey']['asm'])
        assert (fundoutid >= 0), "fund output not found"

        inputs = [{
            "txid": mstxid3,
            "vout": fundoutid,
            "scriptPubKey": fundscriptpubkey,
            "redeemScript": redeemScript,
            "amount": 8.0,  # Must specify amount
        }]

        addrTo = nodes[2].getnewaddress()
        outputs = {addrTo: 2, msAddr: 5.99}
        locktime = 946684801

        hexRaw = nodes[0].createrawtransaction(inputs, outputs, locktime)

        vk0 = nodes[0].dumpprivkey(addrs[0])
        signkeys = [
            vk0,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw, signkeys, inputs)
        hexRaw1 = ro['hex']

        ro = nodes[0].decoderawtransaction(hexRaw1)

        vk1 = nodes[0].dumpprivkey(addrs[1])
        signkeys = [
            vk1,
        ]
        ro = nodes[0].signrawtransactionwithkey(hexRaw1, signkeys, inputs)
        hexRaw2 = ro['hex']

        txnid_spendMultisig3 = nodes[0].sendrawtransaction(hexRaw2)

        self.stakeBlocks(1)
        block3_hash = nodes[0].getblockhash(3)
        ro = nodes[0].getblock(block3_hash)
        assert (txnid_spendMultisig3 in ro['tx'])

        self.log.info("Coldstake script")

        stakeAddr = nodes[0].getnewaddress()
        addrTo = nodes[0].getnewaddress()

        opts = {
            "recipe": "ifcoinstake",
            "addrstake": stakeAddr,
            "addrspend": msAddr
        }
        ro = nodes[0].buildscript(opts)
        scriptTo = ro['hex']

        outputs = [{'address': 'script', 'amount': 1, 'script': scriptTo}]
        txFundId = nodes[0].sendtypeto('part', 'part', outputs)
        hexfund = nodes[0].gettransaction(txFundId)['hex']
        ro = nodes[0].decoderawtransaction(hexfund)
        for vout in ro['vout']:
            if not isclose(vout['value'], 1.0):
                continue
            fundoutn = vout['n']
            fundscriptpubkey = vout['scriptPubKey']['hex']
            assert ('OP_ISCOINSTAKE' in vout['scriptPubKey']['asm'])
        assert (fundoutn >= 0), "fund output not found"

        ro = nodes[0].getaddressinfo(msAddr)
        assert (ro['isscript'] == True)
        scriptPubKey = ro['scriptPubKey']
        redeemScript = ro['hex']

        inputs = [{
            'txid': txFundId,
            'vout': fundoutn,
            'scriptPubKey': fundscriptpubkey,
            'redeemScript': redeemScript,
            'amount': 1.0,
        }]

        outputs = {addrTo: 0.99}
        hexRaw = nodes[0].createrawtransaction(inputs, outputs)

        sig0 = nodes[0].createsignaturewithwallet(hexRaw, inputs[0], addrs[0])
        sig1 = nodes[0].createsignaturewithwallet(hexRaw, inputs[0], addrs[1])

        self.log.info(
            'Test createsignaturewithwallet without providing prevout details')
        outpoint_only = {'txid': txFundId, 'vout': fundoutn}
        sig1_check1 = nodes[0].createsignaturewithwallet(
            hexRaw, outpoint_only, addrs[1])
        assert (sig1 == sig1_check1)
        addr1_privkey = nodes[0].dumpprivkey(addrs[1])
        sig1_check2 = nodes[0].createsignaturewithkey(hexRaw, inputs[0],
                                                      addr1_privkey)
        assert (sig1 == sig1_check2)
        try:
            sig1_check3 = nodes[0].createsignaturewithkey(
                hexRaw, outpoint_only, addr1_privkey)
            assert (
                False), 'createsignaturewithkey passed with no redeemscript'
        except JSONRPCException as e:
            assert ('"redeemScript" is required' in e.error['message'])
        outpoint_only['redeemScript'] = redeemScript
        sig1_check3 = nodes[0].createsignaturewithkey(hexRaw, outpoint_only,
                                                      addr1_privkey)
        assert (sig1 == sig1_check3)

        witnessStack = [
            "",
            sig0,
            sig1,
            redeemScript,
        ]
        hexRawSigned = nodes[0].tx(
            [hexRaw, 'witness=0:' + ':'.join(witnessStack)])

        ro = nodes[0].verifyrawtransaction(hexRawSigned)
        assert (ro['complete'] == True)

        ro = nodes[0].signrawtransactionwithwallet(hexRaw)
        assert (ro['complete'] == True)
        assert (ro['hex'] == hexRawSigned)

        txid = nodes[0].sendrawtransaction(hexRawSigned)

        self.stakeBlocks(1)
        block4_hash = nodes[0].getblockhash(4)
        ro = nodes[0].getblock(block4_hash)
        assert (txid in ro['tx'])

        self.log.info("Test combinerawtransaction")
        unspent0 = nodes[0].listunspent()
        unspent2 = nodes[2].listunspent()

        inputs = [unspent0[0], unspent2[0]]
        outputs = {
            nodes[0].getnewaddress():
            satoshi_round(unspent0[0]['amount'] + unspent2[0]['amount'] -
                          Decimal(0.1))
        }
        rawtx = nodes[0].createrawtransaction(inputs, outputs)

        rawtx0 = nodes[0].signrawtransactionwithwallet(rawtx)
        assert (rawtx0['complete'] == False)

        rawtx2 = nodes[2].signrawtransactionwithwallet(
            rawtx0['hex'])  # Keeps signature from node0
        assert (rawtx2['complete'])

        rawtx2 = nodes[2].signrawtransactionwithwallet(rawtx)
        assert (rawtx2['complete'] == False)

        rawtx_complete = nodes[0].combinerawtransaction(
            [rawtx0['hex'], rawtx2['hex']])
        nodes[0].sendrawtransaction(rawtx_complete)
    def test_cttx(self):
        nodes = self.nodes
        # Test confidential transactions
        addrA_sx = nodes[0].getnewstealthaddress()  # party A
        addrB_sx = nodes[1].getnewstealthaddress()  # party B

        outputs = [
            {
                'address': addrA_sx,
                'type': 'blind',
                'amount': 100,
            },
            {
                'address': addrB_sx,
                'type': 'blind',
                'amount': 100,
            },
        ]
        ro = nodes[0].createrawparttransaction([], outputs)

        ro = nodes[0].fundrawtransactionfrom('standard', ro['hex'], {},
                                             ro['amounts'])
        rawtx = ro['hex']

        ro = nodes[0].signrawtransactionwithwallet(rawtx)
        assert (ro['complete'] == True)

        ro = nodes[0].sendrawtransaction(ro['hex'])
        txnid = ro

        self.stakeBlocks(1)

        ro = nodes[0].getwalletinfo()
        assert (isclose(ro['blind_balance'], 100.0))

        ro = nodes[0].filtertransactions()
        n = getIndexAtProperty(ro, 'txid', txnid)
        assert (n > -1)
        assert (isclose(ro[n]['amount'], -100.00203200))

        ro = nodes[1].getwalletinfo()
        assert (isclose(ro['blind_balance'], 100.0))

        ro = nodes[1].filtertransactions()
        n = getIndexAtProperty(ro, 'txid', txnid)
        assert (n > -1)
        assert (isclose(ro[n]['amount'], 100.0))

        # Initiate A -> B
        # A has address (addrB_sx) of B

        amountA = 7.0
        amountB = 7.0

        secretA = os.urandom(32)
        secretAHash = sha256(secretA)
        lockTime = int(time.time()) + 10000  # future locktime

        destA = nodes[0].derivefromstealthaddress(addrA_sx)
        pkh0_0 = b58decode(destA['address'])[1:-4]

        ro = nodes[0].derivefromstealthaddress(addrA_sx,
                                               destA['ephemeral_pubkey'])
        privKeyA = ro['privatekey']
        pubKeyA = ro['pubkey']

        destB = nodes[0].derivefromstealthaddress(addrB_sx)
        pkh1_0 = b58decode(destB['address'])[1:-4]

        ro = nodes[1].derivefromstealthaddress(addrB_sx,
                                               destB['ephemeral_pubkey'])
        privKeyB = ro['privatekey']
        pubKeyB = ro['pubkey']

        scriptInitiate = CreateAtomicSwapScript(payTo=pkh1_0,
                                                refundTo=pkh0_0,
                                                lockTime=lockTime,
                                                secretHash=secretAHash)
        p2sh_initiate = script_to_p2sh_part(scriptInitiate)

        outputs = [
            {
                'address': p2sh_initiate,
                'pubkey': destB['pubkey'],
                'type': 'blind',
                'amount': amountA,
            },
        ]
        ro = nodes[0].createrawparttransaction([], outputs)
        ro = nodes[0].fundrawtransactionfrom('blind', ro['hex'], {},
                                             ro['amounts'])
        output_amounts_i = ro['output_amounts']
        ro = nodes[0].signrawtransactionwithwallet(ro['hex'])
        assert (ro['complete'] == True)
        rawtx_i = ro['hex']

        rawtx_i_refund = createRefundTxCT(nodes[0], rawtx_i, output_amounts_i,
                                          scriptInitiate, lockTime, privKeyA,
                                          pubKeyA, addrA_sx)
        ro = nodes[0].testmempoolaccept([
            rawtx_i_refund,
        ])
        assert ('64: non-final' in ro[0]['reject-reason'])

        txnid1 = nodes[0].sendrawtransaction(rawtx_i)
        self.stakeBlocks(1)

        # Party A sends B rawtx_i/txnid1, script and output_amounts_i

        # auditcontract
        # Party B extracts the secrethash and verifies the txn:

        ro = nodes[1].decoderawtransaction(rawtx_i)
        n = getOutputByAddr(ro, p2sh_initiate)
        valueCommitment = ro['vout'][n]['valueCommitment']

        amount = output_amounts_i[str(n)]['value']
        blind = output_amounts_i[str(n)]['blind']

        assert (nodes[1].verifycommitment(valueCommitment, blind,
                                          amount)['result'] == True)

        # Participate B -> A
        # needs address and publickey from A, amount and secretAHash

        lockTimeP = int(time.time()) + 10000  # future locktime
        scriptParticipate = CreateAtomicSwapScript(payTo=pkh0_0,
                                                   refundTo=pkh1_0,
                                                   lockTime=lockTimeP,
                                                   secretHash=secretAHash)
        p2sh_participate = script_to_p2sh_part(scriptParticipate)

        outputs = [
            {
                'address': p2sh_participate,
                'pubkey': destA['pubkey'],
                'type': 'blind',
                'amount': amountB,
            },
        ]

        ro = nodes[1].createrawparttransaction([], outputs)
        ro = nodes[1].fundrawtransactionfrom('blind', ro['hex'], {},
                                             ro['amounts'])
        output_amounts_p = ro['output_amounts']
        ro = nodes[1].signrawtransactionwithwallet(ro['hex'])
        rawtx_p = ro['hex']

        rawtx_p_refund = createRefundTxCT(nodes[1], rawtx_p, output_amounts_p,
                                          scriptParticipate, lockTime,
                                          privKeyB, pubKeyB, addrB_sx)
        ro = nodes[1].testmempoolaccept([
            rawtx_p_refund,
        ])
        assert ('64: non-final' in ro[0]['reject-reason'])

        txnid_p = nodes[0].sendrawtransaction(rawtx_p)
        self.stakeBlocks(1)
        assert (txnid_p in nodes[0].getblock(nodes[0].getblockhash(
            nodes[0].getblockcount()))['tx'])

        # B sends output_amounts to A

        # Party A Redeem/Claim from participate txn
        # Party A spends the funds from the participate txn, and to do so must reveal secretA

        rawtxclaimA = createClaimTxCT(nodes[0], rawtx_p, output_amounts_p,
                                      scriptParticipate, secretA, privKeyA,
                                      pubKeyA, addrA_sx)
        txnidAClaim = nodes[0].sendrawtransaction(rawtxclaimA)

        # Party B claims from initiate txn
        # Get secret from txnidAClaim

        #ro = nodes[1].getrawtransaction(txnidAClaim, True)
        #print('ro', json.dumps(ro, indent=4, default=jsonDecimal))

        rawtxclaimB = createClaimTxCT(nodes[1], rawtx_i, output_amounts_i,
                                      scriptInitiate, secretA, privKeyB,
                                      pubKeyB, addrB_sx)
        txnidBClaim = nodes[0].sendrawtransaction(rawtxclaimB)

        nodes[0].getmempoolentry(txnidAClaim)
        nodes[0].getmempoolentry(txnidBClaim)

        # Test Refund expired initiate tx
        secretA = os.urandom(32)
        secretAHash = sha256(secretA)
        lockTime = int(time.time()) - 100000  # past locktime

        amountA = 7.1
        scriptInitiate = CreateAtomicSwapScript(payTo=pkh1_0,
                                                refundTo=pkh0_0,
                                                lockTime=lockTime,
                                                secretHash=secretAHash)
        p2sh_initiate = script_to_p2sh_part(scriptInitiate)

        outputs = [
            {
                'address': p2sh_initiate,
                'pubkey': destB['pubkey'],
                'type': 'blind',
                'amount': amountA,
            },
        ]
        ro = nodes[0].createrawparttransaction([], outputs)
        ro = nodes[0].fundrawtransactionfrom('blind', ro['hex'], {},
                                             ro['amounts'])

        r2 = nodes[0].verifyrawtransaction(ro['hex'])
        assert (r2['complete'] == False)

        output_amounts_i = ro['output_amounts']
        ro = nodes[0].signrawtransactionwithwallet(ro['hex'])
        assert (ro['complete'] == True)
        rawtx_i = ro['hex']

        r2 = nodes[0].verifyrawtransaction(rawtx_i)
        assert (r2['complete'] == True)

        rawtx_i_refund = createRefundTxCT(nodes[0], rawtx_i, output_amounts_i,
                                          scriptInitiate, lockTime, privKeyA,
                                          pubKeyA, addrA_sx)
        ro = nodes[0].testmempoolaccept([
            rawtx_i_refund,
        ])
        assert ('missing-inputs' in ro[0]['reject-reason'])

        txnid1 = nodes[0].sendrawtransaction(rawtx_i)
        ro = nodes[0].getwalletinfo()
        assert (ro['unconfirmed_blind'] > 6.0
                and ro['unconfirmed_blind'] < 7.0)

        txnidRefund = nodes[0].sendrawtransaction(rawtx_i_refund)
        nodes[0].getmempoolentry(txnidRefund)

        ro = nodes[0].getwalletinfo()
        assert (ro['unconfirmed_blind'] > 14.0
                and ro['unconfirmed_blind'] < 14.1)
    def test_standardtx(self):
        nodes = self.nodes

        addrA_0 = nodes[0].getnewaddress()  # party A
        addrB_0 = nodes[1].getnewaddress()  # party B

        # Initiate A -> B
        # A has address (addrB_0) of B

        amountA = 5.0
        amountB = 5.0
        pkh0_0 = b58decode(addrA_0)[1:-4]
        pkh1_0 = b58decode(addrB_0)[1:-4]

        secretA = os.urandom(32)
        secretAHash = sha256(secretA)

        lockTime = int(time.time()) + 10000  # future locktime

        scriptInitiate = CreateAtomicSwapScript(payTo=pkh1_0,
                                                refundTo=pkh0_0,
                                                lockTime=lockTime,
                                                secretHash=secretAHash)
        p2sh_initiate = script_to_p2sh_part(scriptInitiate)
        rawtxInitiate = nodes[0].createrawtransaction([],
                                                      {p2sh_initiate: amountA})
        rawtxInitiate = nodes[0].fundrawtransaction(rawtxInitiate)['hex']
        ro = nodes[0].signrawtransactionwithwallet(rawtxInitiate)
        assert (ro['complete'] == True)
        rawtxInitiate = ro['hex']

        rawtx1refund = createRefundTx(nodes[0], rawtxInitiate, scriptInitiate,
                                      lockTime, addrA_0, addrA_0)

        nodes[0].sendrawtransaction(rawtxInitiate)
        self.stakeBlocks(1)

        ro = nodes[0].getblockchaininfo()
        assert (ro['mediantime'] < lockTime)
        try:
            txnidrefund = nodes[0].sendrawtransaction(rawtx1refund)
            assert (False)
        except JSONRPCException as e:
            assert ('non-final' in e.error['message'])

        # Party A sends B rawtxInitiate/txnid1 and script

        # auditcontract
        # Party B extracts the secrethash and verifies the txn:
        assert (len(scriptInitiate) == 97)
        extractedSecretAHash = scriptInitiate[7:7 + 32]
        assert (extractedSecretAHash == secretAHash)
        tx1 = nodes[1].decoderawtransaction(rawtxInitiate)
        self.log.info("Verify txn " + tx1['txid'])  # TODO

        # Participate B -> A
        # needs address from A, amount and secretAHash

        lockTimeP = int(time.time()) + 10000  # future locktime
        scriptParticipate = CreateAtomicSwapScript(payTo=pkh0_0,
                                                   refundTo=pkh1_0,
                                                   lockTime=lockTimeP,
                                                   secretHash=secretAHash)
        p2sh_participate = script_to_p2sh_part(scriptParticipate)

        rawtx_p = nodes[1].createrawtransaction([],
                                                {p2sh_participate: amountB})
        rawtx_p = nodes[1].fundrawtransaction(rawtx_p)['hex']

        ro = nodes[1].signrawtransactionwithwallet(rawtx_p)
        assert (ro['complete'] == True)
        rawtx_p = ro['hex']

        rawtxRefundP = createRefundTx(nodes[1], rawtx_p, scriptParticipate,
                                      lockTimeP, addrB_0, addrB_0)

        txnidParticipate = nodes[1].sendrawtransaction(rawtx_p)
        self.sync_all()
        self.stakeBlocks(1)
        assert (txnidParticipate in nodes[0].getblock(nodes[0].getblockhash(
            nodes[0].getblockcount()))['tx'])

        ro = nodes[0].getblockchaininfo()
        assert (ro['mediantime'] < lockTimeP)
        try:
            txnidrefund = nodes[1].sendrawtransaction(rawtxRefundP)
            assert (False)
        except JSONRPCException as e:
            assert ('non-final' in e.error['message'])

        # auditcontract
        # Party A verifies the participate txn from B

        # Party A Redeem/Claim from participate txn
        # Party A spends the funds from the participate txn, and to do so must reveal secretA

        rawtxclaimA = createClaimTx(nodes[0], rawtx_p, scriptParticipate,
                                    secretA, addrA_0, addrA_0)
        txnidAClaim = nodes[0].sendrawtransaction(rawtxclaimA)

        # Party B Redeem/Claim from initiate txn
        # Get secret from txnidAClaim

        #ro = nodes[1].getrawtransaction(txnidAClaim, True)
        #print('ro', json.dumps(ro, indent=4, default=jsonDecimal))

        rawtxclaimB = createClaimTx(nodes[1], rawtxInitiate, scriptInitiate,
                                    secretA, addrB_0, addrB_0)
        txnidBClaim = nodes[0].sendrawtransaction(
            rawtxclaimB)  # send from staking node to avoid syncing

        self.stakeBlocks(1)
        last_block_txns = nodes[0].getblock(nodes[0].getblockhash(
            nodes[0].getblockcount()))['tx']
        assert (txnidAClaim in last_block_txns)
        assert (txnidBClaim in last_block_txns)

        ftxB = nodes[1].filtertransactions()
        assert (ftxB[0]['confirmations'] == 1)
        assert (ftxB[0]['outputs'][0]['amount'] < 5.0
                and ftxB[-1]['outputs'][0]['amount'] > 4.9)
        assert (isclose(ftxB[1]['outputs'][0]['amount'], -5.0))

        # Test Refund expired initiate tx
        lockTime = int(time.time()) - 100000  # past locktime

        scriptInitiate2 = CreateAtomicSwapScript(payTo=pkh1_0,
                                                 refundTo=pkh0_0,
                                                 lockTime=lockTime,
                                                 secretHash=secretAHash)

        p2sh_initiate = script_to_p2sh_part(scriptInitiate2)
        rawtxInitiate = nodes[0].createrawtransaction([], {p2sh_initiate: 6.0})
        rawtxInitiate = nodes[0].fundrawtransaction(rawtxInitiate)['hex']
        ro = nodes[0].signrawtransactionwithwallet(rawtxInitiate)
        assert (ro['complete'] == True)
        rawtxInitiate = ro['hex']

        rawtx2refund = createRefundTx(nodes[0], rawtxInitiate, scriptInitiate2,
                                      lockTime, addrA_0, addrA_0)
        txnid2 = nodes[0].sendrawtransaction(rawtxInitiate)

        self.stakeBlocks(1)

        ro = nodes[0].getblockchaininfo()
        assert (ro['mediantime'] > lockTime)

        txnidrefund = nodes[0].sendrawtransaction(rawtx2refund)

        ftxA = nodes[0].filtertransactions()
        n = getIndexAtProperty(ftxA, 'txid', txnidrefund)
        assert (n > -1)
        assert (ftxA[n]['outputs'][0]['amount'] > 5.9
                and ftxA[n]['outputs'][0]['amount'] < 6.0)
示例#10
0
    def run_test(self):
        nodes = self.nodes
        txnHashes = []

        ro = nodes[0].extkeyimportmaster(
            'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'
        )
        assert (ro['account_id'] == 'aaaZf2qnNr5T7PWRmqgmusuu5ACnBcX2ev')
        assert (nodes[0].getwalletinfo()['total_balance'] == 100000)

        ro = nodes[1].extkeyimportmaster(
            'drip fog service village program equip minute dentist series hawk crop sphere olympic lazy garbage segment fox library good alley steak jazz force inmate'
        )
        sxAddrTo1 = nodes[1].getnewstealthaddress()
        assert (
            sxAddrTo1 ==
            'TetbYTGv5LiqyFiUD3a5HHbpSinQ9KiRYDGAMvRzPfz4RnHMbKGAwDr1fjLGJ5Eqg1XDwpeGyqWMiwdK3qM3zKWjzHNpaatdoHVzzA'
        )

        ro = nodes[1].getaddressinfo(sxAddrTo1)
        assert (ro['ismine'] == True)
        assert (ro['isstealthaddress'] == True)
        assert (ro['account'] == 'ahL1QdHhzNCtZWJzv36ScfPipJP1cUzAD8')
        assert (ro['scan_path'] == "m/0'/0'")
        assert (ro['spend_path'] == "m/0'/1'")

        txnHash = nodes[0].sendtoaddress(sxAddrTo1, 1)
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[1], txnHash))

        ro = nodes[1].listtransactions()
        assert (len(ro) == 1)
        assert (ro[0]['stealth_address'] == sxAddrTo1)
        assert (isclose(ro[0]['amount'], 1))

        ro = nodes[1].getaddressinfo(ro[0]['address'])
        assert (ro['ismine'] == True)
        assert (ro['from_stealth_address'] == sxAddrTo1)

        # Test imported sx address
        ro = nodes[1].importstealthaddress(
            '7pJLDnLxoYmkwpMNDX69dWGT7tuZ45LHgMajQDD8JrXb9LHmzfBA',
            '7uk8ELaUsop2r4vMg415wEGBfRd1MmY7JiXX7CRhwuwq5PaWXQ9N',
            'importedAddr', '5', '0xaaaa')
        sxAddrTo2 = '32eEcCuGkGjP82BTF3kquiCDjZWmZiyhqe7C6isbv6MJZSKAeWNx5g436QuhGNc6DNYpboDm3yNiqYmTmkg76wYr5JCKgdEUPqLCWaMW'
        assert (ro['stealth_address'] == sxAddrTo2)

        ro = nodes[1].liststealthaddresses()
        sro = str(ro)
        assert (sxAddrTo1 in sro)
        assert (sxAddrTo2 in sro)

        txnHash = nodes[0].sendtoaddress(sxAddrTo2, 0.2)
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[1], txnHash))

        ro = nodes[1].listtransactions()

        sxAddrTo3 = nodes[1].getnewstealthaddress()
        assert (
            sxAddrTo3 ==
            'TetcV5ZNzM6hT6Tz8Vc5t6FM74nojY8oFdeCnPr9Vyx6QNqrR7LKy87aZ1ytGGqBSAJ9CpWDj81pPwYPYHjg6Ks8GKXvGyLoBdTDYQ'
        )

        txnHash = nodes[0].sendtoaddress(sxAddrTo3, 0.3, '', '', False,
                                         'narration test')
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[1], txnHash))

        ro = nodes[1].listtransactions()
        assert (ro[-1]['stealth_address'] == sxAddrTo3)
        assert (isclose(ro[-1]['amount'], 0.3))
        assert ('narration test' in str(ro[-1]))

        # - Test encrypted narrations on sent wtx (from sending nodes[0])
        ro = nodes[0].listtransactions()
        assert ('narration test' in str(ro[-1]))

        oRoot2 = nodes[2].mnemonic('new')
        assert ('mnemonic' in oRoot2)

        ro = nodes[2].extkeyimportmaster(oRoot2['mnemonic'])
        assert ('Success.' in ro['result'])

        sxAddrTo2_1 = nodes[2].getnewstealthaddress('lbl test 3 bits', '3')

        ro = nodes[2].importstealthaddress(
            '7uk8ELaUsop2r4vMg415wEGBfRd1MmY7JiXX7CRhwuwq5PaWXQ9N',  # secrets are backwards
            '7pJLDnLxoYmkwpMNDX69dWGT7tuZ45LHgMajQDD8JrXb9LHmzfBA',
            'importedAddr',
            '9',
            '0xabcd')
        sxAddrTo2_2 = '9xFM875J9ApSymuT9Yuz6mqmy36JE1tNANGZmvS6hXFoQaV7ZLx8ZGjT2WULbuxwY4EsmNhHivLd4f8SRkxSjGjUED51SA4WqJRysUk9f'
        assert (ro['stealth_address'] == sxAddrTo2_2)

        nodes[2].encryptwallet('qwerty234')

        ro = nodes[2].walletpassphrase('qwerty234', 300)
        ro = nodes[2].reservebalance(True, 10000000)
        ro = nodes[2].walletlock()

        # Test send to locked wallet
        txnHash = nodes[0].sendtoaddress(sxAddrTo2_1, 0.4, '', '', False,
                                         'narration test node2')
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[2], txnHash))

        ro = nodes[2].listtransactions()
        assert (isclose(ro[-1]['amount'], 0.4))
        assert ('narration test node2' in str(ro[-1]))

        txnHash = nodes[0].sendtoaddress(sxAddrTo2_2, 0.5, '', '', False,
                                         'test 5')
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[2], txnHash))

        ro = nodes[2].listtransactions()
        assert (isclose(ro[-1]['amount'], 0.5))
        assert ('test 5' in str(ro[-1]))

        txnHash = nodes[0].sendtoaddress(sxAddrTo2_2, 0.6, '', '', False,
                                         'test 6')
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[2], txnHash))

        ro = nodes[2].listtransactions()
        assert (isclose(ro[-1]['amount'], 0.6))
        assert ('test 6' in str(ro[-1]))

        ro = nodes[2].walletpassphrase('qwerty234', 400)

        self.stakeBlocks(1)

        block1_hash = nodes[0].getblockhash(1)
        ro = nodes[0].getblock(block1_hash)
        for txnHash in txnHashes:
            assert (txnHash in ro['tx'])

        self.sync_all()
        ro = nodes[2].getwalletinfo()

        txnHash = nodes[2].sendtoaddress(sxAddrTo3, 1.4, '', '', False,
                                         'node2 -> node1')
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[1], txnHash))
        ro = nodes[1].listtransactions()
        assert (isclose(ro[-1]['amount'], 1.4))
        assert ('node2 -> node1' in str(ro[-1]))

        assert_raises_rpc_error(
            -8, 'Spend secret must be different to scan secret.',
            nodes[0].importstealthaddress,
            '57F59BA2F9D9146635380FA453E4EED7E44290F0AAAE657C300AB0E51184151E',
            '57F59BA2F9D9146635380FA453E4EED7E44290F0AAAE657C300AB0E51184151E',
            '', '9', '0xabcd', True)

        # Test bech32 encoding
        ro = nodes[0].importstealthaddress(
            '57F59BA2F9D9146635380FA453E4EED7E44290F0AAAE657C300AB0E51184151E',
            'F4708BD9B3D367F02EA6581AC446F12AA24350F1E0DEE309FACB561C2D81877A',
            'importedAddr1b32', '9', '0xabcd', True)
        sx1_b32 = 'tps1qqpt67v3g652e5mvqv3hl60zkj3424l0chhvsc0ervrltujd7dgl6uspqfd2hf5dglxt285yp9d9h3nym39cdzdpr5ndcm940lhmg6z3tjuvzqqfe5qs2gep0t'
        assert (ro['stealth_address'] == sx1_b32)

        ro = nodes[0].getnewstealthaddress('importedAddr2b32', '', '', True)
        sx2_b32 = 'tps1qqpxdqs29p7sadu3fqpc808aw93a25k9zjy6f5hzgyf3vluy3n4f4ygpqwkkfhujgzgq83y55enleldy9lh7tkv6dmkaxjrjtyaswjcx3mjyyqqqhefkp7'
        assert (ro == sx2_b32)
        flat = json.dumps(nodes[0].filteraddresses())
        assert (sx1_b32 in flat and sx2_b32 in flat)

        ro = nodes[1].createrawtransaction([], {sx1_b32: 0.1})
        ro = nodes[1].fundrawtransaction(ro)
        ro = nodes[1].signrawtransactionwithwallet(ro['hex'])
        assert (ro['complete'] == True)
        txnHash = nodes[1].sendrawtransaction(ro['hex'])
        txnHashes.append(txnHash)

        assert (self.wait_for_mempool(nodes[0], txnHash))

        ro = nodes[0].filtertransactions({'use_bech32': True})
        assert (ro[0]['outputs'][0]['stealth_address'] == sx1_b32)

        ro = nodes[0].derivefromstealthaddress(sx2_b32)
        assert (len(ro) == 4)
        assert (len(ro['pubkey']) == 66)
        assert (len(ro['ephemeral_pubkey']) == 66)

        recover = nodes[0].derivefromstealthaddress(sx2_b32,
                                                    ro['ephemeral_pubkey'])
        assert (recover['pubkey'] == ro['pubkey'])
        assert (recover['ephemeral_pubkey'] == ro['ephemeral_pubkey'])
        assert (len(recover['privatekey']) > 0)

        replay = nodes[0].derivefromstealthaddress(sx2_b32,
                                                   ro['ephemeral_privatekey'])
        assert (replay['pubkey'] == ro['pubkey'])
        assert (replay['ephemeral_pubkey'] == ro['ephemeral_pubkey'])

        self.log.info('Test v2 stealth address')
        sxAddrV2 = []
        for i in range(6):
            sxAddrV2.append(nodes[1].getnewstealthaddress(
                'addr v2 {}'.format(i), '0', '0', True, True))
        # Import should recover both stealth addresses, despite only detecting txns for the second and sixth.
        nodes[0].sendtoaddress(sxAddrV2[1], 2.0)
        self.stakeBlocks(1)
        nodes[0].sendtoaddress(sxAddrV2[5], 2.0)
        self.stakeBlocks(1)

        self.log.info('Test rescan lookahead')
        nodes[1].createwallet('test_import')
        w_import = nodes[1].get_wallet_rpc('test_import')
        w_import.extkeyimportmaster(
            'drip fog service village program equip minute dentist series hawk crop sphere olympic lazy garbage segment fox library good alley steak jazz force inmate'
        )
        wi_info = w_import.getwalletinfo()

        w1 = nodes[1].get_wallet_rpc('')
        w1_info = w1.getwalletinfo()

        # Imported wallet should be missing imported sx addr
        assert (wi_info['txcount'] == w1_info['txcount'] - 1)

        wi_ls = w_import.liststealthaddresses()
        w1_ls = w1.liststealthaddresses()
        w1_ls_flat = self.dumpj(w1_ls)
        for sx in wi_ls[0]['Stealth Addresses']:
            assert (sx['Address'] in w1_ls_flat)