请编写一个区块链代码,用goland语言
时间: 2024-04-30 21:21:23 浏览: 111
这里提供一个简单的基于Go语言的区块链代码,其中包括了区块结构体、区块链结构体、添加区块、验证区块链以及生成哈希值等功能。
```go
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
)
type Block struct {
Index int
Timestamp string
Data string
PrevHash string
Hash string
}
type Blockchain struct {
chain []Block
}
func (b *Blockchain) addBlock(data string) {
prevBlock := b.chain[len(b.chain)-1]
newBlock := Block{
Index: prevBlock.Index + 1,
Timestamp: "2021-01-01T00:00:00Z",
Data: data,
PrevHash: prevBlock.Hash,
}
newBlock.Hash = generateHash(newBlock)
b.chain = append(b.chain, newBlock)
}
func (b *Blockchain) isValid() bool {
for i := 1; i < len(b.chain); i++ {
currentBlock := b.chain[i]
prevBlock := b.chain[i-1]
if currentBlock.Hash != generateHash(currentBlock) {
return false
}
if currentBlock.PrevHash != prevBlock.Hash {
return false
}
}
return true
}
func generateHash(b Block) string {
record := fmt.Sprintf("%d%s%s%s", b.Index, b.Timestamp, b.Data, b.PrevHash)
h := sha256.New()
h.Write([]byte(record))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}
func main() {
blockchain := Blockchain{}
genesisBlock := Block{
Index: 0,
Timestamp: "2021-01-01T00:00:00Z",
Data: "Genesis Block",
PrevHash: "",
}
genesisBlock.Hash = generateHash(genesisBlock)
blockchain.chain = append(blockchain.chain, genesisBlock)
blockchain.addBlock("Second Block")
blockchain.addBlock("Third Block")
fmt.Println(blockchain.isValid())
}
```
这个代码演示了如何创建一个区块链,添加区块并验证区块链的有效性。在这个例子中,我们使用SHA-256哈希函数来生成哈希值。在实际应用中,可能需要更复杂的哈希算法来确保安全性。
阅读全文