This repository has been archived by the owner on Jan 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
297 lines (234 loc) · 6.93 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"log"
"math/big"
"strconv"
"strings"
)
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte
Vin []TXInput
Vout []TXOutput
}
// IsCoinbase checks whether the transaction is coinbase
func (tx Transaction) IsCoinbase() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
// Serialize returns a serialized Transaction
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()
}
// 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[:]
}
// Sign signs each input of a Transaction
func (tx *Transaction) Sign(privKey ecdsa.PrivateKey, prevTXs map[string]Transaction) {
if tx.IsCoinbase() {
return
}
for _, vin := range tx.Vin {
if prevTXs[hex.EncodeToString(vin.Txid)].ID == nil {
log.Panic("ERROR: Previous transaction is not correct")
}
}
txCopy := tx.TrimmedCopy()
for inID, vin := range txCopy.Vin {
prevTx := prevTXs[hex.EncodeToString(vin.Txid)]
txCopy.Vin[inID].Signature = nil
txCopy.Vin[inID].PubKey = prevTx.Vout[vin.Vout].PubKeyHash
txCopy.ID = txCopy.Hash()
txCopy.Vin[inID].PubKey = nil
r, s, err := ecdsa.Sign(rand.Reader, &privKey, txCopy.ID)
if err != nil {
log.Panic(err)
}
signature := append(r.Bytes(), s.Bytes()...)
tx.Vin[inID].Signature = signature
}
}
// String returns a human-readable representation of a transaction
func (tx Transaction) 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.Vout))
lines = append(lines, fmt.Sprintf(" Signature: %x", input.Signature))
lines = append(lines, fmt.Sprintf(" PubKey: %x", input.PubKey))
}
for i, output := range tx.Vout {
lines = append(lines, fmt.Sprintf(" Output %d:", i))
lines = append(lines, fmt.Sprintf(" ProductID: %s", output.Item))
lines = append(lines, fmt.Sprintf(" Script: %x", output.PubKeyHash))
}
return strings.Join(lines, "\n")
}
// TrimmedCopy creates a trimmed copy of Transaction to be used in signing
func (tx *Transaction) TrimmedCopy() Transaction {
var inputs []TXInput
var outputs []TXOutput
for _, vin := range tx.Vin {
inputs = append(inputs, TXInput{vin.Txid, vin.Vout, nil, nil})
}
for _, vout := range tx.Vout {
outputs = append(outputs, TXOutput{vout.Index, vout.Item, vout.PubKeyHash})
}
txCopy := Transaction{tx.ID, inputs, outputs}
return txCopy
}
// Verify verifies signatures of Transaction inputs
func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool {
if tx.IsCoinbase() {
return true
}
for _, vin := range tx.Vin {
if prevTXs[hex.EncodeToString(vin.Txid)].ID == nil {
log.Panic("ERROR: Previous transaction is not correct")
}
}
txCopy := tx.TrimmedCopy()
curve := elliptic.P256()
for inID, vin := range tx.Vin {
prevTx := prevTXs[hex.EncodeToString(vin.Txid)]
txCopy.Vin[inID].Signature = nil
txCopy.Vin[inID].PubKey = prevTx.Vout[vin.Vout].PubKeyHash
txCopy.ID = txCopy.Hash()
txCopy.Vin[inID].PubKey = nil
r := big.Int{}
s := big.Int{}
sigLen := len(vin.Signature)
r.SetBytes(vin.Signature[:(sigLen / 2)])
s.SetBytes(vin.Signature[(sigLen / 2):])
x := big.Int{}
y := big.Int{}
keyLen := len(vin.PubKey)
x.SetBytes(vin.PubKey[:(keyLen / 2)])
y.SetBytes(vin.PubKey[(keyLen / 2):])
rawPubKey := ecdsa.PublicKey{curve, &x, &y}
if ecdsa.Verify(&rawPubKey, txCopy.ID, &r, &s) == false {
return false
}
}
return true
}
// NewCoinbaseTX creates a new coinbase transaction
func NewCoinbaseTX(utxoSet *UTXOSet, to string, subsidy []string, nodeID string) (*Transaction, error) {
var codes []int
var sgtin []string
var packetCode string
wallets, err := NewWallets(nodeID)
wallet := wallets.GetWallet(to)
r := utxoSet.Blockchain.GetRole(wallet.PublicKey)
if r == nil {
return &Transaction{}, errors.New("Organisation not found")
}
if bytes.Compare(r, []byte("Manufacturer")) != 0 {
return &Transaction{}, errors.New("Not authorized to perform this action")
}
for _, p := range subsidy {
i, err := strconv.Atoi(p)
if err != nil {
return &Transaction{}, errors.New(fmt.Sprintf("Code %s is not numeric", p))
} else {
codes = append(codes, i)
}
}
for i := range codes {
packetCode, err = utxoSet.Blockchain.GenerateSGTIN(to, wallet.PublicKey, codes[i])
if err != nil {
return &Transaction{}, err
} else {
sgtin = append(sgtin, packetCode)
}
}
data := ""
if data == "" {
randData := make([]byte, 20)
_, err := rand.Read(randData)
if err != nil {
log.Panic(err)
}
data = fmt.Sprintf("%x", randData)
}
txin := TXInput{[]byte{}, -1, nil, []byte(data)}
txout := NewTXOutput(0, sgtin[0], to)
tx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}
for i, index := range sgtin[1:] {
//fmt.Println(i)
tx.Vout = append(tx.Vout, *NewTXOutput(i+1, index, to))
}
tx.ID = tx.Hash()
return &tx, nil
}
// NewUTXOTransaction creates a new transaction
func NewUTXOTransaction(wallet Wallet, from string, to string,products []string, UTXOSet *UTXOSet) *Transaction {
var inputs []TXInput
wallets, err := NewWallets()
if err != nil {
log.Panic(err)
}
pubKeyHash := HashPubKey(wallet.PublicKey)
found, validOutputs := UTXOSet.FindSpendableOutputs(pubKeyHash, products)
if found != len(products) {
log.Panic("ERROR: Item Not found")
}
// Build a list of inputs
for txid, outs := range validOutputs {
txID, err := hex.DecodeString(txid)
if err != nil {
log.Panic(err)
}
for _, out := range outs {
input := TXInput{txID, out, nil, wallet.PublicKey}
inputs = append(inputs, input)
}
}
// Build a list of outputs
txout := NewTXOutput(0, products[0], to)
tx := Transaction{nil, inputs, []TXOutput{*txout}}
for i, index := range products[1:] {
//fmt.Println(i)
tx.Vout = append(tx.Vout, *NewTXOutput(i+1, index, to))
}
tx.ID = tx.Hash()
//outputs = append(outputs, *NewTXOutput(product, to))
//if acc > amount {
// outputs = append(outputs, *NewTXOutput(acc-amount, from)) // a change
//}
//tx := Transaction{nil, inputs, outputs}
//tx.ID = tx.Hash()
UTXOSet.Blockchain.SignTransaction(&tx, wallet.PrivateKey)
return &tx
}
// DeserializeTransaction deserializes a transaction
func DeserializeTransaction(data []byte) Transaction {
var transaction Transaction
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&transaction)
if err != nil {
log.Panic(err)
}
return transaction
}