How are TXIDs decided from the uncooked hex knowledge of a block? Additionally, what’s the coinbase transaction?

0
85


It’s a little-endian double SHA256 hash of the binary transaction knowledge


Some refined errors I’ve seen individuals make:

  • Not changing hex to binary earlier than hashing. Hash("DEADBEEF") shouldn’t be the identical because the required Hash(0xDEADBEEF)
  • Not altering a big-endian consequence to little-endian – reversing the byte order.

See https://go.dev/play/p/PDURm9NTLYm for a labored instance utilizing your knowledge.

bundle principal

import (
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "log"
    "strings"
)

const knowledge string = `0100000001c997a5 e56e104102fa209c 
6a852dd90660a20b 2d9c352423edce25 857fcd3704000000 004847304402204e 
45e16932b8af5149 61a1d3a1a25fdf3f 4f7732e9d624c6c6 1548ab5fb8cd4102 
20181522ec8eca07 de4860a4acdd1290 9d831cc56cbbac46 22082221a8768d1d 
0901ffffffff0200 ca9a3b0000000043 4104ae1a62fe09c5 f51b13905f07f06b 
99a2f7159b2225f3 74cd378d71302fa2 8414e7aab37397f5 54a7df5f142c21c1 
b7303b8a0626f1ba ded5c72a704f7e6c d84cac00286bee00 00000043410411db 
93e1dcdb8a016b49 840f8c53bc1eb68a 382e97b1482ecad7 b148a6909a5cb2e0 
eaddfb84ccf97444 64f82e160bfa9b8b 64f9d4c03f999b86 43f656b412a3ac00 
000000`

const expectedID string = "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16"

func principal() {
    // Take away whitespace in our hex string
    transactionHex := strings.Be part of(strings.Fields(knowledge), "")

    // Convert hex illustration again into binary knowledge
    transactionBin := make([]byte, hex.DecodedLen(len(transactionHex)))
    _, err := hex.Decode(transactionBin, []byte(transactionHex))
    Test(err)

    // Calculate the transaction ID utilizing a double SHA256 hash
    sum := sha256.Sum256(transactionBin)
    sum = sha256.Sum256(sum[:])

    // Reverse the bytes as a result of Bitcoin makes use of little-endian byte-ordering!
    // and convert binary worth to a hex string illustration for human readability
    transactionID := hex.EncodeToString(Reverse(sum[:]))

    // See if we bought the proper worth
    if transactionID == expectedID {
        fmt.Printf("TransactionID is %s as expectedn", transactionID)
    } else {
        fmt.Println("We made a mistake somewheren")
        fmt.Printf("calculated %snexpected  %sn", transactionID, expectedID)
    }
}

func Reverse(enter []byte) []byte {
    l := len(enter)
    reversed := make([]byte, l)
    for i, n := vary enter {
        j := l - i - 1
        reversed[j] = n
    }
    return reversed
}

func Test(err error) {
    if err != nil {
        log.Deadly(err)
    }
}

when run …

TransactionID is f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16 as anticipated

LEAVE A REPLY

Please enter your comment!
Please enter your name here