add util function for converting txid:nout to claimID

This commit is contained in:
Alex Grintsvayg 2018-03-15 10:47:11 -04:00
parent 4fda52d531
commit 0b1546cc79
No known key found for this signature in database
GPG key ID: AEB3F089F86A22B5

47
util/blockchain.go Normal file
View file

@ -0,0 +1,47 @@
package util
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"golang.org/x/crypto/ripemd160"
)
// rev reverses a byte slice. useful for switching endian-ness
func rev(b []byte) []byte {
r := make([]byte, len(b))
for left, right := 0, len(b)-1; left < right; left, right = left+1, right-1 {
r[left], r[right] = b[right], b[left]
}
return r
}
func ClaimIDFromOutpoint(txid string, nout int) (string, error) {
// convert transaction id to byte array
txidBytes, err := hex.DecodeString(txid)
if err != nil {
return "", err
}
// reverse (make big-endian)
txidBytes = rev(txidBytes)
// append nout
noutBytes := make([]byte, 4) // num bytes in uint32
binary.BigEndian.PutUint32(noutBytes, uint32(nout))
txidBytes = append(txidBytes, noutBytes...)
// sha256 it
s := sha256.New()
s.Write(txidBytes)
// ripemd it
r := ripemd160.New()
r.Write(s.Sum(nil))
// reverse (make little-endian)
res := rev(r.Sum(nil))
return hex.EncodeToString(res), nil
}