-
Notifications
You must be signed in to change notification settings - Fork 8
/
transaction.go
138 lines (111 loc) · 2.15 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package bitacoin
import "time"
import "bytes"
import "fmt"
const (
coinBaseReward = 100000
)
type Transaction struct {
ID []byte
VOut []TXOutput
VIn []TXInput
}
func (txn *Transaction) IsCoinBase() bool {
return len(txn.VOut) == 1 &&
len(txn.VIn) == 1 &&
txn.VIn[0].VOut == -1 &&
len(txn.VIn[0].TXID) == 0
}
type TXOutput struct {
Value int
PubKey []byte
}
func (txo *TXOutput) TryUnlock(key []byte) bool {
return bytes.Equal(txo.PubKey, key)
}
type TXInput struct {
TXID []byte
VOut int
Sig []byte
}
func (txi *TXInput) MatchLock(key []byte) bool {
return bytes.Equal(txi.Sig, key)
}
func calculateTxnID(txn *Transaction) []byte {
return EasyHash(txn.VOut, txn.VIn)
}
func calculateTxnsHash(txns ...*Transaction) []byte {
data := make([]interface{}, len(txns))
for i := range txns {
data[i] = txns[i].ID
}
return EasyHash(data...)
}
func NewCoinBaseTxn(to, data []byte) *Transaction {
if len(data) == 0 {
data = EasyHash(to, time.Now())
}
txi := TXInput{
TXID: []byte{},
VOut: -1,
Sig: data,
}
txo := TXOutput{
Value: coinBaseReward,
PubKey: to,
}
txn := &Transaction{
VOut: []TXOutput{txo},
VIn: []TXInput{txi},
}
txn.ID = calculateTxnID(txn)
return txn
}
func NewTransaction(bc *BlockChain, from, to []byte, amount int) (*Transaction, error) {
txns, txom, acc, err := bc.UnspentTxn(from)
if err != nil {
return nil, fmt.Errorf("get unused txn failed: %w", err)
}
if amount <= 0 {
return nil, fmt.Errorf("negative transfer?")
}
if acc < amount {
return nil, fmt.Errorf("not enough money, want %d have %d", amount, acc)
}
var (
vin []TXInput
required = amount
)
bigLoop:
for id, txn := range txns {
for _, v := range txom[id] {
required -= txn.VOut[v].Value
vin = append(vin, TXInput{
TXID: txn.ID,
VOut: v,
Sig: from, // TODO : real sign
})
if required <= 0 {
break bigLoop
}
}
}
vout := []TXOutput{
TXOutput{
Value: amount,
PubKey: to,
},
}
if required < 0 {
vout = append(vout, TXOutput{
Value: -required,
PubKey: from,
})
}
txn := &Transaction{
VIn: vin,
VOut: vout,
}
txn.ID = calculateTxnID(txn)
return txn, nil
}