forked from kaspanet/kaspad
-
Notifications
You must be signed in to change notification settings - Fork 27
/
block.go
55 lines (47 loc) · 1.95 KB
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package consensushashing
import (
"io"
"github.com/karlsen-network/karlsend/domain/consensus/utils/serialization"
"github.com/karlsen-network/karlsend/domain/consensus/model/externalapi"
"github.com/karlsen-network/karlsend/domain/consensus/utils/hashes"
"github.com/pkg/errors"
)
// BlockHash returns the given block's hash
func BlockHash(block *externalapi.DomainBlock) *externalapi.DomainHash {
return HeaderHash(block.Header)
}
// HeaderHash returns the given header's hash
func HeaderHash(header externalapi.BaseBlockHeader) *externalapi.DomainHash {
// Encode the header and hash everything prior to the number of
// transactions.
writer := hashes.NewBlockHashWriter()
err := serializeHeader(writer, header)
if err != nil {
// It seems like this could only happen if the writer returned an error.
// and this writer should never return an error (no allocations or possible failures)
// the only non-writer error path here is unknown types in `WriteElement`
panic(errors.Wrap(err, "this should never happen. Hash digest should never return an error"))
}
return writer.Finalize()
}
func serializeHeader(w io.Writer, header externalapi.BaseBlockHeader) error {
timestamp := header.TimeInMilliseconds()
blueWork := header.BlueWork().Bytes()
numParents := len(header.Parents())
if err := serialization.WriteElements(w, header.Version(), uint64(numParents)); err != nil {
return err
}
for _, blockLevelParents := range header.Parents() {
numBlockLevelParents := len(blockLevelParents)
if err := serialization.WriteElements(w, uint64(numBlockLevelParents)); err != nil {
return err
}
for _, hash := range blockLevelParents {
if err := serialization.WriteElement(w, hash); err != nil {
return err
}
}
}
return serialization.WriteElements(w, header.HashMerkleRoot(), header.AcceptedIDMerkleRoot(), header.UTXOCommitment(), timestamp,
header.Bits(), header.Nonce(), header.DAAScore(), header.BlueScore(), blueWork, header.PruningPoint())
}