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.

155 lines
3.4 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. "github.com/fatih/color"
  10. )
  11. type Block struct {
  12. Hash string `json:"hash"`
  13. Height int64 `json:"height"`
  14. Date time.Time `json:"date"`
  15. PreviousHash string `json:"previoushash"`
  16. NextHash string `json:"nexthash"`
  17. Data []Address `json:"data"`
  18. Emitter string `json:"emitter"` //the ID of the peer that has emmited the block
  19. }
  20. type Blockchain struct {
  21. GenesisBlock string `json:"genesisblock"`
  22. LastUpdate time.Time `json:"lastupdate"`
  23. Blocks []Block `json:"blocks"`
  24. }
  25. var blockchain Blockchain
  26. func (bc *Blockchain) getBlockByHash(hash string) (Block, error) {
  27. for _, block := range bc.Blocks {
  28. if block.Hash == hash {
  29. return block, nil
  30. }
  31. }
  32. var b Block
  33. return b, errors.New("Block Hash not found")
  34. }
  35. func (bc *Blockchain) createBlock(address Address) Block {
  36. var b Block
  37. b.Height = int64(len(bc.Blocks))
  38. if len(bc.Blocks) == 0 {
  39. b.Height = 0
  40. } else {
  41. b.PreviousHash = bc.Blocks[len(bc.Blocks)-1].Hash
  42. }
  43. b.Date = time.Now()
  44. b.Data = append(b.Data, address)
  45. b.Emitter = runningPeer.ID
  46. b.Hash = hashBlock(b)
  47. return b
  48. }
  49. func (bc *Blockchain) blockExists(block Block) bool {
  50. for _, b := range bc.Blocks {
  51. if b.Hash == block.Hash {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. func (bc *Blockchain) addBlock(block Block) error {
  58. if blockchain.blockExists(block) {
  59. return errors.New("[Error adding Block]: Block already exists in the Blockchain")
  60. }
  61. if len(bc.Blocks) > 0 {
  62. bc.Blocks[len(bc.Blocks)-1].NextHash = block.Hash
  63. } else {
  64. bc.GenesisBlock = block.Hash
  65. }
  66. bc.Blocks = append(bc.Blocks, block)
  67. bc.saveToDisk()
  68. return nil
  69. }
  70. func reconstructBlockchainFromBlock(urlAPI string, h string) {
  71. color.Yellow("reconstructing the blockchain from last block in memory")
  72. var block Block
  73. var err error
  74. block, err = blockchain.getBlockByHash(h)
  75. check(err)
  76. if h == "" {
  77. //no genesis block yet
  78. color.Green(urlAPI + "/blocks/genesis")
  79. res, err := http.Get(urlAPI + "/blocks/genesis")
  80. check(err)
  81. body, err := ioutil.ReadAll(res.Body)
  82. check(err)
  83. err = json.Unmarshal(body, &block)
  84. check(err)
  85. color.Yellow("[New Block]: " + block.Hash)
  86. err = blockchain.addBlock(block)
  87. check(err)
  88. } else {
  89. block.NextHash = h
  90. }
  91. for block.NextHash != "" && block.Hash != "" {
  92. res, err := http.Get(urlAPI + "/blocks/next/" + block.Hash)
  93. check(err)
  94. body, err := ioutil.ReadAll(res.Body)
  95. check(err)
  96. err = json.Unmarshal(body, &block)
  97. check(err)
  98. if block.Hash != "" {
  99. color.Yellow("[New Block]: " + block.Hash)
  100. err = blockchain.addBlock(block)
  101. check(err)
  102. }
  103. }
  104. blockchain.print()
  105. }
  106. func (bc *Blockchain) print() {
  107. color.Green("Printing Blockchain stored in memory")
  108. color.Green("Genesis Block: " + bc.GenesisBlock)
  109. for _, b := range bc.Blocks {
  110. color.Green("Block height:")
  111. fmt.Println(b.Height)
  112. color.Green("Hash: " + b.Hash)
  113. color.Green("Date: " + b.Date.String())
  114. color.Green("---")
  115. }
  116. }
  117. func (bc *Blockchain) readFromDisk() error {
  118. file, err := ioutil.ReadFile("blockchain.data")
  119. if err != nil {
  120. return err
  121. }
  122. content := string(file)
  123. json.Unmarshal([]byte(content), &bc)
  124. return nil
  125. }
  126. func (bc *Blockchain) saveToDisk() error {
  127. bytesBlockchain, err := json.Marshal(blockchain)
  128. if err != nil {
  129. return err
  130. }
  131. err = ioutil.WriteFile("blockchain.data", bytesBlockchain, 0644)
  132. if err != nil {
  133. return err
  134. }
  135. return nil
  136. }