From 8d372a34eb7b25fc73cb69124ac02a2c29c539b0 Mon Sep 17 00:00:00 2001 From: OsauravO Date: Fri, 26 Apr 2024 23:50:24 +0530 Subject: [PATCH] transaction serialization fixed --- main.go | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/main.go b/main.go index f514666..0a34d8e 100644 --- a/main.go +++ b/main.go @@ -340,7 +340,67 @@ func Ordering() (uint64, []string, []string) { fmt.Println("reward: ", reward) return reward, permittedTxIDs, permittedWTxIDs } +func SerializeTransaction(tx *Transaction) ([]byte, error) { + + var serialized []byte + // Serialize version + versionBytes := make([]byte, 4) + binary.LittleEndian.PutUint32(versionBytes, tx.Version) + serialized = append(serialized, versionBytes...) + // Serialize vin count + vinCount := uint64(len(tx.Vin)) + serialized = append(serialized, SerializeVarInt(vinCount)...) + + // Serialize vin + for _, vin := range tx.Vin { + txidBytes, _ := hex.DecodeString(vin.TxID) + serialized = append(serialized, ReverseBytes(txidBytes)...) + + voutBytes := make([]byte, 4) + binary.LittleEndian.PutUint32(voutBytes, vin.Vout) + serialized = append(serialized, voutBytes...) + + Scriptsig_bytes, _ := hex.DecodeString(vin.Scriptsig) + length_scriptsig := (uint64(len(Scriptsig_bytes))) + serialized = append(serialized, SerializeVarInt(length_scriptsig)...) + + serialized = append(serialized, Scriptsig_bytes...) + + // Serialize sequence + sequenceBytes := make([]byte, 4) + binary.LittleEndian.PutUint32(sequenceBytes, vin.Sequence) + serialized = append(serialized, sequenceBytes...) + + } + // Serialize vout count + voutCount := uint64(len(tx.Vout)) + serialized = append(serialized, SerializeVarInt(voutCount)...) + + // Serialize vout + for _, vout := range tx.Vout { + valueBytes := make([]byte, 8) + binary.LittleEndian.PutUint64(valueBytes, vout.Value) + serialized = append(serialized, valueBytes...) + + // Serialize scriptPubKey length + scriptPubKeyBytes, err := hex.DecodeString(vout.Scriptpubkey) + scriptPubKeyLen := uint64(len(scriptPubKeyBytes)) // Divide by 2 if appending the length of the non decoded form to get byte length since scriptPubKey is hex encoded + serialized = append(serialized, SerializeVarInt(scriptPubKeyLen)...) + + // Serialize scriptPubKey + if err != nil { + return nil, err + } + serialized = append(serialized, scriptPubKeyBytes...) + } + //Locktime + locktimeBytes := make([]byte, 4) + binary.LittleEndian.PutUint32(locktimeBytes, tx.Locktime) + serialized = append(serialized, locktimeBytes...) + + return serialized, nil +} func main() { networkReward, transactionIDs, _ := Ordering()