package chain import ( "blockchain/config" "crypto/sha256" "encoding/hex" "strconv" "strings" ) type Block struct { Height int Transactions []*Transaction PrevHash string Hash string Nonce int } func NewBlock(height int, txs []*Transaction, prevHash string) *Block { return &Block{ Height: height, Transactions: txs, PrevHash: prevHash, } } // HashBase returns the pre-computed prefix for nonce iteration. func (b *Block) HashBase() string { var sb strings.Builder sb.WriteString(strconv.Itoa(b.Height)) for _, tx := range b.Transactions { sb.WriteString(tx.TxID()) } sb.WriteString(b.PrevHash) return sb.String() } func (b *Block) CalcHash() string { data := b.HashBase() + strconv.Itoa(b.Nonce) hash := sha256.Sum256([]byte(data)) return hex.EncodeToString(hash[:]) } func (b *Block) CheckProofOfWork() bool { prefix := strings.Repeat("0", config.Default.Chain.Difficulty) return b.Hash == b.CalcHash() && strings.HasPrefix(b.Hash, prefix) }