Skip to content

Commit

Permalink
transaction serialization fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
OsauravO committed Apr 26, 2024
1 parent 7fd82a8 commit 8d372a3
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 8d372a3

Please sign in to comment.