Post
Topic
Board Development & Technical Discussion
Merits 6 from 2 users
Re: how to get block height for given day
by
pooya87
on 19/02/2023, 03:23:22 UTC
⭐ Merited by Welsh (4) ,ETFbitcoin (2)
Here is another fun way of doing it which is a lot faster and cheaper to do:
If you run a SPV client like Electrum on your computer you already have all the block headers saved up in a ~60 MB file called "blockchain_headers" which is a stream of bytes. All you have to do is to programatically read this file to get the raw bytes which should be a multiple of 80. Then start from the start (byte 0) and extract the time from each 80 byte chunk (ie. one header) knowing that 4th item is the timestamp.
Here is a pseudocode
Code:
stream = File.Read("blockchain_headers")
while(stream.HasBytesLeft)
    stream.Skip(68)
    timestamp = stream.Read(4).ConvertLittleEndian()
    resultList.Add(timestamp)
    stream.Skip(8)
Now all you have to do is search in the list of timestamps to see when the day in the datetime you converted changes to get the last height of the day. The height is the index of the datetime inside the resultList/array.