#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Unlimited developers
"""
Tests the electrum call 'blockchain.transaction.get_merkle'
"""

import asyncio
from test_framework.util import assert_equal
from test_framework.electrumutil import (
    ElectrumTestFramework,
    ERROR_CODE_INVALID_PARAMS,
    assert_response_error,
    get_txid_from_idem,
    some_amount,
)
from test_framework.electrumconnection import ElectrumConnection


class ElectrumGetMerkle(ElectrumTestFramework):
    async def run_test(self):
        n = self.nodes[0]

        n.generate(110)

        cli = ElectrumConnection()
        await cli.connect()

        await self.test_basic(n, cli)

        cli.disconnect()

    async def test_basic(self, n, cli):
        txid = await get_txid_from_idem(
            n, n.sendtoaddress(n.getnewaddress(), some_amount())
        )
        await self.wait_for_mempool_count(cli, n, count=1)

        # Invalid request, should throw "not confirmed" error
        await assert_response_error(
            lambda: cli.call("blockchain.transaction.get_merkle", txid),
            ERROR_CODE_INVALID_PARAMS,
            "is not confirmed in a block",
        )

        n.generate(1)
        await self.sync_all(cli, n)

        # Test valid request
        height = n.getblockcount()
        res1 = await cli.call("blockchain.transaction.get_merkle", txid, height)

        # rostrum allows height to be optional (outside of specification)
        res2 = await cli.call("blockchain.transaction.get_merkle", txid)
        assert_equal(res1, res2)

        assert_equal(height, res1["block_height"])
        assert "merkle" in res1
        assert_equal(1, res1["pos"])


if __name__ == "__main__":
    asyncio.run(ElectrumGetMerkle().main())
