-
Notifications
You must be signed in to change notification settings - Fork 9
/
transit.go
66 lines (50 loc) · 1.3 KB
/
transit.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
package server
import (
"errors"
"github.com/gelembjuk/democoin/lib/net"
"github.com/gelembjuk/democoin/lib/utils"
)
type nodeTransit struct {
Blocks map[string][][]byte
MaxKnownHeigh int
Logger *utils.LoggerMan
}
func (t *nodeTransit) Init(l *utils.LoggerMan) error {
t.Logger = l
t.Blocks = make(map[string][][]byte)
return nil
}
func (t *nodeTransit) AddBlocks(fromaddr net.NodeAddr, blocks [][]byte) error {
key := fromaddr.NodeAddrToString()
_, ok := t.Blocks[key]
if !ok {
t.Blocks[key] = blocks
} else {
t.Blocks[key] = append(t.Blocks[key], blocks...)
}
return nil
}
func (t *nodeTransit) CleanBlocks(fromaddr net.NodeAddr) {
key := fromaddr.NodeAddrToString()
if _, ok := t.Blocks[key]; ok {
delete(t.Blocks, key)
}
}
func (t *nodeTransit) GetBlocksCount(fromaddr net.NodeAddr) int {
if _, ok := t.Blocks[fromaddr.NodeAddrToString()]; ok {
return len(t.Blocks[fromaddr.NodeAddrToString()])
}
return 0
}
func (t *nodeTransit) ShiftNextBlock(fromaddr net.NodeAddr) ([]byte, error) {
key := fromaddr.NodeAddrToString()
if _, ok := t.Blocks[key]; ok {
data := t.Blocks[key][0][:]
t.Blocks[key] = t.Blocks[key][1:]
if len(t.Blocks[key]) == 0 {
delete(t.Blocks, key)
}
return data, nil
}
return nil, errors.New("The address is not in blocks transit")
}