Skip to content

Instantly share code, notes, and snippets.

@laalaguer
Last active February 28, 2022 09:23
Show Gist options
  • Select an option

  • Save laalaguer/0cee317aae7892be60bbf5638911502f to your computer and use it in GitHub Desktop.

Select an option

Save laalaguer/0cee317aae7892be60bbf5638911502f to your computer and use it in GitHub Desktop.
Find block that one account has code
# Python
from typing import Union
MAX_RETRACE_BLOCKS = 1000000 # 1 million blocks to retrace at most
def account_has_code (account_address: str, block_number: int) -> bool:
''' Fill your judgment function here, return True/False '''
pass
def get_best_block_number () -> int:
''' Fill in your logic of : get "best" block, return the number of the block'''
pass
def binary_search(account_address: str, start_n: int, end_n: int) -> Union[int, None]:
''' This ensures we find it within log2(N) times, where N = end_n - start_n
N = 1 million, find it in 19.9 times
'''
# oops, not found!
if not (start_n <= end_n):
return None
# found!
if account_has_code(account_address, start_n):
return start_n
pivot = int((start_n + end_n) / 2)
possible_1 = binary_search(account_address, start_n+1, pivot)
if possible_1 is not None:
return possible_1
possible_2 = binary_search(account_address, pivot+1, end_n)
if possible_2 is not None:
return possible_2
return None
def earliest_block_that_account_has_code(account_address: str, max_go_back_blocks: int):
''' Wrapper function to cover some edge cases '''
# Set up boundary
latest_block_n = get_best_block_number()
first_block_n = latest_block_n - max_go_back_blocks
# Anti stupid
if not account_has_code(account_address, latest_block_n):
raise Exception(f"Wow, this account {account_address} doesn't have code at all till now!")
# Anti stupid
if account_has_code(account_address, first_block_n):
raise Exception(f"Wow, this account already has code before {max_go_back_blocks} blocks before, try go more way back!!")
# Now we sure to find the n in the between start and end
return binary_search(account_address, first_block_n, latest_block_n)
if __name__ == "__main__":
earliest_block_that_account_has_code(
# Fill in your params here
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment