-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransaction.go
More file actions
110 lines (84 loc) · 1.86 KB
/
Copy pathTransaction.go
File metadata and controls
110 lines (84 loc) · 1.86 KB
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
106
107
108
109
package main
import (
"fmt"
"crypto/sha256"
"bytes"
"encoding/gob"
"log"
"encoding/hex"
)
const subsidy = 10
/*
BlockChain transaction
*/
type Transaction struct {
ID []byte
Vin []TXInput
Vout []TXOutput
}
// Hash returns the hash of the Transaction
func (tx *Transaction) Hash() []byte {
var hash [32]byte
txCopy := *tx
txCopy.ID = []byte{}
hash = sha256.Sum256(txCopy.Serialize())
return hash[:]
}
func (tx *Transaction) Serialize() []byte {
var encoded bytes.Buffer
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
return encoded.Bytes()
}
/*
Check if transactions is coin base.
*/
func (tx *Transaction) IsCoinbase() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
/*
Coinbase Transaction constructor
*/
func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Reward to %s", to)
}
txin := TXInput{[]byte{}, -1, data}
txout := TXOutput{subsidy, to}
tx := Transaction{nil, []TXInput{txin}, []TXOutput{txout}}
tx.ID = tx.Hash()
return &tx
}
/*
Create new transaction
*/
func NewUTXOTransactions(from, to string, amount int, bc *BlockChain) *Transaction {
var inputs []TXInput
var outputs []TXOutput
acc, validOutputs := bc.FindSpendableOutputs(from, amount)
if acc < amount {
log.Panic("Error: Not enough funds.")
}
//build list of inputs
for txid, outs := range validOutputs {
txID, err := hex.DecodeString(txid)
if err != nil {
log.Panicf("Not able to DecodeString:%s",txid)
}
for _, out := range outs {
input := TXInput{ txID, out, from}
inputs = append(inputs, input)
}
}
//Build list of outputs
outputs = append(outputs, TXOutput{amount, to})
if acc > amount {
outputs = append(outputs, TXOutput{acc - amount, from})
}
tx := Transaction{nil, inputs, outputs}
tx.ID = tx.Hash()
return &tx
}