1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| package main
import ( "bytes" "encoding/gob" "log" "crypto/sha256" "fmt" "strings" ) const subsidy = 100 type Transation struct{ ID []byte Vin []TXInput Vout []TXOutput
}
type TXInput struct { TXid []byte Voutindex int Signature []byte }
type TXOutput struct { value int PubkeyHash []byte }
func (tx Transation) String() string { var lines []string
lines = append(lines, fmt.Sprintf("--- Transaction %x:", tx.ID))
for i, input := range tx.Vin { lines = append(lines, fmt.Sprintf(" Input %d:", i)) lines = append(lines, fmt.Sprintf(" TXID: %x", input.TXid)) lines = append(lines, fmt.Sprintf(" Out: %d", input.Voutindex)) lines = append(lines, fmt.Sprintf(" Signature: %x", input.Signature)) }
for i, output := range tx.Vout { lines = append(lines, fmt.Sprintf(" Output %d:", i)) lines = append(lines, fmt.Sprintf(" Value: %d", output.value)) lines = append(lines, fmt.Sprintf(" Script: %x", output.PubkeyHash)) }
return strings.Join(lines, "\n") }
func (tx Transation) Serialize() []byte{ var encoded bytes.Buffer enc:= gob.NewEncoder(&encoded)
err:= enc.Encode(tx)
if err!=nil{ log.Panic(err) } return encoded.Bytes() }
func (tx *Transation) Hash() []byte{
txcopy := *tx txcopy.ID = []byte{}
hash:= sha256.Sum256(txcopy.Serialize())
return hash[:] }
func NewTXOutput(value int,address string) * TXOutput{ txo := &TXOutput{value,nil} txo.PubkeyHash = []byte(address) return txo }
func NewCoinbaseTX(to string) *Transation{ txin := TXInput{[]byte{},-1,nil} txout := NewTXOutput(subsidy,to)
tx:= Transation{nil,[]TXInput{txin},[]TXOutput{*txout}}
tx.ID = tx.Hash()
return &tx }
func main(){ newTX := NewCoinbaseTX("jonson") fmt.Printf("%s",newTX.String())
}
|