/
blockid.go
56 lines (46 loc) · 1012 Bytes
/
blockid.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
package objects
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"strconv"
)
type BlockID struct {
Data [20]byte
}
func (b BlockID) BlockNumber() uint32 {
return binary.BigEndian.Uint32(b.Data[:4])
}
func (b BlockID) ID() []byte {
return b.Data[4:]
}
func (b BlockID) RefBlockNum() UInt16 {
return UInt16(b.BlockNumber())
}
func (b BlockID) RefBlockPrefix() UInt32 {
var prefix UInt32
binary.Read(bytes.NewReader(b.Data[4:8]), binary.LittleEndian, &prefix)
return prefix
}
func (b BlockID) String() string {
return hex.EncodeToString(b.Data[:])
}
func (b BlockID) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(hex.EncodeToString(b.Data[:]))), nil
}
func (b *BlockID) UnmarshalJSON(data []byte) error {
unqoted, err := strconv.Unquote(string(data))
if err != nil {
return nil
}
bin, err := hex.DecodeString(unqoted)
if err != nil {
return err
}
if len(bin) != len(b.Data) {
return fmt.Errorf("Invalid BlockID size")
}
copy(b.Data[:], bin)
return err
}