You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.4 KiB

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