Skip to content

Instantly share code, notes, and snippets.

@pmaoui
Created June 28, 2022 21:08
Show Gist options
  • Save pmaoui/7c0f3f411a0acda6bcadcf7407f850c3 to your computer and use it in GitHub Desktop.
Save pmaoui/7c0f3f411a0acda6bcadcf7407f850c3 to your computer and use it in GitHub Desktop.
Merkle root of a bitcoin block calculated in bash
#!/bin/bash
# usage : ./merkel.sh tx1 tx2 ... txn
# better: ./merkel.sh $(bitcoin-cli getblock {hashOfABlock}|jq -rc '.tx[]')
function concat() {
echo -e "$1$2"
}
function toggleEndian() {
echo $(echo $1 |tac -rs ..)
}
function hash() {
echo $(echo $1|xxd -r -p|sha256sum| tr -d "\n *-"|xxd -r -p|sha256sum| tr -d "\n *-")
}
function merkleTree() {
nbArgs=$#
current=()
if [ $nbArgs -eq 1 ];
then
echo $1
else
if [ $nbArgs -eq 2 ];
then
echo $(hash $(concat $1 $2))
else
i=0
for leaf in $@
do
isOdd=$(expr $nbArgs % 2)
modulo=$(expr $i % 2)
if [ $modulo -eq 0 ];
then
prev=$leaf
if [ $isOdd -eq 1 ];
then
if [ $((i+1)) -eq $# ];
then
current+=($(merkleTree $leaf $leaf))
fi
fi
else
current+=($(merkleTree $prev $leaf))
fi
i=$((i+1))
done
echo $(merkleTree "${current[@]}")
fi
fi
}
function merkleTreeInit() {
params=()
for param in $@
do
params+=($(toggleEndian $param))
done
echo $(toggleEndian $(merkleTree "${params[@]}"))
}
merkleTreeInit $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment