-
Notifications
You must be signed in to change notification settings - Fork 30
/
blockheightat.sh
executable file
·51 lines (41 loc) · 1.46 KB
/
blockheightat.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env bash
# shellcheck disable=SC1091
# shellcheck source=./inc.common.sh
. "$(dirname "$(readlink -m "$0")")/inc.common.sh"
if [ "$1" == "" ]; then
echo "Usage: $(basename "$0") [options] timestr"
echo "Where:"
echo " timestr - any date/time string recognized by date command"
exit 0
fi
target_timestr="$1"
target_unixtime=$(date -d "$1" +"%s")
function get_time_at_height()
{
call_bitcoin_cli getblockheader \
"$(call_bitcoin_cli getblockhash "$1")" | jq ".time"
}
start_height=1
start_unixtime=$(get_time_at_height $start_height)
if (( target_unixtime < start_unixtime )); then
echoerr "Requested target time $target_timestr ($target_unixtime) is before block height 1 ($start_unixtime)"
exit 1
fi
end_height=$(call_bitcoin_cli getblockchaininfo | jq ".blocks")
end_unixtime=$(get_time_at_height "$end_height")
if (( target_unixtime >= end_unixtime )); then
echo "$end_height"
exit 0
fi
while (( $(( end_height - start_height )) > 1 )); do
current_height=$(( start_height + (end_height - start_height) / 2 ))
current_unixtime=$(get_time_at_height "$current_height")
if (( current_unixtime > target_unixtime )); then
end_height=$((current_height--))
end_unixtime=$(get_time_at_height "$end_height")
elif (( current_unixtime < target_unixtime )); then
start_height=$((current_height++))
start_unixtime=$(get_time_at_height "$start_height")
fi
done
echo "$start_height"