1#!/usr/bin/env python3
2# Copyright (c) 2019 Daniel Kraft
3# Distributed under the MIT/X11 software license, see the accompanying
4# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6# RPC test for lookups of names by hash rather than preimage.
7
8from test_framework.names import NameTestFramework
9from test_framework.util import *
10
11import hashlib
12
13
14class NameByHashTest (NameTestFramework):
15
16  def set_test_params (self):
17    # We start without -namehashindex initially so that we can test the
18    # "not enabled" error first.
19    self.setup_name_test ([["-namehistory"]] * 1)
20    self.setup_clean_chain = True
21
22  def run_test (self):
23    node = self.nodes[0]
24    node.generate (200)
25
26    name = "testname"
27    nameHex = name.encode ("ascii").hex ()
28    singleHash = hashlib.new ("sha256", name.encode ("ascii")).digest ()
29    doubleHashHex = hashlib.new ("sha256", singleHash).hexdigest ()
30    byHashOptions = {"nameEncoding": "hex", "byHash": "sha256d"}
31
32    # Start by setting up a test name.
33    new = node.name_new (name)
34    node.generate (10)
35    self.firstupdateName (0, name, new, "value")
36    node.generate (5)
37
38    # Check looking up "direct".
39    res = node.name_show (name, {"byHash": "direct"})
40    assert_equal (res["name"], name)
41    assert_equal (res["value"], "value")
42
43    # -namehashindex is not enabled yet.
44    assert_raises_rpc_error (-1, 'namehashindex is not enabled',
45                             node.name_show, doubleHashHex, byHashOptions)
46    assert_equal (node.getindexinfo ("namehash"), {})
47
48    # Restart the node and enable indexing.
49    self.restart_node (0, extra_args=["-namehashindex", "-namehistory"])
50    self.wait_until (
51        lambda: all (i["synced"] for i in node.getindexinfo ().values ()))
52    assert_equal (node.getindexinfo ("namehash"), {
53      "namehash": {
54        "synced": True,
55        "best_block_height": node.getblockcount (),
56      }
57    })
58
59    # Now the lookup by hash should work.
60    res = node.name_show (doubleHashHex, byHashOptions)
61    assert_equal (res["name"], nameHex)
62    assert_equal (res["value"], "value")
63    res = node.name_history (doubleHashHex, byHashOptions)
64    assert_equal (len (res), 1)
65    assert_equal (res[0]["name"], nameHex)
66
67    # Unknown name by hash.
68    assert_raises_rpc_error (-4, "name hash not found",
69                             node.name_show, "42" * 32, byHashOptions)
70
71    # General errors with the parameters.
72    assert_raises_rpc_error (-8, "Invalid value for byHash",
73                             node.name_show, doubleHashHex, {"byHash": "foo"})
74    assert_raises_rpc_error (-8, "must be 32 bytes long",
75                             node.name_show, "abcd", {"byHash": "sha256d"})
76
77
78if __name__ == '__main__':
79  NameByHashTest ().main ()
80