block.go 706 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package blockchain
  2. type BlockChain struct {
  3. Blocks []*Block
  4. }
  5. type Block struct {
  6. Hash []byte
  7. Data []byte
  8. PrevHash []byte
  9. Nonce int
  10. }
  11. func CreateBlock(data string, prevHash []byte) *Block {
  12. block := &Block{[]byte{}, []byte(data), prevHash, 0}
  13. pow := NewProof(block)
  14. nonce, hash := pow.Run()
  15. block.Hash = hash[:]
  16. block.Nonce = nonce
  17. return block
  18. }
  19. func (chain *BlockChain) AddBlock(data string) {
  20. prevBlock := chain.Blocks[len(chain.Blocks)-1]
  21. new := CreateBlock(data, prevBlock.Hash)
  22. chain.Blocks = append(chain.Blocks, new)
  23. }
  24. func Genesis() *Block {
  25. return CreateBlock("Genesis", []byte{})
  26. }
  27. func InitBlockChain() *BlockChain {
  28. return &BlockChain{[]*Block{Genesis()}}
  29. }