slowlorisdb/core/tx.go
core/tx.goRaw
1package core
2
3import (
4 "crypto/ecdsa"
5 "encoding/json"
6
7 log "github.com/sirupsen/logrus"
8)
9
10var GenesisHashTxInput = HashBytes([]byte("genesis"))
11
12type Input struct {
13 TxId Hash
14 Vout int // index of the output from the TxId
15 Value uint64
16}
17
18type Output struct {
19 Value uint64
20}
21
22// Tx holds the data structure of a transaction
23type Tx struct {
24 TxId Hash
25 From *ecdsa.PublicKey
26 To *ecdsa.PublicKey
27 InputCount uint64
28 Inputs []Input
29 Outputs []Output
30 Signature []byte
31}
32
33func (tx *Tx) Bytes() []byte {
34 // TODO add parser, to use minimum amount of bytes
35 b, _ := json.Marshal(tx)
36 return b
37}
38
39func (tx *Tx) CalculateTxId() {
40 h := HashBytes(tx.Bytes())
41 tx.TxId = h
42}
43
44func NewTx(from, to *ecdsa.PublicKey, in []Input, out []Output) *Tx {
45 tx := &Tx{
46 From: from,
47 To: to,
48 InputCount: uint64(len(in)),
49 Inputs: in,
50 Outputs: out,
51 Signature: []byte{},
52 }
53 tx.CalculateTxId()
54 return tx
55}
56
57// CheckTx checks if the transaction is consistent
58func CheckTx(tx *Tx) bool {
59 // check that inputs == outputs
60 totalIn := 0
61 for _, in := range tx.Inputs {
62 // check that inputs are not empty, to avoid spam tx
63 if in.Value == uint64(0) {
64 return false
65 }
66 totalIn = totalIn + int(in.Value)
67 }
68 totalOut := 0
69 for _, out := range tx.Outputs {
70 totalOut = totalOut + int(out.Value)
71 }
72 if totalIn != totalOut {
73 log.Info("totalIn != totalOut")
74 return false
75 }
76
77 // TODO check signature
78 return true
79}