def run_test(self):
        nodes = self.nodes

        # Stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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(nodes[1].mnemonic('new')['master'])

        addr1 = nodes[1].getnewaddress()
        addr2 = nodes[1].getnewstealthaddress()

        txnid = nodes[0].sendmany(
            fromaccount='',
            amounts={
                addr1: 1,
                addr2: 2
            },
            subtractfeefrom=[addr1],
            minconf=0,
        )
        self.sync_all()

        ro = nodes[1].filtertransactions()
        assert (ro[0]['txid'] == txnid)
        assert (isclose(ro[0]['amount'], 2.999512))
        assert (len(ro[0]['outputs']) == 2)
    def run_test (self):
        nodes = self.nodes

        # Stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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)

        ro = nodes[1].getwalletinfo()
        assert(isclose(ro['watchonly_balance'], 10000.0))

        ro = nodes[1].filtertransactions({'include_watchonly': True})
        assert(len(ro) == 1)
Пример #3
0
    def run_test(self):
        nodes = self.nodes

        # Stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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)

        txnHashes = []

        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_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)

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

        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)

        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.09498274))
        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()
        ro = nodes[0].getwalletinfo()
        assert (isclose(ro['total_balance'], 99996.09292874))

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

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

        # Test lockunspent
        unspent = nodes[1].listunspentblind(minconf=0)
        assert (nodes[1].lockunspent(False, [unspent[0]]) == True)
        assert (len(nodes[1].listlockunspent()) == 1)
        unspentCheck = nodes[1].listunspentblind(minconf=0)
        assert (len(unspentCheck) < len(unspent))
        assert (nodes[1].lockunspent(True, [unspent[0]]) == True)
        unspentCheck = nodes[1].listunspentblind(minconf=0)
        assert (len(unspentCheck) == 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)

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

        try:
            ro = nodes[1].sendtypeto('blind', 'blind', outputs)
        except JSONRPCException as e:
            assert ('Insufficient blinded funds' in e.error['message'])
Пример #4
0
    def run_test(self):
        nodes = self.nodes

        # stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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)
Пример #5
0
    def run_test(self):

        # Check that bitcoinc 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(
                "bitcoincd has not been built with usb device enabled.")

        nodes = self.nodes

        # Stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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()
        except JSONRPCException as e:
            pass
        else:
            assert (False)

        txnid0 = nodes[0].sendtoaddress(addr1_0, 10)

        self.stakeBlocks(1)

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

        addr0_0 = nodes[0].getnewaddress()
        hexRaw = nodes[1].createrawtransaction([], {addr0_0: 1})
        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 = [
            {
                'txid': txDecoded['vin'][0]['txid'],
                'vout': txDecoded['vin'][0]['vout'],
                'scriptPubKey': va_addr1_0['scriptPubKey'],
                'amount': 10
            },
        ]
        ro = nodes[1].devicesignrawtransaction(hexFunded, prevtxns, [
            '0/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()

        ro = nodes[0].filtertransactions()
        assert (ro[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) == 4)
        assert ('test msg' in json.dumps(ro[3], default=self.jsonDecimal))

        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)

        extaddr1_0 = nodes[1].getnewextaddress()
        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))
Пример #6
0
    def run_test(self):
        nodes = self.nodes

        # stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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)]

        # test reserve balance
        ro = nodes[0].walletsettings('stakelimit', {'height': 1})
        ro = nodes[0].getwalletinfo()
        assert (isclose(ro['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})
        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)

        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)
Пример #7
0
    def run_test(self):
        node = self.nodes[0]
        node1 = self.nodes[1]

        # stop staking
        node.reservebalance(True, 10000000)

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

        # Start staking
        node.walletsettings('stakelimit', {'height': 1})
        node.reservebalance(False)

        assert (self.wait_for_height(node, 1))

        # stop staking
        node.reservebalance(True, 10000000)
        node1.reservebalance(True, 10000000)

        ro = node1.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'
        )
        assert (ro['account_id'] == 'ahL1QdHhzNCtZWJzv36ScfPipJP1cUzAD8')

        extAddrTo = node1.getnewextaddress('test label')
        assert (
            extAddrTo ==
            'pparszNYZ1cpWxnNieFqHCV2rtXmG74a4WAXHHhXaRATzzU6kMixjy1rXDM1UM4LVgkXRpLNM1rQNvkgLf7kUeMXiyaBMK8aSR3td4b4cX4epnHF'
        )

        ro = node1.filteraddresses()
        assert (len(ro) == 1)
        assert (ro[0]['label'] == 'test label')

        ro = node1.getaddressinfo(extAddrTo)
        assert (ro['ismine'] == True)
        assert (ro['isextkey'] == True)

        ro = node1.dumpprivkey(extAddrTo)
        assert (
            ro ==
            'xparFnnG7xJkEekTjWGumcEY1BKgryY4txW5Ce56KQPBJG7u3cNsUHxGgjVwHGEaxUGDAjT4SXv7fkWkp4TFaFHjaoZVh8Zricnwz3DjAxtqtmi'
        )

        txnHash = node.sendtoaddress(extAddrTo, 10)

        ro = node.getmempoolentry(txnHash)
        assert (ro['height'] == 1)

        # start staking
        node.walletsettings('stakelimit', {'height': 2})
        node.reservebalance(False)

        assert (self.wait_for_height(node, 2))

        # stop staking
        ro = node.reservebalance(True, 10000000)

        ro = node1.listtransactions()
        assert (len(ro) == 1)
        assert (ro[0]['address'] == 'pkGv5xgviEAEjwpRPeEt8c9cvraw2umKYo')
        assert (ro[0]['amount'] == 10)

        ro = node1.getwalletinfo()
        assert (ro['total_balance'] == 10)

        block2_hash = node.getblockhash(2)

        ro = node.getblock(block2_hash)
        assert (txnHash in ro['tx'])

        txnHash2 = node.sendtoaddress(extAddrTo, 20, '', '', False,
                                      'narration test')

        assert (self.wait_for_mempool(node1, txnHash2))

        ro = node1.listtransactions()
        assert (len(ro) == 2)
        assert (ro[1]['address'] == 'pbo5e7tsLJBdUcCWteTTkGBxjW8Xy12o1V')
        assert (ro[1]['amount'] == 20)
        assert ('narration test' in ro[1].values())

        ro = node.listtransactions()
        assert ('narration test' in ro[-1].values())

        extAddrTo0 = node.getnewextaddress()

        txnHashes = []
        for k in range(24):
            v = round(0.01 * float(k + 1), 5)
            node1.syncwithvalidationinterfacequeue()
            txnHash = node1.sendtoaddress(extAddrTo0, v, '', '', False)
            txnHashes.append(txnHash)

        for txnHash in txnHashes:
            assert (self.wait_for_mempool(node, txnHash))

        ro = node.listtransactions('*', 24)
        assert (len(ro) == 24)
        assert [isclose(ro[0]['amount'], 0.01)]
        assert [isclose(ro[23]['amount'], 0.24)]
        assert [ro[23]['address'] == 'pm23xKs3gy6AhZZ7JZe61Rn1m8VB83P49d']

        # start staking
        ro = node.walletsettings('stakelimit', {'height': 3})
        ro = node.reservebalance(False)

        assert (self.wait_for_height(node, 3))

        block3_hash = node.getblockhash(3)
        ro = node.getblock(block3_hash)

        for txnHash in txnHashes:
            assert (txnHash in ro['tx'])

        # Test bech32 encoding
        ek_b32 = 'tpep1q3ehtcetqqqqqqesj04mypkmhnly5rktqmcpmjuq09lyevcsjxrgra6x8trd52vp2vpsk6kf86v3npg6x66ymrn5yrqnclxtqrlfdlw3j4f0309dhxct8kc68paxt'
        assert (node.getnewextaddress('lbl_b32', '', True) == ek_b32)
        assert (ek_b32 in json.dumps(node.filteraddresses()))
    def run_test(self):
        tmpdir = self.options.tmpdir
        nodes = self.nodes

        # Stop staking
        for i in range(len(nodes)):
            nodes[i].reservebalance(True, 10000000)

        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')

        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.00085800))

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

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

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

        ro = nodes[0].smsgimportprivkey(
            '7pHSJFY1tNwi6d68UttGzB8YnXq2wFWrBVoadLv4Y6ekJD3L1iKs',
            'smsg test key')

        address0_1 = 'pasdoMwEn35xQUXFvsChWAQjuG8rEKJQW9'
        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].node_encrypt_wallet('qwerty234')
        self.start_node(0)

        connect_nodes(self.nodes[0], 1)
        connect_nodes(self.nodes[0], 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 = json.dumps(ro, default=self.jsonDecimal)
        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 = json.dumps(ro, default=self.jsonDecimal)
        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)

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

        ro = nodes[1].smsgsend(address1, address0_1,
                               binascii.hexlify(msg).decode("utf-8"), True, 4,
                               False, False, True)
        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)

        # 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)

        # 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)
        assert (int(ro['buckets'][0]['no. messages']) == int(
            ro['buckets'][0]['active messages']) + 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))
Пример #9
0
    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.00581000))

        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)

        # 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)

        # 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)

        ro = nodes[0].getwalletinfo()
        assert (ro['unconfirmed_blind'] > 14.0
                and ro['unconfirmed_blind'] < 14.1)
Пример #10
0
    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.stakeBlocks(1)

        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)
        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)