aboutsummaryrefslogtreecommitdiffstats
path: root/simulation/node.go
blob: 56c583238f5425642f59989246670f83c0357a87 (plain) (blame)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Copyright 2018 The dexon-consensus Authors
// This file is part of the dexon-consensus library.
//
// The dexon-consensus library is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// The dexon-consensus library is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the dexon-consensus library. If not, see
// <http://www.gnu.org/licenses/>.

package simulation

import (
    "encoding/json"
    "fmt"
    "sort"
    "time"

    "github.com/dexon-foundation/dexon-consensus/common"
    "github.com/dexon-foundation/dexon-consensus/core"
    "github.com/dexon-foundation/dexon-consensus/core/blockdb"
    "github.com/dexon-foundation/dexon-consensus/core/crypto"
    "github.com/dexon-foundation/dexon-consensus/core/test"
    "github.com/dexon-foundation/dexon-consensus/core/types"
    typesDKG "github.com/dexon-foundation/dexon-consensus/core/types/dkg"
    "github.com/dexon-foundation/dexon-consensus/simulation/config"
)

type infoStatus string

const (
    statusInit     infoStatus = "init"
    statusNormal   infoStatus = "normal"
    statusShutdown infoStatus = "shutdown"
)

type messageType string

const (
    shutdownAck    messageType = "shutdownAck"
    blockTimestamp messageType = "blockTimestamps"
)

// message is a struct for peer sending message to server.
type message struct {
    Type    messageType     `json:"type"`
    Payload json.RawMessage `json:"payload"`
}

// node represents a node in DexCon.
type node struct {
    app core.Application
    gov *simGovernance
    db  blockdb.BlockDatabase

    config    config.Node
    netModule *test.Network

    ID        types.NodeID
    chainID   uint64
    prvKey    crypto.PrivateKey
    consensus *core.Consensus
}

// newNode returns a new empty node.
func newNode(
    prvKey crypto.PrivateKey,
    config config.Config) *node {
    pubKey := prvKey.PublicKey()
    netModule := test.NewNetwork(
        pubKey,
        &test.NormalLatencyModel{
            Mean:  config.Networking.Mean,
            Sigma: config.Networking.Sigma,
        },
        test.NewDefaultMarshaller(&jsonMarshaller{}),
        test.NetworkConfig{
            Type:       config.Networking.Type,
            PeerServer: config.Networking.PeerServer,
            PeerPort:   peerPort,
        })
    id := types.NewNodeID(pubKey)
    db, err := blockdb.NewMemBackedBlockDB(id.String() + ".blockdb")
    if err != nil {
        panic(err)
    }
    gov := newSimGovernance(
        id,
        config.Node.Num,
        config.Node.Consensus.NotarySetSize,
        config.Node.Consensus.DKGSetSize,
        config.Node.Consensus)
    return &node{
        ID:        id,
        prvKey:    prvKey,
        config:    config.Node,
        app:       newSimApp(id, netModule),
        gov:       gov,
        db:        db,
        netModule: netModule,
    }
}

// GetID returns the ID of node.
func (n *node) GetID() types.NodeID {
    return n.ID
}

// run starts the node.
func (n *node) run(serverEndpoint interface{}, dMoment time.Time) {
    // Run network.
    if err := n.netModule.Setup(serverEndpoint); err != nil {
        panic(err)
    }
    msgChannel := n.netModule.ReceiveChanForNode()
    peers := n.netModule.Peers()
    go n.netModule.Run()
    n.gov.setNetwork(n.netModule)
    // Run consensus.
    hashes := make(common.Hashes, 0, len(peers))
    for _, pubKey := range peers {
        nID := types.NewNodeID(pubKey)
        n.gov.addNode(pubKey)
        hashes = append(hashes, nID.Hash)
    }
    sort.Sort(hashes)
    for i, hash := range hashes {
        if hash == n.ID.Hash {
            n.chainID = uint64(i)
            break
        }
    }
    n.consensus = core.NewConsensus(
        dMoment,
        n.app,
        n.gov,
        n.db,
        n.netModule,
        n.prvKey,
        &common.SimpleLogger{})
    go n.consensus.Run(&types.Block{})

    // Blocks forever.
MainLoop:
    for {
        msg := <-msgChannel
        switch val := msg.(type) {
        case infoStatus:
            if val == statusShutdown {
                break MainLoop
            }
        case *typesDKG.Complaint:
            n.gov.AddDKGComplaint(val.Round, val)
        case *typesDKG.MasterPublicKey:
            n.gov.AddDKGMasterPublicKey(val.Round, val)
        case *typesDKG.Finalize:
            n.gov.AddDKGFinalize(val.Round, val)
        default:
            panic(fmt.Errorf("unexpected message from server: %v", val))
        }
    }
    // Cleanup.
    n.consensus.Stop()
    if err := n.db.Close(); err != nil {
        fmt.Println(err)
    }
    n.netModule.Report(&message{
        Type: shutdownAck,
    })
    // TODO(mission): once we have a way to know if consensus is stopped, stop
    //                the network module.
    return
}