-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
80 lines (61 loc) · 1.42 KB
/
transaction.go
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
package blockchain
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"fmt"
"log"
)
type Transaction struct {
ID []byte
Inputs []TxInput
Outputs []TxOutput
}
func (tx *Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte
encode := gob.NewEncoder(&encoded)
err := encode.Encode(tx)
Handle(err)
hash = sha256.Sum256(encoded.Bytes())
tx.ID = hash[:]
}
func CoinbaseTx(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Coins to %s", to)
}
txin := TxInput{[]byte{}, -1, data}
txout := TxOutput{100, to}
tx := Transaction{nil, []TxInput{txin}, []TxOutput{txout}}
tx.SetID()
return &tx
}
func NewTransaction(from, to string, amount int, chain *BlockChain) *Transaction {
var inputs []TxInput
var outputs []TxOutput
acc, validOutputs := chain.FindSpendableOutputs(from, amount)
if acc < amount {
log.Panic("Error: not enought funds")
}
for txid, outs := range validOutputs {
txID, err := hex.DecodeString(txid)
Handle(err)
for _, out := range outs {
input := TxInput{txID, out, from}
inputs = append(inputs, input)
}
}
outputs = append(outputs, TxOutput{amount, to})
if acc > amount {
outputs = append(outputs, TxOutput{acc - amount, from})
}
tx := Transaction{nil, inputs, outputs}
tx.SetID()
return &tx
}
func (tx *Transaction) IsCoinbase() bool {
return len(tx.Inputs) == 1 &&
len(tx.Inputs[0].ID) == 0 &&
tx.Inputs[0].Out == -1
}