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.

83 lines
1.7 KiB

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