/
transaction.go
424 lines (337 loc) · 9.97 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package structures
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"math"
"strings"
"time"
"encoding/gob"
"fmt"
"github.com/gelembjuk/oursql/lib"
"github.com/gelembjuk/oursql/lib/utils"
)
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte
Time int64
Signature []byte // one signature for full transaction
ByPubKey []byte
Vin []TXCurrencyInput
Vout []TXCurrrencyOutput
SQLCommand SQLUpdate
SQLBaseTX []byte // ID of transaction where same row was affected last time
}
// execute when new tranaction object is created
func (tx *Transaction) initNewTX() {
tx.Time = time.Now().UTC().UnixNano()
}
// execute when new TX is ready. all is set. do last action
func (tx *Transaction) completeNewTX() {
tx.makeHash()
}
// Return ID of transaction
func (tx Transaction) GetID() []byte {
return tx.ID
}
func (tx Transaction) GetIDString() string {
return fmt.Sprintf("%x", tx.ID)
}
// returns base TX for this SQL update TX
func (tx Transaction) GetSQLBaseTX() []byte {
return tx.SQLBaseTX
}
// Checks whether the transaction is currency transaction (sends money to somewhere)
func (tx Transaction) IsCurrencyTransfer() bool {
// returns true if there is some money IN or some monet OUT
if len(tx.Vin) > 0 {
return true
}
if len(tx.Vout) > 0 {
return true
}
return false
}
// IsCoinbase checks whether the transaction is coinbase
func (tx Transaction) IsSQLCommand() bool {
return !tx.SQLCommand.IsEmpty()
}
// check if TX is coin base
func (tx Transaction) IsCoinbaseTransfer() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
// check if needs signatures. in case of coin base doesn't need it
func (tx Transaction) NeedsSignature() bool {
return !tx.IsCoinbaseTransfer()
}
// Hash returns the hash of the Transaction
func (tx *Transaction) makeHash() ([]byte, error) {
var hash [32]byte
txCopy := *tx
txCopy.ID = []byte{}
txser, err := txCopy.serialize()
if err != nil {
return nil, err
}
hash = sha256.Sum256(txser)
tx.ID = hash[:]
return tx.ID, nil
}
// TrimmedCopy creates a trimmed copy of Transaction to be used in signing
func (tx Transaction) Copy() (*Transaction, error) {
//if tx.IsCoinbase() {
// return *tx, nil
//}
txCopy := &Transaction{}
txCopy.ID = tx.ID
txCopy.Time = tx.Time
txCopy.Vin = tx.Vin
txCopy.Vout = tx.Vout
txCopy.Signature = tx.Signature
txCopy.ByPubKey = tx.ByPubKey
txCopy.SQLCommand = tx.SQLCommand
txCopy.SQLBaseTX = tx.SQLBaseTX
return txCopy, nil
}
// prepare data to sign a transaction
// this return []bytes. it is bytes representation of a TX.
func (tx *Transaction) PrepareSignData(pubKey []byte, prevTXs map[int]*Transaction) ([]byte, error) {
pubKeyHash, _ := utils.HashPubKey(pubKey)
// check if input transactions map is correct
for vinInd, vin := range tx.Vin {
if _, ok := prevTXs[vinInd]; !ok {
return nil, errors.New("Previous transaction is not correct")
}
if bytes.Compare(prevTXs[vinInd].GetID(), vin.Txid) != 0 {
return nil, errors.New("Previous transaction is not correct")
}
if bytes.Compare(pubKeyHash, prevTXs[vinInd].Vout[vin.Vout].PubKeyHash) != 0 {
// check if output of previous transaction really belomgs to this pub key
return nil, errors.New("Previous Transaction was assigned to other address")
}
}
tx.ByPubKey = pubKey
tx.Signature = []byte{}
tx.ID = []byte{}
return tx.ToBytes()
}
// Sets signatures for inputs. Signatures were created separately for data set prepared before
// in the function PrepareSignData
func (tx *Transaction) CompleteTransaction(signature []byte) error {
tx.Signature = signature
tx.completeNewTX()
return nil
}
// Verify verifies signatures of Transaction inputs
// And total amount of inputs and outputs
// TODO in future to replace coinstoadd with some Config structure where all external things for verify are included
func (tx *Transaction) Verify(prevTXs map[int]*Transaction, coinstoadd float64) error {
if tx.IsCoinbaseTransfer() {
// coinbase has only 1 output and it must have value equal to constant
if tx.Vout[0].Value != coinstoadd {
return errors.New("Value of coinbase transaction is wrong")
}
if len(tx.Vout) > 1 {
return errors.New("Coinbase transaction can have only 1 output")
}
return nil
}
// calculate total input
totalinput := float64(0)
for vind, vin := range tx.Vin {
prevTx := prevTXs[vind]
if prevTx.ID == nil {
return errors.New("Previous transaction is not correct")
}
amount := prevTx.Vout[vin.Vout].Value
totalinput += amount
}
// VERIFY signature
// build copy to make sign data
txCopy, err := tx.Copy()
if err != nil {
return err
}
txCopy.Signature = []byte{}
txCopy.ID = []byte{}
stringtosign, err := txCopy.ToBytes()
if err != nil {
return err
}
v, err := utils.VerifySignature(tx.Signature, stringtosign, tx.ByPubKey)
if err != nil {
return err
}
if !v {
return errors.New(fmt.Sprintf("Signatire doe not match for TX %x.", tx.GetID()))
}
pubKeyHash, _ := utils.HashPubKey(tx.ByPubKey)
for inID, vin := range tx.Vin {
// full input transaction
prevTx := prevTXs[inID]
if bytes.Compare(prevTx.Vout[vin.Vout].PubKeyHash, pubKeyHash) != 0 {
return errors.New(fmt.Sprintf("Sign Key Hash for input %x is different from output hash", vin.Txid))
}
}
// calculate total output of transaction
totaloutput := float64(0)
for _, vout := range tx.Vout {
if vout.Value < lib.CurrencySmallestUnit {
return errors.New(fmt.Sprintf("Too small output value %f", vout.Value))
}
totaloutput += vout.Value
}
if math.Abs(totalinput-totaloutput) >= lib.CurrencySmallestUnit {
return errors.New(fmt.Sprintf("Input and output values of a transaction are not same: %.10f vs %.10f . Diff %.10f", totalinput, totaloutput, totalinput-totaloutput))
}
return nil
}
// Serialize returns a serialized Transaction
func (tx Transaction) serialize() ([]byte, error) {
// to remove any references to other ponters
// do full copy of the TX
gob.Register(SQLUpdate{})
var encoded bytes.Buffer
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
return nil, err
}
return encoded.Bytes(), nil
}
// DeserializeTransaction deserializes a transaction
func (tx *Transaction) DeserializeTransaction(data []byte) error {
gob.Register(SQLUpdate{})
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(tx)
if err != nil {
return err
}
return nil
}
// converts transaction to slice of bytes
// this will be used to do a hash of transactions
func (tx Transaction) ToBytes() ([]byte, error) {
buff := new(bytes.Buffer)
err := binary.Write(buff, binary.BigEndian, tx.ID)
if err != nil {
return nil, err
}
for _, vin := range tx.Vin {
b, err := vin.ToBytes()
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, b)
if err != nil {
return nil, err
}
}
for _, vout := range tx.Vout {
b, err := vout.ToBytes()
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, b)
if err != nil {
return nil, err
}
}
err = binary.Write(buff, binary.BigEndian, tx.Time)
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, tx.Signature)
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, tx.ByPubKey)
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, tx.SQLCommand.ToBytes())
if err != nil {
return nil, err
}
err = binary.Write(buff, binary.BigEndian, tx.SQLBaseTX)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
func (tx Transaction) IsComplete() bool {
if tx.ID != nil {
return true
}
return false
}
// UsesKey checks whether the address initiated the transaction
func (tx Transaction) CreatedByPubKeyHash(pubKeyHash []byte) bool {
lockingHash, _ := utils.HashPubKey(tx.ByPubKey)
return bytes.Compare(lockingHash, pubKeyHash) == 0
}
//
func (tx Transaction) GetTime() int64 {
return tx.Time
}
//
func (tx *Transaction) SetSQLPart(sql SQLUpdate) {
tx.SQLCommand = sql
}
// set ID of previous TX where SQL item was updated
func (tx *Transaction) SetSQLPreviousTX(baseTX []byte) {
tx.SQLBaseTX = baseTX
}
// returns SQL command as string
func (tx Transaction) GetSQLQuery() string {
if len(tx.SQLCommand.Query) > 0 {
return string(tx.SQLCommand.Query)
}
return ""
}
// String returns a human-readable representation of a transaction
func (tx Transaction) String() string {
var lines []string
from := "Coin Base"
fromhash := []byte{}
if !tx.IsCoinbaseTransfer() {
from, _ = utils.PubKeyToAddres(tx.ByPubKey)
fromhash, _ = utils.HashPubKey(tx.ByPubKey)
}
to := ""
amount := 0.0
for _, output := range tx.Vout {
if bytes.Compare(fromhash, output.PubKeyHash) != 0 {
to, _ = utils.PubKeyHashToAddres(output.PubKeyHash)
amount = output.Value
break
}
}
lines = append(lines, fmt.Sprintf("--- Transaction %x:", tx.ID))
lines = append(lines, fmt.Sprintf(" Time %d (%s)", tx.Time, time.Unix(0, tx.Time)))
if amount > 0 {
lines = append(lines, fmt.Sprintf(" FROM %s TO %s VALUE %f", from, to, amount))
}
if !tx.IsCoinbaseTransfer() && !tx.IsSQLCommand() {
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))
}
}
for i, output := range tx.Vout {
address, _ := utils.PubKeyHashToAddres(output.PubKeyHash)
lines = append(lines, fmt.Sprintf(" Output %d:", i))
lines = append(lines, fmt.Sprintf(" Value: %f", output.Value))
//lines = append(lines, fmt.Sprintf(" Script: %x", output.PubKeyHash))
lines = append(lines, fmt.Sprintf(" Address: %s", address))
}
if tx.IsSQLCommand() {
lines = append(lines, fmt.Sprintf(" SQL: %s", tx.GetSQLQuery()))
lines = append(lines, fmt.Sprintf(" By: %s", from))
lines = append(lines, fmt.Sprintf(" Based On: %x", tx.SQLBaseTX))
}
lines = append(lines, " ---")
return strings.Join(lines, "\n")
}