package consensus

import (
	"Walnut-HS/pkg/protobuf"
	"crypto/sha256"
	"log"

	"google.golang.org/protobuf/proto"
)

func NewQuorumCert(qctype string, view uint32, com uint32, block []byte, voters []uint32, sigs []*protobuf.SigByte) *protobuf.QuorumCert {
	return &protobuf.QuorumCert{
		Type:   qctype,
		View:   view,
		Com:    com,
		Block:  block,
		Voters: voters,
		Sigs:   sigs,
	}
}

// NewBlock creates a new Block
func NewBlock(view uint32, com uint32, parent []byte, batch *protobuf.Batch, comchange bool) *protobuf.Block {
	b := &protobuf.Block{
		Header: &protobuf.Header{
			View:      view,
			Com:       com,
			Parent:    parent,
			Comchange: comchange,
		},
		Batch: batch,
	}

	// cache the hash immediately because it is too racy to do it in Hash()
	btobyte, err := proto.Marshal(b)
	if err != nil {
		log.Fatalln(err)
	}
	hash := sha256.Sum256(btobyte)
	b.Header.Hash = hash[:]
	return b
}