Exemplo n.º 1
0
def test_pegin(test_obj):
    btc_rpc = test_obj.btcConn.get_rpc()
    elm_rpc = test_obj.elmConn.get_rpc()

    # generate pegin address
    path = '{}/0/0'.format(ROOT_PATH)
    main_ext_sk = test_obj.hdwallet.get_privkey(path=path)
    main_sk = str(main_ext_sk.privkey)
    main_pk = str(main_ext_sk.privkey.pubkey)
    pegin_address, claim_script, _ = AddressUtil.get_pegin_address(
        fedpeg_script=test_obj.fedpegscript,
        pubkey=main_pk,
        mainchain_network=Network.REGTEST)
    pegin_address = str(pegin_address)
    claim_script = claim_script.hex
    # pegin_addr_info = elm_rpc.getpeginaddress()
    # pegin_address = pegin_addr_info['mainchain_address']
    # claim_script = pegin_addr_info['claim_script']

    for i in range(3):
        try:
            blk_cnt = btc_rpc.getblockcount() + 1
            # send bitcoin
            utxos = get_utxo(btc_rpc, [])
            amount = 0
            for utxo in utxos:
                amount += utxo['amount']
            amount -= 1
            if amount > 100:
                amount = 100
            txid = btc_rpc.sendtoaddress(pegin_address, amount)

            # generate bitcoin 100 block
            addr = str(test_obj.addr_dic['btc'])
            btc_rpc.generatetoaddress(101, addr)
            max_blk_cnt = btc_rpc.getblockcount()

            txout_proof = None
            for i in range(max_blk_cnt - blk_cnt):
                blk_hash = btc_rpc.getblockhash(blk_cnt + i)
                block_hex = btc_rpc.getblock(blk_hash, 0)
                block = Block(block_hex)
                if block.exist_txid(txid):
                    tx_data, txout_proof = block.get_tx_data(txid)
                    print(f'pegin block: {str(block)}')
                    break

            if txout_proof is None:
                raise Exception('txoutproof is empty.')

            # pegin transaction for fee address
            # tx_data = btc_rpc.gettransaction(txid)['hex']
            tx = Transaction(tx_data)
            vout = tx.get_txout_index(pegin_address)
            pegged_amount = tx.txout_list[vout].amount
            # txout_proof = btc_rpc.gettxoutproof([txid])
            # pegin_tx = elm_rpc.createrawpegin(
            #     tx_data, txout_proof, claim_script)['hex']
            # pegin_tx = update_pegin_tx(
            #     test_obj, pegin_tx, tx_data, pegin_address, txout_proof)
            pegin_tx = create_pegin_tx(test_obj, tx, pegin_address,
                                       txout_proof, claim_script)
            ct = ConfidentialTransaction(pegin_tx)
            ct.sign_with_privkey(OutPoint(txid, vout), HashType.P2WPKH,
                                 main_sk, pegged_amount)
            pegin_tx = str(ct)
            # broadcast
            print(
                ConfidentialTransaction.parse_to_json(pegin_tx,
                                                      network=NETWORK))
            txid = elm_rpc.sendrawtransaction(pegin_tx)
            test_obj.tx_dic[txid] = pegin_tx
            # generatetoaddress -> gen address
            addr = str(test_obj.addr_dic['gen'])
            elm_rpc.generatetoaddress(2, addr)
            time.sleep(2)
        except Exception as err:
            print('Exception({})'.format(i))
            raise err

    # generatetoaddress -> gen address
    addr = str(test_obj.addr_dic['gen'])
    elm_rpc.generatetoaddress(100, addr)
    elm_rpc.generatetoaddress(5, addr)
    time.sleep(2)
    fee_addr = test_obj.addr_dic['fee']
    utxos = get_utxo(elm_rpc, [str(fee_addr)])
    # utxos = get_utxo(elm_rpc, [])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 2
0
def test_bitcoin_multisig(test_obj):
    btc_rpc = test_obj.conn.get_rpc()
    # create tx (output multisig)
    txouts = [
        TxOut(100000000, str(test_obj.addr_dic['p2sh'])),
        TxOut(100000000, str(test_obj.addr_dic['p2wsh'])),
        TxOut(100000000, str(test_obj.addr_dic['p2sh-p2wsh'])),
    ]
    tx = Transaction.create(2, 0, [], txouts)
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_addr,
                            target_amount=0,
                            effective_fee_rate=20.0,
                            knapsack_min_change=1)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             amount=utxo.amount,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # create tx (output wpkh only, input multisig tx1-3)
    txid = tx.txid
    txin_list = []
    txin_utxo_list = []
    for index, txout in enumerate(tx.txout_list):
        temp_addr = str(txout.get_address(network=NETWORK))
        if temp_addr == fee_addr:
            continue
        txin_list.append(TxIn(txid=txid, vout=index))
        if temp_addr not in test_obj.desc_dic:
            test_obj.assertTrue(
                False, 'addr not found. [{}]:[{}]'.format(index, temp_addr))
        desc = test_obj.desc_dic[temp_addr]
        txin_utxo_list.append(
            UtxoData(txid=txid,
                     vout=index,
                     amount=txout.amount,
                     descriptor=desc))
    txouts2 = [
        TxOut(300000000, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=20.0,
                             knapsack_min_change=1)

    # add sign

    def multisig_sign(tx_obj, utxo, path_list):
        sighash = tx_obj.get_sighash(
            outpoint=utxo.outpoint,
            hash_type=utxo.descriptor.data.hash_type,
            amount=utxo.amount,
            redeem_script=utxo.descriptor.data.redeem_script)
        signature_list = []
        for path in path_list:
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            sig = sk.calculate_ec_signature(sighash)
            sig.related_pubkey = sk.pubkey
            signature_list.append(sig)
            if len(signature_list) == 2:
                break
        tx_obj.add_multisig_sign(utxo.outpoint, utxo.descriptor.data.hash_type,
                                 utxo.descriptor.data.redeem_script,
                                 signature_list)

    join_utxo_list = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = utxo_list
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if not utxo.descriptor.data.redeem_script:
            path = test_obj.path_dic[str(utxo.descriptor.data.address)]
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            tx2.sign_with_privkey(txin.outpoint,
                                  utxo.descriptor.data.hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL)
        else:
            path_list = test_obj.path_dic[str(utxo.descriptor.data.address)]
            multisig_sign(tx2, utxo, path_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)
    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 3
0
def update_pegin_tx(test_obj, pegin_tx, btc_tx, pegin_address, claim_script,
                    txout_proof) -> str:
    pegin_tx2 = pegin_tx
    btc_tx_obj = Transaction.from_hex(btc_tx)
    btc_txid = btc_tx_obj.txid
    btc_txout_index = btc_tx_obj.get_txout_index(address=pegin_address)
    btc_amount = btc_tx_obj.txout_list[btc_txout_index].amount
    btc_size = len(btc_tx) / 2
    txoutproof_size = len(txout_proof) / 2

    # decode
    tx = ConfidentialTransaction.from_hex(pegin_tx)
    target_script_pubkey = ''
    target_amount = 0
    target_index = 0
    # fee_index = -1
    fee_amount = 0
    has_fee = len(tx.txout_list) == 2
    for index, txout in enumerate(tx.txout_list):
        if len(txout.locking_script.hex) > 0:
            target_script_pubkey = str(txout.locking_script)
            target_amount = txout.amount
            target_index = index
        else:
            fee_amount = txout.amount
            # fee_index = index
    # change script pubkey (string replace)
    target_script_pubkey = '16' + target_script_pubkey

    fee_addr = test_obj.addr_dic['fee']
    new_script_pubkey = '16' + str(fee_addr.locking_script)
    pegin_tx2 = pegin_tx.replace(target_script_pubkey, new_script_pubkey)
    tx = ConfidentialTransaction.from_hex(pegin_tx2)
    total_amount = target_amount + fee_amount
    utxo_amount = 0
    if has_fee:
        utxo_amount = total_amount - btc_amount

    # add txout
    tx.add_txout(amount=1,
                 address=test_obj.ct_addr_dic[str(test_obj.addr_dic['main'])],
                 asset=test_obj.pegged_asset)

    # calc fee
    pegin_utxo = ElementsUtxoData(
        txid=btc_txid,
        vout=btc_txout_index,
        amount=btc_amount,
        descriptor='wpkh({})'.format('02' * 33),  # dummy
        asset=test_obj.pegged_asset,
        is_pegin=True,
        pegin_btc_tx_size=int(btc_size),
        pegin_txoutproof_size=int(txoutproof_size),
        claim_script=claim_script)
    utxo_list = [pegin_utxo]
    if utxo_amount > 0:
        for txin in tx.txin_list:
            if txin.outpoint.txid != btc_txid:
                utxo = ElementsUtxoData(outpoint=txin.outpoint,
                                        amount=utxo_amount,
                                        descriptor='',
                                        asset=test_obj.pegged_asset)
                utxo_list.append(utxo)
                break
    calc_fee, _, _ = tx.estimate_fee(utxo_list, test_obj.pegged_asset)
    # update fee
    tx.update_txout_fee_amount(calc_fee)

    # change amount
    new_amount = total_amount - calc_fee - 1
    tx.update_txout_amount(target_index, new_amount)

    # blind
    fee_ct_addr = test_obj.ct_addr_dic[str(fee_addr)]
    print('before blind tx=', str(tx))
    tx.blind_txout(utxo_list, confidential_address_list=[fee_ct_addr])
    return str(tx)
Exemplo n.º 4
0
            if 'lockingScript' in utxo:
                script = utxo['lockingScript']
                desc = f'raw({script})'
        data = UtxoData(txid=utxo['txid'],
                        vout=utxo['vout'],
                        amount=utxo['amount'],
                        descriptor=desc)
        result.append(data)
    return result


def test_transaction_func1(obj, name, case, req, exp, error):
    try:
        resp = None
        if 'tx' in req:
            resp = Transaction.from_hex(req['tx'])
        txins, txouts = [], []
        for input in req.get('txins', []):
            txins.append(
                TxIn(txid=input['txid'],
                     vout=input['vout'],
                     sequence=input.get('sequence', TxIn.SEQUENCE_DISABLE)))
        for output in req.get('txouts', []):
            txouts.append(
                TxOut(output['amount'],
                      address=output.get('address', ''),
                      locking_script=output.get('directLockingScript', '')))

        if name == 'Transaction.Create':
            resp = Transaction.create(req['version'], req['locktime'], txins,
                                      txouts)
Exemplo n.º 5
0
    def test_create_raw_transaction(self):
        privkey = ExtPrivkey(
            'xprv9zt1onyw8BdEf7SQ6wUVH3bQQdGD9iy9QzXveQQRhX7i5iUN7jZgLbqFEe491LfjozztYa6bJAGZ65GmDCNcbjMdjZcgmdisPJwVjcfcDhV'
        )  # noqa: E501
        addr1 = AddressUtil.p2wpkh(
            privkey.derive_pubkey(number=1).pubkey, Network.REGTEST)
        addr2 = AddressUtil.p2wpkh(
            privkey.derive_pubkey(number=2).pubkey, Network.REGTEST)
        addr3 = AddressUtil.p2wpkh(
            privkey.derive_pubkey(number=3).pubkey, Network.REGTEST)

        outpoint1 = OutPoint(
            '0000000000000000000000000000000000000000000000000000000000000001',
            2)
        outpoint2 = OutPoint(
            '0000000000000000000000000000000000000000000000000000000000000001',
            3)
        txin1 = TxIn(outpoint=outpoint1)
        txout1 = TxOut(amount=10000, locking_script=addr1.locking_script)
        txout2 = TxOut(amount=10000, address=addr2)
        self.assertEqual(str(outpoint1), str(txin1))
        self.assertEqual(str(addr1.locking_script), str(txout1))
        self.assertEqual(str(addr2), str(txout2))
        self.assertEqual(str(addr1), str(txout1.get_address(Network.REGTEST)))

        tx = Transaction.create(version=2,
                                locktime=0,
                                txins=[
                                    txin1,
                                    TxIn(outpoint=outpoint2),
                                ],
                                txouts=[
                                    txout1,
                                    txout2,
                                ])
        tx.add_txout(amount=50000, address=addr3)
        self.assertEqual(
            "020000000201000000000000000000000000000000000000000000000000000000000000000200000000ffffffff01000000000000000000000000000000000000000000000000000000000000000300000000ffffffff0310270000000000001600148b756cbd98f4f55e985f80437a619d47f0732a941027000000000000160014c0a3dd0b7c1b3281be91112e16ce931dbac2a97950c3000000000000160014ad3abd3c325e40e20d89aa054dd980b97494f16c00000000",  # noqa: E501
            tx.hex)

        privkey1 = privkey.derive(number=11).privkey
        pubkey1 = privkey1.pubkey
        sighash_type = SigHashType.ALL
        sighash = tx.get_sighash(outpoint=outpoint1,
                                 hash_type=HashType.P2WPKH,
                                 pubkey=pubkey1,
                                 amount=50000,
                                 sighashtype=sighash_type)
        signature = privkey1.calculate_ec_signature(sighash)
        tx.add_sign(outpoint=outpoint1,
                    hash_type=HashType.P2WPKH,
                    sign_data=signature,
                    clear_stack=True,
                    use_der_encode=True,
                    sighashtype=sighash_type)
        tx.add_sign(outpoint=outpoint1,
                    hash_type=HashType.P2WPKH,
                    sign_data=pubkey1)
        self.assertEqual(
            "0200000000010201000000000000000000000000000000000000000000000000000000000000000200000000ffffffff01000000000000000000000000000000000000000000000000000000000000000300000000ffffffff0310270000000000001600148b756cbd98f4f55e985f80437a619d47f0732a941027000000000000160014c0a3dd0b7c1b3281be91112e16ce931dbac2a97950c3000000000000160014ad3abd3c325e40e20d89aa054dd980b97494f16c02473044022034db802aad655cd9be589075fc8ef325b6ffb8c24e5b27eb87bde8ad38f5fd7a0220364c916c8e8fc0adf714d7148cd1c6dc6f3e67d55471e57233b1870c65ec2727012103782f0ea892d7000e5f0f82b6ff283382a76500137a542bb0a616530094a8f54c0000000000",  # noqa: E501
            tx.hex)
Exemplo n.º 6
0
def test_taproot_tapscript(test_obj: 'TestBitcoin'):
    btc_rpc = test_obj.conn.get_rpc()
    main_addr = test_obj.addr_dic['main']
    main_pk, _ = SchnorrPubkey.from_pubkey(str(main_addr.pubkey))
    pkh_addr = test_obj.addr_dic['p2pkh']
    spk1, _ = SchnorrPubkey.from_pubkey(str(pkh_addr.pubkey))
    wpkh_addr = test_obj.addr_dic['p2wpkh']
    spk2, _ = SchnorrPubkey.from_pubkey(str(wpkh_addr.pubkey))
    main_path = str(test_obj.path_dic[str(main_addr)])
    main_sk = test_obj.hdwallet.get_privkey(path=main_path).privkey
    pkh_path = str(test_obj.path_dic[str(pkh_addr)])
    sk1 = test_obj.hdwallet.get_privkey(path=pkh_path).privkey
    # wpkh_path = str(test_obj.path_dic[str(wpkh_addr)])
    # sk2 = test_obj.hdwallet.get_privkey(path=wpkh_path).privkey

    script1 = Script.from_asm([str(spk1), 'OP_CHECKSIG'])
    script2 = Script.from_asm([str(spk2), 'OP_CHECKSIG'])
    op_true_script = Script('51')
    op_true_sub_tree1 = TaprootScriptTree(op_true_script)
    op_true_sub_tree1.add_branch(script1)

    script1_tree = TaprootScriptTree(script1)
    script1_tree.add_branches([op_true_script, script2])
    script1_tree.internal_pubkey = main_pk

    op_true_tree = TaprootScriptTree(op_true_script)
    op_true_tree.add_branches([script1, script2])
    op_true_tree.internal_pubkey = main_pk

    script2_tree = TaprootScriptTree(script2)
    script2_tree.add_branch(op_true_sub_tree1)
    script2_tree.internal_pubkey = main_pk

    tr_addr1 = AddressUtil.taproot(script1_tree, network=NETWORK)
    tr_addr2 = AddressUtil.taproot(op_true_tree, network=NETWORK)
    tr_addr3 = AddressUtil.taproot(script2_tree, network=NETWORK)

    txouts = [
        TxOut(100000, str(tr_addr1)),
        TxOut(150000, str(tr_addr2)),
        TxOut(200000, str(tr_addr3)),
    ]
    tx = Transaction.create(2, 0, [], txouts)
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_addr,
                            target_amount=0,
                            effective_fee_rate=2.0,
                            knapsack_min_change=0)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             amount=utxo.amount,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    txid = tx.txid
    utxo1 = UtxoData(txid=txid,
                     vout=0,
                     amount=txouts[0].amount,
                     descriptor=f'raw({str(tr_addr1.locking_script)})')
    utxo2 = UtxoData(txid=txid,
                     vout=1,
                     amount=txouts[1].amount,
                     descriptor=f'raw({str(tr_addr2.locking_script)})')
    utxo3 = UtxoData(txid=txid,
                     vout=2,
                     amount=txouts[2].amount,
                     descriptor=f'raw({str(tr_addr3.locking_script)})')

    # send tapscript script1
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=0))
    txin_utxo_list.append(utxo1)
    txouts2 = [
        TxOut(txouts[0].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list: List['UtxoData'] = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sk = sk1
            sighash = tx2.get_sighash(txin.outpoint,
                                      HashType.TAPROOT,
                                      redeem_script=script1,
                                      sighashtype=SigHashType.DEFAULT,
                                      utxos=join_utxo_list)
            sig = SchnorrUtil.sign(sighash, sk1)
            sign_param = SignParameter(sig, sighashtype=SigHashType.DEFAULT)
            _, _, _, control_block = script1_tree.get_taproot_data()
            tx2.add_tapscript_sign(txin.outpoint, [sign_param], script1,
                                   control_block)
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
            tx2.sign_with_privkey(txin.outpoint,
                                  hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL,
                                  utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # send tapscript OP_TRUE
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=1))
    txin_utxo_list.append(utxo2)
    txouts2 = [
        TxOut(txouts[1].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            _, _, _, control_block = op_true_tree.get_taproot_data()
            tx2.add_tapscript_sign(txin.outpoint, [], op_true_script,
                                   control_block)
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
            tx2.sign_with_privkey(txin.outpoint,
                                  hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL,
                                  utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # send tapscript internal_pubkey
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=2))
    txin_utxo_list.append(utxo3)
    txouts2 = [
        TxOut(txouts[2].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sk = script2_tree.get_privkey(main_sk)
            hash_type = tr_addr3.hash_type
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
        tx2.sign_with_privkey(txin.outpoint,
                              hash_type,
                              sk,
                              amount=utxo.amount,
                              sighashtype=SigHashType.ALL,
                              utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 7
0
def test_taproot_single_key(test_obj: 'TestBitcoin'):
    btc_rpc = test_obj.conn.get_rpc()
    main_addr = test_obj.addr_dic['main']
    main_pk, _ = SchnorrPubkey.from_pubkey(str(main_addr.pubkey))
    pkh_addr = test_obj.addr_dic['p2pkh']
    spk1, _ = SchnorrPubkey.from_pubkey(str(pkh_addr.pubkey))
    wpkh_addr = test_obj.addr_dic['p2wpkh']
    spk2, _ = SchnorrPubkey.from_pubkey(str(wpkh_addr.pubkey))
    main_path = str(test_obj.path_dic[str(main_addr)])
    main_sk = test_obj.hdwallet.get_privkey(path=main_path).privkey
    pkh_path = str(test_obj.path_dic[str(pkh_addr)])
    sk1 = test_obj.hdwallet.get_privkey(path=pkh_path).privkey
    wpkh_path = str(test_obj.path_dic[str(wpkh_addr)])
    sk2 = test_obj.hdwallet.get_privkey(path=wpkh_path).privkey

    branch = TapBranch()
    tr_addr1 = AddressUtil.taproot(main_pk,
                                   script_tree=branch,
                                   network=NETWORK)
    tr_sk1 = branch.get_privkey(main_sk)
    tr_addr2 = AddressUtil.taproot(spk1, script_tree=branch, network=NETWORK)
    tr_sk2 = branch.get_privkey(sk1)
    tr_addr3 = AddressUtil.taproot(spk2, script_tree=branch, network=NETWORK)
    tr_sk3 = branch.get_privkey(sk2)

    txouts = [
        TxOut(100000, str(tr_addr1)),
        TxOut(150000, str(tr_addr2)),
        TxOut(200000, str(tr_addr3)),
    ]
    tx = Transaction.create(2, 0, [], txouts)
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_addr,
                            target_amount=0,
                            effective_fee_rate=2.0,
                            knapsack_min_change=0)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             amount=utxo.amount,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    txid = tx.txid
    utxo1 = UtxoData(txid=txid,
                     vout=0,
                     amount=txouts[0].amount,
                     descriptor=f'raw({str(tr_addr1.locking_script)})')
    utxo2 = UtxoData(txid=txid,
                     vout=1,
                     amount=txouts[1].amount,
                     descriptor=f'raw({str(tr_addr2.locking_script)})')
    utxo3 = UtxoData(txid=txid,
                     vout=2,
                     amount=txouts[2].amount,
                     descriptor=f'raw({str(tr_addr3.locking_script)})')

    # send taproot singleKey1
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=0))
    txin_utxo_list.append(utxo1)
    txouts2 = [
        TxOut(txouts[0].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list: List['UtxoData'] = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sighash = tx2.get_sighash(txin.outpoint,
                                      HashType.TAPROOT,
                                      pubkey=tr_addr1.pubkey,
                                      sighashtype=SigHashType.DEFAULT,
                                      utxos=join_utxo_list)
            sig = SchnorrUtil.sign(sighash, tr_sk1)
            sign_param = SignParameter(sig, sighashtype=SigHashType.DEFAULT)
            tx2.add_taproot_sign(txin.outpoint, sign_param)
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
            tx2.sign_with_privkey(txin.outpoint,
                                  hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL,
                                  utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # send taproot singleKey2
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=1))
    txin_utxo_list.append(utxo2)
    txouts2 = [
        TxOut(txouts[1].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sighash = tx2.get_sighash(txin.outpoint,
                                      HashType.TAPROOT,
                                      pubkey=tr_addr2.pubkey,
                                      sighashtype=SigHashType.DEFAULT,
                                      utxos=join_utxo_list)
            sig = SchnorrUtil.sign(sighash, tr_sk2)
            sign_param = SignParameter(sig, sighashtype=SigHashType.DEFAULT)
            tx2.add_taproot_sign(txin.outpoint, sign_param)
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
            tx2.sign_with_privkey(txin.outpoint,
                                  hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL,
                                  utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # send taproot singleKey3
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=2))
    txin_utxo_list.append(utxo3)
    txouts2 = [
        TxOut(txouts[2].amount, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=2.0,
                             knapsack_min_change=0)
    # add sign
    join_utxo_list = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sighash = tx2.get_sighash(txin.outpoint,
                                      HashType.TAPROOT,
                                      pubkey=tr_addr3.pubkey,
                                      sighashtype=SigHashType.DEFAULT,
                                      utxos=join_utxo_list)
            sig = SchnorrUtil.sign(sighash, tr_sk3)
            sign_param = SignParameter(sig, sighashtype=SigHashType.DEFAULT)
            tx2.add_taproot_sign(txin.outpoint, sign_param)
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
            tx2.sign_with_privkey(txin.outpoint,
                                  hash_type,
                                  sk,
                                  amount=utxo.amount,
                                  sighashtype=SigHashType.ALL,
                                  utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 8
0
def test_taproot_schnorr(test_obj: 'TestBitcoin'):
    btc_rpc = test_obj.conn.get_rpc()
    main_addr = test_obj.addr_dic['main']
    main_pk, _ = SchnorrPubkey.from_pubkey(str(main_addr.pubkey))
    tr_addr = AddressUtil.taproot(main_pk, network=NETWORK)
    main_path = str(test_obj.path_dic[str(main_addr)])
    main_sk = test_obj.hdwallet.get_privkey(path=main_path).privkey

    txouts = [
        TxOut(100000000, str(tr_addr)),
    ]
    tx = Transaction.create(2, 0, [], txouts)
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_addr,
                            target_amount=0,
                            effective_fee_rate=2.0,
                            knapsack_min_change=0)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             amount=utxo.amount,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # create tx (output wpkh only, input tx1-3)
    txid = tx.txid
    txin_list = []
    txin_utxo_list = []
    txin_list.append(TxIn(txid=txid, vout=0))
    desc = f'raw({str(tr_addr.locking_script)})'
    txin_utxo_list.append(
        UtxoData(txid=txid, vout=0, amount=txouts[0].amount, descriptor=desc))
    txouts2 = [
        TxOut(100000000, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=20.0,
                             knapsack_min_change=1)
    # add sign
    join_utxo_list: List['UtxoData'] = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        for utxo in utxo_list:
            if utxo.outpoint == txin.outpoint:
                join_utxo_list.append(utxo)
    for index, txin in enumerate(tx2.txin_list):
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        if index == 0:
            sk = main_sk
            hash_type = main_addr.hash_type
        else:
            path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
            sk = test_obj.hdwallet.get_privkey(path=path).privkey
            hash_type = utxo.descriptor.data.hash_type
        tx2.sign_with_privkey(txin.outpoint,
                              hash_type,
                              sk,
                              amount=utxo.amount,
                              sighashtype=SigHashType.ALL,
                              utxos=join_utxo_list)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 9
0
def test_psbt(test_obj: 'TestBitcoin'):
    btc_rpc = test_obj.conn.get_rpc()
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [str(fee_addr)])  # listunspent
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    txouts = [
        PsbtAppendOutputData(100000000,
                             address=test_obj.addr_dic['p2pkh'],
                             descriptor=test_obj.desc_dic[str(
                                 test_obj.addr_dic['p2pkh'])]),
        PsbtAppendOutputData(100000000,
                             address=str(test_obj.addr_dic['p2wpkh']),
                             descriptor=test_obj.desc_dic[str(
                                 test_obj.addr_dic['p2wpkh'])]),
        PsbtAppendOutputData(
            100000000,
            address=str(test_obj.addr_dic['p2sh-p2wpkh']),
            descriptor=test_obj.desc_dic[str(
                test_obj.addr_dic['p2sh-p2wpkh'])],
        ),
    ]
    psbt = Psbt.create(tx_version=2, network=NETWORK)
    psbt.add(outputs=txouts)
    psbt.fund(utxo_list=utxo_list,
              reserved_address_descriptor=test_obj.desc_dic[str(fee_addr)],
              effective_fee_rate=2.0,
              long_term_fee_rate=2.0,
              knapsack_min_change=0)
    psbt.sign(fee_sk)
    # bitcoinrpc: finalize extract
    ret = btc_rpc.finalizepsbt(str(psbt), True)
    tx_hex = ret['hex'] if 'hex' in ret else ''
    if not ret.get('complete', True):
        raise AssertionError("finalizepsbt not complete.")
    print(Transaction.parse_to_json(tx_hex, network=NETWORK))
    txid = btc_rpc.sendrawtransaction(tx_hex)
    tx = Transaction(tx_hex)
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)
    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))

    txid = tx.txid
    txin_list = []
    key_list = []
    for index, _ in enumerate(txouts):
        txout = tx.txout_list[index]
        addr = txout.get_address(network=NETWORK)
        desc = test_obj.desc_dic[str(addr)]
        txin_list.append(
            PsbtAppendInputData(outpoint=OutPoint(txid, index),
                                utxo=txout,
                                descriptor=str(desc),
                                utxo_tx=tx_hex))
        path = str(test_obj.path_dic[str(addr)])
        key_list.append(test_obj.hdwallet.get_privkey(path=path).privkey)
    txouts2 = [
        TxOut(300000000, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, [], txouts2)
    psbt2 = Psbt.from_transaction(transaction=tx2, network=NETWORK)
    psbt2.set_output_bip32_key(0,
                               pubkey=str(test_obj.desc_dic[str(
                                   txouts2[0].address)]))
    psbt2.add(inputs=txin_list)
    utxos = get_utxo(btc_rpc, [str(fee_addr)])  # listunspent
    utxo_list2 = convert_bitcoin_utxos(test_obj, utxos)
    psbt2.fund(utxo_list=utxo_list2,
               reserved_address_descriptor=test_obj.desc_dic[str(fee_addr)],
               effective_fee_rate=2.0,
               long_term_fee_rate=2.0,
               knapsack_min_change=0)
    psbt21 = Psbt(str(psbt2), network=NETWORK)
    psbt22 = Psbt(str(psbt2), network=NETWORK)
    psbt21.sign(fee_sk)
    for key in key_list:
        psbt22.sign(key)
    # psbt2_str = btc_rpc.combinepsbt([str(psbt21), str(psbt22)])
    # psbt2 = Psbt(psbt2_str, network=NETWORK)
    psbt2 = Psbt.combine_psbts([str(psbt21), psbt22])
    tx2 = psbt2.extract(True)
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    txid = btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)
    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 10
0
def test_bitcoin_pkh(test_obj: 'TestBitcoin'):
    btc_rpc = test_obj.conn.get_rpc()
    # create tx (output wpkh, p2sh-segwit, pkh)
    txouts = [
        TxOut(100000000, str(test_obj.addr_dic['p2pkh'])),
        TxOut(100000000, str(test_obj.addr_dic['p2wpkh'])),
        TxOut(100000000, str(test_obj.addr_dic['p2sh-p2wpkh'])),
    ]
    tx = Transaction.create(2, 0, [], txouts)
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_addr,
                            target_amount=0,
                            effective_fee_rate=20.0,
                            knapsack_min_change=1)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             amount=utxo.amount,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)

    # create tx (output wpkh only, input tx1-3)
    txid = tx.txid
    txin_list = []
    txin_utxo_list = []
    for index, txout in enumerate(tx.txout_list):
        temp_addr = str(txout.get_address(network=NETWORK))
        if temp_addr == fee_addr:
            continue
        txin_list.append(TxIn(txid=txid, vout=index))
        if temp_addr not in test_obj.desc_dic:
            test_obj.assertTrue(
                False, 'addr not found. [{}]:[{}]'.format(index, temp_addr))
        desc = test_obj.desc_dic[temp_addr]
        txin_utxo_list.append(
            UtxoData(txid=txid,
                     vout=index,
                     amount=txout.amount,
                     descriptor=desc))
    txouts2 = [
        TxOut(300000000, str(test_obj.addr_dic['main'])),
    ]
    tx2 = Transaction.create(2, 0, txin_list, txouts2)
    main_addr = test_obj.addr_dic['main']
    utxos = get_utxo(btc_rpc, [fee_addr])
    utxo_list = convert_bitcoin_utxos(test_obj, utxos)
    tx2.fund_raw_transaction(txin_utxo_list,
                             utxo_list,
                             fee_addr,
                             target_amount=0,
                             effective_fee_rate=20.0,
                             knapsack_min_change=1)
    # add sign
    join_utxo_list: List['UtxoData'] = []
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = utxo_list
    join_utxo_list[len(join_utxo_list):len(join_utxo_list)] = txin_utxo_list
    for txin in tx2.txin_list:
        utxo = search_utxos(test_obj, join_utxo_list, txin.outpoint)
        path = str(test_obj.path_dic[str(utxo.descriptor.data.address)])
        sk = test_obj.hdwallet.get_privkey(path=path).privkey
        tx2.sign_with_privkey(txin.outpoint,
                              utxo.descriptor.data.hash_type,
                              sk,
                              amount=utxo.amount,
                              sighashtype=SigHashType.ALL)
    # broadcast
    print(Transaction.parse_to_json(str(tx2), network=NETWORK))
    btc_rpc.sendrawtransaction(str(tx2))
    # generate block
    btc_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)
    utxos = get_utxo(btc_rpc, [str(main_addr)])
    print('UTXO: {}'.format(utxos))
Exemplo n.º 11
0
def test_elements_dynafed(test_obj):
    btc_rpc = test_obj.btcConn.get_rpc()
    elm_rpc = test_obj.elmConn.get_rpc()

    # generate block
    chaininfo = elm_rpc.getblockchaininfo()
    epoch_length = chaininfo['epoch_length']
    epoch_age = chaininfo['epoch_age']
    gen_num = epoch_length - epoch_age - 1
    addr = str(test_obj.addr_dic['gen'])
    elm_rpc.generatetoaddress(gen_num, addr)
    # generate dynafed block

    block_data = elm_rpc.getnewblockhex(
        0, {
            "signblockscript": WSH_OP_TRUE,
            "max_block_witness": 500,
            "fedpegscript": new_fedpeg_script,
            "extension_space": [pak1],
        })
    elm_rpc.submitblock(block_data)
    elm_rpc.getblockchaininfo()
    elm_rpc.getsidechaininfo()
    elm_rpc.getblock(chaininfo['bestblockhash'])
    generatetoaddress_dynafed(test_obj, epoch_length)
    time.sleep(2)
    chaininfo = elm_rpc.getblockchaininfo()
    sidechaininfo = elm_rpc.getsidechaininfo()

    # generate pegin address
    path = '{}/0/0'.format(ROOT_PATH)
    main_ext_sk = test_obj.hdwallet.get_privkey(path=path)
    main_sk = str(main_ext_sk.privkey)
    main_pk = str(main_ext_sk.privkey.pubkey)
    pegin_address, claim_script, tweaked = AddressUtil.get_pegin_address(
        fedpeg_script=new_fedpeg_script,
        pubkey=main_pk,
        mainchain_network=Network.REGTEST,
        hash_type=HashType.P2WSH)  # TODO: Dynafed mode (need p2wsh)
    pegin_address = str(pegin_address)
    claim_script = claim_script.hex
    print(f'pegin_address[{pegin_address}]')
    print(f'claim_script[{claim_script}]')
    print(f'tweaked_fedpeg_script[{tweaked}]')
    # pegin_addr_info = elm_rpc.getpeginaddress()
    # pegin_address = pegin_addr_info['mainchain_address']
    # claim_script = pegin_addr_info['claim_script']

    for i in range(3):
        try:
            blk_cnt = btc_rpc.getblockcount() + 1
            # send bitcoin
            utxos = get_utxo(btc_rpc, [])
            amount = 0
            for utxo in utxos:
                amount += utxo['amount']
            amount -= 1
            if amount > 100:
                amount = 100
            txid = btc_rpc.sendtoaddress(pegin_address, amount)

            # generate bitcoin 100 block
            addr = str(test_obj.addr_dic['btc'])
            btc_rpc.generatetoaddress(101, addr)
            max_blk_cnt = btc_rpc.getblockcount()

            txout_proof = None
            for i in range(max_blk_cnt - blk_cnt):
                blk_hash = btc_rpc.getblockhash(blk_cnt + i)
                block_hex = btc_rpc.getblock(blk_hash, 0)
                block = Block(block_hex)
                if block.exist_txid(txid):
                    tx_data, txout_proof = block.get_tx_data(txid)
                    print(f'pegin block: {str(block)}')
                    break

            if txout_proof is None:
                raise Exception('txoutproof is empty.')

            # pegin transaction for fee address
            # tx_data = btc_rpc.gettransaction(txid)['hex']
            tx = Transaction(tx_data)
            vout = tx.get_txout_index(pegin_address)
            pegged_amount = tx.txout_list[vout].amount
            # txout_proof = btc_rpc.gettxoutproof([txid])
            # pegin_tx = elm_rpc.createrawpegin(
            #     tx_data, txout_proof, claim_script)['hex']
            # pegin_tx = update_pegin_tx(
            #     test_obj, pegin_tx, tx_data, pegin_address, txout_proof)
            pegin_tx = create_pegin_tx(test_obj, tx, pegin_address,
                                       txout_proof, claim_script)
            ct = ConfidentialTransaction(pegin_tx)
            ct.sign_with_privkey(OutPoint(txid, vout), HashType.P2WPKH,
                                 main_sk, pegged_amount)
            pegin_tx = str(ct)
            # broadcast
            print(
                ConfidentialTransaction.parse_to_json(pegin_tx,
                                                      network=NETWORK))
            txid = elm_rpc.sendrawtransaction(pegin_tx)
            test_obj.tx_dic[txid] = pegin_tx
            # generatetoaddress -> gen address
            addr = str(test_obj.addr_dic['gen'])
            # elm_rpc.generatetoaddress(2, addr)
            generatetoaddress_dynafed(test_obj, 2)
            time.sleep(2)
        except Exception as err:
            print('Exception({})'.format(i))
            raise err

    # generatetoaddress -> gen address
    addr = str(test_obj.addr_dic['gen'])
    # elm_rpc.generatetoaddress(100, addr)
    generatetoaddress_dynafed(test_obj, 100)
    # elm_rpc.generatetoaddress(5, addr)
    generatetoaddress_dynafed(test_obj, 5)
    time.sleep(2)
    fee_addr = test_obj.addr_dic['fee']
    utxos = get_utxo(elm_rpc, [str(fee_addr)])
    # utxos = get_utxo(elm_rpc, [])
    print('UTXO: {}'.format(utxos))

    # pegout
    pegout_amount = 1000000
    counter = 3
    mainchain_bip32 = 'tpubDDbMfNVnS7fmrTyv98A1bPydovdx2GhaxVAfvgPztEw3R3J2bZ7c2yy3oHx1D3ivjEH5tidRdA766QC83omWBtoUN7CBrk6vyogkTEPUb5b'  # noqa: E501
    pegout_descriptor = f'pkh({mainchain_bip32}/0/*)'
    online_key = 'cVSf1dmLm1XjafyXSXn955cyb2uabdtXxjBXx6fHMQLPQKzHCpT7'
    online_pubkey = \
        '024fb0908ea9263bedb5327da23ff914ce1883f851337d71b3ca09b32701003d05'
    whitelist = ''.join(chaininfo['extension_space'])
    txouts = [
        ConfidentialTxOut(100000000,
                          test_obj.ct_addr_dic[str(
                              test_obj.addr_dic['p2wsh'])],
                          asset=test_obj.pegged_asset),
    ]
    tx = ConfidentialTransaction.create(2, 0, [], txouts)
    tx.add_pegout_output(
        asset=test_obj.pegged_asset,
        amount=pegout_amount,
        mainchain_network_type=Network.REGTEST,
        elements_network_type=Network.ELEMENTS_REGTEST,
        mainchain_genesis_block_hash=sidechaininfo['parent_blockhash'],
        online_pubkey=online_pubkey,
        master_online_key=online_key,
        mainchain_output_descriptor=pegout_descriptor,
        bip32_counter=counter,
        whitelist=whitelist,
    )
    # fundrawtransaction
    fee_addr = str(test_obj.addr_dic['fee'])
    fee_desc = test_obj.desc_dic[fee_addr]
    fee_ct_addr = test_obj.ct_addr_dic[fee_addr]
    fee_sk = test_obj.hdwallet.get_privkey(path=FEE_PATH).privkey
    # utxos = get_utxo(elm_rpc, [fee_addr])
    utxo_list = convert_elements_utxos(test_obj, utxos)
    target_list = [
        TargetAmountData(amount=1,
                         asset=test_obj.pegged_asset,
                         reserved_address=fee_ct_addr)
    ]
    tx.fund_raw_transaction([],
                            utxo_list,
                            fee_asset=test_obj.pegged_asset,
                            target_list=target_list,
                            effective_fee_rate=0.1,
                            knapsack_min_change=1)
    # blind
    blind_utxo_list = []
    for txin in tx.txin_list:
        blind_utxo_list.append(search_utxos(test_obj, utxo_list,
                                            txin.outpoint))
    tx.blind_txout(blind_utxo_list)
    # add sign
    for txin in tx.txin_list:
        utxo = search_utxos(test_obj, utxo_list, txin.outpoint)
        tx.sign_with_privkey(txin.outpoint,
                             fee_desc.data.hash_type,
                             fee_sk,
                             value=utxo.value,
                             sighashtype=SigHashType.ALL)
    # broadcast
    print(ConfidentialTransaction.parse_to_json(str(tx), network=NETWORK))
    elm_rpc.sendrawtransaction(str(tx))
    # generate block
    elm_rpc.generatetoaddress(2, fee_addr)
    time.sleep(2)
Exemplo n.º 12
0
         req['version'],
         req['locktime'],
         network=req.get(
             'network',
             Network.MAINNET))
     for txin in req.get('txins', []):
         sequence = txin.get('sequence', TxIn.SEQUENCE_DISABLE)
         if (sequence == TxIn.SEQUENCE_DISABLE) and (
                 req['locktime'] != 0):
             sequence = TxIn.SEQUENCE_FINAL
         resp.add_input(OutPoint(txin['txid'], txin['vout']),
                        sequence=sequence)
     for txout in req.get('txouts', []):
         resp.add_output(txout['amount'], address=txout['address'])
 elif name == 'Psbt.ConvertToPsbt':
     tx = Transaction(req['tx'])
     resp = Psbt.from_transaction(
         tx,
         permit_sig_data=req.get('permitSigData', False),
         network=req.get('network', Network.MAINNET))
 elif name == 'Psbt.JoinPsbts':
     resp = Psbt.join_psbts(req['psbts'], network=req.get(
         'network', Network.MAINNET))
 elif name == 'Psbt.CombinePsbt':
     resp = Psbt.combine_psbts(req['psbts'], network=req.get(
         'network', Network.MAINNET))
 elif name == 'Psbt.FinalizePsbtInput':
     psbt = Psbt(req['psbt'], network=req.get(
         'network', Network.MAINNET))
     for input in req.get('inputs', []):
         scripts = []