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.

73 lines
1.3 KiB

  1. package core
  2. import (
  3. "encoding/json"
  4. "time"
  5. )
  6. type Input struct {
  7. }
  8. type Output struct {
  9. }
  10. // Tx holds the data structure of a transaction
  11. type Tx struct {
  12. From Address
  13. To Address
  14. InputCount uint64
  15. Inputs []Input
  16. Outputs []Output
  17. }
  18. func NewTx(from, to Address, in []Input, out []Output) *Tx {
  19. tx := &Tx{
  20. From: from,
  21. To: to,
  22. InputCount: uint64(len(in)),
  23. Inputs: in,
  24. Outputs: out,
  25. }
  26. return tx
  27. }
  28. // Block holds the data structure for the block
  29. type Block struct {
  30. Height uint64
  31. PrevHash Hash
  32. NextHash Hash
  33. Txs []Tx
  34. Miner Address
  35. Timestamp time.Time
  36. Nonce uint64
  37. Hash Hash
  38. Signature []byte
  39. }
  40. // Bytes outputs a byte array containing the data of the Block
  41. func (blk Block) Bytes() []byte {
  42. b, _ := json.Marshal(blk)
  43. return b
  44. }
  45. func (blk *Block) GetNonce() uint64 {
  46. return blk.Nonce
  47. }
  48. func (blk *Block) IncrementNonce() {
  49. blk.Nonce++
  50. }
  51. func (block *Block) CalculatePoW(difficulty int) error {
  52. hash := HashBytes(block.Bytes())
  53. for !CheckPoW(hash, difficulty) {
  54. block.IncrementNonce()
  55. hash = HashBytes(block.Bytes())
  56. }
  57. block.Hash = hash
  58. return nil
  59. }
  60. func BlockFromBytes(b []byte) (*Block, error) {
  61. var block *Block
  62. err := json.Unmarshal(b, &block)
  63. return block, err
  64. }