-
Notifications
You must be signed in to change notification settings - Fork 47
/
messages.go
60 lines (48 loc) · 1.33 KB
/
messages.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
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package notifications
import (
"encoding/hex"
"encoding/json"
"github.com/dusk-network/dusk-blockchain/pkg/core/data/block"
)
// BlockMsg represents the data need by Explorer UI on each new block accepted.
type BlockMsg struct {
Height uint64
Hash string
Timestamp int64
Txs []string
// BlocksGeneratedCount is number of blocks generated last 24 hours.
BlocksGeneratedCount uint
}
// MarshalBlockMsg builds the JSON from a subset of block fields.
func MarshalBlockMsg(blk block.Block) (string, error) {
hash, err := blk.CalculateHash()
if err != nil {
return "", err
}
var p BlockMsg
p.Height = blk.Header.Height
p.Timestamp = blk.Header.Timestamp
p.Hash = hex.EncodeToString(hash)
p.Txs = make([]string, 0)
// Get a limited set of block txs hashes
for _, tx := range blk.Txs {
if len(p.Txs) >= maxTxsPerMsg {
break
}
txid, e := tx.CalculateHash()
if e != nil {
return "", e
}
p.Txs = append(p.Txs, hex.EncodeToString(txid))
}
msg, marshalErr := json.Marshal(p)
if marshalErr != nil {
return "", marshalErr
}
return string(msg), nil
}