我們知道區塊鏈是由數個區塊串成鏈組成的,因此我們現在就來開工吧~
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
}
func (b *Block) SetHash() {
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10)) // 把 Timestamp 換算成 10 進位
payload := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{}) // 把 Block 的 Data 都放進去
hash := sha256.Sum256(payload) // 產生 Hash
b.Hash = hash[:] // 設置 Hash
}
func CreateBlock(Data string, PrevBlockHash []byte) *Block{
block := &Block{
time.Now().Unix(), // 如此才會產生先前說的 Unix 的時間戳
[]byte(Data),
PrevBlockHash,
[]byte{},
} // 創建一個 Block 類別
block.SetHash() // 為 Block 設置 Hash
return block
}
import time
import hashlib
class Block:
def __init__(self, timestamp, data, prevblockhash, hash_value):
self.timestamp = timestamp
self.data = data
self.prevblockhash = prevblockhash
self.hash = hash_value
def SetHash(self):
self.timestamp = str(int self.timestamp)
payload = self.timestamp + self.data + self.prevblockhash
s = hashlib.sha256()
s.update(payload)
self.hash = str(s.hexdigest())
def CreateBlock(data, prevblockhash):
b = block(time.time(), data, prevblockhash, '')
b.SetHash()
return b