Not sure what’s am i missing here in this piece of code. The output is not matching with the correct value and possibly rightfully so as sha256 changes significantly with minor changes.
package main
import (
"fmt"
"crypto/sha256"
"encoding/hex"
)
func main() {
serializedstring := "00000020b7ad78103f526078f2be76b76c6e0f8e7e4cc48d204d26000000000000000000da9a6ff076bd145134d6a590aa7b41fea803a976f3842239cffe2b33cf910783b41c885af8e96117dc1a8566\n"
expectedvalueofhash := "4a79e221c63a7953e2606d359c3394834e237c2d04c836000000000000000000"
first := sha256.New()
first.Write([]byte(serializedstring))
firstout := hex.EncodeToString(first.Sum(nil))
second := sha256.New()
second.Write([]byte(firstout))
secondout := hex.EncodeToString(second.Sum(nil))
fmt.Println("Hash Value derived :", secondout)
fmt.Println("Hash Value expected :", expectedvalueofhash)
}
(The % is a marker in my shell for “No EOL before EOF” and in the terminal its easily distinguishable from the actual output because of its inverted colors)
So we remove the \n from your original input and also use hex.DecodeString as a substitution for xxd -r -p, last but not least let us remove the superflous back and forth encoding from bytes to hex and back between getting the first hash and using it as input in the second stage, and then you get the following code:
package main
import (
"fmt"
"crypto/sha256"
"encoding/hex"
)
func main() {
serializedstring := "00000020b7ad78103f526078f2be76b76c6e0f8e7e4cc48d204d26000000000000000000da9a6ff076bd145134d6a590aa7b41fea803a976f3842239cffe2b33cf910783b41c885af8e96117dc1a8566"
expectedvalueofhash := "4a79e221c63a7953e2606d359c3394834e237c2d04c836000000000000000000"
first := sha256.New()
firstBytes, _ := hex.DecodeString(serializedstring)
first.Write(firstBytes)
second := sha256.New()
second.Write(first.Sum(nil))
secondout := hex.EncodeToString(second.Sum(nil))
fmt.Println("Hash Value derived :", secondout)
fmt.Println("Hash Value expected :", expectedvalueofhash)
}