-
Notifications
You must be signed in to change notification settings - Fork 79
/
block.go
65 lines (58 loc) · 1.62 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
56
57
58
59
60
61
62
63
64
65
package result
import (
"encoding/json"
"errors"
"github.com/nspcc-dev/neo-go/pkg/core/block"
"github.com/nspcc-dev/neo-go/pkg/util"
)
type (
// Block wrapper used for the representation of
// block.Block / block.Base on the RPC Server.
Block struct {
block.Block
BlockMetadata
}
// BlockMetadata is an additional metadata added to the standard
// block.Block.
BlockMetadata struct {
Size int `json:"size"`
NextBlockHash *util.Uint256 `json:"nextblockhash,omitempty"`
Confirmations uint32 `json:"confirmations"`
}
)
// MarshalJSON implements the json.Marshaler interface.
func (b Block) MarshalJSON() ([]byte, error) {
output, err := json.Marshal(b.BlockMetadata)
if err != nil {
return nil, err
}
baseBytes, err := json.Marshal(b.Block)
if err != nil {
return nil, err
}
// We have to keep both "fields" at the same level in json in order to
// match C# API, so there's no way to marshall Block correctly with
// the standard json.Marshaller tool.
if output[len(output)-1] != '}' || baseBytes[0] != '{' {
return nil, errors.New("can't merge internal jsons")
}
output[len(output)-1] = ','
output = append(output, baseBytes[1:]...)
return output, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (b *Block) UnmarshalJSON(data []byte) error {
// As block.Block and BlockMetadata are at the same level in json,
// do unmarshalling separately for both structs.
meta := new(BlockMetadata)
err := json.Unmarshal(data, meta)
if err != nil {
return err
}
err = json.Unmarshal(data, &b.Block)
if err != nil {
return err
}
b.BlockMetadata = *meta
return nil
}