micw/server/core/block.go

53 lines
1.0 KiB
Go

package core
import (
"crypto/sha512"
"fmt"
"mic-wallet/common"
"sync"
)
type Block struct {
ID int64
IgnoreSignatures map[string]struct{}
TXs map[string]*common.NewTxOpts
Lock *sync.RWMutex
PrevHash []byte
Hash []byte
}
func NewBlock(id int64, prevHash []byte) *Block {
return &Block{
ID: id,
IgnoreSignatures: make(map[string]struct{}),
TXs: make(map[string]*common.NewTxOpts),
Lock: &sync.RWMutex{},
PrevHash: prevHash,
}
}
func (b *Block) AddTx(tx *common.NewTxOpts) error {
b.Lock.Lock()
hashStr := tx.HashString()
sigStr := tx.SignatureString()
if _, ok := b.IgnoreSignatures[sigStr]; ok {
return fmt.Errorf("duplicate")
}
b.TXs[hashStr] = tx
b.Lock.Unlock()
return nil
}
func (b *Block) RemoveTx(hash string) {}
func (b *Block) CalcHash() []byte {
hash := sha512.New()
b.Lock.Lock()
hash.Write(b.PrevHash)
for _, tx := range b.TXs {
hash.Write(tx.Hash)
}
b.Hash = hash.Sum(nil)
return b.Hash
}