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.

93 lines
2.0 KiB

  1. package core
  2. import (
  3. "crypto/ecdsa"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. )
  8. // Block holds the data structure for the block
  9. type Block struct {
  10. Height uint64
  11. PrevHash Hash
  12. Txs []Tx
  13. Miner Address
  14. MinerPubK *ecdsa.PublicKey // tmp meanwhile no ecrecover function
  15. Timestamp time.Time
  16. Nonce uint64
  17. Hash Hash
  18. Signature []byte
  19. }
  20. // for testing
  21. func (block Block) Print() {
  22. fmt.Println("height", block.Height)
  23. fmt.Println("hash", block.Hash.String())
  24. fmt.Println("PrevHash", block.PrevHash.String())
  25. fmt.Println("timestamp", block.Timestamp.String())
  26. fmt.Println("signature", block.Signature)
  27. }
  28. func (block Block) Copy() *Block {
  29. return &Block{
  30. Height: block.Height,
  31. PrevHash: block.PrevHash,
  32. Txs: block.Txs,
  33. Miner: block.Miner,
  34. MinerPubK: block.MinerPubK,
  35. Timestamp: block.Timestamp,
  36. Nonce: block.Nonce,
  37. Hash: block.Hash,
  38. Signature: block.Signature,
  39. }
  40. }
  41. // Bytes outputs a byte array containing the data of the Block
  42. func (blk Block) Bytes() []byte {
  43. // TODO add parser, to use minimum amount of bytes
  44. b, _ := json.Marshal(blk)
  45. return b
  46. }
  47. func (block *Block) CalculateHash() {
  48. blockCopy := block.Copy()
  49. blockCopy.Hash = Hash{}
  50. blockCopy.Signature = []byte{}
  51. hash := HashBytes(blockCopy.Bytes())
  52. block.Hash = hash
  53. }
  54. func (blk *Block) GetNonce() uint64 {
  55. return blk.Nonce
  56. }
  57. func (blk *Block) IncrementNonce() {
  58. blk.Nonce++
  59. }
  60. func (block *Block) CalculatePoW(difficulty uint64) error {
  61. blockCopy := block.Copy()
  62. blockCopy.Hash = Hash{}
  63. hash := HashBytes(blockCopy.Bytes())
  64. for !CheckPoW(hash, difficulty) {
  65. blockCopy.IncrementNonce()
  66. hash = HashBytes(blockCopy.Bytes())
  67. }
  68. block.Hash = hash
  69. block.Nonce = blockCopy.Nonce
  70. return nil
  71. }
  72. func CheckBlockPoW(block *Block, difficulty uint64) bool {
  73. blockCopy := block.Copy()
  74. blockCopy.Hash = Hash{}
  75. blockCopy.Signature = []byte{}
  76. return CheckPoW(HashBytes(blockCopy.Bytes()), difficulty)
  77. }
  78. func BlockFromBytes(b []byte) (*Block, error) {
  79. var block *Block
  80. err := json.Unmarshal(b, &block)
  81. return block, err
  82. }