Guest User

Untitled

a guest
Apr 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. // make sure block is valid by checking index, and comparing the hash of the previous block
  2. func isBlockValid(newBlock, oldBlock Block) bool {
  3. if oldBlock.Index+1 != newBlock.Index {
  4. return false
  5. }
  6.  
  7. if oldBlock.Hash != newBlock.PrevHash {
  8. return false
  9. }
  10.  
  11. if calculateHash(newBlock) != newBlock.Hash {
  12. return false
  13. }
  14.  
  15. return true
  16. }
  17.  
  18. // SHA256 hashing
  19. func calculateHash(block Block) string {
  20. record := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.BPM) + block.PrevHash
  21. h := sha256.New()
  22. h.Write([]byte(record))
  23. hashed := h.Sum(nil)
  24. return hex.EncodeToString(hashed)
  25. }
  26.  
  27. // create a new block using previous block's hash
  28. func generateBlock(oldBlock Block, BPM int) Block {
  29.  
  30. var newBlock Block
  31.  
  32. t := time.Now()
  33.  
  34. newBlock.Index = oldBlock.Index + 1
  35. newBlock.Timestamp = t.String()
  36. newBlock.BPM = BPM
  37. newBlock.PrevHash = oldBlock.Hash
  38. newBlock.Hash = calculateHash(newBlock)
  39.  
  40. return newBlock
  41. }
Add Comment
Please, Sign In to add comment