-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
83 lines (64 loc) · 1.38 KB
/
hash.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package capusta
import (
"crypto/sha256"
"encoding/binary"
"math"
)
type Hashible interface {
Binary() []byte
}
func Hash(obj Hashible) [32]byte {
data := obj.Binary()
return sha256.Sum256(data)
}
type blob struct {
bytes []byte
}
func (b *blob) Bytes() []byte {
return b.bytes
}
func (b *blob) Write(chunk []byte) {
b.bytes = append(b.bytes, chunk...)
}
func (b *blob) WriteHash(chunk [32]byte) {
b.Write(chunk[:])
}
func (b *blob) WriteString(chunk string) {
b.Write([]byte(chunk))
}
func (b *blob) WriteInt64(chunk int64) {
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, uint64(chunk))
b.Write(bytes)
}
func (b *blob) WriteFloat64(chunk float64) {
bytes := make([]byte, 8)
binary.BigEndian.PutUint64(bytes, math.Float64bits(chunk))
b.Write(bytes)
}
func (b *Block) Binary() []byte {
var data blob
var transactionData blob
for _, t := range b.data {
transactionData.Write(t.Binary())
}
data.WriteInt64(b.index)
data.WriteInt64(b.timestamp)
data.WriteHash(b.previousHash)
data.Write(transactionData.bytes)
data.WriteInt64(b.proof)
return data.Bytes()
}
func (t *Transaction) Binary() []byte {
var data blob
for _, ti := range t.inputs {
data.WriteHash(ti.transactionHash)
data.WriteFloat64(ti.value)
data.WriteString(ti.from)
}
for _, to := range t.outputs {
data.WriteFloat64(to.value)
data.WriteString(to.to)
}
return data.Bytes()
}