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