#!/usr/bin/env python3
# Copyright (c) 2022 The Bitcoin Unlimited developers
"""
Tests for RPC call 'blockchain.address.decode'
"""

import asyncio
from test_framework.environment import on_bch, on_nex
from test_framework.util import assert_equal
from test_framework.electrumutil import (
    ElectrumTestFramework,
)
from test_framework.serialize import from_hex
from test_framework import bch, nex
from test_framework.electrumconnection import ElectrumConnection


class BlockchainHeadersTip(ElectrumTestFramework):
    async def run_test(self):
        n = self.nodes[0]
        await self.bootstrap_p2p()
        cli = ElectrumConnection()
        await cli.connect()
        await self.mine_blocks(cli, n, num_blocks=1)

        tip_hash = n.getbestblockhash()
        tip_height = n.getblockcount()

        tip = await cli.call("blockchain.headers.tip")
        assert_equal(tip_height, tip["height"])

        if on_bch():
            header = from_hex(bch.nodemessages.CBlockHeader(), tip["hex"])
        elif on_nex():
            header = from_hex(nex.nodemessages.CBlockHeader(), tip["hex"])
        else:
            raise NotImplementedError()

        assert_equal(tip_hash, header.gethash("hex"))
        cli.disconnect()


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