Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rpc): fix the implementation of get_block_proof for light client #4585

Merged
merged 2 commits into from
Jul 27, 2021

Conversation

bowenwang1996
Copy link
Collaborator

@bowenwang1996 bowenwang1996 commented Jul 27, 2021

The implementation of get_block_proof has the following issue that caused it to have O(n) complexity sometimes:

        root
         / \ 
       /     \ 
      7       \
   /    \       \
  5       6    \
  / \    / \       \
0   1   2   3    4

In the above example, when we try to prove block 0, the current implementation, when trying to get the sibling of node 7, will do a useless traversal of a full binary tree with 4 leaves, whereas it does not need to recurse when it is known that the position is already outside of the number of leaves we have. More specifically, getting the left child (call to get_merkle_tree_node) should almost always be O(1) except when we are close to the right most leaf of the tree. For example

         / \ 
       /     \
      / \      \       
...   8   9   10  

if we have 11 leaves in the above example (only the rightmost part drawn), then we must get the parent of 8 and 9, and 10, respectively, to prove 0. This is because the parent of 10 will be different once 11 is inserted and the shape of the tree also changes slightly. Therefore, when we are at the parent of 10, we need to recursive in both directions and cannot just go to the left only. This condition is captured by a comparison between index * counter and tree_size.

Test plan

test_block_merkle_proof still works and manually check that the hashmap constructed when we call test_block_merkle_proof_with_len(10000) is roughly log2(10000)^2

@near-bulldozer near-bulldozer bot merged commit 6390d68 into master Jul 27, 2021
@near-bulldozer near-bulldozer bot deleted the fix-light-client-proof branch July 27, 2021 23:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants